From 71ee6e835c8c0af97c7bb77627409fa1d7d89428 Mon Sep 17 00:00:00 2001 From: leaysgur <6259812+leaysgur@users.noreply.github.com> Date: Tue, 16 Dec 2025 11:39:42 +0000 Subject: [PATCH] refactor(oxfmt): Allow to call `setupConfig()` multiple times (#16934) For exposing the Node.js API's `format()` method; I did not expect for it being called multiple times, so fix it. --- apps/oxfmt/src-js/prettier-proxy.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/apps/oxfmt/src-js/prettier-proxy.ts b/apps/oxfmt/src-js/prettier-proxy.ts index 1a4d2baf888f8..e567fcc07f819 100644 --- a/apps/oxfmt/src-js/prettier-proxy.ts +++ b/apps/oxfmt/src-js/prettier-proxy.ts @@ -2,8 +2,12 @@ import Tinypool from "tinypool"; import type { WorkerData, FormatEmbeddedCodeArgs, FormatFileArgs } from "./prettier-worker.ts"; // Worker pool for parallel Prettier formatting +// Used by each exported function let pool: Tinypool | null = null; +type SetupResult = string[]; +let setupCache: SetupResult | null = null; + // --- /** @@ -13,14 +17,17 @@ let pool: Tinypool | null = null; * @param numThreads - Number of worker threads to use (same as Rayon thread count) * @returns Array of loaded plugin's `languages` info * */ -export async function setupConfig(configJSON: string, numThreads: number): Promise { +export async function setupConfig(configJSON: string, numThreads: number): Promise { + // NOTE: When called from CLI, it's only called once at the beginning. + // However, when called via API, like `format(fileName, code)`, it may be called multiple times. + // Therefore, allow it by returning cached result. + if (setupCache !== null) return setupCache; + const workerData: WorkerData = { // SAFETY: Always valid JSON constructed by Rust side prettierConfig: JSON.parse(configJSON), }; - if (pool) throw new Error("`setupConfig()` has already been called"); - // Initialize worker pool for parallel Prettier formatting // Pass config via workerData so all workers get it on initialization pool = new Tinypool({ @@ -34,7 +41,9 @@ export async function setupConfig(configJSON: string, numThreads: number): Promi // - Read `plugins` field // - Load plugins dynamically and parse `languages` field // - Map file extensions and filenames to Prettier parsers - return []; + setupCache = []; + + return setupCache; } // ---