All files / packages/design-tokens/src/style-dictionary/utils path-resolution.js

100% Statements 13/13
100% Branches 6/6
100% Functions 2/2
100% Lines 12/12

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                2x 2x 2x                   2x 53x 1x     52x       52x 52x 2x     50x                 12x  
import path from 'path';
import { fileURLToPath } from 'url';
 
/**
 * Resolves the package root directory relative to this file's location.
 * This file is at: src/style-dictionary/utils/path-resolution.js
 * Package root is: two levels up (../..)
 */
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const packageRoot = path.resolve(__dirname, '../../..');
 
/**
 * Resolves a path relative to the package root directory.
 * This ensures paths are resolved correctly regardless of the current working directory.
 *
 * @param {string} relativePath - Path relative to package root (e.g., 'dist/config/', 'src/tokens/common/config.json')
 * @returns {string} Absolute path resolved from package root
 * @throws {Error} If an absolute path is provided or if the resolved path is outside package boundaries
 */
export const resolvePackagePath = (relativePath) => {
  if (path.isAbsolute(relativePath)) {
    throw new Error(`resolvePackagePath expects relative paths, got absolute: ${relativePath}`);
  }
 
  const resolved = path.resolve(packageRoot, relativePath);
 
  // Ensure resolved path is within package boundaries (prevent path traversal attacks)
  // Use path.relative() for cross-platform compatibility (Windows uses \ while Unix uses /)
  const relative = path.relative(packageRoot, resolved);
  if (relative.startsWith('..') || path.isAbsolute(relative)) {
    throw new Error(`Path '${relativePath}' resolves outside package root`);
  }
 
  return resolved;
};
 
/**
 * Gets the package root directory path.
 * Useful for testing and other utilities that need to know the package root.
 *
 * @returns {string} Absolute path to package root
 */
export const getPackageRoot = () => packageRoot;