// Modified from: https://raw.githubusercontent.com/epoberezkin/fast-deep-equal/master/src/index.jst // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-nocheck This file is copied from a JS project, so it's not type-safe. import { colors } from "@cliffy/ansi/colors"; import * as log from "../core/log.ts"; import nodePath, { sep as SEP } from "node:path"; import crypto from "node:crypto"; import { readFileSync, realpathSync, writeFileSync } from "node:fs"; import { readdir, readFile } from "node:fs/promises"; import { fetchVersion } from "../core/context.ts"; import { updateGlobalVersions } from "../commands/sync/global.ts"; import { isRawAppPath } from "./resource_folders.ts"; import { VERSION } from "../core/constants.ts"; export function deepEqual(a: T, b: T): boolean { if (a === b) return true; if (a && b && typeof a === "object" && typeof b === "object") { if (a.constructor !== b.constructor) return false; let length, i; if (Array.isArray(a)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0; ) { if (!deepEqual(a[i], b[i])) return false; } return true; } if (a instanceof Map && b instanceof Map) { if (a.size !== b.size) return false; for (i of a.entries()) { if (!b.has(i[0])) return false; } for (i of a.entries()) { if (!deepEqual(i[1], b.get(i[0]))) return false; } return true; } if (a instanceof Set && b instanceof Set) { if (a.size !== b.size) return false; for (i of a.entries()) { if (!b.has(i[0])) return false; } return true; } if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0; ) { if (a[i] !== b[i]) return false; } return true; } if (a.constructor === RegExp) { return a.source === b.source && a.flags === b.flags; } if (a.valueOf !== Object.prototype.valueOf) { return a.valueOf() === b.valueOf(); } if ( a.toString !== Object.prototype.toString && typeof a.toString == "function" ) { return a.toString() === b.toString(); } const keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0; ) { if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; } for (i = length; i-- !== 0; ) { const key = keys[i]; if (!deepEqual(a[key], b[key])) return false; } return true; } // true if both NaN, false otherwise return a !== a && b !== b; } export function getHeaders(): Record | undefined { const headers = process.env["HEADERS"]; if (headers) { const parsedHeaders = Object.fromEntries( headers.split(",").map((h) => h.split(":").map((s) => s.trim())) ); log.debug( "Headers from env keys: " + JSON.stringify(Object.keys(parsedHeaders)) ); return parsedHeaders; } else { return undefined; } } export async function digestDir(path: string, conf: string) { const hashes: string = []; const entries = await readdir(path, { withFileTypes: true }); entries.sort((a, b) => a.name.localeCompare(b.name)); for (const e of entries) { const npath = path + "/" + e.name; if (e.isFile()) { hashes.push(await generateHashFromBuffer(await readFile(npath))); } else if (e.isDirectory() && !e.isSymbolicLink()) { hashes.push(await digestDir(npath, "")); } } return await generateHash(hashes.join("") + conf); } export async function generateHash(content: string): Promise { const messageBuffer = new TextEncoder().encode(content); return await generateHashFromBuffer(messageBuffer); } export async function generateHashFromBuffer( content: BufferSource ): Promise { const hashBuffer = await crypto.subtle.digest("SHA-256", content); return Buffer.from(hashBuffer).toString("hex"); } function decodeBufferAsUtf8(buf: Buffer, path: string | URL): string { if (buf.length >= 2) { if (buf[0] === 0xff && buf[1] === 0xfe) { if (buf.length >= 4 && buf[2] === 0x00 && buf[3] === 0x00) { throw new Error( `File ${path} is encoded as UTF-32 LE, which is not supported. Please convert it to UTF-8.` ); } throw new Error( `File ${path} is encoded as UTF-16 LE, which is not supported. Please convert it to UTF-8.` ); } if (buf[0] === 0xfe && buf[1] === 0xff) { throw new Error( `File ${path} is encoded as UTF-16 BE, which is not supported. Please convert it to UTF-8.` ); } if (buf.length >= 4 && buf[0] === 0x00 && buf[1] === 0x00 && buf[2] === 0xfe && buf[3] === 0xff) { throw new Error( `File ${path} is encoded as UTF-32 BE, which is not supported. Please convert it to UTF-8.` ); } } if (buf.length >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf) { return buf.subarray(3).toString("utf-8"); } return buf.toString("utf-8"); } export function stripBom(content: string): string { if (content.charCodeAt(0) === 0xfeff) { return content.slice(1); } return content; } export async function readTextFile(path: string | URL): Promise { return decodeBufferAsUtf8(await readFile(path), path); } export function readTextFileSync(path: string | URL): string { return decodeBufferAsUtf8(readFileSync(path), path); } function isWithin(base: string, target: string): boolean { const rel = nodePath.relative(base, target); return ( rel !== "" && rel !== ".." && !rel.startsWith(".." + SEP) && !nodePath.isAbsolute(rel) ); } /** * Resolve an `!inline` reference against `root` (the sync root by default) and * refuse one that lands outside it, directly or through a symlink. References * are tracked data a pull can write verbatim, so following one must never read * a file the checkout does not hold. */ export function inlinePathWithin(ref: string, root: string = "."): string { const base = nodePath.resolve(root); const target = nodePath.resolve(base, ref.replaceAll("/", SEP)); let inside = isWithin(base, target); if (inside) { let realBase: string; let realTarget: string; try { realBase = realpathSync(base); realTarget = realpathSync(target); } catch { // Nothing to follow yet: the caller's read reports the missing file. return target; } inside = isWithin(realBase, realTarget); } if (!inside) { throw new Error( `'!inline ${ref}' refers to a file outside ${base}; inline references must stay within it`, ); } return target; } export function readInlinePathSync(path: string, root: string = "."): string { const target = inlinePathWithin(path, root); try { return readTextFileSync(target); } catch (error) { log.warn(`Error reading inline path: ${path}, ${error}`); return ""; } } export function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } export function isFileResource(path: string): boolean { const splitPath = path.split("."); // Check for pattern: *.resource.file.* (handles both base and branch-specific) return ( splitPath.length >= 4 && splitPath[splitPath.length - 3] == "resource" && splitPath[splitPath.length - 2] == "file" ); } /** * Local resource path -> the resource's path on the server. The suffix is * `.resource.` on a metadata file but `.resource.file.` on a * file resource, so its length depends on which of the two the path is. */ export function removeResourceSuffix(path: string): string { if (isFileResource(path)) { // isFileResource only matches a dotless extension, so the resource path is // everything before the trailing `resource`, `file`, `` segments. return path.split(".").slice(0, -3).join("."); } return path.replace(/\.resource\.(yaml|json)$/, ""); } /** Matches children inside a .fileset/ directory, not the directory itself. */ export function isFilesetResource(path: string): boolean { return path.includes(".fileset/") || path.includes(".fileset\\"); } export function isRawAppFile(path: string): boolean { return isRawAppPath(path); } /** Sync paths carry the platform separator: `dependencies\x` on Windows. */ export function isWorkspaceDependencies(path: string): boolean { return path.startsWith("dependencies/") || path.startsWith("dependencies\\"); } export function printSync(input: string | Uint8Array) { process.stdout.write( typeof input === "string" ? input : Buffer.from(input) ); } // Repository interface for shared selection logic export interface Repository { git_repo_resource_path: string; } // Shared repository selection logic export async function selectRepository( repositories: T[], operation?: string ): Promise { if (repositories.length === 0) { throw new Error("No git-sync repositories configured in workspace"); } if (repositories.length === 1) { const repoPath = repositories[0].git_repo_resource_path.replace( /^\$res:/, "" ); log.info(colors.cyan(`Auto-selected repository: ${colors.bold(repoPath)}`)); return repositories[0]; } // Check if we're in a non-interactive environment const isInteractive = !!process.stdin.isTTY && !!process.stdout.isTTY; if (!isInteractive) { const repoPaths = repositories.map((r) => r.git_repo_resource_path.replace(/^\$res:/, "") ); throw new Error( `Multiple repositories found: ${repoPaths.join( ", " )}. Use --repository to specify which one to ${operation || "use"}.` ); } // Import Select dynamically to avoid dependency issues const { Select } = await import("@cliffy/prompt/select"); console.log( `\nMultiple repositories found. Please select which repository to ${ operation || "use" }:\n` ); const selectedRepo = await Select.prompt({ message: `Select repository for ${operation || "operation"}:`, options: repositories.map((repo, index) => { const displayPath = repo.git_repo_resource_path.replace(/^\$res:/, ""); return { name: `${index + 1}. ${displayPath}`, value: repo.git_repo_resource_path, }; }), }); return repositories.find((r) => r.git_repo_resource_path === selectedRepo)!; } let isWin: boolean | undefined = undefined; export async function getIsWin(): Promise { if (isWin === undefined) { const os = await import("node:os"); isWin = os.platform() === "win32"; } return isWin; } /** * Writes content to a file only if it differs from existing content. * Creates parent directories if they don't exist. * * @param path - The file path to write to * @param content - The content to write * @returns true if file was written, false if skipped (content unchanged) */ export function writeIfChanged(path: string, content: string): boolean { try { const existing = readTextFileSync(path); if (existing === content) { return false; // Content unchanged, skip write } } catch (error: any) { // File doesn't exist or can't be read, proceed with write if (error?.code !== "ENOENT") { // If it's not a "not found" error, we might want to know about it // but still proceed with the write attempt } } writeFileSync(path, content, "utf-8"); return true; // File was written } export async function fetchRemoteVersion( workspace: Workspace ): Promise { const version = await fetchVersion(workspace.remote, workspace.token); if (version) { updateGlobalVersions(version); } log.info(colors.gray("CLI version: " + VERSION)); log.info(colors.gray("Remote version: " + version)); } export function toCamel(s: string) { return s.replace(/([-_][a-z])/gi, ($1) => { return $1.toUpperCase().replace("-", "").replace("_", ""); }); } export function capitalize(str: string): string { return str.charAt(0).toUpperCase() + str.slice(1); } export function formatTimestamp(ts: string): string { return new Date(ts).toISOString().replace("T", " ").substring(0, 19); } /** Whether the server refused the request's credential (HTTP 401). */ export function isUnauthorized(e: unknown): boolean { return ( !!e && typeof e === "object" && "name" in e && e.name === "ApiError" && (e as { status?: number }).status === 401 ); } /** * The server does not say why it refused a token, so this only names the likely cause for a * token that worked before: one bound to a single workspace is refused everywhere else. */ export const BOUND_TOKEN_HINT = "If this token was created for a single workspace, other workspaces and instance-level " + "commands refuse it: log in again and pick 'All workspaces' on the login page, or create " + "one with `wmill token create --all-workspaces`."; /** * ": " for an error thrown by the generated API client, * undefined for anything else. Backend source references such as * `(flows.rs:1400)` are stripped from the body. */ export function apiErrorMessage(e: unknown): string | undefined { if (!(e && typeof e === "object" && "name" in e && e.name === "ApiError")) { return undefined; } const { body, statusText } = e as { body?: unknown; statusText?: string }; const bodyStr = typeof body === "object" && body !== null ? JSON.stringify(body) : String(body ?? ""); return statusText + ": " + bodyStr.replace(/\s*[@(]\w+\.rs:\d+[:\d]*\)?/g, ""); } function fetchFailureCause( e: unknown, ): { code?: string; message?: string } | undefined { if (!(e instanceof TypeError)) { return undefined; } if (e.message === "fetch failed") { const cause = (e as { cause?: unknown }).cause; return cause && typeof cause === "object" ? (cause as { code?: string; message?: string }) : {}; } // Bun puts the code on the error itself. Node's own argument errors carry an `ERR_` code // too, and are not network failures. const code = (e as { code?: unknown }).code; return typeof code === "string" && !code.startsWith("ERR_") ? { code, message: e.message } : undefined; } /** * A readable message for a request that got no response from the server, which Node reports * as a bare "fetch failed" with the actual reason in `cause`. Undefined for anything else. */ export function networkErrorMessage(e: unknown): string | undefined { const cause = fetchFailureCause(e); if (!cause) { return undefined; } const detail = [cause.message, cause.code && `(${cause.code})`] .filter(Boolean) .join(" "); if (cause.code === "UND_ERR_HEADERS_TIMEOUT") { return ( `The Windmill server did not respond in time: ${detail}. ` + `It may still be processing the request.` ); } if (cause.code !== undefined && NO_RESPONSE_CODES.has(cause.code)) { return ( `The connection to the Windmill server closed before it responded: ${detail}. ` + `It may still be processing the request.` ); } return `Could not reach the Windmill server: ${detail || "fetch failed"}`; } const NO_RESPONSE_CODES = new Set([ "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "UND_ERR_SOCKET", "ECONNRESET", ]); /** * True when a request was sent but its outcome is unknown: the client timed out, the * connection dropped mid-request, or a proxy in front of the server gave up (502/504). * The server may still complete the request. */ export function isNoResponseError(e: unknown): boolean { const cause = fetchFailureCause(e); if (cause) { return cause.code !== undefined && NO_RESPONSE_CODES.has(cause.code); } if (e && typeof e === "object" && "name" in e && e.name === "ApiError") { const status = (e as { status?: number }).status; return status === 502 || status === 504; } return false; } /** * Validate that required arguments are present when no -d data was provided. * Fetches the schema from the API and checks required fields. * @param schema - The JSON schema object from the script/flow definition * @throws Error if required arguments are missing */ export function validateRequiredArgs( schema: Record | undefined | null, ): void { const required = (schema as { required?: string[] })?.required ?? []; if (required.length > 0) { throw new Error( `Missing required arguments: ${required.join(", ")}.\nUse -d '{"${required[0]}": ...}' to provide input data.` ); } }