@sf-kmods/kdataforgejs-cli 0.0.0-stage → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @sf-kmods/kdataforgejs-cli
2
+
3
+ `kdf` sets up, checks and validates KDataForge projects that use KDataForgeJS (TypeScript) scripts.
4
+
5
+ ```sh
6
+ npx @sf-kmods/kdataforgejs-cli init MyPack
7
+ cd MyPack
8
+ npm install
9
+ npm run verify
10
+ ```
11
+
12
+ ## Commands
13
+
14
+ | Command | What it does |
15
+ | --- | --- |
16
+ | `kdf init [dir]` | Creates a project: `package.json`, `tsconfig.json` and a `DataForge/` pack with `pack.yml` and `scripts/main.ts`. `--name` sets the pack ref, `--force` writes into a non-empty folder. |
17
+ | `kdf check [dir]` | Type-checks the project against `@sf-kmods/kdataforgejs` with the bundled TypeScript. Nothing is emitted. |
18
+ | `kdf validate [dir]` | Checks `pack.yml`, the entry file, the static import graph and the digests of declared imports. |
19
+ | `kdf hash [dir]` | Rewrites stale `sha256` values of declared imports and leaves your comments alone. |
20
+ | `kdf game-data [dir]` | Finds a modded Satisfactory installation, starts a full reflection export, closes the game and imports the archive plus generated TypeScript declarations. Use `--game-path <root-or-executable>` to select an installation explicitly. |
21
+
22
+ Exit code `0` means all good, `1` means findings, `2` means the command was used wrong.
23
+
24
+ `validate` repeats the checks the game does when it loads a pack, so most mistakes show up before you start Satisfactory.
25
+ It does not replace the runtime: catalog, authority and limits are still decided in game.
26
+
27
+ The generated project keeps `package.json` and `tsconfig.json` next to the `DataForge` folder, never inside it. The pack
28
+ itself has no `node_modules`.
29
+
30
+ ## Import game data
31
+
32
+ Run from the project directory:
33
+
34
+ ```sh
35
+ kdf game-data
36
+ ```
37
+
38
+ The command searches Steam libraries and Epic manifests on Windows. On Linux it searches native and Flatpak Steam
39
+ libraries and launches app `526870` through Steam. Only installations containing both KDataForge and KDataForgeJS are
40
+ eligible. To bypass discovery:
41
+
42
+ ```sh
43
+ kdf game-data --game-path "C:\\Games\\Satisfactory"
44
+ ```
45
+
46
+ The game starts with automatic full reflection export and exits when publication completes. The CLI waits up to 15
47
+ minutes by default; override this with `--timeout <seconds>`. It writes `.kdataforge/satisfactory.kdfdata`, imports
48
+ generated declarations below `DataForge/typescript/kdataforgejs/`, creates `tsconfig.kdf.json`, and makes later
49
+ `kdf check` calls use those installed-game types automatically. `.kdataforge/` is added to `.gitignore` because the
50
+ archive can be large.
package/dist/bin.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { run } from "./cli.js";
4
+ const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
5
+ process.exitCode = await run(process.argv.slice(2), { out: (line) => console.log(line), err: (line) => console.error(line) }, manifest.version);
package/dist/cli.js ADDED
@@ -0,0 +1,101 @@
1
+ import { parseArgs } from "node:util";
2
+ import { checkProject } from "./commands/check.js";
3
+ import { importGameData } from "./commands/gameData.js";
4
+ import { hashProject } from "./commands/hash.js";
5
+ import { initProject } from "./commands/init.js";
6
+ import { validateProject } from "./commands/validate.js";
7
+ import { formatDiagnostic, hasErrors } from "./diagnostics.js";
8
+ const USAGE = `kdf - KDataForgeJS project tooling
9
+
10
+ Usage:
11
+ kdf init [dir] [--name <PackRef>] [--force] Create a new KDataForge project with a TypeScript script
12
+ kdf check [dir] Type-check the project (tsconfig.json, no emit)
13
+ kdf validate [dir] Check pack.yml, entry, static imports and import digests
14
+ kdf hash [dir] Update sha256 of declared script imports in pack.yml
15
+ kdf game-data [dir] [--game-path <path>] Export installed game data and import it into the project
16
+ kdf --help | --version
17
+ `;
18
+ const DEFAULT_DEPENDENCIES = { importGameData };
19
+ /** Runs the CLI and returns the process exit code: 0 ok, 1 findings, 2 usage error. */
20
+ export const run = createCli(DEFAULT_DEPENDENCIES);
21
+ export function createCli(dependencies) {
22
+ return (argv, io, version) => runCli({ argv, io, version }, dependencies);
23
+ }
24
+ async function runCli(request, dependencies) {
25
+ const { argv, io, version } = request;
26
+ const { values, positionals } = parseArgs({
27
+ args: [...argv],
28
+ allowPositionals: true,
29
+ options: {
30
+ name: { type: "string" },
31
+ "game-path": { type: "string" },
32
+ timeout: { type: "string" },
33
+ force: { type: "boolean", default: false },
34
+ help: { type: "boolean", short: "h", default: false },
35
+ version: { type: "boolean", short: "v", default: false },
36
+ },
37
+ });
38
+ const [command, directory = "."] = positionals;
39
+ if (values.version)
40
+ return print(io.out, version);
41
+ if (values.help || command === undefined)
42
+ return print(io.out, USAGE);
43
+ try {
44
+ switch (command) {
45
+ case "init": {
46
+ const result = initProject({ directory, force: values.force, ...(values.name ? { name: values.name } : {}) });
47
+ io.out(`Created KDataForge project '${result.ref}' in ${result.directory}`);
48
+ io.out("Next: npm install, then npm run check");
49
+ return 0;
50
+ }
51
+ case "check":
52
+ return report(io, checkProject(directory), "Type check passed.");
53
+ case "validate":
54
+ return report(io, validateProject(directory), "Pack is valid.");
55
+ case "hash": {
56
+ const changed = hashProject(directory);
57
+ io.out(changed.length === 0 ? "All import digests are up to date." : `Updated digests:\n${changed.join("\n")}`);
58
+ return 0;
59
+ }
60
+ case "game-data": {
61
+ const timeoutMilliseconds = parseTimeout(values.timeout);
62
+ const result = await dependencies.importGameData({
63
+ destination: directory,
64
+ ...(values["game-path"] ? { gamePath: values["game-path"] } : {}),
65
+ ...(timeoutMilliseconds === undefined ? {} : { timeoutMilliseconds }),
66
+ });
67
+ io.out(`Imported game data from ${result.installation.root}`);
68
+ io.out(`Archive: ${result.archivePath}`);
69
+ io.out(`Types: ${result.declarationPath}`);
70
+ return 0;
71
+ }
72
+ default:
73
+ io.err(`Unknown command '${command}'.\n${USAGE}`);
74
+ return 2;
75
+ }
76
+ }
77
+ catch (error) {
78
+ io.err(error instanceof Error ? error.message : String(error));
79
+ return 1;
80
+ }
81
+ }
82
+ function parseTimeout(value) {
83
+ if (value === undefined)
84
+ return undefined;
85
+ const seconds = Number(value);
86
+ if (!Number.isFinite(seconds) || seconds <= 0)
87
+ throw new Error("--timeout must be a positive number of seconds.");
88
+ return Math.round(seconds * 1_000);
89
+ }
90
+ function print(write, text) {
91
+ write(text.trimEnd());
92
+ return 0;
93
+ }
94
+ function report(io, diagnostics, success) {
95
+ for (const diagnostic of diagnostics)
96
+ io.err(formatDiagnostic(diagnostic));
97
+ if (hasErrors(diagnostics))
98
+ return 1;
99
+ io.out(success);
100
+ return 0;
101
+ }
@@ -0,0 +1,38 @@
1
+ import { existsSync } from "node:fs";
2
+ import { dirname, join, relative, resolve } from "node:path";
3
+ import ts from "typescript";
4
+ /** Type-checks the project's tsconfig.json (no emit) with the TypeScript compiler bundled with the CLI. */
5
+ export function checkProject(projectRoot, configName) {
6
+ const absoluteProjectRoot = resolve(projectRoot);
7
+ const selectedConfig = configName ?? (existsSync(join(absoluteProjectRoot, "tsconfig.kdf.json")) ? "tsconfig.kdf.json" : "tsconfig.json");
8
+ const configPath = join(absoluteProjectRoot, selectedConfig);
9
+ if (!existsSync(configPath)) {
10
+ return [
11
+ {
12
+ severity: "error",
13
+ code: "check.no-tsconfig",
14
+ file: selectedConfig,
15
+ message: "tsconfig.json not found. Run 'kdf init' or extend @sf-kmods/kdataforgejs/tsconfig.base.json.",
16
+ },
17
+ ];
18
+ }
19
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
20
+ if (read.error !== undefined)
21
+ return [toDiagnostic(read.error, absoluteProjectRoot)];
22
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(configPath), undefined, configPath);
23
+ const program = ts.createProgram({ rootNames: parsed.fileNames, options: { ...parsed.options, noEmit: true } });
24
+ return [...parsed.errors, ...ts.getPreEmitDiagnostics(program)].map((d) => toDiagnostic(d, absoluteProjectRoot));
25
+ }
26
+ function toDiagnostic(diagnostic, projectRoot) {
27
+ let file = "tsconfig.json";
28
+ if (diagnostic.file !== undefined && diagnostic.start !== undefined) {
29
+ const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
30
+ file = `${relative(projectRoot, diagnostic.file.fileName).split("\\").join("/")}:${line + 1}:${character + 1}`;
31
+ }
32
+ return {
33
+ severity: diagnostic.category === ts.DiagnosticCategory.Error ? "error" : "warning",
34
+ code: `TS${diagnostic.code}`,
35
+ file,
36
+ message: ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n").trim(),
37
+ };
38
+ }
@@ -0,0 +1,125 @@
1
+ import { spawn } from "node:child_process";
2
+ import { appendFileSync, copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { detectGameInstallations, resolveGameInstallation, supportedPlatform } from "../game/installations.js";
6
+ const DEFAULT_TIMEOUT_MILLISECONDS = 15 * 60 * 1_000;
7
+ const POLL_INTERVAL_MILLISECONDS = 500;
8
+ export async function importGameData(options, dependencies = {}) {
9
+ const timeoutMilliseconds = options.timeoutMilliseconds ?? DEFAULT_TIMEOUT_MILLISECONDS;
10
+ assertValidTimeout(timeoutMilliseconds);
11
+ const platform = supportedPlatform(dependencies.platform ?? process.platform);
12
+ const installation = selectInstallation(options.gamePath, platform);
13
+ const destination = resolve(options.destination);
14
+ const exportDirectory = mkdtempSync(join(tmpdir(), "kdf-game-data-export-"));
15
+ try {
16
+ const plan = createLaunchPlan(installation, platform, exportDirectory);
17
+ await (dependencies.launch ?? launchGame)(plan);
18
+ const artifacts = await waitForExport(exportDirectory, timeoutMilliseconds, dependencies.sleep ?? delay);
19
+ return installExport(destination, installation, artifacts);
20
+ }
21
+ finally {
22
+ rmSync(exportDirectory, { recursive: true, force: true });
23
+ }
24
+ }
25
+ export function createLaunchPlan(installation, platform, exportDirectory) {
26
+ const gameArguments = [
27
+ "-EpicPortal",
28
+ "-log",
29
+ "-nosplash",
30
+ `-KDFReflectionAutoExport=${exportDirectory}`,
31
+ "-KDFReflectionAutoExit",
32
+ ];
33
+ if (platform === "win32") {
34
+ return { command: installation.executable, arguments: gameArguments, workingDirectory: installation.root, exportDirectory };
35
+ }
36
+ if (installation.root.includes("/.var/app/com.valvesoftware.Steam/")) {
37
+ return {
38
+ command: "flatpak",
39
+ arguments: ["run", "com.valvesoftware.Steam", "-applaunch", "526870", "--", ...gameArguments],
40
+ workingDirectory: installation.root,
41
+ exportDirectory,
42
+ };
43
+ }
44
+ return {
45
+ command: "steam",
46
+ arguments: ["-applaunch", "526870", "--", ...gameArguments],
47
+ workingDirectory: installation.root,
48
+ exportDirectory,
49
+ };
50
+ }
51
+ function selectInstallation(gamePath, platform) {
52
+ if (gamePath !== undefined)
53
+ return resolveGameInstallation(gamePath, platform);
54
+ const installations = detectGameInstallations({ platform });
55
+ const installation = installations[0];
56
+ if (installation !== undefined)
57
+ return installation;
58
+ throw new Error("No Satisfactory installation containing KDataForge and KDataForgeJS was found. Pass --game-path <root-or-executable>.");
59
+ }
60
+ async function launchGame(plan) {
61
+ await new Promise((resolveLaunch, rejectLaunch) => {
62
+ const child = spawn(plan.command, [...plan.arguments], {
63
+ cwd: plan.workingDirectory,
64
+ stdio: "inherit",
65
+ windowsHide: false,
66
+ detached: false,
67
+ });
68
+ child.once("spawn", resolveLaunch);
69
+ child.once("error", rejectLaunch);
70
+ });
71
+ }
72
+ async function waitForExport(exportDirectory, timeoutMilliseconds, sleep) {
73
+ assertValidTimeout(timeoutMilliseconds);
74
+ const deadline = Date.now() + timeoutMilliseconds;
75
+ while (Date.now() <= deadline) {
76
+ const artifacts = findCompletedExport(exportDirectory);
77
+ if (artifacts !== undefined)
78
+ return artifacts;
79
+ await sleep(POLL_INTERVAL_MILLISECONDS);
80
+ }
81
+ throw new Error(`Timed out after ${timeoutMilliseconds} ms waiting for KDataForge reflection export.`);
82
+ }
83
+ function assertValidTimeout(timeoutMilliseconds) {
84
+ if (!Number.isSafeInteger(timeoutMilliseconds) || timeoutMilliseconds <= 0) {
85
+ throw new Error("Game-data timeout must be a positive integer number of milliseconds.");
86
+ }
87
+ }
88
+ function findCompletedExport(exportDirectory) {
89
+ const archive = readdirSync(exportDirectory, { withFileTypes: true })
90
+ .filter((entry) => entry.isFile() && entry.name.toLocaleLowerCase().endsWith(".kdfdata"))
91
+ .map((entry) => join(exportDirectory, entry.name))
92
+ .sort()
93
+ .at(-1);
94
+ const typesDirectory = join(exportDirectory, "typescript/kdataforgejs");
95
+ if (archive === undefined || !existsSync(join(typesDirectory, "kdataforge.generated.d.ts")) || !existsSync(join(typesDirectory, "tsconfig.json"))) {
96
+ return undefined;
97
+ }
98
+ return { archive, typesDirectory };
99
+ }
100
+ function installExport(destination, installation, artifacts) {
101
+ mkdirSync(destination, { recursive: true });
102
+ const archiveDirectory = join(destination, ".kdataforge");
103
+ mkdirSync(archiveDirectory, { recursive: true });
104
+ const archivePath = join(archiveDirectory, "satisfactory.kdfdata");
105
+ copyFileSync(artifacts.archive, archivePath);
106
+ const typesDirectory = join(destination, "DataForge/typescript/kdataforgejs");
107
+ rmSync(typesDirectory, { recursive: true, force: true });
108
+ mkdirSync(typesDirectory, { recursive: true });
109
+ cpSync(artifacts.typesDirectory, typesDirectory, { recursive: true });
110
+ const declarationPath = join(typesDirectory, "kdataforge.generated.d.ts");
111
+ writeFileSync(join(destination, "tsconfig.kdf.json"), `${JSON.stringify({ extends: "./DataForge/typescript/kdataforgejs/tsconfig.json", include: ["DataForge/**/*.ts"] }, null, "\t")}\n`);
112
+ ensureGitIgnoreEntry(destination, ".kdataforge/");
113
+ return { installation, archivePath, declarationPath };
114
+ }
115
+ function ensureGitIgnoreEntry(destination, entry) {
116
+ const gitIgnore = join(destination, ".gitignore");
117
+ const existing = existsSync(gitIgnore) ? readFileSync(gitIgnore, "utf8") : "";
118
+ if (existing.split(/\r?\n/u).includes(entry))
119
+ return;
120
+ const separator = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
121
+ appendFileSync(gitIgnore, `${separator}${entry}\n`);
122
+ }
123
+ function delay(milliseconds) {
124
+ return new Promise((resolveDelay) => setTimeout(resolveDelay, milliseconds));
125
+ }
@@ -0,0 +1,6 @@
1
+ import { findPackRoots } from "../pack/discover.js";
2
+ import { syncImportDigests } from "../pack/imports.js";
3
+ /** Updates sha256 of declared script imports; returns one `pack: key` line per changed import. */
4
+ export function hashProject(projectRoot) {
5
+ return findPackRoots(projectRoot).flatMap((packRoot) => syncImportDigests(packRoot).map((key) => `${packRoot}: ${key}`));
6
+ }
@@ -0,0 +1,51 @@
1
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { PACK_REF_PATTERN } from "../conventions.js";
5
+ /** Nearest ancestor holding the CLI's package.json; works from src/, dist/ and compiled tests alike. */
6
+ function findCliRoot(directory) {
7
+ return existsSync(join(directory, "package.json")) ? directory : findCliRoot(dirname(directory));
8
+ }
9
+ const CLI_ROOT = findCliRoot(dirname(fileURLToPath(import.meta.url)));
10
+ /** Files that npm would strip or rename on publish are stored with an underscore. */
11
+ const RENAMED_ON_COPY = { _gitignore: ".gitignore" };
12
+ export function packRefFrom(name) {
13
+ const cleaned = name.replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^[^A-Za-z]+/, "").replace(/-+$/, "");
14
+ return cleaned.slice(0, 50);
15
+ }
16
+ export function initProject(options) {
17
+ const directory = resolve(options.directory);
18
+ const ref = packRefFrom(options.name ?? basename(directory));
19
+ if (!PACK_REF_PATTERN.test(ref)) {
20
+ throw new Error(`Cannot derive a valid pack ref from '${options.name ?? basename(directory)}'. Use --name with letters, digits, '-' or '_'.`);
21
+ }
22
+ if (existsSync(directory) && readdirSync(directory).length > 0 && !options.force) {
23
+ throw new Error(`Directory '${directory}' is not empty. Use --force to write into it.`);
24
+ }
25
+ mkdirSync(directory, { recursive: true });
26
+ cpSync(join(CLI_ROOT, "templates/default"), directory, { recursive: true });
27
+ for (const [from, to] of Object.entries(RENAMED_ON_COPY)) {
28
+ if (existsSync(join(directory, from)))
29
+ renameSync(join(directory, from), join(directory, to));
30
+ }
31
+ const values = { ref, sdkVersion: readSdkVersion() };
32
+ substitutePlaceholders(directory, values);
33
+ return { directory, ref };
34
+ }
35
+ function readSdkVersion() {
36
+ const manifest = JSON.parse(readFileSync(join(CLI_ROOT, "package.json"), "utf8"));
37
+ return manifest.version;
38
+ }
39
+ function substitutePlaceholders(directory, values) {
40
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
41
+ const path = join(directory, entry.name);
42
+ if (entry.isDirectory()) {
43
+ substitutePlaceholders(path, values);
44
+ continue;
45
+ }
46
+ const text = readFileSync(path, "utf8");
47
+ const replaced = text.replace(/\{\{(\w+)\}\}/g, (match, key) => values[key] ?? match);
48
+ if (replaced !== text)
49
+ writeFileSync(path, replaced);
50
+ }
51
+ }
@@ -0,0 +1,39 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { CANONICAL_ENTRY, DETERMINISTIC_CAPABILITIES } from "../conventions.js";
4
+ import { findPackRoots } from "../pack/discover.js";
5
+ import { checkImports } from "../pack/imports.js";
6
+ import { readManifest } from "../pack/manifest.js";
7
+ import { checkEntryShape, checkSourceGraph, readEntryMeta } from "../pack/sourceGraph.js";
8
+ /** Static checks mirroring what the KDataForgeJS runtime rejects at load time. */
9
+ export function validateProject(projectRoot) {
10
+ const roots = findPackRoots(projectRoot);
11
+ if (roots.length === 0) {
12
+ return [{ severity: "error", code: "project.no-pack", file: projectRoot, message: "No pack.yml found (expected DataForge/pack.yml)." }];
13
+ }
14
+ return roots.flatMap(validatePack);
15
+ }
16
+ function validatePack(packRoot) {
17
+ const manifest = readManifest(packRoot);
18
+ const diagnostics = [...manifest.diagnostics];
19
+ for (const forbidden of ["package.json", "node_modules"]) {
20
+ if (existsSync(join(packRoot, forbidden))) {
21
+ diagnostics.push({ severity: "error", code: "pack.forbidden", file: forbidden, message: `Packs must not contain '${forbidden}'; keep it in the project root.` });
22
+ }
23
+ }
24
+ for (const script of manifest.scripts) {
25
+ if (!existsSync(join(packRoot, CANONICAL_ENTRY))) {
26
+ diagnostics.push({ severity: "error", code: "entry.missing", file: CANONICAL_ENTRY, message: "Entry file does not exist." });
27
+ continue;
28
+ }
29
+ const meta = readEntryMeta(packRoot, script.entry);
30
+ diagnostics.push(...meta.diagnostics);
31
+ const deterministic = meta.capabilities.some((capability) => DETERMINISTIC_CAPABILITIES.includes(capability));
32
+ if (deterministic && (script.realm !== "any" || script.authority !== "any")) {
33
+ diagnostics.push({ severity: "error", code: "script.deterministic-lane", file: script.entry,
34
+ message: "Authoring capabilities require realm: any and authority: any." });
35
+ }
36
+ diagnostics.push(...checkEntryShape(packRoot, script.entry), ...checkSourceGraph(packRoot, script.entry), ...checkImports(packRoot, [script]));
37
+ }
38
+ return diagnostics;
39
+ }
@@ -0,0 +1,20 @@
1
+ /** Contract shared with the KDataForgeJS runtime (KDataForgeJSModule.cpp). */
2
+ export const RUNTIME_MODULE = "@sf-kmods/kdataforgejs";
3
+ export const SATISFACTORY_MODULE = "satisfactory";
4
+ export const CANONICAL_ENTRY = "scripts/main.ts";
5
+ export const SCRIPT_LANGUAGE = "kmods.typescript";
6
+ export const REALMS = ["any", "server", "client"];
7
+ export const NETWORKS = ["any", "standalone", "networked"];
8
+ export const AUTHORITIES = ["any", "required", "forbidden"];
9
+ export const IMPORT_KINDS = ["text", "yaml", "structured", "binary", "image", "audio"];
10
+ export const MAX_REFLECTION_CLASSES = 64;
11
+ /** Capabilities that need a deterministic lane (realm and authority must stay "any"). */
12
+ export const DETERMINISTIC_CAPABILITIES = [
13
+ "kdf.items.define",
14
+ "kdf.recipes.define",
15
+ "kdf.documents.apply",
16
+ "kdf.classes.define",
17
+ "kdf.reflection.write",
18
+ ];
19
+ export const PACK_REF_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,49}$/;
20
+ export const SCRIPT_ID_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
@@ -0,0 +1,6 @@
1
+ export function formatDiagnostic(diagnostic) {
2
+ return `${diagnostic.file}: ${diagnostic.severity} ${diagnostic.code}: ${diagnostic.message}`;
3
+ }
4
+ export function hasErrors(diagnostics) {
5
+ return diagnostics.some((diagnostic) => diagnostic.severity === "error");
6
+ }
@@ -0,0 +1,205 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
5
+ const STEAM_APP_ID = "526870";
6
+ const REQUIRED_MODS = ["KDataForge", "KDataForgeJS"];
7
+ export function detectGameInstallations(options = {}) {
8
+ const platform = supportedPlatform(options.platform ?? process.platform);
9
+ const environment = options.environment ?? process.env;
10
+ const installations = [
11
+ ...detectSteamInstallations(platform, options.steamRoots ?? defaultSteamRoots(platform, environment)),
12
+ ...detectEpicInstallations(platform, options.epicManifestDirectories ?? defaultEpicManifestDirectories(platform, environment)),
13
+ ];
14
+ const unique = new Map();
15
+ for (const installation of installations) {
16
+ if (!hasRequiredMods(installation.root))
17
+ continue;
18
+ unique.set(installation.root.toLocaleLowerCase(), installation);
19
+ }
20
+ return [...unique.values()].sort(compareInstallations);
21
+ }
22
+ export function resolveGameInstallation(input, platformInput = process.platform) {
23
+ const platform = supportedPlatform(platformInput);
24
+ const absolute = resolve(input);
25
+ if (!existsSync(absolute))
26
+ throw new Error(`Satisfactory path '${absolute}' does not exist.`);
27
+ const inputIsFile = statSync(absolute).isFile();
28
+ const root = inputIsFile ? dirname(absolute) : absolute;
29
+ const executable = resolveExecutable(root, platform, inputIsFile ? absolute : undefined);
30
+ assertRequiredMods(root);
31
+ return {
32
+ source: basename(executable).toLocaleLowerCase().includes("egs") ? "epic" : "steam",
33
+ channel: root.toLocaleLowerCase().includes("experimental") ? "experimental" : "stable",
34
+ root,
35
+ executable,
36
+ };
37
+ }
38
+ export function supportedPlatform(platform) {
39
+ if (platform === "win32" || platform === "linux")
40
+ return platform;
41
+ throw new Error(`Game-data export supports Windows and Linux; current platform is '${platform}'.`);
42
+ }
43
+ function detectSteamInstallations(platform, roots) {
44
+ const installations = [];
45
+ for (const steamRoot of roots) {
46
+ if (!existsSync(steamRoot))
47
+ continue;
48
+ const libraries = [steamRoot, ...readSteamLibraryPaths(join(steamRoot, "steamapps/libraryfolders.vdf"))];
49
+ for (const library of libraries) {
50
+ const steamApps = join(library, "steamapps");
51
+ const manifestPath = join(steamApps, `appmanifest_${STEAM_APP_ID}.acf`);
52
+ const manifest = readTextIfPresent(manifestPath);
53
+ const installDirectory = manifest === undefined ? "Satisfactory" : fieldValue(manifest, "installdir") ?? "Satisfactory";
54
+ const root = join(steamApps, "common", installDirectory);
55
+ if (!existsSync(manifestPath) && !existsSync(root))
56
+ continue;
57
+ const executable = join(root, "FactoryGameSteam.exe");
58
+ if (!existsSync(executable))
59
+ continue;
60
+ installations.push({
61
+ source: "steam",
62
+ channel: fieldValue(manifest ?? "", "betakey")?.toLocaleLowerCase().includes("experimental") ? "experimental" : "stable",
63
+ root,
64
+ executable,
65
+ });
66
+ }
67
+ }
68
+ return installations;
69
+ }
70
+ function detectEpicInstallations(platform, manifestDirectories) {
71
+ if (platform !== "win32")
72
+ return [];
73
+ const installations = [];
74
+ for (const directory of manifestDirectories) {
75
+ if (!existsSync(directory))
76
+ continue;
77
+ for (const entry of readdirSync(directory, { withFileTypes: true }).slice(0, 1_000)) {
78
+ if (!entry.isFile() || !entry.name.toLocaleLowerCase().endsWith(".item"))
79
+ continue;
80
+ const file = join(directory, entry.name);
81
+ if (statSync(file).size > 1024 * 1024)
82
+ continue;
83
+ const manifest = parseJsonRecord(readFileSync(file, "utf8"));
84
+ if (manifest === undefined)
85
+ continue;
86
+ const displayName = stringField(manifest, "DisplayName");
87
+ const appName = stringField(manifest, "AppName");
88
+ if (!`${displayName} ${appName}`.toLocaleLowerCase().includes("satisfactory"))
89
+ continue;
90
+ const root = stringField(manifest, "InstallLocation");
91
+ if (root === undefined || !isAbsolute(root))
92
+ continue;
93
+ const executable = join(root, "FactoryGameEGS.exe");
94
+ if (!existsSync(executable))
95
+ continue;
96
+ installations.push({
97
+ source: "epic",
98
+ channel: `${displayName} ${appName}`.toLocaleLowerCase().includes("experimental") ? "experimental" : "stable",
99
+ root,
100
+ executable,
101
+ });
102
+ }
103
+ }
104
+ return installations;
105
+ }
106
+ function defaultSteamRoots(platform, environment) {
107
+ if (platform === "win32") {
108
+ return [windowsSteamRegistryPath(), environment["ProgramFiles(x86)"], environment.ProgramFiles]
109
+ .filter((value) => value !== undefined)
110
+ .map((value) => basename(value).toLocaleLowerCase() === "steam" ? value : join(value, "Steam"));
111
+ }
112
+ const home = environment.HOME ?? homedir();
113
+ return [join(home, ".steam/steam"), join(home, ".local/share/Steam"), join(home, ".var/app/com.valvesoftware.Steam/.local/share/Steam")];
114
+ }
115
+ function windowsSteamRegistryPath() {
116
+ try {
117
+ const output = execFileSync("reg.exe", ["query", "HKCU\\Software\\Valve\\Steam", "/v", "SteamPath"], {
118
+ encoding: "utf8",
119
+ stdio: ["ignore", "pipe", "ignore"],
120
+ windowsHide: true,
121
+ });
122
+ return output.match(/SteamPath\s+REG_SZ\s+(.+)$/imu)?.[1]?.trim();
123
+ }
124
+ catch {
125
+ return undefined;
126
+ }
127
+ }
128
+ function defaultEpicManifestDirectories(platform, environment) {
129
+ if (platform !== "win32")
130
+ return [];
131
+ return [join(environment.ProgramData ?? "C:\\ProgramData", "Epic/EpicGamesLauncher/Data/Manifests")];
132
+ }
133
+ function resolveExecutable(root, platform, explicit) {
134
+ if (explicit !== undefined)
135
+ return explicit;
136
+ for (const name of platform === "win32" ? ["FactoryGameSteam.exe", "FactoryGameEGS.exe"] : ["FactoryGameSteam.exe"]) {
137
+ const executable = join(root, name);
138
+ if (existsSync(executable))
139
+ return executable;
140
+ }
141
+ throw new Error(`No supported Satisfactory client executable found in '${root}'.`);
142
+ }
143
+ function assertRequiredMods(root) {
144
+ for (const mod of REQUIRED_MODS) {
145
+ if (!hasMod(root, mod))
146
+ throw new Error(`Satisfactory installation '${root}' does not contain required ${mod} mod.`);
147
+ }
148
+ }
149
+ function hasRequiredMods(root) {
150
+ return REQUIRED_MODS.every((mod) => hasMod(root, mod));
151
+ }
152
+ function hasMod(root, mod) {
153
+ return [
154
+ join(root, "FactoryGame/Mods", mod, `${mod}.uplugin`),
155
+ join(root, "FactoryGame/Mods/GameFeatures", mod, `${mod}.uplugin`),
156
+ ].some(existsSync);
157
+ }
158
+ function readSteamLibraryPaths(file) {
159
+ const content = readTextIfPresent(file);
160
+ if (content === undefined)
161
+ return [];
162
+ const paths = [];
163
+ for (const fields of parseQuotedFields(content)) {
164
+ for (let index = 0; index + 1 < fields.length; index += 1) {
165
+ if (fields[index]?.toLocaleLowerCase() === "path")
166
+ paths.push(fields[index + 1]);
167
+ }
168
+ }
169
+ return paths;
170
+ }
171
+ function fieldValue(content, wanted) {
172
+ for (const fields of parseQuotedFields(content)) {
173
+ for (let index = 0; index + 1 < fields.length; index += 1) {
174
+ if (fields[index]?.toLocaleLowerCase() === wanted.toLocaleLowerCase())
175
+ return fields[index + 1];
176
+ }
177
+ }
178
+ return undefined;
179
+ }
180
+ function parseQuotedFields(content) {
181
+ return content.split(/\r?\n/u).map((line) => [...line.matchAll(/"((?:\\.|[^"\\])*)"/gu)].map((match) => unescapeVdf(match[1] ?? "")));
182
+ }
183
+ function unescapeVdf(value) {
184
+ return value.replaceAll("\\\\", "\\").replaceAll('\\"', '"');
185
+ }
186
+ function readTextIfPresent(path) {
187
+ return existsSync(path) ? readFileSync(path, "utf8") : undefined;
188
+ }
189
+ function parseJsonRecord(content) {
190
+ try {
191
+ const value = JSON.parse(content);
192
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
193
+ }
194
+ catch {
195
+ return undefined;
196
+ }
197
+ }
198
+ function stringField(record, key) {
199
+ const value = record[key];
200
+ return typeof value === "string" ? value : undefined;
201
+ }
202
+ function compareInstallations(left, right) {
203
+ const sourceOrder = { steam: 0, epic: 1 };
204
+ return sourceOrder[left.source] - sourceOrder[right.source] || left.channel.localeCompare(right.channel) || left.root.localeCompare(right.root);
205
+ }
@@ -0,0 +1,19 @@
1
+ import { existsSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ const SKIPPED = new Set(["node_modules", ".git"]);
4
+ /** Finds every directory below the project that contains a pack.yml (a DataForge root or sub-pack). */
5
+ export function findPackRoots(projectRoot) {
6
+ const dataForge = join(projectRoot, "DataForge");
7
+ const start = existsSync(dataForge) ? dataForge : projectRoot;
8
+ const roots = [];
9
+ const walk = (directory) => {
10
+ if (existsSync(join(directory, "pack.yml")))
11
+ roots.push(directory);
12
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
13
+ if (entry.isDirectory() && !SKIPPED.has(entry.name))
14
+ walk(join(directory, entry.name));
15
+ }
16
+ };
17
+ walk(start);
18
+ return roots;
19
+ }
@@ -0,0 +1,62 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { join, relative, resolve } from "node:path";
4
+ import { isMap, isSeq, parseDocument } from "yaml";
5
+ const SHA256_PATTERN = /^[0-9a-f]{64}$/;
6
+ export function sha256Of(file) {
7
+ return createHash("sha256").update(readFileSync(file)).digest("hex");
8
+ }
9
+ function resolveInside(packRoot, path) {
10
+ const target = resolve(packRoot, path);
11
+ return relative(packRoot, target).startsWith("..") ? undefined : target;
12
+ }
13
+ export function checkImports(packRoot, scripts) {
14
+ const diagnostics = [];
15
+ const report = (code, message) => {
16
+ diagnostics.push({ severity: "error", code, file: "pack.yml", message });
17
+ };
18
+ for (const script of scripts) {
19
+ for (const item of script.imports) {
20
+ const target = resolveInside(packRoot, item.path);
21
+ if (target === undefined || !existsSync(target)) {
22
+ report("import.missing", `Import '${item.key}': '${item.path}' does not exist inside the pack.`);
23
+ }
24
+ else if (!SHA256_PATTERN.test(item.sha256)) {
25
+ report("import.digest", `Import '${item.key}': sha256 is missing or malformed. Run 'kdf hash'.`);
26
+ }
27
+ else if (sha256Of(target) !== item.sha256) {
28
+ report("import.digest-mismatch", `Import '${item.key}': sha256 does not match '${item.path}'. Run 'kdf hash'.`);
29
+ }
30
+ }
31
+ }
32
+ return diagnostics;
33
+ }
34
+ /** Rewrites stale or missing sha256 values in place and keeps comments and formatting. Returns changed keys. */
35
+ export function syncImportDigests(packRoot) {
36
+ const manifestFile = join(packRoot, "pack.yml");
37
+ const document = parseDocument(readFileSync(manifestFile, "utf8"));
38
+ const scripts = document.get("scripts");
39
+ const changed = [];
40
+ if (isSeq(scripts)) {
41
+ for (const script of scripts.items) {
42
+ const imports = isMap(script) ? script.get("imports") : undefined;
43
+ if (!isSeq(imports))
44
+ continue;
45
+ for (const item of imports.items) {
46
+ if (!isMap(item))
47
+ continue;
48
+ const target = resolveInside(packRoot, String(item.get("path")));
49
+ if (target === undefined || !existsSync(target))
50
+ continue;
51
+ const digest = sha256Of(target);
52
+ if (item.get("sha256") !== digest) {
53
+ item.set("sha256", digest);
54
+ changed.push(String(item.get("key")));
55
+ }
56
+ }
57
+ }
58
+ }
59
+ if (changed.length > 0)
60
+ writeFileSync(manifestFile, document.toString());
61
+ return changed;
62
+ }
@@ -0,0 +1,117 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { isScalar, parseDocument } from "yaml";
5
+ import { AUTHORITIES, CANONICAL_ENTRY, IMPORT_KINDS, MAX_REFLECTION_CLASSES, NETWORKS, PACK_REF_PATTERN, REALMS, SCRIPT_LANGUAGE, } from "../conventions.js";
6
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7
+ const oneOf = (allowed, value) => typeof value === "string" && allowed.includes(value.toLowerCase());
8
+ export function readManifest(packRoot) {
9
+ const file = "pack.yml";
10
+ const diagnostics = [];
11
+ const fail = (code, message) => {
12
+ diagnostics.push({ severity: "error", code, file, message });
13
+ };
14
+ const document = parseDocument(readFileSync(join(packRoot, file), "utf8"));
15
+ for (const error of document.errors)
16
+ fail("manifest.yaml", error.message);
17
+ const root = document.toJS();
18
+ if (!isRecord(root)) {
19
+ fail("manifest.shape", "pack.yml must be a map.");
20
+ return { ref: undefined, scripts: [], diagnostics };
21
+ }
22
+ const ref = typeof root.ref === "string" ? root.ref : basename(dirname(packRoot));
23
+ if (ref !== undefined && !PACK_REF_PATTERN.test(ref))
24
+ fail("manifest.ref", `Pack ref '${ref}' is not a safe ref.`);
25
+ const rawScripts = root.scripts ?? [];
26
+ if (!Array.isArray(rawScripts)) {
27
+ fail("manifest.scripts", "`scripts` must be a sequence.");
28
+ return { ref, scripts: [], diagnostics };
29
+ }
30
+ const scripts = rawScripts.flatMap((raw, index) => parseScript(raw, index, ref, fail, document));
31
+ return { ref, scripts, diagnostics };
32
+ }
33
+ function parseScript(raw, index, ref, fail, document) {
34
+ const at = `scripts[${index}]`;
35
+ if (!isRecord(raw)) {
36
+ fail("script.shape", `${at} must be a map.`);
37
+ return [];
38
+ }
39
+ if (raw.id !== undefined)
40
+ fail("script.id", `${at}.id is generated from pack ref and entry; remove it.`);
41
+ if (raw.language !== SCRIPT_LANGUAGE)
42
+ fail("script.language", `${at}.language must be '${SCRIPT_LANGUAGE}'.`);
43
+ const version = raw.languageVersion ?? 1;
44
+ if (!Number.isInteger(version) || version <= 0) {
45
+ fail("script.language-version", `${at}.languageVersion must be a positive integer.`);
46
+ }
47
+ const entry = typeof raw.entry === "string" ? raw.entry : "";
48
+ if (entry !== CANONICAL_ENTRY)
49
+ fail("script.entry", `${at}.entry must be '${CANONICAL_ENTRY}'.`);
50
+ const id = `script.${createHash("sha256").update(`${ref ?? ""}\n${entry}`, "utf8").digest("hex")}`;
51
+ const policies = [
52
+ ["realm", REALMS],
53
+ ["network", NETWORKS],
54
+ ["authority", AUTHORITIES],
55
+ ];
56
+ for (const [key, allowed] of policies) {
57
+ if (raw[key] !== undefined && !oneOf(allowed, raw[key])) {
58
+ fail(`script.${key}`, `${at}.${key} must be ${allowed.join(", ")}.`);
59
+ }
60
+ }
61
+ if (raw.capabilities !== undefined)
62
+ fail("script.capabilities", `${at}.capabilities belongs in optional TypeScript meta.`);
63
+ checkReflectionClasses(raw, at, fail);
64
+ return [{ id, entry, realm: String(raw.realm ?? "any").toLowerCase(), authority: String(raw.authority ?? "any").toLowerCase(),
65
+ imports: parseImports(raw.imports, at, fail, (i) => rawDigest(document, index, i)) }];
66
+ }
67
+ function checkReflectionClasses(raw, at, fail) {
68
+ if (raw.reflectionClasses !== undefined && raw.classes !== undefined) {
69
+ fail("script.classes", `${at}: reflectionClasses and classes cannot both be present.`);
70
+ }
71
+ const classes = raw.reflectionClasses ?? raw.classes;
72
+ if (classes === undefined)
73
+ return;
74
+ if (!Array.isArray(classes) || classes.length > MAX_REFLECTION_CLASSES) {
75
+ fail("script.classes", `${at}.reflectionClasses must be a sequence with at most ${MAX_REFLECTION_CLASSES} entries.`);
76
+ return;
77
+ }
78
+ for (const path of classes) {
79
+ if (typeof path !== "string" || !path.startsWith("/") || path.includes("\\") || path.includes("..") || path.length > 1024) {
80
+ fail("script.classes", `${at}: invalid reflection class path '${String(path)}'.`);
81
+ }
82
+ }
83
+ if (new Set(classes).size !== classes.length)
84
+ fail("script.classes", `${at}: reflection class paths must be unique.`);
85
+ }
86
+ function parseImports(raw, at, fail, digestAt) {
87
+ if (raw === undefined)
88
+ return [];
89
+ if (!Array.isArray(raw)) {
90
+ fail("script.imports", `${at}.imports must be a sequence.`);
91
+ return [];
92
+ }
93
+ const imports = [];
94
+ for (const [index, item] of raw.entries()) {
95
+ if (!isRecord(item) || typeof item.key !== "string" || typeof item.path !== "string") {
96
+ fail("script.import", `${at}.imports[${index}] needs string key and path.`);
97
+ continue;
98
+ }
99
+ const kind = typeof item.kind === "string" ? item.kind : "";
100
+ if (!oneOf(IMPORT_KINDS, kind))
101
+ fail("script.import-kind", `${at}.imports[${index}].kind '${kind}' is unsupported.`);
102
+ const sha256 = digestAt(index);
103
+ imports.push({ key: item.key, kind, path: item.path, sha256 });
104
+ }
105
+ if (new Set(imports.map((i) => i.key)).size !== imports.length)
106
+ fail("script.import-key", `${at}: import keys must be unique.`);
107
+ return imports;
108
+ }
109
+ /** A digest made only of digits would load as a YAML number, so the digest is read as written. */
110
+ function rawDigest(document, scriptIndex, importIndex) {
111
+ for (const key of ["sha256", "digest"]) {
112
+ const node = document.getIn(["scripts", scriptIndex, "imports", importIndex, key], true);
113
+ if (isScalar(node))
114
+ return node.source ?? String(node.value);
115
+ }
116
+ return "";
117
+ }
@@ -0,0 +1,130 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, extname, relative, resolve, sep } from "node:path";
3
+ import ts from "typescript";
4
+ import { RUNTIME_MODULE, SATISFACTORY_MODULE } from "../conventions.js";
5
+ /** Walks the static import graph from the entry and reports everything the runtime would reject. */
6
+ export function checkSourceGraph(packRoot, entry) {
7
+ const diagnostics = [];
8
+ const visited = new Set();
9
+ const entryFile = resolve(packRoot, entry);
10
+ const scriptsRoot = dirname(entryFile);
11
+ const queue = [entryFile];
12
+ while (queue.length > 0) {
13
+ const file = queue.pop();
14
+ if (visited.has(file))
15
+ continue;
16
+ visited.add(file);
17
+ const shown = relative(packRoot, file).split(sep).join("/");
18
+ if (!existsSync(file)) {
19
+ diagnostics.push({ severity: "error", code: "source.missing", file: shown, message: "Module file does not exist." });
20
+ continue;
21
+ }
22
+ const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.ES2020, true);
23
+ const report = (code, message) => {
24
+ diagnostics.push({ severity: "error", code, file: shown, message });
25
+ };
26
+ visit(source, (node) => {
27
+ const specifier = staticSpecifier(node);
28
+ if (specifier !== undefined) {
29
+ const target = resolveSpecifier(scriptsRoot, file, specifier, report);
30
+ if (target !== undefined)
31
+ queue.push(target);
32
+ }
33
+ else if (isDynamicImport(node) || isRequireCall(node)) {
34
+ report("source.dynamic-import", "Dynamic import() and require() are not supported; use static imports.");
35
+ }
36
+ });
37
+ }
38
+ return diagnostics;
39
+ }
40
+ function visit(node, callback) {
41
+ callback(node);
42
+ ts.forEachChild(node, (child) => visit(child, callback));
43
+ }
44
+ function staticSpecifier(node) {
45
+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier !== undefined) {
46
+ return ts.isStringLiteral(node.moduleSpecifier) ? node.moduleSpecifier.text : undefined;
47
+ }
48
+ return undefined;
49
+ }
50
+ function isDynamicImport(node) {
51
+ return ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword;
52
+ }
53
+ function isRequireCall(node) {
54
+ return ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "require";
55
+ }
56
+ /** Mirrors FKDFJSModuleLexicalScanner::ResolveStaticImport: extensionless means `.ts`, modules stay inside scripts/. */
57
+ function resolveSpecifier(scriptsRoot, importer, specifier, report) {
58
+ if (specifier === RUNTIME_MODULE || specifier === SATISFACTORY_MODULE)
59
+ return undefined;
60
+ if (!specifier.startsWith("./") && !specifier.startsWith("../")) {
61
+ report("source.external-import", `Import '${specifier}' must be '${RUNTIME_MODULE}', '${SATISFACTORY_MODULE}', or a relative module.`);
62
+ return undefined;
63
+ }
64
+ const extension = extname(specifier);
65
+ if (extension !== "" && extension !== ".ts" && extension !== ".js") {
66
+ report("source.import-extension", `Relative import '${specifier}' must be a .ts or .js module.`);
67
+ return undefined;
68
+ }
69
+ const target = resolve(dirname(importer), extension === "" ? `${specifier}.ts` : specifier);
70
+ if (relative(scriptsRoot, target).startsWith("..")) {
71
+ report("source.outside-scripts", `Import '${specifier}' leaves the scripts folder.`);
72
+ return undefined;
73
+ }
74
+ return target;
75
+ }
76
+ /** Entry metadata is optional; default handler is required. */
77
+ export function checkEntryShape(packRoot, entry) {
78
+ const file = resolve(packRoot, entry);
79
+ if (!existsSync(file))
80
+ return [];
81
+ const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.ES2020, true);
82
+ let hasDefault = false;
83
+ for (const statement of source.statements) {
84
+ if (ts.isExportAssignment(statement) && !statement.isExportEquals)
85
+ hasDefault = true;
86
+ }
87
+ const diagnostics = [];
88
+ if (!hasDefault)
89
+ diagnostics.push({ severity: "error", code: "entry.handler", file: entry, message: "Entry must default-export `defineHandler(async (ctx) => ...)`." });
90
+ return diagnostics;
91
+ }
92
+ /** Mirrors runtime's literal-only optional defineMeta contract without executing pack code. */
93
+ export function readEntryMeta(packRoot, entry) {
94
+ const file = resolve(packRoot, entry);
95
+ if (!existsSync(file))
96
+ return { capabilities: [], diagnostics: [] };
97
+ const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.ES2020, true);
98
+ const diagnostics = [];
99
+ const hasDefineMetaImport = source.statements.some((statement) => ts.isImportDeclaration(statement) &&
100
+ ts.isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text === RUNTIME_MODULE &&
101
+ statement.importClause?.namedBindings && ts.isNamedImports(statement.importClause.namedBindings) &&
102
+ statement.importClause.namedBindings.elements.some((element) => !element.propertyName && element.name.text === "defineMeta"));
103
+ const metaDeclarations = source.statements.flatMap((statement) => ts.isVariableStatement(statement) && ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
104
+ ? statement.declarationList.declarations.filter((declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === "meta")
105
+ : []);
106
+ if (metaDeclarations.length === 0)
107
+ return { capabilities: [], diagnostics };
108
+ if (!hasDefineMetaImport)
109
+ diagnostics.push({ severity: "error", code: "entry.meta", file: entry,
110
+ message: "Optional meta requires an unaliased defineMeta import from @sf-kmods/kdataforgejs." });
111
+ const declaration = metaDeclarations.length === 1 ? metaDeclarations[0] : undefined;
112
+ const call = declaration?.initializer;
113
+ const argument = call && ts.isCallExpression(call) ? call.arguments.at(0) : undefined;
114
+ const object = call && ts.isCallExpression(call) && ts.isIdentifier(call.expression) && call.expression.text === "defineMeta" &&
115
+ call.arguments.length === 1 && argument && ts.isObjectLiteralExpression(argument) ? argument : undefined;
116
+ const firstProperty = object?.properties.at(0);
117
+ const property = object?.properties.length === 1 && firstProperty && ts.isPropertyAssignment(firstProperty) &&
118
+ ts.isIdentifier(firstProperty.name) && firstProperty.name.text === "capabilities" ? firstProperty : undefined;
119
+ const array = property && ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined;
120
+ if (!array || array.elements.some((element) => !ts.isStringLiteral(element))) {
121
+ diagnostics.push({ severity: "error", code: "entry.meta", file: entry,
122
+ message: "Optional meta must be `defineMeta({ capabilities: [literal ids] })`." });
123
+ return { capabilities: [], diagnostics };
124
+ }
125
+ const capabilities = array.elements.map((element) => element.text);
126
+ if (new Set(capabilities).size !== capabilities.length)
127
+ diagnostics.push({ severity: "error", code: "entry.meta", file: entry,
128
+ message: "Meta capability ids must be unique." });
129
+ return { capabilities, diagnostics };
130
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@sf-kmods/kdataforgejs-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.18",
4
+ "description": "kdf - create, type-check and validate KDataForge projects with KDataForgeJS (TypeScript) scripts.",
5
+ "license": "MIT",
6
+ "author": "Kyri123/Kyrium",
7
+ "homepage": "https://docs.k-mods.com/kdataforge/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Satisfactory-KMods/modding.git",
11
+ "directory": "kdataforgejs-sdk/packages/cli"
12
+ },
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
16
+ "keywords": [
17
+ "kdataforge",
18
+ "satisfactory",
19
+ "modding",
20
+ "cli"
21
+ ],
22
+ "type": "module",
23
+ "bin": {
24
+ "kdf": "dist/bin.js",
25
+ "kdataforgejs": "dist/bin.js",
26
+ "kdataforgejs-cli": "dist/bin.js"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "templates",
31
+ "README.md"
32
+ ],
33
+ "engines": {
34
+ "node": ">=20"
35
+ },
36
+ "dependencies": {
37
+ "typescript": ">=5.7.3 <6",
38
+ "yaml": "^2.6.1",
39
+ "@sf-kmods/kdataforgejs": "^0.1.18"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^22.10.0"
43
+ },
44
+ "scripts": {
45
+ "build": "tsc -p tsconfig.build.json",
46
+ "test": "tsc -p tsconfig.test.json && node --test \"dist-test/test/*.test.js\""
47
+ }
6
48
  }
@@ -0,0 +1,10 @@
1
+ ref: {{ref}}
2
+ name: {{ref}}
3
+ version: 0.1.0
4
+ priority: 0
5
+ enabled: true
6
+ description: KDataForgeJS starter pack.
7
+ scripts:
8
+ - language: kmods.typescript
9
+ languageVersion: 1
10
+ entry: scripts/main.ts
@@ -0,0 +1,3 @@
1
+ export function describeCatalog(digest: string): string {
2
+ return `{{ref}} started with catalog ${digest}`;
3
+ }
@@ -0,0 +1,7 @@
1
+ import { defineHandler } from "@sf-kmods/kdataforgejs";
2
+ import { describeCatalog } from "./lib";
3
+
4
+ export default defineHandler(async (ctx) => {
5
+ console.info(describeCatalog(ctx.catalog().digest));
6
+ await Promise.resolve();
7
+ });
@@ -0,0 +1,17 @@
1
+ # {{ref}}
2
+
3
+ KDataForge project with a KDataForgeJS (TypeScript) script, created with `kdf init`.
4
+
5
+ | Path | Purpose |
6
+ | --- | --- |
7
+ | `DataForge/` | The pack. Copy it to `FactoryGame/DataForge/<name>/` or ship it with your mod. |
8
+ | `DataForge/pack.yml` | Pack manifest including the script policy (capabilities, realm, imports). |
9
+ | `DataForge/scripts/main.ts` | Canonical entry: `export const meta` and a default `defineHandler`. |
10
+ | `package.json`, `tsconfig.json` | Editor tooling only. Never put them inside `DataForge/`. |
11
+
12
+ ```sh
13
+ npm install
14
+ npm run check # type-check against @sf-kmods/kdataforgejs
15
+ npm run validate # pack.yml, entry shape, static imports, import digests
16
+ npm run hash # refresh sha256 of declared imports after editing them
17
+ ```
@@ -0,0 +1,2 @@
1
+ node_modules/
2
+ .kdataforge/
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "{{ref}}",
3
+ "private": true,
4
+ "version": "0.1.0",
5
+ "description": "KDataForge project with KDataForgeJS (TypeScript) scripts. The DataForge folder is the pack; this file is editor tooling only.",
6
+ "scripts": {
7
+ "check": "kdf check",
8
+ "validate": "kdf validate",
9
+ "hash": "kdf hash",
10
+ "verify": "kdf check && kdf validate"
11
+ },
12
+ "devDependencies": {
13
+ "@sf-kmods/kdataforgejs": "^{{sdkVersion}}",
14
+ "@sf-kmods/kdataforgejs-cli": "^{{sdkVersion}}"
15
+ }
16
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "@sf-kmods/kdataforgejs/tsconfig.base.json",
3
+ "include": ["DataForge/**/*.ts"]
4
+ }