@sf-kmods/kdataforgejs-cli 2026.4.23 → 2026.4.28

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.
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
- import { join, relative, resolve } from "node:path";
2
+ import { existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import { isInside } from "./discover.js";
4
5
  import { isMap, isSeq, parseDocument } from "yaml";
5
6
  const SHA256_PATTERN = /^[0-9a-f]{64}$/;
6
7
  export function sha256Of(file) {
@@ -8,7 +9,7 @@ export function sha256Of(file) {
8
9
  }
9
10
  function resolveInside(packRoot, path) {
10
11
  const target = resolve(packRoot, path);
11
- return relative(packRoot, target).startsWith("..") ? undefined : target;
12
+ return isInside(packRoot, target) && (!existsSync(target) || isInside(realpathSync(packRoot), realpathSync(target))) ? target : undefined;
12
13
  }
13
14
  export function checkImports(packRoot, scripts) {
14
15
  const diagnostics = [];
@@ -33,6 +34,12 @@ export function checkImports(packRoot, scripts) {
33
34
  }
34
35
  /** Rewrites stale or missing sha256 values in place and keeps comments and formatting. Returns changed keys. */
35
36
  export function syncImportDigests(packRoot) {
37
+ const update = updatedImportDigests(packRoot);
38
+ if (update.changed.length > 0)
39
+ writeFileSync(join(packRoot, "pack.yml"), update.content);
40
+ return update.changed;
41
+ }
42
+ export function updatedImportDigests(packRoot) {
36
43
  const manifestFile = join(packRoot, "pack.yml");
37
44
  const document = parseDocument(readFileSync(manifestFile, "utf8"));
38
45
  const scripts = document.get("scripts");
@@ -56,7 +63,5 @@ export function syncImportDigests(packRoot) {
56
63
  }
57
64
  }
58
65
  }
59
- if (changed.length > 0)
60
- writeFileSync(manifestFile, document.toString());
61
- return changed;
66
+ return { content: document.toString(), changed };
62
67
  }
@@ -1,7 +1,8 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
2
2
  import { dirname, extname, relative, resolve, sep } from "node:path";
3
3
  import ts from "typescript";
4
4
  import { RUNTIME_MODULE, SATISFACTORY_MODULE } from "../conventions.js";
5
+ import { isInside } from "./discover.js";
5
6
  /** Walks the static import graph from the entry and reports everything the runtime would reject. */
6
7
  export function checkSourceGraph(packRoot, entry) {
7
8
  const diagnostics = [];
@@ -67,7 +68,7 @@ function resolveSpecifier(scriptsRoot, importer, specifier, report) {
67
68
  return undefined;
68
69
  }
69
70
  const target = resolve(dirname(importer), extension === "" ? `${specifier}.ts` : specifier);
70
- if (relative(scriptsRoot, target).startsWith("..")) {
71
+ if (!isInside(scriptsRoot, target) || (existsSync(target) && !isInside(realpathSync(scriptsRoot), realpathSync(target)))) {
71
72
  report("source.outside-scripts", `Import '${specifier}' leaves the scripts folder.`);
72
73
  return undefined;
73
74
  }
@@ -0,0 +1,110 @@
1
+ import { closeSync, existsSync, lstatSync, mkdirSync, openSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { dirname, join, relative, resolve, sep } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { workspaceRootFor } from "./discover.js";
5
+ /** Serializes CLI writers. A stale lock needs deliberate removal after checking no writer remains. */
6
+ export function withProjectLock(root, run) {
7
+ if (!existsSync(root) || !statSync(root).isDirectory())
8
+ throw new Error(`Project directory does not exist: ${root}`);
9
+ const lockRoot = workspaceRootFor(root);
10
+ const directory = join(lockRoot, ".kdataforge");
11
+ assertSafeWrite(lockRoot, join(directory, "writer.lock"));
12
+ mkdirSync(directory, { recursive: true });
13
+ const lock = join(directory, "writer.lock");
14
+ let handle;
15
+ try {
16
+ handle = openSync(lock, "wx");
17
+ }
18
+ catch {
19
+ throw new Error(`KDF writer lock exists: ${lock}. Check for a running writer before removing it.`);
20
+ }
21
+ try {
22
+ return run();
23
+ }
24
+ finally {
25
+ closeSync(handle);
26
+ rmSync(lock, { force: true });
27
+ }
28
+ }
29
+ export async function withProjectLockAsync(root, run) {
30
+ if (!existsSync(root) || !statSync(root).isDirectory())
31
+ throw new Error(`Project directory does not exist: ${root}`);
32
+ const lockRoot = workspaceRootFor(root);
33
+ const directory = join(lockRoot, ".kdataforge");
34
+ assertSafeWrite(lockRoot, join(directory, "writer.lock"));
35
+ mkdirSync(directory, { recursive: true });
36
+ const lock = join(directory, "writer.lock");
37
+ let handle;
38
+ try {
39
+ handle = openSync(lock, "wx");
40
+ }
41
+ catch {
42
+ throw new Error(`KDF writer lock exists: ${lock}. Check for a running writer before removing it.`);
43
+ }
44
+ try {
45
+ return await run();
46
+ }
47
+ finally {
48
+ closeSync(handle);
49
+ rmSync(lock, { force: true });
50
+ }
51
+ }
52
+ export function stageText(target, content) {
53
+ mkdirSync(dirname(target), { recursive: true });
54
+ const stage = `${target}.${randomUUID()}.stage`;
55
+ writeFileSync(stage, content, { flag: "wx" });
56
+ return { target, stage };
57
+ }
58
+ export function stageTexts(files) {
59
+ const stages = [];
60
+ try {
61
+ for (const file of files)
62
+ stages.push(stageText(file.path, file.content));
63
+ return stages;
64
+ }
65
+ catch (error) {
66
+ for (const stage of stages)
67
+ rmSync(stage.stage, { force: true });
68
+ throw error;
69
+ }
70
+ }
71
+ export function assertSafeWrite(root, target) {
72
+ const base = resolve(root);
73
+ let path = resolve(target);
74
+ const relativePath = relative(base, path);
75
+ if (relativePath === ".." || relativePath.startsWith(`..${sep}`))
76
+ throw new Error(`Write escapes project: ${target}`);
77
+ while (path !== base) {
78
+ if (existsSync(path) && lstatSync(path).isSymbolicLink())
79
+ throw new Error(`Write path contains symlink: ${path}`);
80
+ path = dirname(path);
81
+ }
82
+ }
83
+ /** Staged files/directories swap under the writer lock; ordinary failures restore old paths. */
84
+ export function commitStaged(paths) {
85
+ const committed = [];
86
+ try {
87
+ for (const { target, stage } of paths) {
88
+ const backup = existsSync(target) ? `${target}.${randomUUID()}.backup` : undefined;
89
+ if (backup)
90
+ renameSync(target, backup);
91
+ committed.push({ target, ...(backup ? { backup } : {}) });
92
+ renameSync(stage, target);
93
+ }
94
+ }
95
+ catch (error) {
96
+ for (const item of committed.reverse()) {
97
+ rmSync(item.target, { recursive: true, force: true });
98
+ if (item.backup)
99
+ renameSync(item.backup, item.target);
100
+ }
101
+ throw error;
102
+ }
103
+ finally {
104
+ for (const item of paths)
105
+ rmSync(item.stage, { recursive: true, force: true });
106
+ }
107
+ for (const item of committed)
108
+ if (item.backup)
109
+ rmSync(item.backup, { recursive: true, force: true });
110
+ }
@@ -1,8 +1,9 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
2
2
  import { dirname, extname, relative, resolve, sep } from "node:path";
3
3
  import ts from "typescript";
4
4
  import { parse } from "yaml";
5
5
  import { RUNTIME_MODULE, SATISFACTORY_MODULE } from "../conventions.js";
6
+ import { isInside } from "./discover.js";
6
7
  const REFLECTION_METHODS = new Set(["getClass", "getObject", "getDataAsset"]);
7
8
  /** Discovers manifest authority inputs from reachable TypeScript and imported YAML without executing pack code. */
8
9
  export function discoverPackUsage(packRoot, entry) {
@@ -27,6 +28,18 @@ export function discoverPackUsage(packRoot, entry) {
27
28
  if (target !== undefined)
28
29
  queue.push(target);
29
30
  }
31
+ if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) &&
32
+ (node.expression.text === "YMLFile" || node.expression.text === "JSONFile")) {
33
+ if (declaresName(source, node.expression.text)) {
34
+ throw new Error(`${shownPath(packRoot, file)}: ${node.expression.text} cannot be shadowed.`);
35
+ }
36
+ const path = stringLiteral(node.arguments?.[0]);
37
+ const validExtension = node.expression.text === "JSONFile" ? path?.endsWith(".json") : /\.ya?ml$/.test(path ?? "");
38
+ if (node.arguments?.length !== 1 || path === undefined || !validExtension) {
39
+ throw new Error(`${shownPath(packRoot, file)}: ${node.expression.text} requires one literal pack-relative path with the matching extension.`);
40
+ }
41
+ imports.set(`yaml\n${path}`, { kind: "yaml", path });
42
+ }
30
43
  if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression))
31
44
  return;
32
45
  const method = node.expression.name.text;
@@ -58,6 +71,21 @@ export function discoverPackUsage(packRoot, entry) {
58
71
  reflectionClasses: [...reflectionClasses].sort((left, right) => left.localeCompare(right)),
59
72
  };
60
73
  }
74
+ function declaresName(source, name) {
75
+ let declared = false;
76
+ visit(source, (node) => {
77
+ if (declared)
78
+ return;
79
+ if ((ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) ||
80
+ ts.isParameter(node)) && node.name && ts.isIdentifier(node.name) && node.name.text === name)
81
+ declared = true;
82
+ if (ts.isImportSpecifier(node) && node.name.text === name)
83
+ declared = true;
84
+ if (ts.isImportClause(node) && node.name?.text === name)
85
+ declared = true;
86
+ });
87
+ return declared;
88
+ }
61
89
  function visit(node, callback) {
62
90
  callback(node);
63
91
  ts.forEachChild(node, (child) => visit(child, callback));
@@ -74,14 +102,17 @@ function resolveModule(scriptsRoot, importer, specifier) {
74
102
  return undefined;
75
103
  const extension = extname(specifier);
76
104
  const target = resolve(dirname(importer), extension === "" ? `${specifier}.ts` : specifier);
77
- return relative(scriptsRoot, target).startsWith("..") ? undefined : target;
105
+ if (!isInside(scriptsRoot, target) || (existsSync(target) && !isInside(realpathSync(scriptsRoot), realpathSync(target)))) {
106
+ throw new Error(`Script import escapes scripts/: ${specifier}`);
107
+ }
108
+ return target;
78
109
  }
79
110
  function stringLiteral(node) {
80
111
  return node !== undefined && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : undefined;
81
112
  }
82
113
  function resolveInside(packRoot, path) {
83
114
  const target = resolve(packRoot, path);
84
- return relative(packRoot, target).startsWith("..") ? undefined : target;
115
+ return isInside(packRoot, target) && (!existsSync(target) || isInside(realpathSync(packRoot), realpathSync(target))) ? target : undefined;
85
116
  }
86
117
  function collectYamlTargets(value, targets) {
87
118
  if (Array.isArray(value)) {
@@ -8,6 +8,14 @@ const MAX_FIELDS = 1024;
8
8
  const MAX_DIRECTORY_DEPTH = 16;
9
9
  /** Emits pack-local keys only; a generated map never grants config access to a script. */
10
10
  export function syncConfigTypes(packRoot) {
11
+ const output = generateConfigTypes(packRoot);
12
+ if (!existsSync(output.path) || readFileSync(output.path, "utf8") !== output.content) {
13
+ mkdirSync(dirname(output.path), { recursive: true });
14
+ writeFileSync(output.path, output.content);
15
+ }
16
+ return output.path;
17
+ }
18
+ export function generateConfigTypes(packRoot) {
11
19
  const fields = new Map();
12
20
  for (const path of configFiles(packRoot)) {
13
21
  const document = parse(readFileSync(path, "utf8"));
@@ -29,11 +37,7 @@ export function syncConfigTypes(packRoot) {
29
37
  const entries = [...fields].sort(([left], [right]) => left.localeCompare(right))
30
38
  .map(([id, type]) => `readonly ${JSON.stringify(id)}: ${type};`).join("\n");
31
39
  const content = formatGeneratedContent(`// Generated by kdf sync. Do not edit.\ndeclare module "@sf-kmods/kdataforgejs" { export interface ConfigValueMap {\n${entries}\n} }\n`, path);
32
- if (!existsSync(path) || readFileSync(path, "utf8") !== content) {
33
- mkdirSync(dirname(path), { recursive: true });
34
- writeFileSync(path, content);
35
- }
36
- return path;
40
+ return { path, content };
37
41
  }
38
42
  function configFiles(root) {
39
43
  const result = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sf-kmods/kdataforgejs-cli",
3
- "version": "2026.4.23",
3
+ "version": "2026.4.28",
4
4
  "description": "kdf - create, type-check and validate KDataForge projects with KDataForgeJS (TypeScript) scripts.",
5
5
  "license": "MIT",
6
6
  "author": "Kyri123/Kyrium",
@@ -39,7 +39,7 @@
39
39
  "@biomejs/wasm-nodejs": "2.6.3",
40
40
  "typescript": ">=5.7.3 <6",
41
41
  "yaml": "^2.6.1",
42
- "@sf-kmods/kdataforgejs": "^2026.4.23"
42
+ "@sf-kmods/kdataforgejs": "^2026.4.28"
43
43
  },
44
44
  "devDependencies": {
45
45
  "@types/node": "^22.10.0"
@@ -0,0 +1,7 @@
1
+ import type { Context } from "@sf-kmods/kdataforgejs";
2
+ import { describeCatalog } from "../lib/catalog-v1";
3
+
4
+ export function install(ctx: Context): () => void {
5
+ const timer = ctx.setTimeout(() => console.info(describeCatalog("{{ref}}", ctx.catalog().digest)), 0.1);
6
+ return () => ctx.clearTimeout(timer);
7
+ }
@@ -0,0 +1,3 @@
1
+ export function describeCatalog(packId: string, digest: string): string {
2
+ return `${packId} started with catalog ${digest}`;
3
+ }
@@ -1,7 +1,12 @@
1
- import { defineHandler } from "@sf-kmods/kdataforgejs";
2
- import { describeCatalog } from "./lib";
1
+ import { defineHandler, defineMeta } from "@sf-kmods/kdataforgejs";
2
+ import { install as installCatalog } from "./features/catalog";
3
+
4
+ export const meta = defineMeta({ capabilities: [] });
5
+
6
+ const ENABLE_CATALOG_FEATURE = false;
3
7
 
4
8
  export default defineHandler(async (ctx) => {
5
- console.info(describeCatalog(ctx.catalog().digest));
9
+ const cleanup = ctx.createCleanupBag();
10
+ if (ENABLE_CATALOG_FEATURE) cleanup.add(installCatalog(ctx));
6
11
  await Promise.resolve();
7
12
  });
@@ -6,7 +6,9 @@ KDataForge project with a KDataForgeJS (TypeScript) script, created with `kdf in
6
6
  | --- | --- |
7
7
  | `DataForge/` | The pack. Copy it to `FactoryGame/DataForge/<name>/` or ship it with your mod. |
8
8
  | `DataForge/pack.yml` | Pack manifest with script entry, optional realm policy, imports, and reflected classes. |
9
- | `DataForge/scripts/main.ts` | Canonical entry with default `defineHandler` and optional capability `meta`. |
9
+ | `DataForge/scripts/main.ts` | Canonical entry with default `defineHandler`, `defineMeta`, feature flag and cleanup bag. |
10
+ | `DataForge/scripts/features/catalog.ts` | Typed `install(ctx): disposer` example, disabled by default. |
11
+ | `DataForge/scripts/lib/catalog-v1.ts` | Named, typed reusable helper. |
10
12
  | `package.json`, `tsconfig.json` | Editor tooling only. Never put them inside `DataForge/`. |
11
13
 
12
14
  ```sh
@@ -22,7 +24,25 @@ npm run validate # pack.yml, entry shape, static imports, import digests
22
24
  npm run hash # refresh sha256 of declared imports after editing them
23
25
  npm run fix # format scripts and synchronize generated manifest fields
24
26
  npm run verify # sync, type-check, lint and validate
27
+ kdf update # inspect installed SDK/CLI versions and game-data freshness
28
+ kdf update --apply # update local dev dependencies, then refresh game data
25
29
  ```
26
30
 
31
+ For a multi-pack repository, create each project with `kdf init packs/<name> --name <ref>`.
32
+ Declare `packs/*` in root npm `workspaces` or `pnpm-workspace.yaml`, and install once from
33
+ workspace root. Root commands cover every pack; use `--pack <ref>` to target one for checks,
34
+ formatting or scaffolding. `kdf game-data` refreshes all packs from one installed-game export.
35
+ `kdf update --offline --apply` uses packages already installed and leaves lockfiles alone.
36
+
37
+ Set `ENABLE_CATALOG_FEATURE` in `scripts/main.ts` to `true` to install the example feature. The entry
38
+ registers its disposer in `ctx.createCleanupBag()`; call `dispose()` if you stop a feature early. Realm shutdown
39
+ cleans up timers and subscriptions automatically. Keep direct `satisfactory` imports inside a versioned
40
+ `scripts/lib/<library>-v1.ts` helper when adding game types. Declare capabilities only through entry
41
+ `defineMeta({ capabilities: [...] })`.
42
+
43
+ Disabled features still count toward the static source graph, authorized imports/reflection classes, and
44
+ file/depth limits. Keep one `scripts/main.ts` entry and use static same-pack imports only. Pack scripts cannot
45
+ load `node_modules`, sibling-pack runtime modules, network modules, dynamic imports or a shared VM.
46
+
27
47
  Use `npx kdf add item Example` (or `recipe`, `handler`, `hook`, `document`) to create a scaffold.
28
48
  Edit placeholder item/recipe values before loading the pack. `npx kdf game-data --force` rebuilds cached game data.
@@ -1,3 +0,0 @@
1
- export function describeCatalog(digest: string): string {
2
- return `{{ref}} started with catalog ${digest}`;
3
- }