@sf-kmods/kdataforgejs-cli 0.1.17 → 0.1.19

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
@@ -43,8 +43,8 @@ eligible. To bypass discovery:
43
43
  kdf game-data --game-path "C:\\Games\\Satisfactory"
44
44
  ```
45
45
 
46
- The game starts with automatic full reflection export and exits when publication completes. The CLI waits up to 15
46
+ The CLI loads the newest local save automatically, starts a full reflection export, and exits the game when publication completes. The CLI waits up to 15
47
47
  minutes by default; override this with `--timeout <seconds>`. It writes `.kdataforge/satisfactory.kdfdata`, imports
48
48
  generated declarations below `DataForge/typescript/kdataforgejs/`, creates `tsconfig.kdf.json`, and makes later
49
49
  `kdf check` calls use those installed-game types automatically. `.kdataforge/` is added to `.gitignore` because the
50
- archive can be large.
50
+ archive can be large. Temporary export and staging directories are removed after the game exits.
@@ -1,26 +1,54 @@
1
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";
2
+ import { appendFileSync, copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { basename, extname, join, resolve } from "node:path";
5
5
  import { detectGameInstallations, resolveGameInstallation, supportedPlatform } from "../game/installations.js";
6
6
  const DEFAULT_TIMEOUT_MILLISECONDS = 15 * 60 * 1_000;
7
7
  const POLL_INTERVAL_MILLISECONDS = 500;
8
8
  export async function importGameData(options, dependencies = {}) {
9
+ const timeoutMilliseconds = options.timeoutMilliseconds ?? DEFAULT_TIMEOUT_MILLISECONDS;
10
+ assertValidTimeout(timeoutMilliseconds);
9
11
  const platform = supportedPlatform(dependencies.platform ?? process.platform);
10
12
  const installation = selectInstallation(options.gamePath, platform);
13
+ const savePath = resolveSavePath(options.savePath, installation, platform);
11
14
  const destination = resolve(options.destination);
12
15
  const exportDirectory = mkdtempSync(join(tmpdir(), "kdf-game-data-export-"));
13
16
  try {
14
- const plan = createLaunchPlan(installation, platform, exportDirectory);
15
- await (dependencies.launch ?? launchGame)(plan);
16
- const artifacts = await waitForExport(exportDirectory, options.timeoutMilliseconds ?? DEFAULT_TIMEOUT_MILLISECONDS, dependencies.sleep ?? delay);
17
- return installExport(destination, installation, artifacts);
17
+ const plan = createLaunchPlan(installation, platform, exportDirectory, savePath);
18
+ const launchedGame = await (dependencies.launch ?? launchGame)(plan);
19
+ const artifacts = await waitForExport(exportDirectory, timeoutMilliseconds, dependencies.sleep ?? delay, launchedGame?.exited);
20
+ const result = installExport(destination, installation, artifacts);
21
+ if (launchedGame !== undefined)
22
+ await waitForCleanGameExit(launchedGame.exited);
23
+ return result;
18
24
  }
19
25
  finally {
20
- rmSync(exportDirectory, { recursive: true, force: true });
26
+ cleanupTemporaryExport(exportDirectory);
21
27
  }
22
28
  }
23
- export function createLaunchPlan(installation, platform, exportDirectory) {
29
+ async function waitForCleanGameExit(exited) {
30
+ await new Promise((resolveExit, rejectExit) => {
31
+ const timer = setTimeout(() => rejectExit(new Error("Game did not exit within 30 seconds after reflection export completed.")), 30_000);
32
+ exited.then((result) => {
33
+ clearTimeout(timer);
34
+ if (result.code !== null && result.code !== 0)
35
+ rejectExit(new Error(`Game exited with code ${result.code} after reflection export completed.`));
36
+ else
37
+ resolveExit();
38
+ }, rejectExit);
39
+ });
40
+ }
41
+ function cleanupTemporaryExport(exportDirectory) {
42
+ rmSync(exportDirectory, { recursive: true, force: true });
43
+ const parent = resolve(exportDirectory, "..");
44
+ const stagingPrefix = `.${basename(exportDirectory)}.kdf-export-`;
45
+ for (const entry of readdirSync(parent, { withFileTypes: true })) {
46
+ if (entry.isDirectory() && entry.name.startsWith(stagingPrefix) && entry.name.endsWith(".stage")) {
47
+ rmSync(join(parent, entry.name), { recursive: true, force: true });
48
+ }
49
+ }
50
+ }
51
+ export function createLaunchPlan(installation, platform, exportDirectory, savePath) {
24
52
  const gameArguments = [
25
53
  "-EpicPortal",
26
54
  "-log",
@@ -28,6 +56,8 @@ export function createLaunchPlan(installation, platform, exportDirectory) {
28
56
  `-KDFReflectionAutoExport=${exportDirectory}`,
29
57
  "-KDFReflectionAutoExit",
30
58
  ];
59
+ if (savePath !== undefined)
60
+ gameArguments.push(createSaveGameOverride(savePath));
31
61
  if (platform === "win32") {
32
62
  return { command: installation.executable, arguments: gameArguments, workingDirectory: installation.root, exportDirectory };
33
63
  }
@@ -56,30 +86,86 @@ function selectInstallation(gamePath, platform) {
56
86
  throw new Error("No Satisfactory installation containing KDataForge and KDataForgeJS was found. Pass --game-path <root-or-executable>.");
57
87
  }
58
88
  async function launchGame(plan) {
59
- await new Promise((resolveLaunch, rejectLaunch) => {
89
+ return new Promise((resolveLaunch, rejectLaunch) => {
60
90
  const child = spawn(plan.command, [...plan.arguments], {
61
91
  cwd: plan.workingDirectory,
62
92
  stdio: "inherit",
63
93
  windowsHide: false,
64
94
  detached: false,
65
95
  });
66
- child.once("spawn", resolveLaunch);
96
+ const exited = new Promise((resolveExit) => {
97
+ child.once("exit", (code, signal) => resolveExit({ code, signal }));
98
+ });
99
+ child.once("spawn", () => resolveLaunch({ exited }));
67
100
  child.once("error", rejectLaunch);
68
101
  });
69
102
  }
70
- async function waitForExport(exportDirectory, timeoutMilliseconds, sleep) {
71
- if (!Number.isSafeInteger(timeoutMilliseconds) || timeoutMilliseconds <= 0) {
72
- throw new Error("Game-data timeout must be a positive integer number of milliseconds.");
73
- }
103
+ async function waitForExport(exportDirectory, timeoutMilliseconds, sleep, exited) {
104
+ assertValidTimeout(timeoutMilliseconds);
74
105
  const deadline = Date.now() + timeoutMilliseconds;
106
+ const exitState = {};
107
+ const observeExit = exited?.then((value) => {
108
+ exitState.value = value;
109
+ });
75
110
  while (Date.now() <= deadline) {
76
111
  const artifacts = findCompletedExport(exportDirectory);
77
112
  if (artifacts !== undefined)
78
113
  return artifacts;
79
- await sleep(POLL_INTERVAL_MILLISECONDS);
114
+ if (exitState.value !== undefined) {
115
+ const reason = exitState.value.code === null ? `signal ${exitState.value.signal ?? "unknown"}` : `code ${exitState.value.code}`;
116
+ throw new Error(`Game exited before reflection export completed (${reason}).`);
117
+ }
118
+ await (observeExit === undefined ? sleep(POLL_INTERVAL_MILLISECONDS) : Promise.race([sleep(POLL_INTERVAL_MILLISECONDS), observeExit]));
80
119
  }
81
120
  throw new Error(`Timed out after ${timeoutMilliseconds} ms waiting for KDataForge reflection export.`);
82
121
  }
122
+ function createSaveGameOverride(savePath) {
123
+ const saveName = basename(savePath, extname(savePath));
124
+ return `-ini:Engine:[/Script/EngineSettings.GameMapsSettings]:GameDefaultMap=/Game/FactoryGame/Map/GameLevel01/Persistent_Level.Persistent_Level,[/Script/EngineSettings.GameMapsSettings]:LocalMapOptions=?skipOnboarding?listen?loadgame=${saveName}`;
125
+ }
126
+ function resolveSavePath(explicit, installation, platform) {
127
+ if (explicit !== undefined) {
128
+ const path = resolve(explicit);
129
+ if (!existsSync(path) || !statSync(path).isFile())
130
+ throw new Error(`Satisfactory save '${path}' does not exist.`);
131
+ return path;
132
+ }
133
+ const roots = platform === "win32"
134
+ ? [join(process.env.LOCALAPPDATA ?? join(homedir(), "AppData/Local"), "FactoryGame/Saved/SaveGames")]
135
+ : [
136
+ resolve(installation.root, "../../compatdata/526870/pfx/drive_c/users/steamuser/AppData/Local/FactoryGame/Saved/SaveGames"),
137
+ join(homedir(), ".local/share/Steam/steamapps/compatdata/526870/pfx/drive_c/users/steamuser/AppData/Local/FactoryGame/Saved/SaveGames"),
138
+ ];
139
+ const saves = roots.flatMap(findSaveFiles).sort((left, right) => statSync(right).mtimeMs - statSync(left).mtimeMs);
140
+ const latest = saves[0];
141
+ if (latest === undefined)
142
+ throw new Error("No Satisfactory save was found; start a save once before importing game data.");
143
+ return latest;
144
+ }
145
+ function findSaveFiles(root) {
146
+ if (!existsSync(root))
147
+ return [];
148
+ const saves = [];
149
+ const pending = [root];
150
+ while (pending.length > 0) {
151
+ const directory = pending.pop();
152
+ if (directory === undefined)
153
+ break;
154
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
155
+ const path = join(directory, entry.name);
156
+ if (entry.isDirectory())
157
+ pending.push(path);
158
+ else if (entry.isFile() && entry.name.toLocaleLowerCase().endsWith(".sav"))
159
+ saves.push(path);
160
+ }
161
+ }
162
+ return saves;
163
+ }
164
+ function assertValidTimeout(timeoutMilliseconds) {
165
+ if (!Number.isSafeInteger(timeoutMilliseconds) || timeoutMilliseconds <= 0) {
166
+ throw new Error("Game-data timeout must be a positive integer number of milliseconds.");
167
+ }
168
+ }
83
169
  function findCompletedExport(exportDirectory) {
84
170
  const archive = readdirSync(exportDirectory, { withFileTypes: true })
85
171
  .filter((entry) => entry.isFile() && entry.name.toLocaleLowerCase().endsWith(".kdfdata"))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sf-kmods/kdataforgejs-cli",
3
- "version": "0.1.17",
3
+ "version": "0.1.19",
4
4
  "description": "kdf - create, type-check and validate KDataForge projects with KDataForgeJS (TypeScript) scripts.",
5
5
  "license": "MIT",
6
6
  "author": "Kyri123/Kyrium",
@@ -36,7 +36,7 @@
36
36
  "dependencies": {
37
37
  "typescript": ">=5.7.3 <6",
38
38
  "yaml": "^2.6.1",
39
- "@sf-kmods/kdataforgejs": "^0.1.17"
39
+ "@sf-kmods/kdataforgejs": "^0.1.19"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@types/node": "^22.10.0"