@skathi-native/cli 0.0.0 → 0.1.0-beta.2

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 (81) hide show
  1. package/aot-inputs.ts +294 -0
  2. package/ascii.ts +397 -0
  3. package/build.ts +1236 -0
  4. package/check/builtins.json +1219 -0
  5. package/check/builtins.ts +112 -0
  6. package/check/codes.ts +178 -0
  7. package/check/command.ts +105 -0
  8. package/check/config.ts +76 -0
  9. package/check/finding.ts +30 -0
  10. package/check/graph.ts +69 -0
  11. package/check/highlight.ts +40 -0
  12. package/check/index.ts +308 -0
  13. package/check/packages.ts +54 -0
  14. package/check/program.ts +209 -0
  15. package/check/report.ts +219 -0
  16. package/check/rules.ts +307 -0
  17. package/check/schema.ts +69 -0
  18. package/check/typing.ts +703 -0
  19. package/cli/assets.ts +114 -0
  20. package/cli/build-app.ts +587 -0
  21. package/cli/config.ts +646 -0
  22. package/cli/create.ts +327 -0
  23. package/cli/dev.ts +92 -0
  24. package/cli/elf.ts +142 -0
  25. package/cli/help.ts +160 -0
  26. package/cli/host-fetch.ts +178 -0
  27. package/cli/host.ts +378 -0
  28. package/cli/icon.ts +303 -0
  29. package/cli/macos-bundle.ts +451 -0
  30. package/cli/pe.ts +429 -0
  31. package/cli/platform.ts +74 -0
  32. package/cli/sk.ts +290 -0
  33. package/cli/skpk.ts +268 -0
  34. package/cli/stamp.ts +254 -0
  35. package/cli/term.ts +176 -0
  36. package/cli/versioninfo.ts +123 -0
  37. package/css-prefixes.ts +118 -0
  38. package/devtools/apps.ts +68 -0
  39. package/devtools/commands.ts +860 -0
  40. package/devtools/ctl.ts +166 -0
  41. package/package.json +52 -3
  42. package/prod.ts +701 -0
  43. package/runtime-path.ts +24 -0
  44. package/tailwind.ts +76 -0
  45. package/templates/minimal/assets/hello.txt +1 -0
  46. package/templates/minimal/src/App.vue +142 -0
  47. package/templates/minimal/src/main.ts +4 -0
  48. package/templates/showcase/assets/hello.txt +1 -0
  49. package/templates/showcase/assets/media/aurora.png +0 -0
  50. package/templates/showcase/assets/media/clip.mp4 +0 -0
  51. package/templates/showcase/assets/media/sticker.tgs +0 -0
  52. package/templates/showcase/src/App.vue +128 -0
  53. package/templates/showcase/src/components/Card.vue +41 -0
  54. package/templates/showcase/src/components/Icon.vue +29 -0
  55. package/templates/showcase/src/components/Missing.vue +26 -0
  56. package/templates/showcase/src/components/Page.vue +41 -0
  57. package/templates/showcase/src/components/Titlebar.vue +128 -0
  58. package/templates/showcase/src/engine.ts +33 -0
  59. package/templates/showcase/src/icons.ts +22 -0
  60. package/templates/showcase/src/main.ts +7 -0
  61. package/templates/showcase/src/pages/AudioPage.vue +124 -0
  62. package/templates/showcase/src/pages/FilesPage.vue +91 -0
  63. package/templates/showcase/src/pages/FormsPage.vue +139 -0
  64. package/templates/showcase/src/pages/GraphicsPage.vue +156 -0
  65. package/templates/showcase/src/pages/HomePage.vue +141 -0
  66. package/templates/showcase/src/pages/LocalePage.vue +71 -0
  67. package/templates/showcase/src/pages/MediaPage.vue +85 -0
  68. package/templates/showcase/src/pages/MotionPage.vue +199 -0
  69. package/templates/showcase/src/pages/NetworkPage.vue +103 -0
  70. package/templates/showcase/src/pages/PermissionsPage.vue +80 -0
  71. package/templates/showcase/src/pages/StoragePage.vue +117 -0
  72. package/templates/showcase/src/pages/StylesPage.vue +199 -0
  73. package/templates/showcase/src/pages/SystemPage.vue +89 -0
  74. package/templates/showcase/src/pages/TrayPage.vue +66 -0
  75. package/templates/showcase/src/pages/WindowPage.vue +128 -0
  76. package/templates/showcase/src/product.ts +2 -0
  77. package/templates/showcase/src/router.ts +149 -0
  78. package/templates/showcase/src/stores/counter.ts +9 -0
  79. package/templates/showcase/src/stores/desktop.ts +115 -0
  80. package/templates/showcase/src/styles.css +140 -0
  81. package/vitecompat.ts +1151 -0
package/cli/create.ts ADDED
@@ -0,0 +1,327 @@
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 template, the OSes to package for, the engine parts, whether published builds keep devtools,
3
+ // and the package manager. `--yes` (or no terminal) takes the defaults.
4
+ //
5
+ // It copies templates/<template>/ (src/, assets/) with the placeholders filled in, and writes
6
+ // package.json (the app root the builders resolve npm dependencies from), sk.config.json, a generated
7
+ // 256² icon.png and a tsconfig.json that type-checks against the runtime.
8
+ // Nothing is overwritten: an existing file is an error, not a merge.
9
+
10
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
11
+ import { basename, extname, join, relative, resolve } from "node:path";
12
+ import * as p from "@clack/prompts";
13
+ import { runtimeRequire } from "../runtime-path";
14
+ import { ConfigError, OPTIONAL, parseParts, sanitizeExeName, type Part } from "./config";
15
+ import { CLI_VERSION } from "./host";
16
+ import { encodePng } from "./icon";
17
+ import { currentPlatform, parsePlatform, type Platform } from "./platform";
18
+ import { colorEnabled, paint } from "./term";
19
+
20
+ export const PACKAGE_MANAGERS = ["bun", "npm", "pnpm", "yarn"] as const;
21
+ export type PackageManager = (typeof PACKAGE_MANAGERS)[number];
22
+
23
+ export const TEMPLATES = ["showcase", "minimal"] as const;
24
+ export type Template = (typeof TEMPLATES)[number];
25
+
26
+ interface TemplateInfo {
27
+ hint: string;
28
+ /** Taken at the versions the runtime itself depends on. */
29
+ dependencies: string[];
30
+ window: Record<string, unknown>;
31
+ packs?: { name: string; match?: string[] }[];
32
+ }
33
+
34
+ const TEMPLATE_INFO: Record<Template, TemplateInfo> = {
35
+ showcase: {
36
+ hint: "every Skathi feature, one page each",
37
+ dependencies: ["pinia", "vue-router"],
38
+ window: { width: 1100, height: 720, minWidth: 480, minHeight: 360, titleBarStyle: "hidden", titleBarHeight: 40 },
39
+ packs: [{ name: "media", match: ["assets/media/**"] }],
40
+ },
41
+ minimal: {
42
+ hint: "one window, one component",
43
+ dependencies: [],
44
+ window: { width: 760, height: 520, titleBarStyle: "default" },
45
+ },
46
+ };
47
+
48
+ export const TEMPLATES_DIR = resolve(import.meta.dir, "..", "templates");
49
+
50
+ /** Files whose text has its `{{key}}` placeholders filled in; anything else is copied byte for byte. */
51
+ const TEXT_FILES = new Set([".vue", ".ts", ".css", ".txt", ".json", ".html", ".svg"]);
52
+
53
+ export interface CreateOptions {
54
+ name?: string | undefined;
55
+ template?: Template | undefined;
56
+ platforms?: Platform[] | undefined;
57
+ /** Engine parts left out of every build; devtools is {@link CreateOptions.keepDevtools}'s. */
58
+ without?: Part[] | undefined;
59
+ /** Whether `sk publish` keeps devtools (`sk build` always has them). */
60
+ keepDevtools?: boolean | undefined;
61
+ packageManager?: PackageManager | undefined;
62
+ }
63
+
64
+ const ENGINE_PARTS: { value: Exclude<Part, "devtools">; label: string; hint: string }[] = [
65
+ { value: "audio", label: "Audio", hint: "Web Audio, <audio>, sound from <video>" },
66
+ { value: "clipboard", label: "Clipboard", hint: "navigator.clipboard" },
67
+ { value: "storages", label: "Storage on disk", hint: "localStorage and IndexedDB that survive a restart" },
68
+ { value: "indexeddb", label: "IndexedDB", hint: "indexedDB" },
69
+ { value: "webgpu", label: "WebGPU", hint: "navigator.gpu" },
70
+ ];
71
+
72
+ /** The package manager this was started from (`npm_config_user_agent`), else bun. */
73
+ export function detectPackageManager(agent = process.env.npm_config_user_agent ?? ""): PackageManager {
74
+ return PACKAGE_MANAGERS.find((pm) => agent.startsWith(`${pm}/`)) ?? "bun";
75
+ }
76
+
77
+ export const runScript = (pm: PackageManager, script: string) =>
78
+ pm === "npm" || pm === "bun" ? `${pm} run ${script}` : `${pm} ${script}`;
79
+
80
+ function icon(): Uint8Array {
81
+ const size = 256;
82
+ const data = new Uint8Array(size * size * 4);
83
+ const r = 56;
84
+ for (let y = 0; y < size; y++) {
85
+ for (let x = 0; x < size; x++) {
86
+ const dx = Math.max(0, Math.abs(x - 127.5) - (128 - r));
87
+ const dy = Math.max(0, Math.abs(y - 127.5) - (128 - r));
88
+ const inside = dx * dx + dy * dy <= r * r;
89
+ const t = (x + y) / (2 * size);
90
+ const o = (y * size + x) * 4;
91
+ data[o] = Math.round(0x42 + (0x2f - 0x42) * t);
92
+ data[o + 1] = Math.round(0xb8 + (0x6f - 0xb8) * t);
93
+ data[o + 2] = Math.round(0x83 + (0xd8 - 0x83) * t);
94
+ data[o + 3] = inside ? 255 : 0;
95
+ }
96
+ }
97
+ return encodePng({ width: size, height: size, data });
98
+ }
99
+
100
+ const json = (v: unknown) => JSON.stringify(v, null, 2) + "\n";
101
+
102
+ function listFiles(dir: string, prefix = ""): string[] {
103
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
104
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
105
+ return entry.isDirectory() ? listFiles(join(dir, entry.name), rel) : [rel];
106
+ });
107
+ }
108
+
109
+ /** The template's files, keyed by app-relative path; `{{key}}` is replaced in text files, escaped for a string literal except in .txt. */
110
+ export function templateFiles(template: Template, values: Record<string, string>): Record<string, string | Uint8Array> {
111
+ const dir = join(TEMPLATES_DIR, template);
112
+ const out: Record<string, string | Uint8Array> = {};
113
+ for (const rel of listFiles(dir)) {
114
+ const bytes = readFileSync(join(dir, rel));
115
+ const ext = extname(rel);
116
+ if (!TEXT_FILES.has(ext)) {
117
+ out[rel] = bytes;
118
+ continue;
119
+ }
120
+ out[rel] = bytes.toString("utf8").replace(/\{\{(\w+)\}\}/g, (whole, key: string) => {
121
+ const value = values[key];
122
+ if (value === undefined) return whole;
123
+ return ext === ".txt" ? value : JSON.stringify(value).slice(1, -1);
124
+ });
125
+ }
126
+ return out;
127
+ }
128
+
129
+ /** Writes the app; every option has a default. Returns the files written. */
130
+ export function create(target: string, options: CreateOptions = {}): string[] {
131
+ const dir = resolve(target);
132
+ const name = (options.name ?? basename(dir)).trim();
133
+ if (!name) throw new ConfigError("sk create: the app needs a name");
134
+ const productName = name
135
+ .replace(/(^|[-_.\s])(\w)/g, (_, sep: string, c: string) => (sep ? " " : "") + c.toUpperCase())
136
+ .trim();
137
+ const exeName = sanitizeExeName(productName) || "App";
138
+ const slug =
139
+ name
140
+ .toLowerCase()
141
+ .replace(/[^a-z0-9]+/g, "-")
142
+ .replace(/^-|-$/g, "") || "app";
143
+ const template = options.template ?? "showcase";
144
+ const info = TEMPLATE_INFO[template];
145
+ const platforms = options.platforms?.length ? options.platforms : [currentPlatform()];
146
+ const without: Part[] = OPTIONAL.filter((part) =>
147
+ part === "devtools" ? !options.keepDevtools : (options.without ?? []).includes(part),
148
+ );
149
+ const runtimeDeps = (runtimeRequire("./package.json") as { dependencies: Record<string, string> }).dependencies;
150
+ const sdk = `^${CLI_VERSION}`;
151
+
152
+ const files: Record<string, string | Uint8Array> = {
153
+ ...templateFiles(template, { name, productName }),
154
+ "package.json": json({
155
+ name: slug,
156
+ version: "0.1.0",
157
+ private: true,
158
+ type: "module",
159
+ scripts: {
160
+ dev: "sk dev",
161
+ build: "sk build",
162
+ publish: "sk publish",
163
+ check: "sk check",
164
+ typecheck: "vue-tsc --noEmit",
165
+ },
166
+ dependencies: {
167
+ "@skathi-native/runtime": sdk,
168
+ ...Object.fromEntries(info.dependencies.map((dep) => [dep, runtimeDeps[dep]])),
169
+ },
170
+ devDependencies: { "@skathi-native/cli": sdk, typescript: "^5", "vue-tsc": "^3" },
171
+ }),
172
+ "sk.config.json": json({
173
+ name,
174
+ productName,
175
+ version: "0.1.0",
176
+ platforms,
177
+ window: { title: productName, ...info.window, backdrop: "mica" },
178
+ assets: ["assets"],
179
+ ...(info.packs ? { packs: info.packs } : {}),
180
+ windows: { exeName, icon: "icon.png", without },
181
+ ...(platforms.includes("macos") ? { macos: { bundleId: `com.example.${slug}` } } : {}),
182
+ }),
183
+ "icon.png": icon(),
184
+ "tsconfig.json": json({
185
+ extends: "@skathi-native/runtime/tsconfig.app.json",
186
+ include: ["src/**/*.ts", "src/**/*.vue"],
187
+ }),
188
+ ".gitignore": "node_modules/\ndist/\n",
189
+ };
190
+
191
+ for (const rel of Object.keys(files)) {
192
+ if (existsSync(join(dir, rel)))
193
+ throw new ConfigError(`sk create: ${join(dir, rel)} already exists — nothing was written`);
194
+ }
195
+ const written: string[] = [];
196
+ for (const [rel, body] of Object.entries(files)) {
197
+ const path = join(dir, rel);
198
+ mkdirSync(join(path, ".."), { recursive: true });
199
+ writeFileSync(path, body);
200
+ written.push(path);
201
+ }
202
+ return written;
203
+ }
204
+
205
+ export interface CreateFlags {
206
+ name?: string | undefined;
207
+ template?: string | undefined;
208
+ os?: string | undefined;
209
+ without?: string | undefined;
210
+ devtools?: boolean | undefined;
211
+ pm?: string | undefined;
212
+ yes?: boolean | undefined;
213
+ }
214
+
215
+ function parsePm(v: string): PackageManager {
216
+ const pm = PACKAGE_MANAGERS.find((m) => m === v.trim().toLowerCase());
217
+ if (!pm) throw new ConfigError(`--pm ${JSON.stringify(v)}: expected one of ${PACKAGE_MANAGERS.join(", ")}`);
218
+ return pm;
219
+ }
220
+
221
+ export function parseTemplate(v: string): Template {
222
+ const template = TEMPLATES.find((t) => t === v.trim().toLowerCase());
223
+ if (!template) throw new ConfigError(`--template ${JSON.stringify(v)}: expected one of ${TEMPLATES.join(", ")}`);
224
+ return template;
225
+ }
226
+
227
+ function answered<T>(value: T): Exclude<T, symbol> {
228
+ if (p.isCancel(value) || typeof value === "symbol") {
229
+ p.cancel("Nothing was created.");
230
+ process.exit(130);
231
+ }
232
+ return value as Exclude<T, symbol>;
233
+ }
234
+
235
+ /** `sk create`: the questions the flags leave open, then {@link create}. */
236
+ export async function createCommand(target: string | undefined, flags: CreateFlags): Promise<number> {
237
+ const ask = !flags.yes && process.stdin.isTTY === true && process.stdout.isTTY === true;
238
+ const options: CreateOptions = {
239
+ name: flags.name,
240
+ template: flags.template !== undefined ? parseTemplate(flags.template) : undefined,
241
+ platforms: flags.os
242
+ ?.split(/[\s,]+/)
243
+ .filter(Boolean)
244
+ .map(parsePlatform),
245
+ without: flags.without !== undefined ? parseParts(flags.without, "--without") : undefined,
246
+ keepDevtools: flags.devtools,
247
+ packageManager: flags.pm !== undefined ? parsePm(flags.pm) : undefined,
248
+ };
249
+ let dir = target;
250
+
251
+ if (ask) {
252
+ p.intro("sk create");
253
+ dir ??= answered(
254
+ await p.text({
255
+ message: "Where should the app go?",
256
+ placeholder: "my-app",
257
+ defaultValue: "my-app",
258
+ validate: (v) =>
259
+ v && existsSync(join(resolve(v), "package.json")) ? `${v} already has a package.json` : undefined,
260
+ }),
261
+ );
262
+ options.name ??= answered(
263
+ await p.text({
264
+ message: "App name",
265
+ initialValue: basename(resolve(dir)),
266
+ validate: (v) => (v?.trim() ? undefined : "it needs a name"),
267
+ }),
268
+ );
269
+ options.template ??= answered(
270
+ await p.select<Template>({
271
+ message: "Template",
272
+ options: TEMPLATES.map((t) => ({ value: t, label: t, hint: TEMPLATE_INFO[t].hint })),
273
+ initialValue: "showcase",
274
+ }),
275
+ );
276
+ options.platforms ??= answered(
277
+ await p.multiselect<Platform>({
278
+ message: "Package it for",
279
+ options: [
280
+ { value: "windows", label: "Windows" },
281
+ { value: "macos", label: "macOS" },
282
+ { value: "linux", label: "Linux" },
283
+ ],
284
+ initialValues: [currentPlatform()],
285
+ required: true,
286
+ }),
287
+ );
288
+ if (!options.without) {
289
+ const kept = answered(
290
+ await p.multiselect<Exclude<Part, "devtools">>({
291
+ message: "Engine parts (leaving one out makes the exe smaller)",
292
+ options: ENGINE_PARTS,
293
+ initialValues: ENGINE_PARTS.map((e) => e.value),
294
+ required: false,
295
+ }),
296
+ );
297
+ options.without = ENGINE_PARTS.map((e) => e.value).filter((v) => !kept.includes(v));
298
+ }
299
+ options.keepDevtools ??= answered(
300
+ await p.confirm({
301
+ message: "Keep devtools (F12) in published builds? sk build always has them",
302
+ initialValue: false,
303
+ }),
304
+ );
305
+ options.packageManager ??= answered(
306
+ await p.select<PackageManager>({
307
+ message: "Package manager",
308
+ options: PACKAGE_MANAGERS.map((pm) => ({ value: pm, label: pm })),
309
+ initialValue: detectPackageManager(),
310
+ }),
311
+ );
312
+ }
313
+
314
+ dir ??= "my-app";
315
+ const pm = options.packageManager ?? detectPackageManager();
316
+ create(dir, options);
317
+ const where = relative(process.cwd(), resolve(dir)) || ".";
318
+ const next = [...(where === "." ? [] : [`cd ${where}`]), `${pm} install`, runScript(pm, "dev")].join("\n");
319
+ if (ask) {
320
+ p.note(next, "Next");
321
+ p.outro(`${options.name ?? basename(resolve(dir))} is ready`);
322
+ } else {
323
+ const c = paint(colorEnabled(process.stdout));
324
+ console.log(`${c.green("✓")} created ${c.cyan(resolve(dir))}\n ${c.dim("next:")} ${next.replace(/\n/g, " && ")}`);
325
+ }
326
+ return 0;
327
+ }
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
+ }