@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/host.ts ADDED
@@ -0,0 +1,378 @@
1
+ // Where `sk build` gets the prebuilt bare host it stamps: `cargo build --release -p sk-app
2
+ // --features prod` (the whole engine, no app), built once per Skathi version and variant. A
3
+ // variant names the engine parts left out (config.ts `OPTIONAL`).
4
+ //
5
+ // Resolution, first hit wins: 1. `--host <exe>` or `SK_HOST`; 2. in-repo
6
+ // target/x86_64-pc-windows-msvc/release/sk-app.exe, when that is a prod host of this variant and
7
+ // version; 3. the local cache (`sk host add <exe>`, `sk host build`, or a download from this
8
+ // version's GitHub release: host-fetch.ts); 4. an error naming them. Paths per OS are in platform.ts.
9
+ //
10
+ // A host for another OS cannot be run to ask what it is: only `--host` / `SK_HOST` names one, its
11
+ // format is sniffed, and what it is comes from a `host.json` beside it or is taken on trust, with a warning.
12
+ //
13
+ // A host and a bundle must come from the same Skathi version (the bundle carries the JS half of
14
+ // the `__sk_*` protocol): the CLI refuses a host whose `--sk-host-info` disagrees
15
+ // (`--allow-host-mismatch` is for maintainers).
16
+
17
+ import { spawnSync } from "node:child_process";
18
+ import {
19
+ chmodSync,
20
+ copyFileSync,
21
+ existsSync,
22
+ mkdirSync,
23
+ readdirSync,
24
+ readFileSync,
25
+ renameSync,
26
+ rmSync,
27
+ statSync,
28
+ writeFileSync,
29
+ } from "node:fs";
30
+ import { homedir } from "node:os";
31
+ import { dirname, join, resolve } from "node:path";
32
+ import { cargoFeatureArgs, OPTIONAL, partsLeftOut, type Variant } from "./config";
33
+ import { appendedPayloadOf, elfMachineOf } from "./elf";
34
+ import { bundlePayloadPath, machOArchs } from "./macos-bundle";
35
+ import { readPe, RT } from "./pe";
36
+ import { currentPlatform, hostsFor, repoHostExe, type Platform } from "./platform";
37
+ import { PAYLOAD_NAME } from "./stamp";
38
+
39
+ export const PKG_DIR = resolve(import.meta.dir, "..");
40
+ export const CLI_VERSION: string = JSON.parse(readFileSync(join(PKG_DIR, "package.json"), "utf8")).version;
41
+
42
+ export const REPO_ROOT: string | null = (() => {
43
+ const root = resolve(PKG_DIR, "../..");
44
+ return existsSync(join(root, "Cargo.toml")) && existsSync(join(root, "crates", "sk-app")) ? root : null;
45
+ })();
46
+
47
+ export const REPO_RELEASE_EXE = REPO_ROOT ? repoHostExe(REPO_ROOT, hostsFor(currentPlatform()), "release") : null;
48
+
49
+ export interface HostInfo {
50
+ mode: "prod" | "dev";
51
+ skathi: string;
52
+ crate: string;
53
+ variant: Variant;
54
+ devtools: boolean;
55
+ features: string[];
56
+ jscPin: string;
57
+ payloadFormat: number;
58
+ profile: string;
59
+ }
60
+
61
+ export interface ResolvedHost {
62
+ exe: string;
63
+ info: HostInfo;
64
+ source: "--host" | "SK_HOST" | "repo" | "cache";
65
+ unverified?: string;
66
+ }
67
+
68
+ export class HostError extends Error {}
69
+
70
+ /** True when `exe` already carries an app (asking it for host info would launch it): a stamped resource on Windows, `Contents/Resources/app.skpk` on macOS, an appended payload on Linux. */
71
+ export function isStamped(exe: string): boolean {
72
+ const bundled = bundlePayloadPath(exe);
73
+ if (bundled && existsSync(bundled)) return true;
74
+ if (appendedPayloadOf(exe)) return true;
75
+ try {
76
+ return readPe(exe).resources.some((r) => r.type === RT.RCDATA && r.name === PAYLOAD_NAME);
77
+ } catch {
78
+ return false;
79
+ }
80
+ }
81
+
82
+ function formatProblem(exe: string, platform: Platform): string | null {
83
+ if (platform === "windows") return null;
84
+ if (platform === "linux") {
85
+ const machine = elfMachineOf(exe);
86
+ if (!machine) return `${exe} is not an ELF executable — a Linux build needs a Linux sk-app`;
87
+ if (machine !== "x86_64" && machine !== "aarch64") return `${exe} is an ELF for ${machine}, not x86_64 or aarch64`;
88
+ return null;
89
+ }
90
+ const archs = machOArchs(exe);
91
+ if (!archs) return `${exe} is not a Mach-O executable — a macOS bundle needs a macOS sk-app`;
92
+ if (!archs.some((a) => a === "arm64" || a === "x86_64"))
93
+ return `${exe} is a Mach-O for ${archs.join(", ")}, not arm64 or x86_64`;
94
+ return null;
95
+ }
96
+
97
+ export function crossHostInfo(
98
+ exe: string,
99
+ variant: Variant,
100
+ platform: Platform,
101
+ ): { info: HostInfo; unverified: string } {
102
+ const problem = formatProblem(exe, platform);
103
+ if (problem) throw new HostError(problem);
104
+ const sidecar = join(dirname(exe), "host.json");
105
+ if (existsSync(sidecar)) {
106
+ try {
107
+ const info = JSON.parse(readFileSync(sidecar, "utf8")) as HostInfo;
108
+ if (info.mode && info.skathi && info.variant) {
109
+ return { info, unverified: `${platform} host described by ${sidecar}, not run (this is ${process.platform})` };
110
+ }
111
+ } catch {}
112
+ }
113
+ const off = partsLeftOut(variant);
114
+ const info: HostInfo = {
115
+ mode: "prod",
116
+ skathi: CLI_VERSION,
117
+ crate: "unknown",
118
+ variant,
119
+ devtools: !off.includes("devtools"),
120
+ features: ["prod", ...OPTIONAL.filter((p) => p !== "devtools" && !off.includes(p))],
121
+ jscPin: "unknown",
122
+ payloadFormat: 1,
123
+ profile: "unknown",
124
+ };
125
+ return {
126
+ info,
127
+ unverified:
128
+ `a ${platform} host cannot be run on ${process.platform} to check it — ${exe} is taken to be a prod ${variant} host ` +
129
+ `of Skathi ${CLI_VERSION}. Put its \`--sk-host-info\` output in ${sidecar} to have it checked.`,
130
+ };
131
+ }
132
+
133
+ export function hostInfo(exe: string): HostInfo {
134
+ if (!existsSync(exe)) throw new HostError(`${exe} does not exist`);
135
+ if (isStamped(exe)) {
136
+ throw new HostError(`${exe} is a packaged app, not a bare host (it already carries a SKPAYLOAD)`);
137
+ }
138
+ const r = spawnSync(exe, ["--sk-host-info"], { encoding: "utf8", timeout: 30_000, windowsHide: true });
139
+ if (r.error) throw new HostError(`${exe} could not be run: ${r.error.message}`);
140
+ const line = (r.stdout ?? "").trim().split(/\r?\n/).pop() ?? "";
141
+ try {
142
+ const info = JSON.parse(line) as HostInfo;
143
+ if (!info.mode || !info.skathi) throw new Error("missing fields");
144
+ return info;
145
+ } catch {
146
+ throw new HostError(
147
+ `${exe} did not answer --sk-host-info (exit ${r.status}). Hosts older than this CLI do not know the flag — ` +
148
+ `rebuild it.\n${(r.stderr ?? "").trim().split(/\r?\n/).slice(-5).join("\n")}`,
149
+ );
150
+ }
151
+ }
152
+
153
+ export function cacheRoot(platform: Platform = currentPlatform()): string {
154
+ return hostsFor(platform).cacheRoot();
155
+ }
156
+
157
+ export const cachedHost = (version: string, variant: Variant, platform: Platform = currentPlatform()) =>
158
+ join(cacheRoot(platform), version, variant, hostsFor(platform).cachedFile);
159
+
160
+ /** The host `sk dev` runs: every part, built without `prod`, so it reads a dev dist and hot-reloads. Cached and released beside the prod variants under this name. */
161
+ export const DEV_HOST: Variant = "dev";
162
+
163
+ export function checkHost(exe: string, info: HostInfo, variant: Variant | null, allowMismatch: boolean): string | null {
164
+ const mismatch =
165
+ info.skathi !== CLI_VERSION && !allowMismatch
166
+ ? `${exe} is Skathi ${info.skathi}, this CLI is ${CLI_VERSION} — the bundle carries the JS half of the ` +
167
+ `host protocol, so the two must match (--allow-host-mismatch overrides, for maintainers)`
168
+ : null;
169
+ if (variant === DEV_HOST) {
170
+ return info.mode === "dev"
171
+ ? mismatch
172
+ : `${exe} is a ${info.mode} host — sk dev needs one built without --features prod`;
173
+ }
174
+ if (info.mode !== "prod") return `${exe} is a ${info.mode} host — sk build needs one built with --features prod`;
175
+ if (variant && info.variant !== variant) return `${exe} is the ${info.variant} variant, not ${variant}`;
176
+ if (!partsLeftOut(variant ?? info.variant).includes("webgpu") && !info.features?.includes("webgpu")) {
177
+ return `${exe} lacks native WebGPU required by ${variant} — rebuild or replace the cached host`;
178
+ }
179
+ return mismatch;
180
+ }
181
+
182
+ function newestHostSource(): number {
183
+ if (!REPO_ROOT) return 0;
184
+ let newest = 0;
185
+ const visit = (dir: string) => {
186
+ let names: string[];
187
+ try {
188
+ names = readdirSync(dir);
189
+ } catch {
190
+ return;
191
+ }
192
+ for (const name of names) {
193
+ if (name === "node_modules" || name === "target" || name.startsWith(".")) continue;
194
+ const abs = join(dir, name);
195
+ let st;
196
+ try {
197
+ st = statSync(abs);
198
+ } catch {
199
+ continue;
200
+ }
201
+ if (st.isDirectory()) visit(abs);
202
+ else if (/\.(rs|toml|ts|vue|json)$/.test(name)) newest = Math.max(newest, st.mtimeMs);
203
+ }
204
+ };
205
+ visit(join(REPO_ROOT, "crates"));
206
+ visit(join(REPO_ROOT, "apps", "devtools"));
207
+ visit(join(REPO_ROOT, "packages", "runtime", "src"));
208
+ for (const f of ["Cargo.toml", "Cargo.lock"]) {
209
+ try {
210
+ newest = Math.max(newest, statSync(join(REPO_ROOT, f)).mtimeMs);
211
+ } catch {}
212
+ }
213
+ return newest;
214
+ }
215
+
216
+ export interface ResolveOptions {
217
+ host?: string | undefined;
218
+ variant: Variant;
219
+ allowMismatch?: boolean | undefined;
220
+ platform?: Platform | undefined;
221
+ log?: (line: string) => void;
222
+ }
223
+
224
+ export function resolveHost(options: ResolveOptions): ResolvedHost {
225
+ const log = options.log ?? (() => {});
226
+ const allow = options.allowMismatch ?? false;
227
+ const platform = options.platform ?? currentPlatform();
228
+ const cross = platform !== currentPlatform();
229
+ const explicit = options.host ?? process.env.SK_HOST;
230
+ if (explicit) {
231
+ const exe = resolve(explicit);
232
+ const source = options.host ? "--host" : "SK_HOST";
233
+ if (cross) {
234
+ if (!existsSync(exe)) throw new HostError(`${exe} does not exist`);
235
+ if (isStamped(exe))
236
+ throw new HostError(`${exe} is a packaged app, not a bare host (it already carries an app payload)`);
237
+ const { info, unverified } = crossHostInfo(exe, options.variant, platform);
238
+ const problem = checkHost(exe, info, options.variant, allow);
239
+ if (problem) throw new HostError(problem);
240
+ return { exe, info, source, unverified };
241
+ }
242
+ const format = existsSync(exe) ? formatProblem(exe, platform) : null;
243
+ if (format) throw new HostError(format);
244
+ const info = hostInfo(exe);
245
+ const problem = checkHost(exe, info, options.variant, allow);
246
+ if (problem) throw new HostError(problem);
247
+ return { exe, info, source };
248
+ }
249
+ if (cross) {
250
+ throw new HostError(
251
+ `a ${platform} build on ${process.platform} needs the host named: --host <path to a ${platform} sk-app> ` +
252
+ `(or SK_HOST). This machine's checkout and cache hold ${currentPlatform()} hosts.`,
253
+ );
254
+ }
255
+
256
+ const tried: string[] = [];
257
+ if (REPO_RELEASE_EXE && existsSync(REPO_RELEASE_EXE)) {
258
+ try {
259
+ const info = hostInfo(REPO_RELEASE_EXE);
260
+ const problem = checkHost(REPO_RELEASE_EXE, info, options.variant, allow);
261
+ if (!problem) {
262
+ if (statSync(REPO_RELEASE_EXE).mtimeMs < newestHostSource()) {
263
+ log(
264
+ `warning: ${REPO_RELEASE_EXE} is older than the sources it is built from — ` +
265
+ "`bun packages/cli/cli/sk.ts host build` rebuilds it",
266
+ );
267
+ }
268
+ return { exe: REPO_RELEASE_EXE, info, source: "repo" };
269
+ }
270
+ tried.push(`in-repo: ${problem}`);
271
+ } catch (e) {
272
+ tried.push(`in-repo: ${(e as Error).message}`);
273
+ }
274
+ } else if (REPO_RELEASE_EXE) {
275
+ tried.push(`in-repo: ${REPO_RELEASE_EXE} has not been built`);
276
+ }
277
+
278
+ const cached = cachedHost(CLI_VERSION, options.variant);
279
+ if (existsSync(cached)) {
280
+ const info = hostInfo(cached);
281
+ const problem = checkHost(cached, info, options.variant, allow);
282
+ if (!problem) return { exe: cached, info, source: "cache" };
283
+ tried.push(`cache: ${problem}`);
284
+ } else {
285
+ tried.push(`cache: ${cached} does not exist`);
286
+ }
287
+
288
+ throw new HostError(
289
+ `no ${options.variant} Skathi ${CLI_VERSION} host found.\n` +
290
+ tried.map((t) => ` - ${t}`).join("\n") +
291
+ "\nSupply one of:\n" +
292
+ ` ${`--host <${hostsFor(platform).exeFile}>`.padEnd(21)}(or SK_HOST=<exe>) a prod host built from this version\n` +
293
+ ` sk host fetch download it from the Skathi ${CLI_VERSION} release\n` +
294
+ " sk host add <exe> import one into the local cache\n" +
295
+ (REPO_ROOT
296
+ ? options.variant === "standard" || options.variant === "no-devtools"
297
+ ? " sk host build build both variants from this checkout (cargo)\n"
298
+ : ` sk host build --variant ${options.variant} build this one from this checkout (cargo)\n`
299
+ : ""),
300
+ );
301
+ }
302
+
303
+ export function addHost(exe: string, log: (line: string) => void = () => {}): { path: string; info: HostInfo } {
304
+ const src = resolve(exe);
305
+ const info = hostInfo(src);
306
+ const problem = checkHost(src, info, null, true);
307
+ if (problem) throw new HostError(problem);
308
+ const dest = cachedHost(info.skathi, info.variant);
309
+ mkdirSync(dirname(dest), { recursive: true });
310
+ const tmp = `${dest}.partial`;
311
+ copyFileSync(src, tmp);
312
+ // A POSIX host must stay runnable whatever mode the source had.
313
+ if (process.platform !== "win32") chmodSync(tmp, 0o755);
314
+ rmSync(dest, { force: true });
315
+ renameSync(tmp, dest);
316
+ writeFileSync(join(dirname(dest), "host.json"), JSON.stringify(info, null, 2) + "\n");
317
+ log(`cached ${info.variant} host ${info.skathi} (${info.profile}) → ${dest}`);
318
+ return { path: dest, info };
319
+ }
320
+
321
+ function cargo(): string {
322
+ const which = Bun.which("cargo");
323
+ if (which) return which;
324
+ const home = process.env.CARGO_HOME ?? join(process.env.USERPROFILE ?? homedir(), ".cargo");
325
+ const exe = join(home, "bin", process.platform === "win32" ? "cargo.exe" : "cargo");
326
+ if (existsSync(exe)) return exe;
327
+ throw new HostError("cargo is not on PATH — building a host needs the Rust toolchain (sk build does not)");
328
+ }
329
+
330
+ /** The cargo command line for `variant`, plus `extra` features (`native-inspector` for a release host). */
331
+ export function hostCargoArgs(variant: Variant, extra: string[] = []): string[] {
332
+ const args = variant === DEV_HOST ? [] : cargoFeatureArgs(variant);
333
+ const at = args.indexOf("--features");
334
+ if (extra.length) {
335
+ if (at < 0) args.push("--features", extra.join(","));
336
+ else args[at + 1] = [args[at + 1], ...extra].join(",");
337
+ }
338
+ return ["build", "--release", "-p", "sk-app", ...hostsFor(currentPlatform()).cargoTarget, ...args];
339
+ }
340
+
341
+ export interface CargoExtras {
342
+ features?: string[];
343
+ env?: Record<string, string>;
344
+ }
345
+
346
+ /** MAINTAINERS ONLY, in a checkout: cargo-builds the bare host for `variant` into the checkout's target/; returns its path. */
347
+ export function cargoBuildHost(
348
+ variant: Variant,
349
+ log: (line: string) => void = console.log,
350
+ extras: CargoExtras = {},
351
+ ): { exe: string; ms: number } {
352
+ if (!REPO_ROOT || !REPO_RELEASE_EXE) {
353
+ throw new HostError("sk host build runs from a Skathi checkout; elsewhere, use sk host fetch or sk host add <exe>");
354
+ }
355
+ const args = hostCargoArgs(variant, extras.features);
356
+ log(`cargo ${args.join(" ")}`);
357
+ const t0 = performance.now();
358
+ const r = spawnSync(cargo(), args, {
359
+ cwd: REPO_ROOT,
360
+ stdio: "inherit",
361
+ env: { ...process.env, ...extras.env },
362
+ });
363
+ if (r.status !== 0) throw new HostError(`cargo ${args.join(" ")} failed (exit ${r.status})`);
364
+ return { exe: REPO_RELEASE_EXE, ms: Math.round(performance.now() - t0) };
365
+ }
366
+
367
+ /** MAINTAINERS ONLY, in a checkout: builds the bare host for `variant` and imports it into the cache. */
368
+ export function buildHost(
369
+ variant: Variant,
370
+ log: (line: string) => void = console.log,
371
+ ): { path: string; info: HostInfo; ms: number } {
372
+ const { exe, ms } = cargoBuildHost(variant, log);
373
+ const added = addHost(exe, log);
374
+ if (added.info.variant !== variant) {
375
+ throw new HostError(`built the ${variant} variant but the exe reports ${added.info.variant}`);
376
+ }
377
+ return { ...added, ms };
378
+ }
package/cli/icon.ts ADDED
@@ -0,0 +1,303 @@
1
+ // The exe's icon: `RT_ICON` 1..n plus `RT_GROUP_ICON` 1. Id 1 is not our choice: gpui's window class
2
+ // loads `MAKEINTRESOURCE(1)`, so a group icon under that id lands on the window, taskbar, Alt-Tab
3
+ // and the file in Explorer.
4
+ //
5
+ // Two inputs: an `.ico`, taken verbatim; or a square 8-bit `.png`, which becomes PNG-compressed
6
+ // images at 256 (the file itself when already 256), 48, 32, 24 and 16. Anything else is an error.
7
+
8
+ import { readFileSync } from "node:fs";
9
+ import { extname } from "node:path";
10
+ import { deflateSync, inflateSync } from "node:zlib";
11
+ import { crc32 } from "./skpk";
12
+
13
+ export interface IconImage {
14
+ width: number;
15
+ height: number;
16
+ bitCount: number;
17
+ planes: number;
18
+ colorCount: number;
19
+ data: Uint8Array;
20
+ }
21
+
22
+ export const PNG_ICON_SIZES = [256, 48, 32, 24, 16];
23
+
24
+ const PNG_SIG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
25
+
26
+ export interface Rgba {
27
+ width: number;
28
+ height: number;
29
+ data: Uint8Array;
30
+ }
31
+
32
+ export function isPng(bytes: Uint8Array): boolean {
33
+ return PNG_SIG.every((b, i) => bytes[i] === b);
34
+ }
35
+
36
+ const be32 = (b: Uint8Array, o: number) => ((b[o]! << 24) | (b[o + 1]! << 16) | (b[o + 2]! << 8) | b[o + 3]!) >>> 0;
37
+
38
+ export function decodePng(bytes: Uint8Array, label = "png"): Rgba {
39
+ if (!isPng(bytes)) throw new Error(`${label}: not a PNG`);
40
+ let o = 8;
41
+ let width = 0;
42
+ let height = 0;
43
+ let depth = 0;
44
+ let color = 0;
45
+ let interlace = 0;
46
+ let palette: Uint8Array | null = null;
47
+ let trns: Uint8Array | null = null;
48
+ const idat: Uint8Array[] = [];
49
+ while (o + 8 <= bytes.length) {
50
+ const len = be32(bytes, o);
51
+ const type = String.fromCharCode(...bytes.subarray(o + 4, o + 8));
52
+ const body = bytes.subarray(o + 8, o + 8 + len);
53
+ o += 12 + len;
54
+ if (type === "IHDR") {
55
+ width = be32(body, 0);
56
+ height = be32(body, 4);
57
+ depth = body[8]!;
58
+ color = body[9]!;
59
+ interlace = body[12]!;
60
+ } else if (type === "PLTE") palette = body;
61
+ else if (type === "tRNS") trns = body;
62
+ else if (type === "IDAT") idat.push(body);
63
+ else if (type === "IEND") break;
64
+ }
65
+ if (!width || !height) throw new Error(`${label}: no IHDR`);
66
+ if (depth !== 8 || interlace !== 0 || ![0, 2, 3, 4, 6].includes(color)) {
67
+ throw new Error(
68
+ `${label}: only 8-bit, non-interlaced PNGs are converted (this one is ${depth}-bit, colour type ${color}` +
69
+ `${interlace ? ", interlaced" : ""}) — give windows.icon an .ico instead`,
70
+ );
71
+ }
72
+ const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[color]!;
73
+ const stride = width * channels;
74
+ const total = idat.reduce((n, c) => n + c.length, 0);
75
+ const z = new Uint8Array(total);
76
+ let zo = 0;
77
+ for (const c of idat) {
78
+ z.set(c, zo);
79
+ zo += c.length;
80
+ }
81
+ const raw = new Uint8Array(inflateSync(z));
82
+ if (raw.length < (stride + 1) * height) throw new Error(`${label}: truncated image data`);
83
+ const px = new Uint8Array(stride * height);
84
+ const bpp = channels;
85
+ for (let y = 0; y < height; y++) {
86
+ const filter = raw[y * (stride + 1)]!;
87
+ const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1));
88
+ const cur = px.subarray(y * stride, (y + 1) * stride);
89
+ const prev = y ? px.subarray((y - 1) * stride, y * stride) : new Uint8Array(stride);
90
+ for (let x = 0; x < stride; x++) {
91
+ const a = x >= bpp ? cur[x - bpp]! : 0;
92
+ const b = prev[x]!;
93
+ const c = x >= bpp ? prev[x - bpp]! : 0;
94
+ let v = line[x]!;
95
+ if (filter === 1) v += a;
96
+ else if (filter === 2) v += b;
97
+ else if (filter === 3) v += (a + b) >> 1;
98
+ else if (filter === 4) {
99
+ const p = a + b - c;
100
+ const pa = Math.abs(p - a);
101
+ const pb = Math.abs(p - b);
102
+ const pc = Math.abs(p - c);
103
+ v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
104
+ } else if (filter !== 0) throw new Error(`${label}: bad filter ${filter} on row ${y}`);
105
+ cur[x] = v & 0xff;
106
+ }
107
+ }
108
+ const out = new Uint8Array(width * height * 4);
109
+ for (let i = 0; i < width * height; i++) {
110
+ let r = 0;
111
+ let g = 0;
112
+ let b = 0;
113
+ let a = 255;
114
+ if (color === 0) r = g = b = px[i]!;
115
+ else if (color === 4) {
116
+ r = g = b = px[i * 2]!;
117
+ a = px[i * 2 + 1]!;
118
+ } else if (color === 2) {
119
+ r = px[i * 3]!;
120
+ g = px[i * 3 + 1]!;
121
+ b = px[i * 3 + 2]!;
122
+ } else if (color === 6) {
123
+ r = px[i * 4]!;
124
+ g = px[i * 4 + 1]!;
125
+ b = px[i * 4 + 2]!;
126
+ a = px[i * 4 + 3]!;
127
+ } else {
128
+ const idx = px[i]!;
129
+ if (!palette || idx * 3 + 2 >= palette.length) throw new Error(`${label}: palette index ${idx} out of range`);
130
+ r = palette[idx * 3]!;
131
+ g = palette[idx * 3 + 1]!;
132
+ b = palette[idx * 3 + 2]!;
133
+ a = trns && idx < trns.length ? trns[idx]! : 255;
134
+ }
135
+ out[i * 4] = r;
136
+ out[i * 4 + 1] = g;
137
+ out[i * 4 + 2] = b;
138
+ out[i * 4 + 3] = a;
139
+ }
140
+ return { width, height, data: out };
141
+ }
142
+
143
+ function chunk(type: string, body: Uint8Array): Uint8Array {
144
+ const out = new Uint8Array(12 + body.length);
145
+ const dv = new DataView(out.buffer);
146
+ dv.setUint32(0, body.length);
147
+ for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i);
148
+ out.set(body, 8);
149
+ dv.setUint32(8 + body.length, crc32(out.subarray(4, 8 + body.length)));
150
+ return out;
151
+ }
152
+
153
+ export function encodePng(img: Rgba): Uint8Array {
154
+ const { width, height, data } = img;
155
+ const stride = width * 4;
156
+ const raw = new Uint8Array((stride + 1) * height);
157
+ for (let y = 0; y < height; y++) {
158
+ raw[y * (stride + 1)] = 0;
159
+ raw.set(data.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1);
160
+ }
161
+ const ihdr = new Uint8Array(13);
162
+ const dv = new DataView(ihdr.buffer);
163
+ dv.setUint32(0, width);
164
+ dv.setUint32(4, height);
165
+ ihdr[8] = 8;
166
+ ihdr[9] = 6;
167
+ const parts = [
168
+ new Uint8Array(PNG_SIG),
169
+ chunk("IHDR", ihdr),
170
+ chunk("IDAT", new Uint8Array(deflateSync(raw, { level: 9 }))),
171
+ chunk("IEND", new Uint8Array(0)),
172
+ ];
173
+ const n = parts.reduce((a, p) => a + p.length, 0);
174
+ const out = new Uint8Array(n);
175
+ let o = 0;
176
+ for (const p of parts) {
177
+ out.set(p, o);
178
+ o += p.length;
179
+ }
180
+ return out;
181
+ }
182
+
183
+ export function resizeRgba(src: Rgba, dw: number, dh: number): Rgba {
184
+ const { width: sw, height: sh, data } = src;
185
+ const out = new Uint8Array(dw * dh * 4);
186
+ const sx = sw / dw;
187
+ const sy = sh / dh;
188
+ for (let y = 0; y < dh; y++) {
189
+ const y0 = y * sy;
190
+ const y1 = y0 + sy;
191
+ for (let x = 0; x < dw; x++) {
192
+ const x0 = x * sx;
193
+ const x1 = x0 + sx;
194
+ let r = 0;
195
+ let g = 0;
196
+ let b = 0;
197
+ let a = 0;
198
+ let wsum = 0;
199
+ for (let yy = Math.floor(y0); yy < Math.ceil(y1); yy++) {
200
+ const wy = Math.min(yy + 1, y1) - Math.max(yy, y0);
201
+ if (wy <= 0) continue;
202
+ for (let xx = Math.floor(x0); xx < Math.ceil(x1); xx++) {
203
+ const wx = Math.min(xx + 1, x1) - Math.max(xx, x0);
204
+ if (wx <= 0) continue;
205
+ const w = wx * wy;
206
+ const i = (Math.min(yy, sh - 1) * sw + Math.min(xx, sw - 1)) * 4;
207
+ const pa = data[i + 3]! / 255;
208
+ r += data[i]! * pa * w;
209
+ g += data[i + 1]! * pa * w;
210
+ b += data[i + 2]! * pa * w;
211
+ a += pa * w;
212
+ wsum += w;
213
+ }
214
+ }
215
+ const o = (y * dw + x) * 4;
216
+ const alpha = wsum ? a / wsum : 0;
217
+ if (a > 0) {
218
+ out[o] = Math.round(r / a);
219
+ out[o + 1] = Math.round(g / a);
220
+ out[o + 2] = Math.round(b / a);
221
+ }
222
+ out[o + 3] = Math.round(alpha * 255);
223
+ }
224
+ }
225
+ return { width: dw, height: dh, data: out };
226
+ }
227
+
228
+ export function parseIco(bytes: Uint8Array, label = "ico"): IconImage[] {
229
+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
230
+ if (bytes.length < 6 || dv.getUint16(0, true) !== 0 || dv.getUint16(2, true) !== 1) {
231
+ throw new Error(`${label}: not an .ico (ICONDIR type must be 1)`);
232
+ }
233
+ const count = dv.getUint16(4, true);
234
+ if (!count) throw new Error(`${label}: the .ico holds no images`);
235
+ const images: IconImage[] = [];
236
+ for (let i = 0; i < count; i++) {
237
+ const e = 6 + i * 16;
238
+ if (e + 16 > bytes.length) throw new Error(`${label}: truncated ICONDIRENTRY ${i}`);
239
+ const size = dv.getUint32(e + 8, true);
240
+ const off = dv.getUint32(e + 12, true);
241
+ if (off + size > bytes.length) throw new Error(`${label}: image ${i} runs past the end of the file`);
242
+ images.push({
243
+ width: bytes[e]! || 256,
244
+ height: bytes[e + 1]! || 256,
245
+ colorCount: bytes[e + 2]!,
246
+ planes: dv.getUint16(e + 4, true),
247
+ bitCount: dv.getUint16(e + 6, true),
248
+ data: bytes.slice(off, off + size),
249
+ });
250
+ }
251
+ return images;
252
+ }
253
+
254
+ export function iconImagesFrom(path: string): IconImage[] {
255
+ const bytes = new Uint8Array(readFileSync(path));
256
+ const ext = extname(path).toLowerCase();
257
+ if (ext === ".ico") return parseIco(bytes, path);
258
+ if (ext !== ".png" && !isPng(bytes)) {
259
+ throw new Error(`${path}: windows.icon must be an .ico or a square .png`);
260
+ }
261
+ const img = decodePng(bytes, path);
262
+ if (img.width !== img.height) {
263
+ throw new Error(
264
+ `${path}: a PNG icon must be square (this one is ${img.width}×${img.height}) — give an .ico instead`,
265
+ );
266
+ }
267
+ if (img.width < 16) throw new Error(`${path}: ${img.width}px is smaller than the smallest icon size (16)`);
268
+ const sizes = PNG_ICON_SIZES.filter((s) => s <= img.width);
269
+ if (img.width < 256 && !sizes.includes(img.width)) sizes.unshift(img.width);
270
+ return sizes.map((s) => ({
271
+ width: s,
272
+ height: s,
273
+ bitCount: 32,
274
+ planes: 1,
275
+ colorCount: 0,
276
+ // The file itself when it is already the right size: re-encoding would only lose the author's tool's work.
277
+ data: s === img.width ? bytes : encodePng(resizeRgba(img, s, s)),
278
+ }));
279
+ }
280
+
281
+ export function groupIcon(
282
+ images: IconImage[],
283
+ firstId = 1,
284
+ ): { icons: { id: number; data: Uint8Array }[]; group: Uint8Array } {
285
+ const group = new Uint8Array(6 + images.length * 14);
286
+ const dv = new DataView(group.buffer);
287
+ dv.setUint16(0, 0, true);
288
+ dv.setUint16(2, 1, true);
289
+ dv.setUint16(4, images.length, true);
290
+ const icons = images.map((img, i) => {
291
+ const o = 6 + i * 14;
292
+ group[o] = img.width >= 256 ? 0 : img.width;
293
+ group[o + 1] = img.height >= 256 ? 0 : img.height;
294
+ group[o + 2] = img.colorCount;
295
+ group[o + 3] = 0;
296
+ dv.setUint16(o + 4, img.planes || 1, true);
297
+ dv.setUint16(o + 6, img.bitCount || 32, true);
298
+ dv.setUint32(o + 8, img.data.length, true);
299
+ dv.setUint16(o + 12, firstId + i, true);
300
+ return { id: firstId + i, data: img.data };
301
+ });
302
+ return { icons, group };
303
+ }