All files / packages/fds-uif/core/src resolve.ts

95.74% Statements 45/47
96% Branches 24/25
100% Functions 8/8
95.74% Lines 45/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226                                          39x   20x 20x                   21x     21x               10x           21x 2x   19x 1x   18x                               41x     41x 1x       40x 1x     39x       39x 39x   1x       38x 18x 18x       20x     20x 20x   3x 2x   1x       17x 17x   41x                                                                                         20x 20x   20x                                                           2x   2x 1x     1x 1x 1x   1x   1x             6x               3x    
/**
 * @fds-uif/core - Resolution Utilities
 *
 * Utilities for resolving UIF `extends` chains and loading UIF files.
 */
 
import { readFile } from 'node:fs/promises';
import { dirname, resolve as resolvePath, isAbsolute } from 'node:path';
import { UifCircularDependencyError, UifExtensionError } from './errors.js';
import { mergeAndClean } from './merge.js';
import { PROP_EXTENDS } from './constants.js';
import type { UifWithExtends, PlainObject, ResolveOptions } from './types.js';
 
// ============================================================================
// File Loading
// ============================================================================
 
/**
 * Load and parse a JSON file.
 */
async function loadJsonFile<T>(filePath: string, loader?: (path: string) => Promise<string>): Promise<T> {
  const content = loader ? await loader(filePath) : await readFile(filePath, 'utf-8');
 
  try {
    return JSON.parse(content) as T;
  } catch (error) {
    throw new Error(`Failed to parse JSON at "${filePath}": ${(error as Error).message}`);
  }
}
 
/**
 * Resolve a relative path from a base file path.
 */
function resolveRelativePath(basePath: string, relativePath: string): string {
  Iif (isAbsolute(relativePath)) {
    return relativePath;
  }
  return resolvePath(dirname(basePath), relativePath);
}
 
// ============================================================================
// Caching
// ============================================================================
 
/** Default cache for resolved files */
const defaultCache = new Map<string, PlainObject>();
 
/**
 * Get the cache to use based on options.
 */
function getCache(options: ResolveOptions): Map<string, PlainObject> | null {
  if (options.cache === true) {
    return defaultCache;
  }
  if (options.cache instanceof Map) {
    return options.cache;
  }
  return null;
}
 
// ============================================================================
// Resolution Implementation
// ============================================================================
 
/**
 * Internal recursive implementation of resolveExtends.
 */
async function resolveExtendsRecursive<T extends PlainObject>(
  filePath: string,
  visited: Set<string>,
  options: ResolveOptions,
  cache: Map<string, PlainObject> | null,
): Promise<T> {
  const normalizedPath = resolvePath(filePath);
 
  // Check for circular dependency
  if (visited.has(normalizedPath)) {
    throw new UifCircularDependencyError([...visited, normalizedPath]);
  }
 
  // Check cache
  if (cache?.has(normalizedPath)) {
    return cache.get(normalizedPath) as T;
  }
 
  visited.add(normalizedPath);
 
  // Load the UIF file
  let uif: UifWithExtends;
  try {
    uif = await loadJsonFile<UifWithExtends>(normalizedPath, options.loadFile);
  } catch (error) {
    throw new UifExtensionError(normalizedPath, normalizedPath, (error as Error).message);
  }
 
  // If no extends, this is a base definition
  if (!uif[PROP_EXTENDS]) {
    cache?.set(normalizedPath, uif);
    return uif as T;
  }
 
  // Resolve the base file
  const basePath = resolveRelativePath(normalizedPath, uif[PROP_EXTENDS]);
 
  let base: PlainObject;
  try {
    base = await resolveExtendsRecursive(basePath, visited, options, cache);
  } catch (error) {
    if (error instanceof UifCircularDependencyError) {
      throw error;
    }
    throw new UifExtensionError(normalizedPath, uif[PROP_EXTENDS], (error as Error).message);
  }
 
  // Merge and cache result
  const result = mergeAndClean(base, uif, { onWarning: options.onWarning }) as T;
  cache?.set(normalizedPath, result);
 
  return result;
}
 
// ============================================================================
// Public API
// ============================================================================
 
/**
 * Recursively resolve a UIF file's `extends` chain.
 *
 * This function:
 * 1. Loads the UIF file
 * 2. If `extends` is present, recursively resolves the base UIF
 * 3. Merges the current UIF onto the resolved base
 * 4. Returns the fully merged result with `extends` removed
 *
 * @param filePath - Path to the UIF file to resolve
 * @param options - Resolution options
 * @returns The fully resolved and merged UIF definition
 *
 * @throws {UifExtensionError} If the base file cannot be found or loaded
 * @throws {UifCircularDependencyError} If a circular extends chain is detected
 *
 * @example
 * ```ts
 * import { resolveExtends } from '@fds-uif/core';
 *
 * // Basic usage
 * const resolved = await resolveExtends('./badge.slds.uif.json');
 *
 * // With caching for better performance
 * const resolved = await resolveExtends('./badge.slds.uif.json', {
 *   cache: true,
 * });
 *
 * // With custom cache
 * const cache = new Map();
 * const resolved1 = await resolveExtends('./badge.slds.uif.json', { cache });
 * const resolved2 = await resolveExtends('./button.slds.uif.json', { cache });
 * ```
 */
export async function resolveExtends<T extends PlainObject>(
  filePath: string,
  options: ResolveOptions = {},
): Promise<T> {
  const visited = new Set<string>();
  const cache = getCache(options);
 
  return resolveExtendsRecursive<T>(filePath, visited, options, cache);
}
 
/**
 * Resolve a UIF object's `extends` chain when you already have the object in memory.
 *
 * @param uif - The UIF object to resolve
 * @param basePath - Base path for resolving relative extends references
 * @param options - Resolution options
 * @returns The fully resolved and merged UIF definition
 *
 * @example
 * ```ts
 * const system = {
 *   apiVersion: '1.0.0',
 *   extends: './badge.foundation.uif.json',
 *   structure: { ... }
 * };
 *
 * const resolved = await resolveExtendsFromObject(
 *   system,
 *   '/path/to/badge.slds.uif.json'
 * );
 * ```
 */
export async function resolveExtendsFromObject<T extends PlainObject>(
  uif: PlainObject,
  basePath: string,
  options: ResolveOptions = {},
): Promise<T> {
  const extendsPath = uif[PROP_EXTENDS];
 
  if (!extendsPath || typeof extendsPath !== 'string') {
    return uif as T;
  }
 
  const visited = new Set<string>();
  const cache = getCache(options);
  const resolvedBasePath = resolveRelativePath(basePath, extendsPath);
 
  const base = await resolveExtendsRecursive<PlainObject>(resolvedBasePath, visited, options, cache);
 
  return mergeAndClean(base, uif, { onWarning: options.onWarning }) as T;
}
 
/**
 * Check if a UIF definition extends another.
 */
export function hasExtends(uif: unknown): uif is UifWithExtends & { extends: string } {
  return typeof uif === 'object' && uif !== null && typeof (uif as UifWithExtends)[PROP_EXTENDS] === 'string';
}
 
/**
 * Clear the default resolution cache.
 * Call this if you need to re-read files that may have changed.
 */
export function clearResolveCache(): void {
  defaultCache.clear();
}