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

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 (33) hide show
  1. package/aot/host-globals.json +105 -0
  2. package/aot/native.ts +142 -0
  3. package/aot/pin.ts +67 -0
  4. package/aot/toolchain.lock.json +17 -0
  5. package/aot/transform.ts +69 -0
  6. package/cli/aot-build.ts +189 -0
  7. package/cli/build-app.ts +67 -25
  8. package/cli/config.ts +44 -101
  9. package/cli/create.ts +10 -53
  10. package/cli/help.ts +4 -5
  11. package/cli/host-fetch.ts +87 -48
  12. package/cli/host.ts +18 -8
  13. package/cli/sk.ts +16 -25
  14. package/cli/skpk.ts +4 -0
  15. package/package.json +3 -2
  16. package/templates/icon.png +0 -0
  17. package/templates/minimal/.vscode/settings.json +3 -0
  18. package/templates/showcase/.vscode/settings.json +3 -0
  19. package/templates/showcase/src/components/Titlebar.vue +7 -3
  20. package/templates/showcase/src/engine.ts +3 -26
  21. package/templates/showcase/src/pages/AudioPage.vue +6 -9
  22. package/templates/showcase/src/pages/FilesPage.vue +11 -15
  23. package/templates/showcase/src/pages/FormsPage.vue +2 -3
  24. package/templates/showcase/src/pages/GraphicsPage.vue +13 -15
  25. package/templates/showcase/src/pages/HomePage.vue +1 -2
  26. package/templates/showcase/src/pages/LocalePage.vue +2 -2
  27. package/templates/showcase/src/pages/MediaPage.vue +1 -1
  28. package/templates/showcase/src/pages/MotionPage.vue +1 -1
  29. package/templates/showcase/src/pages/NetworkPage.vue +6 -5
  30. package/templates/showcase/src/pages/PermissionsPage.vue +2 -2
  31. package/templates/showcase/src/pages/StoragePage.vue +23 -36
  32. package/templates/showcase/src/pages/SystemPage.vue +3 -3
  33. package/templates/showcase/src/components/Missing.vue +0 -26
@@ -0,0 +1,105 @@
1
+ {
2
+ "table": "4750b3540882158b35c1f7cc946edc1acb18561345bc70f9151fb913e59268b8",
3
+ "names": [
4
+ "$vm",
5
+ "AbortController",
6
+ "AbortSignal",
7
+ "Blob",
8
+ "BroadcastChannel",
9
+ "Buffer",
10
+ "BuildError",
11
+ "BuildMessage",
12
+ "Bun",
13
+ "ByteLengthQueuingStrategy",
14
+ "CloseEvent",
15
+ "CompressionStream",
16
+ "CountQueuingStrategy",
17
+ "Crypto",
18
+ "CryptoKey",
19
+ "CustomEvent",
20
+ "DOMException",
21
+ "DecompressionStream",
22
+ "ErrorEvent",
23
+ "Event",
24
+ "EventTarget",
25
+ "File",
26
+ "FormData",
27
+ "HTMLRewriter",
28
+ "Headers",
29
+ "Loader",
30
+ "MessageChannel",
31
+ "MessageEvent",
32
+ "MessagePort",
33
+ "Performance",
34
+ "PerformanceEntry",
35
+ "PerformanceMark",
36
+ "PerformanceMeasure",
37
+ "PerformanceObserver",
38
+ "PerformanceObserverEntryList",
39
+ "PerformanceResourceTiming",
40
+ "PerformanceServerTiming",
41
+ "PerformanceTiming",
42
+ "ReadableByteStreamController",
43
+ "ReadableStream",
44
+ "ReadableStreamBYOBReader",
45
+ "ReadableStreamBYOBRequest",
46
+ "ReadableStreamDefaultController",
47
+ "ReadableStreamDefaultReader",
48
+ "Request",
49
+ "ResolveError",
50
+ "ResolveMessage",
51
+ "Response",
52
+ "SubtleCrypto",
53
+ "TextDecoder",
54
+ "TextDecoderStream",
55
+ "TextEncoder",
56
+ "TextEncoderStream",
57
+ "TransformStream",
58
+ "TransformStreamDefaultController",
59
+ "URL",
60
+ "URLPattern",
61
+ "URLSearchParams",
62
+ "WebSocket",
63
+ "Worker",
64
+ "WritableStream",
65
+ "WritableStreamDefaultController",
66
+ "WritableStreamDefaultWriter",
67
+ "__disableSamplingProfiler",
68
+ "__disableSuperSampler",
69
+ "__dumpAndClearSamplingProfilerSamples",
70
+ "__enableSamplingProfiler",
71
+ "__enableSuperSampler",
72
+ "__signpostStart",
73
+ "__signpostStop",
74
+ "__tracePointStart",
75
+ "__tracePointStop",
76
+ "addEventListener",
77
+ "alert",
78
+ "atob",
79
+ "btoa",
80
+ "clearImmediate",
81
+ "clearInterval",
82
+ "clearTimeout",
83
+ "confirm",
84
+ "crypto",
85
+ "dispatchEvent",
86
+ "fetch",
87
+ "gc",
88
+ "global",
89
+ "navigator",
90
+ "onerror",
91
+ "onmessage",
92
+ "performance",
93
+ "postMessage",
94
+ "process",
95
+ "prompt",
96
+ "queueMicrotask",
97
+ "removeEventListener",
98
+ "reportError",
99
+ "self",
100
+ "setImmediate",
101
+ "setInterval",
102
+ "setTimeout",
103
+ "structuredClone"
104
+ ]
105
+ }
package/aot/native.ts ADDED
@@ -0,0 +1,142 @@
1
+ // One production bundle -> one native image: the opaque-host transform, then `sk-aot compile`
2
+ // (bundle -> IR -> machine code). Shared by `sk build --aot` and the inspector's release build, so
3
+ // both produce manifests the host validates the same way.
4
+ import { createHash } from "node:crypto";
5
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { COMPILER_FIELDS, type CompilerInfo } from "./pin";
8
+ import { opaqueHost, TRANSFORM } from "./transform";
9
+
10
+ export class AotError extends Error {}
11
+
12
+ const sha256 = (bytes: string | Uint8Array) => createHash("sha256").update(bytes).digest("hex");
13
+
14
+ interface Ran {
15
+ code: number;
16
+ stdout: string;
17
+ stderr: string;
18
+ }
19
+
20
+ /** Async, so a spinner keeps turning while sk-aot works. */
21
+ async function run(command: string[], cwd?: string): Promise<Ran> {
22
+ const child = Bun.spawn(command, { ...(cwd ? { cwd } : {}), stdout: "pipe", stderr: "pipe", stdin: "ignore" });
23
+ const [stdout, stderr, code] = await Promise.all([
24
+ new Response(child.stdout).text(),
25
+ new Response(child.stderr).text(),
26
+ child.exited,
27
+ ]);
28
+ return { code, stdout, stderr };
29
+ }
30
+
31
+ /** Where `cargo build --release` in a checkout's tools/sk-aot puts sk-aot. */
32
+ export const repoSkAot = (root: string) =>
33
+ join(root, "tools", "sk-aot", "target", "x86_64-pc-windows-msvc", "release", "sk-aot.exe");
34
+
35
+ const tail = (text: string, lines = 40) => text.trim().split(/\r?\n/).slice(-lines).join("\n");
36
+
37
+ export async function compilerInfo(compiler: string): Promise<CompilerInfo> {
38
+ if (!existsSync(compiler)) throw new AotError(`the native image compiler ${compiler} does not exist`);
39
+ const ran = await run([compiler, "info"]);
40
+ let info: Record<string, unknown> = {};
41
+ try {
42
+ info = JSON.parse(ran.stdout.trim()) as Record<string, unknown>;
43
+ } catch {}
44
+ const fields = COMPILER_FIELDS.map((name) => [name, info[name]] as const);
45
+ if (ran.code !== 0 || fields.some(([, value]) => typeof value !== "string")) {
46
+ throw new AotError(
47
+ `${compiler} is not a working sk-aot (\`info\` exited ${ran.code})\n${tail(ran.stdout + ran.stderr, 5)}`,
48
+ );
49
+ }
50
+ return Object.fromEntries(fields) as unknown as CompilerInfo;
51
+ }
52
+
53
+ /** The first field where `actual` and `expected` disagree, or null. */
54
+ export function compilerMismatch(actual: CompilerInfo, expected: CompilerInfo): string | null {
55
+ for (const name of COMPILER_FIELDS)
56
+ if (actual[name] !== expected[name]) return `${name} ${actual[name]} (the host needs ${expected[name]})`;
57
+ return null;
58
+ }
59
+
60
+ export interface NativeImage {
61
+ image: Uint8Array;
62
+ entry: number;
63
+ identity: string;
64
+ imageSha256: string;
65
+ sourceBundleSha256: string;
66
+ nativeInputSha256: string;
67
+ irSha256: string;
68
+ diagnostics: string;
69
+ }
70
+
71
+ export interface CompileOptions {
72
+ /** sk-aot. */
73
+ compiler: string;
74
+ source: string;
75
+ /** Holds the transformed input, the IR and the image. */
76
+ work: string;
77
+ }
78
+
79
+ export async function compileNative(options: CompileOptions): Promise<NativeImage> {
80
+ const { compiler, source, work } = options;
81
+ mkdirSync(work, { recursive: true });
82
+ const input = join(work, "native-input.js");
83
+ const ir = join(work, "app.ir");
84
+ const image = join(work, "app.image");
85
+ for (const stale of [ir, image, `${image}.entries`, `${image}.identity`]) rmSync(stale, { force: true });
86
+ const wrapped = opaqueHost(source);
87
+ writeFileSync(input, wrapped);
88
+
89
+ const compiled = await run([compiler, "compile", input, ir, image], work);
90
+ if (compiled.code !== 0 || !existsSync(ir) || !existsSync(image)) {
91
+ throw new AotError(
92
+ `sk-aot could not compile the app bundle (exit ${compiled.code}); its input is ${input}\n` +
93
+ tail(compiled.stderr + compiled.stdout),
94
+ );
95
+ }
96
+ const entries = readFileSync(`${image}.entries`, "utf8").trim().split(/\s+/).map(Number);
97
+ const entry = entries[0];
98
+ if (entries.length !== 1 || entry === undefined || !Number.isSafeInteger(entry) || entry < 1)
99
+ throw new AotError(`sk-aot reported entries ${JSON.stringify(entries)}, expected one`);
100
+ const identity = readFileSync(`${image}.identity`);
101
+ if (identity.length !== 16) throw new AotError("sk-aot wrote an invalid image identity");
102
+ const bytes = new Uint8Array(readFileSync(image));
103
+ return {
104
+ image: bytes,
105
+ entry,
106
+ identity: identity.toString("hex"),
107
+ imageSha256: sha256(bytes),
108
+ sourceBundleSha256: sha256(source),
109
+ nativeInputSha256: sha256(wrapped),
110
+ irSha256: sha256(readFileSync(ir)),
111
+ diagnostics: compiled.stdout.trim(),
112
+ };
113
+ }
114
+
115
+ export type NativeKind = "inspector" | "application";
116
+
117
+ /** The manifest the host checks before it loads `image` (crates/sk-app/src/native_aot.rs). */
118
+ export function nativeManifest(
119
+ kind: NativeKind,
120
+ info: CompilerInfo,
121
+ native: NativeImage,
122
+ options: { image: string; preludeSha256: string },
123
+ ): Record<string, unknown> {
124
+ return {
125
+ schema: "skathi.native-aot",
126
+ version: 1,
127
+ stage: "native-image",
128
+ kind,
129
+ ...info,
130
+ image: options.image,
131
+ imageSha256: native.imageSha256,
132
+ imageBytes: native.image.length,
133
+ entry: native.entry,
134
+ identity: native.identity,
135
+ transform: TRANSFORM,
136
+ sourceBundleSha256: native.sourceBundleSha256,
137
+ preludeSha256: options.preludeSha256,
138
+ nativeInputSha256: native.nativeInputSha256,
139
+ irSha256: native.irSha256,
140
+ sourceStage: "production-javascript",
141
+ };
142
+ }
package/aot/pin.ts ADDED
@@ -0,0 +1,67 @@
1
+ // The reviewed native-AOT toolchain: the Bun revision sk-aot's frontend is built from, the engine
2
+ // revision and the builtin table id that sk-aot must report. Reading it runs nothing.
3
+ import { createHash } from "node:crypto";
4
+ import { createReadStream, readFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+
7
+ export const PIN_PATH = join(import.meta.dir, "toolchain.lock.json");
8
+
9
+ export interface ToolchainPin {
10
+ schema: string;
11
+ version: number;
12
+ target: string;
13
+ frontend: { revision: string; sourceRepository: string };
14
+ engine: { revision: string; archiveSha256: string };
15
+ table: { id: string; dumpSha256: string };
16
+ }
17
+
18
+ /** What `sk-aot info` prints, and what a host's `--sk-host-info` `aot` names. */
19
+ export interface CompilerInfo {
20
+ target: string;
21
+ frontend: string;
22
+ engine: string;
23
+ tableId: string;
24
+ compileOptions: string;
25
+ }
26
+
27
+ export const COMPILER_FIELDS = ["target", "frontend", "engine", "tableId", "compileOptions"] as const;
28
+
29
+ export function loadPin(path: string = PIN_PATH): ToolchainPin {
30
+ const pin = JSON.parse(readFileSync(path, "utf8").replace(/^/, "")) as ToolchainPin;
31
+ if (pin.schema !== "skathi.native-aot-toolchain" || pin.version !== 1 || pin.target !== "x86_64-windows")
32
+ throw Error("Unsupported native AOT toolchain pin");
33
+ for (const revision of [pin.frontend?.revision, pin.engine?.revision])
34
+ if (!/^[a-f0-9]{40}$/.test(revision || "")) throw Error("Invalid native AOT revision");
35
+ for (const digest of [pin.engine?.archiveSha256, pin.table?.id, pin.table?.dumpSha256])
36
+ if (!/^[a-f0-9]{64}$/.test(digest || "")) throw Error("Invalid native AOT digest");
37
+ if (pin.frontend.sourceRepository !== "https://github.com/oven-sh/bun.git")
38
+ throw Error("The AOT frontend must be built from the official Bun repository");
39
+ return pin;
40
+ }
41
+
42
+ export function pinnedCompilerInfo(pin: ToolchainPin): CompilerInfo {
43
+ return {
44
+ target: pin.target,
45
+ frontend: pin.frontend.revision,
46
+ engine: pin.engine.revision,
47
+ tableId: pin.table.id,
48
+ compileOptions: `x86_64;references=narrow;image=pic;threads=1;admit=FilesRunByHost;default-options@${pin.engine.revision}`,
49
+ };
50
+ }
51
+
52
+ export async function fileDigest(path: string): Promise<string> {
53
+ const hash = createHash("sha256");
54
+ for await (const chunk of createReadStream(path, { highWaterMark: 64 * 1024 })) hash.update(chunk);
55
+ return hash.digest("hex");
56
+ }
57
+
58
+ export async function verifyFile(path: string, expected: string): Promise<void> {
59
+ const actual = await fileDigest(path);
60
+ if (actual !== expected)
61
+ throw Error(`Native AOT input digest mismatch: ${path}; expected ${expected}, got ${actual}`);
62
+ }
63
+
64
+ export function verifyCompilerInfo(info: Record<string, unknown>, pin: ToolchainPin): void {
65
+ for (const [name, value] of Object.entries(pinnedCompilerInfo(pin)))
66
+ if (info[name] !== value) throw Error(`Native AOT compiler ${name} differs from the reviewed toolchain`);
67
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "schema": "skathi.native-aot-toolchain",
3
+ "version": 1,
4
+ "target": "x86_64-windows",
5
+ "frontend": {
6
+ "revision": "7ca0042d3ba23ed60fd9cd8af1a1ce6ec3f8d074",
7
+ "sourceRepository": "https://github.com/oven-sh/bun.git"
8
+ },
9
+ "engine": {
10
+ "revision": "4d45755fed4aeef19e95beb90d3d0c884a2812bd",
11
+ "archiveSha256": "fd79937b7f8becd5c0961646cd7f8af4409122e9cf710ffd766dc0c89df1f619"
12
+ },
13
+ "table": {
14
+ "id": "4750b3540882158b35c1f7cc946edc1acb18561345bc70f9151fb913e59268b8",
15
+ "dumpSha256": "afac4f15bc41518c037d80965fed1c53edd36b96837602cab40660b3a0f5beb2"
16
+ }
17
+ }
@@ -0,0 +1,69 @@
1
+ // opaque-host-v1: the production bundle, wrapped so the host's globals are opaque inputs to the
2
+ // native frontend. It must not assume that this host's URL, fetch, WebSocket or Blob have Bun's
3
+ // layouts or helpers; the host binds `__SK_AOT_HOST__` to the realm's globalThis before the entry runs.
4
+ import HOST_TABLE from "./host-globals.json";
5
+
6
+ export const TRANSFORM = "opaque-host-v1";
7
+
8
+ export interface BuiltinEntry {
9
+ holder: string;
10
+ origin: string;
11
+ isSymbolName: boolean;
12
+ name: string;
13
+ }
14
+
15
+ /** The host-implemented globals of a builtin table dump: what host-globals.json records. */
16
+ export function hostGlobalsFromTable(entries: BuiltinEntry[]): string[] {
17
+ return [
18
+ ...new Set(
19
+ entries
20
+ .filter(
21
+ (entry) =>
22
+ entry.holder === "GlobalThis" &&
23
+ entry.origin === "Host" &&
24
+ !entry.isSymbolName &&
25
+ /^[A-Za-z_$][\w$]*$/.test(entry.name),
26
+ )
27
+ .map((entry) => entry.name),
28
+ ),
29
+ ].sort();
30
+ }
31
+
32
+ /** Browser globals this host provides that the table does not describe as host APIs. */
33
+ const BROWSER_GLOBALS = [
34
+ "Object",
35
+ "console",
36
+ "window",
37
+ "self",
38
+ "document",
39
+ "navigator",
40
+ "location",
41
+ "performance",
42
+ "requestAnimationFrame",
43
+ "cancelAnimationFrame",
44
+ "ResizeObserver",
45
+ "MutationObserver",
46
+ "IntersectionObserver",
47
+ "Image",
48
+ "Audio",
49
+ "AudioContext",
50
+ "OffscreenCanvas",
51
+ "Path2D",
52
+ "ImageData",
53
+ "createImageBitmap",
54
+ "localStorage",
55
+ "sessionStorage",
56
+ "indexedDB",
57
+ "matchMedia",
58
+ "getComputedStyle",
59
+ ];
60
+
61
+ export const TABLE_ID: string = HOST_TABLE.table;
62
+
63
+ export function opaqueGlobals(tableGlobals: readonly string[] = HOST_TABLE.names): string[] {
64
+ return [...new Set([...tableGlobals, ...BROWSER_GLOBALS])].sort();
65
+ }
66
+
67
+ export function opaqueHost(source: string, names: readonly string[] = opaqueGlobals()): string {
68
+ return `// ${TRANSFORM}: stable host API references are opaque inputs.\n(function(__sk_host) {\nconst globalThis = __sk_host;\nconst {${names.join(",")}} = __sk_host;\n${source}\n})(__SK_AOT_HOST__);\n`;
69
+ }
@@ -0,0 +1,189 @@
1
+ // `sk build --aot`: the app's production bundle compiled to a native image that travels in the
2
+ // payload beside app.prod.js (which stays: the host checks the image against it, and stacks name it).
3
+ //
4
+ // sk check (errors refuse the build) -> sk-aot matching the host (--aot-compiler, the checkout's
5
+ // build, or the release asset, cached) -> image + manifest
6
+ //
7
+ // The host checks the manifest against itself before it loads the image (crates/sk-app/src/native_aot.rs).
8
+
9
+ import { deflateRawSync } from "node:zlib";
10
+ import { existsSync, writeFileSync } from "node:fs";
11
+ import { join, resolve } from "node:path";
12
+ import { AotError, compileNative, compilerInfo, compilerMismatch, nativeManifest, repoSkAot } from "../aot/native";
13
+ import type { CompilerInfo } from "../aot/pin";
14
+ import { TRANSFORM } from "../aot/transform";
15
+ import { exitCode, formatPretty, runCheck, type CheckReport } from "../check/index";
16
+ import { ConfigError } from "./config";
17
+ import { CLI_VERSION, HostError, REPO_ROOT, type HostAot, type ResolvedHost } from "./host";
18
+ import { cachedAotCompiler, fetchAotCompiler } from "./host-fetch";
19
+ import type { Platform } from "./platform";
20
+ import { KIND, NAMES, type SkpkInput } from "./skpk";
21
+ import type { Progress } from "./term";
22
+
23
+ export const AOT_PLATFORM_ONLY = "AOT builds are Windows x64 only for now";
24
+
25
+ /** `--aot`, `--no-aot` and `--aot-compiler <exe>`; an unset `aot` leaves sk.config.json "aot" in charge. */
26
+ export function aotFlags(flags: Record<string, string | boolean>): {
27
+ aot: boolean | undefined;
28
+ aotCompiler: string | undefined;
29
+ } {
30
+ if (flags.aot === true && flags["no-aot"] === true) throw new ConfigError("--aot and --no-aot contradict each other");
31
+ const compiler = flags["aot-compiler"];
32
+ if (compiler !== undefined && (typeof compiler !== "string" || !compiler.trim()))
33
+ throw new ConfigError("--aot-compiler needs the path of sk-aot.exe");
34
+ return {
35
+ aot: flags["no-aot"] === true ? false : flags.aot === true ? true : undefined,
36
+ aotCompiler: typeof compiler === "string" ? resolve(compiler.trim()) : undefined,
37
+ };
38
+ }
39
+
40
+ /** Why this build cannot be AOT-compiled here, or null. */
41
+ export function aotPlatformProblem(
42
+ target: Platform,
43
+ here: { platform: string; arch: string } = { platform: process.platform, arch: process.arch },
44
+ ): string | null {
45
+ if (target !== "windows")
46
+ return `${AOT_PLATFORM_ONLY}: build ${target} with --no-aot (or without "aot": true in sk.config.json)`;
47
+ if (here.platform !== "win32" || here.arch !== "x64")
48
+ return `${AOT_PLATFORM_ONLY}: the native compiler runs on Windows x64 and this is ${here.platform}-${here.arch}; build here with --no-aot`;
49
+ return null;
50
+ }
51
+
52
+ /** The host's native AOT identity; an error when the host cannot load app images. */
53
+ export function hostAot(host: ResolvedHost): HostAot {
54
+ const aot = host.info.aot;
55
+ if (!host.info.features.includes("native-aot") || !aot) {
56
+ throw new HostError(
57
+ `${host.exe} cannot load native images (it was built without the native AOT loader) — ` +
58
+ `use a Skathi ${CLI_VERSION} release host (sk host fetch), or build one with the native-aot cargo feature`,
59
+ );
60
+ }
61
+ if (aot.transform !== TRANSFORM) {
62
+ throw new HostError(
63
+ `${host.exe} expects native images made with the ${aot.transform} transform and this sk makes ${TRANSFORM} — ` +
64
+ "use the sk that matches the host",
65
+ );
66
+ }
67
+ return aot;
68
+ }
69
+
70
+ export interface CompilerChoice {
71
+ path: string;
72
+ info: CompilerInfo;
73
+ source: "--aot-compiler" | "SK_AOT_COMPILER" | "repo" | "cache" | "release";
74
+ }
75
+
76
+ /**
77
+ * The sk-aot matching `aot`, first hit wins: --aot-compiler or SK_AOT_COMPILER (must match);
78
+ * the checkout's own build; the cache; a download from this version's release.
79
+ */
80
+ export async function resolveAotCompiler(
81
+ aot: HostAot,
82
+ named: string | undefined,
83
+ log: (line: string) => void,
84
+ ): Promise<CompilerChoice> {
85
+ const explicit = named ?? process.env.SK_AOT_COMPILER;
86
+ if (explicit) {
87
+ const info = await compilerInfo(explicit);
88
+ const mismatch = compilerMismatch(info, aot);
89
+ if (mismatch) throw new AotError(`${explicit} compiles for another host: ${mismatch}`);
90
+ return { path: explicit, info, source: named ? "--aot-compiler" : "SK_AOT_COMPILER" };
91
+ }
92
+ const tried: string[] = [];
93
+ const candidates: { path: string; source: "repo" | "cache" }[] = [];
94
+ if (REPO_ROOT) candidates.push({ path: repoSkAot(REPO_ROOT), source: "repo" });
95
+ candidates.push({ path: cachedAotCompiler(CLI_VERSION), source: "cache" });
96
+ for (const c of candidates) {
97
+ if (!existsSync(c.path)) continue;
98
+ const info = await compilerInfo(c.path);
99
+ const mismatch = compilerMismatch(info, aot);
100
+ if (!mismatch) return { ...c, info };
101
+ tried.push(`${c.path}: ${mismatch}`);
102
+ }
103
+ if (process.env.SK_HOST_OFFLINE === "1") {
104
+ throw new AotError(
105
+ `no sk-aot matches the host${tried.length ? `:\n ${tried.join("\n ")}` : ""}\n` +
106
+ "SK_HOST_OFFLINE=1 forbids downloading it; pass --aot-compiler <sk-aot.exe>",
107
+ );
108
+ }
109
+ const fetched = await fetchAotCompiler({ log });
110
+ const mismatch = compilerMismatch(fetched.info, aot);
111
+ if (mismatch) throw new AotError(`the Skathi ${CLI_VERSION} release's sk-aot: ${mismatch}`);
112
+ return { path: fetched.path, info: await compilerInfo(fetched.path), source: "release" };
113
+ }
114
+
115
+ /** One line per diagnostic, for warnings that do not stop the build. */
116
+ export function checkLine(d: CheckReport["diagnostics"][number]): string {
117
+ return `${d.file}:${d.range.start.line + 1}:${d.range.start.character + 1} ${d.code} ${d.message}`;
118
+ }
119
+
120
+ /** `sk check` over the app: errors (and fatal findings) refuse the build with the report; warnings are printed. */
121
+ export async function aotCheck(
122
+ target: string,
123
+ configPath: string | undefined,
124
+ progress: Progress,
125
+ color: boolean,
126
+ ): Promise<CheckReport> {
127
+ const report = await runCheck({ target, configPath, toolVersion: CLI_VERSION, progress });
128
+ const code = exitCode(report, false);
129
+ if (code !== 0) {
130
+ throw new ConfigError(
131
+ `sk check found what a native image cannot run, so the AOT build stops here:\n\n${formatPretty(report, { color })}\n\n` +
132
+ "Fix the errors (sk explain <CODE> says how), or build with --no-aot.",
133
+ );
134
+ }
135
+ for (const d of report.diagnostics) progress.warn(checkLine(d));
136
+ return report;
137
+ }
138
+
139
+ export interface NativeBuild {
140
+ inputs: SkpkInput[];
141
+ manifestPath: string;
142
+ imageBytes: number;
143
+ compressedBytes: number;
144
+ entry: number;
145
+ compiler: CompilerChoice;
146
+ }
147
+
148
+ /** The two payload entries that make an app native, written also to `work` for inspection. */
149
+ export async function buildNative(options: {
150
+ source: Uint8Array;
151
+ aot: HostAot;
152
+ compilerPath: string | undefined;
153
+ work: string;
154
+ progress: Progress;
155
+ log: (line: string) => void;
156
+ }): Promise<NativeBuild> {
157
+ const { progress, log, aot, work } = options;
158
+ progress.step("AOT toolchain");
159
+ const compiler = await resolveAotCompiler(aot, options.compilerPath, log);
160
+ progress.detail(`sk-aot (${compiler.source})`);
161
+ progress.step("native image");
162
+ const native = await compileNative({
163
+ compiler: compiler.path,
164
+ source: new TextDecoder().decode(options.source),
165
+ work,
166
+ });
167
+ const compressed = deflateRawSync(native.image, { level: 9 });
168
+ progress.detail(
169
+ `${(native.image.length / 2 ** 20).toFixed(1)} MiB, ${(compressed.length / 2 ** 20).toFixed(1)} MiB packed`,
170
+ );
171
+ const manifest = nativeManifest("application", compiler.info, native, {
172
+ image: NAMES.NATIVE_IMAGE,
173
+ preludeSha256: aot.preludeSha256,
174
+ });
175
+ const text = JSON.stringify(manifest, null, 2);
176
+ const manifestPath = join(work, "app.native.json");
177
+ writeFileSync(manifestPath, text);
178
+ return {
179
+ inputs: [
180
+ { name: NAMES.NATIVE_MANIFEST, kind: KIND.NATIVE_MANIFEST, data: new TextEncoder().encode(text) },
181
+ { name: NAMES.NATIVE_IMAGE, kind: KIND.NATIVE_IMAGE, data: new Uint8Array(compressed) },
182
+ ],
183
+ manifestPath,
184
+ imageBytes: native.image.length,
185
+ compressedBytes: compressed.length,
186
+ entry: native.entry,
187
+ compiler,
188
+ };
189
+ }