Skip to content

Embedding the compiler

The compiler is a normal ES module. It exports three compile functions, three decompile functions, two editor helpers, the error type and two resolver hooks, which is enough to build a browser playground, a different editor integration, or a build step.

Terminal window
npm install @katnip-org/compiler
import {
checkSource,
compileToIR,
compileToSb3,
decompileProject,
decompileSb3,
decompileSb3ToKpkg,
getHover,
getMemberCompletions,
KatnipError,
} from "@katnip-org/compiler";

Requires Node 20+. The package is ESM-only.

checkSource(source: string, options?: Options): readonly KatnipError[]

Lex, parse, analyze. Returns the diagnostics, warnings included; an empty array means clean.

const errors = checkSource(source);
for (const e of errors) {
console.log(`${e.severity}: ${e.message} at ${e.location?.line}:${e.location?.column}`);
}
compileToSb3(source: string, options?: Options): { errors: readonly KatnipError[]; sb3?: Uint8Array }

The whole pipeline. sb3 is absent when errors holds anything of severity "error"; warnings do not stop a build.

import { writeFile } from "node:fs/promises";
const { errors, sb3 } = compileToSb3(source, { path: "/proj/main.knip" });
if (!sb3) throw new Error(errors.map(e => e.message).join("\n"));
await writeFile("out.sb3", sb3);

In a browser, hand the bytes straight to a download or to MistWarp:

const url = URL.createObjectURL(new Blob([sb3], { type: "application/zip" }));
compileToIR(source: string, options?: Options): { errors: readonly KatnipError[]; ir?: IRProgram }

Stops after lowering. Useful for tooling that wants the Scratch-shaped tree without the zip.

interface Options {
path?: string; // the entry file's path, for resolving relative imports and assets
resolve?: ImportResolver; // how to fetch an imported file
readAsset?: AssetReader; // how to fetch a costume, sound or data file
compression?: number; // zip deflate level 0-9, default 6 (compileToSb3 only)
}

Imports are only followed when you supply a resolve. Without it, the entry file is compiled alone.

Assets are only found when you supply a readAsset. Without it, every costume, sound and import("./data.csv") is reported as a missing file, a clearer failure than silently shipping the default costume.

type ImportResolver = (specifier: string, fromPath: string)
=> { path: string; source: string } | null;

Return null for an unresolvable specifier; the compiler reports it against the importing file with a source span.

import { readFileSync } from "node:fs";
import path from "node:path";
const fileResolver = (specifier, fromPath) => {
const resolved = path.resolve(
path.dirname(fromPath),
specifier.endsWith(".knip") ? specifier : `${specifier}.knip`,
);
try {
return { path: resolved, source: readFileSync(resolved, "utf8") };
} catch {
return null;
}
};
const files = {
"/main.knip": "import \"./lib.knip\";",
"/lib.knip": "public proc double(n: num) -> num { return n * 2; }",
};
const virtualResolver = (specifier, fromPath) => {
const resolved = new URL(specifier, `file://${fromPath}`).pathname;
const key = resolved.endsWith(".knip") ? resolved : `${resolved}.knip`;
return files[key] ? { path: key, source: files[key] } : null;
};

Each file is read and parsed exactly once per compile, no matter how many times it is imported. Cycles are detected and reported.

type AssetReader = (specifier: string, fromPath: string) => Uint8Array | null;

Same contract as an import resolver, but returning bytes. Return null when the file does not exist and the compiler reports it against the path in the declaring file.

import { readFileSync } from "node:fs";
import path from "node:path";
const fileAssetReader = (specifier, fromPath) => {
try {
return readFileSync(path.resolve(path.dirname(fromPath), specifier));
} catch {
return null;
}
};

For a virtual filesystem, key a map by resolved path and return files[resolved] ?? null.

decompileSb3(sb3: Uint8Array): string
decompileProject(project: Sb3Project): string
decompileSb3ToKpkg(sb3: Uint8Array, options?: { split?: boolean }): Uint8Array

decompileSb3 takes the .sb3 bytes and returns .knip source, and throws if the zip has no project.json. decompileProject does the same from an already-parsed project.json. Neither one extracts assets.

decompileSb3ToKpkg returns the zipped .kpkg, the same one katnip decompile writes: main.knip and its costumes and sounds, or one file per sprite with split. The limits are listed under katnip decompile.

getHover(source: string, line: number, column: number, options?: Options): string | null
getMemberCompletions(source: string, line: number, column: number, options?: Options): Completion[] | null

Both take a 1-based line and column, counted in code points.

getHover returns the signature of the call or the type of the value under the cursor, or null when there is nothing there or the source doesn’t parse.

getMemberCompletions lists what can follow the . before the cursor: namespaces, enums and their members, methods and struct fields. It works while the line is still unfinished, like config.. It returns null when the cursor isn’t after a dot. Each completion has a name, a kind (function, field, enumMember, enum or variable) and a detail.

class KatnipError extends Error {
source: string; // the stage, e.g. "Parser" or "Asset"
message: string;
severity: "error" | "warning";
location?: { // absent for IR and codegen errors
line: number;
column: number;
length?: number;
endLine?: number;
endColumn?: number;
};
}

Errors are collected, not thrown — the parser recovers into error nodes so a syntax error does not hide the semantic errors after it. Both compileToIR and compileToSb3 catch the KatnipErrors that codegen throws and return them in errors; anything else propagates.

The standard library is parsed once and cached across calls in module scope. The first checkSource in a process pays for it; the rest do not. That is what makes an on-every-keystroke editor integration viable.