@fluid-app/fluid-cli 0.1.809 → 0.1.810

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 @@
1
+ export { r as saveClientProfile } from "./client-B1TfaVpZ.mjs";
@@ -1,10 +1,10 @@
1
- import { G as isIdentityProfile, P as readConfig, S as peekClientToken, W as isClientProfile, c as peekIdentityToken, u as profileAccessToken, y as clientAccessToken } from "./profiles-BxQg0jB_.mjs";
1
+ import { D as peekClientToken, F as SessionError, J as isClientProfile, P as exchangeNativeToken, R as readConfig, Y as isIdentityProfile, _ as profileAccessToken, a as RoleNotGrantedError, h as peekIdentityToken, j as resolveIdentityUrl, w as clientAccessToken } from "./client-B1TfaVpZ.mjs";
2
2
  import { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync, writeSync } from "node:fs";
3
3
  import { dirname, isAbsolute, join, sep } from "node:path";
4
4
  import { createHash } from "node:crypto";
5
5
  import { Socket } from "node:net";
6
6
  import { AsyncLocalStorage } from "node:async_hooks";
7
- //#region src/catalog/annotations.ts
7
+ // src/catalog/annotations.ts
8
8
  const ANNOTATION = Symbol.for("@fluid-app/fluid-cli.command-annotation");
9
9
  /**
10
10
  * Record the endpoints a command calls and whether it writes, so
@@ -21,8 +21,7 @@ function describeCommand(command, annotation) {
21
21
  function readAnnotation(command) {
22
22
  return command[ANNOTATION] ?? null;
23
23
  }
24
- //#endregion
25
- //#region src/catalog/walk.ts
24
+ // src/catalog/walk.ts
26
25
  function isHidden(command) {
27
26
  return command._hidden === true;
28
27
  }
@@ -103,17 +102,12 @@ function filterCatalog(entries, root, prefix) {
103
102
  const base = commandPath$1(target);
104
103
  return entries.filter((entry) => base.every((word, index) => entry.path[index] === word));
105
104
  }
106
- //#endregion
107
- //#region package.json
108
- var version = "0.1.809";
109
- //#endregion
110
- //#region src/auth/client-headers.ts
105
+ // src/auth/client-headers.ts
111
106
  const CLIENT_HEADERS = {
112
107
  "X-Fluid-Client": "cli",
113
- "X-Fluid-Client-Version": version
108
+ "X-Fluid-Client-Version": "0.1.810"
114
109
  };
115
- //#endregion
116
- //#region src/utils/result.ts
110
+ // src/utils/result.ts
117
111
  function success(value) {
118
112
  return {
119
113
  success: true,
@@ -174,8 +168,7 @@ function getErrorMessage(error) {
174
168
  if (typeof error === "string") return error;
175
169
  return String(error);
176
170
  }
177
- //#endregion
178
- //#region src/auth/fluid-api.ts
171
+ // src/auth/fluid-api.ts
179
172
  /**
180
173
  * Fluid API client for authentication operations, and the public signup
181
174
  * that comes before any of them
@@ -194,6 +187,7 @@ function isInsecureRemoteBase(base) {
194
187
  const host = url.hostname;
195
188
  return !(host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host.endsWith(".localhost"));
196
189
  }
190
+ const DEFAULT_FLUID_API_BASE = "https://api.fluid.app";
197
191
  function getFluidApiBase() {
198
192
  return process.env["FLUID_API_BASE"] ?? "https://api.fluid.app";
199
193
  }
@@ -311,15 +305,35 @@ async function validateToken(token, options = {}) {
311
305
  cleanup();
312
306
  }
313
307
  }
314
- /** The roles a CLI login may hold, as `/api/me` names them. */
315
- const STAFF_ROLES = new Set(["admin", "rep"]);
308
+ /** The roles a CLI login may hold, as `/api/v2026-10/me` names them. */
309
+ const STAFF_ROLES = /* @__PURE__ */ new Set(["admin", "rep"]);
316
310
  /**
317
- * The company of an admin's or a rep's login, from `/api/me`. A token it
318
- * refuses, or one that belongs to a customer, is invalid for the CLI; any
319
- * other failure, or an answer with no company name, leaves the API
311
+ * The company of an admin's or a rep's login, from `/api/v2026-10/me`.
312
+ * Falls back to `/api/me` on 403 so valid company-restricted staff sessions
313
+ * (which `/api/v2026-10/me` refuses) remain usable while keeping the same
314
+ * staff-role allowlist. Any other refusal, or a customer token, is invalid for
315
+ * the CLI; any other failure, or an answer with no company name, leaves the API
320
316
  * unreachable, as `/companies/me` does.
321
317
  */
322
318
  async function staffCompanyFromMe(token, apiBase, signal) {
319
+ const response = await fetch(`${apiBase}/api/v2026-10/me?include=membership.details,company`, {
320
+ method: "GET",
321
+ headers: {
322
+ ...CLIENT_HEADERS,
323
+ Authorization: `Bearer ${token}`
324
+ },
325
+ signal
326
+ });
327
+ if (response.status === 403) return staffCompanyFromLegacyMe(token, apiBase, signal);
328
+ if (response.status === 401) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, `HTTP ${response.status}: Check that your token is valid and non-expired.`));
329
+ if (!response.ok) {
330
+ const body = await response.text();
331
+ return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status} from /api/v2026-10/me: ${body}`));
332
+ }
333
+ const body = await response.json();
334
+ return parseStaffCompany(body.data?.membership?.role, body.data?.company?.name, "/api/v2026-10/me");
335
+ }
336
+ async function staffCompanyFromLegacyMe(token, apiBase, signal) {
323
337
  const response = await fetch(`${apiBase}/api/me`, {
324
338
  method: "GET",
325
339
  headers: {
@@ -334,9 +348,11 @@ async function staffCompanyFromMe(token, apiBase, signal) {
334
348
  return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status} from /api/me: ${body}`));
335
349
  }
336
350
  const data = await response.json();
337
- if (typeof data?.role !== "string" || !STAFF_ROLES.has(data.role)) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, "This login is not an admin's or a rep's, so it cannot be used with the CLI."));
338
- const name = data.company?.name;
339
- if (typeof name !== "string" || name === "") return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, "Unexpected response shape from /api/me"));
351
+ return parseStaffCompany(data?.role, data?.company?.name, "/api/me");
352
+ }
353
+ function parseStaffCompany(role, name, endpoint) {
354
+ if (typeof role !== "string" || !STAFF_ROLES.has(role)) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, "This login is not an admin's or a rep's, so it cannot be used with the CLI."));
355
+ if (typeof name !== "string" || name === "") return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `Unexpected response shape from ${endpoint}`));
340
356
  return success({ name });
341
357
  }
342
358
  /**
@@ -485,7 +501,7 @@ async function fetchUserCompanies(token, baseUrl) {
485
501
  const { signal, cleanup } = makeSignal();
486
502
  const apiBase = baseUrl ?? getFluidApiBase();
487
503
  try {
488
- const response = await fetch(`${apiBase}/api/me`, {
504
+ const response = await fetch(`${apiBase}/api/v2026-10/me?include=companies,legacy_ids`, {
489
505
  method: "GET",
490
506
  headers: {
491
507
  ...CLIENT_HEADERS,
@@ -494,11 +510,11 @@ async function fetchUserCompanies(token, baseUrl) {
494
510
  signal
495
511
  });
496
512
  if (response.ok) {
497
- const data = await response.json();
498
- return success((Array.isArray(data.companies) ? data.companies : []).map((c) => ({
499
- id: c.id,
513
+ const body = await response.json();
514
+ return success((Array.isArray(body.data?.companies) ? body.data.companies : []).filter((c) => typeof c.legacy_id === "number").map((c) => ({
515
+ id: c.legacy_id,
500
516
  name: c.name,
501
- ...typeof c.uuid_v7 === "string" ? { uuidV7: c.uuid_v7 } : {}
517
+ ...typeof c.id === "string" ? { uuidV7: c.id } : {}
502
518
  })));
503
519
  }
504
520
  if (response.status === 401 || response.status === 403) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, `HTTP ${response.status}`));
@@ -787,8 +803,7 @@ async function pollAgentAccess(handle) {
787
803
  cleanup();
788
804
  }
789
805
  }
790
- //#endregion
791
- //#region src/config/project-config.ts
806
+ // src/config/project-config.ts
792
807
  /**
793
808
  * Project-level config (.fluidrc) reader.
794
809
  *
@@ -846,13 +861,13 @@ function findProjectConfig(startDir) {
846
861
  };
847
862
  return null;
848
863
  }
849
- //#endregion
850
- //#region src/auth/token.ts
864
+ // src/auth/token.ts
851
865
  /**
852
866
  * Token storage and retrieval from config
853
867
  */
854
868
  const FD_ENV = "FLUID_TOKEN_FD";
855
869
  const LIVE_HEADER = "live\n";
870
+ const memberTokenCache = /* @__PURE__ */ new Map();
856
871
  let fdTokenCache;
857
872
  function closeQuietly(fd) {
858
873
  try {
@@ -1112,17 +1127,47 @@ async function getAuthTokenAsync(profileName) {
1112
1127
  * `roles` in the company (RFC 8693), and holds that token apart from the
1113
1128
  * default one, which every other reader keeps getting.
1114
1129
  *
1115
- * Only an identity-mode profile can be narrowed. A literal token
1116
- * (`FLUID_TOKEN`) and a legacy profile come back exactly as
1117
- * {@link getAuthTokenAsync} returns them, because their token already is what
1118
- * it is. Resolves with null when there is no credential. Rejects with an
1130
+ * Resolves with null when there is no credential. Rejects with an
1119
1131
  * error {@link isRoleNotGrantedError} recognises when the person does not
1120
1132
  * hold `roles` in the company, and when an identity session has ended.
1121
1133
  */
1122
1134
  async function getRoleAuthTokenAsync(roles, profileName) {
1123
1135
  const source = resolveCredentialSource(profileName);
1124
1136
  if (!source) return null;
1125
- if (source.kind === "token") return source.token;
1137
+ if (source.kind === "token") {
1138
+ if (process.env["FLUID_MEMBER_LITERAL_TOKEN_NARROW"] !== "1" || roles.length !== 1 || roles[0] !== "rep") return source.token;
1139
+ const identityUrl = resolveIdentityUrl(process.env["FLUID_API_BASE"] ?? "");
1140
+ if (!identityUrl) throw new Error("Cannot narrow a member token: no identity URL for FLUID_API_BASE.");
1141
+ let claims;
1142
+ try {
1143
+ claims = JSON.parse(Buffer.from(source.token.split(".")[1] ?? "", "base64url").toString("utf8"));
1144
+ } catch {
1145
+ throw new Error("Cannot narrow a member token: cannot determine the token's org.");
1146
+ }
1147
+ const org = claims?.org;
1148
+ if (typeof org !== "string" || !org.trim()) throw new Error("Cannot narrow a member token: cannot determine the token's org.");
1149
+ if (typeof claims.iss === "string" && new URL(claims.iss).origin !== identityUrl) throw new Error("Cannot narrow a member token: issuer does not match the identity URL.");
1150
+ if (Array.isArray(claims.roles) && claims.roles.length === 1 && claims.roles[0] === "rep") return source.token;
1151
+ const clientId = process.env["FLUID_IDENTITY_CLIENT_ID"] || "fluid-cli";
1152
+ const key = `${identityUrl} ${clientId} ${org} ${createHash("sha256").update(source.token).digest("hex")}`;
1153
+ const cached = memberTokenCache.get(key);
1154
+ if (cached && Date.now() < cached.expiresAt - 3e4) return cached.accessToken;
1155
+ memberTokenCache.delete(key);
1156
+ try {
1157
+ const exchanged = await exchangeNativeToken({
1158
+ identityUrl,
1159
+ clientId
1160
+ }, source.token, {
1161
+ org,
1162
+ roles: ["rep"]
1163
+ });
1164
+ memberTokenCache.set(key, exchanged);
1165
+ return exchanged.accessToken;
1166
+ } catch (error) {
1167
+ if (error instanceof SessionError && error.code === "access_denied") throw new RoleNotGrantedError(["rep"], org);
1168
+ throw error;
1169
+ }
1170
+ }
1126
1171
  if (isIdentityProfile(source.profile)) return profileAccessToken(source.profile, roles);
1127
1172
  if (isClientProfile(source.profile)) return clientAccessToken(source.profile);
1128
1173
  return source.profile.token ?? null;
@@ -1142,8 +1187,7 @@ function listProfileNames() {
1142
1187
  const config = readConfig();
1143
1188
  return Object.keys(config.profiles);
1144
1189
  }
1145
- //#endregion
1146
- //#region src/inputs/declare.ts
1190
+ // src/inputs/declare.ts
1147
1191
  const resolvers = /* @__PURE__ */ new WeakMap();
1148
1192
  /**
1149
1193
  * Declares the local inputs a command's action reads.
@@ -1161,8 +1205,7 @@ function declareInputs(command, resolver) {
1161
1205
  function getInputResolver(command) {
1162
1206
  return resolvers.get(command);
1163
1207
  }
1164
- //#endregion
1165
- //#region src/inputs/scope.ts
1208
+ // src/inputs/scope.ts
1166
1209
  let internalDepth = 0;
1167
1210
  const asyncScope = new AsyncLocalStorage();
1168
1211
  /** True while the inputs implementation itself is touching the filesystem. */
@@ -1184,8 +1227,7 @@ function withInternalReads(fn) {
1184
1227
  async function withInternalReadsAsync(fn) {
1185
1228
  return asyncScope.run(true, fn);
1186
1229
  }
1187
- //#endregion
1188
- //#region src/inputs/paths.ts
1230
+ // src/inputs/paths.ts
1189
1231
  function lexicalPath(path, cwd = process.cwd()) {
1190
1232
  return isAbsolute(path) ? path : `${cwd}${sep}${path}`;
1191
1233
  }
@@ -1201,8 +1243,7 @@ function canonicalPath(path, cwd = process.cwd()) {
1201
1243
  canonical: withInternalReads(() => realpathSync.native(lexical))
1202
1244
  };
1203
1245
  }
1204
- //#endregion
1205
- //#region src/inputs/tree.ts
1246
+ // src/inputs/tree.ts
1206
1247
  function normalizeIgnore(ignore) {
1207
1248
  const out = /* @__PURE__ */ new Set();
1208
1249
  for (const pattern of ignore ?? []) {
@@ -1290,8 +1331,7 @@ function readTreeFileFromDisk(root, rel) {
1290
1331
  }
1291
1332
  });
1292
1333
  }
1293
- //#endregion
1294
- //#region src/inputs/snapshot.ts
1334
+ // src/inputs/snapshot.ts
1295
1335
  function treeKey(root, ignore, skipDotNames = false) {
1296
1336
  return `${root}\0${ignoreKey(ignore, skipDotNames)}`;
1297
1337
  }
@@ -1401,8 +1441,7 @@ function manifestJson(command, entries) {
1401
1441
  inputs: canonicalEntries(entries)
1402
1442
  });
1403
1443
  }
1404
- //#endregion
1405
- //#region src/inputs/reader.ts
1444
+ // src/inputs/reader.ts
1406
1445
  let activeSnapshot = null;
1407
1446
  function setActiveSnapshot(snapshot) {
1408
1447
  activeSnapshot = snapshot;
@@ -1496,8 +1535,7 @@ function createInputsReader() {
1496
1535
  }
1497
1536
  };
1498
1537
  }
1499
- //#endregion
1500
- //#region src/inputs/hook.ts
1538
+ // src/inputs/hook.ts
1501
1539
  const INPUTS_MODE_ENV = "FLUID_INPUTS_MODE";
1502
1540
  const INPUTS_EXPECT_ENV = "FLUID_INPUTS_EXPECT";
1503
1541
  const INPUTS_UNDECLARED_CODE = "inputs_undeclared";
@@ -1596,7 +1634,6 @@ function exitOnInputsError(error, io = processIo) {
1596
1634
  io.stderr(`${INPUTS_UNDECLARED_CODE}\n`);
1597
1635
  io.exit(64);
1598
1636
  }
1599
- //#endregion
1600
- export { unwrapOr as $, confirmMfa as A, validateToken as B, getRoleAuthTokenAsync as C, findProjectConfig as D, resolveCredentialSource as E, pollAgentAccess as F, isNodeError as G, getErrorMessage as H, redeemIdentityLink as I, mapResult as J, isSuccess as K, sendMfa as L, fetchUserCompanies as M, getFluidApiBase as N, FLUID_API_ERROR as O, isInsecureRemoteBase as P, unwrap as Q, signup as R, getAuthTokenAsync as S, readFdToken as T, isError as U, failure as V, isFailure as W, tryCatch as X, success as Y, tryCatchAsync as Z, describeCredentialSource as _, INPUTS_UNDECLARED_CODE as a, describeCommand as at, getActiveProfile as b, inputsModeActive as c, setActiveSnapshot as d, filterCatalog as et, inInternalRead as f, adoptIdentityProfile as g, declareInputs as h, INPUTS_MODE_ENV as i, walkCommands as it, fetchCompanyShops as j, SIGNUP_ERROR as k, registerInputsHook as l, withInternalReadsAsync as m, INPUTS_MISMATCH_CODE as n, visibleOptions as nt, INPUTS_UNDECLARED_EXIT as o, withInternalReads as p, mapError as q, INPUTS_MISMATCH_EXIT as r, visibleSubcommands as rt, exitOnInputsError as s, INPUTS_EXPECT_ENV as t, rootCommand as tt, createInputsReader as u, findIdentityFallbackCandidates as v, listProfileNames as w, getAuthToken as x, findIdentityFallbackProfile as y, switchCompany as z };
1637
+ export { unwrap as $, SIGNUP_ERROR as A, switchCompany as B, getRoleAuthTokenAsync as C, findProjectConfig as D, resolveCredentialSource as E, isInsecureRemoteBase as F, isFailure as G, failure as H, pollAgentAccess as I, mapError as J, isNodeError as K, redeemIdentityLink as L, fetchCompanyShops as M, fetchUserCompanies as N, DEFAULT_FLUID_API_BASE as O, getFluidApiBase as P, tryCatchAsync as Q, sendMfa as R, getAuthTokenAsync as S, readFdToken as T, getErrorMessage as U, validateToken as V, isError as W, success as X, mapResult as Y, tryCatch as Z, describeCredentialSource as _, INPUTS_UNDECLARED_CODE as a, walkCommands as at, getActiveProfile as b, inputsModeActive as c, setActiveSnapshot as d, unwrapOr as et, inInternalRead as f, adoptIdentityProfile as g, declareInputs as h, INPUTS_MODE_ENV as i, visibleSubcommands as it, confirmMfa as j, FLUID_API_ERROR as k, registerInputsHook as l, withInternalReadsAsync as m, INPUTS_MISMATCH_CODE as n, rootCommand as nt, INPUTS_UNDECLARED_EXIT as o, describeCommand as ot, withInternalReads as p, isSuccess as q, INPUTS_MISMATCH_EXIT as r, visibleOptions as rt, exitOnInputsError as s, INPUTS_EXPECT_ENV as t, filterCatalog as tt, createInputsReader as u, findIdentityFallbackCandidates as v, listProfileNames as w, getAuthToken as x, findIdentityFallbackProfile as y, signup as z };
1601
1638
 
1602
- //# sourceMappingURL=hook-B8HtLI5q.mjs.map
1639
+ //# sourceMappingURL=hook-C37dIffA.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-C37dIffA.mjs","names":["commandPath","pkg.version"],"sources":["../src/catalog/annotations.ts","../src/catalog/walk.ts","../package.json","../src/auth/client-headers.ts","../src/utils/result.ts","../src/auth/fluid-api.ts","../src/config/project-config.ts","../src/auth/token.ts","../src/inputs/declare.ts","../src/inputs/scope.ts","../src/inputs/paths.ts","../src/inputs/tree.ts","../src/inputs/snapshot.ts","../src/inputs/reader.ts","../src/inputs/hook.ts"],"sourcesContent":["/**\n * What a command does to the API, for the command catalog.\n *\n * Commander has nowhere to keep this, so it rides on the command object\n * under a registered symbol. A plugin installed with its own copy of\n * @fluid-app/fluid-cli still writes to the same key the running CLI reads,\n * which a module-scoped WeakMap would not.\n */\n\nimport type { Command } from \"commander\";\n\nexport interface CommandEndpoint {\n readonly method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n /** Path as the API documents it, e.g. `/api/domains/{id}`. */\n readonly path: string;\n}\n\nexport interface CommandAnnotation {\n /** The endpoints the command calls. */\n readonly endpoints?: readonly CommandEndpoint[];\n /** Whether the command changes data. */\n readonly writes?: boolean;\n}\n\nconst ANNOTATION = Symbol.for(\"@fluid-app/fluid-cli.command-annotation\");\n\ntype Annotated = Command & { [ANNOTATION]?: CommandAnnotation };\n\n/**\n * Record the endpoints a command calls and whether it writes, so\n * `fluid commands --json` can list them. Returns the command for chaining.\n */\nexport function describeCommand<T extends Command>(\n command: T,\n annotation: CommandAnnotation,\n): T {\n const target = command as T & Annotated;\n target[ANNOTATION] = { ...target[ANNOTATION], ...annotation };\n return command;\n}\n\nexport function readAnnotation(command: Command): CommandAnnotation | null {\n return (command as Annotated)[ANNOTATION] ?? null;\n}\n","/**\n * Walk the loaded command tree into a plain catalog: every command, its\n * arguments and flags, and what it does to the API. `fluid commands` prints\n * it and shell completion reads the same tree, so neither can drift from\n * the commands a user actually has installed.\n */\n\nimport type { Argument, Command, Option } from \"commander\";\nimport { readAnnotation, type CommandEndpoint } from \"./annotations.js\";\n\nexport interface CatalogOption {\n readonly flags: string;\n readonly long: string | null;\n readonly short: string | null;\n readonly description: string;\n /** `<value>` must follow the flag. */\n readonly takesValue: boolean;\n /** `[value]` may follow the flag. */\n readonly optionalValue: boolean;\n /** The command refuses to run without it. */\n readonly required: boolean;\n readonly defaultValue: unknown;\n}\n\nexport interface CatalogArgument {\n readonly name: string;\n readonly description: string;\n readonly required: boolean;\n readonly variadic: boolean;\n}\n\nexport interface CatalogEntry {\n /** Full invocation, e.g. `fluid domains add`. */\n readonly command: string;\n readonly path: readonly string[];\n readonly description: string;\n readonly aliases: readonly string[];\n readonly arguments: readonly CatalogArgument[];\n readonly options: readonly CatalogOption[];\n /** Ancestors whose flags this command also accepts, e.g. `fluid admin`'s `--token`. */\n readonly inheritsOptionsFrom: readonly string[];\n readonly subcommands: readonly string[];\n /** False for a group that only holds subcommands. */\n readonly runnable: boolean;\n /** True or false when the plugin says so or the command takes `--yes`; null when unknown. */\n readonly writes: boolean | null;\n /** The endpoints the plugin declared; null when it declared none, which means unknown, not none. */\n readonly endpoints: readonly CommandEndpoint[] | null;\n}\n\n// Commander keeps these two private; they have been stable since v7.\ntype CommandInternals = { _hidden?: boolean; _actionHandler?: unknown };\n\nexport function isHidden(command: Command): boolean {\n return (command as unknown as CommandInternals)._hidden === true;\n}\n\nfunction isRunnable(command: Command): boolean {\n return (command as unknown as CommandInternals)._actionHandler != null;\n}\n\nexport function visibleSubcommands(command: Command): Command[] {\n return command.commands.filter((sub) => !isHidden(sub));\n}\n\nexport function visibleOptions(command: Command): Option[] {\n return command.options.filter((option) => !option.hidden);\n}\n\nfunction describeOption(option: Option): CatalogOption {\n return {\n flags: option.flags,\n long: option.long ?? null,\n short: option.short ?? null,\n description: option.description,\n takesValue: option.required,\n optionalValue: option.optional,\n required: option.mandatory,\n defaultValue: option.defaultValue,\n };\n}\n\nfunction describeArgument(argument: Argument): CatalogArgument {\n return {\n name: argument.name(),\n description: argument.description,\n required: argument.required,\n variadic: argument.variadic,\n };\n}\n\nfunction inferWrites(command: Command, declared: boolean | undefined) {\n if (declared !== undefined) return declared;\n // Commands that change live data confirm with --yes across the plugins.\n return command.options.some((option) => option.long === \"--yes\")\n ? true\n : null;\n}\n\nexport function walkCommands(root: Command): CatalogEntry[] {\n const entries: CatalogEntry[] = [];\n\n function visit(command: Command, path: string[], ancestors: Command[]) {\n const annotation = readAnnotation(command);\n const subcommands = visibleSubcommands(command);\n entries.push({\n command: path.join(\" \"),\n path,\n description: command.description(),\n aliases: command.aliases(),\n arguments: command.registeredArguments.map(describeArgument),\n options: visibleOptions(command).map(describeOption),\n inheritsOptionsFrom: ancestors\n .filter((ancestor) =>\n // The program's --version is not a flag a subcommand takes.\n visibleOptions(ancestor).some(\n (option) => option.long !== \"--version\",\n ),\n )\n .map((ancestor) => commandPath(ancestor).join(\" \")),\n subcommands: subcommands.map((sub) => sub.name()),\n runnable: isRunnable(command),\n writes: inferWrites(command, annotation?.writes),\n endpoints: annotation?.endpoints ?? null,\n });\n for (const sub of subcommands) {\n visit(sub, [...path, sub.name()], [...ancestors, command]);\n }\n }\n\n visit(root, [root.name()], []);\n return entries;\n}\n\nexport function rootCommand(command: Command): Command {\n let root = command;\n while (root.parent) root = root.parent;\n return root;\n}\n\nexport function commandPath(command: Command): string[] {\n const path: string[] = [];\n for (let c: Command | null = command; c; c = c.parent) {\n path.unshift(c.name());\n }\n return path;\n}\n\n/** Keep the entries at or under `prefix`, matching names or aliases. */\nexport function filterCatalog(\n entries: readonly CatalogEntry[],\n root: Command,\n prefix: readonly string[],\n): CatalogEntry[] {\n let target = root;\n for (const word of prefix) {\n const next = visibleSubcommands(target).find(\n (sub) => sub.name() === word || sub.aliases().includes(word),\n );\n if (!next) return [];\n target = next;\n }\n const base = commandPath(target);\n return entries.filter((entry) =>\n base.every((word, index) => entry.path[index] === word),\n );\n}\n","","import pkg from \"../../package.json\" with { type: \"json\" };\n\nexport const CLIENT_HEADERS: Readonly<Record<string, string>> = {\n \"X-Fluid-Client\": \"cli\",\n \"X-Fluid-Client-Version\": pkg.version,\n};\n","/**\n * Result type utilities for type-safe error handling\n *\n * The Result<T, E> pattern provides a discriminated union for fallible operations,\n * enabling exhaustive handling without try/catch blocks.\n */\n\n// Result type - discriminated union for success/failure\n\nexport interface Success<T> {\n readonly success: true;\n readonly value: T;\n}\n\nexport interface Failure<E> {\n readonly success: false;\n readonly error: E;\n}\n\nexport type Result<T, E = Error> = Success<T> | Failure<E>;\n\n// Constructor functions\n\nexport function success<T>(value: T): Success<T> {\n return { success: true, value };\n}\n\nexport function failure<E>(error: E): Failure<E> {\n return { success: false, error };\n}\n\n// Type guards\n\nexport function isSuccess<T, E>(result: Result<T, E>): result is Success<T> {\n return result.success === true;\n}\n\nexport function isFailure<T, E>(result: Result<T, E>): result is Failure<E> {\n return result.success === false;\n}\n\n// Utility functions\n\nexport function tryCatch<T>(fn: () => T): Result<T, Error> {\n try {\n return success(fn());\n } catch (error) {\n return failure(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\nexport async function tryCatchAsync<T>(\n fn: () => Promise<T>,\n): Promise<Result<T, Error>> {\n try {\n return success(await fn());\n } catch (error) {\n return failure(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\nexport function unwrap<T, E>(result: Result<T, E>): T {\n if (isSuccess(result)) return result.value;\n // Always throw an Error instance so V8 attaches a stack trace and\n // `instanceof Error` checks in catch blocks work as expected.\n if (result.error instanceof Error) throw result.error;\n throw new Error(\n typeof result.error === \"object\" && result.error !== null\n ? JSON.stringify(result.error)\n : String(result.error),\n );\n}\n\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n if (isSuccess(result)) return result.value;\n return defaultValue;\n}\n\nexport function mapResult<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => U,\n): Result<U, E> {\n if (isSuccess(result)) return success(fn(result.value));\n return result;\n}\n\nexport function mapError<T, E, F>(\n result: Result<T, E>,\n fn: (error: E) => F,\n): Result<T, F> {\n if (isFailure(result)) return failure(fn(result.error));\n return result;\n}\n\n// Error narrowing utilities\n\nexport function isError(value: unknown): value is Error {\n return value instanceof Error;\n}\n\nexport function isNodeError(value: unknown): value is NodeJS.ErrnoException {\n return value instanceof Error && \"code\" in value;\n}\n\nexport function getErrorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n if (typeof error === \"string\") return error;\n return String(error);\n}\n","/**\n * Fluid API client for authentication operations, and the public signup\n * that comes before any of them\n */\n\nimport { CLIENT_HEADERS } from \"./client-headers.js\";\nimport type { CliError } from \"../utils/errors.js\";\nimport { type Result, success, failure } from \"../utils/result.js\";\n\nconst API_TIMEOUT_MS = 10_000;\n// A signup creates and sets up a company before it answers, so it gets\n// longer than a sign-in call.\nconst SIGNUP_TIMEOUT_MS = 60_000;\n\n/** Whether `base` is plain http to a host other than this machine. */\nexport function isInsecureRemoteBase(base: string): boolean {\n let url: URL;\n try {\n url = new URL(base);\n } catch {\n return false;\n }\n if (url.protocol !== \"http:\") return false;\n const host = url.hostname;\n return !(\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"[::1]\" ||\n host.endsWith(\".localhost\")\n );\n}\n\nexport const DEFAULT_FLUID_API_BASE = \"https://api.fluid.app\";\n\nexport function getFluidApiBase(): string {\n return process.env[\"FLUID_API_BASE\"] ?? DEFAULT_FLUID_API_BASE;\n}\n\nfunction makeSignal(timeoutMs: number = API_TIMEOUT_MS): {\n signal: AbortSignal;\n cleanup: () => void;\n} {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return { signal: controller.signal, cleanup: () => clearTimeout(timer) };\n}\n\nexport interface FluidApiError extends CliError {\n readonly code: string;\n readonly message: string;\n readonly details?: string;\n}\n\nexport const FLUID_API_ERROR = {\n INVALID_TOKEN: {\n code: \"INVALID_TOKEN\",\n message: \"Token is invalid or expired\",\n },\n API_UNREACHABLE: {\n code: \"API_UNREACHABLE\",\n message: \"Could not reach the Fluid API\",\n },\n // A 404 from confirm_mfa: the code confirmed but opens no company here; see\n // ConfirmMfaAction#confirm. Servers before ENG-2877 also answer an unknown\n // sign-in with it, so the message holds for both.\n SIGN_IN_UNFINISHED: {\n code: \"SIGN_IN_UNFINISHED\",\n message:\n \"This sign-in can't be finished. Check the shop and the address, then request a new code\",\n },\n // Servers before ENG-2877 answer 410 for an expired code, a used one, and\n // one locked after too many wrong attempts; current ones answer 422.\n CODE_EXPIRED: {\n code: \"CODE_EXPIRED\",\n message:\n \"Verification code has expired, was already used, or is locked after too many attempts — please request a new one\",\n },\n RATE_LIMITED: {\n code: \"RATE_LIMITED\",\n message: \"Too many sign-in requests — wait a minute and try again\",\n },\n // The server gives one answer to every code that does not confirm: an\n // unknown sign-in, a wrong code, an expired or used one, and one locked\n // after too many wrong attempts, so it never tells whether an address can\n // sign in (ENG-2877). It gives only the reasons; each login flow names its\n // own next step.\n INVALID_CODE: {\n code: \"INVALID_CODE\",\n message:\n \"Verification code is invalid, expired, already used, or locked after too many attempts\",\n },\n // A 422 naming the verification channel follows only a correct code: the\n // email or phone the code was sent to is no longer on the account, so it\n // is not a code problem and tells nothing about whether an address can\n // sign in. The code is not spent, so a caller that kept the challenge can\n // use it once the contact is back; each login flow names its own next step.\n CONTACT_MISSING: {\n code: \"CONTACT_MISSING\",\n message:\n \"The code is right, but the email or phone it was sent to is no longer on this account. Ask the company's admin to restore it\",\n },\n COMPANY_NOT_FOUND: {\n code: \"COMPANY_NOT_FOUND\",\n message: \"Company not found\",\n },\n SWITCH_FAILED: {\n code: \"SWITCH_FAILED\",\n message: \"Failed to switch company\",\n },\n LINK_GONE: {\n code: \"LINK_GONE\",\n message:\n \"This sign-in link has expired or was already used — run `fluid login` for a new one\",\n },\n} as const;\n\nfunction createApiError(\n template: { readonly code: string; readonly message: string },\n details?: string,\n): FluidApiError {\n return { code: template.code, message: template.message, details };\n}\n\nexport interface CompanyInfo {\n readonly name: string;\n}\n\nexport interface UserCompany {\n readonly id: number;\n readonly name: string;\n /** The company's `uuid_v7`, which an identity token exchange names. */\n readonly uuidV7?: string;\n}\n\nexport interface SwitchCompanyResult {\n readonly companyId: number;\n readonly companyName: string;\n readonly fluidShop: string;\n readonly jwt: string;\n}\n\nexport interface SwitchAdoptAnswer {\n readonly adoptCode: string;\n readonly companyId: number;\n}\n\nexport interface MfaResponse {\n readonly uuid: string;\n readonly expiresAt: string;\n /** \"identity\" when no code was emailed because the address signs in through the browser. */\n readonly signInPath?: \"identity\";\n /** The shop's company uuid_v7 on an `identity` answer to a request that named a shop. */\n readonly companyUuid?: string;\n}\n\nexport interface CompanyChoice {\n readonly id: number;\n readonly name: string;\n readonly shopName: string;\n readonly jwt: string;\n /** \"rep\" for an admin or rep session; \"member\" or \"customer\" for a shopper's. */\n readonly authType?: string;\n}\n\nexport interface ConfirmMfaResponse {\n readonly authType: string;\n readonly companies: CompanyChoice[];\n /**\n * `identity` when every company the code covered signs in through the\n * identity service, so Rails handed out no token for them.\n */\n readonly signInPath: \"identity\" | \"legacy\";\n /** The company (uuid_v7) the confirmed code was for, when Rails names one. */\n readonly companyUuid?: string;\n}\n\n/**\n * The shop identifiers (`fluid_shop` and `subdomain`) of the company a token\n * belongs to, from `/companies/me`. Empty when the API does not answer with\n * them, including for a rep, whom that endpoint refuses.\n */\nexport async function fetchCompanyShops(\n token: string,\n options: { readonly baseUrl?: string } = {},\n): Promise<readonly string[]> {\n const { signal, cleanup } = makeSignal();\n try {\n const response = await fetch(\n `${options.baseUrl ?? getFluidApiBase()}/api/company/v1/companies/me`,\n {\n method: \"GET\",\n headers: { ...CLIENT_HEADERS, Authorization: `Bearer ${token}` },\n signal,\n },\n );\n if (!response.ok) return [];\n const data = (await response.json()) as {\n data?: { company?: { fluid_shop?: unknown; subdomain?: unknown } };\n };\n const company = data?.data?.company;\n return [company?.fluid_shop, company?.subdomain].filter(\n (value): value is string => typeof value === \"string\" && value !== \"\",\n );\n } catch {\n return [];\n } finally {\n cleanup();\n }\n}\n\n/**\n * Validate a token against the Fluid API and return company info.\n * `baseUrl` is the API the token belongs to; it defaults to the CLI's.\n */\nexport async function validateToken(\n token: string,\n options: { readonly baseUrl?: string } = {},\n): Promise<Result<CompanyInfo, FluidApiError>> {\n const { signal, cleanup } = makeSignal();\n const apiBase = options.baseUrl ?? getFluidApiBase();\n try {\n const response = await fetch(`${apiBase}/api/company/v1/companies/me`, {\n method: \"GET\",\n headers: {\n ...CLIENT_HEADERS,\n Authorization: `Bearer ${token}`,\n },\n signal,\n });\n\n if (response.ok) {\n const data = (await response.json()) as {\n data?: { company?: { name?: string } };\n };\n const name = data?.data?.company?.name;\n if (!name) {\n return failure(\n createApiError(\n FLUID_API_ERROR.API_UNREACHABLE,\n \"Unexpected response shape from /companies/me\",\n ),\n );\n }\n return success({ name });\n }\n\n // `/companies/me` serves admins only and refuses a rep's valid login\n // with a 403, so ask `/api/me`, which answers for both, before calling\n // the token invalid.\n if (response.status === 403) {\n return await staffCompanyFromMe(token, apiBase, signal);\n }\n\n if (response.status === 401) {\n return failure(\n createApiError(\n FLUID_API_ERROR.INVALID_TOKEN,\n `HTTP ${response.status}: Check that your token is valid and non-expired.`,\n ),\n );\n }\n\n const body = await response.text();\n return failure(\n createApiError(\n FLUID_API_ERROR.API_UNREACHABLE,\n `HTTP ${response.status}: ${body}`,\n ),\n );\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));\n } finally {\n cleanup();\n }\n}\n\n/** The roles a CLI login may hold, as `/api/v2026-10/me` names them. */\nconst STAFF_ROLES = new Set([\"admin\", \"rep\"]);\n\n/**\n * The company of an admin's or a rep's login, from `/api/v2026-10/me`.\n * Falls back to `/api/me` on 403 so valid company-restricted staff sessions\n * (which `/api/v2026-10/me` refuses) remain usable while keeping the same\n * staff-role allowlist. Any other refusal, or a customer token, is invalid for\n * the CLI; any other failure, or an answer with no company name, leaves the API\n * unreachable, as `/companies/me` does.\n */\nasync function staffCompanyFromMe(\n token: string,\n apiBase: string,\n signal: AbortSignal,\n): Promise<Result<CompanyInfo, FluidApiError>> {\n const response = await fetch(\n `${apiBase}/api/v2026-10/me?include=membership.details,company`,\n {\n method: \"GET\",\n headers: { ...CLIENT_HEADERS, Authorization: `Bearer ${token}` },\n signal,\n },\n );\n if (response.status === 403) {\n return staffCompanyFromLegacyMe(token, apiBase, signal);\n }\n if (response.status === 401) {\n return failure(\n createApiError(\n FLUID_API_ERROR.INVALID_TOKEN,\n `HTTP ${response.status}: Check that your token is valid and non-expired.`,\n ),\n );\n }\n if (!response.ok) {\n const body = await response.text();\n return failure(\n createApiError(\n FLUID_API_ERROR.API_UNREACHABLE,\n `HTTP ${response.status} from /api/v2026-10/me: ${body}`,\n ),\n );\n }\n const body = (await response.json()) as {\n data?: {\n membership?: { role?: unknown };\n company?: { name?: unknown };\n };\n };\n return parseStaffCompany(\n body.data?.membership?.role,\n body.data?.company?.name,\n \"/api/v2026-10/me\",\n );\n}\n\nasync function staffCompanyFromLegacyMe(\n token: string,\n apiBase: string,\n signal: AbortSignal,\n): Promise<Result<CompanyInfo, FluidApiError>> {\n const response = await fetch(`${apiBase}/api/me`, {\n method: \"GET\",\n headers: { ...CLIENT_HEADERS, Authorization: `Bearer ${token}` },\n signal,\n });\n if (response.status === 401 || response.status === 403) {\n return failure(\n createApiError(\n FLUID_API_ERROR.INVALID_TOKEN,\n `HTTP ${response.status}: Check that your token is valid and non-expired.`,\n ),\n );\n }\n if (!response.ok) {\n const body = await response.text();\n return failure(\n createApiError(\n FLUID_API_ERROR.API_UNREACHABLE,\n `HTTP ${response.status} from /api/me: ${body}`,\n ),\n );\n }\n const data = (await response.json()) as {\n role?: unknown;\n company?: { name?: unknown };\n };\n return parseStaffCompany(data?.role, data?.company?.name, \"/api/me\");\n}\n\nfunction parseStaffCompany(\n role: unknown,\n name: unknown,\n endpoint: string,\n): Result<CompanyInfo, FluidApiError> {\n if (typeof role !== \"string\" || !STAFF_ROLES.has(role)) {\n return failure(\n createApiError(\n FLUID_API_ERROR.INVALID_TOKEN,\n \"This login is not an admin's or a rep's, so it cannot be used with the CLI.\",\n ),\n );\n }\n if (typeof name !== \"string\" || name === \"\") {\n return failure(\n createApiError(\n FLUID_API_ERROR.API_UNREACHABLE,\n `Unexpected response shape from ${endpoint}`,\n ),\n );\n }\n return success({ name });\n}\n\n/**\n * Send a multi-factor authentication code to the given email address.\n * The API answers 201 whether or not the address can sign in\n * (anti-enumeration).\n *\n * With `fluidShop`, the server ties the code to the person's membership in\n * that company, so redeeming it signs in to that company alone and, for an\n * admin's emailed code, confirms a new signup.\n */\nexport async function sendMfa(\n email: string,\n options: {\n readonly fluidShop?: string;\n readonly identityHint?: boolean;\n } = {},\n): Promise<Result<MfaResponse, FluidApiError>> {\n const { signal, cleanup } = makeSignal();\n try {\n const response = await fetch(\n `${getFluidApiBase()}/api/authentication/send_mfa`,\n {\n method: \"POST\",\n headers: { ...CLIENT_HEADERS, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n email,\n ...(options.fluidShop ? { fluid_shop: options.fluidShop } : {}),\n ...(options.identityHint ? { identity_hint_supported: \"true\" } : {}),\n }),\n signal,\n },\n );\n\n if (response.status === 201) {\n const data = (await response.json()) as {\n sign_in_path?: string;\n company_uuid?: unknown;\n multi_factor_authentication?: {\n uuid?: string;\n verification_code_expires_at?: string;\n };\n };\n const uuid = data.multi_factor_authentication?.uuid;\n const expiresAt =\n data.multi_factor_authentication?.verification_code_expires_at;\n if (!uuid || !expiresAt) {\n return failure(\n createApiError(\n FLUID_API_ERROR.API_UNREACHABLE,\n \"Unexpected response shape from /send_mfa\",\n ),\n );\n }\n return success(\n data.sign_in_path === \"identity\"\n ? {\n uuid,\n expiresAt,\n signInPath: \"identity\",\n ...(typeof data.company_uuid === \"string\" && data.company_uuid\n ? { companyUuid: data.company_uuid }\n : {}),\n }\n : { uuid, expiresAt },\n );\n }\n\n const body = await response.text();\n if (response.status === 429) {\n return failure(\n createApiError(FLUID_API_ERROR.RATE_LIMITED, `HTTP 429: ${body}`),\n );\n }\n return failure(\n createApiError(\n FLUID_API_ERROR.API_UNREACHABLE,\n `HTTP ${response.status}: ${body}`,\n ),\n );\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));\n } finally {\n cleanup();\n }\n}\n\n/**\n * Confirm a multi-factor authentication code and retrieve company JWTs.\n *\n * `baseUrl` is the API the code was sent from; a sign-in finished in a\n * later process passes the one it saved, not the current environment's.\n */\nexport async function confirmMfa(\n uuid: string,\n code: string,\n options: { readonly fluidShop?: string; readonly baseUrl?: string } = {},\n): Promise<Result<ConfirmMfaResponse, FluidApiError>> {\n const { signal, cleanup } = makeSignal();\n const apiBase = options.baseUrl ?? getFluidApiBase();\n try {\n const response = await fetch(`${apiBase}/api/authentication/confirm_mfa`, {\n method: \"POST\",\n headers: { ...CLIENT_HEADERS, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n uuid,\n multi_factor_authentication: { verification_code: code },\n ...(options.fluidShop ? { fluid_shop: options.fluidShop } : {}),\n }),\n signal,\n });\n\n if (response.ok) {\n const data = (await response.json()) as {\n authenticated?: boolean;\n auth_type?: string;\n sign_in_path?: string;\n company_uuid?: unknown;\n companies?:\n | {\n id: number;\n name: string;\n shop_name: string;\n jwt: string;\n auth_type?: string | null;\n }[]\n | null;\n };\n if (!data.authenticated) {\n return failure(\n createApiError(\n FLUID_API_ERROR.INVALID_CODE,\n \"Authentication was not confirmed by the server\",\n ),\n );\n }\n const companies = Array.isArray(data.companies) ? data.companies : [];\n return success({\n authType: data.auth_type ?? \"\",\n companies: companies.map((c) => ({\n id: c.id,\n name: c.name,\n shopName: c.shop_name,\n jwt: c.jwt,\n ...(c.auth_type ? { authType: c.auth_type } : {}),\n })),\n signInPath: data.sign_in_path === \"identity\" ? \"identity\" : \"legacy\",\n ...(typeof data.company_uuid === \"string\" && data.company_uuid\n ? { companyUuid: data.company_uuid }\n : {}),\n });\n }\n\n if (response.status === 404) {\n return failure(createApiError(FLUID_API_ERROR.SIGN_IN_UNFINISHED));\n }\n if (response.status === 410) {\n return failure(createApiError(FLUID_API_ERROR.CODE_EXPIRED));\n }\n const body = await response.text();\n if (response.status === 422) {\n return failure(\n createApiError(\n namesVerificationChannel(body)\n ? FLUID_API_ERROR.CONTACT_MISSING\n : FLUID_API_ERROR.INVALID_CODE,\n ),\n );\n }\n if (response.status === 429) {\n return failure(\n createApiError(FLUID_API_ERROR.RATE_LIMITED, `HTTP 429: ${body}`),\n );\n }\n return failure(\n createApiError(\n FLUID_API_ERROR.API_UNREACHABLE,\n `HTTP ${response.status}: ${body}`,\n ),\n );\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));\n } finally {\n cleanup();\n }\n}\n\nexport interface IdentityLinkRedemption {\n /** Always `identity`: only a flagged company's sign-in emails a link. */\n readonly signInPath: \"identity\";\n readonly fluidShop: string;\n /** The company's uuid_v7: the identity sign-in must land in it. */\n readonly companyUuid: string;\n}\n\n/**\n * Redeem the single-use token in an identity sign-in email, the email a\n * person whose company signs in through the identity service receives\n * instead of a code. Rails answers 410 for a forged, expired, or used link.\n */\nexport async function redeemIdentityLink(\n token: string,\n options: { readonly baseUrl?: string } = {},\n): Promise<Result<IdentityLinkRedemption, FluidApiError>> {\n const { signal, cleanup } = makeSignal();\n try {\n const response = await fetch(\n `${options.baseUrl ?? getFluidApiBase()}/api/v2026-10/single-sign-ons/identity-link-redemptions`,\n {\n method: \"POST\",\n headers: { ...CLIENT_HEADERS, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ token }),\n signal,\n },\n );\n\n if (response.ok) {\n const data = (await response.json()) as {\n sign_in_path?: string;\n fluid_shop?: string;\n company_uuid?: string;\n };\n if (\n data.sign_in_path !== \"identity\" ||\n !data.fluid_shop ||\n typeof data.company_uuid !== \"string\" ||\n !data.company_uuid\n ) {\n return failure(\n createApiError(\n FLUID_API_ERROR.API_UNREACHABLE,\n \"Unexpected response shape from /identity-link-redemptions\",\n ),\n );\n }\n return success({\n signInPath: \"identity\",\n fluidShop: data.fluid_shop,\n companyUuid: data.company_uuid,\n });\n }\n\n if (response.status === 410 || response.status === 404) {\n return failure(createApiError(FLUID_API_ERROR.LINK_GONE));\n }\n\n const body = await response.text();\n return failure(\n createApiError(\n FLUID_API_ERROR.API_UNREACHABLE,\n `HTTP ${response.status}: ${body}`,\n ),\n );\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));\n } finally {\n cleanup();\n }\n}\n\n/**\n * Fetch all companies the authenticated user has access to.\n */\nexport async function fetchUserCompanies(\n token: string,\n baseUrl?: string,\n): Promise<Result<UserCompany[], FluidApiError>> {\n const { signal, cleanup } = makeSignal();\n const apiBase = baseUrl ?? getFluidApiBase();\n try {\n const response = await fetch(\n `${apiBase}/api/v2026-10/me?include=companies,legacy_ids`,\n {\n method: \"GET\",\n headers: { ...CLIENT_HEADERS, Authorization: `Bearer ${token}` },\n signal,\n },\n );\n\n if (response.ok) {\n const body = (await response.json()) as {\n data?: {\n companies?: { id?: string; legacy_id: number; name: string }[];\n };\n };\n const companies = Array.isArray(body.data?.companies)\n ? body.data.companies\n : [];\n return success(\n companies\n .filter((c) => typeof c.legacy_id === \"number\")\n .map((c) => ({\n id: c.legacy_id,\n name: c.name,\n ...(typeof c.id === \"string\" ? { uuidV7: c.id } : {}),\n })),\n );\n }\n\n if (response.status === 401 || response.status === 403) {\n return failure(\n createApiError(\n FLUID_API_ERROR.INVALID_TOKEN,\n `HTTP ${response.status}`,\n ),\n );\n }\n\n const body = await response.text();\n return failure(\n createApiError(\n FLUID_API_ERROR.API_UNREACHABLE,\n `HTTP ${response.status}: ${body}`,\n ),\n );\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));\n } finally {\n cleanup();\n }\n}\n\n/**\n * Switch to a different company and receive a new JWT.\n *\n * Response shape (from @fluid-app/auth SwitchCompanyResponse):\n * { company: { id, name, fluid_shop, jwt }, meta: { request_id, timestamp } }\n */\nexport async function switchCompany(\n token: string,\n companyId: number,\n baseUrl?: string,\n adoptChallenge?: string,\n): Promise<Result<SwitchCompanyResult | SwitchAdoptAnswer, FluidApiError>> {\n const { signal, cleanup } = makeSignal();\n const apiBase = baseUrl ?? getFluidApiBase();\n try {\n const response = await fetch(\n `${apiBase}/api/authentication/company/${companyId}/switch`,\n {\n method: \"PUT\",\n headers: {\n ...CLIENT_HEADERS,\n Authorization: `Bearer ${token}`,\n \"Content-Type\": \"application/json\",\n ...(adoptChallenge ? { \"X-Fluid-Switch\": \"adopt\" } : {}),\n },\n ...(adoptChallenge\n ? {\n body: JSON.stringify({\n adopt: {\n code_challenge: adoptChallenge,\n code_challenge_method: \"S256\",\n },\n }),\n }\n : {}),\n signal,\n },\n );\n\n if (response.ok) {\n const data = (await response.json()) as {\n company?: {\n id: number;\n name: string;\n fluid_shop: string;\n jwt: string;\n };\n adopt?: { code?: unknown; company_id?: unknown };\n };\n const company = data.company;\n const adopt = adoptChallenge && !company ? data.adopt : undefined;\n if (\n typeof adopt?.code === \"string\" &&\n adopt.code &&\n typeof adopt.company_id === \"number\"\n ) {\n return success({ adoptCode: adopt.code, companyId: adopt.company_id });\n }\n if (!company?.jwt) {\n return failure(\n createApiError(\n FLUID_API_ERROR.SWITCH_FAILED,\n \"Unexpected response shape from /switch\",\n ),\n );\n }\n return success({\n companyId: company.id,\n companyName: company.name,\n fluidShop: company.fluid_shop,\n jwt: company.jwt,\n });\n }\n\n if (response.status === 404) {\n return failure(\n createApiError(\n FLUID_API_ERROR.COMPANY_NOT_FOUND,\n `Company ${companyId} not found`,\n ),\n );\n }\n\n if (response.status === 401 || response.status === 403) {\n return failure(\n createApiError(\n FLUID_API_ERROR.INVALID_TOKEN,\n `HTTP ${response.status}`,\n ),\n );\n }\n\n const body = await response.text();\n return failure(\n createApiError(\n FLUID_API_ERROR.SWITCH_FAILED,\n `HTTP ${response.status}: ${body}`,\n ),\n );\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));\n } finally {\n cleanup();\n }\n}\n\nexport interface SignupRequest {\n readonly firstName: string;\n readonly lastName: string;\n readonly email: string;\n readonly companyName: string;\n /** Already in the server's form (see `normaliseSubdomain`). */\n readonly subdomain: string;\n readonly color?: string;\n /** Asks Fluid for a credential the new company's admin can approve for an agent. */\n readonly agentAccess?: { readonly name: string };\n}\n\n/** The agent-access request a signup opened. */\nexport interface AgentAccessRequestHandle {\n /** The poll credential; never printed or logged. */\n readonly handle: string;\n readonly approvalUrl: string;\n readonly expiresAt: string;\n /** The company's `uuid_v7`, the organization its client is registered for. */\n readonly companyUuid: string;\n}\n\nexport interface SignupResponse {\n readonly company: {\n readonly id: number;\n readonly name: string;\n readonly subdomain: string;\n readonly fluidShop: string;\n };\n readonly userCompany: { readonly id: number; readonly email: string };\n /** What the person still has to do, such as \"email_confirmation\". New values may appear. */\n readonly currentlyDue: readonly string[];\n /** Present only while Fluid has agent access enabled. */\n readonly agentAccess?: AgentAccessRequestHandle;\n}\n\n/** A signup that was refused or went unanswered. */\nexport interface SignupError extends CliError {\n /** The HTTP status, when the server answered. */\n readonly status?: number;\n /**\n * A 422 body's `errors`: keyed by record and then field (`company.subdomain`),\n * or by `base` alone for a request refused before any record was built.\n */\n readonly errors?: Record<string, unknown>;\n /** Seconds until the rate-limit window resets, on a 429. */\n readonly retryAfter?: number;\n}\n\nexport const SIGNUP_ERROR = {\n SUBDOMAIN_TAKEN: {\n code: \"SUBDOMAIN_TAKEN\",\n message:\n \"That subdomain belongs to another company. Pick another, unless an earlier signup of yours sent it: then the company exists, so sign in instead.\",\n },\n // The server answers `company.base` both for a setup failure that rolled\n // the company back and for an error raised after it was saved, and the\n // body does not say which, so this assumes the company may exist.\n SIGNUP_MAY_EXIST: {\n code: \"SIGNUP_MAY_EXIST\",\n message:\n \"The signup failed, and the company may still have been created. Run the same command once more with the same subdomain: if it then says the subdomain is taken, the company exists, so sign in instead.\",\n },\n SIGNUP_INVALID: {\n code: \"SIGNUP_INVALID\",\n message: \"Fluid rejected the signup. See errors for each field.\",\n },\n RATE_LIMITED: {\n code: \"RATE_LIMITED\",\n message:\n \"Too many signups from this address or for this email. Failed attempts count too, so wait out the retry time before trying again.\",\n },\n SIGNUP_FORBIDDEN: {\n code: \"SIGNUP_FORBIDDEN\",\n message: \"Fluid refused this signup. Don't retry; contact Fluid support.\",\n },\n SIGNUP_OUTCOME_UNKNOWN: {\n code: \"SIGNUP_OUTCOME_UNKNOWN\",\n message:\n \"No usable answer from Fluid, so the company may or may not have been created. Check before retrying: sign in, or run the same command once more and read a 'subdomain is taken' as created.\",\n },\n} as const;\n\nfunction signupError(\n template: { readonly code: string; readonly message: string },\n extra: Omit<SignupError, \"code\" | \"message\"> = {},\n): SignupError {\n return { code: template.code, message: template.message, ...extra };\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** Whether a confirm 422 body names the verification channel. */\nfunction namesVerificationChannel(body: string): boolean {\n try {\n const errors = asRecord(asRecord(JSON.parse(body))?.errors);\n return (\n errors !== undefined &&\n fieldMessages(\n errors,\n \"multi_factor_authentication\",\n \"verification_channel\",\n ).length > 0\n );\n } catch {\n return false;\n }\n}\n\nfunction fieldMessages(\n errors: Record<string, unknown>,\n record: string,\n field: string,\n): string[] {\n const messages = asRecord(errors[record])?.[field];\n return Array.isArray(messages)\n ? messages.filter((m): m is string => typeof m === \"string\")\n : [];\n}\n\nfunction signupRejection(body: unknown): SignupError {\n const errors = asRecord(asRecord(body)?.[\"errors\"]) ?? {};\n // \"is taken\" from the pre-check, \"has already been taken\" from the\n // model's uniqueness validation.\n if (\n fieldMessages(errors, \"company\", \"subdomain\").some((m) =>\n m.includes(\"taken\"),\n )\n ) {\n return signupError(SIGNUP_ERROR.SUBDOMAIN_TAKEN, { status: 422, errors });\n }\n if (fieldMessages(errors, \"company\", \"base\").length > 0) {\n return signupError(SIGNUP_ERROR.SIGNUP_MAY_EXIST, { status: 422, errors });\n }\n return signupError(SIGNUP_ERROR.SIGNUP_INVALID, { status: 422, errors });\n}\n\nfunction readSignup(body: unknown): SignupResponse | undefined {\n const root = asRecord(body);\n const company = asRecord(root?.[\"company\"]);\n const userCompany = asRecord(root?.[\"user_company\"]);\n const due = asRecord(root?.[\"requirements\"])?.[\"currently_due\"];\n if (\n typeof company?.[\"id\"] !== \"number\" ||\n typeof company[\"fluid_shop\"] !== \"string\" ||\n typeof userCompany?.[\"id\"] !== \"number\"\n ) {\n return undefined;\n }\n const agent = readAgentAccess(root?.[\"agent_access\"]);\n return {\n company: {\n id: company[\"id\"],\n name: String(company[\"name\"] ?? \"\"),\n subdomain: String(company[\"subdomain\"] ?? \"\"),\n fluidShop: company[\"fluid_shop\"],\n },\n userCompany: {\n id: userCompany[\"id\"],\n email: String(userCompany[\"email\"] ?? \"\"),\n },\n currentlyDue: Array.isArray(due)\n ? due.filter((d): d is string => typeof d === \"string\")\n : [],\n ...(agent ? { agentAccess: agent } : {}),\n };\n}\n\nfunction readAgentAccess(value: unknown): AgentAccessRequestHandle | undefined {\n const agent = asRecord(value);\n const handle = agent?.[\"handle\"];\n const approvalUrl = agent?.[\"approval_url\"];\n const expiresAt = agent?.[\"expires_at\"];\n const companyUuid = agent?.[\"company_uuid\"];\n if (\n typeof handle !== \"string\" ||\n typeof approvalUrl !== \"string\" ||\n typeof expiresAt !== \"string\" ||\n typeof companyUuid !== \"string\" ||\n !handle\n ) {\n return undefined;\n }\n return { handle, approvalUrl, expiresAt, companyUuid };\n}\n\nasync function readJson(response: Response): Promise<unknown> {\n try {\n return await response.json();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Sign up a new company with the public, unauthenticated `POST /api/company`.\n *\n * Sends exactly one request and never retries it: a 422 can follow a saved\n * company, and every attempt, failed or not, counts toward the per-IP and\n * per-email signup limits.\n */\nexport async function signup(\n request: SignupRequest,\n): Promise<Result<SignupResponse, SignupError>> {\n const { signal, cleanup } = makeSignal(SIGNUP_TIMEOUT_MS);\n try {\n const response = await fetch(`${getFluidApiBase()}/api/company`, {\n method: \"POST\",\n headers: { ...CLIENT_HEADERS, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n user: {\n first_name: request.firstName,\n last_name: request.lastName,\n email: request.email,\n },\n company: {\n name: request.companyName,\n subdomain: request.subdomain,\n ...(request.color ? { color: request.color } : {}),\n },\n ...(request.agentAccess\n ? { agent_access: { name: request.agentAccess.name } }\n : {}),\n }),\n signal,\n });\n const body = await readJson(response);\n\n if (response.status === 200) {\n const created = readSignup(body);\n return created\n ? success(created)\n : failure(\n signupError(SIGNUP_ERROR.SIGNUP_OUTCOME_UNKNOWN, {\n status: 200,\n details: \"Unexpected response shape from POST /api/company\",\n }),\n );\n }\n if (response.status === 422) return failure(signupRejection(body));\n if (response.status === 429) {\n const retryAfter = asRecord(body)?.[\"retry_after\"];\n return failure(\n signupError(SIGNUP_ERROR.RATE_LIMITED, {\n status: 429,\n ...(typeof retryAfter === \"number\" ? { retryAfter } : {}),\n }),\n );\n }\n if (response.status === 403) {\n return failure(\n signupError(SIGNUP_ERROR.SIGNUP_FORBIDDEN, { status: 403 }),\n );\n }\n return failure(\n signupError(SIGNUP_ERROR.SIGNUP_OUTCOME_UNKNOWN, {\n status: response.status,\n details: `HTTP ${response.status}`,\n }),\n );\n } catch (err) {\n // A timeout or a dropped connection can come after the server saved the\n // company, so this is never reported as \"not created\".\n const message = err instanceof Error ? err.message : String(err);\n return failure(\n signupError(SIGNUP_ERROR.SIGNUP_OUTCOME_UNKNOWN, { details: message }),\n );\n } finally {\n cleanup();\n }\n}\n\n/** One answer to an agent-access poll. */\nexport type AgentAccessPoll =\n | { readonly state: \"pending\" | \"issuing_soon\"; readonly retryAfter?: number }\n | {\n readonly state: \"delivered\";\n readonly clientId: string;\n readonly clientSecret: string;\n }\n | { readonly state: \"denied\" | \"expired\" | \"revoked\" | \"unavailable\" }\n | { readonly state: \"slow_down\"; readonly retryAfter: number }\n | { readonly state: \"retry\"; readonly retryAfter?: number };\n\nfunction retryAfterSeconds(response: Response): number | undefined {\n const value = Number(response.headers.get(\"Retry-After\"));\n return Number.isFinite(value) && value > 0 ? value : undefined;\n}\n\n/**\n * Asks once for the outcome of an agent-access request. The handle goes in\n * the POST body only: Fluid treats one in the URL as leaked and expires the\n * request. Anything unclear or transient comes back as `retry`; a 404 or a\n * 409 means the request cannot succeed.\n */\nexport async function pollAgentAccess(\n handle: string,\n): Promise<AgentAccessPoll> {\n const { signal, cleanup } = makeSignal();\n try {\n const response = await fetch(\n `${getFluidApiBase()}/api/agent-access/v1/poll`,\n {\n method: \"POST\",\n headers: { ...CLIENT_HEADERS, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ handle }),\n redirect: \"error\",\n signal,\n },\n );\n const retryAfter = retryAfterSeconds(response);\n const body = asRecord(await readJson(response));\n const status = body?.[\"status\"];\n if (response.status === 429) {\n return { state: \"slow_down\", retryAfter: retryAfter ?? 5 };\n }\n if (response.status === 503 && status === \"unavailable\") {\n return { state: \"slow_down\", retryAfter: retryAfter ?? 60 };\n }\n if (response.status === 404 || response.status === 409) {\n return { state: \"unavailable\" };\n }\n if (response.status === 200) {\n if (status === \"pending\" || status === \"issuing_soon\") {\n return { state: status, ...(retryAfter ? { retryAfter } : {}) };\n }\n if (status === \"denied\" || status === \"expired\" || status === \"revoked\") {\n return { state: status };\n }\n const clientId = body?.[\"client_id\"];\n const clientSecret = body?.[\"client_secret\"];\n if (\n status === \"delivered\" &&\n typeof clientId === \"string\" &&\n typeof clientSecret === \"string\" &&\n clientId &&\n clientSecret\n ) {\n return { state: \"delivered\", clientId, clientSecret };\n }\n }\n return { state: \"retry\", ...(retryAfter ? { retryAfter } : {}) };\n } catch {\n return { state: \"retry\" };\n } finally {\n cleanup();\n }\n}\n","/**\n * Project-level config (.fluidrc) reader.\n *\n * Walks upward from a starting directory to find a `.fluidrc` file.\n * The file is JSON with a `profile` field that maps to a profile name\n * in `~/.fluid/config.json`.\n *\n * This allows portal repos to pin themselves to a specific CLI profile\n * so that `fluid portal pull` / `push` always use the correct company\n * credentials, regardless of which profile is globally active.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nexport interface ProjectRcConfig {\n readonly profile: string;\n}\n\nconst RC_FILENAME = \".fluidrc\";\n\n/** Cached result keyed by the starting directory. */\nlet cachedResult: { dir: string; config: ProjectRcConfig | null } | undefined;\n\n/**\n * Walk upward from `startDir` looking for a `.fluidrc` file.\n *\n * Returns the parsed config when found, or `null` if no valid `.fluidrc`\n * exists in any ancestor directory.\n *\n * The result is cached per starting directory for the lifetime of the\n * process — CLI commands are short-lived so stale-cache is not a concern.\n */\nexport function findProjectConfig(startDir: string): ProjectRcConfig | null {\n if (cachedResult && cachedResult.dir === startDir) {\n return cachedResult.config;\n }\n\n let dir = startDir;\n while (true) {\n const rcPath = join(dir, RC_FILENAME);\n if (existsSync(rcPath)) {\n try {\n const raw = readFileSync(rcPath, \"utf8\");\n const parsed = JSON.parse(raw) as Partial<ProjectRcConfig>;\n if (typeof parsed.profile === \"string\" && parsed.profile.length > 0) {\n const config: ProjectRcConfig = { profile: parsed.profile };\n cachedResult = { dir: startDir, config };\n return config;\n }\n } catch {\n // Malformed .fluidrc — treat as absent\n }\n\n // Found a .fluidrc but it was invalid or empty — stop searching\n // upward to avoid confusing inheritance from a parent directory.\n cachedResult = { dir: startDir, config: null };\n return null;\n }\n\n const parent = dirname(dir);\n if (parent === dir) break; // reached filesystem root\n dir = parent;\n }\n\n cachedResult = { dir: startDir, config: null };\n return null;\n}\n\n/** Reset the cache. Exposed for tests only. */\nexport function _resetProjectConfigCache(): void {\n cachedResult = undefined;\n}\n","/**\n * Token storage and retrieval from config\n */\n\nimport { createHash } from \"node:crypto\";\nimport { closeSync, readSync } from \"node:fs\";\nimport { Socket } from \"node:net\";\nimport {\n exchangeNativeToken,\n SessionError,\n type ExchangedToken,\n} from \"@fluid-app/auth/native\";\nimport {\n IDENTITY_CLIENT_ID,\n resolveIdentityUrl,\n} from \"./identity/environment.js\";\nimport { readConfig } from \"../config/config.js\";\nimport { findProjectConfig } from \"../config/project-config.js\";\nimport {\n type FluidProfile,\n type IdentityProfile,\n isClientProfile,\n isIdentityProfile,\n} from \"../config/types.js\";\nimport { clientAccessToken, peekClientToken } from \"./identity/client.js\";\nimport {\n peekIdentityToken,\n profileAccessToken,\n RoleNotGrantedError,\n} from \"./identity/session.js\";\n\n/** A role a company access token can be narrowed to. */\nexport type AuthRole = \"root_admin\" | \"admin\" | \"rep\";\n\n/**\n * Where a command's credential comes from: a literal token (a flag or an\n * environment variable), or a stored profile.\n */\nexport type CredentialSource =\n | {\n readonly kind: \"token\";\n readonly token: string;\n readonly origin?: \"fd\" | \"env\" | \"explicit\";\n readonly envVar?: \"FLUID_TOKEN\" | \"FLUID_API_TOKEN\";\n }\n | {\n readonly kind: \"profile\";\n readonly profile: FluidProfile;\n readonly origin?: \"fluidrc\" | \"active\" | \"explicit\";\n };\n\nconst FD_ENV = \"FLUID_TOKEN_FD\";\nconst LIVE_HEADER = \"live\\n\";\n\nconst memberTokenCache = new Map<string, ExchangedToken>();\n\nlet fdTokenCache: { readonly token: string } | undefined;\nlet fdChannel: Socket | undefined;\n\n/** Forgets the cached fd token and drops the live channel. For tests. */\nexport function resetFdTokenForTests(): void {\n fdTokenCache = undefined;\n memberTokenCache.clear();\n fdChannel?.destroy();\n fdChannel = undefined;\n}\n\nfunction closeQuietly(fd: number): void {\n try {\n closeSync(fd);\n } catch {\n // already closed\n }\n}\n\n/**\n * Follows the channel: each further complete line is a fresh bearer that\n * replaces the cached one. The socket is unreferenced, so it never keeps the\n * process alive, and a channel that errors or closes leaves the last token.\n */\nfunction followFdChannel(fd: number, pending: string): void {\n let buffered = pending;\n const take = (): void => {\n let end = buffered.indexOf(\"\\n\");\n while (end !== -1) {\n const next = buffered.slice(0, end).trim();\n buffered = buffered.slice(end + 1);\n if (next) fdTokenCache = { token: next };\n end = buffered.indexOf(\"\\n\");\n }\n };\n take();\n const channel = new Socket({ fd, readable: true, writable: false });\n channel.setEncoding(\"utf8\");\n channel.on(\"data\", (chunk: string) => {\n buffered += chunk;\n take();\n });\n channel.on(\"error\", () => undefined);\n channel.unref();\n fdChannel = channel;\n}\n\n/**\n * The bearer a parent process wrote to the inherited descriptor named by\n * `FLUID_TOKEN_FD`, or null when that variable is unset. The variable holds\n * only the descriptor number, never the token.\n *\n * A token that ends at end of input is read once, cached, and the descriptor\n * closed. Input that opens with a `live` line is a live channel: the token is\n * the next line, the descriptor stays open, and each further line the parent\n * writes replaces the cached token, so a long-running command keeps a bearer\n * that has not expired.\n *\n * Throws when the descriptor is not a number, cannot be read or holds\n * nothing. It never falls back to a profile, which could be another\n * company's.\n */\nexport function readFdToken(): string | null {\n if (fdTokenCache) return fdTokenCache.token;\n const raw = process.env[FD_ENV];\n if (raw === undefined || raw === \"\") return null;\n const fd = /^\\d+$/.test(raw) ? Number(raw) : NaN;\n if (!Number.isSafeInteger(fd) || fd < 3) {\n throw new Error(`${FD_ENV} must be an inherited descriptor number.`);\n }\n const chunk = Buffer.alloc(4096);\n let text = \"\";\n const liveReady = (): boolean =>\n text.startsWith(LIVE_HEADER) && text.indexOf(\"\\n\", LIVE_HEADER.length) > -1;\n try {\n for (;;) {\n const count = readSync(fd, chunk, 0, chunk.length, null);\n if (count === 0) break;\n text += chunk.toString(\"utf8\", 0, count);\n if (liveReady()) break;\n }\n } catch {\n closeQuietly(fd);\n throw new Error(`Could not read the token from ${FD_ENV}=${fd}.`);\n }\n const live = liveReady();\n const body = live ? text.slice(LIVE_HEADER.length) : text;\n const end = live ? body.indexOf(\"\\n\") : body.length;\n const token = body.slice(0, end).trim();\n if (!token) {\n closeQuietly(fd);\n throw new Error(`${FD_ENV}=${fd} held no token.`);\n }\n fdTokenCache = { token };\n if (!live) {\n closeQuietly(fd);\n return token;\n }\n followFdChannel(fd, body.slice(end + 1));\n return (fdTokenCache as { readonly token: string }).token;\n}\n\n/**\n * Resolve the credential for a named profile, or for the active one when\n * omitted.\n *\n * Resolution order (when `profileName` is omitted — mirrors\n * `createCommandContext` in domain/context.ts):\n * 1. A token on the inherited descriptor `FLUID_TOKEN_FD` names\n * 2. `FLUID_TOKEN` / `FLUID_API_TOKEN` environment variables\n * 3. Project-level `.fluidrc` profile (walks upward from cwd)\n * 4. Global active profile from `~/.fluid/config.json`\n *\n * When `profileName` is provided explicitly (e.g. via `--profile` flag),\n * it takes precedence over the environment variables, `.fluidrc`, and the\n * active profile.\n *\n * A legacy profile whose token {@link primeCommandCredential} found dead, and\n * replaced with an identity profile of the same company, resolves to that\n * identity profile for the rest of the process, by name or by default.\n */\nexport function resolveCredentialSource(\n profileName?: string,\n): CredentialSource | null {\n const config = readConfig();\n\n if (profileName) {\n const profile = config.profiles[profileName];\n return profile\n ? { kind: \"profile\", profile: adoptedFor(profile), origin: \"explicit\" }\n : null;\n }\n\n const fdToken = readFdToken();\n if (fdToken) return { kind: \"token\", token: fdToken, origin: \"fd\" };\n\n const fluidToken = process.env[\"FLUID_TOKEN\"];\n if (fluidToken) {\n return {\n kind: \"token\",\n token: fluidToken,\n origin: \"env\",\n envVar: \"FLUID_TOKEN\",\n };\n }\n const apiToken = process.env[\"FLUID_API_TOKEN\"];\n if (apiToken) {\n return {\n kind: \"token\",\n token: apiToken,\n origin: \"env\",\n envVar: \"FLUID_API_TOKEN\",\n };\n }\n\n const projectConfig = findProjectConfig(process.cwd());\n if (projectConfig?.profile) {\n const profile = config.profiles[projectConfig.profile];\n if (profile) {\n return {\n kind: \"profile\",\n profile: adoptedFor(profile),\n origin: \"fluidrc\",\n };\n }\n }\n\n if (!config.activeProfile) return null;\n const profile = config.profiles[config.activeProfile];\n return profile\n ? { kind: \"profile\", profile: adoptedFor(profile), origin: \"active\" }\n : null;\n}\n\n/** What a credential source is, without the credential itself. */\nexport interface CredentialSourceDescription {\n readonly origin: \"fd\" | \"env\" | \"explicit\" | \"fluidrc\" | \"active\";\n readonly mode: \"legacy\" | \"identity\" | \"client\" | \"token\";\n readonly profileName?: string;\n readonly envVar?: string;\n}\n\n/**\n * Names where a credential comes from and its mode. Never carries the token.\n */\nexport function describeCredentialSource(\n source: CredentialSource,\n): CredentialSourceDescription {\n if (source.kind === \"token\") {\n const origin = source.origin ?? \"explicit\";\n const envVar =\n origin === \"fd\" ? FD_ENV : origin === \"env\" ? source.envVar : undefined;\n return { origin, mode: \"token\", ...(envVar ? { envVar } : {}) };\n }\n const mode = isIdentityProfile(source.profile)\n ? \"identity\"\n : isClientProfile(source.profile)\n ? \"client\"\n : \"legacy\";\n return {\n origin: source.origin ?? \"active\",\n mode,\n profileName: source.profile.name,\n };\n}\n\nconst trimSlash = (url: string): string => url.replace(/\\/+$/, \"\");\n\nlet adopted: {\n readonly from: string;\n readonly identity: IdentityProfile;\n} | null = null;\n\nfunction sameBase(identity: IdentityProfile, rejected: FluidProfile): boolean {\n return (\n (!identity.fluidShop ||\n !rejected.fluidShop ||\n identity.fluidShop === rejected.fluidShop) &&\n !!identity.baseUrl &&\n !!rejected.baseUrl &&\n trimSlash(identity.baseUrl) === trimSlash(rejected.baseUrl)\n );\n}\n\nfunction sameTenant(\n identity: IdentityProfile,\n rejected: FluidProfile,\n): boolean {\n return (\n !!identity.companyName &&\n identity.companyName === rejected.companyName &&\n sameBase(identity, rejected)\n );\n}\n\nfunction adoptedFor(profile: FluidProfile): FluidProfile {\n if (\n adopted &&\n adopted.from === profile.name &&\n !isIdentityProfile(profile) &&\n !isClientProfile(profile)\n ) {\n return adopted.identity;\n }\n return profile;\n}\n\n/**\n * Makes `identity` the credential for the rest of this process in place of the\n * legacy profile named `from`, for every reader of\n * {@link resolveCredentialSource}, whether it asks for that profile by name or\n * resolves the default one. The caller has already established that both\n * profiles are the same company.\n */\nexport function adoptIdentityProfile(\n identity: IdentityProfile,\n from: string,\n): void {\n adopted = { from, identity };\n}\n\n/** Forgets the adopted identity profile. For tests. */\nexport function resetAdoptedIdentityForTests(): void {\n adopted = null;\n}\n\n/**\n * A candidate identity-mode profile for the company of `rejected`, or null\n * when none exists. This is a prefilter, not proof: company names are not\n * unique, so it compares only the name and the base URLs, which must both be\n * set and agree, and a `fluidShop` when both profiles carry one. An identity\n * profile written by `fluid login` carries none. The caller must confirm the\n * identity session's company before relying on the candidate.\n */\nexport function findIdentityFallbackProfile(\n rejected: FluidProfile,\n): IdentityProfile | null {\n return (\n Object.values(readConfig().profiles)\n .filter(isIdentityProfile)\n .find((profile) => sameTenant(profile, rejected)) ?? null\n );\n}\n\n/**\n * Identity-mode profiles that could be the company of `rejected`, in two\n * groups: those whose company name also matches, then those on the same base\n * URL (and `fluidShop`, when both carry one) whose name differs, since a\n * company rename leaves the legacy profile's name stale. Still only a\n * prefilter: the caller must confirm each candidate's authenticated shop.\n */\nexport function findIdentityFallbackCandidates(\n rejected: FluidProfile,\n): readonly (readonly IdentityProfile[])[] {\n const sameBaseProfiles = Object.values(readConfig().profiles)\n .filter(isIdentityProfile)\n .filter((profile) => sameBase(profile, rejected));\n const named = sameBaseProfiles.filter((profile) =>\n sameTenant(profile, rejected),\n );\n const renamed = sameBaseProfiles.filter(\n (profile) => !named.includes(profile),\n );\n return [named, renamed].filter((group) => group.length > 0);\n}\n\n/**\n * Get the auth token for a named profile, or the active profile when omitted,\n * in the order {@link resolveCredentialSource} describes.\n *\n * An identity-mode profile keeps no token in the config file. Its access\n * token lives in this process's memory once the session has been restored,\n * which the CLI does before running a command; until then, and after its\n * session ends, this returns null. Prefer {@link getAuthTokenAsync}, which\n * restores and refreshes the session itself.\n */\nexport function getAuthToken(profileName?: string): string | null {\n const source = resolveCredentialSource(profileName);\n if (!source) return null;\n if (source.kind === \"token\") return source.token;\n if (isIdentityProfile(source.profile)) {\n return peekIdentityToken(source.profile.name);\n }\n if (isClientProfile(source.profile)) return peekClientToken(source.profile);\n return source.profile.token ?? null;\n}\n\n/**\n * Like {@link getAuthToken}, but restores, refreshes, or exchanges an\n * identity-mode profile's session as needed. Resolves with null when there\n * is no credential; rejects when an identity session has ended.\n */\nexport async function getAuthTokenAsync(\n profileName?: string,\n): Promise<string | null> {\n const source = resolveCredentialSource(profileName);\n if (!source) return null;\n if (source.kind === \"token\") return source.token;\n if (isIdentityProfile(source.profile)) {\n return profileAccessToken(source.profile);\n }\n if (isClientProfile(source.profile)) return clientAccessToken(source.profile);\n return source.profile.token ?? null;\n}\n\n/**\n * Like {@link getAuthTokenAsync}, for a token that acts only as `roles`. An\n * admin who is also a rep holds an `admin` token by default, which an API that\n * wants a rep refuses; this asks the identity service to narrow the session to\n * `roles` in the company (RFC 8693), and holds that token apart from the\n * default one, which every other reader keeps getting.\n *\n * Resolves with null when there is no credential. Rejects with an\n * error {@link isRoleNotGrantedError} recognises when the person does not\n * hold `roles` in the company, and when an identity session has ended.\n */\nexport async function getRoleAuthTokenAsync(\n roles: readonly AuthRole[],\n profileName?: string,\n): Promise<string | null> {\n const source = resolveCredentialSource(profileName);\n if (!source) return null;\n if (source.kind === \"token\") {\n if (\n process.env[\"FLUID_MEMBER_LITERAL_TOKEN_NARROW\"] !== \"1\" ||\n roles.length !== 1 ||\n roles[0] !== \"rep\"\n ) {\n return source.token;\n }\n const identityUrl = resolveIdentityUrl(process.env[\"FLUID_API_BASE\"] ?? \"\");\n if (!identityUrl) {\n throw new Error(\n \"Cannot narrow a member token: no identity URL for FLUID_API_BASE.\",\n );\n }\n let claims: { org?: unknown; roles?: unknown; iss?: unknown };\n try {\n claims = JSON.parse(\n Buffer.from(source.token.split(\".\")[1] ?? \"\", \"base64url\").toString(\n \"utf8\",\n ),\n );\n } catch {\n throw new Error(\n \"Cannot narrow a member token: cannot determine the token's org.\",\n );\n }\n const org = claims?.org;\n if (typeof org !== \"string\" || !org.trim()) {\n throw new Error(\n \"Cannot narrow a member token: cannot determine the token's org.\",\n );\n }\n if (\n typeof claims.iss === \"string\" &&\n new URL(claims.iss).origin !== identityUrl\n ) {\n throw new Error(\n \"Cannot narrow a member token: issuer does not match the identity URL.\",\n );\n }\n if (\n Array.isArray(claims.roles) &&\n claims.roles.length === 1 &&\n claims.roles[0] === \"rep\"\n ) {\n return source.token;\n }\n const clientId =\n process.env[\"FLUID_IDENTITY_CLIENT_ID\"] || IDENTITY_CLIENT_ID;\n const tokenHash = createHash(\"sha256\").update(source.token).digest(\"hex\");\n const key = `${identityUrl} ${clientId} ${org} ${tokenHash}`;\n const cached = memberTokenCache.get(key);\n if (cached && Date.now() < cached.expiresAt - 30_000)\n return cached.accessToken;\n memberTokenCache.delete(key);\n try {\n const exchanged = await exchangeNativeToken(\n { identityUrl, clientId },\n source.token,\n { org, roles: [\"rep\"] },\n );\n memberTokenCache.set(key, exchanged);\n return exchanged.accessToken;\n } catch (error) {\n if (error instanceof SessionError && error.code === \"access_denied\") {\n throw new RoleNotGrantedError([\"rep\"], org);\n }\n throw error;\n }\n }\n if (isIdentityProfile(source.profile)) {\n return profileAccessToken(source.profile, roles);\n }\n if (isClientProfile(source.profile)) return clientAccessToken(source.profile);\n return source.profile.token ?? null;\n}\n\n/**\n * Get the active profile, or null if not logged in\n */\nexport function getActiveProfile(): FluidProfile | null {\n const config = readConfig();\n if (!config.activeProfile) return null;\n\n return config.profiles[config.activeProfile] ?? null;\n}\n\n/**\n * List all stored profile names\n */\nexport function listProfileNames(): string[] {\n const config = readConfig();\n return Object.keys(config.profiles);\n}\n","import type { Command } from \"commander\";\n\nimport type { InputResolver } from \"./types.js\";\n\nconst resolvers = new WeakMap<Command, InputResolver>();\n\n/**\n * Declares the local inputs a command's action reads.\n *\n * command - the leaf command whose action reads the inputs\n * resolver - maps commander's parsed opts and args to the input specs; it\n * must be a pure function of opts and args and must not touch the filesystem\n *\n * Returns the command.\n */\nexport function declareInputs(\n command: Command,\n resolver: InputResolver,\n): Command {\n resolvers.set(command, resolver);\n return command;\n}\n\nexport function getInputResolver(command: Command): InputResolver | undefined {\n return resolvers.get(command);\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nlet internalDepth = 0;\nconst asyncScope = new AsyncLocalStorage<true>();\n\n/** True while the inputs implementation itself is touching the filesystem. */\nexport function inInternalRead(): boolean {\n return internalDepth > 0 || asyncScope.getStore() === true;\n}\n\nexport function withInternalReads<T>(fn: () => T): T {\n internalDepth++;\n try {\n return fn();\n } finally {\n internalDepth--;\n }\n}\n\n/**\n * Async form of withInternalReads. The scope follows fn's own async\n * continuations only; unrelated concurrent work stays guarded.\n */\nexport async function withInternalReadsAsync<T>(\n fn: () => Promise<T>,\n): Promise<T> {\n return asyncScope.run(true, fn);\n}\n","import { realpathSync } from \"node:fs\";\nimport { isAbsolute, sep } from \"node:path\";\n\nimport { withInternalReads } from \"./scope.js\";\n\nexport interface CanonicalPath {\n lexical: string;\n canonical: string;\n}\n\nexport function lexicalPath(path: string, cwd: string = process.cwd()): string {\n return isAbsolute(path) ? path : `${cwd}${sep}${path}`;\n}\n\n/**\n * The path rule for resolve and expect mode (default mode reads the lexical\n * path so /dev/stdin works): make the path absolute without normalizing, then realpath it natively so `..` after a symlink keeps OS\n * semantics. Throws when the path does not exist.\n */\nexport function canonicalPath(\n path: string,\n cwd: string = process.cwd(),\n): CanonicalPath {\n const lexical = lexicalPath(path, cwd);\n return {\n lexical,\n canonical: withInternalReads(() => realpathSync.native(lexical)),\n };\n}\n","import {\n closeSync,\n constants,\n fstatSync,\n openSync,\n readdirSync,\n readFileSync,\n realpathSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nimport { withInternalReads } from \"./scope.js\";\n\nexport function normalizeIgnore(\n ignore: readonly string[] | undefined,\n): string[] {\n const out = new Set<string>();\n for (const pattern of ignore ?? []) {\n const segments = pattern.split(\"/\");\n if (\n pattern === \"\" ||\n /[*?[\\]{}]/.test(pattern) ||\n segments.some((s) => s === \"\" || s === \".\" || s === \"..\")\n ) {\n throw new Error(\n `Invalid tree ignore pattern: ${JSON.stringify(pattern)}`,\n );\n }\n out.add(pattern);\n }\n return [...out].sort(compare);\n}\n\nexport function ignoreKey(\n ignore: readonly string[],\n skipDotNames = false,\n): string {\n return skipDotNames\n ? JSON.stringify({ ignore, skipDotNames: true })\n : JSON.stringify(ignore);\n}\n\nexport function normalizeSkipDotNames(value: unknown): boolean {\n if (value === undefined || typeof value === \"boolean\") return value === true;\n throw new Error(\n `Invalid tree skipDotNames: ${JSON.stringify(value) ?? String(value)}`,\n );\n}\n\nfunction compare(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/**\n * The single ignore matcher for tree inputs, used by resolve, expect and\n * default mode alike. A pattern without \"/\" matches an entry's basename at\n * any depth; a pattern with \"/\" matches a root-relative path. A match on a\n * directory also excludes every descendant.\n *\n * rel - \"/\"-separated path relative to the tree root\n * ignore - patterns from normalizeIgnore\n *\n * Returns true when rel or any ancestor directory of rel is ignored.\n */\nexport function isIgnored(rel: string, ignore: readonly string[]): boolean {\n const segments = rel.split(\"/\");\n let prefix = \"\";\n for (const segment of segments) {\n prefix = prefix === \"\" ? segment : `${prefix}/${segment}`;\n if (ignore.includes(segment) || ignore.includes(prefix)) return true;\n }\n return false;\n}\n\n/**\n * Lists the regular files under an already canonical root as sorted\n * \"/\"-separated relative paths. Symlink entries are skipped at list time in\n * every mode. Throws if a directory being walked is not its own canonical\n * path. With skipDotNames, every entry whose name starts with \".\" is skipped\n * before its directory is read.\n */\nexport function listTreeFiles(\n root: string,\n ignore: readonly string[],\n skipDotNames = false,\n): string[] {\n const out: string[] = [];\n const walk = (dir: string, relDir: string): void => {\n assertCanonicalDir(dir);\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const rel = relDir === \"\" ? entry.name : `${relDir}/${entry.name}`;\n if (skipDotNames && entry.name.startsWith(\".\")) continue;\n if (isIgnored(rel, ignore)) continue;\n if (entry.isDirectory()) walk(join(dir, entry.name), rel);\n else if (entry.isFile()) out.push(rel);\n }\n };\n withInternalReads(() => walk(root, \"\"));\n return out.sort(compare);\n}\n\nfunction assertCanonicalDir(dir: string): void {\n if (realpathSync.native(dir) !== dir) {\n throw new Error(`Tree directory changed during read: ${dir}`);\n }\n}\n\n/**\n * Reads one tree member from a canonical root. Rejects a non-canonical parent\n * directory and a symlinked or non-regular final component (O_NOFOLLOW).\n * Known residual: a parent directory swapped between the canonical check and\n * the open is not detected; it needs a local writer to the tree during the\n * command, and Node has no openat2.\n */\nexport function readTreeFileFromDisk(root: string, rel: string): Buffer {\n return withInternalReads(() => {\n const path = join(root, rel);\n assertCanonicalDir(join(root, dirname(rel)));\n const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);\n try {\n if (!fstatSync(fd).isFile()) {\n throw new Error(`Tree member is not a regular file: ${path}`);\n }\n return readFileSync(fd);\n } finally {\n closeSync(fd);\n }\n });\n}\n","import { createHash } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\n\nimport { canonicalPath } from \"./paths.js\";\nimport { withInternalReads } from \"./scope.js\";\nimport {\n ignoreKey,\n listTreeFiles,\n normalizeIgnore,\n normalizeSkipDotNames,\n readTreeFileFromDisk,\n} from \"./tree.js\";\n\nimport type { InputEntry, InputSpec, TreeEntry } from \"./types.js\";\n\nexport interface Snapshot {\n files: Map<string, Buffer>;\n aliases: Map<string, string>;\n trees: Map<string, Map<string, Buffer>>;\n treeAliases: Map<string, string>;\n refs: Map<string, string>;\n}\n\nexport function treeKey(\n root: string,\n ignore: readonly string[],\n skipDotNames = false,\n): string {\n return `${root}\\0${ignoreKey(ignore, skipDotNames)}`;\n}\n\nexport const MANIFEST_VERSION = 1;\n\nexport function sha256(data: Buffer): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\nexport function resolveInputs(\n specs: readonly InputSpec[],\n cwd: string = process.cwd(),\n): { entries: InputEntry[]; snapshot: Snapshot } {\n return withInternalReads(() => {\n const snapshot: Snapshot = {\n files: new Map(),\n aliases: new Map(),\n trees: new Map(),\n treeAliases: new Map(),\n refs: new Map(),\n };\n const entries: InputEntry[] = [];\n for (const spec of specs) {\n if (spec.kind === \"ref\") {\n snapshot.refs.set(spec.name, spec.value);\n entries.push({ kind: \"ref\", name: spec.name, value: spec.value });\n } else if (spec.kind === \"file\" || spec.kind === \"config\") {\n const { lexical, canonical: path } = canonicalPath(spec.path, cwd);\n const content = readFileSync(path);\n snapshot.aliases.set(lexical, path);\n snapshot.aliases.set(path, path);\n snapshot.files.set(path, content);\n entries.push({\n kind: spec.kind,\n path,\n sha256: sha256(content),\n size: content.length,\n });\n } else {\n if (spec.kind !== \"tree\" || typeof spec.path !== \"string\") {\n throw new Error(\"Invalid tree input spec\");\n }\n const { lexical, canonical: root } = canonicalPath(spec.path, cwd);\n const ignore = normalizeIgnore(spec.ignore);\n const skipDot = normalizeSkipDotNames(spec.skipDotNames);\n const members = new Map<string, Buffer>();\n const files: TreeEntry[\"files\"] = [];\n for (const rel of listTreeFiles(root, ignore, skipDot)) {\n const content = readTreeFileFromDisk(root, rel);\n members.set(rel, content);\n files.push({\n path: rel,\n sha256: sha256(content),\n size: content.length,\n });\n }\n snapshot.treeAliases.set(lexical, root);\n snapshot.treeAliases.set(root, root);\n snapshot.trees.set(treeKey(root, ignore, skipDot), members);\n entries.push({\n kind: \"tree\",\n path: root,\n ignore,\n ...(skipDot ? { skipDotNames: true as const } : {}),\n files,\n });\n }\n }\n return { entries, snapshot };\n });\n}\n\nfunction sortKey(entry: InputEntry): string {\n const id =\n entry.kind === \"ref\"\n ? entry.name\n : entry.kind === \"tree\"\n ? `${entry.path}\\0${ignoreKey(entry.ignore, entry.skipDotNames === true)}`\n : entry.path;\n return `${entry.kind}\\0${id}`;\n}\n\nexport function canonicalEntries(entries: readonly InputEntry[]): InputEntry[] {\n return entries\n .map((e): InputEntry => {\n if (e.kind === \"ref\") {\n return { kind: \"ref\", name: e.name, value: e.value };\n }\n if (e.kind === \"tree\") {\n return {\n kind: \"tree\",\n path: e.path,\n ignore: [...e.ignore],\n ...(e.skipDotNames === true ? { skipDotNames: true as const } : {}),\n files: e.files.map((f) => ({\n path: f.path,\n sha256: f.sha256,\n size: f.size,\n })),\n };\n }\n return { kind: e.kind, path: e.path, sha256: e.sha256, size: e.size };\n })\n .sort((a, b) => {\n const ka = sortKey(a);\n const kb = sortKey(b);\n return ka < kb ? -1 : ka > kb ? 1 : 0;\n });\n}\n\nexport function manifestJson(\n command: string,\n entries: readonly InputEntry[],\n): string {\n return JSON.stringify({\n version: MANIFEST_VERSION,\n command,\n inputs: canonicalEntries(entries),\n });\n}\n","import { readFileSync } from \"node:fs\";\n\nimport { canonicalPath, lexicalPath } from \"./paths.js\";\nimport { withInternalReads } from \"./scope.js\";\nimport { treeKey, type Snapshot } from \"./snapshot.js\";\nimport {\n listTreeFiles,\n normalizeIgnore,\n normalizeSkipDotNames,\n readTreeFileFromDisk,\n} from \"./tree.js\";\nimport type { CommandInputs, InputTree, TreeOptions } from \"./types.js\";\n\nlet activeSnapshot: Snapshot | null = null;\n\nexport function setActiveSnapshot(snapshot: Snapshot | null): void {\n activeSnapshot = snapshot;\n}\n\nexport class InputsUndeclaredError extends Error {\n constructor(path: string) {\n super(`Undeclared input read: ${path}`);\n this.name = \"InputsUndeclaredError\";\n }\n}\n\nfunction declaredKey(path: string, snapshot: Snapshot): string | undefined {\n const lexical = lexicalPath(path);\n const key = snapshot.aliases.get(lexical) ?? lexical;\n return snapshot.files.has(key) ? key : undefined;\n}\n\nfunction bytes(content: Buffer, encoding?: BufferEncoding): never {\n return (\n encoding ? content.toString(encoding) : Buffer.from(content)\n ) as never;\n}\n\nfunction snapshotTree(\n rootPath: string,\n ignore: string[],\n skipDot: boolean,\n snapshot: Snapshot,\n): { root: string; members: Map<string, Buffer> } {\n const root = snapshot.treeAliases.get(lexicalPath(rootPath)) ?? rootPath;\n const members = snapshot.trees.get(treeKey(root, ignore, skipDot));\n if (!members) throw new InputsUndeclaredError(rootPath);\n return { root, members };\n}\n\nfunction openTree(rootPath: string, options?: TreeOptions): InputTree {\n const ignore = normalizeIgnore(options?.ignore);\n const skipDot = normalizeSkipDotNames(options?.skipDotNames);\n let disk: { root: string; known: Set<string> } | undefined;\n const fromDisk = (): { root: string; known: Set<string> } => {\n if (!disk) {\n const root = canonicalPath(rootPath).canonical;\n disk = { root, known: new Set(listTreeFiles(root, ignore, skipDot)) };\n }\n return disk;\n };\n if (activeSnapshot) snapshotTree(rootPath, ignore, skipDot, activeSnapshot);\n else fromDisk();\n return {\n get root() {\n return activeSnapshot\n ? snapshotTree(rootPath, ignore, skipDot, activeSnapshot).root\n : fromDisk().root;\n },\n list() {\n if (activeSnapshot) {\n return [\n ...snapshotTree(\n rootPath,\n ignore,\n skipDot,\n activeSnapshot,\n ).members.keys(),\n ];\n }\n return [...fromDisk().known];\n },\n readFile(rel: string, encoding?: BufferEncoding): never {\n const missing = () => new InputsUndeclaredError(`${rootPath}/${rel}`);\n if (activeSnapshot) {\n const content = snapshotTree(\n rootPath,\n ignore,\n skipDot,\n activeSnapshot,\n ).members.get(rel);\n if (!content) throw missing();\n return bytes(content, encoding);\n }\n const { root, known } = fromDisk();\n if (!known.has(rel)) throw missing();\n return bytes(readTreeFileFromDisk(root, rel), encoding);\n },\n };\n}\n\n/**\n * The reader behind ctx.inputs. Outside expect mode it reads from disk; once\n * an expect-mode snapshot is active it serves only that snapshot and throws\n * for anything undeclared.\n */\nexport function createInputsReader(): CommandInputs {\n return {\n isExpecting: () => activeSnapshot !== null,\n ref(name: string) {\n const snapshot = activeSnapshot;\n if (!snapshot) return undefined;\n const value = snapshot.refs.get(name);\n if (value === undefined) throw new InputsUndeclaredError(`ref ${name}`);\n return value;\n },\n tree: openTree,\n readFile(path: string, encoding?: BufferEncoding): never {\n const snapshot = activeSnapshot;\n if (!snapshot) {\n const content = withInternalReads(() =>\n readFileSync(lexicalPath(path)),\n );\n return (encoding ? content.toString(encoding) : content) as never;\n }\n const key = declaredKey(path, snapshot);\n const content = key === undefined ? undefined : snapshot.files.get(key);\n if (!content) throw new InputsUndeclaredError(path);\n return (\n encoding ? content.toString(encoding) : Buffer.from(content)\n ) as never;\n },\n };\n}\n","import { readFileSync, writeSync } from \"node:fs\";\nimport type { Command } from \"commander\";\n\nimport { getInputResolver } from \"./declare.js\";\nimport { InputsUndeclaredError, setActiveSnapshot } from \"./reader.js\";\nimport {\n canonicalEntries,\n MANIFEST_VERSION,\n manifestJson,\n resolveInputs,\n} from \"./snapshot.js\";\nimport { withInternalReads } from \"./scope.js\";\nimport type { InputEntry } from \"./types.js\";\n\nexport const INPUTS_MODE_ENV = \"FLUID_INPUTS_MODE\";\nexport const INPUTS_EXPECT_ENV = \"FLUID_INPUTS_EXPECT\";\n\nexport const INPUTS_UNDECLARED_CODE = \"inputs_undeclared\";\nexport const INPUTS_UNDECLARED_EXIT = 64;\nexport const INPUTS_MISMATCH_CODE = \"inputs_mismatch\";\nexport const INPUTS_MISMATCH_EXIT = 65;\nexport const INPUTS_RESOLVE_FAILED_EXIT = 1;\n\nexport interface InputsHookIo {\n env: NodeJS.ProcessEnv;\n stdout: (text: string) => void;\n stderr: (text: string) => void;\n exit: (code: number) => never;\n}\n\nfunction writeAll(fd: number, text: string): void {\n const buffer = Buffer.from(text);\n let offset = 0;\n while (offset < buffer.length) {\n try {\n offset += writeSync(fd, buffer, offset);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EAGAIN\") throw error;\n }\n }\n}\n\nconst processIo: InputsHookIo = {\n env: process.env,\n stdout: (text) => writeAll(1, text),\n stderr: (text) => writeAll(2, text),\n exit: (code) => process.exit(code),\n};\n\nexport function inputsModeActive(env: NodeJS.ProcessEnv): boolean {\n return (\n env[INPUTS_MODE_ENV] !== undefined || env[INPUTS_EXPECT_ENV] !== undefined\n );\n}\n\nfunction commandPath(command: Command): string {\n const names: string[] = [];\n for (let c: Command | null = command; c; c = c.parent)\n names.unshift(c.name());\n return names.join(\" \");\n}\n\nfunction readManifest(\n path: string,\n): { version: unknown; command: unknown; inputs: InputEntry[] } | null {\n try {\n const parsed = JSON.parse(\n withInternalReads(() => readFileSync(path, \"utf8\")),\n ) as { version?: unknown; command?: unknown; inputs?: unknown };\n if (!Array.isArray(parsed.inputs)) return null;\n return {\n version: parsed.version,\n command: parsed.command,\n inputs: canonicalEntries(parsed.inputs as InputEntry[]),\n };\n } catch {\n return null;\n }\n}\n\nexport function inputsPreAction(\n actionCommand: Command,\n io: InputsHookIo = processIo,\n): void {\n const mode = io.env[INPUTS_MODE_ENV];\n const expectPath = io.env[INPUTS_EXPECT_ENV];\n setActiveSnapshot(null);\n if (mode === undefined && expectPath === undefined) return;\n const resolveMode = mode === \"resolve\";\n if (\n (mode !== undefined && !resolveMode) ||\n expectPath === \"\" ||\n (resolveMode && expectPath !== undefined)\n ) {\n io.stderr(`${INPUTS_MISMATCH_CODE}\\n`);\n return io.exit(INPUTS_MISMATCH_EXIT);\n }\n\n const resolver = getInputResolver(actionCommand);\n if (!resolver) {\n io.stderr(`${INPUTS_UNDECLARED_CODE}\\n`);\n return io.exit(INPUTS_UNDECLARED_EXIT);\n }\n\n let resolved: ReturnType<typeof resolveInputs>;\n try {\n resolved = resolveInputs(\n resolver(actionCommand.optsWithGlobals(), actionCommand.args),\n );\n } catch (error) {\n if (resolveMode) {\n const message = error instanceof Error ? error.message : String(error);\n io.stderr(`${message}\\n`);\n return io.exit(INPUTS_RESOLVE_FAILED_EXIT);\n }\n io.stderr(`${INPUTS_MISMATCH_CODE}\\n`);\n return io.exit(INPUTS_MISMATCH_EXIT);\n }\n\n if (resolveMode) {\n io.stdout(\n `${manifestJson(commandPath(actionCommand), resolved.entries)}\\n`,\n );\n return io.exit(0);\n }\n\n const expected = readManifest(expectPath as string);\n if (\n !expected ||\n expected.version !== MANIFEST_VERSION ||\n expected.command !== commandPath(actionCommand) ||\n JSON.stringify(expected.inputs) !==\n JSON.stringify(canonicalEntries(resolved.entries))\n ) {\n io.stderr(`${INPUTS_MISMATCH_CODE}\\n`);\n return io.exit(INPUTS_MISMATCH_EXIT);\n }\n setActiveSnapshot(resolved.snapshot);\n}\n\n/**\n * Registers the inputs preAction hook. Register it before any credential\n * hook.\n */\nexport function registerInputsHook(\n program: Command,\n io: InputsHookIo = processIo,\n): void {\n program.hook(\"preAction\", (_program, actionCommand) => {\n inputsPreAction(actionCommand, io);\n });\n}\n\n/**\n * Maps an undeclared read in expect mode to the fixed undeclared exit; any\n * other error is returned to the caller untouched.\n */\nexport function exitOnInputsError(\n error: unknown,\n io: InputsHookIo = processIo,\n): void {\n if (!(error instanceof InputsUndeclaredError)) return;\n io.stderr(`${INPUTS_UNDECLARED_CODE}\\n`);\n io.exit(INPUTS_UNDECLARED_EXIT);\n}\n"],"mappings":";;;;;;;AAwBA,MAAM,aAAa,OAAO,IAAI,yCAAyC;;;;;AAQvE,SAAgB,gBACd,SACA,YACG;CACH,MAAM,SAAS;CACf,OAAO,cAAc;EAAE,GAAG,OAAO;EAAa,GAAG;CAAW;CAC5D,OAAO;AACT;AAEA,SAAgB,eAAe,SAA4C;CACzE,OAAQ,QAAsB,eAAe;AAC/C;;ACUA,SAAgB,SAAS,SAA2B;CAClD,OAAQ,QAAwC,YAAY;AAC9D;AAEA,SAAS,WAAW,SAA2B;CAC7C,OAAQ,QAAwC,kBAAkB;AACpE;AAEA,SAAgB,mBAAmB,SAA6B;CAC9D,OAAO,QAAQ,SAAS,QAAQ,QAAQ,CAAC,SAAS,GAAG,CAAC;AACxD;AAEA,SAAgB,eAAe,SAA4B;CACzD,OAAO,QAAQ,QAAQ,QAAQ,WAAW,CAAC,OAAO,MAAM;AAC1D;AAEA,SA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