Files
webstudio/packages/cli/src/api-connection.ts
T
Oleg Isonen c389cd3bb2 fix: classify errors with structured codes and types (#6539)
Invalid or revoked share links now return an actionable 401 response
instead of an unexpected server error. Missing project and workspace
records receive distinct responses at their lookup sites. Token,
project, and workspace lookups use `.maybeSingle()` and rely on database
uniqueness. Missing projects have an explicit `ProjectNotFoundError`;
the loader no longer interprets `PGRST116`.

The API preserves `UNAUTHORIZED` and `INVALID_AUTH_TOKEN` when
authorization fails during context creation, so CLI and MCP clients can
offer relinking guidance without inspecting error text. Tokens without
API access carry `API_ACCESS_DISABLED`.

A repository audit replaces error-message matching with typed errors,
stable codes, or structured diagnostics in CLI argument/configuration
handling, session conflicts, preview cleanup, import retries, domain
unpublishing, asset validation, JSX/expression diagnostics, CSS
validation, and publish diagnostics. `AGENTS.md` now explicitly
prohibits message-based error classification and recovery.

The existing build-permission preflight now advertises structured
import-error support. Clients upload assets before importing into older
servers that do not advertise it; newer servers keep selective retries
using structured missing-file details. The internal template-validation
error class remains outside public JSX bindings and input descriptions.

Shared Builder `parseError` normalizes tRPC and local validation errors,
so UI components only add display context instead of decoding transport
payloads.

Simplification removes three redundant error classes, catch-and-ignore
handlers, an unused formatter, and nested loader error handling.
Unpublishing an already unpublished domain succeeds after authorization.
CLI configuration failures use the existing shared error handling, and
plan parsing catches only JSON parsing failures.

Validation: affected suites passed (271 tests across 8 suites in the
latest simplification checks), affected package typechecks passed, and
lint, package-boundary checks, and `git diff --check` passed. The audit
replaced synthetic parser branches and private-method assertions with
actual tRPC round trips, PostgREST responses, and public VM behavior.
Controlled regressions confirmed that removing serialized validation
details and exposing the internal JSX error class both fail the revised
tests. Astra reviewed the production changes at medium effort; its
compatibility finding and the GitHub JSX-binding comment are fixed, and
follow-up review found no remaining substantive issues.
2026-10-16 12:14:57 +02:00

71 lines
2.1 KiB
TypeScript

import { CliError } from "./errors";
import { readFile } from "node:fs/promises";
import { cwd } from "node:process";
import { join } from "node:path";
import {
GLOBAL_CONFIG_FILE,
LOCAL_CONFIG_FILE,
jsonToGlobalConfig,
jsonToLocalConfig,
} from "./config";
import { isFileExists } from "./fs-utils";
export type ApiConnection = {
origin: string;
authToken: string;
projectId: string;
headers?: Record<string, string | undefined>;
};
export type ApiConnectionDependencies = {
isFileExists: typeof isFileExists;
readFile: (path: string, encoding: "utf-8") => Promise<string>;
};
export const defaultApiConnectionDependencies: ApiConnectionDependencies = {
isFileExists,
readFile,
};
export const resolveApiConnection = async (
dependencies = defaultApiConnectionDependencies,
projectRoot = cwd(),
projectId?: string
): Promise<ApiConnection> => {
const isExplicitProject = projectId !== undefined;
if (projectId === undefined) {
const localConfigFile = join(projectRoot, LOCAL_CONFIG_FILE);
if ((await dependencies.isFileExists(localConfigFile)) === false) {
throw new CliError(
"NOT_INITIALIZED",
"Local config file is not found. Run webstudio init --link <api-share-link> from a Webstudio project."
);
}
projectId = jsonToLocalConfig(
JSON.parse(await dependencies.readFile(localConfigFile, "utf-8"))
).projectId;
}
if (projectId.trim() === "") {
throw new CliError("INVALID_ARGUMENT", "Project id must not be empty.");
}
const globalConfig = jsonToGlobalConfig(
JSON.parse(await dependencies.readFile(GLOBAL_CONFIG_FILE, "utf-8"))
);
const projectConfig = globalConfig[projectId];
if (projectConfig === undefined) {
throw new CliError(
"NOT_INITIALIZED",
isExplicitProject
? `Project config for "${projectId}" is not found. Run webstudio init --link <api-share-link> once to save its credentials.`
: "Project config is not found. Run webstudio init --link <api-share-link>."
);
}
return {
origin: projectConfig.origin,
authToken: projectConfig.token,
projectId,
};
};