akanjs 3.3.0 → 3.4.0-rc.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.
- package/common/PipelinePlanSchema.ts +31 -7
- package/common/index.ts +6 -0
- package/common/pipelinePlan.ts +31 -5
- package/index.ts +7 -5
- package/package.json +1 -1
- package/pipelineConfig.ts +25 -2
- package/service/agentLoop/agentLoop.ts +19 -12
- package/service/predefinedAdaptor/anthropicTools.ts +8 -2
- package/types/common/index.d.ts +1 -1
- package/types/common/pipelinePlan.d.ts +35 -6
- package/types/index.d.ts +7 -5
- package/types/pipelineConfig.d.ts +20 -3
- package/types/server/logging/rotatingLogWriter.d.ts +1 -1
- package/types/service/predefinedAdaptor/anthropicTools.d.ts +1 -0
- package/types/vendor/@akanjs/native/packages/cli/src/api-updates.d.ts +149 -0
- package/types/vendor/@akanjs/native/packages/cli/src/api.d.ts +16 -162
- package/types/vendor/@akanjs/native/packages/cli/src/config.d.ts +3 -2
- package/types/vendor/@akanjs/native/packages/cli/src/lib/api-task.d.ts +79 -0
- package/types/vendor/@akanjs/native/packages/cli/src/lib/prepare.d.ts +1 -1
- package/types/vendor/@akanjs/native/packages/cli/src/lib/publish.d.ts +17 -5
- package/types/vendor/@akanjs/native/packages/cli/src/lib/updates.d.ts +29 -2
- package/types/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.d.ts +36 -0
- package/types/vendor/@akanjs/native/packages/cli/src/platforms/linux-install.d.ts +15 -0
- package/types/vendor/@akanjs/native/packages/core/src/kernel.d.ts +16 -5
- package/types/vendor/@akanjs/native/packages/desktop/src/commands.d.ts +81 -0
- package/types/vendor/@akanjs/native/packages/desktop/src/deeplinks.d.ts +5 -1
- package/types/vendor/@akanjs/native/packages/desktop/src/dispatcher.d.ts +3 -0
- package/types/vendor/@akanjs/native/packages/desktop/src/lifecycle.d.ts +8 -1
- package/types/vendor/@akanjs/native/packages/desktop/src/plugin.d.ts +21 -0
- package/types/vendor/@akanjs/native/packages/desktop/src/server.d.ts +1 -0
- package/types/vendor/@akanjs/native/plugins/updates/src/desktop.d.ts +4 -4
- package/types/vendor/@akanjs/native/plugins/updates/src/reports.d.ts +49 -0
- package/types/vendor/@akanjs/native/plugins/updates/src/signer.d.ts +21 -0
- package/types/vendor/@akanjs/native/plugins/window/src/index.d.ts +55 -3
- package/vendor/@akanjs/native/native/desktop/src/lib.rs +209 -54
- package/vendor/@akanjs/native/packages/cli/src/api-updates.ts +332 -0
- package/vendor/@akanjs/native/packages/cli/src/api.ts +67 -419
- package/vendor/@akanjs/native/packages/cli/src/commands/build.ts +4 -1
- package/vendor/@akanjs/native/packages/cli/src/config.ts +3 -2
- package/vendor/@akanjs/native/packages/cli/src/lib/api-task.ts +223 -0
- package/vendor/@akanjs/native/packages/cli/src/lib/prepare.ts +2 -7
- package/vendor/@akanjs/native/packages/cli/src/lib/publish.ts +164 -19
- package/vendor/@akanjs/native/packages/cli/src/lib/updates.ts +90 -3
- package/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.ts +195 -43
- package/vendor/@akanjs/native/packages/cli/src/platforms/linux-appimage.ts +1 -1
- package/vendor/@akanjs/native/packages/cli/src/platforms/linux-install.ts +206 -0
- package/vendor/@akanjs/native/packages/cli/src/platforms/linux.ts +5 -1
- package/vendor/@akanjs/native/packages/core/src/kernel.ts +21 -6
- package/vendor/@akanjs/native/packages/core/vectors/updates.json +2 -1
- package/vendor/@akanjs/native/packages/desktop/src/commands.ts +380 -0
- package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +20 -3
- package/vendor/@akanjs/native/packages/desktop/src/dispatcher.ts +28 -13
- package/vendor/@akanjs/native/packages/desktop/src/host.ts +6 -18
- package/vendor/@akanjs/native/packages/desktop/src/lifecycle.ts +8 -1
- package/vendor/@akanjs/native/packages/desktop/src/plugin.ts +21 -0
- package/vendor/@akanjs/native/packages/desktop/src/server.ts +1 -1
- package/vendor/@akanjs/native/plugins/updates/src/desktop.ts +90 -164
- package/vendor/@akanjs/native/plugins/updates/src/reports.ts +255 -0
- package/vendor/@akanjs/native/plugins/updates/src/signer.ts +133 -0
- package/vendor/@akanjs/native/plugins/window/native-plugin.json +6 -1
- package/vendor/@akanjs/native/plugins/window/src/desktop.ts +20 -4
- package/vendor/@akanjs/native/plugins/window/src/index.ts +55 -3
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { accessSync, constants, existsSync, statSync } from "node:fs";
|
|
5
|
+
import { userInfo } from "node:os";
|
|
6
|
+
import { basename, delimiter, isAbsolute, join, resolve as resolvePath } from "node:path";
|
|
7
|
+
import { AkanNativeError } from "../../core/src/index.ts";
|
|
8
|
+
import type { DocumentScope } from "./plugin.ts";
|
|
9
|
+
import { envValue, pathWithFirst, pipeLines } from "./server.ts";
|
|
10
|
+
|
|
11
|
+
export interface ResolvedCommand {
|
|
12
|
+
path: string;
|
|
13
|
+
/** Windows: a `.cmd` or `.bat` file, which only cmd.exe runs. ctx.spawn does that itself. */
|
|
14
|
+
shell: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface DesktopSpawnOptions {
|
|
18
|
+
cwd?: string;
|
|
19
|
+
/**
|
|
20
|
+
* The child's whole environment, nothing added. Default: the app's own, with the app's bin folder and then the
|
|
21
|
+
* user's PATH (userPath) as its PATH.
|
|
22
|
+
*/
|
|
23
|
+
env?: Record<string, string | undefined>;
|
|
24
|
+
/** "pipe": `stdin` writes to the child. Default "ignore". */
|
|
25
|
+
stdin?: "pipe" | "ignore";
|
|
26
|
+
/** Reads the child's output line by line; `stdout` and `stderr` are null then. */
|
|
27
|
+
onLine?(line: string, stream: "stdout" | "stderr"): void;
|
|
28
|
+
/** `ctx.document`: the child also ends when that page does (a reload, a navigation, its window closed). */
|
|
29
|
+
document?: DocumentScope;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface DesktopProcessInput {
|
|
33
|
+
write(chunk: string | Uint8Array): void;
|
|
34
|
+
end(): void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface DesktopProcess {
|
|
38
|
+
readonly pid: number;
|
|
39
|
+
/** The exit code; 128 + the signal's number when a signal ended it. */
|
|
40
|
+
readonly exited: Promise<number>;
|
|
41
|
+
readonly stdin: DesktopProcessInput | null;
|
|
42
|
+
readonly stdout: ReadableStream<Uint8Array> | null;
|
|
43
|
+
readonly stderr: ReadableStream<Uint8Array> | null;
|
|
44
|
+
/** Signals the child and what it started (macOS, Linux: its process group; Windows: its tree, ended outright). */
|
|
45
|
+
kill(signal?: NodeJS.Signals): void;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface DesktopCommands {
|
|
49
|
+
userPath(): Promise<string>;
|
|
50
|
+
resolveCommand(name: string): Promise<ResolvedCommand | null>;
|
|
51
|
+
spawn(cmd: string[], options?: DesktopSpawnOptions): Promise<DesktopProcess>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface CommandsOptions {
|
|
55
|
+
/** The app's own executables (desktop.bin), searched first. */
|
|
56
|
+
binDir: string | null;
|
|
57
|
+
platform?: NodeJS.Platform;
|
|
58
|
+
env?: Record<string, string | undefined>;
|
|
59
|
+
/** The user's shell; the account's by default. */
|
|
60
|
+
shell?: string;
|
|
61
|
+
probeTimeout?: number;
|
|
62
|
+
reapGrace?: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A login shell with a heavy profile takes seconds (5 s measured for bash with nvm and conda). */
|
|
66
|
+
export const PROBE_TIMEOUT = 10_000;
|
|
67
|
+
/** What a child gets between SIGTERM and SIGKILL when its page or the app ends. */
|
|
68
|
+
export const REAP_GRACE = 2000;
|
|
69
|
+
|
|
70
|
+
/** The app's bin folder first on this process's PATH, under one name; null when the app carries none. */
|
|
71
|
+
export function appBinFirst(resources: string): string | null {
|
|
72
|
+
const binDir = join(resources, "bin");
|
|
73
|
+
if (!existsSync(binDir)) return null;
|
|
74
|
+
|
|
75
|
+
const path = envValue(process.env, "PATH");
|
|
76
|
+
for (const name of Object.keys(process.env)) if (name.toUpperCase() === "PATH") delete process.env[name];
|
|
77
|
+
process.env.PATH = pathWithFirst(binDir, path);
|
|
78
|
+
return binDir;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const isFile = (path: string, executable: boolean): boolean => {
|
|
82
|
+
try {
|
|
83
|
+
if (!statSync(path).isFile()) return false;
|
|
84
|
+
if (executable) accessSync(path, constants.X_OK);
|
|
85
|
+
return true;
|
|
86
|
+
} catch {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* `name` in `dirs`, the first hit. Windows tries each PATHEXT ending unless the name already has one of them. A name
|
|
93
|
+
* with a folder in it is looked up as that path alone.
|
|
94
|
+
*/
|
|
95
|
+
export function findCommand(
|
|
96
|
+
name: string,
|
|
97
|
+
dirs: readonly string[],
|
|
98
|
+
{ platform = process.platform, pathExt }: { platform?: NodeJS.Platform; pathExt?: string } = {},
|
|
99
|
+
): ResolvedCommand | null {
|
|
100
|
+
if (!name || name.includes("\0")) return null;
|
|
101
|
+
const windows = platform === "win32";
|
|
102
|
+
const endings = windows
|
|
103
|
+
? (pathExt || ".COM;.EXE;.BAT;.CMD")
|
|
104
|
+
.split(";")
|
|
105
|
+
.map((ending) => ending.trim().toLowerCase())
|
|
106
|
+
.filter((ending) => ending.startsWith("."))
|
|
107
|
+
: [];
|
|
108
|
+
const named = endings.some((ending) => name.toLowerCase().endsWith(ending));
|
|
109
|
+
const candidates = windows ? (named ? [name] : endings.map((ending) => `${name}${ending}`)) : [name];
|
|
110
|
+
const within = /[\\/]/.test(name) ? [""] : dirs.filter((dir) => dir && (windows || isAbsolute(dir)));
|
|
111
|
+
for (const dir of within)
|
|
112
|
+
for (const candidate of candidates) {
|
|
113
|
+
const path = dir ? join(dir, candidate) : resolvePath(candidate);
|
|
114
|
+
if (isFile(path, !windows)) return { path, shell: windows && /\.(cmd|bat)$/i.test(path) };
|
|
115
|
+
}
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* A command line cmd.exe hands to a batch file unchanged: each argument quoted as CommandLineToArgvW reads it, then
|
|
121
|
+
* every character cmd.exe gives a meaning escaped with `^`, twice for the arguments, which the batch file's own line
|
|
122
|
+
* (`node "%~dp0\…" %*`) puts through cmd.exe again.
|
|
123
|
+
*/
|
|
124
|
+
export function batchCommandLine(file: string, args: readonly string[]): string {
|
|
125
|
+
|
|
126
|
+
if (args.some((arg) => /[\r\n\0]/.test(arg)))
|
|
127
|
+
throw new AkanNativeError("INVALID_ARGS", "an argument of a .cmd or .bat file cannot hold a line break");
|
|
128
|
+
const meta = /([()\][%!^"`<>&|;, *?])/g;
|
|
129
|
+
const quoted = (arg: string) => `"${arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"`;
|
|
130
|
+
const line = [file.replace(meta, "^$1"), ...args.map((arg) => quoted(arg).replace(meta, "^$1").replace(meta, "^$1"))];
|
|
131
|
+
return `"${line.join(" ")}"`;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const REAPER = `groups=""
|
|
135
|
+
while IFS=" " read -r op id; do
|
|
136
|
+
case "$op" in
|
|
137
|
+
add) groups="$groups $id" ;;
|
|
138
|
+
del) kept=""; for g in $groups; do [ "$g" = "$id" ] || kept="$kept $g"; done; groups=$kept ;;
|
|
139
|
+
esac
|
|
140
|
+
done
|
|
141
|
+
[ -n "$groups" ] || exit 0
|
|
142
|
+
for g in $groups; do kill -TERM "-$g" 2>/dev/null; done
|
|
143
|
+
sleep "$AKAN_NATIVE_REAP_GRACE"
|
|
144
|
+
for g in $groups; do kill -KILL "-$g" 2>/dev/null; done
|
|
145
|
+
exit 0`;
|
|
146
|
+
|
|
147
|
+
const endGroup = (pid: number, signal: NodeJS.Signals) => {
|
|
148
|
+
try {
|
|
149
|
+
process.kill(-pid, signal);
|
|
150
|
+
} catch {
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
/** The process groups the helper ends once this process is gone; the helper starts with the first of them. */
|
|
155
|
+
function createReaper(grace: number) {
|
|
156
|
+
let helper: { proc: Bun.Subprocess<"pipe", "ignore", "ignore">; alive: boolean } | undefined;
|
|
157
|
+
const groups = new Set<number>();
|
|
158
|
+
const tell = (line: string) => {
|
|
159
|
+
if (!helper?.alive) {
|
|
160
|
+
const proc = Bun.spawn(["/bin/sh", "-c", REAPER], {
|
|
161
|
+
stdin: "pipe",
|
|
162
|
+
stdout: "ignore",
|
|
163
|
+
stderr: "ignore",
|
|
164
|
+
env: { PATH: "/usr/bin:/bin", AKAN_NATIVE_REAP_GRACE: String(grace / 1000) },
|
|
165
|
+
|
|
166
|
+
detached: true,
|
|
167
|
+
});
|
|
168
|
+
proc.unref();
|
|
169
|
+
const started = { proc, alive: true };
|
|
170
|
+
void proc.exited.then(() => {
|
|
171
|
+
started.alive = false;
|
|
172
|
+
});
|
|
173
|
+
helper = started;
|
|
174
|
+
for (const group of groups) proc.stdin.write(`add ${group}\n`);
|
|
175
|
+
}
|
|
176
|
+
helper.proc.stdin.write(line);
|
|
177
|
+
helper.proc.stdin.flush();
|
|
178
|
+
};
|
|
179
|
+
return {
|
|
180
|
+
add(group: number) {
|
|
181
|
+
groups.add(group);
|
|
182
|
+
tell(`add ${group}\n`);
|
|
183
|
+
},
|
|
184
|
+
drop(group: number) {
|
|
185
|
+
if (groups.delete(group)) tell(`del ${group}\n`);
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** The PATH `shell` has once it read its files as `flags` make it, or null when it did not say within `timeout`. */
|
|
191
|
+
async function askShell(
|
|
192
|
+
shell: string,
|
|
193
|
+
flags: string[],
|
|
194
|
+
env: Record<string, string | undefined>,
|
|
195
|
+
timeout: number,
|
|
196
|
+
): Promise<string | null> {
|
|
197
|
+
const mark = `__akan_native_${randomBytes(8).toString("hex")}__`;
|
|
198
|
+
try {
|
|
199
|
+
const proc = Bun.spawn([shell, ...flags, `/bin/sh -c 'printf "${mark}%s${mark}" "$PATH"'`], {
|
|
200
|
+
stdin: "ignore",
|
|
201
|
+
stdout: "pipe",
|
|
202
|
+
stderr: "ignore",
|
|
203
|
+
env,
|
|
204
|
+
|
|
205
|
+
detached: true,
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
const reader = proc.stdout.getReader();
|
|
209
|
+
const stop = () => void reader.cancel().catch(() => {});
|
|
210
|
+
const late = setTimeout(stop, timeout);
|
|
211
|
+
const decoder = new TextDecoder();
|
|
212
|
+
let out = "";
|
|
213
|
+
try {
|
|
214
|
+
while (out.split(mark).length < 3) {
|
|
215
|
+
const { done, value } = await reader.read();
|
|
216
|
+
if (done) break;
|
|
217
|
+
out += decoder.decode(value, { stream: true });
|
|
218
|
+
}
|
|
219
|
+
} finally {
|
|
220
|
+
clearTimeout(late);
|
|
221
|
+
stop();
|
|
222
|
+
endGroup(proc.pid, "SIGKILL");
|
|
223
|
+
}
|
|
224
|
+
const path = out.split(mark)[1];
|
|
225
|
+
return out.split(mark).length >= 3 && path?.includes("/") ? path : null;
|
|
226
|
+
} catch {
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** The user's shell's PATH: as an interactive login shell first, then as a login shell only; null when neither told. */
|
|
232
|
+
export async function loginShellPath(
|
|
233
|
+
env: Record<string, string | undefined>,
|
|
234
|
+
{ shell, timeout = PROBE_TIMEOUT }: { shell?: string; timeout?: number } = {},
|
|
235
|
+
): Promise<string | null> {
|
|
236
|
+
let asked = shell;
|
|
237
|
+
try {
|
|
238
|
+
asked ||= userInfo().shell || undefined;
|
|
239
|
+
} catch {
|
|
240
|
+
}
|
|
241
|
+
asked ||= env.SHELL || "/bin/sh";
|
|
242
|
+
|
|
243
|
+
const attempts = /^t?csh$/.test(basename(asked))
|
|
244
|
+
? [["-ic"], ["-c"]]
|
|
245
|
+
: [
|
|
246
|
+
["-l", "-i", "-c"],
|
|
247
|
+
["-l", "-c"],
|
|
248
|
+
];
|
|
249
|
+
for (const flags of attempts) {
|
|
250
|
+
const path = await askShell(asked, flags, env, timeout);
|
|
251
|
+
if (path) return path;
|
|
252
|
+
}
|
|
253
|
+
console.warn(
|
|
254
|
+
`[akan-native] ${asked} did not tell its PATH; commands are looked up on the app's own and in the usual folders`,
|
|
255
|
+
);
|
|
256
|
+
return null;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Where a user's own tools usually are, for a shell that did not tell its PATH (a profile slower than the timeout on a
|
|
261
|
+
* loaded machine): after the app's own PATH, and only the folders that exist. Homebrew, the per-user bin folders and
|
|
262
|
+
* the shims of the version managers that put one folder on PATH.
|
|
263
|
+
*/
|
|
264
|
+
export function usualToolDirs(home: string | undefined): string[] {
|
|
265
|
+
const own = [".local/bin", ".bun/bin", ".cargo/bin", ".volta/bin", ".asdf/shims", ".local/share/mise/shims"];
|
|
266
|
+
return [...(home ? own.map((dir) => join(home, dir)) : []), "/opt/homebrew/bin", "/usr/local/bin"].filter((dir) =>
|
|
267
|
+
existsSync(dir),
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export function createCommands(options: CommandsOptions): DesktopCommands {
|
|
272
|
+
const platform = options.platform ?? process.platform;
|
|
273
|
+
const windows = platform === "win32";
|
|
274
|
+
const env = options.env ?? process.env;
|
|
275
|
+
const { binDir } = options;
|
|
276
|
+
const grace = options.reapGrace ?? REAP_GRACE;
|
|
277
|
+
const separator = windows ? ";" : delimiter;
|
|
278
|
+
const isBin = (dir: string) => (windows ? dir.toLowerCase() === binDir?.toLowerCase() : dir === binDir);
|
|
279
|
+
const withoutBin = (path: string) =>
|
|
280
|
+
path
|
|
281
|
+
.split(separator)
|
|
282
|
+
.filter((dir) => dir && !isBin(dir))
|
|
283
|
+
.join(separator);
|
|
284
|
+
const inherited = withoutBin(envValue(env, "PATH", platform) ?? "");
|
|
285
|
+
const readUserPath = async () => {
|
|
286
|
+
if (windows) return inherited;
|
|
287
|
+
const told = await loginShellPath(
|
|
288
|
+
{ ...env, PATH: inherited },
|
|
289
|
+
{ shell: options.shell, timeout: options.probeTimeout },
|
|
290
|
+
);
|
|
291
|
+
if (told !== null) return withoutBin(told);
|
|
292
|
+
const known = inherited.split(separator);
|
|
293
|
+
return [...known, ...usualToolDirs(env.HOME).filter((dir) => !known.includes(dir))].filter(Boolean).join(separator);
|
|
294
|
+
};
|
|
295
|
+
let user: Promise<string> | undefined;
|
|
296
|
+
const userPath = () => (user ??= readUserPath());
|
|
297
|
+
const resolveIn = (name: string, path: string) =>
|
|
298
|
+
findCommand(name, [...(binDir ? [binDir] : []), ...path.split(separator)], {
|
|
299
|
+
platform,
|
|
300
|
+
pathExt: envValue(env, "PATHEXT", platform),
|
|
301
|
+
});
|
|
302
|
+
const reaper = windows ? null : createReaper(grace);
|
|
303
|
+
|
|
304
|
+
const spawn = async (cmd: string[], spawnOptions: DesktopSpawnOptions = {}): Promise<DesktopProcess> => {
|
|
305
|
+
const [name, ...args] = cmd;
|
|
306
|
+
if (typeof name !== "string" || !name) throw new AkanNativeError("INVALID_ARGS", "spawn needs a command to run");
|
|
307
|
+
const childEnv = spawnOptions.env ?? {
|
|
308
|
+
...Object.fromEntries(Object.entries(env).filter(([key]) => key.toUpperCase() !== "PATH")),
|
|
309
|
+
PATH: [binDir, await userPath()].filter(Boolean).join(separator),
|
|
310
|
+
};
|
|
311
|
+
const found = resolveIn(name, envValue(childEnv, "PATH", platform) ?? "");
|
|
312
|
+
if (!found)
|
|
313
|
+
throw new AkanNativeError(
|
|
314
|
+
"NOT_FOUND",
|
|
315
|
+
`${name} is not in the app's bin folder nor on the PATH it would run with`,
|
|
316
|
+
);
|
|
317
|
+
const proc = Bun.spawn(
|
|
318
|
+
found.shell
|
|
319
|
+
? [envValue(env, "ComSpec", platform) || "cmd.exe", "/d", "/s", "/c", batchCommandLine(found.path, args)]
|
|
320
|
+
: [found.path, ...args],
|
|
321
|
+
{
|
|
322
|
+
cwd: spawnOptions.cwd,
|
|
323
|
+
env: childEnv,
|
|
324
|
+
stdin: spawnOptions.stdin ?? "ignore",
|
|
325
|
+
stdout: "pipe",
|
|
326
|
+
stderr: "pipe",
|
|
327
|
+
windowsHide: true,
|
|
328
|
+
windowsVerbatimArguments: found.shell,
|
|
329
|
+
|
|
330
|
+
detached: !windows,
|
|
331
|
+
},
|
|
332
|
+
);
|
|
333
|
+
const { pid } = proc;
|
|
334
|
+
const kill = (signal: NodeJS.Signals = "SIGTERM") => {
|
|
335
|
+
if (!windows) return endGroup(pid, signal);
|
|
336
|
+
try {
|
|
337
|
+
const taskkill = join(envValue(env, "SystemRoot", platform) ?? "C:\\Windows", "System32", "taskkill.exe");
|
|
338
|
+
Bun.spawn([taskkill, "/pid", String(pid), "/t", "/f"], { stdio: ["ignore", "ignore", "ignore"] });
|
|
339
|
+
} catch {
|
|
340
|
+
proc.kill();
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
let late: ReturnType<typeof setTimeout> | undefined;
|
|
344
|
+
const forget = spawnOptions.document?.own(() => {
|
|
345
|
+
kill("SIGTERM");
|
|
346
|
+
late = setTimeout(() => kill("SIGKILL"), grace);
|
|
347
|
+
});
|
|
348
|
+
reaper?.add(pid);
|
|
349
|
+
void proc.exited.then(() => {
|
|
350
|
+
clearTimeout(late);
|
|
351
|
+
forget?.();
|
|
352
|
+
if (!reaper) return;
|
|
353
|
+
endGroup(pid, "SIGKILL");
|
|
354
|
+
reaper.drop(pid);
|
|
355
|
+
});
|
|
356
|
+
const { onLine } = spawnOptions;
|
|
357
|
+
if (onLine) {
|
|
358
|
+
const failed = (error: unknown) => console.error(`[akan-native] reading ${name}'s output failed`, error);
|
|
359
|
+
pipeLines(proc.stdout, (line) => onLine(line, "stdout")).catch(failed);
|
|
360
|
+
pipeLines(proc.stderr, (line) => onLine(line, "stderr")).catch(failed);
|
|
361
|
+
}
|
|
362
|
+
const sink = typeof proc.stdin === "object" ? proc.stdin : null;
|
|
363
|
+
return {
|
|
364
|
+
pid,
|
|
365
|
+
exited: proc.exited,
|
|
366
|
+
stdin: sink && {
|
|
367
|
+
write(chunk) {
|
|
368
|
+
sink.write(chunk);
|
|
369
|
+
sink.flush();
|
|
370
|
+
},
|
|
371
|
+
end: () => void sink.end(),
|
|
372
|
+
},
|
|
373
|
+
stdout: onLine ? null : proc.stdout,
|
|
374
|
+
stderr: onLine ? null : proc.stderr,
|
|
375
|
+
kill,
|
|
376
|
+
};
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
return { userPath, resolveCommand: async (name) => resolveIn(name, await userPath()), spawn };
|
|
380
|
+
}
|
|
@@ -26,11 +26,15 @@ export function desktopExec(exe: string): string {
|
|
|
26
26
|
return `"${exe.replace(/[\\"`$]/g, (c) => `\\${c}`)}" %u`;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
+
/** What marks the launcher entry install.sh wrote (packages/cli/src/platforms/linux-install.ts). */
|
|
30
|
+
export const INSTALLED_MARKER = "X-AkanNative-Installed=true";
|
|
31
|
+
|
|
32
|
+
/** `categories`: the entry is install.sh's launcher entry, and stays one with these Categories. */
|
|
29
33
|
export function desktopEntry(
|
|
30
34
|
name: string,
|
|
31
35
|
exe: string,
|
|
32
36
|
schemes: readonly string[],
|
|
33
|
-
{ id, icon = false }: { id?: string; icon?: boolean } = {},
|
|
37
|
+
{ id, icon = false, categories }: { id?: string; icon?: boolean; categories?: string } = {},
|
|
34
38
|
): string {
|
|
35
39
|
return [
|
|
36
40
|
"[Desktop Entry]",
|
|
@@ -41,12 +45,21 @@ export function desktopEntry(
|
|
|
41
45
|
...(id ? [`StartupWMClass=${id}`] : []),
|
|
42
46
|
"Terminal=false",
|
|
43
47
|
|
|
44
|
-
"NoDisplay=true",
|
|
48
|
+
...(categories === undefined ? ["NoDisplay=true"] : [`Categories=${categories}`]),
|
|
45
49
|
`MimeType=${schemes.map((s) => `x-scheme-handler/${s};`).join("")}`,
|
|
50
|
+
...(categories === undefined ? [] : [INSTALLED_MARKER]),
|
|
46
51
|
"",
|
|
47
52
|
].join("\n");
|
|
48
53
|
}
|
|
49
54
|
|
|
55
|
+
/** The Categories of the entry at `path` when install.sh made it; undefined for any other entry, or none. */
|
|
56
|
+
function launcherCategories(path: string): string | undefined {
|
|
57
|
+
if (!existsSync(path)) return undefined;
|
|
58
|
+
const lines = readFileSync(path, "utf8").split(/\r?\n/);
|
|
59
|
+
if (!lines.includes(INSTALLED_MARKER)) return undefined;
|
|
60
|
+
return lines.find((line) => line.startsWith("Categories="))?.slice("Categories=".length) ?? "Utility;";
|
|
61
|
+
}
|
|
62
|
+
|
|
50
63
|
/** mimeapps.list with `x-scheme-handler/<scheme>=<desktop file>` set in [Default Applications]. */
|
|
51
64
|
export function withDefaults(list: string, desktopFile: string, schemes: readonly string[]): string {
|
|
52
65
|
const lines = list.split("\n");
|
|
@@ -97,7 +110,11 @@ async function registerLinux(
|
|
|
97
110
|
const file = `${app.id}.desktop`;
|
|
98
111
|
const dataHome = xdg(env.XDG_DATA_HOME, join(home, ".local", "share"));
|
|
99
112
|
const applications = join(dataHome, "applications");
|
|
100
|
-
const entry = desktopEntry(app.name, exe, schemes, {
|
|
113
|
+
const entry = desktopEntry(app.name, exe, schemes, {
|
|
114
|
+
id: app.id,
|
|
115
|
+
icon: installIcon(dataHome, app.id, icon),
|
|
116
|
+
categories: launcherCategories(join(applications, file)),
|
|
117
|
+
});
|
|
101
118
|
const entryChanged = writeIfChanged(join(applications, file), entry);
|
|
102
119
|
const listPath = join(xdg(env.XDG_CONFIG_HOME, join(home, ".config")), "mimeapps.list");
|
|
103
120
|
const list = existsSync(listPath) ? readFileSync(listPath, "utf8") : "";
|
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
UNLISTEN,
|
|
19
19
|
validateRequest,
|
|
20
20
|
} from "../../core/src/protocol.ts";
|
|
21
|
+
import { createCommands, type DesktopCommands } from "./commands.ts";
|
|
21
22
|
import type { Lifecycle } from "./lifecycle.ts";
|
|
22
23
|
import type {
|
|
23
24
|
DesktopContext,
|
|
@@ -53,6 +54,8 @@ export interface HostServices {
|
|
|
53
54
|
appLocalDataDir?: string;
|
|
54
55
|
/** desktop.bin in the app's resources, or null. */
|
|
55
56
|
binDir?: string | null;
|
|
57
|
+
/** ctx.userPath, resolveCommand and spawn; made for `binDir` when not given. */
|
|
58
|
+
commands?: DesktopCommands;
|
|
56
59
|
/** The carried server (resources/server.json), or null. */
|
|
57
60
|
server?: DesktopServerStatus | null;
|
|
58
61
|
/** Sends an event (numbered for its document) to a window's page. */
|
|
@@ -206,6 +209,24 @@ export interface DispatcherOptions {
|
|
|
206
209
|
declarations?: Record<string, unknown>;
|
|
207
210
|
}
|
|
208
211
|
|
|
212
|
+
/** ctx.appDataDir and ctx.appLocalDataDir, each made at its first read. */
|
|
213
|
+
function dataDirs(services: HostServices): Pick<DesktopContext, "appDataDir" | "appLocalDataDir"> {
|
|
214
|
+
const made = new Set<string>();
|
|
215
|
+
const ensured = (dir: string) => {
|
|
216
|
+
if (!made.has(dir)) mkdirSync(dir, { recursive: true });
|
|
217
|
+
made.add(dir);
|
|
218
|
+
return dir;
|
|
219
|
+
};
|
|
220
|
+
return {
|
|
221
|
+
get appDataDir() {
|
|
222
|
+
return ensured(services.appDataDir);
|
|
223
|
+
},
|
|
224
|
+
get appLocalDataDir() {
|
|
225
|
+
return ensured(services.appLocalDataDir ?? services.appDataDir);
|
|
226
|
+
},
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
209
230
|
/** Only the plugin's own members: "constructor" or "toString" must not reach Object.prototype. */
|
|
210
231
|
function own<T>(record: Record<string, T> | undefined, key: string): T | undefined {
|
|
211
232
|
return record && Object.hasOwn(record, key) ? record[key] : undefined;
|
|
@@ -217,8 +238,8 @@ export function createDispatcher(
|
|
|
217
238
|
options: DispatcherOptions = {},
|
|
218
239
|
): Dispatcher {
|
|
219
240
|
const byId = new Map(plugins.map((p) => [p.id, p]));
|
|
220
|
-
|
|
221
|
-
|
|
241
|
+
const dirs = dataDirs(services);
|
|
242
|
+
const commands = services.commands ?? createCommands({ binDir: services.binDir ?? null });
|
|
222
243
|
const launch: Launch = { window: {} };
|
|
223
244
|
let launching = true;
|
|
224
245
|
const duringLaunch = (plugin: DesktopPlugin, what: string, apply: () => void) => {
|
|
@@ -234,21 +255,15 @@ export function createDispatcher(
|
|
|
234
255
|
app: services.app,
|
|
235
256
|
dev: services.dev === true,
|
|
236
257
|
get appDataDir() {
|
|
237
|
-
|
|
238
|
-
mkdirSync(services.appDataDir, { recursive: true });
|
|
239
|
-
dataDirReady = true;
|
|
240
|
-
}
|
|
241
|
-
return services.appDataDir;
|
|
258
|
+
return dirs.appDataDir;
|
|
242
259
|
},
|
|
243
260
|
get appLocalDataDir() {
|
|
244
|
-
|
|
245
|
-
if (!localDataDirReady) {
|
|
246
|
-
mkdirSync(dir, { recursive: true });
|
|
247
|
-
localDataDirReady = true;
|
|
248
|
-
}
|
|
249
|
-
return dir;
|
|
261
|
+
return dirs.appLocalDataDir;
|
|
250
262
|
},
|
|
251
263
|
binDir: services.binDir ?? null,
|
|
264
|
+
userPath: commands.userPath,
|
|
265
|
+
resolveCommand: commands.resolveCommand,
|
|
266
|
+
spawn: commands.spawn,
|
|
252
267
|
server: services.server ?? null,
|
|
253
268
|
emit: (event, data, target) => deliver(plugin.id, event, data, target),
|
|
254
269
|
registerFile: (path, mime) => services.registerFile(path, mime),
|
|
@@ -8,22 +8,16 @@ import { ID_FILE_REF } from "../../core/src/contract.ts";
|
|
|
8
8
|
import type { AppInfo, ErrorCode } from "../../core/src/index.ts";
|
|
9
9
|
import { AkanNativeError, aclCheck, loadAcl } from "../../core/src/index.ts";
|
|
10
10
|
import { CONSOLE_PLUGIN, ERROR_CODES, errorResponse, HOST_PLUGIN } from "../../core/src/protocol.ts";
|
|
11
|
+
import { appBinFirst, createCommands } from "./commands.ts";
|
|
11
12
|
import { linkArguments, registerDeepLinks } from "./deeplinks.ts";
|
|
12
13
|
import { createDispatcher } from "./dispatcher.ts";
|
|
13
14
|
import { cstr, FRAME_EVENT, FRAME_HEADER, FRAME_IPC, openNative, resolvePaths } from "./ffi.ts";
|
|
14
|
-
import { createLifecycle } from "./lifecycle.ts";
|
|
15
|
+
import { appWindows, createLifecycle } from "./lifecycle.ts";
|
|
15
16
|
import { appDataDir, appLocalDataDir, reservedDirs, serverDataDir } from "./paths.ts";
|
|
16
17
|
import { type DesktopPlugin, useShellOpenLimit } from "./plugin.ts";
|
|
17
18
|
import { appLauncher, nextRelaunchDelay, relaunchAfterExit } from "./relaunch.ts";
|
|
18
19
|
import { createSecretStore } from "./secretStore.ts";
|
|
19
|
-
import {
|
|
20
|
-
createDesktopServer,
|
|
21
|
-
createServerStatus,
|
|
22
|
-
envValue,
|
|
23
|
-
pathWithFirst,
|
|
24
|
-
readServerManifest,
|
|
25
|
-
type ServerManifest,
|
|
26
|
-
} from "./server.ts";
|
|
20
|
+
import { createDesktopServer, createServerStatus, readServerManifest, type ServerManifest } from "./server.ts";
|
|
27
21
|
|
|
28
22
|
declare const self: Worker;
|
|
29
23
|
|
|
@@ -110,14 +104,7 @@ export function createShellCalls(send: (id: number, json: string) => void, deadl
|
|
|
110
104
|
|
|
111
105
|
export function startHost(plugins: DesktopPlugin[]): void {
|
|
112
106
|
const paths = resolvePaths();
|
|
113
|
-
|
|
114
|
-
const binDir = existsSync(join(paths.resources, "bin")) ? join(paths.resources, "bin") : null;
|
|
115
|
-
if (binDir) {
|
|
116
|
-
|
|
117
|
-
const path = envValue(process.env, "PATH");
|
|
118
|
-
for (const name of Object.keys(process.env)) if (name.toUpperCase() === "PATH") delete process.env[name];
|
|
119
|
-
process.env.PATH = pathWithFirst(binDir, path);
|
|
120
|
-
}
|
|
107
|
+
const binDir = appBinFirst(paths.resources);
|
|
121
108
|
const lib = openNative(paths.lib);
|
|
122
109
|
const native = lib.symbols;
|
|
123
110
|
|
|
@@ -182,7 +169,7 @@ export function startHost(plugins: DesktopPlugin[]): void {
|
|
|
182
169
|
cancelSessionEnd: () => native.akan_native_quit_cancel(),
|
|
183
170
|
hideWindow: (window) => shell("window.hide", { window }),
|
|
184
171
|
destroyWindow: (window) => shell("window.destroy", { window }),
|
|
185
|
-
windows: async () => ((await shell("window.list")) as { id: number }[])
|
|
172
|
+
windows: async () => appWindows((await shell("window.list")) as { id: number; auxiliary?: boolean }[]),
|
|
186
173
|
});
|
|
187
174
|
|
|
188
175
|
const reserved = reservedDirs(boot.app.id);
|
|
@@ -203,6 +190,7 @@ export function startHost(plugins: DesktopPlugin[]): void {
|
|
|
203
190
|
appDataDir: appDataDir(boot.app.id),
|
|
204
191
|
appLocalDataDir: appLocalDataDir(boot.app.id),
|
|
205
192
|
binDir,
|
|
193
|
+
commands: createCommands({ binDir }),
|
|
206
194
|
server: serverStatus?.status ?? null,
|
|
207
195
|
emit(window, message) {
|
|
208
196
|
emitJs(window, `window.__AKAN_NATIVE__&&window.__AKAN_NATIVE__.receive(${JSON.stringify(message)})`);
|
|
@@ -16,7 +16,10 @@ export interface LifecycleOptions {
|
|
|
16
16
|
hideWindow(window: number): Promise<unknown>;
|
|
17
17
|
/** Destroys a window that is not the last one. */
|
|
18
18
|
destroyWindow?(window: number): Promise<unknown>;
|
|
19
|
-
/**
|
|
19
|
+
/**
|
|
20
|
+
* The app's windows, hidden ones included and auxiliary ones left out: a companion window does not keep the app from
|
|
21
|
+
* quitting or hiding with its last window. Default: only the one being closed.
|
|
22
|
+
*/
|
|
20
23
|
windows?(): Promise<number[]>;
|
|
21
24
|
/** How long quit() waits for the onQuit hooks, all together. Default QUIT_HOOK_TIMEOUT. */
|
|
22
25
|
quitHookTimeout?: number;
|
|
@@ -41,6 +44,10 @@ export interface Lifecycle {
|
|
|
41
44
|
|
|
42
45
|
export const QUIT_HOOK_TIMEOUT = 2000;
|
|
43
46
|
|
|
47
|
+
export function appWindows(list: { id: number; auxiliary?: boolean }[]): number[] {
|
|
48
|
+
return list.filter((w) => !w.auxiliary).map((w) => w.id);
|
|
49
|
+
}
|
|
50
|
+
|
|
44
51
|
async function allow<E>(vetoes: Set<Veto<E>>, event: E, what: string): Promise<boolean> {
|
|
45
52
|
for (const veto of [...vetoes]) {
|
|
46
53
|
try {
|
|
@@ -2,8 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
import { EXTERNAL_OPENS_PER_SECOND } from "../../core/src/contract.ts";
|
|
4
4
|
import type { AppInfo, CallScope, FileRef } from "../../core/src/index.ts";
|
|
5
|
+
import type { DesktopProcess, DesktopSpawnOptions, ResolvedCommand } from "./commands.ts";
|
|
5
6
|
import type { QuitReason, Veto } from "./lifecycle.ts";
|
|
6
7
|
|
|
8
|
+
export type { DesktopProcess, DesktopProcessInput, DesktopSpawnOptions, ResolvedCommand } from "./commands.ts";
|
|
7
9
|
export type { QuitReason, Veto } from "./lifecycle.ts";
|
|
8
10
|
export { createPageVeto, type PageVeto } from "./page-veto.ts";
|
|
9
11
|
|
|
@@ -56,6 +58,25 @@ export interface DesktopContext {
|
|
|
56
58
|
* Bun.which without `env` reads the environment the app started with, so name a file here or pass the env.
|
|
57
59
|
*/
|
|
58
60
|
readonly binDir: string | null;
|
|
61
|
+
/**
|
|
62
|
+
* The PATH of the user's own shell, without the app's bin folder: an app started from the Finder or a launcher has
|
|
63
|
+
* only the session's. Read from the user's login shell at the first call and kept; that call takes as long as the
|
|
64
|
+
* shell's profile does (seconds, 10 at most), so a plugin that will need it asks in its setup without waiting. A
|
|
65
|
+
* shell that does not answer leaves the PATH the app started with, then the usual tool folders (Homebrew's,
|
|
66
|
+
* ~/.local/bin, ~/.bun/bin and the like). Windows: the PATH the app started with.
|
|
67
|
+
*/
|
|
68
|
+
userPath(): Promise<string>;
|
|
69
|
+
/**
|
|
70
|
+
* The file `name` runs: in the app's bin folder first, then on the user's PATH; null when it is in neither. Windows
|
|
71
|
+
* follows PATHEXT, and `shell` says the file is a `.cmd` or `.bat`.
|
|
72
|
+
*/
|
|
73
|
+
resolveCommand(name: string): Promise<ResolvedCommand | null>;
|
|
74
|
+
/**
|
|
75
|
+
* Starts a program the user installed (or one in binDir) as a child that ends with the app however the app ends, a
|
|
76
|
+
* crash or a kill included; with `document: ctx.document`, also when the calling page does. A bare name is looked up
|
|
77
|
+
* as resolveCommand does, on the PATH the child gets. Rejects NOT_FOUND when there is no such program.
|
|
78
|
+
*/
|
|
79
|
+
spawn(cmd: string[], options?: DesktopSpawnOptions): Promise<DesktopProcess>;
|
|
59
80
|
/**
|
|
60
81
|
* The server the app carries (desktop.server), or null. `ready` settles once per session: true when the server
|
|
61
82
|
* first answered ready, false when it could not start or gave up before that; `state` and `onState` follow it after.
|
|
@@ -394,7 +394,7 @@ export function lastPort(dataDir: string): number | undefined {
|
|
|
394
394
|
}
|
|
395
395
|
}
|
|
396
396
|
|
|
397
|
-
const pipeLines = async (stream: ReadableStream<Uint8Array>, onLine: (line: string) => void) => {
|
|
397
|
+
export const pipeLines = async (stream: ReadableStream<Uint8Array>, onLine: (line: string) => void) => {
|
|
398
398
|
const decoder = new TextDecoder();
|
|
399
399
|
let pending = "";
|
|
400
400
|
for await (const chunk of stream) {
|