/** An error whose cause is known as a bounded code (`ERESOLVE`, `ENOENT`, `exit code 1`). */ export class DetailedError extends Error { readonly detail: string; constructor(message: string, detail: string) { super(message); this.detail = detail; } } /** No project was given or linked, and the API key cannot list projects to pick one. */ export class ProjectNotLinkedError extends Error {} export type ErrorCode = | "REQUEST_TIMEOUT" | "NETWORK_ERROR" | "AUTH_FAILED" | "AUTH_BROWSER_FAILED" | "API_ERROR" | "UNKNOWN_COMMAND" | "MISSING_ARGUMENT" | "CREDENTIALS_DELETE_FAILED" | "NPX_NOT_FOUND" | "NEON_INIT_FAILED" | "NON_INTERACTIVE" | "AUTH_TIMEOUT" | "NOT_SIGNED_IN" | "NODE_VERSION_UNSUPPORTED" | "GIT_NOT_FOUND" | "SKILLS_CLI_FAILED" | "AGENT_COMMAND_UNAVAILABLE" | "PLUGINS_CLI_FAILED" | "DEPENDENCY_INSTALL_FAILED" | "LEGACY_FUNCTION_ENV_KEY" | "PROJECT_NOT_LINKED" | "AMBIGUOUS_BRANCH_ROLE" | "FUNCTION_BUILD_UNFINISHED" | "UNKNOWN_ERROR"; // First match wins: a skills CLI failure caused by a missing git is GIT_NOT_FOUND. const ERROR_MATCHERS = [ [/^Unknown command: (.*)$/, "UNKNOWN_COMMAND"], [/^Missing required argument: (.*)$/, "MISSING_ARGUMENT"], [/^Failed to open web browser. (.*)$/, "AUTH_BROWSER_FAILED"], [/^Setup did not finish\.$/, "NEON_INIT_FAILED"], [/^No interactive terminal\./, "NON_INTERACTIVE"], [/^Authentication timed out after /, "AUTH_TIMEOUT"], [ /^Not signed in: .*no terminal to start a browser sign-in/, "NOT_SIGNED_IN", ], [/^neon skills needs Node\.js /, "NODE_VERSION_UNSUPPORTED"], [/needs npx \(Node\.js\)/, "NPX_NOT_FOUND"], [/spawn git ENOENT/, "GIT_NOT_FOUND"], [/^Installing the Neon plugin needs Git, /, "GIT_NOT_FOUND"], [ /^(Failed to install Neon agent skills|skills CLI failed)/, "SKILLS_CLI_FAILED", ], [/^Cannot install the Neon plugin for /, "AGENT_COMMAND_UNAVAILABLE"], [ /^(Failed to install the Neon plugin for: |plugins CLI (failed|timed out))/, "PLUGINS_CLI_FAILED", ], [/^Could not install the Neon dependencies/, "DEPENDENCY_INSTALL_FAILED"], [/^Could not reach neonstatus\.com /, "NETWORK_ERROR"], [/^Timed out waiting for neonstatus\.com /, "REQUEST_TIMEOUT"], [ / (is|are) no longer pulled\. Pull NEON_BRANCH_ID /, "LEGACY_FUNCTION_ENV_KEY", ], [/^No Neon project is linked here/, "PROJECT_NOT_LINKED"], [ / roles and none is "neondb_owner"; cannot auto-pick\./, "AMBIGUOUS_BRANCH_ROLE", ], // Unanchored: checkout wraps the apply error in its own sentence. [ /function deployments were not confirmed complete/, "FUNCTION_BUILD_UNFINISHED", ], ] as const; export const matchErrorCode = (message?: string): ErrorCode => { if (!message) { return "UNKNOWN_ERROR"; } for (const [matcher, code] of ERROR_MATCHERS) { const match = message.match(matcher); if (match) { return code; } } return "UNKNOWN_ERROR"; }; /** * The CLI reports failures it handles by throwing a plain `Error` with the message to print. * One of JavaScript's own error types is a case it did not handle: a bug, or input it never * validated. */ export const isUnexpectedError = (err: unknown): err is Error => err instanceof TypeError || err instanceof ReferenceError || err instanceof RangeError || err instanceof SyntaxError; /** * The single, human-readable line shown when the CLI couldn't reach the Neon API because * of a connection-level failure (DNS, refused/reset connection, offline). It replaces the * cryptic `fetch failed` / empty axios message a network blip otherwise surfaces (see * {@link isNetworkError}), pointing at the two things the user can actually check. */ export const NETWORK_ERROR_MESSAGE = "Could not reach the Neon API. Please check your internet connection and try again. " + "If your connection is fine and this keeps happening, check https://neonstatus.com for ongoing incidents."; /** * Node-level socket/DNS error codes that mean the request never reached the server — a * genuine connectivity problem rather than an API response we should surface. Deliberately * excludes `ECONNABORTED` (axios' timeout), which the CLI already reports as a timeout. */ const NETWORK_ERROR_CODES = new Set([ "ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN", "EPIPE", "EHOSTUNREACH", "ENETUNREACH", "EHOSTDOWN", "ENETDOWN", ]); /** * Message fragments that mark a connection-level failure across our two transports: the * `@neon/sdk` / global `fetch` path (used by `env pull` / `config` / `deploy`, and `link`'s * bundled env pull) throws a bare `TypeError: fetch failed` / "Failed to fetch", while the * axios `api-client` path throws an `AxiosError` whose message is "Network Error". */ const NETWORK_ERROR_MESSAGE_PATTERN = /fetch failed|failed to fetch|network error/i; const readErrorCode = (value: unknown): string | undefined => { if (value === null || typeof value !== "object") return undefined; const code = (value as { code?: unknown }).code; return typeof code === "string" ? code : undefined; }; /** * Whether `err` is a connection-level failure (the network blip the user sees as a cryptic * `fetch failed`, or no message at all on the axios path) rather than an actual API response. * * A Node `fetch` failure is a bare `TypeError: fetch failed` whose underlying `cause` carries * the real socket `code` (e.g. `ECONNREFUSED`, `ENOTFOUND`, `EAI_AGAIN`), so we walk the * `cause` chain checking both the code and the message. This is what lets the CLI swap the * confusing default for {@link NETWORK_ERROR_MESSAGE}. It matches only failures where no * response was ever received, so it never masks a real 4xx/5xx the user needs to see. */ export const isNetworkError = (err: unknown): boolean => { let current: unknown = err; for ( let depth = 0; depth < 6 && current !== null && current !== undefined; depth++ ) { const code = readErrorCode(current); if (code !== undefined && NETWORK_ERROR_CODES.has(code)) { return true; } if ( current instanceof Error && NETWORK_ERROR_MESSAGE_PATTERN.test(current.message) ) { return true; } current = (current as { cause?: unknown }).cause; } return false; }; /** * Stands in for a flag value the CLI rejected. Error messages are sent as `CLI Error` * telemetry, and a value typed into the wrong flag is sometimes a pasted secret, so an error * names only values it can vouch for (a valid choice, a key it knows) and replaces the rest. */ export const REDACTED_INVALID_VALUE = ""; /** * ` Did you mean x?` for rejected values within two edits of a valid choice, else `""`. The * error cannot show what was typed, so a near miss is named by the choice it was close to. */ export const didYouMean = ( rejected: readonly string[], choices: readonly string[], ): string => { const suggestions = [ ...new Set( rejected .map((value) => closestChoice(value, choices)) .filter((choice): choice is string => choice !== undefined), ), ]; return suggestions.length > 0 ? ` Did you mean ${suggestions.join(" or ")}?` : ""; }; const closestChoice = ( value: string, choices: readonly string[], ): string | undefined => { const closest = choices .map((choice) => [choice, editDistance(value, choice)] as const) .sort((a, b) => a[1] - b[1])[0]; return closest && closest[1] <= 2 ? closest[0] : undefined; }; const editDistance = (left: string, right: string): number => { let previous = Array.from( { length: right.length + 1 }, (_, index) => index, ); for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) { const current = [leftIndex]; for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) { current[rightIndex] = Math.min( (previous[rightIndex] ?? 0) + 1, (current[rightIndex - 1] ?? 0) + 1, (previous[rightIndex - 1] ?? 0) + (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1), ); } previous = current; } return previous[right.length] ?? right.length; };