@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/assets.ts ADDED
@@ -0,0 +1,114 @@
1
+ // What goes into the package: `sk.config.json` `"assets"`, resolved to files. The KEY of each file
2
+ // is its path relative to the app root, `/`-separated, case-preserved: what dev resolves a
3
+ // relative URL to. Vite's `publicDir` is the one remapping (`public/favicon.ico` -> `favicon.ico`),
4
+ // only when declared; the dev host does not remap it yet, a known dev/exe difference.
5
+ // Never packaged: `src/`, `node_modules/`, `dist/`, dotfiles and dot-directories, `sk.config.json`.
6
+ // Files an import pulled in (`?url`) are listed by the builder in assets.json and packed by build-app.ts.
7
+
8
+ import { existsSync, readdirSync, statSync } from "node:fs";
9
+ import { join, relative, sep } from "node:path";
10
+
11
+ export interface AssetFile {
12
+ key: string;
13
+ path: string;
14
+ size: number;
15
+ }
16
+
17
+ export interface Collected {
18
+ files: AssetFile[];
19
+ totalBytes: number;
20
+ warnings: string[];
21
+ }
22
+
23
+ const GLOB = /[*?[\]{}]/;
24
+ const EXCLUDED_ROOTS = new Set(["src", "node_modules", "dist"]);
25
+
26
+ export function excluded(key: string): boolean {
27
+ const segs = key.split("/");
28
+ if (EXCLUDED_ROOTS.has(segs[0]!)) return true;
29
+ if (segs.some((s) => s.startsWith("."))) return true;
30
+ return key === "sk.config.json";
31
+ }
32
+
33
+ const toKey = (appRoot: string, abs: string) => relative(appRoot, abs).split(sep).join("/");
34
+
35
+ function walk(dir: string, out: string[]) {
36
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
37
+ if (entry.name.startsWith(".")) continue;
38
+ const abs = join(dir, entry.name);
39
+ if (entry.isDirectory()) walk(abs, out);
40
+ else if (entry.isFile()) out.push(abs);
41
+ }
42
+ }
43
+
44
+ export function collectAssets(
45
+ appRoot: string,
46
+ patterns: string[],
47
+ declared: boolean,
48
+ publicDir: string | null = null,
49
+ ): Collected {
50
+ const warnings: string[] = [];
51
+ const byKey = new Map<string, AssetFile>();
52
+ if (publicDir) {
53
+ const root = join(appRoot, publicDir);
54
+ const found: string[] = [];
55
+ if (existsSync(root) && statSync(root).isDirectory()) walk(root, found);
56
+ for (const abs of found) {
57
+ const key = toKey(root, abs);
58
+ byKey.set(key, { key, path: abs, size: statSync(abs).size });
59
+ }
60
+ } else if (existsSync(join(appRoot, "public")) && statSync(join(appRoot, "public")).isDirectory()) {
61
+ warnings.push(
62
+ 'the app has a public/ directory but sk.config.json declares no "publicDir": Vite serves public/x at /x, ' +
63
+ 'a package does not unless you set "publicDir": "public"',
64
+ );
65
+ }
66
+ const fromPublic = new Set(byKey.keys());
67
+ for (const pattern of patterns) {
68
+ const clean = pattern.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
69
+ if (!clean || clean.startsWith("/") || /^[a-zA-Z]:/.test(clean) || clean.split("/").includes("..")) {
70
+ throw new Error(
71
+ `sk.config.json "assets": ${JSON.stringify(pattern)} must be relative to the app root and stay inside it`,
72
+ );
73
+ }
74
+ const matched: string[] = [];
75
+ if (GLOB.test(clean)) {
76
+ for (const rel of new Bun.Glob(clean).scanSync({ cwd: appRoot, onlyFiles: true, dot: false })) {
77
+ matched.push(join(appRoot, rel));
78
+ }
79
+ } else {
80
+ const abs = join(appRoot, clean);
81
+ if (existsSync(abs)) {
82
+ if (statSync(abs).isDirectory()) walk(abs, matched);
83
+ else matched.push(abs);
84
+ }
85
+ }
86
+ let kept = 0;
87
+ for (const abs of matched) {
88
+ const key = toKey(appRoot, abs);
89
+ if (key.startsWith("..") || excluded(key)) continue;
90
+ kept++;
91
+ if (fromPublic.has(key)) {
92
+ warnings.push(
93
+ `${JSON.stringify(key)} is both in "${publicDir}/" and in "assets" — the ${publicDir}/ file is packaged`,
94
+ );
95
+ fromPublic.delete(key);
96
+ continue;
97
+ }
98
+ if (!byKey.has(key)) byKey.set(key, { key, path: abs, size: statSync(abs).size });
99
+ }
100
+ if (!kept && (declared || clean !== "assets")) {
101
+ warnings.push(`sk.config.json "assets": ${JSON.stringify(pattern)} matched no files`);
102
+ }
103
+ }
104
+ const files = [...byKey.values()].sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
105
+ // Two keys that differ only in case would be one file on NTFS; the host's case-insensitive fallback could pick either.
106
+ const lower = new Map<string, string>();
107
+ for (const f of files) {
108
+ const k = f.key.toLowerCase();
109
+ const prev = lower.get(k);
110
+ if (prev) warnings.push(`assets ${JSON.stringify(prev)} and ${JSON.stringify(f.key)} differ only in case`);
111
+ else lower.set(k, f.key);
112
+ }
113
+ return { files, totalBytes: files.reduce((n, f) => n + f.size, 0), warnings };
114
+ }
@@ -0,0 +1,587 @@
1
+ // `sk build`: an app directory in, one exe out, no Rust toolchain.
2
+ //
3
+ // sk.config.json + prod.ts (app.prod.js, window.json) + "assets" -> SKPK -> stamp(copy of the bare host)
4
+ // -> <appRoot>/dist/<exeName>.exe
5
+ //
6
+ // Intermediates go to `dist/.sk/` (`app.prod.js`, `window.json`, `assets.json`, `app.skpk`). The
7
+ // `.skpk` is the exact blob that was stamped, so `SK_PAYLOAD=dist/.sk/app.skpk <host>` runs it
8
+ // without a re-stamp. On macOS (or `--platform macos` with `--host <mac sk-app>`) the last step is
9
+ // macos-bundle.ts: the host is copied into `<exeName>.app`, the SKPK goes in Contents/Resources,
10
+ // and the bundle is signed (ad hoc unless an identity is given). On Linux the SKPK is appended to a
11
+ // copy of the host ELF (elf.ts). `PACKAGERS` holds the three.
12
+
13
+ import { createHash } from "node:crypto";
14
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
15
+ import { join, relative, resolve, sep } from "node:path";
16
+ import { collectAssets, type AssetFile } from "./assets";
17
+ import {
18
+ loadAppConfig,
19
+ partsLeftOut,
20
+ variantFor,
21
+ variantWarnings,
22
+ type AppConfig,
23
+ type PackConfig,
24
+ type Variant,
25
+ } from "./config";
26
+ import { stampElf, type ElfStampResult } from "./elf";
27
+ import { CLI_VERSION, PKG_DIR, type ResolvedHost } from "./host";
28
+ import { resolveOrFetchHost } from "./host-fetch";
29
+ import { iconImagesFrom } from "./icon";
30
+ import {
31
+ entitlements,
32
+ icnsFrom,
33
+ ICON_NAME,
34
+ infoPlist,
35
+ plistXml,
36
+ signBundle,
37
+ signPlan,
38
+ writeAppBundle,
39
+ type AppBundleResult,
40
+ } from "./macos-bundle";
41
+ import { currentPlatform, type Platform } from "./platform";
42
+ import { stamp, type StampResult } from "./stamp";
43
+ import { lineProgress, logTo, paint, progressFor, seconds, type Progress } from "./term";
44
+ import { buildVersionInfo, numericVersion } from "./versioninfo";
45
+ import { FORMAT, KIND, NAMES, readHeader, skewFor, writeSkpk, type SkpkInput } from "./skpk";
46
+
47
+ export const PROD_TS = join(PKG_DIR, "prod.ts");
48
+
49
+ export const WARN_PAYLOAD_BYTES = 512 * 1024 * 1024;
50
+ export const MAX_PAYLOAD_BYTES = 1536 * 1024 * 1024;
51
+
52
+ export interface BuildOptions {
53
+ target: string;
54
+ /** Read this config instead of <appRoot>/sk.config.json; paths still belong to appRoot. */
55
+ configPath?: string | undefined;
56
+ out?: string | undefined;
57
+ host?: string | undefined;
58
+ /** The host variant; overrides sk.config.json's `windows` selection. */
59
+ variant?: Variant | undefined;
60
+ console?: boolean;
61
+ payloadOnly?: boolean;
62
+ allowHostMismatch?: boolean;
63
+ defines?: string[] | undefined;
64
+ aotInputs?: boolean;
65
+ platform?: Platform | undefined;
66
+ /** macOS: a codesign identity (`-` = ad hoc), or false for none; over `macos.sign`. */
67
+ sign?: string | false | undefined;
68
+ /**
69
+ * `sk build` is "debug": devtools always in, the bundle not minified, <app>/dist/debug. `sk publish` is
70
+ * "release": sk.config.json's engine selection, and without one, no devtools; <app>/dist/release. Unset:
71
+ * the config's selection into <app>/dist, as the API always did.
72
+ */
73
+ mode?: "debug" | "release" | undefined;
74
+ /** Plain lines instead of the default progress on stderr. */
75
+ log?: (line: string) => void;
76
+ progress?: Progress;
77
+ }
78
+
79
+ /** The variant a mode builds when neither `--variant` nor a selection flag names one. */
80
+ export function modeVariant(config: AppConfig, mode: BuildOptions["mode"]): Variant {
81
+ const selected = config.windows.variant;
82
+ if (mode === "debug") return variantFor(partsLeftOut(selected).filter((p) => p !== "devtools"));
83
+ if (mode === "release" && !config.windows.selected) return "no-devtools";
84
+ return selected;
85
+ }
86
+
87
+ interface BuilderAsset {
88
+ key: string;
89
+ path: string;
90
+ }
91
+
92
+ function readBuilderAssets(path: string): BuilderAsset[] {
93
+ if (!existsSync(path)) return [];
94
+ const list = JSON.parse(readFileSync(path, "utf8")) as unknown;
95
+ if (!Array.isArray(list)) throw new Error(`${path}: not a list`);
96
+ return list.filter(
97
+ (a): a is BuilderAsset =>
98
+ !!a && typeof (a as BuilderAsset).key === "string" && typeof (a as BuilderAsset).path === "string",
99
+ );
100
+ }
101
+
102
+ export interface MacBundle extends AppBundleResult {
103
+ bundleId: string;
104
+ iconSizes: number[];
105
+ signed: string | null;
106
+ signNote: string | null;
107
+ entitlements: string;
108
+ }
109
+
110
+ export interface BuildResult {
111
+ config: AppConfig;
112
+ platform: Platform;
113
+ variant: Variant;
114
+ exe: string | null;
115
+ skpk: string;
116
+ host: ResolvedHost | null;
117
+ stamp: StampResult | null;
118
+ bundle: MacBundle | null;
119
+ elf: ElfStampResult | null;
120
+ assets: AssetFile[];
121
+ bundleBytes: number;
122
+ payloadBytes: number;
123
+ packs: { name: string; path: string; bytes: number; assets: number }[];
124
+ aotInputs: string | null;
125
+ warnings: string[];
126
+ ms: { bundle: number; assets: number; stamp: number; total: number };
127
+ }
128
+
129
+ const enc = new TextEncoder();
130
+
131
+ /** The META entry. No timestamps — two builds of one tree are byte-identical. */
132
+ export function appMeta(
133
+ config: AppConfig,
134
+ variant: Variant,
135
+ host: ResolvedHost | null,
136
+ assetCount: number,
137
+ packs: BuiltPack[] = [],
138
+ ): string {
139
+ const entry = relative(config.appRoot, config.entry).split(sep).join("/");
140
+ return JSON.stringify({
141
+ format: FORMAT,
142
+ name: config.name,
143
+ productName: config.productName,
144
+ version: config.version,
145
+ skathi: CLI_VERSION,
146
+ host: { version: host?.info.skathi ?? CLI_VERSION, variant },
147
+ entry,
148
+ assets: assetCount,
149
+ launch: config.launch,
150
+ ...(packs.length ? { packs: packs.map((p) => ({ name: p.name, file: p.file, id: p.id })) } : {}),
151
+ });
152
+ }
153
+
154
+ export interface BuiltPack {
155
+ name: string;
156
+ file: string;
157
+ id: string;
158
+ blob: Uint8Array;
159
+ assets: AssetFile[];
160
+ }
161
+
162
+ /** Deals the assets out to the packs in order; what no pack takes stays in the payload. */
163
+ export function splitPacks(
164
+ files: AssetFile[],
165
+ packs: PackConfig[],
166
+ ): { own: AssetFile[]; packs: { name: string; files: AssetFile[] }[] } {
167
+ let left = files;
168
+ const dealt = packs.map((p) => {
169
+ const globs = p.match?.map((m) => new Bun.Glob(m));
170
+ const taken = globs ? left.filter((f) => globs.some((g) => g.match(f.key))) : left;
171
+ left = left.filter((f) => !taken.includes(f));
172
+ return { name: p.name, files: taken };
173
+ });
174
+ return { own: left, packs: dealt };
175
+ }
176
+
177
+ /** An asset pack's blob: assets only, data page-aligned in the file (the host maps it from offset 0), and its id. */
178
+ export function writePack(name: string, files: AssetFile[]): BuiltPack {
179
+ const inputs: SkpkInput[] = files.map((f) => ({
180
+ name: f.key,
181
+ kind: KIND.ASSET,
182
+ data: new Uint8Array(readFileSync(f.path)),
183
+ }));
184
+ const unskewed = writeSkpk(inputs);
185
+ const header = readHeader(unskewed);
186
+ const skew = skewFor(0, header);
187
+ const blob = skew ? writeSkpk(inputs, { skew }) : unskewed;
188
+ const id = createHash("sha256")
189
+ .update(blob.subarray(0, header.namesOff + header.namesLen))
190
+ .digest("hex");
191
+ return { name, file: `${name}.skpk`, id, blob, assets: files };
192
+ }
193
+
194
+ interface PackageInput {
195
+ config: AppConfig;
196
+ host: ResolvedHost;
197
+ inputs: SkpkInput[];
198
+ packs: BuiltPack[];
199
+ outDir: string;
200
+ work: string;
201
+ options: BuildOptions;
202
+ warnings: string[];
203
+ log: (line: string) => void;
204
+ }
205
+
206
+ interface Packaged {
207
+ exe: string;
208
+ payload: Uint8Array;
209
+ stamp: StampResult | null;
210
+ bundle: MacBundle | null;
211
+ elf?: ElfStampResult;
212
+ }
213
+
214
+ function stampExe({ config, host, inputs, packs, outDir, options, log }: PackageInput): Packaged {
215
+ for (const p of packs) writeFileSync(join(outDir, p.file), p.blob);
216
+ const fv = numericVersion(config.version);
217
+ const exeFile = `${config.exeName}.exe`;
218
+ const exe = join(outDir, exeFile);
219
+ const w = config.windows;
220
+ const stamped = stamp({
221
+ host: host.exe,
222
+ out: exe,
223
+ payload: (skew) => writeSkpk(inputs, { skew }),
224
+ icons: config.iconPath ? iconImagesFrom(config.iconPath) : undefined,
225
+ versionInfo: buildVersionInfo({
226
+ fileVersion: [fv[0], fv[1], fv[2], 0],
227
+ strings: {
228
+ // Task Manager names a process by its FileDescription, so it is the product name.
229
+ FileDescription: config.productName,
230
+ ProductName: config.productName,
231
+ ProductVersion: config.version,
232
+ FileVersion: `${fv[0]}.${fv[1]}.${fv[2]}.0`,
233
+ InternalName: config.name,
234
+ OriginalFilename: exeFile,
235
+ CompanyName: w.company,
236
+ LegalCopyright: w.copyright,
237
+ Comments: w.description,
238
+ },
239
+ }),
240
+ subsystem: options.console || w.console ? "console" : "gui",
241
+ log,
242
+ });
243
+ return { exe, payload: stamped.payload, stamp: stamped, bundle: null };
244
+ }
245
+
246
+ export function macInfoFor(config: AppConfig, hasIcon: boolean) {
247
+ const m = config.macos;
248
+ const fv = numericVersion(config.version);
249
+ return {
250
+ bundleId: m.bundleId,
251
+ name: config.productName,
252
+ executable: m.exeName,
253
+ // CFBundleShortVersionString is three integers; a prerelease tag has no place in it.
254
+ version: `${fv[0]}.${fv[1]}.${fv[2]}`,
255
+ iconFile: hasIcon ? ICON_NAME : null,
256
+ minimumSystemVersion: m.minimumSystemVersion,
257
+ category: m.category,
258
+ copyright: m.copyright,
259
+ microphoneUsageDescription: m.microphoneUsageDescription,
260
+ cameraUsageDescription: m.cameraUsageDescription,
261
+ urlSchemes: config.launch.protocols,
262
+ };
263
+ }
264
+
265
+ function macBundle({ config, host, inputs, packs, outDir, work, options, warnings, log }: PackageInput): Packaged {
266
+ const m = config.macos;
267
+ if (m.bundleIdFrom === "id" && !m.bundleId.includes(".")) {
268
+ warnings.push(
269
+ `the bundle identifier is ${JSON.stringify(m.bundleId)} (from "id") — set sk.config.json "macos.bundleId" ` +
270
+ 'to a reverse-DNS id such as "com.example.app"; signing and notarisation expect one',
271
+ );
272
+ }
273
+ // The host maps app.skpk from offset 0, so the data region must be page-aligned in the FILE.
274
+ const unskewed = writeSkpk(inputs);
275
+ const skew = skewFor(0, readHeader(unskewed));
276
+ const payload = skew ? writeSkpk(inputs, { skew }) : unskewed;
277
+
278
+ const icon = m.iconPath ? icnsFrom(m.iconPath) : null;
279
+ if (icon && !icon.verbatim && Math.max(...icon.sizes) < 512) {
280
+ warnings.push(
281
+ `${m.iconPath} is ${Math.max(...icon.sizes)} px at most — the Dock and Finder draw up to 1024 px (512@2x); a 1024 px PNG stays sharp`,
282
+ );
283
+ }
284
+ const info = macInfoFor(config, !!icon);
285
+ const entitlementsPath = join(work, "entitlements.plist");
286
+ writeFileSync(entitlementsPath, plistXml(entitlements(info)));
287
+
288
+ const written = writeAppBundle({
289
+ host: host.exe,
290
+ out: join(outDir, `${m.exeName}.app`),
291
+ executable: m.exeName,
292
+ payload,
293
+ icns: icon?.bytes ?? null,
294
+ infoPlist: plistXml(infoPlist(info)),
295
+ log,
296
+ });
297
+ for (const p of packs) writeFileSync(join(written.app, "Contents", "Resources", p.file), p.blob);
298
+
299
+ const onMac = process.platform === "darwin";
300
+ const plan = signPlan({
301
+ want: options.sign ?? m.sign,
302
+ app: written.app,
303
+ entitlements: entitlementsPath,
304
+ codesign: onMac ? Bun.which("codesign") : null,
305
+ onMac,
306
+ });
307
+ if (plan.identity) signBundle(Bun.which("codesign")!, written.app, plan.identity, entitlementsPath, log);
308
+ return {
309
+ exe: written.executable,
310
+ payload,
311
+ stamp: null,
312
+ bundle: {
313
+ ...written,
314
+ bundleId: m.bundleId,
315
+ iconSizes: icon?.sizes ?? [],
316
+ signed: plan.identity,
317
+ signNote: plan.note,
318
+ entitlements: entitlementsPath,
319
+ },
320
+ };
321
+ }
322
+
323
+ function linuxExe({ config, host, inputs, packs, outDir }: PackageInput): Packaged {
324
+ for (const p of packs) writeFileSync(join(outDir, p.file), p.blob);
325
+ const elf = stampElf({
326
+ host: host.exe,
327
+ out: join(outDir, config.exeName),
328
+ payload: (skew) => writeSkpk(inputs, { skew }),
329
+ });
330
+ return { exe: elf.out, payload: elf.payload, stamp: null, bundle: null, elf };
331
+ }
332
+
333
+ const PACKAGERS: Record<Platform, (input: PackageInput) => Packaged> = {
334
+ windows: stampExe,
335
+ macos: macBundle,
336
+ linux: linuxExe,
337
+ };
338
+
339
+ export async function buildApp(options: BuildOptions): Promise<BuildResult> {
340
+ const progress = options.progress ?? (options.log ? lineProgress(options.log, false) : progressFor(process.stderr));
341
+ try {
342
+ return await build(options, progress);
343
+ } finally {
344
+ if (!options.progress) progress.end();
345
+ }
346
+ }
347
+
348
+ const kib = (n: number) => `${(n / 1024).toFixed(0)} KiB`;
349
+ const mib = (n: number) => `${(n / 2 ** 20).toFixed(1)} MiB`;
350
+
351
+ async function build(options: BuildOptions, progress: Progress): Promise<BuildResult> {
352
+ const log = logTo(progress);
353
+ const t0 = performance.now();
354
+ const platform = options.platform ?? currentPlatform();
355
+ const config = loadAppConfig(options.target, { configPath: options.configPath, platform });
356
+ const warnings = [...config.warnings];
357
+ const asked: Variant = options.variant ?? modeVariant(config, options.mode);
358
+ partsLeftOut(asked);
359
+ warnings.push(...variantWarnings(asked));
360
+ const outDir = resolve(options.out ?? join(config.appRoot, "dist", ...(options.mode ? [options.mode] : [])));
361
+ const work = join(outDir, ".sk");
362
+ mkdirSync(work, { recursive: true });
363
+
364
+ // The host first: a missing or mismatched host should fail before a bundle is spent on it.
365
+ if (!options.payloadOnly) progress.step("host");
366
+ const host = options.payloadOnly
367
+ ? null
368
+ : await resolveOrFetchHost({
369
+ host: options.host,
370
+ variant: asked,
371
+ allowMismatch: options.allowHostMismatch,
372
+ platform,
373
+ log,
374
+ });
375
+ if (host) {
376
+ progress.detail(`${host.info.variant} · Skathi ${host.info.skathi} ${host.info.profile} · ${host.source}`);
377
+ if (host.unverified) warnings.push(host.unverified);
378
+ if (host.substitute) warnings.push(host.substitute);
379
+ }
380
+ // The payload names the host it runs on, which a stand-in changes.
381
+ const variant: Variant = host?.substitute ? host.info.variant : asked;
382
+
383
+ const jsOut = join(work, "app.prod.js");
384
+ const assetsJson = join(work, "assets.json");
385
+ // A stale list from an older build must not survive a builder that wrote none.
386
+ rmSync(assetsJson, { force: true });
387
+ const tb = performance.now();
388
+ const defineArgs = (options.defines ?? []).map((d) => `--define=${d}`);
389
+ const pathArgs = [
390
+ `--app-root=${config.appRoot}`,
391
+ ...(config.configPath ? [`--config=${config.configPath}`] : []),
392
+ ...(options.aotInputs ? [`--aot-inputs=${join(work, "aot-inputs")}`] : []),
393
+ ...(options.mode === "debug" ? ["--no-minify"] : []),
394
+ ];
395
+ progress.step("bundle");
396
+ const child = Bun.spawn([process.execPath, PROD_TS, config.entry, jsOut, ...pathArgs, ...defineArgs], {
397
+ cwd: PKG_DIR,
398
+ stdout: "pipe",
399
+ stderr: "pipe",
400
+ });
401
+ const [stdout, stderr, status] = await Promise.all([
402
+ new Response(child.stdout).text(),
403
+ new Response(child.stderr).text(),
404
+ child.exited,
405
+ ]);
406
+ if (status !== 0 || !existsSync(jsOut)) {
407
+ throw new Error(`the production bundle of ${config.entry} failed\n${stdout}${stderr}`.trimEnd());
408
+ }
409
+ for (const line of `${stdout}${stderr}`.trim().split(/\r?\n/)) {
410
+ if (!line) continue;
411
+ const text = line.replace(/^\[prod\] /, "");
412
+ const made = /^prod build: (.*?) -> /.exec(text);
413
+ if (made) progress.detail(made[1]!);
414
+ else if (text.startsWith("advisory: ")) progress.warn(text.slice("advisory: ".length));
415
+ else progress.info(text);
416
+ }
417
+ const script = readFileSync(jsOut);
418
+ const windowJson = readFileSync(join(work, "window.json"));
419
+ const msBundle = performance.now() - tb;
420
+
421
+ progress.step("assets");
422
+ const ta = performance.now();
423
+ const collected = collectAssets(config.appRoot, config.assets, config.assetsDeclared, config.publicDir);
424
+ warnings.push(...collected.warnings);
425
+ // What the bundle's imports referred to (`?url`, image imports): they live under src/ or in a
426
+ // package, which the "assets" walk never packages, so they are added here.
427
+ const known = new Map(collected.files.map((f) => [f.key, f]));
428
+ for (const a of readBuilderAssets(assetsJson)) {
429
+ const prev = known.get(a.key);
430
+ if (prev) {
431
+ if (resolve(prev.path) !== resolve(a.path)) {
432
+ warnings.push(
433
+ `${JSON.stringify(a.key)}: an import refers to ${a.path}, but "assets" packages ${prev.path} under that key — the import's file wins`,
434
+ );
435
+ prev.path = a.path;
436
+ prev.size = statSync(a.path).size;
437
+ }
438
+ continue;
439
+ }
440
+ const file: AssetFile = { key: a.key, path: a.path, size: statSync(a.path).size };
441
+ known.set(a.key, file);
442
+ collected.files.push(file);
443
+ }
444
+ collected.files.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
445
+ collected.totalBytes = collected.files.reduce((n, f) => n + f.size, 0);
446
+ const msAssets = performance.now() - ta;
447
+ if (collected.totalBytes > MAX_PAYLOAD_BYTES) {
448
+ throw new Error(
449
+ `the assets are ${(collected.totalBytes / 2 ** 20).toFixed(0)} MiB — more than a single exe should carry ` +
450
+ `(limit ${MAX_PAYLOAD_BYTES / 2 ** 20} MiB). Ship large media beside the exe instead.`,
451
+ );
452
+ }
453
+ if (collected.totalBytes > WARN_PAYLOAD_BYTES) {
454
+ warnings.push(`the assets are ${(collected.totalBytes / 2 ** 20).toFixed(0)} MiB — every byte is inside the exe`);
455
+ }
456
+
457
+ const split = splitPacks(collected.files, config.packs);
458
+ const packs: BuiltPack[] = [];
459
+ for (const p of split.packs) {
460
+ if (!p.files.length) {
461
+ warnings.push(`sk.config.json "packs": ${JSON.stringify(p.name)} takes no asset — no ${p.name}.skpk is written`);
462
+ continue;
463
+ }
464
+ packs.push(writePack(p.name, p.files));
465
+ }
466
+ const inputs: SkpkInput[] = [
467
+ {
468
+ name: NAMES.META,
469
+ kind: KIND.META,
470
+ data: enc.encode(appMeta(config, variant, host, collected.files.length, packs)),
471
+ },
472
+ { name: NAMES.WINDOW, kind: KIND.WINDOW, data: windowJson },
473
+ { name: NAMES.SCRIPT, kind: KIND.SCRIPT, data: script },
474
+ ...split.own.map((f) => ({ name: f.key, kind: KIND.ASSET, data: new Uint8Array(readFileSync(f.path)) })),
475
+ ];
476
+ const skpk = join(work, "app.skpk");
477
+ for (const p of packs) writeFileSync(join(work, p.file), p.blob);
478
+ progress.detail(`${collected.files.length} files · ${kib(collected.totalBytes)}`);
479
+
480
+ let packaged: Packaged | null = null;
481
+ const ts = performance.now();
482
+ progress.step(options.payloadOnly || !host ? "payload" : platform === "macos" ? "app bundle" : "exe");
483
+ if (options.payloadOnly || !host) {
484
+ // An app split into packs ships app.skpk as a file mapped from offset 0: page-align its data.
485
+ const unskewed = writeSkpk(inputs);
486
+ const skew = packs.length ? skewFor(0, readHeader(unskewed)) : 0;
487
+ writeFileSync(skpk, skew ? writeSkpk(inputs, { skew }) : unskewed);
488
+ } else {
489
+ packaged = PACKAGERS[platform]({ config, host, inputs, packs, outDir, work, options, warnings, log });
490
+ writeFileSync(skpk, packaged.payload);
491
+ }
492
+ const msStamp = performance.now() - ts;
493
+ progress.detail(mib(packaged?.payload.length ?? readFileSync(skpk).length));
494
+ if (packaged?.bundle) progress.detail(mib(packaged.bundle.bytes));
495
+ else if (packaged?.stamp) progress.detail(mib(packaged.stamp.bytes));
496
+ else if (packaged?.elf) progress.detail(mib(packaged.elf.bytes));
497
+ progress.end();
498
+
499
+ for (const w of warnings) progress.warn(w);
500
+ return {
501
+ config,
502
+ platform,
503
+ variant,
504
+ exe: packaged?.exe ?? null,
505
+ skpk,
506
+ host,
507
+ stamp: packaged?.stamp ?? null,
508
+ bundle: packaged?.bundle ?? null,
509
+ elf: packaged?.elf ?? null,
510
+ assets: collected.files,
511
+ bundleBytes: script.length,
512
+ aotInputs: options.aotInputs ? join(work, "aot-inputs", "manifest.json") : null,
513
+ payloadBytes: packaged?.payload.length ?? readFileSync(skpk).length,
514
+ packs: packs.map((p) => ({
515
+ name: p.name,
516
+ path: join(work, p.file),
517
+ bytes: p.blob.length,
518
+ assets: p.assets.length,
519
+ })),
520
+ warnings,
521
+ ms: {
522
+ bundle: Math.round(msBundle),
523
+ assets: Math.round(msAssets),
524
+ stamp: Math.round(msStamp),
525
+ total: Math.round(performance.now() - t0),
526
+ },
527
+ };
528
+ }
529
+
530
+ export function summary(r: BuildResult, color = false): string {
531
+ const p = paint(color);
532
+ const c = r.config;
533
+ const storage =
534
+ r.platform === "macos"
535
+ ? `~/Library/Application Support/${c.name}/storage`
536
+ : r.platform === "linux"
537
+ ? `~/.local/share/${c.name}/storage`
538
+ : `%LOCALAPPDATA%\\${c.name}\\storage`;
539
+ const row = (label: string, text: string) => ` ${p.dim(label.padEnd(8))} ${text}`;
540
+ const bad = (ok: boolean, yes: string, no: string) => (ok ? yes : p.yellow(no));
541
+ const lines = [`${p.bold(`${c.productName} ${c.version}`)} ${p.dim(`name "${c.name}", storage ${storage}`)}`];
542
+ if (r.stamp && r.exe) {
543
+ const s = r.stamp;
544
+ lines.push(
545
+ row("exe", p.cyan(r.exe)),
546
+ row(
547
+ "",
548
+ `${mib(s.bytes)}, ${r.variant} host, subsystem ${s.subsystem === 2 ? "GUI" : "console"}, ` +
549
+ `${s.iconCount ? `${s.iconCount} icon` : "no icon"}, ` +
550
+ bad(s.dataAligned, "data page-aligned", "data NOT aligned"),
551
+ ),
552
+ );
553
+ }
554
+ if (r.elf) {
555
+ const e = r.elf;
556
+ lines.push(
557
+ row("exe", p.cyan(e.out)),
558
+ row(
559
+ "",
560
+ `${mib(e.bytes)}, ${r.variant} host (${e.machine}), payload appended at ${e.payloadOffset}, ` +
561
+ bad(e.dataAligned, "data page-aligned", "data NOT aligned"),
562
+ ),
563
+ );
564
+ }
565
+ if (r.bundle) {
566
+ const b = r.bundle;
567
+ const icon = b.iconSizes.length ? `icon ${b.iconSizes.join("/")} px` : "no icon";
568
+ const signed =
569
+ b.signed === "-" ? "signed ad hoc" : b.signed ? `signed as ${JSON.stringify(b.signed)}` : p.yellow("NOT signed");
570
+ lines.push(
571
+ row("app", p.cyan(b.app)),
572
+ row("", `${mib(b.bytes)}, ${r.variant} host, ${b.bundleId}, ${icon}, ${signed}`),
573
+ );
574
+ if (b.signNote) lines.push(row("", p.dim(b.signNote)));
575
+ }
576
+ lines.push(
577
+ row(
578
+ "bundle",
579
+ `${kib(r.bundleBytes)} script, ${r.assets.length} asset(s) ${kib(r.assets.reduce((n, a) => n + a.size, 0))}`,
580
+ ),
581
+ row("payload", `${kib(r.payloadBytes)} ${p.dim(r.skpk)}`),
582
+ );
583
+ for (const pk of r.packs)
584
+ lines.push(row("pack", `${pk.name}: ${pk.assets} asset(s), ${kib(pk.bytes)} ${p.dim(pk.path)}`));
585
+ lines.push(`${p.green("done")} in ${seconds(r.ms.total)}`);
586
+ return lines.join("\n");
587
+ }