Skip to main content
Version: 0.13

Node.js API

Looking for the cross-language FFI contract? See ./ffi-abi.md for call, the "ERROR:" prefix, the 4 MiB BUFFER_SIZE, and the kcl_lib_napi napi-rs addon. The kcl-lib package is a thin TypeScript wrapper over that single dispatcher; every typed function funnels through napi_call(name, nameLength, args, argsLength, resultPtr).

The Node.js binding is published as the npm package kcl-lib. It is built with napi-rs and exposes the full KclService + BuiltinService surface plus auto-generated TypeScript types from spec/spec.proto. One native addon per platform (linux-x64-gnu, darwin-arm64, win32-x64-msvc, …) is selected at install time via optionalDependencies.

Installation​

npm install kcl-lib

Quick Start​

import { execProgram, ExecProgramArgs } from "kcl-lib";

function main() {
const result = execProgram(new ExecProgramArgs(["path/to/kcl.k"]));
console.log(result.yamlResult);
}

main();

API Reference​

execProgram​

Execute KCL file with arguments and return the JSON/YAML result.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

Node.js Code

import { execProgram, ExecProgramArgs } from "kcl-lib";

const result = execProgram(new ExecProgramArgs(["schema.k"]));

A case with the file not found error

Example

import { execProgram, ExecProgramArgs } from "kcl-lib";

try {
const result = execProgram(new ExecProgramArgs(["file_not_found.k"]));
} catch (error) {
console.log(error.message);
}

parseFile​

Parse KCL single file to Module AST JSON string with import dependencies and parse errors.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

Node.js Code

import { parseFile, ParseFileArgs } from "kcl-lib";

const result = parseFile(new ParseFileArgs("schema.k"));

parseProgram​

Parse KCL program with entry files and return the AST JSON string.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

Node.js Code

import { parseProgram, ParseProgramArgs } from "kcl-lib";

const result = parseProgram(new ParseProgramArgs(["schema.k"]));

loadPackage​

loadPackage provides users with the ability to parse KCL program and semantic model information including symbols, types, definitions, etc.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

Node.js Code

import { loadPackage, LoadPackageArgs } from "kcl-lib";

const result = loadPackage(new LoadPackageArgs(["schema.k"], [], true));

listVariable​

listVariables provides users with the ability to parse KCL program and get all variables by specs.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

Node.js Code

import { listVariables, ListVariablesArgs } from "kcl-lib";

const result = listVariables(new ListVariablesArgs(["schema.k"], []));

listOptions​

listOptions provides users with the ability to parse KCL program and get all option information.

Example

The content of options.k is

a = option("key1")
b = option("key2", required=True)
c = {
metadata.key = option("metadata-key")
}

Node.js Code

import { listOptions, ListOptionsArgs } from "kcl-lib";

const result = listOptions(new ListOptionsArgs(["options.k"]));

getSchemaTypeMapping​

Get schema type mapping defined in the program.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

Node.js Code

import { getSchemaTypeMapping, GetSchemaTypeMappingArgs } from "kcl-lib";

const result = getSchemaTypeMapping(new GetSchemaTypeMappingArgs(["schema.k"]));

getSchemaTypeMappingUnderPath​

Get schema type mapping defined in the program and its dependency packages, keyed by package name. Different from getSchemaTypeMapping, schemas imported from external dependency packages are keyed under their own package name instead of being flattened into __main__.

Example

Node.js Code

import path from 'node:path'
import { getSchemaTypeMappingUnderPath, GetSchemaTypeMappingArgs } from "kcl-lib";

const result = getSchemaTypeMappingUnderPath(
new GetSchemaTypeMappingArgs([path.join("test_data", "get_schema_ty_under_path", "aaa")], null, null, [
{ pkgName: "bbb", pkgPath: path.join("test_data", "get_schema_ty_under_path", "bbb") },
]),
);
console.log(result.schemaTypeMapping["bbb"]); // ["B", "Base"]

overrideFile​

Override KCL file with arguments. See https://www.kcl-lang.io/docs/user_docs/guides/automation for more override spec guide.

Example

The content of main.k is

schema AppConfig:
replicas: int

app: AppConfig {replicas: 4}

Node.js Code

import { overrideFile, OverrideFileArgs } from "kcl-lib";

const result = overrideFile(
new OverrideFileArgs("main.k", ["app.replicas=4"], []),
);

formatCode​

Format the code source.

Example

Node.js Code

import { formatCode, FormatCodeArgs } from "kcl-lib";

const schemaCode = `
schema Person:
name: str
age: int

check:
0 < age < 120
`;
const result = formatCode(new FormatCodeArgs(schemaCode));
console.log(result.formatted);

formatPath​

Format KCL file or directory path contains KCL files and returns the changed file paths.

Example

The content of format_path.k is

schema Person:
name: str
age: int

check:
0 < age < 120

Node.js Code

import { formatPath, FormatPathArgs } from "kcl-lib";

const result = formatPath(new FormatPathArgs("format_path.k"));

lintPath​

Lint files and return error messages including errors and warnings.

Example

The content of lint_path.k is

import math

a = 1

Node.js Code

import { lintPath, LintPathArgs } from "kcl-lib";

const result = lintPath(new LintPathArgs(["lint_path.k"]));

validateCode​

Validate code using schema and JSON/YAML data strings.

Example

Node.js Code

import { validateCode, ValidateCodeArgs } from "kcl-lib";

const code = `
schema Person:
name: str
age: int

check:
0 < age < 120
`;
const data = '{"name": "Alice", "age": 10}';
const result = validateCode(
new ValidateCodeArgs(undefined, data, undefined, code),
);

rename​

Rename all the occurrences of the target symbol in the files. This API will rewrite files if they contain symbols to be renamed. Return the file paths that got changed.

Example

The content of main.k is

a = 1
b = a

Node.js Code

import { rename, RenameArgs } from "kcl-lib";

const args = new RenameArgs(".", "a", ["main.k"], "a2");
const result = rename(args);

renameCode​

Rename all the occurrences of the target symbol and return the modified code if any code has been changed. This API won't rewrite files but return the changed code.

Example

Node.js Code

import { renameCode, RenameCodeArgs } from "kcl-lib";

const args = RenameCodeArgs(
"/mock/path",
"a",
{ "/mock/path/main.k": "a = 1\nb = a" },
"a2",
);
const result = renameCode(args);

test​

Test KCL packages with test arguments.

Example

Node.js Code

import { test as kclTest, TestArgs } from "kcl-lib";

const result = kclTest(new TestArgs(["/path/to/test/module/..."]));

loadSettingsFiles​

Load the setting file config defined in kcl.yaml

Example

The content of kcl.yaml is

kcl_cli_configs:
strict_range_check: true
kcl_options:
- key: key
value: value

Node.js Code

import { loadSettingsFiles, LoadSettingsFilesArgs } from "kcl-lib";

const result = loadSettingsFiles(new LoadSettingsFilesArgs(".", ["kcl.yaml"]));

updateDependencies​

Download and update dependencies defined in the kcl.mod file and return the external package name and location list.

Example

The content of module/kcl.mod is

[package]
name = "mod_update"
edition = "0.0.1"
version = "0.0.1"

[dependencies]
helloworld = { oci = "oci://ghcr.io/kcl-lang/helloworld", tag = "0.1.0" }
flask = { git = "https://github.com/kcl-lang/flask-demo-kcl-manifests", commit = "ade147b" }

Node.js Code

import { updateDependencies, UpdateDependenciesArgs } from "kcl-lib";

const result = updateDependencies(new UpdateDependenciesArgs("module", false));

Call execProgram with external dependencies

Example

The content of module/kcl.mod is

[package]
name = "mod_update"
edition = "0.0.1"
version = "0.0.1"

[dependencies]
helloworld = { oci = "oci://ghcr.io/kcl-lang/helloworld", tag = "0.1.0" }
flask = { git = "https://github.com/kcl-lang/flask-demo-kcl-manifests", commit = "ade147b" }

The content of module/main.k is

import helloworld
import flask

a = helloworld.The_first_kcl_program

Node.js Code

import {
execProgram,
ExecProgramArgs,
updateDependencies,
UpdateDependenciesArgs,
} from "../index.js";

const result = updateDependencies(new UpdateDependenciesArgs("module", false));
const execResult = execProgram(
new ExecProgramArgs(
["module/main.k"],
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
result.externalPkgs,
),
);

getVersion​

Return the KCL service version information.

Example

Node.js Code

import { getVersion } from "../index.js";

const result = getVersion();
console.log(result.versionInfo);

(The exact version / checksum / gitSha values vary per release; assert only on non-empty.)

ping​

Round-trip a value through the dispatcher.

Example

import { ping, PingArgs } from "kcl-lib";

const result = ping(new PingArgs("hello"));
console.log(result.value); // -> "hello"

listMethod​

List the KCL service method names supported by the underlying runtime.

Example

import { listMethod } from "kcl-lib";

for (const name of listMethod().methodNameList) {
console.log(name);
}

Plugin support​

If your KCL program imports kcl_plugin.*, register the plugin before calling any RPC:

import { registerPlugin, execProgram, ExecProgramArgs } from "kcl-lib";

registerPlugin("my_plugin", {
echo(args, kwargs) { return { ...args, ...kwargs }; },
});

const result = execProgram(new ExecProgramArgs(["schema.k"]));

Notes​

The legacy BuildProgram and ExecArtifact RPCs were removed from spec/spec.proto in v0.13.0 (see lib commit 815acac); they are no longer recognised by the dispatcher. If you previously imported a buildProgram or execArtifact symbol, switch to execProgram.