A collection of core utility functions for the Gatsby ecosystem including content hashing, path manipulation, system information, and process coordination
npx @tessl/cli install tessl/npm-gatsby-core-utils@4.15.0Gatsby Core Utils is a comprehensive TypeScript library providing essential utility functions for the Gatsby ecosystem. It offers content hashing, path manipulation, system information detection, CI environment detection, file operations, and process coordination utilities used across various Gatsby packages.
npm install gatsby-core-utilsimport {
createContentDigest,
cpuCoreCount,
isCI,
getCIName,
joinPath,
urlResolve
} from "gatsby-core-utils";For CommonJS:
const {
createContentDigest,
cpuCoreCount,
isCI,
getCIName,
joinPath,
urlResolve
} = require("gatsby-core-utils");import {
createContentDigest,
cpuCoreCount,
isCI,
getCIName,
joinPath
} from "gatsby-core-utils";
// Create content digest for caching
const content = { title: "My Page", body: "Page content" };
const digest = createContentDigest(content);
console.log(digest); // "a1b2c3d4e5f6..."
// Get system information
const cores = cpuCoreCount();
console.log(`Available CPU cores: ${cores}`);
// Detect CI environment
if (isCI()) {
console.log(`Running in CI: ${getCIName()}`);
}
// Safe path joining
const filePath = joinPath("/usr", "local", "bin", "gatsby");
console.log(filePath); // Cross-platform safe pathGatsby Core Utils is organized around several key functional areas:
Content hashing functionality for generating consistent digests used in caching, deduplication, and content identification across Gatsby's build process.
function createContentDigest(input: BinaryLike | string | any): string;Cross-platform path manipulation utilities ensuring consistent path handling across Windows, macOS, and Linux systems.
function joinPath(...paths: Array<string>): string;
function slash(path: string): string;
function urlResolve(...segments: Array<string>): string;
function isNodeInternalModulePath(fileName: string): boolean;System detection utilities for gathering CPU information and CI environment details to optimize build processes.
function cpuCoreCount(ignoreEnvVar?: boolean): number;
function isCI(): boolean;
function getCIName(): string | null;Robust file operations including remote file downloading with built-in caching, retry logic, and error handling.
function fetchRemoteFile(args: IFetchRemoteFileOptions): Promise<string>;
interface IFetchRemoteFileOptions {
url: string;
auth?: {
htaccess_pass?: string;
htaccess_user?: string;
};
httpHeaders?: Headers;
ext?: string;
name?: string;
cacheKey?: string;
excludeDigest?: boolean;
directory?: string;
cache?: GatsbyCache;
}Service locking and process coordination utilities for managing concurrent Gatsby processes and preventing conflicts.
function createServiceLock(
programPath: string,
serviceName: string,
content: Record<string, any>
): Promise<UnlockFn | null>;
function getService<T>(
programPath: string,
serviceName: string,
ignoreLockfile?: boolean
): Promise<T | null>;
type UnlockFn = () => Promise<void>;Configuration file handling and site metadata management for Gatsby projects.
function readConfigFile(root: string): Promise<string>;
function getConfigPath(root: string): string;
function listPlugins(options: { root: string }): Array<string>;Utilities for managing Gatsby page data, HTML generation, and component path parsing.
function fixedPagePath(pagePath: string): string;
function generatePageDataPath(publicDir: string, pagePath: string): string;
function generateHtmlPath(dir: string, outputPath: string): string;
function splitComponentPath(componentPath: string): Array<string>;
function getPathToLayoutComponent(componentPath: string): string;
function getPathToContentComponent(componentPath: string): string;See Configuration Management documentation for complete details on these utilities.
Utility functions for common programming tasks including boolean evaluation and dynamic module loading.
/**
* Checks if a value is truthy based on string, boolean, or numeric evaluation
* @param value - Value to check for truthiness
* @returns true for 'true', true, positive numbers; false otherwise
*/
function isTruthy(value: any): boolean;
/**
* Creates a Node.js require function from a specific file path
* Polyfill for Module.createRequire/createRequireFromPath
* @param filename - File path to create require function from
* @returns Node.js require function scoped to the given path
*/
function createRequireFromPath(filename: string): NodeRequire;Usage Examples:
import { isTruthy, createRequireFromPath } from "gatsby-core-utils";
// Boolean evaluation with various types
console.log(isTruthy(true)); // true
console.log(isTruthy("true")); // true
console.log(isTruthy("false")); // false
console.log(isTruthy(1)); // true
console.log(isTruthy(0)); // false
console.log(isTruthy(-1)); // false
console.log(isTruthy("yes")); // false (not recognized)
// Dynamic require from specific paths
const requireFromSite = createRequireFromPath("/path/to/gatsby-site/gatsby-config.js");
const sitePackage = requireFromSite("./package.json");
const gatsbyPlugin = requireFromSite("gatsby-plugin-sharp");Cryptographically secure UUID v4 generation using Node.js crypto module.
/**
* UUID namespace containing UUID generation functions
*/
namespace uuid {
/**
* Generates a random UUID v4 string
* @returns UUID v4 string in standard format (xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx)
*/
function v4(): string;
}Usage Examples:
import { uuid } from "gatsby-core-utils";
// Generate unique identifiers
const pageId = uuid.v4();
console.log(pageId); // "f47ac10b-58cc-4372-a567-0e02b2c3d479"
// Use in build processes
const buildId = uuid.v4();
const cacheKey = `build-${buildId}`;
// Generate unique file names
const uniqueFileName = `temp-${uuid.v4()}.json`;Converts Gatsby's file-based routing syntax to Express-style route patterns.
/**
* Converts Gatsby file-based route syntax to Express-style patterns
* Transforms [id] to :id and [...id] to *id for route matching
* @param srcPagesPath - Source page path with Gatsby route syntax
* @returns Express-style route pattern or undefined if no dynamic segments
*/
function getMatchPath(srcPagesPath: string): string | undefined;Usage Examples:
import { getMatchPath } from "gatsby-core-utils";
// Dynamic route transformations
console.log(getMatchPath("/blog/[slug]/"));
// "/blog/:slug"
console.log(getMatchPath("/products/[...category]/"));
// "/products/*category"
console.log(getMatchPath("/docs/[...]/"));
// "/docs/*"
console.log(getMatchPath("/static-page/"));
// undefined (no dynamic segments)
// Use in routing setup
const dynamicRoutes = [
"src/pages/blog/[slug].js",
"src/pages/products/[...category].js",
"src/pages/user/[id]/settings.js"
].map(path => ({
path,
matchPath: getMatchPath(path)
})).filter(route => route.matchPath);
console.log(dynamicRoutes);
// [
// { path: "src/pages/blog/[slug].js", matchPath: "src/pages/blog/:slug.js" },
// { path: "src/pages/products/[...category].js", matchPath: "src/pages/products/*category.js" },
// { path: "src/pages/user/[id]/settings.js", matchPath: "src/pages/user/:id/settings.js" }
// ]Gatsby Core Utils respects several environment variables for configuration:
GATSBY_CPU_COUNT - Override CPU core count detection ("logical_cores", "physical_cores", or number)GATSBY_CONCURRENT_DOWNLOAD - Maximum concurrent downloads (default: 50)GATSBY_STALL_RETRY_LIMIT - Retry attempts for stalled downloads (default: 3)GATSBY_STALL_TIMEOUT - Stall timeout in milliseconds (default: 30000)GATSBY_CONNECTION_TIMEOUT - Connection timeout in milliseconds (default: 30000)GATSBY_INCOMPLETE_RETRY_LIMIT - Retry attempts for incomplete downloads (default: 3)