Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions packages/contentstack-utilities/src/chalk.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
/**
* Chalk 5 is ESM-only. We load it via dynamic import and cache for use in CommonJS.
*
* More than one physical copy of this package can load in one process (e.g. pnpm).
* Cache on globalThis via Symbol.for so loadChalk() from any copy warms getChalk() for all.
*/
let chalkInstance: typeof import('chalk').default | null = null;

export type ChalkInstance = typeof import('chalk').default;

const chalkGlobal = Symbol.for('@contentstack/cli-utilities/chalk');

function readCached(): ChalkInstance | undefined {
return (globalThis as unknown as Record<symbol, ChalkInstance | undefined>)[chalkGlobal];
}

function writeCached(chalkInstance: ChalkInstance): void {
(globalThis as unknown as Record<symbol, ChalkInstance>)[chalkGlobal] = chalkInstance;
}

/**
* Load chalk (ESM) and cache it. Call this once during CLI init before any chalk usage.
*/
export async function loadChalk(): Promise<ChalkInstance> {
let chalkInstance = readCached();
if (!chalkInstance) {
const chalkModule = await import('chalk');
chalkInstance = chalkModule.default;
writeCached(chalkInstance);
}
return chalkInstance;
}
Expand All @@ -20,6 +33,7 @@ export async function loadChalk(): Promise<ChalkInstance> {
* Get the cached chalk instance. Must call loadChalk() first (e.g. in init hook).
*/
export function getChalk(): ChalkInstance {
const chalkInstance = readCached();
if (!chalkInstance) {
throw new Error('Chalk not loaded. Ensure loadChalk() is called during init (e.g. in utils-init hook).');
}
Expand Down
Loading