tmux-ide 2.9.20 → 2.9.22

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 (145) hide show
  1. package/bin/cli.js +16998 -4283
  2. package/package.json +3 -2
  3. package/packages/contracts/src/command-catalog.ts +116 -0
  4. package/packages/contracts/src/commands.ts +5 -4
  5. package/packages/contracts/src/daemon-events.ts +2 -1
  6. package/packages/contracts/src/index.ts +3 -0
  7. package/packages/contracts/src/pane-reader.ts +121 -0
  8. package/packages/contracts/src/pane-stream.ts +18 -0
  9. package/packages/contracts/src/plain-text.ts +61 -0
  10. package/packages/contracts/src/visual-theme-presets.ts +58 -2
  11. package/packages/daemon/dist/command-center/command-catalog-routes.js +78 -0
  12. package/packages/daemon/dist/command-center/plugin-routes.js +84 -0
  13. package/packages/daemon/dist/command-center/server.js +13 -0
  14. package/packages/daemon/dist/command-center/tmux-server-reader.js +41 -0
  15. package/packages/daemon/dist/command-center/tmux-servers.js +6 -0
  16. package/packages/daemon/dist/doctor.js +106 -43
  17. package/packages/daemon/dist/lib/cli-action-bridge.js +15 -0
  18. package/packages/daemon/dist/lib/cli-command.js +13 -0
  19. package/packages/daemon/dist/lib/daemon-embed.js +39 -1
  20. package/packages/daemon/dist/lib/headless-daemon.js +1 -0
  21. package/packages/daemon/dist/lib/pane-reader-files.js +226 -0
  22. package/packages/daemon/dist/lib/remote-tmux-command.js +8 -5
  23. package/packages/daemon/dist/lib/tmux-client-execution.js +73 -7
  24. package/packages/daemon/dist/lib/tmux-pane-reader.js +105 -0
  25. package/packages/daemon/dist/lib/tmux-server-features.js +38 -0
  26. package/packages/daemon/dist/lib/tmux-server-owner.js +9 -0
  27. package/packages/daemon/dist/lib/worktree.js +18 -0
  28. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  29. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  30. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  31. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  32. package/packages/daemon/dist/open-browser.js +26 -12
  33. package/packages/daemon/dist/open-reader.js +84 -0
  34. package/packages/daemon/dist/plugins/action-catalog.js +129 -0
  35. package/packages/daemon/dist/plugins/action-cli.js +212 -0
  36. package/packages/daemon/dist/plugins/api-table.js +303 -0
  37. package/packages/daemon/dist/plugins/cli.js +556 -0
  38. package/packages/daemon/dist/plugins/consent.js +107 -0
  39. package/packages/daemon/dist/plugins/daemon-plugins.js +124 -0
  40. package/packages/daemon/dist/plugins/discovery.js +142 -0
  41. package/packages/daemon/dist/plugins/examples/worktree-tasks.js +115 -0
  42. package/packages/daemon/dist/plugins/exec-sandbox.js +202 -0
  43. package/packages/daemon/dist/plugins/host/actions-prelude.js +279 -0
  44. package/packages/daemon/dist/plugins/host/entry.js +4 -0
  45. package/packages/daemon/dist/plugins/host/host-api-prelude.js +232 -0
  46. package/packages/daemon/dist/plugins/host/lua-state.js +493 -0
  47. package/packages/daemon/dist/plugins/host/main.js +322 -0
  48. package/packages/daemon/dist/plugins/host/sandbox.js +299 -0
  49. package/packages/daemon/dist/plugins/host-calls.js +279 -0
  50. package/packages/daemon/dist/plugins/manifest.js +69 -0
  51. package/packages/daemon/dist/plugins/plugin-exec.js +261 -0
  52. package/packages/daemon/dist/plugins/plugin-log.js +54 -0
  53. package/packages/daemon/dist/plugins/plugin-store.js +74 -0
  54. package/packages/daemon/dist/plugins/protocol.js +252 -0
  55. package/packages/daemon/dist/plugins/safe-files.js +97 -0
  56. package/packages/daemon/dist/plugins/supervisor.js +790 -0
  57. package/packages/daemon/dist/plugins/worktree-calls.js +154 -0
  58. package/packages/daemon/dist/restore.js +57 -40
  59. package/packages/daemon/dist/terminal/mirror/session-channel.js +4 -1
  60. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +12 -3
  61. package/packages/daemon/dist/terminal/protocol/reader-option.js +66 -0
  62. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +7 -2
  63. package/packages/daemon/dist/tmux-upgrade/cli.js +106 -0
  64. package/packages/daemon/dist/tmux-upgrade/io.js +540 -0
  65. package/packages/daemon/dist/tmux-upgrade/plan.js +238 -0
  66. package/packages/daemon/dist/tmux-upgrade/run.js +199 -0
  67. package/packages/daemon/dist/tui/chrome/snapshot.js +3 -4
  68. package/packages/daemon/dist/tui/mirror/runtime/application-home-agent-navigation.js +64 -4
  69. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +62 -5
  70. package/packages/daemon/dist/tui/mirror/runtime/application-home-experience.js +2 -0
  71. package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +12 -8
  72. package/packages/daemon/dist/tui/mirror/runtime/application-palette-command-owner.js +30 -2
  73. package/packages/daemon/dist/tui/mirror/runtime/application-plugin-commands.js +152 -0
  74. package/packages/daemon/dist/tui/mirror/runtime/application-plugin-form.js +251 -0
  75. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +125 -111
  76. package/packages/daemon/dist/tui/mirror/workspace/application-command-description.js +14 -0
  77. package/packages/daemon/dist/tui/mirror/workspace/palette-list-layout.js +5 -0
  78. package/packages/daemon/src/command-center/command-catalog-routes.ts +116 -0
  79. package/packages/daemon/src/command-center/plugin-routes.ts +110 -0
  80. package/packages/daemon/src/command-center/server.ts +15 -0
  81. package/packages/daemon/src/command-center/tmux-server-reader.ts +62 -0
  82. package/packages/daemon/src/command-center/tmux-servers.ts +6 -0
  83. package/packages/daemon/src/doctor.ts +118 -45
  84. package/packages/daemon/src/lib/cli-action-bridge.ts +19 -0
  85. package/packages/daemon/src/lib/cli-command.ts +16 -0
  86. package/packages/daemon/src/lib/daemon-embed.ts +59 -0
  87. package/packages/daemon/src/lib/headless-daemon.ts +1 -0
  88. package/packages/daemon/src/lib/pane-reader-files.ts +294 -0
  89. package/packages/daemon/src/lib/remote-tmux-command.ts +13 -6
  90. package/packages/daemon/src/lib/tmux-client-execution.ts +79 -7
  91. package/packages/daemon/src/lib/tmux-pane-reader.ts +144 -0
  92. package/packages/daemon/src/lib/tmux-server-features.ts +43 -0
  93. package/packages/daemon/src/lib/tmux-server-owner.ts +9 -0
  94. package/packages/daemon/src/lib/worktree.ts +16 -0
  95. package/packages/daemon/src/open-browser.ts +59 -18
  96. package/packages/daemon/src/open-reader.ts +148 -0
  97. package/packages/daemon/src/plugins/action-catalog.ts +141 -0
  98. package/packages/daemon/src/plugins/action-cli.ts +248 -0
  99. package/packages/daemon/src/plugins/api-table.ts +346 -0
  100. package/packages/daemon/src/plugins/cli.ts +630 -0
  101. package/packages/daemon/src/plugins/consent.ts +125 -0
  102. package/packages/daemon/src/plugins/daemon-plugins.ts +172 -0
  103. package/packages/daemon/src/plugins/discovery.ts +176 -0
  104. package/packages/daemon/src/plugins/examples/worktree-tasks.ts +120 -0
  105. package/packages/daemon/src/plugins/exec-sandbox.ts +264 -0
  106. package/packages/daemon/src/plugins/host/actions-prelude.ts +280 -0
  107. package/packages/daemon/src/plugins/host/entry.ts +5 -0
  108. package/packages/daemon/src/plugins/host/host-api-prelude.ts +233 -0
  109. package/packages/daemon/src/plugins/host/lua-state.ts +557 -0
  110. package/packages/daemon/src/plugins/host/main.ts +359 -0
  111. package/packages/daemon/src/plugins/host/sandbox.ts +301 -0
  112. package/packages/daemon/src/plugins/host-calls.ts +343 -0
  113. package/packages/daemon/src/plugins/manifest.ts +74 -0
  114. package/packages/daemon/src/plugins/plugin-exec.ts +326 -0
  115. package/packages/daemon/src/plugins/plugin-log.ts +63 -0
  116. package/packages/daemon/src/plugins/plugin-store.ts +80 -0
  117. package/packages/daemon/src/plugins/protocol.ts +275 -0
  118. package/packages/daemon/src/plugins/safe-files.ts +105 -0
  119. package/packages/daemon/src/plugins/supervisor.ts +954 -0
  120. package/packages/daemon/src/plugins/worktree-calls.ts +183 -0
  121. package/packages/daemon/src/restore.ts +80 -44
  122. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  123. package/packages/daemon/src/terminal/mirror/session-channel.ts +6 -1
  124. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +15 -2
  125. package/packages/daemon/src/terminal/protocol/reader-option.ts +77 -0
  126. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +10 -1
  127. package/packages/daemon/src/tmux-upgrade/cli.ts +118 -0
  128. package/packages/daemon/src/tmux-upgrade/io.ts +596 -0
  129. package/packages/daemon/src/tmux-upgrade/plan.ts +353 -0
  130. package/packages/daemon/src/tmux-upgrade/run.ts +325 -0
  131. package/packages/daemon/src/tui/chrome/snapshot.ts +3 -4
  132. package/packages/daemon/src/tui/mirror/runtime/application-fleet-switcher.tsx +3 -1
  133. package/packages/daemon/src/tui/mirror/runtime/application-home-agent-navigation.ts +110 -10
  134. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +90 -6
  135. package/packages/daemon/src/tui/mirror/runtime/application-home-experience.ts +2 -0
  136. package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +20 -9
  137. package/packages/daemon/src/tui/mirror/runtime/application-palette-command-owner.ts +42 -2
  138. package/packages/daemon/src/tui/mirror/runtime/application-palette-preview.tsx +7 -1
  139. package/packages/daemon/src/tui/mirror/runtime/application-plugin-commands.ts +229 -0
  140. package/packages/daemon/src/tui/mirror/runtime/application-plugin-form.ts +312 -0
  141. package/packages/daemon/src/tui/mirror/runtime/application-root-v2.tsx +2 -2
  142. package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +149 -128
  143. package/packages/daemon/src/tui/mirror/workspace/application-command-description.ts +44 -2
  144. package/packages/daemon/src/tui/mirror/workspace/palette-list-layout.ts +4 -0
  145. package/packages/tmux-bridge/src/runner.ts +3 -1
@@ -0,0 +1,275 @@
1
+ /**
2
+ * The daemon ↔ plugin host wire.
3
+ *
4
+ * The daemon writes newline-delimited JSON to the host's stdin. The host
5
+ * writes newline-delimited JSON to file descriptor 3 with synchronous writes,
6
+ * so a "busy" marker is on the wire before a Lua slice starts: if that slice
7
+ * never returns, the daemon still knows which plugin to blame. Stdout and
8
+ * stderr stay free for anything the runtime prints on its own.
9
+ */
10
+ import { z } from "zod";
11
+
12
+ /** Version of the Lua API exposed as `ide.api`. Minor versions only add. */
13
+ export const PLUGIN_API_VERSION = "1.0" as const;
14
+
15
+ /** Bumped when the daemon/host messages change shape. */
16
+ export const PLUGIN_HOST_PROTOCOL_VERSION = 1 as const;
17
+
18
+ export const PLUGIN_NAME_PATTERN = /^[a-z][a-z0-9-]{0,62}$/u;
19
+ export const PluginNameSchemaZ = z.string().regex(PLUGIN_NAME_PATTERN);
20
+
21
+ /** The user's `init.lua` runs as this reserved plugin name. */
22
+ export const INIT_PLUGIN_NAME = "init" as const;
23
+
24
+ /**
25
+ * Names the host and daemon use for their own work. No plugin directory may
26
+ * take one: `run` labels `tmux-ide lua run`, `host` the host's own log lines.
27
+ */
28
+ /** The name the host gives the temporary state behind `tmux-ide lua run`. */
29
+ export const RUN_STATE_NAME = "run" as const;
30
+
31
+ export const RESERVED_PLUGIN_NAMES: ReadonlySet<string> = new Set([
32
+ INIT_PLUGIN_NAME,
33
+ RUN_STATE_NAME,
34
+ "host",
35
+ "daemon",
36
+ "ide",
37
+ "plugin",
38
+ "plugins",
39
+ "tmux-ide",
40
+ ]);
41
+
42
+ export const PluginLimitsSchemaZ = z
43
+ .object({
44
+ /** Lua run time allowed per callback, excluding time spent awaiting the host. */
45
+ callbackBudgetMs: z.number().int().min(10).max(600_000),
46
+ /** Bytes a plugin's Lua state may allocate. */
47
+ memoryBytes: z
48
+ .number()
49
+ .int()
50
+ .min(1024 * 1024)
51
+ .max(1024 * 1024 * 1024),
52
+ /**
53
+ * Wall-clock limit for one load or callback, including time spent waiting
54
+ * for the host. Stops a host call that never settles.
55
+ */
56
+ wallClockMs: z.number().int().min(100).max(3_600_000),
57
+ /** Log lines a plugin may emit per second before lines are dropped. */
58
+ logLinesPerSecond: z.number().int().min(1).max(10_000),
59
+ })
60
+ .strict();
61
+ export type PluginLimits = z.infer<typeof PluginLimitsSchemaZ>;
62
+
63
+ export const DEFAULT_PLUGIN_LIMITS: PluginLimits = Object.freeze({
64
+ callbackBudgetMs: 250,
65
+ memoryBytes: 64 * 1024 * 1024,
66
+ wallClockMs: 30_000,
67
+ logLinesPerSecond: 100,
68
+ });
69
+
70
+ export const PluginSpecSchemaZ = z
71
+ .object({
72
+ name: z.union([PluginNameSchemaZ, z.literal(INIT_PLUGIN_NAME)]),
73
+ kind: z.enum(["init", "plugin"]),
74
+ /** Consented content hash; the host re-hashes the directory and refuses a mismatch. */
75
+ contentHash: z
76
+ .string()
77
+ .regex(/^sha256:[0-9a-f]{64}$/u)
78
+ .optional(),
79
+ /** Absolute path of the entry file. */
80
+ entry: z.string().min(1),
81
+ /** Absolute directories `ide.include` may read from, in search order. */
82
+ includeRoots: z.array(z.string().min(1)).max(8),
83
+ /** Absolute directories `require` may read from, in search order. */
84
+ moduleRoots: z.array(z.string().min(1)).max(8),
85
+ settings: z.record(z.string(), z.json()),
86
+ /** What the owner consented to; init.lua gets everything. */
87
+ capabilities: z
88
+ .object({
89
+ exec: z.union([z.array(z.string()).max(32), z.literal("any")]),
90
+ shell: z.boolean(),
91
+ /** `panes.send`: type into panes and run programs as if typed there. */
92
+ panes: z.boolean(),
93
+ /** Create, open and remove git worktrees and their sessions. */
94
+ worktree: z.boolean(),
95
+ })
96
+ .strict(),
97
+ })
98
+ .strict();
99
+ export type PluginSpec = z.infer<typeof PluginSpecSchemaZ>;
100
+
101
+ /**
102
+ * Host functions the daemon serves for plugins (host-calls.ts). Each is
103
+ * exposed to the preludes as `__ide_internal.host[name]`, never directly to
104
+ * plugin code.
105
+ */
106
+ export const HOST_CALL_METHODS = Object.freeze([
107
+ "_exec",
108
+ "_panes",
109
+ "_pane_read",
110
+ "_pane_send",
111
+ "_action",
112
+ "_notify",
113
+ "_store_get",
114
+ "_store_set",
115
+ "_store_keys",
116
+ "_worktree",
117
+ ] as const);
118
+
119
+ // ---------------------------------------------------------------- daemon → host
120
+
121
+ export const HostCommandSchemaZ = z.discriminatedUnion("type", [
122
+ z
123
+ .object({
124
+ type: z.literal("configure"),
125
+ protocolVersion: z.literal(PLUGIN_HOST_PROTOCOL_VERSION),
126
+ productVersion: z.string(),
127
+ limits: PluginLimitsSchemaZ,
128
+ })
129
+ .strict(),
130
+ z.object({ type: z.literal("load"), plugin: PluginSpecSchemaZ }).strict(),
131
+ z.object({ type: z.literal("unload"), name: z.string() }).strict(),
132
+ z
133
+ .object({
134
+ type: z.literal("run"),
135
+ id: z.string().min(1).max(64),
136
+ code: z.string().max(1024 * 1024),
137
+ chunkName: z.string().min(1).max(200),
138
+ budgetMs: z.number().int().min(10).max(600_000),
139
+ })
140
+ .strict(),
141
+ z
142
+ .object({
143
+ type: z.literal("invoke"),
144
+ id: z.string().min(1).max(64),
145
+ plugin: z.string().min(1).max(64),
146
+ action: z.string().min(1).max(100),
147
+ args: z.record(z.string(), z.json()),
148
+ context: z.record(z.string(), z.json()),
149
+ })
150
+ .strict(),
151
+ z
152
+ .object({
153
+ type: z.literal("param-options"),
154
+ id: z.string().min(1).max(64),
155
+ plugin: z.string().min(1).max(64),
156
+ action: z.string().min(1).max(100),
157
+ param: z.string().min(1).max(64),
158
+ context: z.record(z.string(), z.json()),
159
+ })
160
+ .strict(),
161
+ z
162
+ .object({
163
+ type: z.literal("call-result"),
164
+ id: z.string().min(1).max(64),
165
+ ok: z.boolean(),
166
+ /** JSON text of the result. */
167
+ value: z
168
+ .string()
169
+ .max(8 * 1024 * 1024)
170
+ .optional(),
171
+ error: z
172
+ .string()
173
+ .max(16 * 1024)
174
+ .optional(),
175
+ })
176
+ .strict(),
177
+ z.object({ type: z.literal("shutdown") }).strict(),
178
+ ]);
179
+ export type HostCommand = z.infer<typeof HostCommandSchemaZ>;
180
+
181
+ // ---------------------------------------------------------------- host → daemon
182
+
183
+ export const LogLevelSchemaZ = z.enum(["debug", "info", "warn", "error"]);
184
+ export type PluginLogLevel = z.infer<typeof LogLevelSchemaZ>;
185
+
186
+ export const TripKindSchemaZ = z.enum(["timeout", "memory", "abort"]);
187
+ export type PluginTripKind = z.infer<typeof TripKindSchemaZ>;
188
+
189
+ export const HostEventSchemaZ = z.discriminatedUnion("type", [
190
+ z
191
+ .object({
192
+ type: z.literal("hello"),
193
+ protocolVersion: z.literal(PLUGIN_HOST_PROTOCOL_VERSION),
194
+ pid: z.number().int(),
195
+ })
196
+ .strict(),
197
+ z.object({ type: z.literal("heartbeat"), seq: z.number().int() }).strict(),
198
+ /** A Lua slice for `plugin` is about to run synchronously. */
199
+ z.object({ type: z.literal("busy"), plugin: z.string() }).strict(),
200
+ z.object({ type: z.literal("idle"), plugin: z.string() }).strict(),
201
+ z
202
+ .object({
203
+ type: z.literal("log"),
204
+ plugin: z.string(),
205
+ level: LogLevelSchemaZ,
206
+ message: z.string(),
207
+ fields: z.record(z.string(), z.json()).optional(),
208
+ })
209
+ .strict(),
210
+ z
211
+ .object({
212
+ type: z.literal("loaded"),
213
+ plugin: z.string(),
214
+ ok: z.boolean(),
215
+ error: z.string().optional(),
216
+ memoryBytes: z.number().int().nonnegative().optional(),
217
+ })
218
+ .strict(),
219
+ z.object({ type: z.literal("trip"), plugin: z.string(), kind: TripKindSchemaZ }).strict(),
220
+ z
221
+ .object({
222
+ type: z.literal("call"),
223
+ id: z.string().min(1).max(64),
224
+ plugin: z.string().min(1).max(64),
225
+ method: z.string().min(1).max(64),
226
+ /** JSON text of the argument list. */
227
+ args: z.string().max(4 * 1024 * 1024),
228
+ /** The invoke or param-options request whose callback made the call. */
229
+ origin: z.string().min(1).max(64).optional(),
230
+ })
231
+ .strict(),
232
+ z
233
+ .object({
234
+ type: z.literal("actions"),
235
+ plugin: z.string(),
236
+ /** JSON text of the plugin's plain action descriptors. */
237
+ actions: z.string().max(4 * 1024 * 1024),
238
+ })
239
+ .strict(),
240
+ z
241
+ .object({
242
+ type: z.literal("invoke-result"),
243
+ id: z.string(),
244
+ ok: z.boolean(),
245
+ /** JSON text: an array whose first element is the action's result. */
246
+ value: z.string().optional(),
247
+ error: z.string().optional(),
248
+ })
249
+ .strict(),
250
+ z
251
+ .object({
252
+ type: z.literal("param-options-result"),
253
+ id: z.string(),
254
+ ok: z.boolean(),
255
+ /** JSON text `{ choices?, default? }`. */
256
+ options: z.string().optional(),
257
+ error: z.string().optional(),
258
+ })
259
+ .strict(),
260
+ z
261
+ .object({
262
+ type: z.literal("run-result"),
263
+ id: z.string(),
264
+ ok: z.boolean(),
265
+ /** JSON text of the returned values, as an array. */
266
+ values: z.string().optional(),
267
+ error: z.string().optional(),
268
+ logs: z.array(z.object({ level: LogLevelSchemaZ, message: z.string() }).strict()),
269
+ })
270
+ .strict(),
271
+ ]);
272
+ export type HostEvent = z.infer<typeof HostEventSchemaZ>;
273
+
274
+ /** Longest single protocol line either side accepts. */
275
+ export const MAX_PROTOCOL_LINE_BYTES = 4 * 1024 * 1024;
@@ -0,0 +1,105 @@
1
+ /**
2
+ * File access for paths a plugin's programs might have touched. Nothing
3
+ * here follows a symlink at the final path component, and writes never go
4
+ * through a name someone else could have created first.
5
+ */
6
+ import { randomBytes } from "node:crypto";
7
+ import {
8
+ closeSync,
9
+ constants,
10
+ fstatSync,
11
+ lstatSync,
12
+ mkdirSync,
13
+ openSync,
14
+ readSync,
15
+ renameSync,
16
+ rmSync,
17
+ writeSync,
18
+ } from "node:fs";
19
+ import { dirname } from "node:path";
20
+
21
+ export class UnsafeFileError extends Error {}
22
+
23
+ /**
24
+ * Read `path` as UTF-8 if it is a regular file of at most `maxBytes`.
25
+ * Returns null when it does not exist; throws when it is a symlink, not a
26
+ * regular file, or too large.
27
+ */
28
+ export function readRegularFile(path: string, maxBytes: number): string | null {
29
+ let fd: number;
30
+ try {
31
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
32
+ } catch (error) {
33
+ const code = (error as NodeJS.ErrnoException).code;
34
+ if (code === "ENOENT") return null;
35
+ if (code === "ELOOP" || code === "EMLINK")
36
+ throw new UnsafeFileError(`${path} is a symlink; refusing to read it`);
37
+ throw error;
38
+ }
39
+ try {
40
+ const stat = fstatSync(fd);
41
+ if (!stat.isFile()) throw new UnsafeFileError(`${path} is not a regular file`);
42
+ if (stat.size > maxBytes) throw new UnsafeFileError(`${path} is larger than ${maxBytes} bytes`);
43
+ const buffer = Buffer.alloc(maxBytes + 1);
44
+ let length = 0;
45
+ for (;;) {
46
+ const read = readSync(fd, buffer, length, buffer.length - length, null);
47
+ if (read === 0) break;
48
+ length += read;
49
+ if (length > maxBytes) throw new UnsafeFileError(`${path} is larger than ${maxBytes} bytes`);
50
+ }
51
+ return buffer.subarray(0, length).toString("utf8");
52
+ } finally {
53
+ closeSync(fd);
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Replace `path` with `text`: written to a fresh, randomly named file that
59
+ * must not exist yet (O_EXCL, O_NOFOLLOW), then renamed over `path`. A
60
+ * symlink at `path` is replaced, never followed.
61
+ */
62
+ export function writeFileAtomic(
63
+ path: string,
64
+ text: string,
65
+ /** Tests pass a fixed name to see that a planted file there is refused. */
66
+ temporaryName: () => string = () => `${path}.${randomBytes(12).toString("hex")}.tmp`,
67
+ ): void {
68
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
69
+ const temporary = temporaryName();
70
+ const fd = openSync(
71
+ temporary,
72
+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,
73
+ 0o600,
74
+ );
75
+ let renamed = false;
76
+ try {
77
+ try {
78
+ const data = Buffer.from(text, "utf8");
79
+ let written = 0;
80
+ while (written < data.length) written += writeSync(fd, data, written);
81
+ } finally {
82
+ closeSync(fd);
83
+ }
84
+ renameSync(temporary, path);
85
+ renamed = true;
86
+ } finally {
87
+ if (!renamed) rmSync(temporary, { force: true });
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Make sure `path` is a real directory (not a symlink to one), creating it
93
+ * if needed. Throws if something else is there.
94
+ */
95
+ export function ensureRealDirectory(path: string): void {
96
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
97
+ try {
98
+ mkdirSync(path, { mode: 0o700 });
99
+ } catch (error) {
100
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
101
+ }
102
+ const stat = lstatSync(path);
103
+ if (stat.isSymbolicLink() || !stat.isDirectory())
104
+ throw new UnsafeFileError(`${path} is not a real directory`);
105
+ }