@sf-kmods/kdataforgejs-cli 2026.4.24 → 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,12 +1,14 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
- import { appendFileSync, closeSync, copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { closeSync, copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import { basename, dirname, extname, join, relative, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { detectGameInstallations, resolveGameInstallation, supportedPlatform } from "../game/installations.js";
8
8
  import { formatGeneratedContent } from "../types/format.js";
9
9
  import { organizeGeneratedDeclarations } from "../types/organize.js";
10
+ import { isInside } from "../pack/discover.js";
11
+ import { assertSafeWrite, commitStaged, stageText, withProjectLockAsync } from "../pack/transaction.js";
10
12
  const DEFAULT_TIMEOUT_MILLISECONDS = 15 * 60 * 1_000;
11
13
  const POLL_INTERVAL_MILLISECONDS = 500;
12
14
  const CACHE_SCHEMA = 1;
@@ -127,6 +129,46 @@ function readCache(cachePath) {
127
129
  return undefined;
128
130
  }
129
131
  }
132
+ /** Read-only comparison with the installed-game cache; unknown never means current. */
133
+ export function inspectGameData(destination, projectRoots, gamePath) {
134
+ const root = resolve(destination);
135
+ const archive = join(root, ".kdataforge/satisfactory.kdfdata");
136
+ if (!existsSync(archive))
137
+ return { status: "stale", message: "Game-data archive is missing." };
138
+ if (projectRoots.some((project) => !existsSync(join(project, "DataForge/typescript/kdataforgejs/index.d.ts")))) {
139
+ return { status: "stale", message: "One or more pack projects lack generated reflection types." };
140
+ }
141
+ try {
142
+ const receiptPath = join(root, ".kdataforge/install-receipt.json");
143
+ if (!existsSync(receiptPath))
144
+ return { status: "unknown", message: "Installed types have no verification receipt; refresh to verify." };
145
+ const receipt = JSON.parse(readFileSync(receiptPath, "utf8"));
146
+ if (receipt.schema !== 1 || receipt.archiveSha256 !== sha256(archive) ||
147
+ projectRoots.some((project) => receipt.projects[relative(root, project).split("\\").join("/") || "."] !==
148
+ treeHash(join(project, "DataForge/typescript/kdataforgejs")))) {
149
+ return { status: "stale", message: "Installed archive or reflection types differ from the installation receipt." };
150
+ }
151
+ const platform = supportedPlatform(process.platform);
152
+ const installation = selectInstallation(gamePath, platform);
153
+ const savePath = resolveSavePath(undefined, installation, platform);
154
+ const key = cacheKey(installation, platform, savePath);
155
+ const cached = key && readCache(join(root, ".kdataforge/cache", key));
156
+ if (!cached)
157
+ return { status: "unknown", message: "No validated cache for the current installation and save; refresh to verify." };
158
+ return sha256(archive) === sha256(cached.archive)
159
+ ? { status: "current", message: "Archive matches current installed-game cache; reflection types are present." }
160
+ : { status: "stale", message: "Installed archive differs from current installed-game cache." };
161
+ }
162
+ catch (error) {
163
+ return { status: "unknown", message: error instanceof Error ? error.message : String(error) };
164
+ }
165
+ }
166
+ function treeHash(root) {
167
+ const hash = createHash("sha256");
168
+ for (const path of filesBelow(root))
169
+ hash.update(`${relative(root, path).split("\\").join("/")}\0${sha256(path)}\n`);
170
+ return hash.digest("hex");
171
+ }
130
172
  function publishCache(cachePath, artifacts) {
131
173
  mkdirSync(cachePath, { recursive: true });
132
174
  const stage = mkdtempSync(join(cachePath, ".stage-"));
@@ -166,12 +208,18 @@ export async function importGameData(options, dependencies = {}) {
166
208
  const installation = selectInstallation(options.gamePath, platform);
167
209
  const savePath = resolveSavePath(options.savePath, installation, platform);
168
210
  const destination = resolve(options.destination);
211
+ mkdirSync(destination, { recursive: true });
212
+ return withProjectLockAsync(destination, async () => importLocked({ ...options, destination }, dependencies, platform, installation, savePath, timeoutMilliseconds));
213
+ }
214
+ async function importLocked(options, dependencies, platform, installation, savePath, timeoutMilliseconds) {
215
+ const destination = options.destination;
169
216
  const cacheRoot = join(destination, ".kdataforge/cache");
217
+ assertSafeWrite(destination, join(cacheRoot, "current"));
170
218
  const key = cacheKey(installation, platform, savePath);
171
219
  const cachePath = key === undefined ? undefined : join(cacheRoot, key);
172
220
  const cached = options.force || cachePath === undefined ? undefined : readCache(cachePath);
173
221
  if (cached)
174
- return { ...installExport({ ...options, destination }, installation, cached), cacheHit: true };
222
+ return { ...installExport(options, installation, cached), cacheHit: true };
175
223
  const exportDirectory = mkdtempSync(join(tmpdir(), "kdf-game-data-export-"));
176
224
  try {
177
225
  const plan = createLaunchPlan(installation, platform, exportDirectory, savePath);
@@ -180,7 +228,7 @@ export async function importGameData(options, dependencies = {}) {
180
228
  if (launchedGame !== undefined)
181
229
  await waitForCleanGameExit(launchedGame.exited);
182
230
  const published = cachePath === undefined ? artifacts : publishCache(cachePath, artifacts);
183
- return { ...installExport({ ...options, destination }, installation, published), cacheHit: false };
231
+ return { ...installExport(options, installation, published), cacheHit: false };
184
232
  }
185
233
  finally {
186
234
  cleanupTemporaryExport(exportDirectory);
@@ -339,32 +387,70 @@ function findCompletedExport(exportDirectory) {
339
387
  return { archive, typesDirectory };
340
388
  }
341
389
  function installExport(options, installation, artifacts) {
342
- const destination = options.destination;
390
+ const destination = resolve(options.destination);
343
391
  mkdirSync(destination, { recursive: true });
344
392
  const archiveDirectory = join(destination, ".kdataforge");
345
393
  mkdirSync(archiveDirectory, { recursive: true });
346
394
  const archivePath = join(archiveDirectory, "satisfactory.kdfdata");
347
- copyFileSync(artifacts.archive, archivePath);
348
- const typesDirectory = join(destination, "DataForge/typescript/kdataforgejs");
349
- rmSync(typesDirectory, { recursive: true, force: true });
350
- mkdirSync(typesDirectory, { recursive: true });
351
- cpSync(artifacts.typesDirectory, typesDirectory, { recursive: true });
352
- const declarationPath = organizeGeneratedDeclarations(typesDirectory, { contentTypes: options.contentTypes });
353
- const tsconfigPath = join(destination, "tsconfig.kdf.json");
354
- writeFileSync(tsconfigPath, formatGeneratedContent(JSON.stringify({
355
- extends: "./DataForge/typescript/kdataforgejs/tsconfig.json",
356
- include: ["DataForge/**/*.ts"],
357
- }), tsconfigPath));
358
- ensureGitIgnoreEntry(destination, ".kdataforge/");
359
- return { installation, archivePath, declarationPath };
360
- }
361
- function ensureGitIgnoreEntry(destination, entry) {
362
- const gitIgnore = join(destination, ".gitignore");
363
- const existing = existsSync(gitIgnore) ? readFileSync(gitIgnore, "utf8") : "";
364
- if (existing.split(/\r?\n/u).includes(entry))
365
- return;
366
- const separator = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
367
- appendFileSync(gitIgnore, `${separator}${entry}\n`);
395
+ assertSafeWrite(destination, archivePath);
396
+ const projects = [...new Set(options.projectRoots ?? [destination])];
397
+ const stages = [];
398
+ try {
399
+ const archiveStage = `${archivePath}.${process.pid}-${Date.now()}.stage`;
400
+ copyFileSync(artifacts.archive, archiveStage);
401
+ stages.push({ target: archivePath, stage: archiveStage });
402
+ let declarationPath = "";
403
+ const projectHashes = {};
404
+ for (const project of projects) {
405
+ const root = resolve(project);
406
+ if (!isInside(destination, root) || !isInside(realpathSync(destination), realpathSync(root)) ||
407
+ (options.projectRoots && !existsSync(join(root, "DataForge/pack.yml")))) {
408
+ throw new Error(`Game-data target is not a pack project inside ${destination}: ${root}`);
409
+ }
410
+ const typesDirectory = join(root, "DataForge/typescript/kdataforgejs");
411
+ assertSafeWrite(root, typesDirectory);
412
+ if (existsSync(typesDirectory) && !isInside(root, realpathSync(typesDirectory))) {
413
+ throw new Error(`Generated types escape pack project: ${typesDirectory}`);
414
+ }
415
+ mkdirSync(dirname(typesDirectory), { recursive: true });
416
+ const typesStage = mkdtempSync(join(dirname(typesDirectory), ".kdf-types-"));
417
+ stages.push({ target: typesDirectory, stage: typesStage });
418
+ cpSync(artifacts.typesDirectory, typesStage, { recursive: true });
419
+ organizeGeneratedDeclarations(typesStage, { contentTypes: options.contentTypes });
420
+ projectHashes[relative(destination, root).split("\\").join("/") || "."] = treeHash(typesStage);
421
+ declarationPath ||= join(typesDirectory, "index.d.ts");
422
+ const tsconfigPath = join(root, "tsconfig.kdf.json");
423
+ assertSafeWrite(root, tsconfigPath);
424
+ stages.push(stageText(tsconfigPath, formatGeneratedContent(JSON.stringify({
425
+ extends: "./DataForge/typescript/kdataforgejs/tsconfig.json",
426
+ include: ["DataForge/**/*.ts"],
427
+ }), tsconfigPath)));
428
+ }
429
+ const gitIgnore = join(destination, ".gitignore");
430
+ assertSafeWrite(destination, gitIgnore);
431
+ const existing = existsSync(gitIgnore) ? readFileSync(gitIgnore, "utf8") : "";
432
+ if (!existing.split(/\r?\n/u).includes(".kdataforge/")) {
433
+ const separator = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
434
+ stages.push(stageText(gitIgnore, `${existing}${separator}.kdataforge/\n`));
435
+ }
436
+ for (const file of options.synchronizedFiles ?? []) {
437
+ assertSafeWrite(destination, file.path);
438
+ const actual = existsSync(file.path) ? readFileSync(file.path, "utf8") : undefined;
439
+ if (actual !== file.expected)
440
+ throw new Error(`Authored file changed during game-data export: ${file.path}`);
441
+ stages.push(stageText(file.path, file.content));
442
+ }
443
+ const receiptPath = join(archiveDirectory, "install-receipt.json");
444
+ assertSafeWrite(destination, receiptPath);
445
+ stages.push(stageText(receiptPath, `${JSON.stringify({ schema: 1, archiveSha256: sha256(artifacts.archive),
446
+ projects: projectHashes })}\n`));
447
+ commitStaged(stages);
448
+ return { installation, archivePath, declarationPath };
449
+ }
450
+ finally {
451
+ for (const stage of stages)
452
+ rmSync(stage.stage, { recursive: true, force: true });
453
+ }
368
454
  }
369
455
  function delay(milliseconds) {
370
456
  return new Promise((resolveDelay) => setTimeout(resolveDelay, milliseconds));
@@ -1,6 +1,14 @@
1
- import { findPackRoots } from "../pack/discover.js";
2
- import { syncImportDigests } from "../pack/imports.js";
1
+ import { join } from "node:path";
2
+ import { discoverPacks } from "../pack/discover.js";
3
+ import { updatedImportDigests } from "../pack/imports.js";
4
+ import { commitStaged, stageTexts, withProjectLock } from "../pack/transaction.js";
3
5
  /** 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
+ export function hashProject(projectRoot, packRef) {
7
+ discoverPacks(projectRoot, packRef);
8
+ return withProjectLock(projectRoot, () => {
9
+ const updates = discoverPacks(projectRoot, packRef).packs.map((pack) => ({ root: pack.root, ...updatedImportDigests(pack.root) }));
10
+ commitStaged(stageTexts(updates.filter((item) => item.changed.length > 0)
11
+ .map((item) => ({ path: join(item.root, "pack.yml"), content: item.content }))));
12
+ return updates.flatMap((item) => item.changed.map((key) => `${item.root}: ${key}`));
13
+ });
6
14
  }
@@ -1,21 +1,21 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { join, relative, resolve, sep } from "node:path";
3
3
  import { spanInBytesToSpanInCodeUnits } from "@biomejs/js-api/nodejs";
4
+ import { discoverPacks } from "../pack/discover.js";
4
5
  import { findScriptFiles } from "../pack/scriptFiles.js";
5
6
  import { biome, biomeProjectKey } from "../types/biome.js";
6
7
  /** Lints every JavaScript and TypeScript source file in DataForge/scripts with bundled Biome rules. */
7
- export function lintProject(projectRoot) {
8
+ export function lintProject(projectRoot, packRef) {
8
9
  const absoluteProjectRoot = resolve(projectRoot);
9
- const scriptsRoot = join(absoluteProjectRoot, "DataForge/scripts");
10
- if (!existsSync(scriptsRoot)) {
11
- return [{
12
- severity: "error",
13
- code: "lint.no-scripts",
14
- file: "DataForge/scripts",
15
- message: "Scripts directory not found. Run 'kdf init' or pass project root.",
16
- }];
17
- }
18
- return findScriptFiles(scriptsRoot).flatMap((filePath) => lintFile(filePath, absoluteProjectRoot));
10
+ const roots = discoverPacks(absoluteProjectRoot, packRef).packs.map((pack) => join(pack.root, "scripts"));
11
+ const diagnostics = roots.filter((scriptsRoot) => !existsSync(scriptsRoot)).map((scriptsRoot) => ({
12
+ severity: "error",
13
+ code: "lint.no-scripts",
14
+ file: relative(absoluteProjectRoot, scriptsRoot),
15
+ message: "Scripts directory not found. Run 'kdf init' or pass project root.",
16
+ }));
17
+ const files = new Set(roots.filter(existsSync).flatMap(findScriptFiles));
18
+ return [...diagnostics, ...[...files].sort().flatMap((filePath) => lintFile(filePath, absoluteProjectRoot))];
19
19
  }
20
20
  function lintFile(filePath, projectRoot) {
21
21
  const content = readFileSync(filePath, "utf8");
@@ -1,32 +1,50 @@
1
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { isMap, isSeq, parseDocument, YAMLMap, YAMLSeq } from "yaml";
4
- import { findPackRoots } from "../pack/discover.js";
4
+ import { discoverPacks, isInside } from "../pack/discover.js";
5
5
  import { sha256Of } from "../pack/imports.js";
6
+ import { assertSafeWrite, commitStaged, stageTexts, withProjectLock } from "../pack/transaction.js";
6
7
  import { discoverPackUsage } from "../pack/usage.js";
7
- import { syncConfigTypes } from "../types/configTypes.js";
8
+ import { generateConfigTypes } from "../types/configTypes.js";
8
9
  /** Generates manifest imports, digests, and reflection class authority from source usage. */
9
- export function syncProject(projectRoot) {
10
- if (!existsSync(projectRoot))
11
- return { changedPacks: [] };
12
- const changedPacks = findPackRoots(projectRoot).filter((packRoot) => syncPack(packRoot, true));
13
- return { changedPacks };
10
+ export function syncProject(projectRoot, packRef) {
11
+ discoverPacks(projectRoot, packRef);
12
+ return withProjectLock(projectRoot, () => {
13
+ const prepared = prepareSync(projectRoot, packRef);
14
+ for (const file of prepared.files) {
15
+ const actual = existsSync(file.path) ? readFileSync(file.path, "utf8") : undefined;
16
+ if (actual !== file.expected)
17
+ throw new Error(`Authored file changed during sync: ${file.path}`);
18
+ }
19
+ commitStaged(stageTexts(prepared.files));
20
+ return prepared.result;
21
+ });
14
22
  }
15
23
  /** Reports manifest drift using the same generation path without changing files. */
16
- export function inspectSyncDrift(projectRoot) {
17
- if (!existsSync(projectRoot))
18
- return { changedPacks: [] };
19
- return { changedPacks: findPackRoots(projectRoot).filter((packRoot) => syncPack(packRoot, false)) };
24
+ export function inspectSyncDrift(projectRoot, packRef) {
25
+ return prepareSync(projectRoot, packRef).result;
26
+ }
27
+ export function prepareSync(projectRoot, packRef) {
28
+ const outputs = discoverPacks(projectRoot, packRef).packs.map((pack) => syncPack(pack.root));
29
+ for (const output of outputs) {
30
+ assertSafeWrite(output.root, output.manifest.path);
31
+ assertSafeWrite(output.root, output.config.path);
32
+ }
33
+ return {
34
+ result: { changedPacks: outputs.filter((output) => output.manifest.changed).map((output) => output.root),
35
+ changedTypes: outputs.filter((output) => output.config.changed).map((output) => output.config.path) },
36
+ files: outputs.flatMap((output) => [output.manifest, output.config].filter((file) => file.changed)
37
+ .map((file) => ({ path: file.path, content: file.content,
38
+ ...(existsSync(file.path) ? { expected: readFileSync(file.path, "utf8") } : {}) }))),
39
+ };
20
40
  }
21
- function syncPack(packRoot, write) {
41
+ function syncPack(packRoot) {
22
42
  const manifestFile = join(packRoot, "pack.yml");
23
43
  const before = readFileSync(manifestFile, "utf8");
24
44
  const document = parseDocument(before);
25
45
  const scripts = document.get("scripts", true);
26
- if (!isSeq(scripts))
27
- return false;
28
- syncConfigTypes(packRoot);
29
- for (const script of scripts.items) {
46
+ const config = generateConfigTypes(packRoot);
47
+ for (const script of isSeq(scripts) ? scripts.items : []) {
30
48
  if (!isMap(script))
31
49
  continue;
32
50
  const entry = String(script.get("entry") ?? "");
@@ -37,11 +55,9 @@ function syncPack(packRoot, write) {
37
55
  setImports(script, packRoot, usage.imports);
38
56
  }
39
57
  const after = document.toString();
40
- if (after === before)
41
- return false;
42
- if (write)
43
- writeFileSync(manifestFile, after);
44
- return true;
58
+ return { root: packRoot,
59
+ manifest: { path: manifestFile, content: after, changed: after !== before },
60
+ config: { ...config, changed: !existsSync(config.path) || readFileSync(config.path, "utf8") !== config.content } };
45
61
  }
46
62
  function setSequence(map, key, values) {
47
63
  if (values.length === 0) {
@@ -62,8 +78,9 @@ function setImports(script, packRoot, imports) {
62
78
  const sequence = new YAMLSeq();
63
79
  sequence.items = imports.map((item) => {
64
80
  const target = join(packRoot, item.path);
65
- if (!existsSync(target))
66
- throw new Error(`Imported file '${item.path}' does not exist in ${packRoot}.`);
81
+ if (!existsSync(target) || !isInside(packRoot, target) || !isInside(realpathSync(packRoot), realpathSync(target))) {
82
+ throw new Error(`Imported file '${item.path}' does not exist inside ${packRoot}.`);
83
+ }
67
84
  const preferred = oldKeys.get(`${item.kind}\n${item.path}`) ?? keyFrom(item);
68
85
  const key = uniqueKey(preferred, usedKeys);
69
86
  usedKeys.add(key);
@@ -0,0 +1,114 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { join, relative } from "node:path";
5
+ import { discoverPacks } from "../pack/discover.js";
6
+ import { assertSafeWrite } from "../pack/transaction.js";
7
+ import { inspectGameData } from "./gameData.js";
8
+ const PACKAGES = ["@sf-kmods/kdataforgejs", "@sf-kmods/kdataforgejs-cli"];
9
+ /** Check mode is read-only and network-free. Apply installs only fixed local dev dependencies. */
10
+ export function updateProject(options, dependencies = {}) {
11
+ const selection = discoverPacks(options.directory);
12
+ const root = selection.root;
13
+ const projects = [...new Set(selection.packs.map((pack) => pack.projectRoot))];
14
+ const manager = packageManager(root);
15
+ for (const project of projects)
16
+ assertSafeWrite(root, join(project, "package.json"));
17
+ assertSafeWrite(root, join(root, "package.json"));
18
+ assertSafeWrite(root, join(root, "package-lock.json"));
19
+ assertSafeWrite(root, join(root, "pnpm-lock.yaml"));
20
+ if (selection.workspace) {
21
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
22
+ if (manager === "npm" && manifest.workspaces === undefined ||
23
+ manager === "pnpm" && !existsSync(join(root, "pnpm-workspace.yaml"))) {
24
+ throw new Error(`${manager} workspace metadata is missing at ${root}; no packages were updated.`);
25
+ }
26
+ }
27
+ const installedVersion = dependencies.installedVersion ?? localVersion;
28
+ const lines = [];
29
+ for (const project of projects) {
30
+ const manifest = JSON.parse(readFileSync(join(project, "package.json"), "utf8"));
31
+ for (const name of PACKAGES) {
32
+ lines.push(`${relative(root, project) || "."}: ${name} declared ${manifest.devDependencies?.[name] ?? "missing"}, installed ${installedVersion(project, name) ?? "missing"}`);
33
+ }
34
+ }
35
+ const health = inspectGameData(root, projects, options.gamePath);
36
+ lines.push(`Game data ${health.status}: ${health.message}`);
37
+ lines.push("Latest registry versions are not queried in inspect mode.");
38
+ const command = manager === "npm"
39
+ ? "npm install --ignore-scripts --save-dev @sf-kmods/kdataforgejs@latest @sf-kmods/kdataforgejs-cli@latest"
40
+ : "pnpm add --ignore-scripts --save-dev @sf-kmods/kdataforgejs@latest @sf-kmods/kdataforgejs-cli@latest";
41
+ if (!options.apply) {
42
+ lines.push(`Run kdf update --apply to install locally and refresh game data; package command per pack: ${command}`);
43
+ return { lines, applied: false };
44
+ }
45
+ const run = dependencies.run ?? runProcess;
46
+ if (!options.offline) {
47
+ for (const project of projects) {
48
+ const args = manager === "npm"
49
+ ? ["install", "--ignore-scripts", "--save-dev", ...(selection.workspace ? ["--workspace", relative(root, project)] : []),
50
+ ...PACKAGES.map((name) => `${name}@latest`)]
51
+ : ["--dir", project, "add", "--ignore-scripts", "--save-dev", ...PACKAGES.map((name) => `${name}@latest`)];
52
+ if (run(manager, args, manager === "npm" ? root : project) !== 0) {
53
+ throw new Error(`Package-manager update failed in ${project}. Inspect its manifest and root lockfile before retrying; game data was not refreshed.`);
54
+ }
55
+ }
56
+ }
57
+ else if (projects.some((project) => PACKAGES.some((name) => installedVersion(project, name) === undefined))) {
58
+ throw new Error("Offline refresh needs both packages already installed in every pack project. No lockfile was changed.");
59
+ }
60
+ const versions = projects.flatMap((project) => PACKAGES.map((name) => installedVersion(project, name)));
61
+ if (versions.some((version) => version === undefined) || new Set(versions).size !== 1) {
62
+ throw new Error("Installed SDK and CLI versions differ or are missing; game data was not refreshed.");
63
+ }
64
+ const bin = (dependencies.localBin ?? localCliBin)(projects[0]);
65
+ const args = [bin, "game-data", root,
66
+ ...(options.gamePath ? ["--game-path", options.gamePath] : []),
67
+ ...(options.timeout ? ["--timeout", options.timeout] : []),
68
+ ...(options.contentTypes ? ["--content-types"] : []),
69
+ ...(options.force ? ["--force"] : [])];
70
+ if (run(process.execPath, args, root) !== 0)
71
+ throw new Error("Local kdf game-data failed; previous installed reflection files remain available.");
72
+ lines.push(`Refreshed game data with local CLI ${versions[0]}.`);
73
+ return { lines, applied: true };
74
+ }
75
+ function packageManager(root) {
76
+ const path = join(root, "package.json");
77
+ const manifest = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : {};
78
+ const explicit = manifest.packageManager?.split("@")[0];
79
+ if (explicit && explicit !== "npm" && explicit !== "pnpm")
80
+ throw new Error(`Unsupported package manager '${explicit}'.`);
81
+ const npmLock = existsSync(join(root, "package-lock.json"));
82
+ const pnpmLock = existsSync(join(root, "pnpm-lock.yaml"));
83
+ if (npmLock && pnpmLock)
84
+ throw new Error("Both npm and pnpm lockfiles exist; choose one package manager before updating.");
85
+ if (explicit === "npm" && pnpmLock || explicit === "pnpm" && npmLock)
86
+ throw new Error("packageManager conflicts with root lockfile.");
87
+ return explicit === "npm" || explicit === "pnpm" ? explicit :
88
+ (pnpmLock || existsSync(join(root, "pnpm-workspace.yaml")) ? "pnpm" : "npm");
89
+ }
90
+ function localVersion(project, name) {
91
+ try {
92
+ const require = createRequire(join(project, "package.json"));
93
+ const path = require.resolve(`${name}/package.json`);
94
+ return JSON.parse(readFileSync(path, "utf8")).version;
95
+ }
96
+ catch {
97
+ return undefined;
98
+ }
99
+ }
100
+ function localCliBin(project) {
101
+ const require = createRequire(join(project, "package.json"));
102
+ try {
103
+ return require.resolve("@sf-kmods/kdataforgejs-cli/dist/bin.js");
104
+ }
105
+ catch {
106
+ throw new Error(`Local kdf CLI is missing in ${project}; install both packages first.`);
107
+ }
108
+ }
109
+ function runProcess(command, args, cwd) {
110
+ const result = spawnSync(command, [...args], { cwd, stdio: "inherit", shell: false });
111
+ if (result.error)
112
+ throw result.error;
113
+ return result.status ?? 1;
114
+ }
@@ -1,17 +1,23 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { CANONICAL_ENTRY, DETERMINISTIC_CAPABILITIES } from "../conventions.js";
4
- import { findPackRoots } from "../pack/discover.js";
4
+ import { discoverPacks } from "../pack/discover.js";
5
5
  import { checkImports } from "../pack/imports.js";
6
6
  import { readManifest } from "../pack/manifest.js";
7
7
  import { checkEntryShape, checkSourceGraph, readEntryMeta } from "../pack/sourceGraph.js";
8
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)." }];
9
+ export function validateProject(projectRoot, packRef) {
10
+ try {
11
+ const selection = discoverPacks(projectRoot, packRef);
12
+ return selection.packs.flatMap((pack) => validatePack(pack.root).map((diagnostic) => ({
13
+ ...diagnostic,
14
+ file: selection.packs.length > 1 ? `${pack.ref}/${diagnostic.file}` : diagnostic.file,
15
+ })));
16
+ }
17
+ catch (error) {
18
+ return [{ severity: "error", code: "project.discovery", file: projectRoot,
19
+ message: error instanceof Error ? error.message : String(error) }];
13
20
  }
14
- return roots.flatMap(validatePack);
15
21
  }
16
22
  function validatePack(packRoot) {
17
23
  const manifest = readManifest(packRoot);
@@ -1,19 +1,135 @@
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). */
1
+ import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { parse } from "yaml";
4
+ import { readManifest } from "./manifest.js";
5
+ const SKIPPED = new Set(["node_modules", ".git", ".kdataforge", "dist", "dist-test"]);
6
+ /** Resolve authored packs without running package-manager or workspace code. */
7
+ export function discoverPacks(directory, packRef) {
8
+ const root = resolve(directory);
9
+ if (!existsSync(root) || !lstatSync(root).isDirectory())
10
+ throw new Error(`Project directory does not exist: ${root}`);
11
+ const workspaceRoots = workspaceProjects(root);
12
+ const projects = workspaceRoots === undefined ? [root] : [root, ...workspaceRoots];
13
+ const packs = [];
14
+ const seenPaths = new Set();
15
+ for (const projectRoot of projects) {
16
+ const dataForge = join(projectRoot, "DataForge");
17
+ const start = existsSync(dataForge) ? dataForge : workspaceRoots === undefined ? projectRoot : undefined;
18
+ if (start === undefined)
19
+ continue;
20
+ for (const packRoot of findRoots(start)) {
21
+ const actual = realpathSync(packRoot);
22
+ if (!isInside(projectRoot, actual) || !isInside(root, actual))
23
+ throw new Error(`Pack escapes project: ${packRoot}`);
24
+ if (seenPaths.has(actual))
25
+ continue;
26
+ seenPaths.add(actual);
27
+ const manifestPath = join(packRoot, "pack.yml");
28
+ if (lstatSync(manifestPath).isSymbolicLink() || !isInside(actual, realpathSync(manifestPath))) {
29
+ throw new Error(`Pack manifest must be a regular file inside its pack: ${manifestPath}`);
30
+ }
31
+ const ref = readManifest(packRoot).ref;
32
+ if (!ref)
33
+ throw new Error(`Pack ref is missing: ${manifestPath}`);
34
+ packs.push({ root: packRoot, projectRoot, ref });
35
+ }
36
+ }
37
+ packs.sort((a, b) => a.root.localeCompare(b.root));
38
+ const refs = new Map();
39
+ for (const pack of packs) {
40
+ const key = pack.ref.toLowerCase();
41
+ const previous = refs.get(key);
42
+ if (previous)
43
+ throw new Error(`Duplicate pack ref '${pack.ref}': ${previous} and ${pack.root}`);
44
+ refs.set(key, pack.root);
45
+ }
46
+ if (packs.length === 0)
47
+ throw new Error(`No pack.yml found under ${root}.`);
48
+ const selected = packRef === undefined ? packs : packs.filter((pack) => pack.ref === packRef);
49
+ if (selected.length === 0)
50
+ throw new Error(`No pack with ref '${packRef}' found under ${root}.`);
51
+ return { root, packs: selected, workspace: workspaceRoots !== undefined };
52
+ }
53
+ /** Retained for callers that need only pack roots. */
5
54
  export function findPackRoots(projectRoot) {
6
- const dataForge = join(projectRoot, "DataForge");
7
- const start = existsSync(dataForge) ? dataForge : projectRoot;
55
+ return discoverPacks(projectRoot).packs.map((pack) => pack.root);
56
+ }
57
+ /** Child-project commands share their containing workspace's writer lock. */
58
+ export function workspaceRootFor(directory) {
59
+ const root = resolve(directory);
60
+ let ancestor = dirname(root);
61
+ while (ancestor !== dirname(ancestor)) {
62
+ const projects = workspaceProjects(ancestor);
63
+ if (projects?.some((project) => isInside(project, root)))
64
+ return ancestor;
65
+ ancestor = dirname(ancestor);
66
+ }
67
+ return root;
68
+ }
69
+ export function isInside(root, target) {
70
+ const path = relative(root, target);
71
+ return path === "" || (path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path));
72
+ }
73
+ function findRoots(start) {
8
74
  const roots = [];
9
75
  const walk = (directory) => {
76
+ if (lstatSync(directory).isSymbolicLink())
77
+ return;
10
78
  if (existsSync(join(directory, "pack.yml")))
11
79
  roots.push(directory);
12
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
13
- if (entry.isDirectory() && !SKIPPED.has(entry.name))
80
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
81
+ if (entry.isDirectory() && !SKIPPED.has(entry.name) && !entry.name.startsWith("."))
14
82
  walk(join(directory, entry.name));
15
83
  }
16
84
  };
17
85
  walk(start);
18
86
  return roots;
19
87
  }
88
+ function workspaceProjects(root) {
89
+ const packageFile = join(root, "package.json");
90
+ const packageJson = existsSync(packageFile) ? JSON.parse(readFileSync(packageFile, "utf8")) : {};
91
+ const npmValue = packageJson.workspaces;
92
+ const npmPatterns = Array.isArray(npmValue) ? npmValue :
93
+ isRecord(npmValue) && Array.isArray(npmValue.packages) ? npmValue.packages : undefined;
94
+ const pnpmFile = join(root, "pnpm-workspace.yaml");
95
+ const pnpmValue = existsSync(pnpmFile) ? parse(readFileSync(pnpmFile, "utf8")) : undefined;
96
+ const pnpmPatterns = isRecord(pnpmValue) ? pnpmValue.packages : undefined;
97
+ if (npmPatterns === undefined && pnpmPatterns === undefined)
98
+ return undefined;
99
+ const npmRoots = npmPatterns === undefined ? undefined : expandPatterns(root, npmPatterns);
100
+ const pnpmRoots = pnpmPatterns === undefined ? undefined : expandPatterns(root, pnpmPatterns);
101
+ if (npmRoots && pnpmRoots && (npmRoots.length !== pnpmRoots.length || npmRoots.some((path, i) => path !== pnpmRoots[i]))) {
102
+ throw new Error("package.json workspaces and pnpm-workspace.yaml select different directories.");
103
+ }
104
+ return npmRoots ?? pnpmRoots ?? [];
105
+ }
106
+ function expandPatterns(root, value) {
107
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string"))
108
+ throw new Error("Workspace packages must be string paths.");
109
+ const projects = new Set();
110
+ for (const pattern of value) {
111
+ const segments = pattern.split("/");
112
+ if (isAbsolute(pattern) || segments.some((part) => part === "" || part === "." || part === ".." ||
113
+ (part.includes("*") && part !== "*") || /[?{}[\]\\]/u.test(part)) || segments.filter((part) => part === "*").length > 1) {
114
+ throw new Error(`Unsupported workspace pattern '${pattern}'. Use a literal path or one '*' segment.`);
115
+ }
116
+ const star = segments.indexOf("*");
117
+ const candidates = star < 0 ? [join(root, ...segments)] :
118
+ !existsSync(join(root, ...segments.slice(0, star))) ? [] :
119
+ readdirSync(join(root, ...segments.slice(0, star)), { withFileTypes: true })
120
+ .filter((entry) => (entry.isDirectory() || entry.isSymbolicLink()) && !entry.name.startsWith("."))
121
+ .map((entry) => join(root, ...segments.slice(0, star), entry.name, ...segments.slice(star + 1)));
122
+ for (const candidate of candidates) {
123
+ if (!existsSync(candidate))
124
+ continue;
125
+ if (lstatSync(candidate).isSymbolicLink() || !lstatSync(candidate).isDirectory() || !isInside(root, realpathSync(candidate))) {
126
+ throw new Error(`Workspace package escapes root: ${candidate}`);
127
+ }
128
+ projects.add(candidate);
129
+ }
130
+ }
131
+ return [...projects].sort();
132
+ }
133
+ function isRecord(value) {
134
+ return typeof value === "object" && value !== null && !Array.isArray(value);
135
+ }