securewithtrace 0.12.0 → 0.14.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 +6 -1
  2. package/dist/index.js +1740 -1447
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -3352,1406 +3352,723 @@ var {
3352
3352
  Help
3353
3353
  } = import_index.default;
3354
3354
 
3355
- // src/auth/device-flow.ts
3356
- var WORKOS_DEVICE_AUTH_URL = "https://api.workos.com/user_management/authorize/device";
3357
- var WORKOS_TOKEN_URL = "https://api.workos.com/user_management/authenticate";
3358
- async function requestDeviceAuthorization(clientId) {
3359
- const response = await fetch(WORKOS_DEVICE_AUTH_URL, {
3360
- method: "POST",
3361
- headers: {
3362
- "Content-Type": "application/x-www-form-urlencoded"
3363
- },
3364
- body: new URLSearchParams({ client_id: clientId })
3365
- });
3366
- if (!response.ok) {
3367
- const text = await response.text();
3368
- throw new Error(`Failed to request device authorization: ${response.status} ${text}`);
3369
- }
3370
- return await response.json();
3371
- }
3372
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
3373
- async function pollForToken(clientId, deviceCode, options = {}) {
3374
- const expiresIn = options.expiresIn ?? 300;
3375
- let interval = options.interval ?? 5;
3376
- const deadline = Date.now() + expiresIn * 1e3;
3377
- while (Date.now() < deadline) {
3378
- const response = await fetch(WORKOS_TOKEN_URL, {
3379
- method: "POST",
3380
- headers: {
3381
- "Content-Type": "application/x-www-form-urlencoded"
3382
- },
3383
- body: new URLSearchParams({
3384
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
3385
- device_code: deviceCode,
3386
- client_id: clientId
3387
- })
3388
- });
3389
- if (response.ok) {
3390
- return await response.json();
3391
- }
3392
- const data = await response.json();
3393
- switch (data.error) {
3394
- case "authorization_pending":
3395
- await sleep(interval * 1e3);
3396
- break;
3397
- case "slow_down":
3398
- interval += 1;
3399
- await sleep(interval * 1e3);
3400
- break;
3401
- case "access_denied":
3402
- throw new Error("Authorization was denied by the user.");
3403
- case "expired_token":
3404
- throw new Error("Device code has expired. Please try again.");
3405
- default:
3406
- throw new Error(
3407
- `Authorization failed: ${data.error}${data.error_description ? ` - ${data.error_description}` : ""}`
3408
- );
3409
- }
3410
- }
3411
- throw new Error("Authorization timed out. Please try again.");
3412
- }
3413
- async function refreshAccessToken(clientId, refreshToken) {
3414
- const response = await fetch(WORKOS_TOKEN_URL, {
3415
- method: "POST",
3416
- headers: {
3417
- "Content-Type": "application/x-www-form-urlencoded"
3418
- },
3419
- body: new URLSearchParams({
3420
- grant_type: "refresh_token",
3421
- client_id: clientId,
3422
- refresh_token: refreshToken
3423
- })
3424
- });
3425
- if (!response.ok) {
3426
- const text = await response.text();
3427
- throw new Error(`Failed to refresh token: ${response.status} ${text}`);
3428
- }
3429
- return await response.json();
3430
- }
3431
-
3432
- // src/auth/token.ts
3433
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
3434
- import { homedir } from "os";
3435
- import { join } from "path";
3436
- var ACCESS_TOKEN_FILENAME = "token";
3437
- var REFRESH_TOKEN_FILENAME = "refresh-token";
3438
- function resolveTraceDir() {
3439
- const override = process.env["TRACE_CLI_AUTH_DIR"];
3440
- if (override && override.trim().length > 0) {
3441
- return override;
3442
- }
3443
- return join(homedir(), ".trace");
3444
- }
3445
- function ensureTraceDir() {
3446
- const traceDir = resolveTraceDir();
3447
- if (!existsSync(traceDir)) {
3448
- mkdirSync(traceDir, { recursive: true, mode: 448 });
3355
+ // ../../node_modules/.bun/@ts-rest+core@3.53.0-rc.1+f9199aabcde8d6a0/node_modules/@ts-rest/core/index.esm.mjs
3356
+ var util;
3357
+ (function(util2) {
3358
+ util2.assertEqual = (val) => val;
3359
+ function assertIs2(_arg) {
3449
3360
  }
3450
- }
3451
- function getTokenPath() {
3452
- return join(resolveTraceDir(), ACCESS_TOKEN_FILENAME);
3453
- }
3454
- function getRefreshTokenPath() {
3455
- return join(resolveTraceDir(), REFRESH_TOKEN_FILENAME);
3456
- }
3457
- function readToken() {
3458
- const tokenPath = getTokenPath();
3459
- try {
3460
- if (!existsSync(tokenPath)) {
3461
- return null;
3462
- }
3463
- const token = readFileSync(tokenPath, "utf-8").trim();
3464
- return token || null;
3465
- } catch {
3466
- return null;
3361
+ util2.assertIs = assertIs2;
3362
+ function assertNever2(_x) {
3363
+ throw new Error();
3467
3364
  }
3468
- }
3469
- function readRefreshToken() {
3470
- const refreshTokenPath = getRefreshTokenPath();
3471
- try {
3472
- if (!existsSync(refreshTokenPath)) {
3473
- return null;
3365
+ util2.assertNever = assertNever2;
3366
+ util2.arrayToEnum = (items) => {
3367
+ const obj = {};
3368
+ for (const item of items) {
3369
+ obj[item] = item;
3474
3370
  }
3475
- const token = readFileSync(refreshTokenPath, "utf-8").trim();
3476
- return token || null;
3477
- } catch {
3478
- return null;
3479
- }
3480
- }
3481
- function writeToken(token) {
3482
- ensureTraceDir();
3483
- writeFileSync(getTokenPath(), token, { encoding: "utf-8", mode: 384 });
3484
- }
3485
- function writeRefreshToken(token) {
3486
- ensureTraceDir();
3487
- writeFileSync(getRefreshTokenPath(), token, { encoding: "utf-8", mode: 384 });
3488
- }
3489
- function writeTokens(accessToken, refreshToken) {
3490
- writeToken(accessToken);
3491
- if (refreshToken && refreshToken.trim().length > 0) {
3492
- writeRefreshToken(refreshToken);
3493
- return;
3494
- }
3495
- removeRefreshToken();
3496
- }
3497
- function removeRefreshToken() {
3498
- const refreshTokenPath = getRefreshTokenPath();
3499
- if (!existsSync(refreshTokenPath)) {
3500
- return false;
3501
- }
3502
- rmSync(refreshTokenPath);
3503
- return true;
3504
- }
3505
- function removeToken() {
3506
- let removed = false;
3507
- const tokenPath = getTokenPath();
3508
- if (existsSync(tokenPath)) {
3509
- rmSync(tokenPath);
3510
- removed = true;
3511
- }
3512
- if (removeRefreshToken()) {
3513
- removed = true;
3514
- }
3515
- return removed;
3516
- }
3517
-
3518
- // src/auth/commands.ts
3519
- function getClientId() {
3520
- const clientId = "client_01KEZ01W5Q3107GTBY51WQ67HT";
3521
- if (clientId) {
3522
- return clientId;
3523
- }
3524
- throw new Error(
3525
- "TRACE_WORKOS_CLIENT_ID is not set. Build the CLI with TRACE_WORKOS_CLIENT_ID set, or provide it as an environment variable."
3526
- );
3527
- }
3528
- async function openBrowser(url2) {
3529
- try {
3530
- const parsed = new URL(url2);
3531
- if (parsed.protocol !== "https:") {
3532
- return false;
3371
+ return obj;
3372
+ };
3373
+ util2.getValidEnumValues = (obj) => {
3374
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
3375
+ const filtered = {};
3376
+ for (const k of validKeys) {
3377
+ filtered[k] = obj[k];
3533
3378
  }
3534
- const proc = Bun.spawn(["open", url2], {
3535
- stdout: "ignore",
3536
- stderr: "ignore"
3379
+ return util2.objectValues(filtered);
3380
+ };
3381
+ util2.objectValues = (obj) => {
3382
+ return util2.objectKeys(obj).map(function(e) {
3383
+ return obj[e];
3537
3384
  });
3538
- const exitCode = await proc.exited;
3539
- if (exitCode !== 0) {
3540
- const linuxProc = Bun.spawn(["xdg-open", url2], {
3541
- stdout: "ignore",
3542
- stderr: "ignore"
3543
- });
3544
- return await linuxProc.exited === 0;
3385
+ };
3386
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => {
3387
+ const keys = [];
3388
+ for (const key in object2) {
3389
+ if (Object.prototype.hasOwnProperty.call(object2, key)) {
3390
+ keys.push(key);
3391
+ }
3545
3392
  }
3546
- return true;
3547
- } catch {
3548
- return false;
3393
+ return keys;
3394
+ };
3395
+ util2.find = (arr, checker) => {
3396
+ for (const item of arr) {
3397
+ if (checker(item))
3398
+ return item;
3399
+ }
3400
+ return void 0;
3401
+ };
3402
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
3403
+ function joinValues2(array2, separator = " | ") {
3404
+ return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
3549
3405
  }
3550
- }
3551
- function createLoginCommand() {
3552
- return new Command("login").description("Authenticate with Trace").action(async () => {
3553
- const existingToken = readToken();
3554
- if (existingToken) {
3555
- console.log("You are already logged in. Run `trace auth logout` first to re-authenticate.");
3556
- return;
3406
+ util2.joinValues = joinValues2;
3407
+ util2.jsonStringifyReplacer = (_, value) => {
3408
+ if (typeof value === "bigint") {
3409
+ return value.toString();
3557
3410
  }
3558
- const clientId = getClientId();
3559
- console.log("Initiating device authorization...\n");
3560
- const auth = await requestDeviceAuthorization(clientId);
3561
- console.log("Your one-time code is:\n");
3562
- console.log(` ${auth.user_code}
3563
- `);
3564
- console.log(`Open this URL in your browser: ${auth.verification_uri}`);
3565
- console.log("");
3566
- const opened = await openBrowser(auth.verification_uri_complete);
3567
- if (opened) {
3568
- console.log("A browser window has been opened for you.");
3569
- } else {
3570
- console.log(`Or visit: ${auth.verification_uri_complete}`);
3571
- }
3572
- console.log("\nWaiting for authorization...");
3573
- const tokenResponse = await pollForToken(clientId, auth.device_code, {
3574
- expiresIn: auth.expires_in,
3575
- interval: auth.interval
3576
- });
3577
- writeTokens(tokenResponse.access_token, tokenResponse.refresh_token);
3578
- const name = [tokenResponse.user.first_name, tokenResponse.user.last_name].filter(Boolean).join(" ");
3579
- const displayName = name || tokenResponse.user.email;
3580
- console.log(`
3581
- Authenticated as ${displayName} (${tokenResponse.user.email})`);
3582
- console.log("Tokens saved to ~/.trace");
3583
- });
3584
- }
3585
- function createLogoutCommand() {
3586
- return new Command("logout").description("Log out of Trace").action(() => {
3587
- const removed = removeToken();
3588
- if (removed) {
3589
- console.log("Logged out successfully. Token removed from ~/.trace/token");
3411
+ return value;
3412
+ };
3413
+ })(util || (util = {}));
3414
+ var objectUtil;
3415
+ (function(objectUtil2) {
3416
+ objectUtil2.mergeShapes = (first, second) => {
3417
+ return {
3418
+ ...first,
3419
+ ...second
3420
+ // second overwrites first
3421
+ };
3422
+ };
3423
+ })(objectUtil || (objectUtil = {}));
3424
+ var ZodParsedType = util.arrayToEnum([
3425
+ "string",
3426
+ "nan",
3427
+ "number",
3428
+ "integer",
3429
+ "float",
3430
+ "boolean",
3431
+ "date",
3432
+ "bigint",
3433
+ "symbol",
3434
+ "function",
3435
+ "undefined",
3436
+ "null",
3437
+ "array",
3438
+ "object",
3439
+ "unknown",
3440
+ "promise",
3441
+ "void",
3442
+ "never",
3443
+ "map",
3444
+ "set"
3445
+ ]);
3446
+ var getParsedType = (data) => {
3447
+ const t = typeof data;
3448
+ switch (t) {
3449
+ case "undefined":
3450
+ return ZodParsedType.undefined;
3451
+ case "string":
3452
+ return ZodParsedType.string;
3453
+ case "number":
3454
+ return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
3455
+ case "boolean":
3456
+ return ZodParsedType.boolean;
3457
+ case "function":
3458
+ return ZodParsedType.function;
3459
+ case "bigint":
3460
+ return ZodParsedType.bigint;
3461
+ case "symbol":
3462
+ return ZodParsedType.symbol;
3463
+ case "object":
3464
+ if (Array.isArray(data)) {
3465
+ return ZodParsedType.array;
3466
+ }
3467
+ if (data === null) {
3468
+ return ZodParsedType.null;
3469
+ }
3470
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
3471
+ return ZodParsedType.promise;
3472
+ }
3473
+ if (typeof Map !== "undefined" && data instanceof Map) {
3474
+ return ZodParsedType.map;
3475
+ }
3476
+ if (typeof Set !== "undefined" && data instanceof Set) {
3477
+ return ZodParsedType.set;
3478
+ }
3479
+ if (typeof Date !== "undefined" && data instanceof Date) {
3480
+ return ZodParsedType.date;
3481
+ }
3482
+ return ZodParsedType.object;
3483
+ default:
3484
+ return ZodParsedType.unknown;
3485
+ }
3486
+ };
3487
+ var ZodIssueCode = util.arrayToEnum([
3488
+ "invalid_type",
3489
+ "invalid_literal",
3490
+ "custom",
3491
+ "invalid_union",
3492
+ "invalid_union_discriminator",
3493
+ "invalid_enum_value",
3494
+ "unrecognized_keys",
3495
+ "invalid_arguments",
3496
+ "invalid_return_type",
3497
+ "invalid_date",
3498
+ "invalid_string",
3499
+ "too_small",
3500
+ "too_big",
3501
+ "invalid_intersection_types",
3502
+ "not_multiple_of",
3503
+ "not_finite"
3504
+ ]);
3505
+ var quotelessJson = (obj) => {
3506
+ const json2 = JSON.stringify(obj, null, 2);
3507
+ return json2.replace(/"([^"]+)":/g, "$1:");
3508
+ };
3509
+ var ZodError = class extends Error {
3510
+ constructor(issues) {
3511
+ super();
3512
+ this.issues = [];
3513
+ this.addIssue = (sub) => {
3514
+ this.issues = [...this.issues, sub];
3515
+ };
3516
+ this.addIssues = (subs = []) => {
3517
+ this.issues = [...this.issues, ...subs];
3518
+ };
3519
+ const actualProto = new.target.prototype;
3520
+ if (Object.setPrototypeOf) {
3521
+ Object.setPrototypeOf(this, actualProto);
3590
3522
  } else {
3591
- console.log("No active session found.");
3523
+ this.__proto__ = actualProto;
3592
3524
  }
3593
- });
3594
- }
3595
- function createStatusCommand() {
3596
- return new Command("status").description("Show current authentication status").action(() => {
3597
- const token = readToken();
3598
- const refreshToken = readRefreshToken();
3599
- if (token) {
3600
- try {
3601
- const parts = token.split(".");
3602
- const payload = parts[1];
3603
- if (payload) {
3604
- const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8"));
3605
- const expiry = decoded.exp ? new Date(decoded.exp * 1e3) : null;
3606
- const isExpired = expiry ? expiry < /* @__PURE__ */ new Date() : false;
3607
- console.log("Logged in to Trace");
3608
- if (decoded.sub) {
3609
- console.log(` User ID: ${decoded.sub}`);
3610
- }
3611
- if (decoded.org_id) {
3612
- console.log(` Org ID: ${decoded.org_id}`);
3613
- }
3614
- if (expiry) {
3615
- console.log(` Expires: ${expiry.toISOString()}${isExpired ? " (EXPIRED)" : ""}`);
3616
- }
3617
- console.log(
3618
- ` Refresh: ${refreshToken ? "Available (auto-refresh enabled)" : "Not available"}`
3619
- );
3620
- if (isExpired) {
3621
- if (refreshToken) {
3622
- console.log(
3623
- "\nYour access token is expired, but a refresh token is available and will be used automatically."
3624
- );
3525
+ this.name = "ZodError";
3526
+ this.issues = issues;
3527
+ }
3528
+ get errors() {
3529
+ return this.issues;
3530
+ }
3531
+ format(_mapper) {
3532
+ const mapper = _mapper || function(issue2) {
3533
+ return issue2.message;
3534
+ };
3535
+ const fieldErrors = { _errors: [] };
3536
+ const processError = (error48) => {
3537
+ for (const issue2 of error48.issues) {
3538
+ if (issue2.code === "invalid_union") {
3539
+ issue2.unionErrors.map(processError);
3540
+ } else if (issue2.code === "invalid_return_type") {
3541
+ processError(issue2.returnTypeError);
3542
+ } else if (issue2.code === "invalid_arguments") {
3543
+ processError(issue2.argumentsError);
3544
+ } else if (issue2.path.length === 0) {
3545
+ fieldErrors._errors.push(mapper(issue2));
3546
+ } else {
3547
+ let curr = fieldErrors;
3548
+ let i = 0;
3549
+ while (i < issue2.path.length) {
3550
+ const el = issue2.path[i];
3551
+ const terminal = i === issue2.path.length - 1;
3552
+ if (!terminal) {
3553
+ curr[el] = curr[el] || { _errors: [] };
3625
3554
  } else {
3626
- console.log(
3627
- "\nYour token has expired. Run `trace auth login` after logging out to re-authenticate."
3628
- );
3555
+ curr[el] = curr[el] || { _errors: [] };
3556
+ curr[el]._errors.push(mapper(issue2));
3629
3557
  }
3558
+ curr = curr[el];
3559
+ i++;
3630
3560
  }
3631
- } else {
3632
- console.log("Logged in to Trace (access token stored at ~/.trace/token)");
3633
- console.log(
3634
- ` Refresh: ${refreshToken ? "Available (auto-refresh enabled)" : "Not available"}`
3635
- );
3636
3561
  }
3637
- } catch {
3638
- console.log("Logged in to Trace (access token stored at ~/.trace/token)");
3639
- console.log(
3640
- ` Refresh: ${refreshToken ? "Available (auto-refresh enabled)" : "Not available"}`
3641
- );
3642
3562
  }
3643
- } else {
3644
- console.log("Not logged in. Run `trace auth login` to authenticate.");
3563
+ };
3564
+ processError(this);
3565
+ return fieldErrors;
3566
+ }
3567
+ toString() {
3568
+ return this.message;
3569
+ }
3570
+ get message() {
3571
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
3572
+ }
3573
+ get isEmpty() {
3574
+ return this.issues.length === 0;
3575
+ }
3576
+ flatten(mapper = (issue2) => issue2.message) {
3577
+ const fieldErrors = {};
3578
+ const formErrors = [];
3579
+ for (const sub of this.issues) {
3580
+ if (sub.path.length > 0) {
3581
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
3582
+ fieldErrors[sub.path[0]].push(mapper(sub));
3583
+ } else {
3584
+ formErrors.push(mapper(sub));
3585
+ }
3645
3586
  }
3646
- });
3647
- }
3648
- function createAuthCommand() {
3649
- const auth = new Command("auth").description("Manage authentication");
3650
- auth.addCommand(createLoginCommand());
3651
- auth.addCommand(createLogoutCommand());
3652
- auth.addCommand(createStatusCommand());
3653
- return auth;
3654
- }
3655
-
3656
- // src/banner.ts
3657
- var ESC = "\x1B";
3658
- var RESET = `${ESC}[0m`;
3659
- var CYAN_BOLD = `${ESC}[1;36m`;
3660
- var DIM = `${ESC}[2m`;
3661
- var BANNER = `
3662
- \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557
3663
- \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D
3664
- \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2557
3665
- \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u255D
3666
- \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557
3667
- \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D
3668
- `;
3669
- function showBanner() {
3670
- console.log(`${CYAN_BOLD}${BANNER}${RESET}`);
3671
- console.log(`${DIM} Continuous security vulnerability intelligence${RESET}
3672
- `);
3673
- }
3674
-
3675
- // src/completion/index.ts
3676
- function extractCommandTree(cmd) {
3677
- const BUILTIN_FLAGS = /* @__PURE__ */ new Set(["--help", "-h", "--version", "-V"]);
3678
- const options = cmd.options.filter((o) => !o.hidden).filter((o) => !BUILTIN_FLAGS.has(o.long ?? "") && !BUILTIN_FLAGS.has(o.short ?? "")).map((o) => ({
3679
- flags: o.flags,
3680
- long: o.long ?? "",
3681
- short: o.short ?? null,
3682
- description: o.description,
3683
- takesValue: o.required || o.optional
3684
- }));
3685
- const subcommands = cmd.commands.filter((c25) => !c25._hidden).map((c25) => extractCommandTree(c25));
3686
- return {
3687
- name: cmd.name(),
3688
- description: cmd.description(),
3689
- options,
3690
- subcommands
3691
- };
3692
- }
3693
- function escapeForShell(s) {
3694
- return s.replace(/'/g, "'\\''");
3695
- }
3696
- function generateBashCompletion(tree, binName) {
3697
- const lines = [];
3698
- lines.push("#!/usr/bin/env bash");
3699
- lines.push(`# Bash completion for ${binName}`);
3700
- lines.push(`# Generated by ${binName} completion --shell bash`);
3701
- lines.push("#");
3702
- lines.push("# To enable, add to your ~/.bashrc:");
3703
- lines.push(`# eval "$(${binName} completion --shell bash)"`);
3704
- lines.push("");
3705
- const funcName = `_${binName.replace(/[^a-zA-Z0-9]/g, "_")}_completions`;
3706
- lines.push(`${funcName}() {`);
3707
- lines.push(" local cur prev words cword");
3708
- lines.push(" _get_comp_words_by_ref -n : cur prev words cword 2>/dev/null || {");
3709
- lines.push(` cur="\${COMP_WORDS[COMP_CWORD]}"`);
3710
- lines.push(` prev="\${COMP_WORDS[COMP_CWORD-1]}"`);
3711
- lines.push(` words=("\${COMP_WORDS[@]}")`);
3712
- lines.push(` cword="\${COMP_CWORD}"`);
3713
- lines.push(" }");
3714
- lines.push("");
3715
- lines.push(" # Build the command chain (skip the binary name at index 0)");
3716
- lines.push(` local cmd_chain=""`);
3717
- lines.push(" local i");
3718
- lines.push(" for (( i=1; i<cword; i++ )); do");
3719
- lines.push(` case "\${words[i]}" in`);
3720
- lines.push(" -*) ;; # skip options");
3721
- lines.push(` *) cmd_chain="\${cmd_chain} \${words[i]}" ;;`);
3722
- lines.push(" esac");
3723
- lines.push(" done");
3724
- lines.push(` cmd_chain="\${cmd_chain## }" # trim leading space`);
3725
- lines.push("");
3726
- const cases = collectBashCases(tree, "");
3727
- lines.push(` local completions=""`);
3728
- lines.push(` case "\${cmd_chain}" in`);
3729
- for (const [path, { subcommands, options }] of cases) {
3730
- const pattern = path === "" ? `''` : `'${escapeForShell(path)}'`;
3731
- const all = [...subcommands, ...options];
3732
- lines.push(` ${pattern})`);
3733
- lines.push(` completions="${all.join(" ")}"`);
3734
- lines.push(" ;;");
3587
+ return { formErrors, fieldErrors };
3735
3588
  }
3736
- lines.push(" *)");
3737
- lines.push(` completions=""`);
3738
- lines.push(" ;;");
3739
- lines.push(" esac");
3740
- lines.push("");
3741
- lines.push(` COMPREPLY=( $(compgen -W "\${completions}" -- "\${cur}") )`);
3742
- lines.push(" return 0");
3743
- lines.push("}");
3744
- lines.push("");
3745
- lines.push(`complete -o default -F ${funcName} ${binName}`);
3746
- lines.push("");
3747
- return lines.join("\n");
3748
- }
3749
- function collectBashCases(tree, prefix) {
3750
- const cases = /* @__PURE__ */ new Map();
3751
- const subcommandNames = tree.subcommands.map((c25) => c25.name);
3752
- const optionNames = tree.options.flatMap((o) => o.short ? [o.long, o.short] : [o.long]);
3753
- const extraOptions = prefix === "" ? ["--help", "--version"] : ["--help"];
3754
- const allOptions = [.../* @__PURE__ */ new Set([...optionNames, ...extraOptions])];
3755
- cases.set(prefix, { subcommands: subcommandNames, options: allOptions });
3756
- for (const sub of tree.subcommands) {
3757
- const subPath = prefix ? `${prefix} ${sub.name}` : sub.name;
3758
- const subCases = collectBashCases(sub, subPath);
3759
- for (const [k, v] of subCases) {
3760
- cases.set(k, v);
3761
- }
3589
+ get formErrors() {
3590
+ return this.flatten();
3762
3591
  }
3763
- return cases;
3764
- }
3765
- function generateZshCompletion(tree, binName) {
3766
- const lines = [];
3767
- lines.push(`#compdef ${binName}`);
3768
- lines.push(`# Zsh completion for ${binName}`);
3769
- lines.push(`# Generated by ${binName} completion --shell zsh`);
3770
- lines.push("#");
3771
- lines.push("# To enable, add to your ~/.zshrc:");
3772
- lines.push(`# eval "$(${binName} completion --shell zsh)"`);
3773
- lines.push("");
3774
- const funcName = `_${binName.replace(/[^a-zA-Z0-9]/g, "_")}`;
3775
- lines.push(`${funcName}() {`);
3776
- lines.push(" local -a commands");
3777
- lines.push(" local line state");
3778
- lines.push("");
3779
- generateZshCommandBlock(tree, lines, " ", binName, true);
3780
- lines.push("}");
3781
- lines.push("");
3782
- generateZshSubFunctions(tree, lines, binName);
3783
- lines.push(`compdef ${funcName} ${binName}`);
3784
- lines.push("");
3785
- return lines.join("\n");
3786
- }
3787
- function generateZshCommandBlock(tree, lines, indent, _binName, isRoot) {
3788
- if (tree.subcommands.length > 0) {
3789
- lines.push(`${indent}_arguments -C \\`);
3790
- lines.push(`${indent} '(-h --help)'{-h,--help}'[Show help]' \\`);
3791
- if (isRoot) {
3792
- lines.push(`${indent} '(-V --version)'{-V,--version}'[Show version]' \\`);
3793
- }
3794
- for (const opt of tree.options) {
3795
- const desc = escapeForShell(opt.description);
3796
- if (opt.takesValue) {
3797
- if (opt.short) {
3798
- lines.push(
3799
- `${indent} '(${opt.short} ${opt.long})'{${opt.short},${opt.long}}'[${desc}]:value: ' \\`
3800
- );
3801
- } else {
3802
- lines.push(`${indent} '${opt.long}[${desc}]:value: ' \\`);
3803
- }
3592
+ };
3593
+ ZodError.create = (issues) => {
3594
+ const error48 = new ZodError(issues);
3595
+ return error48;
3596
+ };
3597
+ var errorMap = (issue2, _ctx) => {
3598
+ let message;
3599
+ switch (issue2.code) {
3600
+ case ZodIssueCode.invalid_type:
3601
+ if (issue2.received === ZodParsedType.undefined) {
3602
+ message = "Required";
3804
3603
  } else {
3805
- if (opt.short) {
3806
- lines.push(
3807
- `${indent} '(${opt.short} ${opt.long})'{${opt.short},${opt.long}}'[${desc}]' \\`
3808
- );
3809
- } else {
3810
- lines.push(`${indent} '${opt.long}[${desc}]' \\`);
3811
- }
3604
+ message = `Expected ${issue2.expected}, received ${issue2.received}`;
3812
3605
  }
3813
- }
3814
- lines.push(`${indent} '1: :->command' \\`);
3815
- lines.push(`${indent} '*::arg:->args'`);
3816
- lines.push("");
3817
- lines.push(`${indent}case "$state" in`);
3818
- lines.push(`${indent} command)`);
3819
- lines.push(`${indent} commands=(`);
3820
- for (const sub of tree.subcommands) {
3821
- const desc = escapeForShell(sub.description);
3822
- lines.push(`${indent} '${sub.name}:${desc}'`);
3823
- }
3824
- lines.push(`${indent} )`);
3825
- lines.push(`${indent} _describe 'command' commands`);
3826
- lines.push(`${indent} ;;`);
3827
- lines.push(`${indent} args)`);
3828
- lines.push(`${indent} case "$line[1]" in`);
3829
- for (const sub of tree.subcommands) {
3830
- const subFunc = `_${tree.name.replace(/[^a-zA-Z0-9]/g, "_")}_${sub.name.replace(/[^a-zA-Z0-9]/g, "_")}`;
3831
- lines.push(`${indent} ${sub.name}) ${subFunc} ;;`);
3832
- }
3833
- lines.push(`${indent} esac`);
3834
- lines.push(`${indent} ;;`);
3835
- lines.push(`${indent}esac`);
3836
- } else {
3837
- lines.push(`${indent}_arguments \\`);
3838
- lines.push(`${indent} '(-h --help)'{-h,--help}'[Show help]' \\`);
3839
- for (const opt of tree.options) {
3840
- const desc = escapeForShell(opt.description);
3841
- if (opt.takesValue) {
3842
- if (opt.short) {
3843
- lines.push(
3844
- `${indent} '(${opt.short} ${opt.long})'{${opt.short},${opt.long}}'[${desc}]:value: ' \\`
3845
- );
3606
+ break;
3607
+ case ZodIssueCode.invalid_literal:
3608
+ message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`;
3609
+ break;
3610
+ case ZodIssueCode.unrecognized_keys:
3611
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`;
3612
+ break;
3613
+ case ZodIssueCode.invalid_union:
3614
+ message = `Invalid input`;
3615
+ break;
3616
+ case ZodIssueCode.invalid_union_discriminator:
3617
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`;
3618
+ break;
3619
+ case ZodIssueCode.invalid_enum_value:
3620
+ message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`;
3621
+ break;
3622
+ case ZodIssueCode.invalid_arguments:
3623
+ message = `Invalid function arguments`;
3624
+ break;
3625
+ case ZodIssueCode.invalid_return_type:
3626
+ message = `Invalid function return type`;
3627
+ break;
3628
+ case ZodIssueCode.invalid_date:
3629
+ message = `Invalid date`;
3630
+ break;
3631
+ case ZodIssueCode.invalid_string:
3632
+ if (typeof issue2.validation === "object") {
3633
+ if ("includes" in issue2.validation) {
3634
+ message = `Invalid input: must include "${issue2.validation.includes}"`;
3635
+ if (typeof issue2.validation.position === "number") {
3636
+ message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`;
3637
+ }
3638
+ } else if ("startsWith" in issue2.validation) {
3639
+ message = `Invalid input: must start with "${issue2.validation.startsWith}"`;
3640
+ } else if ("endsWith" in issue2.validation) {
3641
+ message = `Invalid input: must end with "${issue2.validation.endsWith}"`;
3846
3642
  } else {
3847
- lines.push(`${indent} '${opt.long}[${desc}]:value: ' \\`);
3643
+ util.assertNever(issue2.validation);
3848
3644
  }
3645
+ } else if (issue2.validation !== "regex") {
3646
+ message = `Invalid ${issue2.validation}`;
3849
3647
  } else {
3850
- if (opt.short) {
3851
- lines.push(
3852
- `${indent} '(${opt.short} ${opt.long})'{${opt.short},${opt.long}}'[${desc}]' \\`
3853
- );
3854
- } else {
3855
- lines.push(`${indent} '${opt.long}[${desc}]' \\`);
3856
- }
3648
+ message = "Invalid";
3857
3649
  }
3858
- }
3859
- lines.push(`${indent} '*:file:_files'`);
3860
- }
3861
- }
3862
- function generateZshSubFunctions(tree, lines, binName) {
3863
- for (const sub of tree.subcommands) {
3864
- const funcName = `_${tree.name.replace(/[^a-zA-Z0-9]/g, "_")}_${sub.name.replace(/[^a-zA-Z0-9]/g, "_")}`;
3865
- lines.push(`${funcName}() {`);
3866
- generateZshCommandBlock(sub, lines, " ", binName, false);
3867
- lines.push("}");
3868
- lines.push("");
3869
- if (sub.subcommands.length > 0) {
3870
- generateZshSubFunctions(sub, lines, binName);
3871
- }
3872
- }
3873
- }
3874
- function generateFishCompletion(tree, binName) {
3875
- const lines = [];
3876
- lines.push(`# Fish completion for ${binName}`);
3877
- lines.push(`# Generated by ${binName} completion --shell fish`);
3878
- lines.push("#");
3879
- lines.push(`# To enable, add to your ~/.config/fish/completions/${binName}.fish:`);
3880
- lines.push(`# ${binName} completion --shell fish | source`);
3881
- lines.push("");
3882
- lines.push(`complete -c ${binName} -f`);
3883
- lines.push("");
3884
- generateFishCommands(tree, lines, binName, []);
3885
- lines.push("");
3886
- return lines.join("\n");
3887
- }
3888
- function generateFishCommands(tree, lines, binName, parentPath) {
3889
- const condition = buildFishCondition(binName, parentPath);
3890
- for (const sub of tree.subcommands) {
3891
- const desc = sub.description.replace(/'/g, "\\'");
3892
- lines.push(`complete -c ${binName} ${condition} -a '${sub.name}' -d '${desc}'`);
3893
- }
3894
- for (const opt of tree.options) {
3895
- const desc = opt.description.replace(/'/g, "\\'");
3896
- const longFlag = opt.long.replace(/^--/, "");
3897
- const parts = [`complete -c ${binName} ${condition}`];
3898
- if (opt.short) {
3899
- parts.push(`-s '${opt.short.replace(/^-/, "")}'`);
3900
- }
3901
- parts.push(`-l '${longFlag}'`);
3902
- parts.push(`-d '${desc}'`);
3903
- if (opt.takesValue) {
3904
- parts.push("-r");
3905
- }
3906
- lines.push(parts.join(" "));
3907
- }
3908
- for (const sub of tree.subcommands) {
3909
- const subPath = [...parentPath, sub.name];
3910
- generateFishCommands(sub, lines, binName, subPath);
3650
+ break;
3651
+ case ZodIssueCode.too_small:
3652
+ if (issue2.type === "array")
3653
+ message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`;
3654
+ else if (issue2.type === "string")
3655
+ message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`;
3656
+ else if (issue2.type === "number")
3657
+ message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
3658
+ else if (issue2.type === "date")
3659
+ message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`;
3660
+ else
3661
+ message = "Invalid input";
3662
+ break;
3663
+ case ZodIssueCode.too_big:
3664
+ if (issue2.type === "array")
3665
+ message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`;
3666
+ else if (issue2.type === "string")
3667
+ message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`;
3668
+ else if (issue2.type === "number")
3669
+ message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
3670
+ else if (issue2.type === "bigint")
3671
+ message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
3672
+ else if (issue2.type === "date")
3673
+ message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`;
3674
+ else
3675
+ message = "Invalid input";
3676
+ break;
3677
+ case ZodIssueCode.custom:
3678
+ message = `Invalid input`;
3679
+ break;
3680
+ case ZodIssueCode.invalid_intersection_types:
3681
+ message = `Intersection results could not be merged`;
3682
+ break;
3683
+ case ZodIssueCode.not_multiple_of:
3684
+ message = `Number must be a multiple of ${issue2.multipleOf}`;
3685
+ break;
3686
+ case ZodIssueCode.not_finite:
3687
+ message = "Number must be finite";
3688
+ break;
3689
+ default:
3690
+ message = _ctx.defaultError;
3691
+ util.assertNever(issue2);
3911
3692
  }
3693
+ return { message };
3694
+ };
3695
+ var overrideErrorMap = errorMap;
3696
+ function setErrorMap(map2) {
3697
+ overrideErrorMap = map2;
3912
3698
  }
3913
- function buildFishCondition(binName, parentPath) {
3914
- if (parentPath.length === 0) {
3915
- return `-n '__fish_use_subcommand'`;
3916
- }
3917
- if (parentPath.length === 1) {
3918
- return `-n '__fish_seen_subcommand_from ${parentPath[0]}'`;
3919
- }
3920
- const conditions = parentPath.map((p) => `__fish_seen_subcommand_from ${p}`);
3921
- return `-n '${conditions.join("; and ")}'`;
3699
+ function getErrorMap() {
3700
+ return overrideErrorMap;
3922
3701
  }
3923
- function generateCompletion(program3, shell, binName) {
3924
- const name = binName ?? program3.name();
3925
- const tree = extractCommandTree(program3);
3926
- switch (shell) {
3927
- case "bash":
3928
- return generateBashCompletion(tree, name);
3929
- case "zsh":
3930
- return generateZshCompletion(tree, name);
3931
- case "fish":
3932
- return generateFishCompletion(tree, name);
3702
+ var makeIssue = (params) => {
3703
+ const { data, path, errorMaps, issueData } = params;
3704
+ const fullPath = [...path, ...issueData.path || []];
3705
+ const fullIssue = {
3706
+ ...issueData,
3707
+ path: fullPath
3708
+ };
3709
+ let errorMessage = "";
3710
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
3711
+ for (const map2 of maps) {
3712
+ errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message;
3933
3713
  }
3714
+ return {
3715
+ ...issueData,
3716
+ path: fullPath,
3717
+ message: issueData.message || errorMessage
3718
+ };
3719
+ };
3720
+ var EMPTY_PATH = [];
3721
+ function addIssueToContext(ctx, issueData) {
3722
+ const issue2 = makeIssue({
3723
+ issueData,
3724
+ data: ctx.data,
3725
+ path: ctx.path,
3726
+ errorMaps: [
3727
+ ctx.common.contextualErrorMap,
3728
+ ctx.schemaErrorMap,
3729
+ getErrorMap(),
3730
+ errorMap
3731
+ // then global default map
3732
+ ].filter((x) => !!x)
3733
+ });
3734
+ ctx.common.issues.push(issue2);
3934
3735
  }
3935
-
3936
- // src/completion/install.ts
3937
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
3938
- import { homedir as homedir2 } from "os";
3939
- import { join as join2 } from "path";
3940
- var TRACE_DIR = ".trace";
3941
- function completionFileName(shell) {
3942
- switch (shell) {
3943
- case "bash":
3944
- return "tracecli-completion.bash";
3945
- case "zsh":
3946
- return "_tracecli";
3947
- case "fish":
3948
- return "tracecli-completion.fish";
3736
+ var ParseStatus = class _ParseStatus {
3737
+ constructor() {
3738
+ this.value = "valid";
3949
3739
  }
3950
- }
3951
- function getTraceDir() {
3952
- return join2(homedir2(), TRACE_DIR);
3953
- }
3954
- function getCompletionFilePath(shell) {
3955
- return join2(getTraceDir(), completionFileName(shell));
3956
- }
3957
- function writeCompletionFile(shell, script) {
3958
- const dir = getTraceDir();
3959
- if (!existsSync2(dir)) {
3960
- mkdirSync2(dir, { recursive: true });
3740
+ dirty() {
3741
+ if (this.value === "valid")
3742
+ this.value = "dirty";
3961
3743
  }
3962
- const filePath = getCompletionFilePath(shell);
3963
- writeFileSync2(filePath, script, "utf-8");
3964
- return filePath;
3965
- }
3966
- function getSetupInstructions(shell) {
3967
- const traceDir = `~/${TRACE_DIR}`;
3968
- switch (shell) {
3969
- case "bash":
3970
- return [
3971
- "Add the following line to your .bashrc file:",
3972
- "",
3973
- " # The next line enables shell command completion for Trace",
3974
- ` source ${traceDir}/tracecli-completion.bash`,
3975
- ""
3976
- ].join("\n");
3977
- case "zsh":
3978
- return [
3979
- "Add the following lines to your .zshrc file:",
3980
- "",
3981
- " # The next lines enable shell command completion for Trace",
3982
- ` fpath=(${traceDir} $fpath)`,
3983
- " autoload -Uz compinit && compinit -i",
3984
- ""
3985
- ].join("\n");
3986
- case "fish":
3987
- return [
3988
- "Copy the completion file to your fish completions directory:",
3989
- "",
3990
- ` cp ${traceDir}/tracecli-completion.fish ~/.config/fish/completions/tracecli.fish`,
3991
- ""
3992
- ].join("\n");
3744
+ abort() {
3745
+ if (this.value !== "aborted")
3746
+ this.value = "aborted";
3993
3747
  }
3994
- }
3995
-
3996
- // src/completion/commands.ts
3997
- var SUPPORTED_SHELLS = ["bash", "zsh", "fish"];
3998
- function detectShell() {
3999
- const shellEnv = process.env["SHELL"] ?? "";
4000
- if (shellEnv.endsWith("/bash") || shellEnv.endsWith("/bash.exe")) {
4001
- return "bash";
3748
+ static mergeArray(status, results) {
3749
+ const arrayValue = [];
3750
+ for (const s of results) {
3751
+ if (s.status === "aborted")
3752
+ return INVALID;
3753
+ if (s.status === "dirty")
3754
+ status.dirty();
3755
+ arrayValue.push(s.value);
3756
+ }
3757
+ return { status: status.value, value: arrayValue };
4002
3758
  }
4003
- if (shellEnv.endsWith("/zsh")) {
4004
- return "zsh";
3759
+ static async mergeObjectAsync(status, pairs) {
3760
+ const syncPairs = [];
3761
+ for (const pair of pairs) {
3762
+ syncPairs.push({
3763
+ key: await pair.key,
3764
+ value: await pair.value
3765
+ });
3766
+ }
3767
+ return _ParseStatus.mergeObjectSync(status, syncPairs);
4005
3768
  }
4006
- if (shellEnv.endsWith("/fish")) {
4007
- return "fish";
3769
+ static mergeObjectSync(status, pairs) {
3770
+ const finalObject = {};
3771
+ for (const pair of pairs) {
3772
+ const { key, value } = pair;
3773
+ if (key.status === "aborted")
3774
+ return INVALID;
3775
+ if (value.status === "aborted")
3776
+ return INVALID;
3777
+ if (key.status === "dirty")
3778
+ status.dirty();
3779
+ if (value.status === "dirty")
3780
+ status.dirty();
3781
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
3782
+ finalObject[key.value] = value.value;
3783
+ }
3784
+ }
3785
+ return { status: status.value, value: finalObject };
4008
3786
  }
4009
- return null;
4010
- }
4011
- function resolveShell(shellOption) {
4012
- const shell = shellOption ?? detectShell();
4013
- if (!shell) {
4014
- console.error(
4015
- `Could not detect shell. Please specify one with --shell <${SUPPORTED_SHELLS.join("|")}>.`
4016
- );
4017
- process.exit(1);
4018
- }
4019
- if (!SUPPORTED_SHELLS.includes(shell)) {
4020
- console.error(
4021
- `Unsupported shell: '${shell}'. Supported shells: ${SUPPORTED_SHELLS.join(", ")}.`
4022
- );
4023
- process.exit(1);
4024
- }
4025
- return shell;
4026
- }
4027
- function createCompletionCommand(program3) {
4028
- return new Command("completion").description("Generate shell completion script").option("--shell <shell>", `Shell type (${SUPPORTED_SHELLS.join(", ")})`).action((options) => {
4029
- const shell = resolveShell(options.shell);
4030
- const script = generateCompletion(program3, shell);
4031
- const writtenPath = writeCompletionFile(shell, script);
4032
- console.log(`Completion file written to ${writtenPath}`);
4033
- console.log("");
4034
- console.log(getSetupInstructions(shell));
4035
- });
4036
- }
4037
-
4038
- // ../../node_modules/.bun/@ts-rest+core@3.53.0-rc.1+f9199aabcde8d6a0/node_modules/@ts-rest/core/index.esm.mjs
4039
- var util;
4040
- (function(util2) {
4041
- util2.assertEqual = (val) => val;
4042
- function assertIs2(_arg) {
4043
- }
4044
- util2.assertIs = assertIs2;
4045
- function assertNever2(_x) {
4046
- throw new Error();
3787
+ };
3788
+ var INVALID = Object.freeze({
3789
+ status: "aborted"
3790
+ });
3791
+ var DIRTY = (value) => ({ status: "dirty", value });
3792
+ var OK = (value) => ({ status: "valid", value });
3793
+ var isAborted = (x) => x.status === "aborted";
3794
+ var isDirty = (x) => x.status === "dirty";
3795
+ var isValid = (x) => x.status === "valid";
3796
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
3797
+ var errorUtil;
3798
+ (function(errorUtil2) {
3799
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
3800
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
3801
+ })(errorUtil || (errorUtil = {}));
3802
+ var ParseInputLazyPath = class {
3803
+ constructor(parent, value, path, key) {
3804
+ this._cachedPath = [];
3805
+ this.parent = parent;
3806
+ this.data = value;
3807
+ this._path = path;
3808
+ this._key = key;
4047
3809
  }
4048
- util2.assertNever = assertNever2;
4049
- util2.arrayToEnum = (items) => {
4050
- const obj = {};
4051
- for (const item of items) {
4052
- obj[item] = item;
4053
- }
4054
- return obj;
4055
- };
4056
- util2.getValidEnumValues = (obj) => {
4057
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
4058
- const filtered = {};
4059
- for (const k of validKeys) {
4060
- filtered[k] = obj[k];
4061
- }
4062
- return util2.objectValues(filtered);
4063
- };
4064
- util2.objectValues = (obj) => {
4065
- return util2.objectKeys(obj).map(function(e) {
4066
- return obj[e];
4067
- });
4068
- };
4069
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => {
4070
- const keys = [];
4071
- for (const key in object2) {
4072
- if (Object.prototype.hasOwnProperty.call(object2, key)) {
4073
- keys.push(key);
3810
+ get path() {
3811
+ if (!this._cachedPath.length) {
3812
+ if (this._key instanceof Array) {
3813
+ this._cachedPath.push(...this._path, ...this._key);
3814
+ } else {
3815
+ this._cachedPath.push(...this._path, this._key);
4074
3816
  }
4075
3817
  }
4076
- return keys;
4077
- };
4078
- util2.find = (arr, checker) => {
4079
- for (const item of arr) {
4080
- if (checker(item))
4081
- return item;
4082
- }
4083
- return void 0;
4084
- };
4085
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
4086
- function joinValues2(array2, separator = " | ") {
4087
- return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
3818
+ return this._cachedPath;
4088
3819
  }
4089
- util2.joinValues = joinValues2;
4090
- util2.jsonStringifyReplacer = (_, value) => {
4091
- if (typeof value === "bigint") {
4092
- return value.toString();
3820
+ };
3821
+ var handleResult = (ctx, result) => {
3822
+ if (isValid(result)) {
3823
+ return { success: true, data: result.value };
3824
+ } else {
3825
+ if (!ctx.common.issues.length) {
3826
+ throw new Error("Validation failed but no issues detected.");
4093
3827
  }
4094
- return value;
4095
- };
4096
- })(util || (util = {}));
4097
- var objectUtil;
4098
- (function(objectUtil2) {
4099
- objectUtil2.mergeShapes = (first, second) => {
4100
3828
  return {
4101
- ...first,
4102
- ...second
4103
- // second overwrites first
4104
- };
4105
- };
4106
- })(objectUtil || (objectUtil = {}));
4107
- var ZodParsedType = util.arrayToEnum([
4108
- "string",
4109
- "nan",
4110
- "number",
4111
- "integer",
4112
- "float",
4113
- "boolean",
4114
- "date",
4115
- "bigint",
4116
- "symbol",
4117
- "function",
4118
- "undefined",
4119
- "null",
4120
- "array",
4121
- "object",
4122
- "unknown",
4123
- "promise",
4124
- "void",
4125
- "never",
4126
- "map",
4127
- "set"
4128
- ]);
4129
- var getParsedType = (data) => {
4130
- const t = typeof data;
4131
- switch (t) {
4132
- case "undefined":
4133
- return ZodParsedType.undefined;
4134
- case "string":
4135
- return ZodParsedType.string;
4136
- case "number":
4137
- return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
4138
- case "boolean":
4139
- return ZodParsedType.boolean;
4140
- case "function":
4141
- return ZodParsedType.function;
4142
- case "bigint":
4143
- return ZodParsedType.bigint;
4144
- case "symbol":
4145
- return ZodParsedType.symbol;
4146
- case "object":
4147
- if (Array.isArray(data)) {
4148
- return ZodParsedType.array;
4149
- }
4150
- if (data === null) {
4151
- return ZodParsedType.null;
4152
- }
4153
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
4154
- return ZodParsedType.promise;
4155
- }
4156
- if (typeof Map !== "undefined" && data instanceof Map) {
4157
- return ZodParsedType.map;
4158
- }
4159
- if (typeof Set !== "undefined" && data instanceof Set) {
4160
- return ZodParsedType.set;
4161
- }
4162
- if (typeof Date !== "undefined" && data instanceof Date) {
4163
- return ZodParsedType.date;
3829
+ success: false,
3830
+ get error() {
3831
+ if (this._error)
3832
+ return this._error;
3833
+ const error48 = new ZodError(ctx.common.issues);
3834
+ this._error = error48;
3835
+ return this._error;
4164
3836
  }
4165
- return ZodParsedType.object;
4166
- default:
4167
- return ZodParsedType.unknown;
4168
- }
4169
- };
4170
- var ZodIssueCode = util.arrayToEnum([
4171
- "invalid_type",
4172
- "invalid_literal",
4173
- "custom",
4174
- "invalid_union",
4175
- "invalid_union_discriminator",
4176
- "invalid_enum_value",
4177
- "unrecognized_keys",
4178
- "invalid_arguments",
4179
- "invalid_return_type",
4180
- "invalid_date",
4181
- "invalid_string",
4182
- "too_small",
4183
- "too_big",
4184
- "invalid_intersection_types",
4185
- "not_multiple_of",
4186
- "not_finite"
4187
- ]);
4188
- var quotelessJson = (obj) => {
4189
- const json2 = JSON.stringify(obj, null, 2);
4190
- return json2.replace(/"([^"]+)":/g, "$1:");
4191
- };
4192
- var ZodError = class extends Error {
4193
- constructor(issues) {
4194
- super();
4195
- this.issues = [];
4196
- this.addIssue = (sub) => {
4197
- this.issues = [...this.issues, sub];
4198
3837
  };
4199
- this.addIssues = (subs = []) => {
4200
- this.issues = [...this.issues, ...subs];
4201
- };
4202
- const actualProto = new.target.prototype;
4203
- if (Object.setPrototypeOf) {
4204
- Object.setPrototypeOf(this, actualProto);
4205
- } else {
4206
- this.__proto__ = actualProto;
4207
- }
4208
- this.name = "ZodError";
4209
- this.issues = issues;
4210
3838
  }
4211
- get errors() {
4212
- return this.issues;
3839
+ };
3840
+ function processCreateParams(params) {
3841
+ if (!params)
3842
+ return {};
3843
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
3844
+ if (errorMap2 && (invalid_type_error || required_error)) {
3845
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
4213
3846
  }
4214
- format(_mapper) {
4215
- const mapper = _mapper || function(issue2) {
4216
- return issue2.message;
4217
- };
4218
- const fieldErrors = { _errors: [] };
4219
- const processError = (error48) => {
4220
- for (const issue2 of error48.issues) {
4221
- if (issue2.code === "invalid_union") {
4222
- issue2.unionErrors.map(processError);
4223
- } else if (issue2.code === "invalid_return_type") {
4224
- processError(issue2.returnTypeError);
4225
- } else if (issue2.code === "invalid_arguments") {
4226
- processError(issue2.argumentsError);
4227
- } else if (issue2.path.length === 0) {
4228
- fieldErrors._errors.push(mapper(issue2));
4229
- } else {
4230
- let curr = fieldErrors;
4231
- let i = 0;
4232
- while (i < issue2.path.length) {
4233
- const el = issue2.path[i];
4234
- const terminal = i === issue2.path.length - 1;
4235
- if (!terminal) {
4236
- curr[el] = curr[el] || { _errors: [] };
4237
- } else {
4238
- curr[el] = curr[el] || { _errors: [] };
4239
- curr[el]._errors.push(mapper(issue2));
4240
- }
4241
- curr = curr[el];
4242
- i++;
4243
- }
4244
- }
4245
- }
4246
- };
4247
- processError(this);
4248
- return fieldErrors;
3847
+ if (errorMap2)
3848
+ return { errorMap: errorMap2, description };
3849
+ const customMap = (iss, ctx) => {
3850
+ if (iss.code !== "invalid_type")
3851
+ return { message: ctx.defaultError };
3852
+ if (typeof ctx.data === "undefined") {
3853
+ return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
3854
+ }
3855
+ return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
3856
+ };
3857
+ return { errorMap: customMap, description };
3858
+ }
3859
+ var ZodType = class {
3860
+ constructor(def) {
3861
+ this.spa = this.safeParseAsync;
3862
+ this._def = def;
3863
+ this.parse = this.parse.bind(this);
3864
+ this.safeParse = this.safeParse.bind(this);
3865
+ this.parseAsync = this.parseAsync.bind(this);
3866
+ this.safeParseAsync = this.safeParseAsync.bind(this);
3867
+ this.spa = this.spa.bind(this);
3868
+ this.refine = this.refine.bind(this);
3869
+ this.refinement = this.refinement.bind(this);
3870
+ this.superRefine = this.superRefine.bind(this);
3871
+ this.optional = this.optional.bind(this);
3872
+ this.nullable = this.nullable.bind(this);
3873
+ this.nullish = this.nullish.bind(this);
3874
+ this.array = this.array.bind(this);
3875
+ this.promise = this.promise.bind(this);
3876
+ this.or = this.or.bind(this);
3877
+ this.and = this.and.bind(this);
3878
+ this.transform = this.transform.bind(this);
3879
+ this.brand = this.brand.bind(this);
3880
+ this.default = this.default.bind(this);
3881
+ this.catch = this.catch.bind(this);
3882
+ this.describe = this.describe.bind(this);
3883
+ this.pipe = this.pipe.bind(this);
3884
+ this.readonly = this.readonly.bind(this);
3885
+ this.isNullable = this.isNullable.bind(this);
3886
+ this.isOptional = this.isOptional.bind(this);
4249
3887
  }
4250
- toString() {
4251
- return this.message;
3888
+ get description() {
3889
+ return this._def.description;
4252
3890
  }
4253
- get message() {
4254
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
3891
+ _getType(input) {
3892
+ return getParsedType(input.data);
4255
3893
  }
4256
- get isEmpty() {
4257
- return this.issues.length === 0;
3894
+ _getOrReturnCtx(input, ctx) {
3895
+ return ctx || {
3896
+ common: input.parent.common,
3897
+ data: input.data,
3898
+ parsedType: getParsedType(input.data),
3899
+ schemaErrorMap: this._def.errorMap,
3900
+ path: input.path,
3901
+ parent: input.parent
3902
+ };
4258
3903
  }
4259
- flatten(mapper = (issue2) => issue2.message) {
4260
- const fieldErrors = {};
4261
- const formErrors = [];
4262
- for (const sub of this.issues) {
4263
- if (sub.path.length > 0) {
4264
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
4265
- fieldErrors[sub.path[0]].push(mapper(sub));
4266
- } else {
4267
- formErrors.push(mapper(sub));
3904
+ _processInputParams(input) {
3905
+ return {
3906
+ status: new ParseStatus(),
3907
+ ctx: {
3908
+ common: input.parent.common,
3909
+ data: input.data,
3910
+ parsedType: getParsedType(input.data),
3911
+ schemaErrorMap: this._def.errorMap,
3912
+ path: input.path,
3913
+ parent: input.parent
4268
3914
  }
3915
+ };
3916
+ }
3917
+ _parseSync(input) {
3918
+ const result = this._parse(input);
3919
+ if (isAsync(result)) {
3920
+ throw new Error("Synchronous parse encountered promise.");
4269
3921
  }
4270
- return { formErrors, fieldErrors };
3922
+ return result;
4271
3923
  }
4272
- get formErrors() {
4273
- return this.flatten();
3924
+ _parseAsync(input) {
3925
+ const result = this._parse(input);
3926
+ return Promise.resolve(result);
4274
3927
  }
4275
- };
4276
- ZodError.create = (issues) => {
4277
- const error48 = new ZodError(issues);
4278
- return error48;
4279
- };
4280
- var errorMap = (issue2, _ctx) => {
4281
- let message;
4282
- switch (issue2.code) {
4283
- case ZodIssueCode.invalid_type:
4284
- if (issue2.received === ZodParsedType.undefined) {
4285
- message = "Required";
3928
+ parse(data, params) {
3929
+ const result = this.safeParse(data, params);
3930
+ if (result.success)
3931
+ return result.data;
3932
+ throw result.error;
3933
+ }
3934
+ safeParse(data, params) {
3935
+ var _a2;
3936
+ const ctx = {
3937
+ common: {
3938
+ issues: [],
3939
+ async: (_a2 = params === null || params === void 0 ? void 0 : params.async) !== null && _a2 !== void 0 ? _a2 : false,
3940
+ contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
3941
+ },
3942
+ path: (params === null || params === void 0 ? void 0 : params.path) || [],
3943
+ schemaErrorMap: this._def.errorMap,
3944
+ parent: null,
3945
+ data,
3946
+ parsedType: getParsedType(data)
3947
+ };
3948
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
3949
+ return handleResult(ctx, result);
3950
+ }
3951
+ async parseAsync(data, params) {
3952
+ const result = await this.safeParseAsync(data, params);
3953
+ if (result.success)
3954
+ return result.data;
3955
+ throw result.error;
3956
+ }
3957
+ async safeParseAsync(data, params) {
3958
+ const ctx = {
3959
+ common: {
3960
+ issues: [],
3961
+ contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
3962
+ async: true
3963
+ },
3964
+ path: (params === null || params === void 0 ? void 0 : params.path) || [],
3965
+ schemaErrorMap: this._def.errorMap,
3966
+ parent: null,
3967
+ data,
3968
+ parsedType: getParsedType(data)
3969
+ };
3970
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
3971
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
3972
+ return handleResult(ctx, result);
3973
+ }
3974
+ refine(check2, message) {
3975
+ const getIssueProperties = (val) => {
3976
+ if (typeof message === "string" || typeof message === "undefined") {
3977
+ return { message };
3978
+ } else if (typeof message === "function") {
3979
+ return message(val);
4286
3980
  } else {
4287
- message = `Expected ${issue2.expected}, received ${issue2.received}`;
3981
+ return message;
4288
3982
  }
4289
- break;
4290
- case ZodIssueCode.invalid_literal:
4291
- message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`;
4292
- break;
4293
- case ZodIssueCode.unrecognized_keys:
4294
- message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`;
4295
- break;
4296
- case ZodIssueCode.invalid_union:
4297
- message = `Invalid input`;
4298
- break;
4299
- case ZodIssueCode.invalid_union_discriminator:
4300
- message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`;
4301
- break;
4302
- case ZodIssueCode.invalid_enum_value:
4303
- message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`;
4304
- break;
4305
- case ZodIssueCode.invalid_arguments:
4306
- message = `Invalid function arguments`;
4307
- break;
4308
- case ZodIssueCode.invalid_return_type:
4309
- message = `Invalid function return type`;
4310
- break;
4311
- case ZodIssueCode.invalid_date:
4312
- message = `Invalid date`;
4313
- break;
4314
- case ZodIssueCode.invalid_string:
4315
- if (typeof issue2.validation === "object") {
4316
- if ("includes" in issue2.validation) {
4317
- message = `Invalid input: must include "${issue2.validation.includes}"`;
4318
- if (typeof issue2.validation.position === "number") {
4319
- message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`;
3983
+ };
3984
+ return this._refinement((val, ctx) => {
3985
+ const result = check2(val);
3986
+ const setError = () => ctx.addIssue({
3987
+ code: ZodIssueCode.custom,
3988
+ ...getIssueProperties(val)
3989
+ });
3990
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
3991
+ return result.then((data) => {
3992
+ if (!data) {
3993
+ setError();
3994
+ return false;
3995
+ } else {
3996
+ return true;
4320
3997
  }
4321
- } else if ("startsWith" in issue2.validation) {
4322
- message = `Invalid input: must start with "${issue2.validation.startsWith}"`;
4323
- } else if ("endsWith" in issue2.validation) {
4324
- message = `Invalid input: must end with "${issue2.validation.endsWith}"`;
4325
- } else {
4326
- util.assertNever(issue2.validation);
4327
- }
4328
- } else if (issue2.validation !== "regex") {
4329
- message = `Invalid ${issue2.validation}`;
3998
+ });
3999
+ }
4000
+ if (!result) {
4001
+ setError();
4002
+ return false;
4330
4003
  } else {
4331
- message = "Invalid";
4004
+ return true;
4332
4005
  }
4333
- break;
4334
- case ZodIssueCode.too_small:
4335
- if (issue2.type === "array")
4336
- message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`;
4337
- else if (issue2.type === "string")
4338
- message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`;
4339
- else if (issue2.type === "number")
4340
- message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
4341
- else if (issue2.type === "date")
4342
- message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`;
4343
- else
4344
- message = "Invalid input";
4345
- break;
4346
- case ZodIssueCode.too_big:
4347
- if (issue2.type === "array")
4348
- message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`;
4349
- else if (issue2.type === "string")
4350
- message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`;
4351
- else if (issue2.type === "number")
4352
- message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
4353
- else if (issue2.type === "bigint")
4354
- message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
4355
- else if (issue2.type === "date")
4356
- message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`;
4357
- else
4358
- message = "Invalid input";
4359
- break;
4360
- case ZodIssueCode.custom:
4361
- message = `Invalid input`;
4362
- break;
4363
- case ZodIssueCode.invalid_intersection_types:
4364
- message = `Intersection results could not be merged`;
4365
- break;
4366
- case ZodIssueCode.not_multiple_of:
4367
- message = `Number must be a multiple of ${issue2.multipleOf}`;
4368
- break;
4369
- case ZodIssueCode.not_finite:
4370
- message = "Number must be finite";
4371
- break;
4372
- default:
4373
- message = _ctx.defaultError;
4374
- util.assertNever(issue2);
4006
+ });
4375
4007
  }
4376
- return { message };
4377
- };
4378
- var overrideErrorMap = errorMap;
4379
- function setErrorMap(map2) {
4380
- overrideErrorMap = map2;
4381
- }
4382
- function getErrorMap() {
4383
- return overrideErrorMap;
4384
- }
4385
- var makeIssue = (params) => {
4386
- const { data, path, errorMaps, issueData } = params;
4387
- const fullPath = [...path, ...issueData.path || []];
4388
- const fullIssue = {
4389
- ...issueData,
4390
- path: fullPath
4391
- };
4392
- let errorMessage = "";
4393
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
4394
- for (const map2 of maps) {
4395
- errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message;
4008
+ refinement(check2, refinementData) {
4009
+ return this._refinement((val, ctx) => {
4010
+ if (!check2(val)) {
4011
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
4012
+ return false;
4013
+ } else {
4014
+ return true;
4015
+ }
4016
+ });
4396
4017
  }
4397
- return {
4398
- ...issueData,
4399
- path: fullPath,
4400
- message: issueData.message || errorMessage
4401
- };
4402
- };
4403
- var EMPTY_PATH = [];
4404
- function addIssueToContext(ctx, issueData) {
4405
- const issue2 = makeIssue({
4406
- issueData,
4407
- data: ctx.data,
4408
- path: ctx.path,
4409
- errorMaps: [
4410
- ctx.common.contextualErrorMap,
4411
- ctx.schemaErrorMap,
4412
- getErrorMap(),
4413
- errorMap
4414
- // then global default map
4415
- ].filter((x) => !!x)
4416
- });
4417
- ctx.common.issues.push(issue2);
4418
- }
4419
- var ParseStatus = class _ParseStatus {
4420
- constructor() {
4421
- this.value = "valid";
4018
+ _refinement(refinement) {
4019
+ return new ZodEffects({
4020
+ schema: this,
4021
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
4022
+ effect: { type: "refinement", refinement }
4023
+ });
4422
4024
  }
4423
- dirty() {
4424
- if (this.value === "valid")
4425
- this.value = "dirty";
4025
+ superRefine(refinement) {
4026
+ return this._refinement(refinement);
4426
4027
  }
4427
- abort() {
4428
- if (this.value !== "aborted")
4429
- this.value = "aborted";
4028
+ optional() {
4029
+ return ZodOptional.create(this, this._def);
4430
4030
  }
4431
- static mergeArray(status, results) {
4432
- const arrayValue = [];
4433
- for (const s of results) {
4434
- if (s.status === "aborted")
4435
- return INVALID;
4436
- if (s.status === "dirty")
4437
- status.dirty();
4438
- arrayValue.push(s.value);
4439
- }
4440
- return { status: status.value, value: arrayValue };
4031
+ nullable() {
4032
+ return ZodNullable.create(this, this._def);
4441
4033
  }
4442
- static async mergeObjectAsync(status, pairs) {
4443
- const syncPairs = [];
4444
- for (const pair of pairs) {
4445
- syncPairs.push({
4446
- key: await pair.key,
4447
- value: await pair.value
4448
- });
4449
- }
4450
- return _ParseStatus.mergeObjectSync(status, syncPairs);
4034
+ nullish() {
4035
+ return this.nullable().optional();
4451
4036
  }
4452
- static mergeObjectSync(status, pairs) {
4453
- const finalObject = {};
4454
- for (const pair of pairs) {
4455
- const { key, value } = pair;
4456
- if (key.status === "aborted")
4457
- return INVALID;
4458
- if (value.status === "aborted")
4459
- return INVALID;
4460
- if (key.status === "dirty")
4461
- status.dirty();
4462
- if (value.status === "dirty")
4463
- status.dirty();
4464
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
4465
- finalObject[key.value] = value.value;
4466
- }
4467
- }
4468
- return { status: status.value, value: finalObject };
4037
+ array() {
4038
+ return ZodArray.create(this, this._def);
4469
4039
  }
4470
- };
4471
- var INVALID = Object.freeze({
4472
- status: "aborted"
4473
- });
4474
- var DIRTY = (value) => ({ status: "dirty", value });
4475
- var OK = (value) => ({ status: "valid", value });
4476
- var isAborted = (x) => x.status === "aborted";
4477
- var isDirty = (x) => x.status === "dirty";
4478
- var isValid = (x) => x.status === "valid";
4479
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
4480
- var errorUtil;
4481
- (function(errorUtil2) {
4482
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
4483
- errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
4484
- })(errorUtil || (errorUtil = {}));
4485
- var ParseInputLazyPath = class {
4486
- constructor(parent, value, path, key) {
4487
- this._cachedPath = [];
4488
- this.parent = parent;
4489
- this.data = value;
4490
- this._path = path;
4491
- this._key = key;
4040
+ promise() {
4041
+ return ZodPromise.create(this, this._def);
4492
4042
  }
4493
- get path() {
4494
- if (!this._cachedPath.length) {
4495
- if (this._key instanceof Array) {
4496
- this._cachedPath.push(...this._path, ...this._key);
4497
- } else {
4498
- this._cachedPath.push(...this._path, this._key);
4499
- }
4500
- }
4501
- return this._cachedPath;
4043
+ or(option) {
4044
+ return ZodUnion.create([this, option], this._def);
4502
4045
  }
4503
- };
4504
- var handleResult = (ctx, result) => {
4505
- if (isValid(result)) {
4506
- return { success: true, data: result.value };
4507
- } else {
4508
- if (!ctx.common.issues.length) {
4509
- throw new Error("Validation failed but no issues detected.");
4510
- }
4511
- return {
4512
- success: false,
4513
- get error() {
4514
- if (this._error)
4515
- return this._error;
4516
- const error48 = new ZodError(ctx.common.issues);
4517
- this._error = error48;
4518
- return this._error;
4519
- }
4520
- };
4046
+ and(incoming) {
4047
+ return ZodIntersection.create(this, incoming, this._def);
4521
4048
  }
4522
- };
4523
- function processCreateParams(params) {
4524
- if (!params)
4525
- return {};
4526
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
4527
- if (errorMap2 && (invalid_type_error || required_error)) {
4528
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
4049
+ transform(transform2) {
4050
+ return new ZodEffects({
4051
+ ...processCreateParams(this._def),
4052
+ schema: this,
4053
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
4054
+ effect: { type: "transform", transform: transform2 }
4055
+ });
4529
4056
  }
4530
- if (errorMap2)
4531
- return { errorMap: errorMap2, description };
4532
- const customMap = (iss, ctx) => {
4533
- if (iss.code !== "invalid_type")
4534
- return { message: ctx.defaultError };
4535
- if (typeof ctx.data === "undefined") {
4536
- return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
4537
- }
4538
- return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
4539
- };
4540
- return { errorMap: customMap, description };
4541
- }
4542
- var ZodType = class {
4543
- constructor(def) {
4544
- this.spa = this.safeParseAsync;
4545
- this._def = def;
4546
- this.parse = this.parse.bind(this);
4547
- this.safeParse = this.safeParse.bind(this);
4548
- this.parseAsync = this.parseAsync.bind(this);
4549
- this.safeParseAsync = this.safeParseAsync.bind(this);
4550
- this.spa = this.spa.bind(this);
4551
- this.refine = this.refine.bind(this);
4552
- this.refinement = this.refinement.bind(this);
4553
- this.superRefine = this.superRefine.bind(this);
4554
- this.optional = this.optional.bind(this);
4555
- this.nullable = this.nullable.bind(this);
4556
- this.nullish = this.nullish.bind(this);
4557
- this.array = this.array.bind(this);
4558
- this.promise = this.promise.bind(this);
4559
- this.or = this.or.bind(this);
4560
- this.and = this.and.bind(this);
4561
- this.transform = this.transform.bind(this);
4562
- this.brand = this.brand.bind(this);
4563
- this.default = this.default.bind(this);
4564
- this.catch = this.catch.bind(this);
4565
- this.describe = this.describe.bind(this);
4566
- this.pipe = this.pipe.bind(this);
4567
- this.readonly = this.readonly.bind(this);
4568
- this.isNullable = this.isNullable.bind(this);
4569
- this.isOptional = this.isOptional.bind(this);
4057
+ default(def) {
4058
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
4059
+ return new ZodDefault({
4060
+ ...processCreateParams(this._def),
4061
+ innerType: this,
4062
+ defaultValue: defaultValueFunc,
4063
+ typeName: ZodFirstPartyTypeKind.ZodDefault
4064
+ });
4570
4065
  }
4571
- get description() {
4572
- return this._def.description;
4573
- }
4574
- _getType(input) {
4575
- return getParsedType(input.data);
4576
- }
4577
- _getOrReturnCtx(input, ctx) {
4578
- return ctx || {
4579
- common: input.parent.common,
4580
- data: input.data,
4581
- parsedType: getParsedType(input.data),
4582
- schemaErrorMap: this._def.errorMap,
4583
- path: input.path,
4584
- parent: input.parent
4585
- };
4586
- }
4587
- _processInputParams(input) {
4588
- return {
4589
- status: new ParseStatus(),
4590
- ctx: {
4591
- common: input.parent.common,
4592
- data: input.data,
4593
- parsedType: getParsedType(input.data),
4594
- schemaErrorMap: this._def.errorMap,
4595
- path: input.path,
4596
- parent: input.parent
4597
- }
4598
- };
4599
- }
4600
- _parseSync(input) {
4601
- const result = this._parse(input);
4602
- if (isAsync(result)) {
4603
- throw new Error("Synchronous parse encountered promise.");
4604
- }
4605
- return result;
4606
- }
4607
- _parseAsync(input) {
4608
- const result = this._parse(input);
4609
- return Promise.resolve(result);
4610
- }
4611
- parse(data, params) {
4612
- const result = this.safeParse(data, params);
4613
- if (result.success)
4614
- return result.data;
4615
- throw result.error;
4616
- }
4617
- safeParse(data, params) {
4618
- var _a2;
4619
- const ctx = {
4620
- common: {
4621
- issues: [],
4622
- async: (_a2 = params === null || params === void 0 ? void 0 : params.async) !== null && _a2 !== void 0 ? _a2 : false,
4623
- contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
4624
- },
4625
- path: (params === null || params === void 0 ? void 0 : params.path) || [],
4626
- schemaErrorMap: this._def.errorMap,
4627
- parent: null,
4628
- data,
4629
- parsedType: getParsedType(data)
4630
- };
4631
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
4632
- return handleResult(ctx, result);
4633
- }
4634
- async parseAsync(data, params) {
4635
- const result = await this.safeParseAsync(data, params);
4636
- if (result.success)
4637
- return result.data;
4638
- throw result.error;
4639
- }
4640
- async safeParseAsync(data, params) {
4641
- const ctx = {
4642
- common: {
4643
- issues: [],
4644
- contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
4645
- async: true
4646
- },
4647
- path: (params === null || params === void 0 ? void 0 : params.path) || [],
4648
- schemaErrorMap: this._def.errorMap,
4649
- parent: null,
4650
- data,
4651
- parsedType: getParsedType(data)
4652
- };
4653
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
4654
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
4655
- return handleResult(ctx, result);
4656
- }
4657
- refine(check2, message) {
4658
- const getIssueProperties = (val) => {
4659
- if (typeof message === "string" || typeof message === "undefined") {
4660
- return { message };
4661
- } else if (typeof message === "function") {
4662
- return message(val);
4663
- } else {
4664
- return message;
4665
- }
4666
- };
4667
- return this._refinement((val, ctx) => {
4668
- const result = check2(val);
4669
- const setError = () => ctx.addIssue({
4670
- code: ZodIssueCode.custom,
4671
- ...getIssueProperties(val)
4672
- });
4673
- if (typeof Promise !== "undefined" && result instanceof Promise) {
4674
- return result.then((data) => {
4675
- if (!data) {
4676
- setError();
4677
- return false;
4678
- } else {
4679
- return true;
4680
- }
4681
- });
4682
- }
4683
- if (!result) {
4684
- setError();
4685
- return false;
4686
- } else {
4687
- return true;
4688
- }
4689
- });
4690
- }
4691
- refinement(check2, refinementData) {
4692
- return this._refinement((val, ctx) => {
4693
- if (!check2(val)) {
4694
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
4695
- return false;
4696
- } else {
4697
- return true;
4698
- }
4699
- });
4700
- }
4701
- _refinement(refinement) {
4702
- return new ZodEffects({
4703
- schema: this,
4704
- typeName: ZodFirstPartyTypeKind.ZodEffects,
4705
- effect: { type: "refinement", refinement }
4706
- });
4707
- }
4708
- superRefine(refinement) {
4709
- return this._refinement(refinement);
4710
- }
4711
- optional() {
4712
- return ZodOptional.create(this, this._def);
4713
- }
4714
- nullable() {
4715
- return ZodNullable.create(this, this._def);
4716
- }
4717
- nullish() {
4718
- return this.nullable().optional();
4719
- }
4720
- array() {
4721
- return ZodArray.create(this, this._def);
4722
- }
4723
- promise() {
4724
- return ZodPromise.create(this, this._def);
4725
- }
4726
- or(option) {
4727
- return ZodUnion.create([this, option], this._def);
4728
- }
4729
- and(incoming) {
4730
- return ZodIntersection.create(this, incoming, this._def);
4731
- }
4732
- transform(transform2) {
4733
- return new ZodEffects({
4734
- ...processCreateParams(this._def),
4735
- schema: this,
4736
- typeName: ZodFirstPartyTypeKind.ZodEffects,
4737
- effect: { type: "transform", transform: transform2 }
4738
- });
4739
- }
4740
- default(def) {
4741
- const defaultValueFunc = typeof def === "function" ? def : () => def;
4742
- return new ZodDefault({
4743
- ...processCreateParams(this._def),
4744
- innerType: this,
4745
- defaultValue: defaultValueFunc,
4746
- typeName: ZodFirstPartyTypeKind.ZodDefault
4747
- });
4748
- }
4749
- brand() {
4750
- return new ZodBranded({
4751
- typeName: ZodFirstPartyTypeKind.ZodBranded,
4752
- type: this,
4753
- ...processCreateParams(this._def)
4754
- });
4066
+ brand() {
4067
+ return new ZodBranded({
4068
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
4069
+ type: this,
4070
+ ...processCreateParams(this._def)
4071
+ });
4755
4072
  }
4756
4073
  catch(def) {
4757
4074
  const catchValueFunc = typeof def === "function" ? def : () => def;
@@ -24464,7 +23781,7 @@ var VulnerabilityStatusValues = [
24464
23781
  "OPEN",
24465
23782
  "IN_PROGRESS",
24466
23783
  "FIXED",
24467
- "IGNORED",
23784
+ "ARCHIVED",
24468
23785
  "FALSE_POSITIVE",
24469
23786
  "DISMISSED"
24470
23787
  ];
@@ -25226,7 +24543,7 @@ var PrVulnerabilitySummarySchema = external_exports.object({
25226
24543
  byStatus: external_exports.object({
25227
24544
  open: external_exports.number(),
25228
24545
  falsePositive: external_exports.number(),
25229
- acceptedRisk: external_exports.number(),
24546
+ archived: external_exports.number(),
25230
24547
  fixed: external_exports.number()
25231
24548
  })
25232
24549
  });
@@ -25288,147 +24605,1116 @@ var FindingSchema = external_exports.object({
25288
24605
  updatedAt: external_exports.date()
25289
24606
  });
25290
24607
 
25291
- // src/api-client.ts
25292
- var readTokenSafe = readToken;
25293
- var PRODUCTION_API_URL = "https://api.securewithtrace.com";
25294
- var UNAUTHORIZED_STATUS = 401;
25295
- function getApiBaseUrl() {
25296
- const raw = process.env["TRACE_API_URL"];
25297
- if (!raw) {
25298
- return PRODUCTION_API_URL;
25299
- }
25300
- let parsed;
25301
- try {
25302
- parsed = new URL(raw);
25303
- } catch {
25304
- console.error(`Invalid TRACE_API_URL: '${raw}' is not a valid URL. Using default.`);
25305
- return PRODUCTION_API_URL;
24608
+ // src/auth/device-flow.ts
24609
+ var WORKOS_DEVICE_AUTH_URL = "https://api.workos.com/user_management/authorize/device";
24610
+ var WORKOS_TOKEN_URL = "https://api.workos.com/user_management/authenticate";
24611
+ async function requestDeviceAuthorization(clientId) {
24612
+ const response = await fetch(WORKOS_DEVICE_AUTH_URL, {
24613
+ method: "POST",
24614
+ headers: {
24615
+ "Content-Type": "application/x-www-form-urlencoded"
24616
+ },
24617
+ body: new URLSearchParams({ client_id: clientId })
24618
+ });
24619
+ if (!response.ok) {
24620
+ const text = await response.text();
24621
+ throw new Error(`Failed to request device authorization: ${response.status} ${text}`);
25306
24622
  }
25307
- if (parsed.protocol !== "https:") {
25308
- console.error("Invalid TRACE_API_URL: only https:// is allowed. Using default.");
25309
- return PRODUCTION_API_URL;
24623
+ return await response.json();
24624
+ }
24625
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
24626
+ async function pollForToken(clientId, deviceCode, options = {}) {
24627
+ const expiresIn = options.expiresIn ?? 300;
24628
+ let interval = options.interval ?? 5;
24629
+ const deadline = Date.now() + expiresIn * 1e3;
24630
+ while (Date.now() < deadline) {
24631
+ const response = await fetch(WORKOS_TOKEN_URL, {
24632
+ method: "POST",
24633
+ headers: {
24634
+ "Content-Type": "application/x-www-form-urlencoded"
24635
+ },
24636
+ body: new URLSearchParams({
24637
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
24638
+ device_code: deviceCode,
24639
+ client_id: clientId
24640
+ })
24641
+ });
24642
+ if (response.ok) {
24643
+ return await response.json();
24644
+ }
24645
+ const data = await response.json();
24646
+ switch (data.error) {
24647
+ case "authorization_pending":
24648
+ await sleep(interval * 1e3);
24649
+ break;
24650
+ case "slow_down":
24651
+ interval += 1;
24652
+ await sleep(interval * 1e3);
24653
+ break;
24654
+ case "access_denied":
24655
+ throw new Error("Authorization was denied by the user.");
24656
+ case "expired_token":
24657
+ throw new Error("Device code has expired. Please try again.");
24658
+ default:
24659
+ throw new Error(
24660
+ `Authorization failed: ${data.error}${data.error_description ? ` - ${data.error_description}` : ""}`
24661
+ );
24662
+ }
25310
24663
  }
25311
- const hostname3 = parsed.hostname;
25312
- if (hostname3 === "localhost" || hostname3 === "127.0.0.1" || hostname3 === "0.0.0.0" || hostname3 === "::1" || hostname3.startsWith("10.") || hostname3.startsWith("192.168.") || /^172\.(1[6-9]|2[0-9]|3[01])\./.test(hostname3)) {
24664
+ throw new Error("Authorization timed out. Please try again.");
24665
+ }
24666
+ async function refreshAccessToken(clientId, refreshToken) {
24667
+ const response = await fetch(WORKOS_TOKEN_URL, {
24668
+ method: "POST",
24669
+ headers: {
24670
+ "Content-Type": "application/x-www-form-urlencoded"
24671
+ },
24672
+ body: new URLSearchParams({
24673
+ grant_type: "refresh_token",
24674
+ client_id: clientId,
24675
+ refresh_token: refreshToken
24676
+ })
24677
+ });
24678
+ if (!response.ok) {
24679
+ const text = await response.text();
24680
+ throw new Error(`Failed to refresh token: ${response.status} ${text}`);
24681
+ }
24682
+ return await response.json();
24683
+ }
24684
+
24685
+ // src/auth/token.ts
24686
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
24687
+ import { homedir } from "os";
24688
+ import { join } from "path";
24689
+ var ACCESS_TOKEN_FILENAME = "token";
24690
+ var REFRESH_TOKEN_FILENAME = "refresh-token";
24691
+ var SELECTED_ORGANIZATION_FILENAME = "organization";
24692
+ function resolveTraceDir() {
24693
+ const override = process.env["TRACE_CLI_AUTH_DIR"];
24694
+ if (override && override.trim().length > 0) {
24695
+ return override;
24696
+ }
24697
+ return join(homedir(), ".trace");
24698
+ }
24699
+ function ensureTraceDir() {
24700
+ const traceDir = resolveTraceDir();
24701
+ if (!existsSync(traceDir)) {
24702
+ mkdirSync(traceDir, { recursive: true, mode: 448 });
24703
+ }
24704
+ }
24705
+ function getTokenPath() {
24706
+ return join(resolveTraceDir(), ACCESS_TOKEN_FILENAME);
24707
+ }
24708
+ function getRefreshTokenPath() {
24709
+ return join(resolveTraceDir(), REFRESH_TOKEN_FILENAME);
24710
+ }
24711
+ function getSelectedOrganizationPath() {
24712
+ return join(resolveTraceDir(), SELECTED_ORGANIZATION_FILENAME);
24713
+ }
24714
+ function readToken() {
24715
+ const tokenPath = getTokenPath();
24716
+ try {
24717
+ if (!existsSync(tokenPath)) {
24718
+ return null;
24719
+ }
24720
+ const token = readFileSync(tokenPath, "utf-8").trim();
24721
+ return token || null;
24722
+ } catch {
24723
+ return null;
24724
+ }
24725
+ }
24726
+ function readRefreshToken() {
24727
+ const refreshTokenPath = getRefreshTokenPath();
24728
+ try {
24729
+ if (!existsSync(refreshTokenPath)) {
24730
+ return null;
24731
+ }
24732
+ const token = readFileSync(refreshTokenPath, "utf-8").trim();
24733
+ return token || null;
24734
+ } catch {
24735
+ return null;
24736
+ }
24737
+ }
24738
+ function readSelectedOrganizationId() {
24739
+ const organizationPath = getSelectedOrganizationPath();
24740
+ try {
24741
+ if (!existsSync(organizationPath)) {
24742
+ return null;
24743
+ }
24744
+ const organizationId = readFileSync(organizationPath, "utf-8").trim();
24745
+ return organizationId || null;
24746
+ } catch {
24747
+ return null;
24748
+ }
24749
+ }
24750
+ function writeToken(token) {
24751
+ ensureTraceDir();
24752
+ writeFileSync(getTokenPath(), token, { encoding: "utf-8", mode: 384 });
24753
+ }
24754
+ function writeRefreshToken(token) {
24755
+ ensureTraceDir();
24756
+ writeFileSync(getRefreshTokenPath(), token, { encoding: "utf-8", mode: 384 });
24757
+ }
24758
+ function writeSelectedOrganizationId(organizationId) {
24759
+ ensureTraceDir();
24760
+ writeFileSync(getSelectedOrganizationPath(), organizationId, { encoding: "utf-8", mode: 384 });
24761
+ }
24762
+ function writeTokens(accessToken, refreshToken) {
24763
+ writeToken(accessToken);
24764
+ if (refreshToken && refreshToken.trim().length > 0) {
24765
+ writeRefreshToken(refreshToken);
24766
+ return;
24767
+ }
24768
+ removeRefreshToken();
24769
+ }
24770
+ function removeRefreshToken() {
24771
+ const refreshTokenPath = getRefreshTokenPath();
24772
+ if (!existsSync(refreshTokenPath)) {
24773
+ return false;
24774
+ }
24775
+ rmSync(refreshTokenPath);
24776
+ return true;
24777
+ }
24778
+ function removeSelectedOrganizationId() {
24779
+ const organizationPath = getSelectedOrganizationPath();
24780
+ if (!existsSync(organizationPath)) {
24781
+ return false;
24782
+ }
24783
+ rmSync(organizationPath);
24784
+ return true;
24785
+ }
24786
+ function removeToken() {
24787
+ let removed = false;
24788
+ const tokenPath = getTokenPath();
24789
+ if (existsSync(tokenPath)) {
24790
+ rmSync(tokenPath);
24791
+ removed = true;
24792
+ }
24793
+ if (removeRefreshToken()) {
24794
+ removed = true;
24795
+ }
24796
+ if (removeSelectedOrganizationId()) {
24797
+ removed = true;
24798
+ }
24799
+ return removed;
24800
+ }
24801
+
24802
+ // src/api-client.ts
24803
+ var readTokenSafe = readToken;
24804
+ var PRODUCTION_API_URL = "https://api.securewithtrace.com";
24805
+ var UNAUTHORIZED_STATUS = 401;
24806
+ function getApiBaseUrl() {
24807
+ const raw = process.env["TRACE_API_URL"];
24808
+ if (!raw) {
24809
+ return PRODUCTION_API_URL;
24810
+ }
24811
+ let parsed;
24812
+ try {
24813
+ parsed = new URL(raw);
24814
+ } catch {
24815
+ console.error(`Invalid TRACE_API_URL: '${raw}' is not a valid URL. Using default.`);
24816
+ return PRODUCTION_API_URL;
24817
+ }
24818
+ if (parsed.protocol !== "https:") {
24819
+ console.error("Invalid TRACE_API_URL: only https:// is allowed. Using default.");
24820
+ return PRODUCTION_API_URL;
24821
+ }
24822
+ const hostname3 = parsed.hostname;
24823
+ if (hostname3 === "localhost" || hostname3 === "127.0.0.1" || hostname3 === "0.0.0.0" || hostname3 === "::1" || hostname3.startsWith("10.") || hostname3.startsWith("192.168.") || /^172\.(1[6-9]|2[0-9]|3[01])\./.test(hostname3)) {
25313
24824
  console.error(
25314
24825
  "Invalid TRACE_API_URL: private/reserved hostnames are not allowed. Using default."
25315
24826
  );
25316
24827
  return PRODUCTION_API_URL;
25317
24828
  }
25318
- return raw.replace(/\/+$/, "");
24829
+ return raw.replace(/\/+$/, "");
24830
+ }
24831
+ function createClient(token) {
24832
+ return initClient(v1Contract, {
24833
+ baseUrl: getApiBaseUrl(),
24834
+ baseHeaders: {
24835
+ Authorization: `Bearer ${token}`
24836
+ }
24837
+ });
24838
+ }
24839
+ function getWorkosClientId() {
24840
+ const clientId = "client_01KEZ01W5Q3107GTBY51WQ67HT";
24841
+ if (!clientId || clientId.trim().length === 0) {
24842
+ return null;
24843
+ }
24844
+ return clientId;
24845
+ }
24846
+ async function refreshStoredAccessToken() {
24847
+ const clientId = getWorkosClientId();
24848
+ const refreshToken = readRefreshToken();
24849
+ if (!clientId || !refreshToken) {
24850
+ return null;
24851
+ }
24852
+ try {
24853
+ const tokenResponse = await refreshAccessToken(clientId, refreshToken);
24854
+ const nextRefreshToken = tokenResponse.refresh_token ?? refreshToken;
24855
+ writeTokens(tokenResponse.access_token, nextRefreshToken);
24856
+ return tokenResponse.access_token;
24857
+ } catch (error48) {
24858
+ if (error48 instanceof Error && (error48.message.includes(" 400 ") || error48.message.includes(" 401 "))) {
24859
+ removeToken();
24860
+ }
24861
+ return null;
24862
+ }
24863
+ }
24864
+ async function authenticatedRequest(request) {
24865
+ const token = readToken();
24866
+ if (!token) {
24867
+ console.error("Not logged in. Run `tracecli auth login` first.");
24868
+ process.exit(1);
24869
+ }
24870
+ const firstResult = await request(createClient(token));
24871
+ if (firstResult.status !== UNAUTHORIZED_STATUS) {
24872
+ return firstResult;
24873
+ }
24874
+ const refreshedToken = await refreshStoredAccessToken();
24875
+ if (!refreshedToken) {
24876
+ return firstResult;
24877
+ }
24878
+ return request(createClient(refreshedToken));
24879
+ }
24880
+ async function authenticatedRequestSafe(request) {
24881
+ const token = readTokenSafe();
24882
+ if (!token) {
24883
+ return null;
24884
+ }
24885
+ try {
24886
+ const firstResult = await request(createClient(token));
24887
+ if (firstResult.status !== UNAUTHORIZED_STATUS) {
24888
+ return firstResult;
24889
+ }
24890
+ const refreshedToken = await refreshStoredAccessToken();
24891
+ if (!refreshedToken) {
24892
+ return firstResult;
24893
+ }
24894
+ return await request(createClient(refreshedToken));
24895
+ } catch {
24896
+ return null;
24897
+ }
24898
+ }
24899
+ var SAFE_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
24900
+ function determineActiveOrganization(organizations, selectedOrganizationId) {
24901
+ if (organizations.length === 0) {
24902
+ return null;
24903
+ }
24904
+ if (selectedOrganizationId && SAFE_ID_PATTERN.test(selectedOrganizationId)) {
24905
+ const selectedOrganization = organizations.find(
24906
+ (organization) => organization.organizationId === selectedOrganizationId
24907
+ );
24908
+ if (selectedOrganization) {
24909
+ return {
24910
+ organization: selectedOrganization,
24911
+ source: "selected",
24912
+ staleSelectionDetected: false
24913
+ };
24914
+ }
24915
+ }
24916
+ const [fallbackOrganization] = organizations;
24917
+ if (!fallbackOrganization) {
24918
+ return null;
24919
+ }
24920
+ return {
24921
+ organization: fallbackOrganization,
24922
+ source: "default",
24923
+ staleSelectionDetected: selectedOrganizationId != null
24924
+ };
24925
+ }
24926
+ async function resolveOrganizationId(client) {
24927
+ const result = client ? await client.organization.listOrganizations() : await authenticatedRequest(
24928
+ (authenticatedClient) => authenticatedClient.organization.listOrganizations()
24929
+ );
24930
+ if (result.status !== 200) {
24931
+ console.error(`Failed to resolve organization (status ${result.status}).`);
24932
+ process.exit(1);
24933
+ }
24934
+ const organizations = result.body;
24935
+ const selectedOrganizationId = readSelectedOrganizationId();
24936
+ const activeOrganization = determineActiveOrganization(organizations, selectedOrganizationId);
24937
+ if (!activeOrganization) {
24938
+ console.error("No organization found for your account.");
24939
+ process.exit(1);
24940
+ }
24941
+ const id = activeOrganization.organization.organizationId;
24942
+ if (!SAFE_ID_PATTERN.test(id)) {
24943
+ console.error("Invalid organization ID received from API.");
24944
+ process.exit(1);
24945
+ }
24946
+ if (activeOrganization.staleSelectionDetected) {
24947
+ removeSelectedOrganizationId();
24948
+ writeSelectedOrganizationId(id);
24949
+ if (selectedOrganizationId) {
24950
+ console.warn(
24951
+ `Stored organization '${selectedOrganizationId}' is unavailable. Using '${activeOrganization.organization.name}' (${id}) instead.`
24952
+ );
24953
+ }
24954
+ } else if (activeOrganization.source === "default") {
24955
+ writeSelectedOrganizationId(id);
24956
+ }
24957
+ return id;
24958
+ }
24959
+ async function resolveOrganizationIdSafe(client) {
24960
+ try {
24961
+ const result = client ? await client.organization.listOrganizations() : await authenticatedRequestSafe(
24962
+ (authenticatedClient) => authenticatedClient.organization.listOrganizations()
24963
+ );
24964
+ if (!result) {
24965
+ return null;
24966
+ }
24967
+ if (result.status !== 200) {
24968
+ return null;
24969
+ }
24970
+ const organizations = result.body;
24971
+ const selectedOrganizationId = readSelectedOrganizationId();
24972
+ const activeOrganization = determineActiveOrganization(organizations, selectedOrganizationId);
24973
+ if (!activeOrganization) {
24974
+ return null;
24975
+ }
24976
+ const id = activeOrganization.organization.organizationId;
24977
+ if (!SAFE_ID_PATTERN.test(id)) {
24978
+ return null;
24979
+ }
24980
+ if (activeOrganization.staleSelectionDetected) {
24981
+ removeSelectedOrganizationId();
24982
+ writeSelectedOrganizationId(id);
24983
+ } else if (activeOrganization.source === "default") {
24984
+ writeSelectedOrganizationId(id);
24985
+ }
24986
+ return id;
24987
+ } catch {
24988
+ return null;
24989
+ }
24990
+ }
24991
+
24992
+ // src/auth/commands.ts
24993
+ function getClientId() {
24994
+ const clientId = "client_01KEZ01W5Q3107GTBY51WQ67HT";
24995
+ if (clientId) {
24996
+ return clientId;
24997
+ }
24998
+ throw new Error(
24999
+ "TRACE_WORKOS_CLIENT_ID is not set. Build the CLI with TRACE_WORKOS_CLIENT_ID set, or provide it as an environment variable."
25000
+ );
25001
+ }
25002
+ async function openBrowser(url2) {
25003
+ try {
25004
+ const parsed = new URL(url2);
25005
+ if (parsed.protocol !== "https:") {
25006
+ return false;
25007
+ }
25008
+ const proc = Bun.spawn(["open", url2], {
25009
+ stdout: "ignore",
25010
+ stderr: "ignore"
25011
+ });
25012
+ const exitCode = await proc.exited;
25013
+ if (exitCode !== 0) {
25014
+ const linuxProc = Bun.spawn(["xdg-open", url2], {
25015
+ stdout: "ignore",
25016
+ stderr: "ignore"
25017
+ });
25018
+ return await linuxProc.exited === 0;
25019
+ }
25020
+ return true;
25021
+ } catch {
25022
+ return false;
25023
+ }
25024
+ }
25025
+ var SAFE_ORGANIZATION_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
25026
+ function sanitizeForOutput(value) {
25027
+ return value.replace(/[\r\n\t]/g, " ").trim();
25028
+ }
25029
+ function normalizeForComparison(value) {
25030
+ return value.trim().toLowerCase();
25031
+ }
25032
+ function planOrganizationSelectionPersistence(args) {
25033
+ if (args.staleSelectionDetected) {
25034
+ return {
25035
+ effectiveSelectedOrganizationId: args.activeOrganizationId,
25036
+ shouldWriteSelection: true,
25037
+ shouldRemoveStaleSelection: true
25038
+ };
25039
+ }
25040
+ if (args.activeSource === "default") {
25041
+ return {
25042
+ effectiveSelectedOrganizationId: args.activeOrganizationId,
25043
+ shouldWriteSelection: true,
25044
+ shouldRemoveStaleSelection: false
25045
+ };
25046
+ }
25047
+ return {
25048
+ effectiveSelectedOrganizationId: args.activeOrganizationId,
25049
+ shouldWriteSelection: false,
25050
+ shouldRemoveStaleSelection: false
25051
+ };
25052
+ }
25053
+ function isSafeOrganizationId(organizationId) {
25054
+ return SAFE_ORGANIZATION_ID_PATTERN.test(organizationId);
25055
+ }
25056
+ async function fetchOrganizationContext() {
25057
+ const result = await authenticatedRequest((client) => client.organization.listOrganizations());
25058
+ if (result.status !== 200) {
25059
+ console.error(`Failed to list organizations (status ${result.status}).`);
25060
+ process.exit(1);
25061
+ }
25062
+ const organizations = result.body;
25063
+ const selectedOrganizationId = readSelectedOrganizationId();
25064
+ const active = determineActiveOrganization(organizations, selectedOrganizationId);
25065
+ if (!active) {
25066
+ console.error("No organizations found for your account.");
25067
+ process.exit(1);
25068
+ }
25069
+ const persistencePlan = planOrganizationSelectionPersistence({
25070
+ activeOrganizationId: active.organization.organizationId,
25071
+ activeSource: active.source,
25072
+ staleSelectionDetected: active.staleSelectionDetected
25073
+ });
25074
+ if (persistencePlan.shouldRemoveStaleSelection) {
25075
+ removeSelectedOrganizationId();
25076
+ }
25077
+ if (persistencePlan.shouldWriteSelection) {
25078
+ writeSelectedOrganizationId(persistencePlan.effectiveSelectedOrganizationId);
25079
+ if (selectedOrganizationId) {
25080
+ console.warn(
25081
+ `Stored organization '${selectedOrganizationId}' is unavailable. Using '${active.organization.name}' (${active.organization.organizationId}) instead.`
25082
+ );
25083
+ }
25084
+ }
25085
+ return {
25086
+ organizations,
25087
+ activeOrganization: active.organization,
25088
+ selectedOrganizationId: persistencePlan.effectiveSelectedOrganizationId,
25089
+ staleSelectionDetected: active.staleSelectionDetected
25090
+ };
25091
+ }
25092
+ function findOrganizationByInput(organizations, input) {
25093
+ const normalizedInput = normalizeForComparison(input);
25094
+ if (normalizedInput.length === 0) {
25095
+ return { error: "Organization identifier cannot be empty." };
25096
+ }
25097
+ const byId = organizations.find(
25098
+ (organization) => normalizeForComparison(organization.organizationId) === normalizedInput
25099
+ );
25100
+ if (byId) {
25101
+ return { organization: byId };
25102
+ }
25103
+ const bySlug = organizations.find(
25104
+ (organization) => normalizeForComparison(organization.slug) === normalizedInput
25105
+ );
25106
+ if (bySlug) {
25107
+ return { organization: bySlug };
25108
+ }
25109
+ const exactNameMatches = organizations.filter(
25110
+ (organization) => normalizeForComparison(organization.name) === normalizedInput
25111
+ );
25112
+ if (exactNameMatches.length === 1 && exactNameMatches[0]) {
25113
+ return { organization: exactNameMatches[0] };
25114
+ }
25115
+ if (exactNameMatches.length > 1) {
25116
+ return {
25117
+ error: `Multiple organizations have the exact name '${input}'. Use an organization ID or slug instead.`
25118
+ };
25119
+ }
25120
+ const partialMatches = organizations.filter((organization) => {
25121
+ const normalizedName = normalizeForComparison(organization.name);
25122
+ const normalizedSlug = normalizeForComparison(organization.slug);
25123
+ return normalizedName.includes(normalizedInput) || normalizedSlug.includes(normalizedInput);
25124
+ });
25125
+ if (partialMatches.length === 1 && partialMatches[0]) {
25126
+ return { organization: partialMatches[0] };
25127
+ }
25128
+ if (partialMatches.length > 1) {
25129
+ const hints = partialMatches.map((organization) => ` - ${organization.name} (${organization.slug})`).join("\n");
25130
+ return {
25131
+ error: `Organization '${input}' is ambiguous. Multiple matches found:
25132
+ ${hints}
25133
+ Use an organization ID or exact slug.`
25134
+ };
25135
+ }
25136
+ return {
25137
+ error: `Organization '${input}' not found. Run \`tracecli auth org list\` to see available organizations.`
25138
+ };
25139
+ }
25140
+ function createLoginCommand() {
25141
+ return new Command("login").description("Authenticate with Trace").action(async () => {
25142
+ const existingToken = readToken();
25143
+ if (existingToken) {
25144
+ console.log("You are already logged in. Run `trace auth logout` first to re-authenticate.");
25145
+ return;
25146
+ }
25147
+ const clientId = getClientId();
25148
+ console.log("Initiating device authorization...\n");
25149
+ const auth = await requestDeviceAuthorization(clientId);
25150
+ console.log("Your one-time code is:\n");
25151
+ console.log(` ${auth.user_code}
25152
+ `);
25153
+ console.log(`Open this URL in your browser: ${auth.verification_uri}`);
25154
+ console.log("");
25155
+ const opened = await openBrowser(auth.verification_uri_complete);
25156
+ if (opened) {
25157
+ console.log("A browser window has been opened for you.");
25158
+ } else {
25159
+ console.log(`Or visit: ${auth.verification_uri_complete}`);
25160
+ }
25161
+ console.log("\nWaiting for authorization...");
25162
+ const tokenResponse = await pollForToken(clientId, auth.device_code, {
25163
+ expiresIn: auth.expires_in,
25164
+ interval: auth.interval
25165
+ });
25166
+ writeTokens(tokenResponse.access_token, tokenResponse.refresh_token);
25167
+ const name = [tokenResponse.user.first_name, tokenResponse.user.last_name].filter(Boolean).join(" ");
25168
+ const displayName = name || tokenResponse.user.email;
25169
+ console.log(`
25170
+ Authenticated as ${displayName} (${tokenResponse.user.email})`);
25171
+ console.log("Tokens saved to ~/.trace");
25172
+ });
25173
+ }
25174
+ function createLogoutCommand() {
25175
+ return new Command("logout").description("Log out of Trace").action(() => {
25176
+ const removed = removeToken();
25177
+ if (removed) {
25178
+ console.log("Logged out successfully. Local session data removed from ~/.trace/");
25179
+ } else {
25180
+ console.log("No active session found.");
25181
+ }
25182
+ });
25183
+ }
25184
+ function createStatusCommand() {
25185
+ return new Command("status").description("Show current authentication status").action(() => {
25186
+ const token = readToken();
25187
+ const refreshToken = readRefreshToken();
25188
+ const selectedOrganizationId = readSelectedOrganizationId();
25189
+ if (token) {
25190
+ try {
25191
+ const parts = token.split(".");
25192
+ const payload = parts[1];
25193
+ if (payload) {
25194
+ const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8"));
25195
+ const expiry = decoded.exp ? new Date(decoded.exp * 1e3) : null;
25196
+ const isExpired = expiry ? expiry < /* @__PURE__ */ new Date() : false;
25197
+ console.log("Logged in to Trace");
25198
+ if (decoded.sub) {
25199
+ console.log(` User ID: ${decoded.sub}`);
25200
+ }
25201
+ if (decoded.org_id) {
25202
+ console.log(` Org ID: ${decoded.org_id}`);
25203
+ }
25204
+ if (selectedOrganizationId) {
25205
+ console.log(` Active Org (CLI): ${selectedOrganizationId}`);
25206
+ }
25207
+ if (expiry) {
25208
+ console.log(` Expires: ${expiry.toISOString()}${isExpired ? " (EXPIRED)" : ""}`);
25209
+ }
25210
+ console.log(
25211
+ ` Refresh: ${refreshToken ? "Available (auto-refresh enabled)" : "Not available"}`
25212
+ );
25213
+ if (isExpired) {
25214
+ if (refreshToken) {
25215
+ console.log(
25216
+ "\nYour access token is expired, but a refresh token is available and will be used automatically."
25217
+ );
25218
+ } else {
25219
+ console.log(
25220
+ "\nYour token has expired. Run `trace auth login` after logging out to re-authenticate."
25221
+ );
25222
+ }
25223
+ }
25224
+ } else {
25225
+ console.log("Logged in to Trace (access token stored at ~/.trace/token)");
25226
+ if (selectedOrganizationId) {
25227
+ console.log(` Active Org (CLI): ${selectedOrganizationId}`);
25228
+ }
25229
+ console.log(
25230
+ ` Refresh: ${refreshToken ? "Available (auto-refresh enabled)" : "Not available"}`
25231
+ );
25232
+ }
25233
+ } catch {
25234
+ console.log("Logged in to Trace (access token stored at ~/.trace/token)");
25235
+ if (selectedOrganizationId) {
25236
+ console.log(` Active Org (CLI): ${selectedOrganizationId}`);
25237
+ }
25238
+ console.log(
25239
+ ` Refresh: ${refreshToken ? "Available (auto-refresh enabled)" : "Not available"}`
25240
+ );
25241
+ }
25242
+ } else {
25243
+ console.log("Not logged in. Run `trace auth login` to authenticate.");
25244
+ }
25245
+ });
25246
+ }
25247
+ function createOrgListCommand() {
25248
+ return new Command("list").description("List organizations available to your account").option("--json", "Output as JSON").action(async (options) => {
25249
+ const organizationContext = await fetchOrganizationContext();
25250
+ const items = organizationContext.organizations.map(
25251
+ (organization) => ({
25252
+ ...organization,
25253
+ active: organization.organizationId === organizationContext.activeOrganization.organizationId,
25254
+ selected: organization.organizationId === organizationContext.selectedOrganizationId
25255
+ })
25256
+ );
25257
+ if (options.json) {
25258
+ console.log(JSON.stringify(items, null, 2));
25259
+ return;
25260
+ }
25261
+ for (const item of items) {
25262
+ const marker = item.active ? "*" : " ";
25263
+ const labels = [item.active ? "active" : null, item.selected ? "selected" : null].filter(
25264
+ Boolean
25265
+ );
25266
+ const suffix = labels.length > 0 ? ` [${labels.join(", ")}]` : "";
25267
+ console.log(
25268
+ `${marker} ${sanitizeForOutput(item.name)} (${sanitizeForOutput(item.slug)}) - ${item.organizationId}${suffix}`
25269
+ );
25270
+ }
25271
+ if (organizationContext.staleSelectionDetected) {
25272
+ console.log("\nYour previous organization selection is no longer available and was reset.");
25273
+ }
25274
+ });
25275
+ }
25276
+ function createOrgCurrentCommand() {
25277
+ return new Command("current").description("Show the active organization used by CLI commands").option("--json", "Output as JSON").action(async (options) => {
25278
+ const organizationContext = await fetchOrganizationContext();
25279
+ const active = organizationContext.activeOrganization;
25280
+ const source = organizationContext.selectedOrganizationId === active.organizationId ? "selected" : "default";
25281
+ if (options.json) {
25282
+ console.log(
25283
+ JSON.stringify(
25284
+ {
25285
+ ...active,
25286
+ source
25287
+ },
25288
+ null,
25289
+ 2
25290
+ )
25291
+ );
25292
+ return;
25293
+ }
25294
+ console.log(
25295
+ `Active organization: ${sanitizeForOutput(active.name)} (${sanitizeForOutput(active.slug)})`
25296
+ );
25297
+ console.log(` Org ID: ${active.organizationId}`);
25298
+ console.log(` Source: ${source}`);
25299
+ });
25300
+ }
25301
+ function createOrgSwitchCommand() {
25302
+ return new Command("switch").description("Switch the active organization for subsequent CLI commands").argument("<organization>", "Organization ID, slug, or name").action(async (organization) => {
25303
+ const organizationContext = await fetchOrganizationContext();
25304
+ const match = findOrganizationByInput(organizationContext.organizations, organization);
25305
+ if ("error" in match) {
25306
+ console.error(match.error);
25307
+ process.exit(1);
25308
+ }
25309
+ if (!isSafeOrganizationId(match.organization.organizationId)) {
25310
+ console.error(
25311
+ `Cannot switch to organization '${match.organization.organizationId}': invalid organization ID format.`
25312
+ );
25313
+ process.exit(1);
25314
+ }
25315
+ writeSelectedOrganizationId(match.organization.organizationId);
25316
+ console.log(
25317
+ `Active organization set to ${sanitizeForOutput(match.organization.name)} (${sanitizeForOutput(match.organization.slug)})`
25318
+ );
25319
+ console.log(` Org ID: ${match.organization.organizationId}`);
25320
+ });
25321
+ }
25322
+ function createOrgCommand() {
25323
+ const org = new Command("org").description("Manage active organization context");
25324
+ org.addCommand(createOrgListCommand());
25325
+ org.addCommand(createOrgCurrentCommand());
25326
+ org.addCommand(createOrgSwitchCommand());
25327
+ return org;
25328
+ }
25329
+ function createAuthCommand() {
25330
+ const auth = new Command("auth").description("Manage authentication");
25331
+ auth.addCommand(createLoginCommand());
25332
+ auth.addCommand(createLogoutCommand());
25333
+ auth.addCommand(createStatusCommand());
25334
+ auth.addCommand(createOrgCommand());
25335
+ return auth;
25336
+ }
25337
+
25338
+ // src/banner.ts
25339
+ var ESC = "\x1B";
25340
+ var RESET = `${ESC}[0m`;
25341
+ var CYAN_BOLD = `${ESC}[1;36m`;
25342
+ var DIM = `${ESC}[2m`;
25343
+ var BANNER = `
25344
+ \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557
25345
+ \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D
25346
+ \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2557
25347
+ \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u255D
25348
+ \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557
25349
+ \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D
25350
+ `;
25351
+ function showBanner() {
25352
+ console.log(`${CYAN_BOLD}${BANNER}${RESET}`);
25353
+ console.log(`${DIM} Continuous security vulnerability intelligence${RESET}
25354
+ `);
25355
+ }
25356
+
25357
+ // src/completion/index.ts
25358
+ function extractCommandTree(cmd) {
25359
+ const BUILTIN_FLAGS = /* @__PURE__ */ new Set(["--help", "-h", "--version", "-V"]);
25360
+ const options = cmd.options.filter((o) => !o.hidden).filter((o) => !BUILTIN_FLAGS.has(o.long ?? "") && !BUILTIN_FLAGS.has(o.short ?? "")).map((o) => ({
25361
+ flags: o.flags,
25362
+ long: o.long ?? "",
25363
+ short: o.short ?? null,
25364
+ description: o.description,
25365
+ takesValue: o.required || o.optional
25366
+ }));
25367
+ const subcommands = cmd.commands.filter((c25) => !c25._hidden).map((c25) => extractCommandTree(c25));
25368
+ return {
25369
+ name: cmd.name(),
25370
+ description: cmd.description(),
25371
+ options,
25372
+ subcommands
25373
+ };
25374
+ }
25375
+ function escapeForShell(s) {
25376
+ return s.replace(/'/g, "'\\''");
25377
+ }
25378
+ function generateBashCompletion(tree, binName) {
25379
+ const lines = [];
25380
+ lines.push("#!/usr/bin/env bash");
25381
+ lines.push(`# Bash completion for ${binName}`);
25382
+ lines.push(`# Generated by ${binName} completion --shell bash`);
25383
+ lines.push("#");
25384
+ lines.push("# To enable, add to your ~/.bashrc:");
25385
+ lines.push(`# eval "$(${binName} completion --shell bash)"`);
25386
+ lines.push("");
25387
+ const funcName = `_${binName.replace(/[^a-zA-Z0-9]/g, "_")}_completions`;
25388
+ lines.push(`${funcName}() {`);
25389
+ lines.push(" local cur prev words cword");
25390
+ lines.push(" _get_comp_words_by_ref -n : cur prev words cword 2>/dev/null || {");
25391
+ lines.push(` cur="\${COMP_WORDS[COMP_CWORD]}"`);
25392
+ lines.push(` prev="\${COMP_WORDS[COMP_CWORD-1]}"`);
25393
+ lines.push(` words=("\${COMP_WORDS[@]}")`);
25394
+ lines.push(` cword="\${COMP_CWORD}"`);
25395
+ lines.push(" }");
25396
+ lines.push("");
25397
+ lines.push(" # Build the command chain (skip the binary name at index 0)");
25398
+ lines.push(` local cmd_chain=""`);
25399
+ lines.push(" local i");
25400
+ lines.push(" for (( i=1; i<cword; i++ )); do");
25401
+ lines.push(` case "\${words[i]}" in`);
25402
+ lines.push(" -*) ;; # skip options");
25403
+ lines.push(` *) cmd_chain="\${cmd_chain} \${words[i]}" ;;`);
25404
+ lines.push(" esac");
25405
+ lines.push(" done");
25406
+ lines.push(` cmd_chain="\${cmd_chain## }" # trim leading space`);
25407
+ lines.push("");
25408
+ const cases = collectBashCases(tree, "");
25409
+ lines.push(` local completions=""`);
25410
+ lines.push(` case "\${cmd_chain}" in`);
25411
+ for (const [path, { subcommands, options }] of cases) {
25412
+ const pattern = path === "" ? `''` : `'${escapeForShell(path)}'`;
25413
+ const all = [...subcommands, ...options];
25414
+ lines.push(` ${pattern})`);
25415
+ lines.push(` completions="${all.join(" ")}"`);
25416
+ lines.push(" ;;");
25417
+ }
25418
+ lines.push(" *)");
25419
+ lines.push(` completions=""`);
25420
+ lines.push(" ;;");
25421
+ lines.push(" esac");
25422
+ lines.push("");
25423
+ lines.push(` COMPREPLY=( $(compgen -W "\${completions}" -- "\${cur}") )`);
25424
+ lines.push(" return 0");
25425
+ lines.push("}");
25426
+ lines.push("");
25427
+ lines.push(`complete -o default -F ${funcName} ${binName}`);
25428
+ lines.push("");
25429
+ return lines.join("\n");
25430
+ }
25431
+ function collectBashCases(tree, prefix) {
25432
+ const cases = /* @__PURE__ */ new Map();
25433
+ const subcommandNames = tree.subcommands.map((c25) => c25.name);
25434
+ const optionNames = tree.options.flatMap((o) => o.short ? [o.long, o.short] : [o.long]);
25435
+ const extraOptions = prefix === "" ? ["--help", "--version"] : ["--help"];
25436
+ const allOptions = [.../* @__PURE__ */ new Set([...optionNames, ...extraOptions])];
25437
+ cases.set(prefix, { subcommands: subcommandNames, options: allOptions });
25438
+ for (const sub of tree.subcommands) {
25439
+ const subPath = prefix ? `${prefix} ${sub.name}` : sub.name;
25440
+ const subCases = collectBashCases(sub, subPath);
25441
+ for (const [k, v] of subCases) {
25442
+ cases.set(k, v);
25443
+ }
25444
+ }
25445
+ return cases;
25446
+ }
25447
+ function generateZshCompletion(tree, binName) {
25448
+ const lines = [];
25449
+ lines.push(`#compdef ${binName}`);
25450
+ lines.push(`# Zsh completion for ${binName}`);
25451
+ lines.push(`# Generated by ${binName} completion --shell zsh`);
25452
+ lines.push("#");
25453
+ lines.push("# To enable, add to your ~/.zshrc:");
25454
+ lines.push(`# eval "$(${binName} completion --shell zsh)"`);
25455
+ lines.push("");
25456
+ const funcName = `_${binName.replace(/[^a-zA-Z0-9]/g, "_")}`;
25457
+ lines.push(`${funcName}() {`);
25458
+ lines.push(" local -a commands");
25459
+ lines.push(" local line state");
25460
+ lines.push("");
25461
+ generateZshCommandBlock(tree, lines, " ", binName, true);
25462
+ lines.push("}");
25463
+ lines.push("");
25464
+ generateZshSubFunctions(tree, lines, binName);
25465
+ lines.push(`compdef ${funcName} ${binName}`);
25466
+ lines.push("");
25467
+ return lines.join("\n");
25468
+ }
25469
+ function generateZshCommandBlock(tree, lines, indent, _binName, isRoot) {
25470
+ if (tree.subcommands.length > 0) {
25471
+ lines.push(`${indent}_arguments -C \\`);
25472
+ lines.push(`${indent} '(-h --help)'{-h,--help}'[Show help]' \\`);
25473
+ if (isRoot) {
25474
+ lines.push(`${indent} '(-V --version)'{-V,--version}'[Show version]' \\`);
25475
+ }
25476
+ for (const opt of tree.options) {
25477
+ const desc = escapeForShell(opt.description);
25478
+ if (opt.takesValue) {
25479
+ if (opt.short) {
25480
+ lines.push(
25481
+ `${indent} '(${opt.short} ${opt.long})'{${opt.short},${opt.long}}'[${desc}]:value: ' \\`
25482
+ );
25483
+ } else {
25484
+ lines.push(`${indent} '${opt.long}[${desc}]:value: ' \\`);
25485
+ }
25486
+ } else {
25487
+ if (opt.short) {
25488
+ lines.push(
25489
+ `${indent} '(${opt.short} ${opt.long})'{${opt.short},${opt.long}}'[${desc}]' \\`
25490
+ );
25491
+ } else {
25492
+ lines.push(`${indent} '${opt.long}[${desc}]' \\`);
25493
+ }
25494
+ }
25495
+ }
25496
+ lines.push(`${indent} '1: :->command' \\`);
25497
+ lines.push(`${indent} '*::arg:->args'`);
25498
+ lines.push("");
25499
+ lines.push(`${indent}case "$state" in`);
25500
+ lines.push(`${indent} command)`);
25501
+ lines.push(`${indent} commands=(`);
25502
+ for (const sub of tree.subcommands) {
25503
+ const desc = escapeForShell(sub.description);
25504
+ lines.push(`${indent} '${sub.name}:${desc}'`);
25505
+ }
25506
+ lines.push(`${indent} )`);
25507
+ lines.push(`${indent} _describe 'command' commands`);
25508
+ lines.push(`${indent} ;;`);
25509
+ lines.push(`${indent} args)`);
25510
+ lines.push(`${indent} case "$line[1]" in`);
25511
+ for (const sub of tree.subcommands) {
25512
+ const subFunc = `_${tree.name.replace(/[^a-zA-Z0-9]/g, "_")}_${sub.name.replace(/[^a-zA-Z0-9]/g, "_")}`;
25513
+ lines.push(`${indent} ${sub.name}) ${subFunc} ;;`);
25514
+ }
25515
+ lines.push(`${indent} esac`);
25516
+ lines.push(`${indent} ;;`);
25517
+ lines.push(`${indent}esac`);
25518
+ } else {
25519
+ lines.push(`${indent}_arguments \\`);
25520
+ lines.push(`${indent} '(-h --help)'{-h,--help}'[Show help]' \\`);
25521
+ for (const opt of tree.options) {
25522
+ const desc = escapeForShell(opt.description);
25523
+ if (opt.takesValue) {
25524
+ if (opt.short) {
25525
+ lines.push(
25526
+ `${indent} '(${opt.short} ${opt.long})'{${opt.short},${opt.long}}'[${desc}]:value: ' \\`
25527
+ );
25528
+ } else {
25529
+ lines.push(`${indent} '${opt.long}[${desc}]:value: ' \\`);
25530
+ }
25531
+ } else {
25532
+ if (opt.short) {
25533
+ lines.push(
25534
+ `${indent} '(${opt.short} ${opt.long})'{${opt.short},${opt.long}}'[${desc}]' \\`
25535
+ );
25536
+ } else {
25537
+ lines.push(`${indent} '${opt.long}[${desc}]' \\`);
25538
+ }
25539
+ }
25540
+ }
25541
+ lines.push(`${indent} '*:file:_files'`);
25542
+ }
25319
25543
  }
25320
- function createClient(token) {
25321
- return initClient(v1Contract, {
25322
- baseUrl: getApiBaseUrl(),
25323
- baseHeaders: {
25324
- Authorization: `Bearer ${token}`
25544
+ function generateZshSubFunctions(tree, lines, binName) {
25545
+ for (const sub of tree.subcommands) {
25546
+ const funcName = `_${tree.name.replace(/[^a-zA-Z0-9]/g, "_")}_${sub.name.replace(/[^a-zA-Z0-9]/g, "_")}`;
25547
+ lines.push(`${funcName}() {`);
25548
+ generateZshCommandBlock(sub, lines, " ", binName, false);
25549
+ lines.push("}");
25550
+ lines.push("");
25551
+ if (sub.subcommands.length > 0) {
25552
+ generateZshSubFunctions(sub, lines, binName);
25325
25553
  }
25326
- });
25327
- }
25328
- function getWorkosClientId() {
25329
- const clientId = "client_01KEZ01W5Q3107GTBY51WQ67HT";
25330
- if (!clientId || clientId.trim().length === 0) {
25331
- return null;
25332
25554
  }
25333
- return clientId;
25334
25555
  }
25335
- async function refreshStoredAccessToken() {
25336
- const clientId = getWorkosClientId();
25337
- const refreshToken = readRefreshToken();
25338
- if (!clientId || !refreshToken) {
25339
- return null;
25556
+ function generateFishCompletion(tree, binName) {
25557
+ const lines = [];
25558
+ lines.push(`# Fish completion for ${binName}`);
25559
+ lines.push(`# Generated by ${binName} completion --shell fish`);
25560
+ lines.push("#");
25561
+ lines.push(`# To enable, add to your ~/.config/fish/completions/${binName}.fish:`);
25562
+ lines.push(`# ${binName} completion --shell fish | source`);
25563
+ lines.push("");
25564
+ lines.push(`complete -c ${binName} -f`);
25565
+ lines.push("");
25566
+ generateFishCommands(tree, lines, binName, []);
25567
+ lines.push("");
25568
+ return lines.join("\n");
25569
+ }
25570
+ function generateFishCommands(tree, lines, binName, parentPath) {
25571
+ const condition = buildFishCondition(binName, parentPath);
25572
+ for (const sub of tree.subcommands) {
25573
+ const desc = sub.description.replace(/'/g, "\\'");
25574
+ lines.push(`complete -c ${binName} ${condition} -a '${sub.name}' -d '${desc}'`);
25340
25575
  }
25341
- try {
25342
- const tokenResponse = await refreshAccessToken(clientId, refreshToken);
25343
- const nextRefreshToken = tokenResponse.refresh_token ?? refreshToken;
25344
- writeTokens(tokenResponse.access_token, nextRefreshToken);
25345
- return tokenResponse.access_token;
25346
- } catch (error48) {
25347
- if (error48 instanceof Error && (error48.message.includes(" 400 ") || error48.message.includes(" 401 "))) {
25348
- removeToken();
25576
+ for (const opt of tree.options) {
25577
+ const desc = opt.description.replace(/'/g, "\\'");
25578
+ const longFlag = opt.long.replace(/^--/, "");
25579
+ const parts = [`complete -c ${binName} ${condition}`];
25580
+ if (opt.short) {
25581
+ parts.push(`-s '${opt.short.replace(/^-/, "")}'`);
25349
25582
  }
25350
- return null;
25583
+ parts.push(`-l '${longFlag}'`);
25584
+ parts.push(`-d '${desc}'`);
25585
+ if (opt.takesValue) {
25586
+ parts.push("-r");
25587
+ }
25588
+ lines.push(parts.join(" "));
25589
+ }
25590
+ for (const sub of tree.subcommands) {
25591
+ const subPath = [...parentPath, sub.name];
25592
+ generateFishCommands(sub, lines, binName, subPath);
25351
25593
  }
25352
25594
  }
25353
- async function authenticatedRequest(request) {
25354
- const token = readToken();
25355
- if (!token) {
25356
- console.error("Not logged in. Run `tracecli auth login` first.");
25357
- process.exit(1);
25595
+ function buildFishCondition(binName, parentPath) {
25596
+ if (parentPath.length === 0) {
25597
+ return `-n '__fish_use_subcommand'`;
25358
25598
  }
25359
- const firstResult = await request(createClient(token));
25360
- if (firstResult.status !== UNAUTHORIZED_STATUS) {
25361
- return firstResult;
25599
+ if (parentPath.length === 1) {
25600
+ return `-n '__fish_seen_subcommand_from ${parentPath[0]}'`;
25362
25601
  }
25363
- const refreshedToken = await refreshStoredAccessToken();
25364
- if (!refreshedToken) {
25365
- return firstResult;
25602
+ const conditions = parentPath.map((p) => `__fish_seen_subcommand_from ${p}`);
25603
+ return `-n '${conditions.join("; and ")}'`;
25604
+ }
25605
+ function generateCompletion(program3, shell, binName) {
25606
+ const name = binName ?? program3.name();
25607
+ const tree = extractCommandTree(program3);
25608
+ switch (shell) {
25609
+ case "bash":
25610
+ return generateBashCompletion(tree, name);
25611
+ case "zsh":
25612
+ return generateZshCompletion(tree, name);
25613
+ case "fish":
25614
+ return generateFishCompletion(tree, name);
25366
25615
  }
25367
- return request(createClient(refreshedToken));
25368
25616
  }
25369
- async function authenticatedRequestSafe(request) {
25370
- const token = readTokenSafe();
25371
- if (!token) {
25372
- return null;
25617
+
25618
+ // src/completion/install.ts
25619
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
25620
+ import { homedir as homedir2 } from "os";
25621
+ import { join as join2 } from "path";
25622
+ var TRACE_DIR = ".trace";
25623
+ function completionFileName(shell) {
25624
+ switch (shell) {
25625
+ case "bash":
25626
+ return "tracecli-completion.bash";
25627
+ case "zsh":
25628
+ return "_tracecli";
25629
+ case "fish":
25630
+ return "tracecli-completion.fish";
25373
25631
  }
25374
- try {
25375
- const firstResult = await request(createClient(token));
25376
- if (firstResult.status !== UNAUTHORIZED_STATUS) {
25377
- return firstResult;
25378
- }
25379
- const refreshedToken = await refreshStoredAccessToken();
25380
- if (!refreshedToken) {
25381
- return firstResult;
25382
- }
25383
- return await request(createClient(refreshedToken));
25384
- } catch {
25385
- return null;
25632
+ }
25633
+ function getTraceDir() {
25634
+ return join2(homedir2(), TRACE_DIR);
25635
+ }
25636
+ function getCompletionFilePath(shell) {
25637
+ return join2(getTraceDir(), completionFileName(shell));
25638
+ }
25639
+ function writeCompletionFile(shell, script) {
25640
+ const dir = getTraceDir();
25641
+ if (!existsSync2(dir)) {
25642
+ mkdirSync2(dir, { recursive: true });
25386
25643
  }
25644
+ const filePath = getCompletionFilePath(shell);
25645
+ writeFileSync2(filePath, script, "utf-8");
25646
+ return filePath;
25387
25647
  }
25388
- var SAFE_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
25389
- async function resolveOrganizationId(client) {
25390
- const result = client ? await client.organization.listOrganizations() : await authenticatedRequest(
25391
- (authenticatedClient) => authenticatedClient.organization.listOrganizations()
25392
- );
25393
- if (result.status !== 200) {
25394
- console.error(`Failed to resolve organization (status ${result.status}).`);
25395
- process.exit(1);
25648
+ function getSetupInstructions(shell) {
25649
+ const traceDir = `~/${TRACE_DIR}`;
25650
+ switch (shell) {
25651
+ case "bash":
25652
+ return [
25653
+ "Add the following line to your .bashrc file:",
25654
+ "",
25655
+ " # The next line enables shell command completion for Trace",
25656
+ ` source ${traceDir}/tracecli-completion.bash`,
25657
+ ""
25658
+ ].join("\n");
25659
+ case "zsh":
25660
+ return [
25661
+ "Add the following lines to your .zshrc file:",
25662
+ "",
25663
+ " # The next lines enable shell command completion for Trace",
25664
+ ` fpath=(${traceDir} $fpath)`,
25665
+ " autoload -Uz compinit && compinit -i",
25666
+ ""
25667
+ ].join("\n");
25668
+ case "fish":
25669
+ return [
25670
+ "Copy the completion file to your fish completions directory:",
25671
+ "",
25672
+ ` cp ${traceDir}/tracecli-completion.fish ~/.config/fish/completions/tracecli.fish`,
25673
+ ""
25674
+ ].join("\n");
25396
25675
  }
25397
- const org = result.body[0];
25398
- if (!org) {
25399
- console.error("No organization found for your account.");
25400
- process.exit(1);
25676
+ }
25677
+
25678
+ // src/completion/commands.ts
25679
+ var SUPPORTED_SHELLS = ["bash", "zsh", "fish"];
25680
+ function detectShell() {
25681
+ const shellEnv = process.env["SHELL"] ?? "";
25682
+ if (shellEnv.endsWith("/bash") || shellEnv.endsWith("/bash.exe")) {
25683
+ return "bash";
25401
25684
  }
25402
- const id = org.organizationId;
25403
- if (!SAFE_ID_PATTERN.test(id)) {
25404
- console.error("Invalid organization ID received from API.");
25405
- process.exit(1);
25685
+ if (shellEnv.endsWith("/zsh")) {
25686
+ return "zsh";
25406
25687
  }
25407
- return id;
25688
+ if (shellEnv.endsWith("/fish")) {
25689
+ return "fish";
25690
+ }
25691
+ return null;
25408
25692
  }
25409
- async function resolveOrganizationIdSafe(client) {
25410
- try {
25411
- const result = client ? await client.organization.listOrganizations() : await authenticatedRequestSafe(
25412
- (authenticatedClient) => authenticatedClient.organization.listOrganizations()
25693
+ function resolveShell(shellOption) {
25694
+ const shell = shellOption ?? detectShell();
25695
+ if (!shell) {
25696
+ console.error(
25697
+ `Could not detect shell. Please specify one with --shell <${SUPPORTED_SHELLS.join("|")}>.`
25413
25698
  );
25414
- if (!result) {
25415
- return null;
25416
- }
25417
- if (result.status !== 200) {
25418
- return null;
25419
- }
25420
- const org = result.body[0];
25421
- if (!org) {
25422
- return null;
25423
- }
25424
- const id = org.organizationId;
25425
- if (!SAFE_ID_PATTERN.test(id)) {
25426
- return null;
25427
- }
25428
- return id;
25429
- } catch {
25430
- return null;
25699
+ process.exit(1);
25700
+ }
25701
+ if (!SUPPORTED_SHELLS.includes(shell)) {
25702
+ console.error(
25703
+ `Unsupported shell: '${shell}'. Supported shells: ${SUPPORTED_SHELLS.join(", ")}.`
25704
+ );
25705
+ process.exit(1);
25431
25706
  }
25707
+ return shell;
25708
+ }
25709
+ function createCompletionCommand(program3) {
25710
+ return new Command("completion").description("Generate shell completion script").option("--shell <shell>", `Shell type (${SUPPORTED_SHELLS.join(", ")})`).action((options) => {
25711
+ const shell = resolveShell(options.shell);
25712
+ const script = generateCompletion(program3, shell);
25713
+ const writtenPath = writeCompletionFile(shell, script);
25714
+ console.log(`Completion file written to ${writtenPath}`);
25715
+ console.log("");
25716
+ console.log(getSetupInstructions(shell));
25717
+ });
25432
25718
  }
25433
25719
 
25434
25720
  // src/format.ts
@@ -25979,7 +26265,10 @@ function addRepositoryFilterOptions(command) {
25979
26265
  async function runRepositoryListCommand(options) {
25980
26266
  const organizationId = await resolveOrganizationId();
25981
26267
  if (options.dependency) {
25982
- await runDependencyFilter(organizationId, options);
26268
+ await runDependencyFilter(organizationId, {
26269
+ ...options,
26270
+ dependency: options.dependency
26271
+ });
25983
26272
  return;
25984
26273
  }
25985
26274
  let filteredRepositories;
@@ -26019,7 +26308,11 @@ async function runRepositoryListCommand(options) {
26019
26308
  }
26020
26309
  }
26021
26310
  async function runDependencyFilter(organizationId, options) {
26022
- const { name, version: version2 } = parseDependencyFilter(options.dependency);
26311
+ const dependency = options.dependency;
26312
+ if (!dependency) {
26313
+ throw new Error("Dependency filter is required.");
26314
+ }
26315
+ const { name, version: version2 } = parseDependencyFilter(dependency);
26023
26316
  const result = await authenticatedRequest(
26024
26317
  (client) => client.dependency.searchDependencies({
26025
26318
  params: { organizationId },
@@ -26308,7 +26601,7 @@ function createListCommand3() {
26308
26601
  (value) => value.toUpperCase()
26309
26602
  ).option(
26310
26603
  "--status <status>",
26311
- "Filter by status (OPEN, IN_PROGRESS, FIXED, IGNORED, FALSE_POSITIVE)",
26604
+ "Filter by status (OPEN, IN_PROGRESS, FIXED, ARCHIVED, FALSE_POSITIVE)",
26312
26605
  (value) => value.toUpperCase()
26313
26606
  ).option(
26314
26607
  "-L, --limit <n>",