@skathi-native/cli 0.0.0-stage → 0.1.0-beta.1

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/cli/create.ts ADDED
@@ -0,0 +1,411 @@
1
+ // `sk create [dir]`: a new app. In a terminal it asks for what the flags do not say: the directory, the
2
+ // name, the OSes to package for, the engine parts, whether published builds keep devtools, vue-router
3
+ // and pinia, and the package manager. `--yes` (or no terminal) takes the defaults.
4
+ //
5
+ // It writes package.json (the app root the builders resolve npm dependencies from), sk.config.json,
6
+ // src/, assets/, a generated 256² icon.png and a tsconfig.json that type-checks against the runtime.
7
+ // Nothing is overwritten: an existing file is an error, not a merge.
8
+
9
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
10
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
11
+ import * as p from "@clack/prompts";
12
+ import { RUNTIME_DIR, RUNTIME_SRC_DIR, runtimeRequire } from "../runtime-path";
13
+ import { ConfigError, OPTIONAL, parseParts, sanitizeExeName, type Part } from "./config";
14
+ import { encodePng } from "./icon";
15
+ import { currentPlatform, parsePlatform, type Platform } from "./platform";
16
+ import { colorEnabled, paint } from "./term";
17
+
18
+ export const PACKAGE_MANAGERS = ["bun", "npm", "pnpm", "yarn"] as const;
19
+ export type PackageManager = (typeof PACKAGE_MANAGERS)[number];
20
+
21
+ export interface CreateOptions {
22
+ name?: string | undefined;
23
+ platforms?: Platform[] | undefined;
24
+ /** Engine parts left out of every build; devtools is {@link CreateOptions.keepDevtools}'s. */
25
+ without?: Part[] | undefined;
26
+ /** Whether `sk publish` keeps devtools (`sk build` always has them). */
27
+ keepDevtools?: boolean | undefined;
28
+ router?: boolean | undefined;
29
+ packageManager?: PackageManager | undefined;
30
+ }
31
+
32
+ const ENGINE_PARTS: { value: Exclude<Part, "devtools">; label: string; hint: string }[] = [
33
+ { value: "audio", label: "Audio", hint: "Web Audio, <audio>, sound from <video>" },
34
+ { value: "clipboard", label: "Clipboard", hint: "navigator.clipboard" },
35
+ { value: "storages", label: "Storage on disk", hint: "localStorage and IndexedDB that survive a restart" },
36
+ { value: "indexeddb", label: "IndexedDB", hint: "indexedDB" },
37
+ { value: "webgpu", label: "WebGPU", hint: "navigator.gpu" },
38
+ ];
39
+
40
+ /** The package manager this was started from (`npm_config_user_agent`), else bun. */
41
+ export function detectPackageManager(agent = process.env.npm_config_user_agent ?? ""): PackageManager {
42
+ return PACKAGE_MANAGERS.find((pm) => agent.startsWith(`${pm}/`)) ?? "bun";
43
+ }
44
+
45
+ export const runScript = (pm: PackageManager, script: string) =>
46
+ pm === "npm" || pm === "bun" ? `${pm} run ${script}` : `${pm} ${script}`;
47
+
48
+ function icon(): Uint8Array {
49
+ const size = 256;
50
+ const data = new Uint8Array(size * size * 4);
51
+ const r = 56;
52
+ for (let y = 0; y < size; y++) {
53
+ for (let x = 0; x < size; x++) {
54
+ const dx = Math.max(0, Math.abs(x - 127.5) - (128 - r));
55
+ const dy = Math.max(0, Math.abs(y - 127.5) - (128 - r));
56
+ const inside = dx * dx + dy * dy <= r * r;
57
+ const t = (x + y) / (2 * size);
58
+ const o = (y * size + x) * 4;
59
+ data[o] = Math.round(0x42 + (0x2f - 0x42) * t);
60
+ data[o + 1] = Math.round(0xb8 + (0x6f - 0xb8) * t);
61
+ data[o + 2] = Math.round(0x83 + (0xd8 - 0x83) * t);
62
+ data[o + 3] = inside ? 255 : 0;
63
+ }
64
+ }
65
+ return encodePng({ width: size, height: size, data });
66
+ }
67
+
68
+ const json = (v: unknown) => JSON.stringify(v, null, 2) + "\n";
69
+
70
+ const STYLE = `
71
+ .root {
72
+ display: flex;
73
+ flex-direction: column;
74
+ gap: 12px;
75
+ padding: 24px;
76
+ color: white;
77
+ }
78
+ .title {
79
+ font-size: 22px;
80
+ font-weight: 600;
81
+ }
82
+ .btn {
83
+ align-self: flex-start;
84
+ padding: 6px 14px;
85
+ border-radius: 8px;
86
+ background: #ffffff22;
87
+ }`;
88
+
89
+ function sources(productName: string, router: boolean): Record<string, string> {
90
+ if (!router) {
91
+ return {
92
+ "src/main.ts": `import { createApp } from "vue";
93
+ import App from "./App.vue";
94
+
95
+ createApp(App).mount();
96
+ `,
97
+ "src/App.vue": `<script setup lang="ts">
98
+ import { onMounted, ref } from "vue";
99
+
100
+ const count = ref(0);
101
+ // A relative URL resolves against the app root in dev and against the payload once packaged.
102
+ const greeting = ref("…");
103
+ onMounted(async () => {
104
+ const res = await fetch?.("assets/hello.txt");
105
+ const text = res?.ok ? await res.text?.() : undefined;
106
+ greeting.value = text?.trim() ?? "assets/hello.txt did not load";
107
+ });
108
+ </script>
109
+
110
+ <template>
111
+ <div class="root">
112
+ <div class="title">${productName}</div>
113
+ <div class="line">{{ greeting }}</div>
114
+ <div class="btn" @click="count++">clicked {{ count }}×</div>
115
+ </div>
116
+ </template>
117
+
118
+ <style scoped>${STYLE}
119
+ </style>
120
+ `,
121
+ };
122
+ }
123
+ return {
124
+ "src/main.ts": `import { createApp } from "vue";
125
+ import { createPinia } from "pinia";
126
+ import App from "./App.vue";
127
+ import { router } from "./router";
128
+
129
+ createApp(App).use(createPinia()).use(router).mount();
130
+ `,
131
+ "src/router.ts": `import { createMemoryHistory, createRouter } from "vue-router";
132
+ import Home from "./views/Home.vue";
133
+ import About from "./views/About.vue";
134
+
135
+ export const router = createRouter({
136
+ history: createMemoryHistory(),
137
+ routes: [
138
+ { path: "/", component: Home },
139
+ { path: "/about", component: About },
140
+ ],
141
+ });
142
+ `,
143
+ "src/stores/counter.ts": `import { defineStore } from "pinia";
144
+ import { ref } from "vue";
145
+
146
+ export const useCounter = defineStore("counter", () => {
147
+ const count = ref(0);
148
+ const increment = () => count.value++;
149
+ return { count, increment };
150
+ });
151
+ `,
152
+ "src/App.vue": `<template>
153
+ <div class="root">
154
+ <div class="title">${productName}</div>
155
+ <div class="nav">
156
+ <RouterLink class="btn" to="/">Home</RouterLink>
157
+ <RouterLink class="btn" to="/about">About</RouterLink>
158
+ </div>
159
+ <RouterView />
160
+ </div>
161
+ </template>
162
+
163
+ <style scoped>${STYLE}
164
+ .nav {
165
+ display: flex;
166
+ gap: 8px;
167
+ }
168
+ </style>
169
+ `,
170
+ "src/views/Home.vue": `<script setup lang="ts">
171
+ import { onMounted, ref } from "vue";
172
+ import { useCounter } from "../stores/counter";
173
+
174
+ const counter = useCounter();
175
+ // A relative URL resolves against the app root in dev and against the payload once packaged.
176
+ const greeting = ref("…");
177
+ onMounted(async () => {
178
+ const res = await fetch?.("assets/hello.txt");
179
+ const text = res?.ok ? await res.text?.() : undefined;
180
+ greeting.value = text?.trim() ?? "assets/hello.txt did not load";
181
+ });
182
+ </script>
183
+
184
+ <template>
185
+ <div>{{ greeting }}</div>
186
+ <div class="btn" @click="counter.increment()">clicked {{ counter.count }}×</div>
187
+ </template>
188
+
189
+ <style scoped>
190
+ .btn {
191
+ align-self: flex-start;
192
+ padding: 6px 14px;
193
+ border-radius: 8px;
194
+ background: #ffffff22;
195
+ }
196
+ </style>
197
+ `,
198
+ "src/views/About.vue": `<script setup lang="ts">
199
+ import { useCounter } from "../stores/counter";
200
+
201
+ const counter = useCounter();
202
+ </script>
203
+
204
+ <template>
205
+ <div>The counter lives in a pinia store: {{ counter.count }}, here too.</div>
206
+ </template>
207
+ `,
208
+ };
209
+ }
210
+
211
+ /** Writes the app; every option has a default. Returns the files written. */
212
+ export function create(target: string, options: CreateOptions = {}): string[] {
213
+ const dir = resolve(target);
214
+ const name = (options.name ?? basename(dir)).trim();
215
+ if (!name) throw new ConfigError("sk create: the app needs a name");
216
+ const productName = name
217
+ .replace(/(^|[-_.\s])(\w)/g, (_, sep: string, c: string) => (sep ? " " : "") + c.toUpperCase())
218
+ .trim();
219
+ const exeName = sanitizeExeName(productName) || "App";
220
+ const slug =
221
+ name
222
+ .toLowerCase()
223
+ .replace(/[^a-z0-9]+/g, "-")
224
+ .replace(/^-|-$/g, "") || "app";
225
+ const platforms = options.platforms?.length ? options.platforms : [currentPlatform()];
226
+ const without: Part[] = OPTIONAL.filter((part) =>
227
+ part === "devtools" ? !options.keepDevtools : (options.without ?? []).includes(part),
228
+ );
229
+ const rel = (to: string) => relative(dir, to).split(sep).join("/");
230
+ const runtime = rel(RUNTIME_SRC_DIR);
231
+ const pkg = (name: string) => rel(dirname(runtimeRequire.resolve(`${name}/package.json`)));
232
+
233
+ const files: Record<string, string | Uint8Array> = {
234
+ "package.json": json({
235
+ name: slug,
236
+ version: "0.1.0",
237
+ private: true,
238
+ type: "module",
239
+ scripts: { dev: "sk dev", build: "sk build", publish: "sk publish" },
240
+ }),
241
+ "sk.config.json": json({
242
+ name,
243
+ productName,
244
+ version: "0.1.0",
245
+ platforms,
246
+ window: { title: productName, width: 900, height: 640, backdrop: "mica" },
247
+ assets: ["assets"],
248
+ windows: { exeName, icon: "icon.png", without },
249
+ ...(platforms.includes("macos") ? { macos: { bundleId: `com.example.${slug}` } } : {}),
250
+ }),
251
+ ...sources(productName, options.router ?? false),
252
+ "assets/hello.txt": `hello from ${name}'s assets\n`,
253
+ "icon.png": icon(),
254
+ "tsconfig.json": json({
255
+ compilerOptions: {
256
+ target: "ESNext",
257
+ module: "ESNext",
258
+ moduleResolution: "bundler",
259
+ lib: ["ESNext"],
260
+ strict: true,
261
+ noEmit: true,
262
+ skipLibCheck: true,
263
+ useDefineForClassFields: false,
264
+ isolatedModules: true,
265
+ types: [],
266
+ baseUrl: ".",
267
+ paths: {
268
+ vue: [`${runtime}/runtime.ts`],
269
+ "@skathi-native/runtime": [`${runtime}/runtime.ts`],
270
+ "vue-router": [pkg("vue-router")],
271
+ pinia: [pkg("pinia")],
272
+ },
273
+ },
274
+ // Template types from the runtime: an installed `vue` package brings DOM typings the engine does not have.
275
+ vueCompilerOptions: { lib: "@skathi-native/runtime" },
276
+ include: [
277
+ `${runtime}/engine.d.ts`,
278
+ `${runtime}/protocol.d.ts`,
279
+ `${runtime}/indexeddb.d.ts`,
280
+ `${rel(RUNTIME_DIR)}/env.d.ts`,
281
+ "src/**/*.ts",
282
+ "src/**/*.vue",
283
+ ],
284
+ }),
285
+ };
286
+
287
+ for (const rel of Object.keys(files)) {
288
+ if (existsSync(join(dir, rel)))
289
+ throw new ConfigError(`sk create: ${join(dir, rel)} already exists — nothing was written`);
290
+ }
291
+ const written: string[] = [];
292
+ for (const [rel, body] of Object.entries(files)) {
293
+ const path = join(dir, rel);
294
+ mkdirSync(join(path, ".."), { recursive: true });
295
+ writeFileSync(path, body);
296
+ written.push(path);
297
+ }
298
+ return written;
299
+ }
300
+
301
+ export interface CreateFlags {
302
+ name?: string | undefined;
303
+ os?: string | undefined;
304
+ without?: string | undefined;
305
+ devtools?: boolean | undefined;
306
+ router?: boolean | undefined;
307
+ pm?: string | undefined;
308
+ yes?: boolean | undefined;
309
+ }
310
+
311
+ function parsePm(v: string): PackageManager {
312
+ const pm = PACKAGE_MANAGERS.find((m) => m === v.trim().toLowerCase());
313
+ if (!pm) throw new ConfigError(`--pm ${JSON.stringify(v)}: expected one of ${PACKAGE_MANAGERS.join(", ")}`);
314
+ return pm;
315
+ }
316
+
317
+ function answered<T>(value: T): Exclude<T, symbol> {
318
+ if (p.isCancel(value) || typeof value === "symbol") {
319
+ p.cancel("Nothing was created.");
320
+ process.exit(130);
321
+ }
322
+ return value as Exclude<T, symbol>;
323
+ }
324
+
325
+ /** `sk create`: the questions the flags leave open, then {@link create}. */
326
+ export async function createCommand(target: string | undefined, flags: CreateFlags): Promise<number> {
327
+ const ask = !flags.yes && process.stdin.isTTY === true && process.stdout.isTTY === true;
328
+ const options: CreateOptions = {
329
+ name: flags.name,
330
+ platforms: flags.os
331
+ ?.split(/[\s,]+/)
332
+ .filter(Boolean)
333
+ .map(parsePlatform),
334
+ without: flags.without !== undefined ? parseParts(flags.without, "--without") : undefined,
335
+ keepDevtools: flags.devtools,
336
+ router: flags.router,
337
+ packageManager: flags.pm !== undefined ? parsePm(flags.pm) : undefined,
338
+ };
339
+ let dir = target;
340
+
341
+ if (ask) {
342
+ p.intro("sk create");
343
+ dir ??= answered(
344
+ await p.text({
345
+ message: "Where should the app go?",
346
+ placeholder: "my-app",
347
+ defaultValue: "my-app",
348
+ validate: (v) =>
349
+ v && existsSync(join(resolve(v), "package.json")) ? `${v} already has a package.json` : undefined,
350
+ }),
351
+ );
352
+ options.name ??= answered(
353
+ await p.text({
354
+ message: "App name",
355
+ initialValue: basename(resolve(dir)),
356
+ validate: (v) => (v?.trim() ? undefined : "it needs a name"),
357
+ }),
358
+ );
359
+ options.platforms ??= answered(
360
+ await p.multiselect<Platform>({
361
+ message: "Package it for",
362
+ options: [
363
+ { value: "windows", label: "Windows" },
364
+ { value: "macos", label: "macOS" },
365
+ { value: "linux", label: "Linux" },
366
+ ],
367
+ initialValues: [currentPlatform()],
368
+ required: true,
369
+ }),
370
+ );
371
+ if (!options.without) {
372
+ const kept = answered(
373
+ await p.multiselect<Exclude<Part, "devtools">>({
374
+ message: "Engine parts (leaving one out makes the exe smaller)",
375
+ options: ENGINE_PARTS,
376
+ initialValues: ENGINE_PARTS.map((e) => e.value),
377
+ required: false,
378
+ }),
379
+ );
380
+ options.without = ENGINE_PARTS.map((e) => e.value).filter((v) => !kept.includes(v));
381
+ }
382
+ options.keepDevtools ??= answered(
383
+ await p.confirm({
384
+ message: "Keep devtools (F12) in published builds? sk build always has them",
385
+ initialValue: false,
386
+ }),
387
+ );
388
+ options.router ??= answered(await p.confirm({ message: "Add vue-router and pinia?", initialValue: true }));
389
+ options.packageManager ??= answered(
390
+ await p.select<PackageManager>({
391
+ message: "Package manager",
392
+ options: PACKAGE_MANAGERS.map((pm) => ({ value: pm, label: pm })),
393
+ initialValue: detectPackageManager(),
394
+ }),
395
+ );
396
+ }
397
+
398
+ dir ??= "my-app";
399
+ const pm = options.packageManager ?? detectPackageManager();
400
+ create(dir, options);
401
+ const where = relative(process.cwd(), resolve(dir)) || ".";
402
+ const next = [...(where === "." ? [] : [`cd ${where}`]), runScript(pm, "dev")].join("\n");
403
+ if (ask) {
404
+ p.note(next, "Next");
405
+ p.outro(`${options.name ?? basename(resolve(dir))} is ready`);
406
+ } else {
407
+ const c = paint(colorEnabled(process.stdout));
408
+ console.log(`${c.green("✓")} created ${c.cyan(resolve(dir))}\n ${c.dim("next:")} ${next.replace(/\n/g, " && ")}`);
409
+ }
410
+ return 0;
411
+ }
package/cli/dev.ts ADDED
@@ -0,0 +1,92 @@
1
+ // `sk dev [appDir]`: the dev loop for one app, as one command: `bun build.ts <entry>
2
+ // <appRoot>/dist/.sk-dev --watch` (HMR producer) plus a dev host (`SK_DIST=… SK_APP_ROOT=… <host>`).
3
+ //
4
+ // The dev host, first hit wins: `--exe` or SK_DEV_HOST; in a checkout, its debug sk-app (`cargo build
5
+ // -p sk-app`); the cached dev host of this version; a download of it from the release (host-fetch.ts).
6
+
7
+ import { spawn } from "node:child_process";
8
+ import { existsSync, mkdirSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { loadAppConfig } from "./config";
11
+ import { cachedHost, checkHost, DEV_HOST, HostError, hostInfo, PKG_DIR, REPO_ROOT, CLI_VERSION } from "./host";
12
+ import { fetchHost } from "./host-fetch";
13
+ import { currentPlatform, hostsFor, repoHostExe } from "./platform";
14
+ import { colorEnabled, paint, progressFor } from "./term";
15
+
16
+ export async function devHost(
17
+ options: { exe?: string | undefined; log?: (line: string) => void } = {},
18
+ ): Promise<string> {
19
+ const log = options.log ?? console.log;
20
+ const named = options.exe ?? process.env.SK_DEV_HOST;
21
+ if (named) {
22
+ if (!existsSync(named)) throw new HostError(`no dev host at ${named}`);
23
+ return named;
24
+ }
25
+ if (REPO_ROOT) {
26
+ const debug = repoHostExe(REPO_ROOT, hostsFor(currentPlatform()), "debug");
27
+ if (existsSync(debug)) return debug;
28
+ }
29
+ const cached = cachedHost(CLI_VERSION, DEV_HOST);
30
+ const usable = () => {
31
+ try {
32
+ return existsSync(cached) && !checkHost(cached, hostInfo(cached), DEV_HOST, false);
33
+ } catch {
34
+ return false;
35
+ }
36
+ };
37
+ if (!usable()) {
38
+ if (process.env.SK_HOST_OFFLINE === "1") {
39
+ throw new HostError(
40
+ `no dev host: ${cached} is missing or unusable and SK_HOST_OFFLINE=1 forbids a download — ` +
41
+ "pass --exe <dev host>" +
42
+ (REPO_ROOT
43
+ ? `, or build one with \`${["cargo build -p sk-app", ...hostsFor(currentPlatform()).cargoTarget].join(" ")}\``
44
+ : ""),
45
+ );
46
+ }
47
+ await fetchHost({ variant: DEV_HOST, log });
48
+ }
49
+ return cached;
50
+ }
51
+
52
+ export async function dev(target: string, options: { exe?: string | undefined } = {}): Promise<number> {
53
+ const config = loadAppConfig(target);
54
+ const c = paint(colorEnabled(process.stdout));
55
+ const progress = progressFor(process.stderr);
56
+ progress.step("dev host");
57
+ const exe = await devHost({ ...options, log: (line) => progress.detail(line) }).finally(() => progress.end());
58
+ const dist = join(config.appRoot, "dist", ".sk-dev");
59
+ mkdirSync(dist, { recursive: true });
60
+ const watcher = spawn(process.execPath, [join(PKG_DIR, "build.ts"), config.entry, dist, "--watch"], {
61
+ cwd: PKG_DIR,
62
+ stdio: "inherit",
63
+ env: { ...process.env, SK_OWNER_PID: String(process.pid) },
64
+ });
65
+ const deadline = Date.now() + 120_000;
66
+ while (!existsSync(join(dist, "manifest.json"))) {
67
+ if (watcher.exitCode !== null) throw new Error(`bun build.ts exited with ${watcher.exitCode}`);
68
+ if (Date.now() > deadline) throw new Error("bun build.ts produced no manifest within 2 minutes");
69
+ await Bun.sleep(100);
70
+ }
71
+ console.log(`${c.green("▶")} ${c.bold(config.name)} ${c.dim(`dist ${dist}, host ${exe}`)}`);
72
+ const host = spawn(exe, [], {
73
+ stdio: "inherit",
74
+ // SK_OWNER_PID: the host dies with this process however it ends (crates/sk-app/src/owner.rs).
75
+ env: { ...process.env, SK_DIST: dist, SK_APP_ROOT: config.appRoot, SK_OWNER_PID: String(process.pid) },
76
+ });
77
+ const stop = () => {
78
+ try {
79
+ watcher.kill();
80
+ } catch {}
81
+ try {
82
+ host.kill();
83
+ } catch {}
84
+ };
85
+ process.on("SIGINT", () => {
86
+ stop();
87
+ process.exit(130);
88
+ });
89
+ const code: number = await new Promise((done) => host.on("exit", (c) => done(c ?? 0)));
90
+ stop();
91
+ return code;
92
+ }
package/cli/elf.ts ADDED
@@ -0,0 +1,142 @@
1
+ // The Linux side of `sk build`: a copy of the host ELF with the payload appended.
2
+ //
3
+ // <exeName> = host | zero pad to a page | SKPK | u64 offset | u64 length | "SKPKTAIL"
4
+ //
5
+ // The host maps /proc/self/exe and finds the payload by that trailer (`sk_payload::appended`). The
6
+ // offset is page-aligned and the SKPK skewed for offset 0, so its data region lands on a page
7
+ // boundary of the mapping. The file is written as `<out>.partial`, made executable and renamed.
8
+
9
+ import {
10
+ chmodSync,
11
+ closeSync,
12
+ fstatSync,
13
+ openSync,
14
+ readFileSync,
15
+ readSync,
16
+ renameSync,
17
+ rmSync,
18
+ writeFileSync,
19
+ } from "node:fs";
20
+ import { PAGE, readHeader, skewFor } from "./skpk";
21
+
22
+ export const TRAILER_MAGIC = "SKPKTAIL";
23
+ export const TRAILER_SIZE = 24;
24
+
25
+ const MACHINE: Record<number, string> = { 0x3e: "x86_64", 0xb7: "aarch64" };
26
+
27
+ /** The CPU of a 64-bit little-endian ELF, or null when `head` is not one. */
28
+ export function elfMachine(head: Uint8Array): string | null {
29
+ if (head.length < 20 || head[0] !== 0x7f || head[1] !== 0x45 || head[2] !== 0x4c || head[3] !== 0x46) return null;
30
+ if (head[4] !== 2 || head[5] !== 1) return null;
31
+ const machine = head[18]! | (head[19]! << 8);
32
+ return MACHINE[machine] ?? `machine 0x${machine.toString(16)}`;
33
+ }
34
+
35
+ function readAt(path: string, at: (size: number) => { pos: number; len: number }): Uint8Array | null {
36
+ try {
37
+ const fd = openSync(path, "r");
38
+ try {
39
+ const { pos, len } = at(fstatSync(fd).size);
40
+ if (pos < 0 || len <= 0) return new Uint8Array(0);
41
+ const buf = new Uint8Array(len);
42
+ return buf.subarray(0, readSync(fd, buf, 0, len, pos));
43
+ } finally {
44
+ closeSync(fd);
45
+ }
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+
51
+ export function elfMachineOf(path: string): string | null {
52
+ const head = readAt(path, () => ({ pos: 0, len: 20 }));
53
+ return head && elfMachine(head);
54
+ }
55
+
56
+ export function trailer(offset: number, length: number): Uint8Array {
57
+ const t = new Uint8Array(TRAILER_SIZE);
58
+ const dv = new DataView(t.buffer);
59
+ dv.setBigUint64(0, BigInt(offset), true);
60
+ dv.setBigUint64(8, BigInt(length), true);
61
+ t.set(new TextEncoder().encode(TRAILER_MAGIC), 16);
62
+ return t;
63
+ }
64
+
65
+ /** Where the trailer at the end of `tail` says the payload is, in a file of `size` bytes; null without a valid one. */
66
+ export function appendedPayload(tail: Uint8Array, size: number): { offset: number; length: number } | null {
67
+ if (tail.length < TRAILER_SIZE || size < TRAILER_SIZE) return null;
68
+ const t = tail.subarray(tail.length - TRAILER_SIZE);
69
+ if (new TextDecoder().decode(t.subarray(16)) !== TRAILER_MAGIC) return null;
70
+ const dv = new DataView(t.buffer, t.byteOffset, TRAILER_SIZE);
71
+ const offset = Number(dv.getBigUint64(0, true));
72
+ const length = Number(dv.getBigUint64(8, true));
73
+ return offset + length === size - TRAILER_SIZE ? { offset, length } : null;
74
+ }
75
+
76
+ export function appendedPayloadOf(path: string): { offset: number; length: number } | null {
77
+ let size = 0;
78
+ const tail = readAt(path, (s) => {
79
+ size = s;
80
+ return { pos: s - TRAILER_SIZE, len: TRAILER_SIZE };
81
+ });
82
+ return tail && appendedPayload(tail, size);
83
+ }
84
+
85
+ export interface ElfStampOptions {
86
+ host: string;
87
+ out: string;
88
+ payload: (skew: number) => Uint8Array;
89
+ }
90
+
91
+ export interface ElfStampResult {
92
+ out: string;
93
+ bytes: number;
94
+ payloadBytes: number;
95
+ payloadOffset: number;
96
+ skew: number;
97
+ dataAligned: boolean;
98
+ machine: string;
99
+ ms: { total: number };
100
+ payload: Uint8Array;
101
+ }
102
+
103
+ export function stampElf(options: ElfStampOptions): ElfStampResult {
104
+ const t0 = performance.now();
105
+ const host = new Uint8Array(readFileSync(options.host));
106
+ const machine = elfMachine(host);
107
+ if (!machine) throw new Error(`${options.host} is not a 64-bit ELF executable — a Linux build needs a Linux sk-app`);
108
+ if (appendedPayload(host, host.length)) {
109
+ throw new Error(`${options.host} is a packaged app, not a bare host (it already carries a payload)`);
110
+ }
111
+ const offset = Math.ceil(host.length / PAGE) * PAGE;
112
+ const unskewed = options.payload(0);
113
+ const skew = skewFor(0, readHeader(unskewed));
114
+ const payload = skew ? options.payload(skew) : unskewed;
115
+ const header = readHeader(payload);
116
+ const file = new Uint8Array(offset + payload.length + TRAILER_SIZE);
117
+ file.set(host);
118
+ file.set(payload, offset);
119
+ file.set(trailer(offset, payload.length), offset + payload.length);
120
+
121
+ const partial = `${options.out}.partial`;
122
+ try {
123
+ writeFileSync(partial, file);
124
+ chmodSync(partial, 0o755);
125
+ rmSync(options.out, { force: true });
126
+ renameSync(partial, options.out);
127
+ } catch (e) {
128
+ rmSync(partial, { force: true });
129
+ throw new Error(`${options.out} cannot be written — is it running? (${(e as Error).message})`);
130
+ }
131
+ return {
132
+ out: options.out,
133
+ bytes: file.length,
134
+ payloadBytes: payload.length,
135
+ payloadOffset: offset,
136
+ skew,
137
+ dataAligned: (offset + header.dataOff) % PAGE === 0,
138
+ machine,
139
+ ms: { total: Math.round(performance.now() - t0) },
140
+ payload,
141
+ };
142
+ }