@fluid-app/fluid-cli 0.1.781 → 0.1.782
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.
package/dist/bin/fluid.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { $ as walkCommands, A as pollAgentAccess, D as fetchUserCompanies, E as confirmMfa, F as validateToken, M as sendMfa, N as signup, O as getFluidApiBase, P as switchCompany, Q as visibleSubcommands, S as resolveCredentialSource, X as rootCommand, Y as filterCatalog, Z as visibleOptions, _ as getAuthToken, c as inputsModeActive, g as getActiveProfile, j as redeemIdentityLink, k as isInsecureRemoteBase, l as registerInputsHook, s as exitOnInputsError, u as createInputsReader, w as FLUID_API_ERROR, x as readFdToken } from "../hook-
|
|
2
|
+
import { $ as walkCommands, A as pollAgentAccess, D as fetchUserCompanies, E as confirmMfa, F as validateToken, M as sendMfa, N as signup, O as getFluidApiBase, P as switchCompany, Q as visibleSubcommands, S as resolveCredentialSource, X as rootCommand, Y as filterCatalog, Z as visibleOptions, _ as getAuthToken, c as inputsModeActive, g as getActiveProfile, j as redeemIdentityLink, k as isInsecureRemoteBase, l as registerInputsHook, s as exitOnInputsError, u as createInputsReader, w as FLUID_API_ERROR, x as readFdToken } from "../hook-Cwd8HPw7.mjs";
|
|
3
3
|
import { A as isClientProfile, C as readStoredConfig, D as getConfigDir, E as isStrictConfig, S as readConfig, T as writeConfig, _ as primeClientProfile, c as sessionFacts, j as isIdentityProfile, l as signInWithBrowser, n as describeIdentityError, o as primeIdentityProfile, p as clientAccessToken, r as identityToken, t as endUnusedSessions, u as signOutIdentity, w as updateConfig, y as resolveIdentityUrl } from "../profiles-DqDZHbAv.mjs";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
@@ -105,7 +105,7 @@ function filterCatalog(entries, root, prefix) {
|
|
|
105
105
|
}
|
|
106
106
|
//#endregion
|
|
107
107
|
//#region package.json
|
|
108
|
-
var version = "0.1.
|
|
108
|
+
var version = "0.1.782";
|
|
109
109
|
//#endregion
|
|
110
110
|
//#region src/auth/client-headers.ts
|
|
111
111
|
const CLIENT_HEADERS = {
|
|
@@ -1477,4 +1477,4 @@ function exitOnInputsError(error, io = processIo) {
|
|
|
1477
1477
|
//#endregion
|
|
1478
1478
|
export { walkCommands as $, pollAgentAccess as A, isNodeError as B, findProjectConfig as C, fetchUserCompanies as D, confirmMfa as E, validateToken as F, tryCatch as G, mapError as H, failure as I, unwrapOr as J, tryCatchAsync as K, getErrorMessage as L, sendMfa as M, signup as N, getFluidApiBase as O, switchCompany as P, visibleSubcommands as Q, isError as R, resolveCredentialSource as S, SIGNUP_ERROR as T, mapResult as U, isSuccess as V, success as W, rootCommand as X, filterCatalog as Y, visibleOptions as Z, getAuthToken as _, INPUTS_UNDECLARED_CODE as a, listProfileNames as b, inputsModeActive as c, setActiveSnapshot as d, describeCommand as et, inInternalRead as f, getActiveProfile as g, declareInputs as h, INPUTS_MODE_ENV as i, redeemIdentityLink as j, isInsecureRemoteBase as k, registerInputsHook as l, withInternalReadsAsync as m, INPUTS_MISMATCH_CODE as n, INPUTS_UNDECLARED_EXIT as o, withInternalReads as p, unwrap as q, INPUTS_MISMATCH_EXIT as r, exitOnInputsError as s, INPUTS_EXPECT_ENV as t, createInputsReader as u, getAuthTokenAsync as v, FLUID_API_ERROR as w, readFdToken as x, getRoleAuthTokenAsync as y, isFailure as z };
|
|
1479
1479
|
|
|
1480
|
-
//# sourceMappingURL=hook-
|
|
1480
|
+
//# sourceMappingURL=hook-Cwd8HPw7.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hook-V8Djj2Nx.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 function getFluidApiBase(): string {\n return process.env[\"FLUID_API_BASE\"] ?? \"https://api.fluid.app\";\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 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}\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 * 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/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/me`. A token it\n * refuses, or one that belongs to a customer, is invalid for the CLI; any\n * 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(`${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 if (typeof data?.role !== \"string\" || !STAFF_ROLES.has(data.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 const name = data.company?.name;\n if (typeof name !== \"string\" || name === \"\") {\n return failure(\n createApiError(\n FLUID_API_ERROR.API_UNREACHABLE,\n \"Unexpected response shape from /api/me\",\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 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 ? { uuid, expiresAt, signInPath: \"identity\" }\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(`${apiBase}/api/me`, {\n method: \"GET\",\n headers: { ...CLIENT_HEADERS, Authorization: `Bearer ${token}` },\n signal,\n });\n\n if (response.ok) {\n const data = (await response.json()) as {\n companies?: { id: number; name: string; uuid_v7?: string }[];\n };\n const companies = Array.isArray(data.companies) ? data.companies : [];\n return success(\n companies.map((c) => ({\n id: c.id,\n name: c.name,\n ...(typeof c.uuid_v7 === \"string\" ? { uuidV7: c.uuid_v7 } : {}),\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): Promise<Result<SwitchCompanyResult, 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 },\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 };\n const company = data.company;\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 { closeSync, readSync } from \"node:fs\";\nimport { Socket } from \"node:net\";\nimport { readConfig } from \"../config/config.js\";\nimport { findProjectConfig } from \"../config/project-config.js\";\nimport {\n type FluidProfile,\n isClientProfile,\n isIdentityProfile,\n} from \"../config/types.js\";\nimport { clientAccessToken, peekClientToken } from \"./identity/client.js\";\nimport { peekIdentityToken, profileAccessToken } 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 | { readonly kind: \"token\"; readonly token: string }\n | { readonly kind: \"profile\"; readonly profile: FluidProfile };\n\nconst FD_ENV = \"FLUID_TOKEN_FD\";\nconst LIVE_HEADER = \"live\\n\";\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 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 */\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 ? { kind: \"profile\", profile } : null;\n }\n\n const fdToken = readFdToken();\n if (fdToken) return { kind: \"token\", token: fdToken };\n\n const envToken = process.env[\"FLUID_TOKEN\"] ?? process.env[\"FLUID_API_TOKEN\"];\n if (envToken) return { kind: \"token\", token: envToken };\n\n const projectConfig = findProjectConfig(process.cwd());\n if (projectConfig?.profile) {\n const profile = config.profiles[projectConfig.profile];\n if (profile) return { kind: \"profile\", profile };\n }\n\n if (!config.activeProfile) return null;\n const profile = config.profiles[config.activeProfile];\n return profile ? { kind: \"profile\", profile } : null;\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 * Only an identity-mode profile can be narrowed. A literal token\n * (`FLUID_TOKEN`) and a legacy profile come back exactly as\n * {@link getAuthTokenAsync} returns them, because their token already is what\n * it is. 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\") return source.token;\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,0CAA0C;;;;;AAQxE,SAAgB,gBACd,SACA,YACG;CACH,MAAM,SAAS;AACf,QAAO,cAAc;EAAE,GAAG,OAAO;EAAa,GAAG;EAAY;AAC7D,QAAO;;AAGT,SAAgB,eAAe,SAA4C;AACzE,QAAQ,QAAsB,eAAe;;;;ACW/C,SAAgB,SAAS,SAA2B;AAClD,QAAQ,QAAwC,YAAY;;AAG9D,SAAS,WAAW,SAA2B;AAC7C,QAAQ,QAAwC,kBAAkB;;AAGpE,SAAgB,mBAAmB,SAA6B;AAC9D,QAAO,QAAQ,SAAS,QAAQ,QAAQ,CAAC,SAAS,IAAI,CAAC;;AAGzD,SAAgB,eAAe,SAA4B;AACzD,QAAO,QAAQ,QAAQ,QAAQ,WAAW,CAAC,OAAO,OAAO;;AAG3D,SAAS,eAAe,QAA+B;AACrD,QAAO;EACL,OAAO,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,OAAO,OAAO,SAAS;EACvB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B,cAAc;AAChD,KAAI,CAAC,UAAU;AACb,KAAG,OAAO,GAAG,uBAAuB,IAAI;AACxC,SAAO,GAAG,KAAA,GAA4B;;CAGxC,IAAI;AACJ,KAAI;AACF,aAAW,cACT,SAAS,cAAc,iBAAiB,EAAE,cAAc,KAAK,CAC9D;UACM,OAAO;AACd,MAAI,aAAa;GACf,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACtE,MAAG,OAAO,GAAG,QAAQ,IAAI;AACzB,UAAO,GAAG,KAAA,EAAgC;;AAE5C,KAAG,OAAO,GAAG,qBAAqB,IAAI;AACtC,SAAO,GAAG,KAAA,GAA0B;;AAGtC,KAAI,aAAa;AACf,KAAG,OACD,GAAG,aAAa,YAAY,cAAc,EAAE,SAAS,QAAQ,CAAC,IAC/D;AACD,SAAO,GAAG,KAAK,EAAE;;CAGnB,MAAM,WAAW,aAAa,WAAqB;AACnD,KACE,CAAC,YACD,SAAS,YAAA,KACT,SAAS,YAAY,YAAY,cAAc,IAC/C,KAAK,UAAU,SAAS,OAAO,KAC7B,KAAK,UAAU,iBAAiB,SAAS,QAAQ,CAAC,EACpD;AACA,KAAG,OAAO,GAAG,qBAAqB,IAAI;AACtC,SAAO,GAAG,KAAA,GAA0B;;AAEtC,mBAAkB,SAAS,SAAS;;;;;;AAOtC,SAAgB,mBACd,SACA,KAAmB,WACb;AACN,SAAQ,KAAK,cAAc,UAAU,kBAAkB;AACrD,kBAAgB,eAAe,GAAG;GAClC;;;;;;AAOJ,SAAgB,kBACd,OACA,KAAmB,WACb;AACN,KAAI,EAAE,iBAAiB,uBAAwB;AAC/C,IAAG,OAAO,GAAG,uBAAuB,IAAI;AACxC,IAAG,KAAA,GAA4B"}
|
|
1
|
+
{"version":3,"file":"hook-Cwd8HPw7.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 function getFluidApiBase(): string {\n return process.env[\"FLUID_API_BASE\"] ?? \"https://api.fluid.app\";\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 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}\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 * 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/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/me`. A token it\n * refuses, or one that belongs to a customer, is invalid for the CLI; any\n * 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(`${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 if (typeof data?.role !== \"string\" || !STAFF_ROLES.has(data.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 const name = data.company?.name;\n if (typeof name !== \"string\" || name === \"\") {\n return failure(\n createApiError(\n FLUID_API_ERROR.API_UNREACHABLE,\n \"Unexpected response shape from /api/me\",\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 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 ? { uuid, expiresAt, signInPath: \"identity\" }\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(`${apiBase}/api/me`, {\n method: \"GET\",\n headers: { ...CLIENT_HEADERS, Authorization: `Bearer ${token}` },\n signal,\n });\n\n if (response.ok) {\n const data = (await response.json()) as {\n companies?: { id: number; name: string; uuid_v7?: string }[];\n };\n const companies = Array.isArray(data.companies) ? data.companies : [];\n return success(\n companies.map((c) => ({\n id: c.id,\n name: c.name,\n ...(typeof c.uuid_v7 === \"string\" ? { uuidV7: c.uuid_v7 } : {}),\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): Promise<Result<SwitchCompanyResult, 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 },\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 };\n const company = data.company;\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 { closeSync, readSync } from \"node:fs\";\nimport { Socket } from \"node:net\";\nimport { readConfig } from \"../config/config.js\";\nimport { findProjectConfig } from \"../config/project-config.js\";\nimport {\n type FluidProfile,\n isClientProfile,\n isIdentityProfile,\n} from \"../config/types.js\";\nimport { clientAccessToken, peekClientToken } from \"./identity/client.js\";\nimport { peekIdentityToken, profileAccessToken } 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 | { readonly kind: \"token\"; readonly token: string }\n | { readonly kind: \"profile\"; readonly profile: FluidProfile };\n\nconst FD_ENV = \"FLUID_TOKEN_FD\";\nconst LIVE_HEADER = \"live\\n\";\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 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 */\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 ? { kind: \"profile\", profile } : null;\n }\n\n const fdToken = readFdToken();\n if (fdToken) return { kind: \"token\", token: fdToken };\n\n const envToken = process.env[\"FLUID_TOKEN\"] ?? process.env[\"FLUID_API_TOKEN\"];\n if (envToken) return { kind: \"token\", token: envToken };\n\n const projectConfig = findProjectConfig(process.cwd());\n if (projectConfig?.profile) {\n const profile = config.profiles[projectConfig.profile];\n if (profile) return { kind: \"profile\", profile };\n }\n\n if (!config.activeProfile) return null;\n const profile = config.profiles[config.activeProfile];\n return profile ? { kind: \"profile\", profile } : null;\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 * Only an identity-mode profile can be narrowed. A literal token\n * (`FLUID_TOKEN`) and a legacy profile come back exactly as\n * {@link getAuthTokenAsync} returns them, because their token already is what\n * it is. 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\") return source.token;\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,0CAA0C;;;;;AAQxE,SAAgB,gBACd,SACA,YACG;CACH,MAAM,SAAS;AACf,QAAO,cAAc;EAAE,GAAG,OAAO;EAAa,GAAG;EAAY;AAC7D,QAAO;;AAGT,SAAgB,eAAe,SAA4C;AACzE,QAAQ,QAAsB,eAAe;;;;ACW/C,SAAgB,SAAS,SAA2B;AAClD,QAAQ,QAAwC,YAAY;;AAG9D,SAAS,WAAW,SAA2B;AAC7C,QAAQ,QAAwC,kBAAkB;;AAGpE,SAAgB,mBAAmB,SAA6B;AAC9D,QAAO,QAAQ,SAAS,QAAQ,QAAQ,CAAC,SAAS,IAAI,CAAC;;AAGzD,SAAgB,eAAe,SAA4B;AACzD,QAAO,QAAQ,QAAQ,QAAQ,WAAW,CAAC,OAAO,OAAO;;AAG3D,SAAS,eAAe,QAA+B;AACrD,QAAO;EACL,OAAO,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,OAAO,OAAO,SAAS;EACvB,aAAa,OAAO;EACpB,YAAY,OAAO;EACnB,eAAe,OA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AO,GAAG,uBAAuB,IAAI;AACxC,SAAO,GAAG,KAAA,GAA4B;;CAGxC,IAAI;AACJ,KAAI;AACF,aAAW,cACT,SAAS,cAAc,iBAAiB,EAAE,cAAc,KAAK,CAC9D;UACM,OAAO;AACd,MAAI,aAAa;GACf,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACtE,MAAG,OAAO,GAAG,QAAQ,IAAI;AACzB,UAAO,GAAG,KAAA,EAAgC;;AAE5C,KAAG,OAAO,GAAG,qBAAqB,IAAI;AACtC,SAAO,GAAG,KAAA,GAA0B;;AAGtC,KAAI,aAAa;AACf,KAAG,OACD,GAAG,aAAa,YAAY,cAAc,EAAE,SAAS,QAAQ,CAAC,IAC/D;AACD,SAAO,GAAG,KAAK,EAAE;;CAGnB,MAAM,WAAW,aAAa,WAAqB;AACnD,KACE,CAAC,YACD,SAAS,YAAA,KACT,SAAS,YAAY,YAAY,cAAc,IAC/C,KAAK,UAAU,SAAS,OAAO,KAC7B,KAAK,UAAU,iBAAiB,SAAS,QAAQ,CAAC,EACpD;AACA,KAAG,OAAO,GAAG,qBAAqB,IAAI;AACtC,SAAO,GAAG,KAAA,GAA0B;;AAEtC,mBAAkB,SAAS,SAAS;;;;;;AAOtC,SAAgB,mBACd,SACA,KAAmB,WACb;AACN,SAAQ,KAAK,cAAc,UAAU,kBAAkB;AACrD,kBAAgB,eAAe,GAAG;GAClC;;;;;;AAOJ,SAAgB,kBACd,OACA,KAAmB,WACb;AACN,KAAI,EAAE,iBAAiB,uBAAwB;AAC/C,IAAG,OAAO,GAAG,uBAAuB,IAAI;AACxC,IAAG,KAAA,GAA4B"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as walkCommands, B as isNodeError, C as findProjectConfig, D as fetchUserCompanies, E as confirmMfa, F as validateToken, G as tryCatch, H as mapError, I as failure, J as unwrapOr, K as tryCatchAsync, L as getErrorMessage, M as sendMfa, N as signup, O as getFluidApiBase, P as switchCompany, R as isError, S as resolveCredentialSource, T as SIGNUP_ERROR, U as mapResult, V as isSuccess, W as success, _ as getAuthToken, a as INPUTS_UNDECLARED_CODE, b as listProfileNames, c as inputsModeActive, d as setActiveSnapshot, et as describeCommand, f as inInternalRead, g as getActiveProfile, h as declareInputs, i as INPUTS_MODE_ENV, l as registerInputsHook, m as withInternalReadsAsync, n as INPUTS_MISMATCH_CODE, o as INPUTS_UNDECLARED_EXIT, p as withInternalReads, q as unwrap, r as INPUTS_MISMATCH_EXIT, s as exitOnInputsError, t as INPUTS_EXPECT_ENV, u as createInputsReader, v as getAuthTokenAsync, y as getRoleAuthTokenAsync, z as isFailure } from "./hook-
|
|
1
|
+
import { $ as walkCommands, B as isNodeError, C as findProjectConfig, D as fetchUserCompanies, E as confirmMfa, F as validateToken, G as tryCatch, H as mapError, I as failure, J as unwrapOr, K as tryCatchAsync, L as getErrorMessage, M as sendMfa, N as signup, O as getFluidApiBase, P as switchCompany, R as isError, S as resolveCredentialSource, T as SIGNUP_ERROR, U as mapResult, V as isSuccess, W as success, _ as getAuthToken, a as INPUTS_UNDECLARED_CODE, b as listProfileNames, c as inputsModeActive, d as setActiveSnapshot, et as describeCommand, f as inInternalRead, g as getActiveProfile, h as declareInputs, i as INPUTS_MODE_ENV, l as registerInputsHook, m as withInternalReadsAsync, n as INPUTS_MISMATCH_CODE, o as INPUTS_UNDECLARED_EXIT, p as withInternalReads, q as unwrap, r as INPUTS_MISMATCH_EXIT, s as exitOnInputsError, t as INPUTS_EXPECT_ENV, u as createInputsReader, v as getAuthTokenAsync, y as getRoleAuthTokenAsync, z as isFailure } from "./hook-Cwd8HPw7.mjs";
|
|
2
2
|
import { A as isClientProfile, D as getConfigDir, E as isStrictConfig, O as getConfigFilePath, S as readConfig, T as writeConfig, b as ApiError, h as invalidateClientToken, i as isRoleNotGrantedError, j as isIdentityProfile, k as createDefaultConfig, p as clientAccessToken, s as profileAccessToken, w as updateConfig, x as createFetchClient } from "./profiles-DqDZHbAv.mjs";
|
|
3
3
|
import { syncBuiltinESMExports } from "node:module";
|
|
4
4
|
import fs, { constants } from "node:fs";
|