passport-bridge 0.7.0 → 0.8.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.
@@ -0,0 +1,111 @@
1
+ import { CliFailure, failure } from "./cliSupport.js";
2
+ export function firstText(result) {
3
+ return result.content
4
+ .filter((part) => part.type === "text")
5
+ .map((part) => part.text)
6
+ .join("");
7
+ }
8
+ export function hasNonText(result) {
9
+ return result.content.some((part) => part.type !== "text");
10
+ }
11
+ export function payloadOf(result, label) {
12
+ const text = firstText(result);
13
+ if (text) {
14
+ try {
15
+ const parsed = JSON.parse(text);
16
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
17
+ return parsed;
18
+ }
19
+ catch {
20
+ /* structured content may carry a future server payload */
21
+ }
22
+ }
23
+ if (result.structuredContent && !result.structuredContent.cause)
24
+ return result.structuredContent;
25
+ return failure(`Passport returned an invalid ${label} payload.`, 1, "invalid_server_response");
26
+ }
27
+ export function refusalOf(result) {
28
+ const structured = result.structuredContent;
29
+ if (result._meta?.["passport/refusal"] !== true) {
30
+ return result.isError
31
+ ? new CliFailure(firstText(result) || "The tool returned an error.", 1, "tool_error")
32
+ : undefined;
33
+ }
34
+ const cause = typeof structured?.cause === "string" ? structured.cause : "";
35
+ if (!cause) {
36
+ return new CliFailure("Passport returned an invalid refusal payload.", 1, "invalid_server_response");
37
+ }
38
+ const recognized = new Set(["needs_connect", "approval_pending", "approval_denied", "blocked", "unknown_tool"]);
39
+ if (!recognized.has(cause)) {
40
+ return result.isError
41
+ ? new CliFailure(firstText(result) || "The tool returned an error.", 1, "tool_error")
42
+ : undefined;
43
+ }
44
+ const app = typeof structured?.app === "string" ? structured.app : undefined;
45
+ const approvalId = typeof structured?.approvalId === "string" ? structured.approvalId : undefined;
46
+ const connectUrl = (() => {
47
+ if (typeof structured?.connectUrl !== "string")
48
+ return undefined;
49
+ try {
50
+ const parsed = new URL(structured.connectUrl);
51
+ return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.toString() : undefined;
52
+ }
53
+ catch {
54
+ return undefined;
55
+ }
56
+ })();
57
+ let message = firstText(result) || "Passport refused the call.";
58
+ if (cause === "needs_connect") {
59
+ return new CliFailure(message, 3, cause, {
60
+ app,
61
+ connectUrl,
62
+ hint: connectUrl
63
+ ? `Open: ${connectUrl}\nFinish the browser sign-in, then retry the command.`
64
+ : app
65
+ ? "Run the connect action below, then retry the command."
66
+ : "Run passport status to identify the app that needs connecting.",
67
+ next: app
68
+ ? [
69
+ {
70
+ argv: ["passport", "connect", app, "--wait", "120"],
71
+ description: "Connect the required app, then retry the tool call."
72
+ }
73
+ ]
74
+ : [{ argv: ["passport", "status"], description: "Identify the app that needs connecting." }]
75
+ });
76
+ }
77
+ if (cause === "approval_pending") {
78
+ if (approvalId && !message.includes(approvalId))
79
+ message = `${message}\nApproval ID: ${approvalId}`;
80
+ return new CliFailure(message, 4, cause, {
81
+ app,
82
+ approvalId,
83
+ hint: "Approve the request in Passport, then retry it. For future calls, add --wait <seconds>."
84
+ });
85
+ }
86
+ if (cause === "approval_denied" || cause === "blocked") {
87
+ return new CliFailure(message, 5, cause, { app, approvalId });
88
+ }
89
+ if (cause === "unknown_tool") {
90
+ return new CliFailure(message, 6, cause, {
91
+ app,
92
+ hint: `Run: passport search${app ? ` --app ${app}` : ""}`,
93
+ next: [
94
+ {
95
+ argv: app ? ["passport", "search", "", "--app", app] : ["passport", "search", ""],
96
+ description: "List permitted tool names."
97
+ }
98
+ ]
99
+ });
100
+ }
101
+ return new CliFailure(`Passport returned an unsupported refusal cause: ${cause}.`, 1, "invalid_server_response", {
102
+ app,
103
+ approvalId
104
+ });
105
+ }
106
+ export function requireSuccess(result) {
107
+ const refusal = refusalOf(result);
108
+ if (refusal)
109
+ throw refusal;
110
+ return result;
111
+ }
@@ -0,0 +1,163 @@
1
+ import { once } from "node:events";
2
+ import { bool, parseArgs, value } from "./cliArgs.js";
3
+ import { asFailure, failurePayload } from "./cliOutput.js";
4
+ import { callerFrom, CliFailure, failure, resolveCliAuth, timeoutMs } from "./cliSupport.js";
5
+ export const CLI_SESSION_LINE_MAX_BYTES = 1024 * 1024;
6
+ export const CLI_SESSION_ARGV_MAX_ITEMS = 128;
7
+ /**
8
+ * Split an async byte stream into bounded UTF-8 lines. The limit applies before
9
+ * decoding, so a caller cannot grow an unbounded string while omitting `\n`.
10
+ */
11
+ export async function* readBoundedSessionLines(input, signal, maxBytes = CLI_SESSION_LINE_MAX_BYTES) {
12
+ const iterator = input[Symbol.asyncIterator]();
13
+ let pending = Buffer.alloc(0);
14
+ let rejectAborted = () => { };
15
+ const fail = () => rejectAborted(signal.reason ?? new Error("Cancelled."));
16
+ const aborted = new Promise((_, reject) => {
17
+ rejectAborted = reject;
18
+ });
19
+ if (signal.aborted)
20
+ fail();
21
+ else
22
+ signal.addEventListener("abort", fail, { once: true });
23
+ try {
24
+ for (;;) {
25
+ const step = await Promise.race([iterator.next(), aborted]);
26
+ if (step.done)
27
+ break;
28
+ const chunk = Buffer.from(step.value);
29
+ let offset = 0;
30
+ for (;;) {
31
+ const newline = chunk.indexOf(0x0a, offset);
32
+ const end = newline < 0 ? chunk.length : newline;
33
+ const segment = chunk.subarray(offset, end);
34
+ if (pending.byteLength + segment.byteLength > maxBytes) {
35
+ throw new CliFailure(`Session input lines are limited to ${maxBytes} bytes.`, 6, "usage");
36
+ }
37
+ if (segment.byteLength)
38
+ pending = Buffer.concat([pending, segment]);
39
+ if (newline < 0)
40
+ break;
41
+ const line = pending.byteLength && pending[pending.byteLength - 1] === 0x0d ? pending.subarray(0, -1) : pending;
42
+ yield line.toString("utf8");
43
+ pending = Buffer.alloc(0);
44
+ offset = newline + 1;
45
+ }
46
+ }
47
+ if (pending.byteLength)
48
+ yield pending.toString("utf8");
49
+ }
50
+ finally {
51
+ signal.removeEventListener("abort", fail);
52
+ await iterator.return?.();
53
+ }
54
+ }
55
+ export function parseSessionRequest(line) {
56
+ if (!line.trim())
57
+ return undefined;
58
+ let parsed;
59
+ try {
60
+ parsed = JSON.parse(line);
61
+ }
62
+ catch {
63
+ throw new CliFailure("Session input must contain one JSON object per line.", 6, "usage");
64
+ }
65
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
66
+ throw new CliFailure("Each session request must be a JSON object.", 6, "usage");
67
+ }
68
+ const request = parsed;
69
+ if (request.id !== undefined &&
70
+ !((typeof request.id === "string" && Buffer.byteLength(request.id) <= 128) ||
71
+ (typeof request.id === "number" && Number.isSafeInteger(request.id)))) {
72
+ throw new CliFailure("Session request id must be a safe integer or a string of at most 128 bytes.", 6, "usage");
73
+ }
74
+ if (!Array.isArray(request.argv) ||
75
+ request.argv.length === 0 ||
76
+ request.argv.length > CLI_SESSION_ARGV_MAX_ITEMS ||
77
+ !request.argv.every((part) => typeof part === "string")) {
78
+ throw new CliFailure(`Session request argv must contain 1-${CLI_SESSION_ARGV_MAX_ITEMS} strings.`, 6, "usage");
79
+ }
80
+ return { ...(request.id !== undefined ? { id: request.id } : {}), argv: request.argv };
81
+ }
82
+ const SESSION_COMMANDS = new Set([
83
+ "status",
84
+ "search",
85
+ "describe",
86
+ "run",
87
+ "connect",
88
+ "resources",
89
+ "prompts",
90
+ "discover"
91
+ ]);
92
+ async function writeSessionResponse(runtime, value) {
93
+ if (runtime.stdout.write(`${JSON.stringify(value)}\n`) !== false)
94
+ return;
95
+ // A long-running producer must honor pipe backpressure or a slow agent could
96
+ // make Node retain an unbounded queue of otherwise bounded results.
97
+ await once(runtime.stdout, "drain", { signal: runtime.signal });
98
+ }
99
+ export function writeCliSessionFailure(runtime, error) {
100
+ return writeSessionResponse(runtime, { ok: false, ...failurePayload(error) });
101
+ }
102
+ /** Keep one token manager and MCP client alive while processing sequential
103
+ * NDJSON requests. Authorization and policy still run at the gateway for every
104
+ * operation; only local process, token-exchange, initialization, and protocol
105
+ * assertion overhead is shared. */
106
+ export async function runCliSession(args, runtime, dispatch) {
107
+ const auth = resolveCliAuth(args, runtime.env);
108
+ const { CliGateway } = await import("./cliClient.js");
109
+ const gateway = await CliGateway.connect({
110
+ auth,
111
+ caller: callerFrom(args, runtime.env),
112
+ timeoutMs: timeoutMs(args),
113
+ signal: runtime.signal
114
+ });
115
+ try {
116
+ await gateway.assertCliProtocol();
117
+ const nestedRuntime = { ...runtime, sharedGateway: { gateway, auth } };
118
+ for await (const line of readBoundedSessionLines(runtime.stdin ?? process.stdin, runtime.signal)) {
119
+ let id;
120
+ try {
121
+ const request = parseSessionRequest(line);
122
+ if (!request)
123
+ continue;
124
+ id = request.id;
125
+ const nested = parseArgs(request.argv);
126
+ if (!SESSION_COMMANDS.has(nested.command)) {
127
+ return failure(`Command "${nested.command}" is not available in session mode.`, 6, "usage");
128
+ }
129
+ if (value(nested, "profile") !== undefined ||
130
+ value(nested, "caller") !== undefined ||
131
+ value(nested, "timeout") !== undefined ||
132
+ bool(nested, "quiet") ||
133
+ bool(nested, "json")) {
134
+ return failure("Set global options on `passport session`; per-request --profile, --caller, --timeout, --quiet, and --json are not allowed.", 6, "usage");
135
+ }
136
+ if (nested.command === "run" && value(nested, "args") === "-") {
137
+ return failure("Session run requests cannot use --args -; include arguments in argv instead.", 6, "usage");
138
+ }
139
+ nested.booleans.add("json");
140
+ const result = await dispatch(nested, nestedRuntime);
141
+ const exitCode = result.exitCode ?? 0;
142
+ await writeSessionResponse(runtime, {
143
+ ...(id !== undefined ? { id } : {}),
144
+ ok: exitCode === 0,
145
+ result: result.json,
146
+ exitCode
147
+ });
148
+ }
149
+ catch (error) {
150
+ const cliError = asFailure(error);
151
+ await writeSessionResponse(runtime, {
152
+ ...(id !== undefined ? { id } : {}),
153
+ ok: false,
154
+ ...failurePayload(cliError)
155
+ });
156
+ }
157
+ }
158
+ return { json: { closed: true }, exitCode: 0 };
159
+ }
160
+ finally {
161
+ await gateway.close();
162
+ }
163
+ }
@@ -0,0 +1,232 @@
1
+ import { spawn } from "node:child_process";
2
+ import { value } from "./cliArgs.js";
3
+ import { assertProfileName, readActiveProfile, readCreds } from "./credentials.js";
4
+ import { readBoundedJson } from "./boundedResponse.js";
5
+ export { readBoundedJson } from "./boundedResponse.js";
6
+ export const DEFAULT_TIMEOUT_MS = 30_000;
7
+ export class CliFailure extends Error {
8
+ exitCode;
9
+ cause;
10
+ details;
11
+ constructor(message, exitCode, cause, details = {}) {
12
+ super(message);
13
+ this.exitCode = exitCode;
14
+ this.cause = cause;
15
+ this.details = details;
16
+ }
17
+ }
18
+ export function failure(message, exitCode, cause, details = {}) {
19
+ throw new CliFailure(message, exitCode, cause, details);
20
+ }
21
+ export function timeoutMs(args) {
22
+ return Math.ceil(Number(value(args, "timeout") ?? DEFAULT_TIMEOUT_MS / 1000) * 1000);
23
+ }
24
+ export function profileName(raw) {
25
+ try {
26
+ assertProfileName(raw);
27
+ return raw;
28
+ }
29
+ catch (error) {
30
+ return failure(error instanceof Error ? error.message : "Invalid profile name.", 6, "usage");
31
+ }
32
+ }
33
+ export function endpoint(raw) {
34
+ try {
35
+ const parsed = new URL(raw);
36
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
37
+ throw new Error();
38
+ if (parsed.username || parsed.password) {
39
+ return failure("Passport endpoint URLs cannot contain a username or password.", 6, "usage");
40
+ }
41
+ const host = parsed.hostname.toLowerCase();
42
+ const loopback = host === "localhost" || host === "[::1]" || host === "::1" || /^127(?:\.\d{1,3}){3}$/.test(host);
43
+ if (parsed.protocol === "http:" && !loopback) {
44
+ return failure("Passport CLI requires HTTPS for remote servers. Configure HTTPS for your self-hosted Passport deployment; plain HTTP is allowed only on localhost, 127.0.0.0/8, or ::1.", 6, "usage");
45
+ }
46
+ return parsed.toString().replace(/\/$/, "");
47
+ }
48
+ catch (error) {
49
+ if (error instanceof CliFailure)
50
+ throw error;
51
+ return failure("Passport endpoint must be an http or https URL.", 6, "usage");
52
+ }
53
+ }
54
+ export function cloudOrigin(raw) {
55
+ const normalized = endpoint(raw);
56
+ const parsed = new URL(normalized);
57
+ if (parsed.pathname !== "/" || parsed.search || parsed.hash) {
58
+ return failure("--cloud must be a Passport origin without a path, query, or fragment.", 6, "usage");
59
+ }
60
+ return parsed.origin;
61
+ }
62
+ export function sameOriginWebUrl(raw, trustedOrigin, label) {
63
+ const normalized = endpoint(raw);
64
+ if (new URL(normalized).origin !== trustedOrigin) {
65
+ return failure(`Passport returned ${label} on a different origin; the operation was refused.`, 1, "invalid_server_response");
66
+ }
67
+ return normalized;
68
+ }
69
+ export function resolveCliAuth(args, env) {
70
+ const explicitProfile = value(args, "profile");
71
+ const agentKey = env.PASSPORT_AGENT_KEY ?? "";
72
+ const agentEndpoint = env.PASSPORT_ENDPOINT ?? "";
73
+ if (agentKey || agentEndpoint) {
74
+ if (!agentKey || !agentEndpoint) {
75
+ return failure("PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT must be set together.", 2, "auth", {
76
+ hint: "Set both variables, or unset both before running passport login."
77
+ });
78
+ }
79
+ if (explicitProfile !== undefined) {
80
+ return failure("--profile cannot be used with PASSPORT_AGENT_KEY.", 6, "usage");
81
+ }
82
+ return { kind: "agent-key", endpoint: endpoint(agentEndpoint), agentKey };
83
+ }
84
+ const creds = readCreds();
85
+ const names = Object.keys(creds).sort();
86
+ const active = readActiveProfile();
87
+ // Explicit CLI and environment selection always win. A locally selected
88
+ // profile is next, followed by the historical single-profile fallback. We
89
+ // only honor the active pointer when it still names a stored profile; a
90
+ // stale pointer must never make us guess a different workspace.
91
+ const fallbackProfile = env.PASSPORT_PROFILE || (active && creds[active] ? active : names.length === 1 ? names[0] : "");
92
+ const profile = explicitProfile !== undefined ? profileName(explicitProfile) : fallbackProfile ? profileName(fallbackProfile) : "";
93
+ if (!profile) {
94
+ const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
95
+ const hint = names.length
96
+ ? `Choose one with: passport use <name> (available: ${names.join(", ")}), or pass --profile <name>.`
97
+ : "Run: passport login --workspace <workspace-id>.";
98
+ return failure(`No Passport profile selected.${suffix}`, 2, "auth", {
99
+ hint,
100
+ ...(names.length
101
+ ? {
102
+ profiles: names,
103
+ next: [
104
+ { argv: ["passport", "profiles"], description: "List saved profiles." },
105
+ ...names.map((name) => ({
106
+ argv: ["passport", "use", name],
107
+ description: `Select the saved profile "${name}".`
108
+ }))
109
+ ]
110
+ }
111
+ : {
112
+ requiredInput: ["workspace-id"]
113
+ })
114
+ });
115
+ }
116
+ const saved = creds[profile];
117
+ if (!saved) {
118
+ const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
119
+ const hint = names.length
120
+ ? `Choose one with: passport use <name> (available: ${names.join(", ")}), or pass --profile <name>.`
121
+ : "Run: passport login --workspace <workspace-id>.";
122
+ return failure(`Passport profile "${profile}" does not exist.${suffix}`, 2, "auth", {
123
+ hint,
124
+ ...(names.length
125
+ ? {
126
+ profiles: names,
127
+ next: [
128
+ { argv: ["passport", "profiles"], description: "List saved profiles." },
129
+ ...names.map((name) => ({
130
+ argv: ["passport", "use", name],
131
+ description: `Select the saved profile "${name}".`
132
+ }))
133
+ ]
134
+ }
135
+ : {
136
+ requiredInput: ["workspace-id"]
137
+ })
138
+ });
139
+ }
140
+ return { kind: "profile", endpoint: endpoint(saved.endpoint), profile, refreshToken: saved.refreshToken };
141
+ }
142
+ export function callerFrom(args, env) {
143
+ const explicit = value(args, "caller");
144
+ if (explicit !== undefined) {
145
+ const normalized = explicit.trim().toLowerCase();
146
+ if (!/^[a-z0-9-]{1,24}$/.test(normalized)) {
147
+ return failure("--caller must contain 1-24 lowercase letters, numbers, or hyphens.", 6, "usage");
148
+ }
149
+ return normalized;
150
+ }
151
+ const keys = Object.keys(env);
152
+ if (Object.hasOwn(env, "CLAUDECODE") || keys.some((key) => key.startsWith("CLAUDE_CODE")))
153
+ return "claude-code";
154
+ if (Object.hasOwn(env, "CODEX_SANDBOX") || keys.some((key) => key.startsWith("CODEX_")))
155
+ return "codex";
156
+ if (Object.hasOwn(env, "OPENCODE") || keys.some((key) => key.startsWith("OPENCODE_")))
157
+ return "opencode";
158
+ if (Object.hasOwn(env, "CURSOR_TRACE_ID") || keys.some((key) => key.startsWith("CURSOR_")))
159
+ return "cursor";
160
+ if (Object.hasOwn(env, "GEMINI_CLI"))
161
+ return "gemini";
162
+ return undefined;
163
+ }
164
+ export function sanitize(message) {
165
+ return message
166
+ .slice(0, 2_000)
167
+ .replace(/Bearer\s+\S+/gi, "Bearer [redacted]")
168
+ .replace(/("(?:refreshToken|refresh-token|accessToken|access-token|token|agentKey|agent_key|agent-key|apiKey|api_key|api-key|clientSecret|client_secret|client-secret)"\s*:\s*")[^"]*"/gi, '$1[redacted]"')
169
+ .replace(/((?:refreshToken|refresh-token|accessToken|access-token|token|agentKey|agent_key|agent-key|apiKey|api_key|api-key|agent-key|clientSecret|client_secret|client-secret)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&}]+)/gi, "$1[redacted]")
170
+ .replace(/\b(?:[A-Za-z0-9_-]+~)?(?:pak|ppr|ppa|pp)_[A-Za-z0-9_-]{12,}\b/g, "[redacted]")
171
+ .slice(0, 500);
172
+ }
173
+ export async function timedFetch(input, init, ms, parent) {
174
+ return fetch(input, {
175
+ ...init,
176
+ redirect: "error",
177
+ signal: AbortSignal.any([parent, AbortSignal.timeout(ms)])
178
+ });
179
+ }
180
+ export async function safeApiError(response, fallback) {
181
+ try {
182
+ const body = await readBoundedJson(response, 64 * 1024);
183
+ return typeof body.error === "string" ? sanitize(body.error) : fallback;
184
+ }
185
+ catch {
186
+ return fallback;
187
+ }
188
+ }
189
+ export function sleep(ms, signal) {
190
+ return new Promise((resolve, reject) => {
191
+ if (signal.aborted) {
192
+ reject(signal.reason);
193
+ return;
194
+ }
195
+ const timer = setTimeout(done, ms);
196
+ function done() {
197
+ signal.removeEventListener("abort", cancelled);
198
+ resolve();
199
+ }
200
+ function cancelled() {
201
+ clearTimeout(timer);
202
+ signal.removeEventListener("abort", cancelled);
203
+ reject(signal.reason);
204
+ }
205
+ signal.addEventListener("abort", cancelled, { once: true });
206
+ });
207
+ }
208
+ /** Open only a validated web URL. A provider-controlled query string must stay
209
+ * one opaque process argument and never cross a command-shell boundary. */
210
+ export function openUrl(url, platform = process.platform, launch = spawn) {
211
+ try {
212
+ const parsed = new URL(url);
213
+ if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.username || parsed.password) {
214
+ return false;
215
+ }
216
+ const command = platform === "darwin" ? "open" : platform === "win32" ? "rundll32.exe" : "xdg-open";
217
+ const args = platform === "win32" ? ["url.dll,FileProtocolHandler", parsed.toString()] : [parsed.toString()];
218
+ const child = launch(command, args, { stdio: "ignore", detached: true, shell: false });
219
+ child.on("error", () => { });
220
+ child.unref();
221
+ return true;
222
+ }
223
+ catch {
224
+ /* the printed URL remains usable */
225
+ return false;
226
+ }
227
+ }
228
+ export function firstSentence(value) {
229
+ const trimmed = value.trim().replace(/\s+/g, " ");
230
+ const match = trimmed.match(/^.*?[.!?](?:\s|$)/);
231
+ return (match?.[0] ?? trimmed).trim();
232
+ }
@@ -2,6 +2,8 @@ import { COMMANDS } from "./cliArgs.js";
2
2
  const DESCRIPTIONS = {
3
3
  login: "Sign in with the device flow",
4
4
  logout: "Revoke and remove a profile",
5
+ profiles: "List saved profiles and the active selection",
6
+ use: "Select a saved profile for subsequent commands",
5
7
  status: "Show identity and MCP connection state",
6
8
  doctor: "Diagnose local configuration and server compatibility",
7
9
  search: "Find permitted tools",
@@ -11,13 +13,14 @@ const DESCRIPTIONS = {
11
13
  resources: "List or read MCP resources",
12
14
  prompts: "List or get MCP prompts",
13
15
  discover: "Scan local MCP configuration for fleet governance",
16
+ session: "Reuse one authenticated session for NDJSON commands",
14
17
  completion: "Generate shell completion",
15
18
  help: "Show command help",
16
19
  version: "Show CLI version and local context"
17
20
  };
18
21
  const GLOBAL = ["--profile", "--json", "--timeout", "--quiet", "--caller", "--help"];
19
22
  const COMMAND_FLAGS = {
20
- login: ["--cloud", "--workspace", "--client"],
23
+ login: ["--cloud", "--workspace", "--client", "--no-open"],
21
24
  search: ["--app"],
22
25
  run: ["--args", "--set", "--set-json", "--wait"],
23
26
  connect: ["--alias", "--open", "--wait"],
@@ -25,11 +28,22 @@ const COMMAND_FLAGS = {
25
28
  prompts: ["--set", "--out"]
26
29
  };
27
30
  const VALUE_FLAGS = new Set([
28
- "--profile", "--timeout", "--caller", "--cloud", "--workspace", "--client",
29
- "--app", "--args", "--set", "--set-json", "--wait", "--alias", "--out"
31
+ "--profile",
32
+ "--timeout",
33
+ "--caller",
34
+ "--cloud",
35
+ "--workspace",
36
+ "--client",
37
+ "--app",
38
+ "--args",
39
+ "--set",
40
+ "--set-json",
41
+ "--wait",
42
+ "--alias",
43
+ "--out"
30
44
  ]);
31
45
  function flagsFor(command) {
32
- return [...GLOBAL, ...(command ? COMMAND_FLAGS[command] ?? [] : [])];
46
+ return [...GLOBAL, ...(command ? (COMMAND_FLAGS[command] ?? []) : [])];
33
47
  }
34
48
  function bash() {
35
49
  const commandWords = COMMANDS.join(" ");
@@ -64,9 +78,13 @@ complete -F _passport_completion passport
64
78
  function zsh() {
65
79
  const commands = COMMANDS.map((command) => ` '${command}:${DESCRIPTIONS[command]}'`).join("\n");
66
80
  const cases = COMMANDS.map((command) => {
67
- const flags = (COMMAND_FLAGS[command] ?? []).map((flag) => ` '${flag}[${flag.slice(2).replaceAll("-", " ")}]${VALUE_FLAGS.has(flag) ? ":value:" : ""}'`).join("");
81
+ const flags = (COMMAND_FLAGS[command] ?? [])
82
+ .map((flag) => ` '${flag}[${flag.slice(2).replaceAll("-", " ")}]${VALUE_FLAGS.has(flag) ? ":value:" : ""}'`)
83
+ .join("");
68
84
  return flags ? ` ${command}) opts+=(${flags.trimStart()}) ;;` : "";
69
- }).filter(Boolean).join("\n");
85
+ })
86
+ .filter(Boolean)
87
+ .join("\n");
70
88
  return `#compdef passport
71
89
  _passport() {
72
90
  local -a commands opts
@@ -98,10 +116,7 @@ compdef _passport passport
98
116
  `;
99
117
  }
100
118
  function fish() {
101
- const lines = [
102
- "# fish completion for Passport CLI",
103
- "complete -c passport -f"
104
- ];
119
+ const lines = ["# fish completion for Passport CLI", "complete -c passport -f"];
105
120
  for (const command of COMMANDS) {
106
121
  lines.push(`complete -c passport -n '__fish_use_subcommand' -a ${command} -d '${DESCRIPTIONS[command]}'`);
107
122
  }