Config API Reference

Config API Reference

Package Import

import {
  resolveConfigPath,
  parseConfig,
  checkRuntimeVersion,
  validateContext,
  validateBundleRestrictions,
  parseMainField,
  resolveMounts,
  detectNamespaceCollisions,
  loadExtensions,
  buildExtensionBindings,
  buildContextBindings,
  buildResolvers,
  loadProject,
  introspectHandler,
  marshalCliArgs,
} from '@rcrsr/rill-config';

The package path is @rcrsr/rill-config. All functions, types, and error classes documented here are public exports.


Process Isolation Contract

The library never calls process.exit(). It never writes to process.stdout or process.stderr. It never reads process.env. Callers supply all environment variables via the env parameter on each function that requires them.


.env Auto-Loading

The rill-run CLI loads .env automatically using dotenv before calling library functions. The library itself never calls dotenv.config().

Embedded callers must supply pre-resolved environment variables. Resolve your .env file before passing values to parseConfig or loadProject:

import { config } from 'dotenv';
import { loadProject } from '@rcrsr/rill-config';

// Caller resolves .env; library receives pre-resolved values
const env = config().parsed ?? {};

const result = await loadProject({
  configPath: './rill.config.json',
  env,
  rillVersion: '1.2.0',
});

Exported Functions

resolveConfigPath

resolveConfigPath(options: { configFlag?: string; cwd: string }): string

Locates the config file path. Walks ancestor directories from cwd when configFlag is absent.

ParameterTypeRequiredDescription
options.configFlagstringNoExplicit path from --config CLI flag
options.cwdstringYesWorking directory to begin the ancestor walk

Returns: Absolute path to the config file.

Throws: ConfigNotFoundError (EC-1) when no config file is found.


parseConfig

parseConfig(raw: string, env: Record<string, string>): RillConfigFile

Parses and validates a raw JSON config string. Substitutes ${VAR} references using env.

ParameterTypeRequiredDescription
rawstringYesRaw JSON content of the config file
envRecord<string, string>YesPre-resolved environment variables

Returns: Validated RillConfigFile.

Throws: ConfigParseError (EC-2) on invalid JSON. Throws ConfigEnvError (EC-3) on missing env vars. Throws ConfigValidationError (EC-4) on invalid field types or orphaned config keys.


checkRuntimeVersion

checkRuntimeVersion(constraint: string, installedVersion: string): void

Validates that installedVersion satisfies the semver constraint from the config file.

ParameterTypeRequiredDescription
constraintstringYesSemver constraint string (e.g., ">=1.0.0")
installedVersionstringYesInstalled rill version string

Returns: void on success.

Throws: RuntimeVersionError (EC-5) on version mismatch or invalid semver constraint.


validateContext

validateContext(context: ContextBlock): Record<string, unknown>

Validates context values against their schema types.

ParameterTypeRequiredDescription
contextContextBlockYesContext block from the config file

Returns: Validated context values as a plain object.

Throws: ContextValidationError (EC-12) on missing values or type mismatches.


validateBundleRestrictions

validateBundleRestrictions(config: RillConfigFile): void

Checks that the config file contains no fields prohibited at bundle time.

ParameterTypeRequiredDescription
configRillConfigFileYesParsed config to validate

Returns: void on success.

Throws: BundleRestrictionError (EC-14) when prohibited fields are present.


parseMainField

parseMainField(main: string): { filePath: string; handlerName?: string }

Parses the main field of the config file into its file path and optional handler name.

ParameterTypeRequiredDescription
mainstringYesRaw main field value (e.g., "script.rill" or "script.rill::handler")

Returns: Object with filePath and optional handlerName.

Throws: ConfigValidationError (EC-4) on empty path or invalid format.


resolveMounts

resolveMounts(mounts: Record<string, string>): ResolvedMount[]

Validates and resolves raw mount definitions from the config into structured ResolvedMount objects.

ParameterTypeRequiredDescription
mountsRecord<string, string>YesRaw mount map from the config file

Returns: Array of ResolvedMount objects.

Throws: MountValidationError (EC-6) on invalid segments or conflicting version constraints.


detectNamespaceCollisions

detectNamespaceCollisions(mounts: ResolvedMount[]): void

Checks for cross-package mount path collisions (exact match or prefix overlap).

ParameterTypeRequiredDescription
mountsResolvedMount[]YesResolved mount definitions

Returns: void on success.

Throws: NamespaceCollisionError (EC-9/EC-13) when mount paths from different packages conflict or have prefix overlap.


loadExtensions

loadExtensions(
  mounts: ResolvedMount[],
  config: Record<string, Record<string, unknown>>
): Promise<LoadedProject>

Loads all extension packages listed in mounts and applies per-extension config.

ParameterTypeRequiredDescription
mountsResolvedMount[]YesResolved mount definitions
configRecord<string, Record<string, unknown>>YesPer-extension config keyed by mount path

Returns: Promise<LoadedProject> containing all loaded extension data.

Throws: ExtensionLoadError (EC-7) when a package is not found, has no manifest, or the factory fails. Throws ExtensionVersionError (EC-10) on version constraint mismatch.


buildExtensionBindings

buildExtensionBindings(extTree: Record<string, RillValue>): string

Generates rill source text that binds loaded extension values into the script namespace.

ParameterTypeRequiredDescription
extTreeRecord<string, RillValue>YesMap of mount path to mounted extension value

Returns: rill source string with extension bindings.

Throws: ExtensionBindingError when a value cannot be bound (e.g., invalid mount path or incompatible value shape).


buildContextBindings

buildContextBindings(
  schema: Record<string, ContextFieldSchema>,
  values: Record<string, unknown>
): string

Generates rill source text that binds context values into the script namespace.

ParameterTypeRequiredDescription
schemaRecord<string, ContextFieldSchema>YesContext field schema definitions
valuesRecord<string, unknown>YesValidated context values

Returns: rill source string with context variable bindings.


buildResolvers

buildResolvers(options: {
  extTree: Record<string, RillValue>;
  contextValues: Record<string, unknown>;
  extensionBindings: string;
  contextBindings: string;
  modulesConfig: Record<string, string>;
}): ResolverConfig

Assembles the final resolver configuration for the rill runtime.

ParameterTypeRequiredDescription
options.extTreeRecord<string, RillValue>YesMap of mount path to mounted extension value
options.contextValuesRecord<string, unknown>YesValidated context values
options.extensionBindingsstringYesGenerated extension binding source
options.contextBindingsstringYesGenerated context binding source
options.modulesConfigRecord<string, string>YesModule path map for the host resolver

Returns: ResolverConfig for use with createRuntimeContext.


loadProject

loadProject(options: {
  configPath: string;
  env: Record<string, string>;
  rillVersion: string;
}): Promise<ProjectResult>

Orchestrates the full project loading sequence: parse config, check version, load extensions, build bindings, and assemble resolvers.

ParameterTypeRequiredDescription
options.configPathstringYesAbsolute path to the config file
options.envRecord<string, string>YesPre-resolved environment variables
options.rillVersionstringYesInstalled rill version for constraint checking

Returns: Promise<ProjectResult>.

Throws: Any typed error from the functions it orchestrates (EC-1 through EC-14).


introspectHandler

introspectHandler(closure: ScriptCallable): HandlerIntrospection

Extracts parameter metadata from a rill script closure.

ParameterTypeRequiredDescription
closureScriptCallableYesA rill script closure to introspect

Returns: HandlerIntrospection with the closure’s parameter list.


marshalCliArgs

marshalCliArgs(
  args: Record<string, string>,
  params: ReadonlyArray<HandlerParam>
): Record<string, unknown>

Coerces CLI flag values to the types declared in the handler’s parameter list.

ParameterTypeRequiredDescription
argsRecord<string, string>YesRaw CLI flag values (all strings)
paramsReadonlyArray<HandlerParam>YesHandler parameter descriptors

Returns: Coerced argument map with values typed per the parameter schema.

Throws: HandlerArgError (EC-16) on missing required param, coercion failure, or unknown flag.


Exported Types

RillConfigFile

The parsed and validated config file structure.

FieldTypeRequiredDescription
mainstringNoEntry point path with optional ::handlerName suffix
extensionsExtensionsBlockNoExtension mount definitions
contextContextBlockNoContext schema and values
hostHostBlockNoHost and runtime options

ExtensionsBlock

Extension configuration from the extensions section of the config file.

FieldTypeRequiredDescription
mountsRecord<string, string>NoMount path to package specifier map
configRecord<string, Record<string, unknown>>NoPer-extension config keyed by mount path

ContextBlock

Context schema and values from the context section of the config file.

FieldTypeRequiredDescription
schemaRecord<string, ContextFieldSchema>NoField name to type schema map
valuesRecord<string, unknown>NoConcrete values for each schema field

ContextFieldSchema

Type descriptor for a single context field.

FieldTypeRequiredDescription
type'string' | 'number' | 'bool'YesExpected value type

HostBlock

Host and runtime options from the host section of the config file.

FieldTypeRequiredDescription
rillVersionstringNoSemver constraint for the installed rill version
modulesRecord<string, string>NoModule identifier to file path map

ResolvedMount

Structured result of parsing a single mount entry.

FieldTypeRequiredDescription
mountPathstringYesNamespace path where the extension is mounted
packageSpecstringYesnpm package specifier (e.g., "@rcrsr/rill-ext-kv")
versionConstraintstringNoSemver constraint extracted from the package specifier
localPathstringNoResolved local path for file: specifiers

LoadedProject

Result of loadExtensions. Contains all loaded extension data.

FieldTypeRequiredDescription
manifestsReadonlyMap<string, ExtensionManifest>YesMap of mount path to loaded manifest
extTreeRecord<string, RillValue>YesMap of mount path to mounted extension value

ResolverConfig

Resolver configuration for use with createRuntimeContext from @rcrsr/rill.

FieldTypeRequiredDescription
resolversRecord<string, SchemeResolver>YesScheme-to-resolver map
configurationsRecord<string, unknown>YesPer-scheme configuration data

ProjectResult

Result of loadProject. Contains everything needed to run a rill script.

FieldTypeRequiredDescription
resolverConfigResolverConfigYesAssembled resolver configuration
bindingsstringYesCombined extension and context binding source
contextValuesRecord<string, unknown>YesValidated context values
handlerInfoHandlerIntrospectionNoPresent when main specifies a handler name

HandlerIntrospection

Introspection result for a script closure.

FieldTypeRequiredDescription
paramsHandlerParam[]YesOrdered list of parameter descriptors

HandlerParam

Descriptor for a single handler parameter.

FieldTypeRequiredDescription
namestringYesParameter name
typestringNoDeclared type annotation string
requiredbooleanYesWhether the parameter has no default value
descriptionstringNoDescription from closure annotation metadata

Typed Errors

All errors extend ConfigError, which extends Error with a code: string field.

class ConfigError extends Error {
  readonly code: string;
}
Error ClassCodeTriggering ConditionInspectable Fields
ConfigNotFoundErrorEC-1Config file not found by ancestor walk or explicit pathmessage
ConfigParseErrorEC-2Config file contains invalid JSONmessage
ConfigEnvErrorEC-3One or more ${VAR} references have no value in envmessage (lists all missing var names)
ConfigValidationErrorEC-4Invalid field type, empty path or handler, or orphaned config keymessage
RuntimeVersionErrorEC-5Installed version fails the semver constraint, or constraint is invalidmessage
MountValidationErrorEC-6Mount path contains an invalid segment or version constraints conflictmessage
ExtensionLoadErrorEC-7Package not found, extension has no manifest, or factory function failsmessage
NamespaceCollisionErrorEC-9/EC-13Two mounts from different packages conflict or have prefix overlapmessage
ExtensionVersionErrorEC-10Extension version does not satisfy the constraint in the mount specifiermessage
ContextValidationErrorEC-12A required context value is missing, or a value has the wrong typemessage
BundleRestrictionErrorEC-14Config contains fields prohibited in bundle modemessage
HandlerArgErrorEC-16Missing required param, type coercion failure, or unknown CLI flagmessage
ExtensionBindingErrorEXTENSION_BINDINGExtension value cannot be bound — invalid mount path or incompatible value shapemessage, code

Catching Typed Errors

import {
  loadProject,
  ConfigError,
  ConfigNotFoundError,
  ConfigEnvError,
  ExtensionBindingError,
} from '@rcrsr/rill-config';

try {
  const result = await loadProject({ configPath, env, rillVersion });
} catch (err) {
  if (err instanceof ConfigNotFoundError) {
    console.error('No config file found:', err.message);
  } else if (err instanceof ConfigEnvError) {
    console.error('Missing environment variables:', err.message);
  } else if (err instanceof ExtensionBindingError) {
    console.error('Extension binding failed:', err.message);
  } else if (err instanceof ConfigError) {
    console.error(`Config error [${err.code}]:`, err.message);
  } else {
    throw err;
  }
}

See Also