@mostra/runtime 0.2.0 → 0.3.0

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.
Files changed (58) hide show
  1. package/dist/bin.js +7 -7
  2. package/dist/bin.js.map +1 -1
  3. package/dist/builder/child/main.js +18 -17
  4. package/dist/builder/child/main.js.map +1 -1
  5. package/dist/{child-xrHmytks.js → child-BQc3arf7.js} +5 -2
  6. package/dist/{child-xrHmytks.js.map → child-BQc3arf7.js.map} +1 -1
  7. package/dist/deps/child/install.js +9 -6
  8. package/dist/deps/child/install.js.map +1 -1
  9. package/dist/files-KxzOxckl.js +674 -0
  10. package/dist/files-KxzOxckl.js.map +1 -0
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +2 -2
  14. package/dist/{instance-CzBkUyHu.js → instance-DiKSe7s6.js} +1148 -737
  15. package/dist/instance-DiKSe7s6.js.map +1 -0
  16. package/package.json +5 -5
  17. package/src/bin.ts +4 -10
  18. package/src/builder/child/dev.ts +4 -3
  19. package/src/builder/child/plugins.ts +12 -7
  20. package/src/builder/child/spa.ts +15 -9
  21. package/src/builder/index.ts +3 -6
  22. package/src/deps/child/install.ts +3 -2
  23. package/src/deps/index.ts +21 -16
  24. package/src/deps/warm.ts +3 -16
  25. package/src/faults.ts +9 -2
  26. package/src/gateway/capabilities.ts +2 -2
  27. package/src/home/acquire.ts +27 -11
  28. package/src/home/paths.ts +45 -135
  29. package/src/home/platform.ts +17 -9
  30. package/src/home/record.ts +3 -3
  31. package/src/home/settings.ts +5 -16
  32. package/src/instance/index.ts +31 -7
  33. package/src/ledger/index.ts +5 -27
  34. package/src/platform/control.ts +409 -0
  35. package/src/platform/directories.ts +212 -0
  36. package/src/platform/environment.ts +64 -0
  37. package/src/platform/files.ts +368 -0
  38. package/src/platform/helper.ts +152 -0
  39. package/src/{processes → platform}/identity.ts +40 -8
  40. package/src/platform/index.ts +46 -0
  41. package/src/platform/launch.ts +373 -0
  42. package/src/processes/child.ts +4 -1
  43. package/src/processes/environment.ts +22 -3
  44. package/src/processes/index.ts +2 -1
  45. package/src/processes/manager.ts +76 -179
  46. package/src/protocol-server/client.ts +19 -18
  47. package/src/protocol-server/server.ts +75 -54
  48. package/src/publish/publisher.ts +16 -9
  49. package/src/publish/source.ts +7 -4
  50. package/src/registry/store.ts +7 -65
  51. package/src/secrets/index.ts +2 -2
  52. package/src/service/unit.ts +3 -2
  53. package/src/verify/index.ts +5 -3
  54. package/src/verify/typecheck.ts +3 -2
  55. package/src/workers/launcher.ts +3 -1
  56. package/dist/instance-CzBkUyHu.js.map +0 -1
  57. package/dist/types-NjNy7gXX.js +0 -57
  58. package/dist/types-NjNy7gXX.js.map +0 -1
package/src/home/paths.ts CHANGED
@@ -1,14 +1,25 @@
1
1
  /**
2
- * Where a home and its control socket live (DATA_MODEL §1, D82, D84, D85). Resolving a path never
3
- * touches the file system; preparing a directory creates it with mode 0700, tightens one the user
4
- * owns, and refuses one owned by someone else.
2
+ * Where a home and its control endpoint live (DATA_MODEL §1, D82, D84, D85). Resolving a path never
3
+ * touches the file system; preparing a directory creates it owner-only, tightens one the user
4
+ * owns, and refuses one owned by someone else. The per-system details are the platform layer's.
5
5
  */
6
6
  import { createHash } from "node:crypto";
7
- import { chmodSync, mkdirSync, realpathSync, statSync } from "node:fs";
8
7
  import { homedir } from "node:os";
9
- import { isAbsolute, join, resolve } from "node:path";
10
- import { createDiagnostic, RpcError, VersionId } from "@mostra/protocol";
8
+ import { VersionId } from "@mostra/protocol";
11
9
  import type { Environment } from "../log.ts";
10
+ import {
11
+ controlEndpoint,
12
+ defaultHome,
13
+ socketPathLimit as limitFor,
14
+ OS,
15
+ ownedDirectory,
16
+ type PreparedDirectory,
17
+ pathsOf,
18
+ type RuntimeDirChoice,
19
+ runtimeDirFor,
20
+ } from "../platform/index.ts";
21
+
22
+ export type { PreparedDirectory, RuntimeDirChoice };
12
23
 
13
24
  /** What path resolution reads: the flag, the environment and the platform. */
14
25
  export interface PathInputs {
@@ -27,82 +38,34 @@ const nonEmpty = (value: string | undefined): string | undefined =>
27
38
 
28
39
  /**
29
40
  * The home path, resolved in D84's order: `--home`, then `MOSTRA_HOME`, then the platform default
30
- * (`~/.mostra` on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux). An SDK passes its
31
- * `home` option as `--home`.
41
+ * (`~/.mostra` on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux,
42
+ * `%LOCALAPPDATA%\mostra` on Windows). An SDK passes its `home` option as `--home`.
32
43
  */
33
44
  export function resolveHomePath(inputs: PathInputs): string {
34
45
  const cwd = inputs.cwd ?? process.cwd();
35
46
  const chosen = nonEmpty(inputs.home) ?? nonEmpty(inputs.env["MOSTRA_HOME"]);
36
- if (chosen !== undefined) return resolve(cwd, chosen);
37
- const user = inputs.userHome ?? homedir();
38
- if ((inputs.platform ?? process.platform) === "darwin") return join(user, ".mostra");
39
- const data = nonEmpty(inputs.env["XDG_DATA_HOME"]);
40
- return join(
41
- data !== undefined && isAbsolute(data) ? data : join(user, ".local", "share"),
42
- "mostra",
43
- );
44
- }
45
-
46
- /** What the runtime directory resolution decided, and why. */
47
- export interface RuntimeDirChoice {
48
- readonly dir: string;
49
- /** `override` (MOSTRA_RUNTIME_DIR), `xdg` (the safe XDG runtime directory) or `fallback`. */
50
- readonly source: "override" | "xdg" | "fallback";
51
- /** Why `$XDG_RUNTIME_DIR` wasn't used, when it was set. */
52
- readonly rejected?: string;
53
- }
54
-
55
- /** The current user's ID. */
56
- function uid(): number {
57
- return process.getuid?.() ?? -1;
47
+ if (chosen !== undefined) return pathsOf(inputs.platform ?? OS).resolve(cwd, chosen);
48
+ return defaultHome(inputs.platform ?? OS, inputs.env, inputs.userHome ?? homedir());
58
49
  }
59
50
 
60
51
  /**
61
52
  * The runtime directory for control sockets (D82): `MOSTRA_RUNTIME_DIR`; else `~/.mostra/run` on
62
53
  * macOS; on Linux `$XDG_RUNTIME_DIR/mostra` when `$XDG_RUNTIME_DIR` is a directory the user owns
63
- * that nobody else can read or write, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`.
54
+ * that nobody else can read or write, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`. On
55
+ * Windows `undefined`: the control pipe lives in the system's pipe namespace.
64
56
  */
65
- export function resolveRuntimeDir(inputs: Omit<PathInputs, "home">): RuntimeDirChoice {
66
- const override = nonEmpty(inputs.env["MOSTRA_RUNTIME_DIR"]);
67
- if (override !== undefined) {
68
- return { dir: resolve(inputs.cwd ?? process.cwd(), override), source: "override" };
69
- }
70
- const user = inputs.userHome ?? homedir();
71
- if ((inputs.platform ?? process.platform) === "darwin") {
72
- return { dir: join(user, ".mostra", "run"), source: "fallback" };
73
- }
74
- const xdg = nonEmpty(inputs.env["XDG_RUNTIME_DIR"]);
75
- let rejected: string | undefined;
76
- if (xdg !== undefined) {
77
- rejected = unsafeXdgRuntimeDir(xdg);
78
- if (rejected === undefined) return { dir: join(xdg, "mostra"), source: "xdg" };
79
- }
80
- const state = nonEmpty(inputs.env["XDG_STATE_HOME"]);
81
- const base = state !== undefined && isAbsolute(state) ? state : join(user, ".local", "state");
82
- const dir = join(base, "mostra", "run");
83
- return rejected === undefined
84
- ? { dir, source: "fallback" }
85
- : { dir, source: "fallback", rejected };
86
- }
87
-
88
- /** Why `$XDG_RUNTIME_DIR` can't be used, or `undefined` when it can (XDG Base Directory spec). */
89
- function unsafeXdgRuntimeDir(dir: string): string | undefined {
90
- if (!isAbsolute(dir)) return "it isn't an absolute path";
91
- let stats: ReturnType<typeof statSync>;
92
- try {
93
- stats = statSync(dir);
94
- } catch {
95
- return "it doesn't exist";
96
- }
97
- if (!stats.isDirectory()) return "it isn't a directory";
98
- if (stats.uid !== uid()) return "another user owns it";
99
- if ((stats.mode & 0o077) !== 0) return "other users can access it";
100
- return undefined;
57
+ export function resolveRuntimeDir(inputs: Omit<PathInputs, "home">): RuntimeDirChoice | undefined {
58
+ return runtimeDirFor({
59
+ os: inputs.platform ?? OS,
60
+ env: inputs.env,
61
+ userHome: inputs.userHome ?? homedir(),
62
+ cwd: inputs.cwd ?? process.cwd(),
63
+ });
101
64
  }
102
65
 
103
66
  /** The longest control socket path the operating system accepts, in bytes (VERIFIED_FACTS). */
104
- export function socketPathLimit(platform: string = process.platform): number {
105
- return platform === "darwin" ? 103 : 107;
67
+ export function socketPathLimit(platform: string = OS): number {
68
+ return limitFor(platform);
106
69
  }
107
70
 
108
71
  /**
@@ -117,76 +80,23 @@ export function homeHash(realHome: string): string {
117
80
  }
118
81
 
119
82
  /**
120
- * The control socket for a home (D82), named by its {@link homeHash}. Throws
121
- * `MOSTRA_HOME_SOCKET_TOO_LONG` when the path exceeds the limit.
83
+ * The control endpoint for a home (D82), named by its {@link homeHash}: the socket in `runtimeDir`
84
+ * on POSIX, throwing `MOSTRA_HOME_SOCKET_TOO_LONG` past the system's limit; on Windows the pipe
85
+ * name that each bind completes with a random part.
122
86
  */
123
- export function socketPathFor(runtimeDir: string, realHome: string, platform?: string): string {
124
- const hash = homeHash(realHome);
125
- const path = join(runtimeDir, `${hash}.sock`);
126
- const limit = socketPathLimit(platform);
127
- const length = Buffer.byteLength(path);
128
- if (length > limit) {
129
- throw new RpcError(
130
- createDiagnostic("MOSTRA_HOME_SOCKET_TOO_LONG", {
131
- message: `The control socket path ${path} is ${length} bytes; this system allows ${limit}.`,
132
- fix: { kind: "command", command: "export MOSTRA_RUNTIME_DIR=/tmp/mostra-$USER" },
133
- }),
134
- );
135
- }
136
- return path;
137
- }
138
-
139
- /** The outcome of {@link prepareOwnedDirectory}. */
140
- export interface PreparedDirectory {
141
- /** The directory's real path. */
142
- readonly realPath: string;
143
- /** Whether Mostra created it. */
144
- readonly created: boolean;
145
- /** The mode it had when Mostra tightened it to 0700, when it did. */
146
- readonly tightenedFrom?: number;
147
- }
148
-
149
- function notOwned(path: string, why: string): RpcError {
150
- return new RpcError(
151
- createDiagnostic("MOSTRA_HOME_NOT_OWNED", { message: `Mostra can't use ${path}: ${why}.` }),
152
- );
87
+ export function socketPathFor(
88
+ runtimeDir: string | undefined,
89
+ realHome: string,
90
+ platform: string = OS,
91
+ ): string {
92
+ return controlEndpoint(runtimeDir, homeHash(realHome), platform);
153
93
  }
154
94
 
155
95
  /**
156
- * Makes `path` a directory only its owner can use (D85): creates it with mode 0700 when missing,
157
- * tightens one the user owns to 0700, and throws `MOSTRA_HOME_NOT_OWNED` for one owned by
158
- * another user or a path that isn't a directory. Symlinks are followed.
96
+ * Makes `path` a directory only its owner can use (D85): creates it owner-only when missing,
97
+ * tightens one the user owns (mode 0700, or an owner-only access list on Windows), and throws
98
+ * `MOSTRA_HOME_NOT_OWNED` for one owned by another user or a path that isn't a directory.
159
99
  */
160
100
  export function prepareOwnedDirectory(path: string): PreparedDirectory {
161
- try {
162
- return prepare(path);
163
- } catch (error) {
164
- const code = (error as NodeJS.ErrnoException).code;
165
- if (code === "ENOTDIR" || code === "EEXIST")
166
- throw notOwned(path, "a part of the path isn't a directory");
167
- if (code === "EACCES" || code === "EPERM")
168
- throw notOwned(path, "you have no permission to use it");
169
- throw error;
170
- }
171
- }
172
-
173
- function prepare(path: string): PreparedDirectory {
174
- let created = false;
175
- try {
176
- statSync(path);
177
- } catch (error) {
178
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
179
- mkdirSync(path, { recursive: true, mode: 0o700 });
180
- created = true;
181
- }
182
- const realPath = realpathSync(path);
183
- const stats = statSync(realPath);
184
- if (!stats.isDirectory()) throw notOwned(path, "it isn't a directory");
185
- if (stats.uid !== uid()) throw notOwned(path, `it belongs to user ${stats.uid}, not to you`);
186
- const mode = stats.mode & 0o777;
187
- if (mode !== 0o700) {
188
- chmodSync(realPath, 0o700);
189
- return created ? { realPath, created } : { realPath, created, tightenedFrom: mode };
190
- }
191
- return { realPath, created };
101
+ return ownedDirectory(path);
192
102
  }
@@ -1,29 +1,37 @@
1
1
  /**
2
- * The unsupported-platform gate (D35, RT-07). Every entry point calls it before it touches the
3
- * home: Mostra 1.0 runs on macOS and Linux, on x64 and arm64, and fails closed elsewhere.
2
+ * The unsupported-platform gate (D35, D146, RT-07). Every entry point calls it before it touches
3
+ * the home: Mostra runs on macOS and Linux, on x64 and arm64, and fails closed elsewhere. Windows
4
+ * (x64 and arm64) is being built (WP-W1 to WP-W3) and runs only behind the development switch
5
+ * `MOSTRA_DEV_WINDOWS=1`, which only Mostra's own CI sets, so no release exposes a partial port.
6
+ * WP-W3 removes the switch.
4
7
  */
5
8
  import { createDiagnostic, type Diagnostic } from "@mostra/protocol";
9
+ import { OS } from "../platform/index.ts";
6
10
 
7
11
  const OPERATING_SYSTEMS: readonly string[] = ["darwin", "linux"];
8
12
  const ARCHITECTURES: readonly string[] = ["x64", "arm64"];
9
13
 
14
+ /** The development switch that admits Windows until WP-W3 (D146). */
15
+ export const WINDOWS_DEV_SWITCH = "MOSTRA_DEV_WINDOWS";
16
+
10
17
  /** The platform as `<os>-<arch>`, as `InstanceInfo.platform` reports it. */
11
- export function platformName(
12
- platform: string = process.platform,
13
- arch: string = process.arch,
14
- ): string {
18
+ export function platformName(platform: string = OS, arch: string = process.arch): string {
15
19
  return `${platform}-${arch}`;
16
20
  }
17
21
 
18
22
  /**
19
23
  * Returns `MOSTRA_PLATFORM_UNSUPPORTED` for a platform Mostra doesn't run on, or `undefined` for
20
- * a supported one.
24
+ * a supported one. Windows is supported only while `env` sets the development switch to `1`.
21
25
  */
22
26
  export function checkPlatform(
23
- platform: string = process.platform,
27
+ platform: string = OS,
24
28
  arch: string = process.arch,
29
+ env: Readonly<Record<string, string | undefined>> = process.env,
25
30
  ): Diagnostic | undefined {
26
- if (OPERATING_SYSTEMS.includes(platform) && ARCHITECTURES.includes(arch)) return undefined;
31
+ if (ARCHITECTURES.includes(arch)) {
32
+ if (OPERATING_SYSTEMS.includes(platform)) return undefined;
33
+ if (platform === "win32" && env[WINDOWS_DEV_SWITCH] === "1") return undefined;
34
+ }
27
35
  const name =
28
36
  platform === "win32"
29
37
  ? `Windows (${platformName(platform, arch)})`
@@ -4,10 +4,10 @@
4
4
  * atomically after binding its socket and removes it on a clean exit; a record whose PID and
5
5
  * start time match no live process is stale.
6
6
  */
7
- import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
7
+ import { readFileSync, rmSync, writeFileSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import * as z from "zod";
10
- import { isSameProcess } from "../processes/index.ts";
10
+ import { isSameProcess, renamePathSync } from "../platform/index.ts";
11
11
 
12
12
  /** The record's file name in the home. */
13
13
  export const INSTANCE_FILE = "instance.json";
@@ -64,7 +64,7 @@ export function writeInstanceRecord(home: string, record: InstanceRecord): void
64
64
  const file = join(home, INSTANCE_FILE);
65
65
  const temp = `${file}.${process.pid}.tmp`;
66
66
  writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
67
- renameSync(temp, file);
67
+ renamePathSync(temp, file);
68
68
  }
69
69
 
70
70
  /** Removes the record when it is still this process's (a clean exit). */
@@ -6,7 +6,7 @@
6
6
  * Written atomically (a temporary file, then a rename); read fresh by whoever needs a setting, so
7
7
  * a host's change applies to the next request.
8
8
  */
9
- import { closeSync, fsyncSync, openSync, readFileSync, renameSync, writeFileSync } from "node:fs";
9
+ import { readFileSync, writeFileSync } from "node:fs";
10
10
  import { join } from "node:path";
11
11
  import {
12
12
  createDiagnostic,
@@ -15,6 +15,7 @@ import {
15
15
  SubmissionPolicy,
16
16
  } from "@mostra/protocol";
17
17
  import * as z from "zod";
18
+ import { fsyncPath, renamePathSync } from "../platform/index.ts";
18
19
 
19
20
  /** The settings `config.json` holds. Unknown keys are kept, so newer settings survive. */
20
21
  export interface HomeSettings {
@@ -85,21 +86,9 @@ export function writeHomeSettings(home: string, change: HomeSettings): void {
85
86
  const file = join(home, SETTINGS_FILE);
86
87
  const temporary = `${file}.${process.pid}.tmp`;
87
88
  writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
88
- const handle = openSync(temporary, "r");
89
- try {
90
- fsyncSync(handle);
91
- } finally {
92
- closeSync(handle);
93
- }
94
- renameSync(temporary, file);
95
- const dir = openSync(home, "r");
96
- try {
97
- fsyncSync(dir);
98
- } catch {
99
- // Some file systems can't sync a directory; the rename itself is atomic.
100
- } finally {
101
- closeSync(dir);
102
- }
89
+ fsyncPath(temporary);
90
+ renamePathSync(temporary, file);
91
+ fsyncPath(home, true);
103
92
  }
104
93
 
105
94
  /**
@@ -81,6 +81,7 @@ import {
81
81
  } from "../interaction/index.ts";
82
82
  import { createLive, type LatestLive, liveMethods } from "../live/index.ts";
83
83
  import type { Environment, Log } from "../log.ts";
84
+ import { helperPath, type LaunchPipe } from "../platform/index.ts";
84
85
  import {
85
86
  artifactEnvironment,
86
87
  openProcessManager,
@@ -795,7 +796,7 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
795
796
  ...sessionMethods({
796
797
  describe: () => info,
797
798
  startedAt: home.startedAt,
798
- socketPath: () => home.socketPath,
799
+ socketPath: () => server.socketPath ?? home.socketPath,
799
800
  connections: () => server.connections,
800
801
  processes: () => manager.list(),
801
802
  gateway: () =>
@@ -827,7 +828,9 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
827
828
 
828
829
  const instance: Instance = {
829
830
  info,
830
- socketPath: home.socketPath,
831
+ get socketPath() {
832
+ return server.socketPath ?? home.socketPath;
833
+ },
831
834
  processes: manager,
832
835
  reaped,
833
836
  stopped,
@@ -838,7 +841,9 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
838
841
  stopWatchingPublishes();
839
842
  live.stop();
840
843
  interaction.stop();
841
- server.close();
844
+ // Before any child stops: on Windows the pipe's helper is a child, and it hands clients
845
+ // the answers already sent (the `mostra/shutdown` reply among them) before it exits.
846
+ await server.close();
842
847
  await dev.stopAll();
843
848
  await gateway.close();
844
849
  await pool.stopAll();
@@ -865,12 +870,31 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
865
870
  try {
866
871
  await gateway.start();
867
872
  gatewayStarted = true;
868
- await server.listen(home.socketPath, options.checkIntervalMs);
873
+ // On Windows the helper serves the owner-only pipe, as a child like any other (RT-10).
874
+ const launchPipe: LaunchPipe = async (name) => {
875
+ const child = await manager.spawn({
876
+ kind: "control-pipe",
877
+ ownerRef: home.path,
878
+ command: helperPath(),
879
+ args: ["pipe", name],
880
+ channel: true,
881
+ });
882
+ if (!child.channel) throw new Error("The control pipe's helper has no channel.");
883
+ return { channel: child.channel, exited: child.exited, stop: () => child.stop(2000) };
884
+ };
885
+ await server.listen(home.socketPath, options.checkIntervalMs, {
886
+ launchPipe,
887
+ onMoved: (path) => {
888
+ faults.at("endpoint:moved");
889
+ home.publish(options.mode, path);
890
+ log.warn("home.endpoint_moved", { socket: path });
891
+ },
892
+ });
869
893
  // Deliveries pending from before a restart go out again (FAILURE_MODEL §4).
870
894
  interaction.start();
871
895
  // Producers that `always` run, and those hosts subscribe to, start now (LL-04).
872
896
  live.start();
873
- home.publish(options.mode);
897
+ home.publish(options.mode, server.socketPath ?? home.socketPath);
874
898
  // A host-spawned instance marks its home as a host's (D140 item 4).
875
899
  if (options.mode === "host" && markHostConfigured(home.path, "mostra-runtime host"))
876
900
  log.info("home.host_configured", { client: "mostra-runtime host" });
@@ -878,7 +902,7 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
878
902
  // Undo what started before the home is released, so no listener or child outlives it.
879
903
  live.stop();
880
904
  interaction.stop();
881
- server.close();
905
+ await server.close();
882
906
  await gateway.close();
883
907
  await pool.stopAll();
884
908
  await manager.stopAll();
@@ -922,7 +946,7 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
922
946
  log.info("instance.started", {
923
947
  mode: options.mode,
924
948
  pid: process.pid,
925
- socket: home.socketPath,
949
+ socket: server.socketPath ?? home.socketPath,
926
950
  shell: gateway.shellOrigin(),
927
951
  });
928
952
  return instance;
@@ -11,22 +11,13 @@
11
11
  * opened.ledger.write((db) => db.run("INSERT INTO child …", …));
12
12
  * ```
13
13
  */
14
- import {
15
- closeSync,
16
- existsSync,
17
- fsyncSync,
18
- linkSync,
19
- mkdirSync,
20
- openSync,
21
- readdirSync,
22
- rmSync,
23
- statSync,
24
- } from "node:fs";
14
+ import { existsSync, linkSync, mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
25
15
  import { createRequire } from "node:module";
26
16
  import { join } from "node:path";
27
17
  import { createDiagnostic, RpcError } from "@mostra/protocol";
28
18
  import type BetterSqlite3 from "better-sqlite3";
29
19
  import type { Log } from "../log.ts";
20
+ import { fsyncPath } from "../platform/index.ts";
30
21
  import { BOOTSTRAP_SQL, MIGRATIONS, type Migration } from "./migrations.ts";
31
22
  import type { LedgerDb, MigrationDb, RunResult, SqlValue } from "./types.ts";
32
23
 
@@ -166,12 +157,7 @@ function createLedgerFile(storeDir: string, file: string, log: Log): void {
166
157
  } finally {
167
158
  db.close();
168
159
  }
169
- const fd = openSync(temp, "r");
170
- try {
171
- fsyncSync(fd);
172
- } finally {
173
- closeSync(fd);
174
- }
160
+ fsyncPath(temp);
175
161
  try {
176
162
  linkSync(temp, file);
177
163
  log.info("ledger.created", { file });
@@ -185,16 +171,8 @@ function createLedgerFile(storeDir: string, file: string, log: Log): void {
185
171
  }
186
172
 
187
173
  function syncDirectory(dir: string): void {
188
- try {
189
- const fd = openSync(dir, "r");
190
- try {
191
- fsyncSync(fd);
192
- } finally {
193
- closeSync(fd);
194
- }
195
- } catch {
196
- // Some file systems can't fsync a directory; the data itself is synced.
197
- }
174
+ // Some file systems can't fsync a directory; the data itself is synced.
175
+ fsyncPath(dir, true);
198
176
  }
199
177
 
200
178
  /**