@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/sk.ts ADDED
@@ -0,0 +1,290 @@
1
+ #!/usr/bin/env bun
2
+ // sk — create, develop and package a Skathi app for Windows, macOS or Linux, without a
3
+ // Rust toolchain.
4
+
5
+ import { spawn } from "node:child_process";
6
+ import { buildApp, summary } from "./build-app";
7
+ import {
8
+ ConfigError,
9
+ OPTIONAL,
10
+ parseParts,
11
+ partsLeftOut,
12
+ selectVariant,
13
+ VARIANTS,
14
+ variantFor,
15
+ type Variant,
16
+ } from "./config";
17
+ import { dev } from "./dev";
18
+ import { addHost, buildHost, CLI_VERSION, DEV_HOST, HostError, hostInfo, resolveHost } from "./host";
19
+ import { fetchHost } from "./host-fetch";
20
+ import { colorEnabled, colorFlag, lineProgress, logTo, paint, progressFor } from "./term";
21
+ import { createCommand } from "./create";
22
+ import { currentPlatform, parsePlatform } from "./platform";
23
+ import { commandHelp, topHelp } from "./help";
24
+
25
+ type Flags = Record<string, string | boolean>;
26
+ const BOOLEAN = new Set([
27
+ "deny-warnings",
28
+ "no-deps",
29
+ "list",
30
+ "console",
31
+ "payload-only",
32
+ "allow-host-mismatch",
33
+ "aot-inputs",
34
+ "help",
35
+ "version",
36
+ "json",
37
+ "no-sign",
38
+ "yes",
39
+ "devtools",
40
+ "no-devtools",
41
+ "color",
42
+ "no-color",
43
+ ]);
44
+ const REPEATABLE = new Set(["define"]);
45
+
46
+ function parse(argv: string[]): {
47
+ positional: string[];
48
+ flags: Flags;
49
+ repeated: Record<string, string[]>;
50
+ rest: string[];
51
+ } {
52
+ const positional: string[] = [];
53
+ const flags: Flags = {};
54
+ const repeated: Record<string, string[]> = {};
55
+ let rest: string[] = [];
56
+ for (let i = 0; i < argv.length; i++) {
57
+ const a = argv[i]!;
58
+ if (a === "--") {
59
+ rest = argv.slice(i + 1);
60
+ break;
61
+ }
62
+ if (a === "-h") flags.help = true;
63
+ else if (a === "-y") flags.yes = true;
64
+ else if (a === "-v") flags.version = true;
65
+ else if (a.startsWith("--")) {
66
+ // Split at the FIRST "=" only: `--define=K=V` keeps its own "=".
67
+ const body = a.slice(2);
68
+ const eq = body.indexOf("=");
69
+ const name = eq < 0 ? body : body.slice(0, eq);
70
+ const inline = eq < 0 ? undefined : body.slice(eq + 1);
71
+ if (BOOLEAN.has(name)) flags[name] = true;
72
+ else if (REPEATABLE.has(name)) (repeated[name] ??= []).push(inline ?? argv[++i] ?? "");
73
+ else flags[name] = inline ?? argv[++i] ?? "";
74
+ } else positional.push(a);
75
+ }
76
+ return { positional, flags, repeated, rest };
77
+ }
78
+
79
+ function variantOf(flags: Flags): Variant | undefined {
80
+ const list = (name: string) => {
81
+ const v = flags[name];
82
+ if (v === undefined) return undefined;
83
+ if (typeof v !== "string" || !v.trim())
84
+ throw new ConfigError(`--${name} needs a list of parts (${OPTIONAL.join(", ")})`);
85
+ return parseParts(v, `--${name}`);
86
+ };
87
+ const host = flags.variant;
88
+ if (host !== undefined && (typeof host !== "string" || !host.trim()))
89
+ throw new ConfigError("--variant needs a variant name");
90
+ const sel = { features: list("features"), without: list("without"), host: host as string | undefined };
91
+ if (!sel.features && !sel.without && !sel.host) return undefined;
92
+ // Normalised: `no-audio+no-devtools` and `no-devtools+no-audio` are one host.
93
+ return variantFor(partsLeftOut(selectVariant(sel, "the command line")));
94
+ }
95
+
96
+ async function main(argv: string[]): Promise<number> {
97
+ const { positional, flags, repeated, rest } = parse(argv);
98
+ const [command, ...args] = positional;
99
+ if (command === "version" || (!command && flags.version === true)) {
100
+ console.log(CLI_VERSION);
101
+ return 0;
102
+ }
103
+ const color = colorEnabled(process.stdout, colorFlag(flags));
104
+ const about = command === "help" ? args[0] : flags.help ? command : undefined;
105
+ if (about !== undefined) {
106
+ const text = commandHelp(about, color);
107
+ if (text) {
108
+ console.log(text);
109
+ return 0;
110
+ }
111
+ }
112
+ if (!command || flags.help || command === "help") {
113
+ console.log(topHelp(color));
114
+ return command || flags.help ? 0 : 1;
115
+ }
116
+
117
+ if (command === "build" || command === "publish" || command === "run") {
118
+ const platform = flags.platform === undefined ? undefined : parsePlatform(flags.platform);
119
+ if (command === "run" && platform && platform !== currentPlatform()) {
120
+ throw new ConfigError(
121
+ `sk run starts the app here; a ${platform} build cannot run on ${process.platform} — use sk build`,
122
+ );
123
+ }
124
+ if (flags.sign !== undefined && (typeof flags.sign !== "string" || !flags.sign.trim())) {
125
+ throw new ConfigError('--sign needs a codesign identity ("-" for ad hoc)');
126
+ }
127
+ if (flags.sign !== undefined && flags["no-sign"])
128
+ throw new ConfigError("--sign and --no-sign contradict each other");
129
+ const progress = progressFor(process.stderr, colorEnabled(process.stderr, colorFlag(flags)));
130
+ const result = await buildApp({
131
+ progress,
132
+ target: args[0] ?? ".",
133
+ configPath: typeof flags.config === "string" ? flags.config : undefined,
134
+ out: typeof flags.out === "string" ? flags.out : undefined,
135
+ host: typeof flags.host === "string" ? flags.host : undefined,
136
+ variant: variantOf(flags),
137
+ console: flags.console === true,
138
+ payloadOnly: flags["payload-only"] === true,
139
+ allowHostMismatch: flags["allow-host-mismatch"] === true,
140
+ defines: repeated.define,
141
+ aotInputs: flags["aot-inputs"] === true,
142
+ platform,
143
+ sign: flags["no-sign"] ? false : typeof flags.sign === "string" ? flags.sign.trim() : undefined,
144
+ mode: command === "publish" ? "release" : "debug",
145
+ }).finally(() => progress.end());
146
+ if (flags.json) {
147
+ const s = result.stamp;
148
+ console.log(
149
+ JSON.stringify({
150
+ exe: result.exe,
151
+ skpk: result.skpk,
152
+ aotInputs: result.aotInputs,
153
+ name: result.config.name,
154
+ productName: result.config.productName,
155
+ version: result.config.version,
156
+ variant: result.variant,
157
+ host: result.host && { exe: result.host.exe, source: result.host.source, profile: result.host.info.profile },
158
+ assets: result.assets.length,
159
+ bundleBytes: result.bundleBytes,
160
+ payloadBytes: result.payloadBytes,
161
+ ...(result.packs.length ? { packs: result.packs } : {}),
162
+ stamp: s && {
163
+ bytes: s.bytes,
164
+ skew: s.skew,
165
+ dataAligned: s.dataAligned,
166
+ passes: s.passes,
167
+ subsystem: s.subsystem,
168
+ iconCount: s.iconCount,
169
+ ms: s.ms,
170
+ },
171
+ ...(result.bundle && {
172
+ platform: result.platform,
173
+ app: result.bundle.app,
174
+ bundle: {
175
+ bundleId: result.bundle.bundleId,
176
+ bytes: result.bundle.bytes,
177
+ iconSizes: result.bundle.iconSizes,
178
+ signed: result.bundle.signed,
179
+ signNote: result.bundle.signNote,
180
+ entitlements: result.bundle.entitlements,
181
+ ms: result.bundle.ms,
182
+ },
183
+ }),
184
+ warnings: result.warnings,
185
+ ms: result.ms,
186
+ }),
187
+ );
188
+ } else {
189
+ console.log(summary(result, colorEnabled(process.stdout, colorFlag(flags))));
190
+ }
191
+ if (command !== "run" || !result.exe) return 0;
192
+ // `run`: inherited handles, so a GUI-subsystem exe's stderr still lands in this terminal.
193
+ const child = spawn(result.exe, rest, { stdio: "inherit" });
194
+ return await new Promise<number>((done) => child.on("exit", (c) => done(c ?? 0)));
195
+ }
196
+
197
+ if (command === "check") return await (await import("../check/command")).checkCommand(args[0], flags, CLI_VERSION);
198
+ if (command === "explain")
199
+ return (await import("../check/command")).explainCommand(args[0], flags.list === true, flags);
200
+
201
+ if (command === "dev") {
202
+ return await dev(args[0] ?? ".", { exe: typeof flags.exe === "string" ? flags.exe : undefined });
203
+ }
204
+
205
+ if (command === "host") {
206
+ const [sub, arg] = args;
207
+ if (sub === "info") {
208
+ const exe = arg ?? resolveHost({ variant: variantOf(flags) ?? "standard", allowMismatch: true }).exe;
209
+ // `hostInfo` refuses a stamped exe itself: asking one for host info would launch the app inside it.
210
+ console.log(JSON.stringify(hostInfo(exe), null, 2));
211
+ return 0;
212
+ }
213
+ if (sub === "path") {
214
+ const h = resolveHost({
215
+ variant: variantOf(flags) ?? "standard",
216
+ host: typeof flags.host === "string" ? flags.host : undefined,
217
+ platform: flags.platform === undefined ? undefined : parsePlatform(flags.platform),
218
+ });
219
+ console.log(flags.json ? JSON.stringify({ exe: h.exe, source: h.source, info: h.info }, null, 2) : h.exe);
220
+ return 0;
221
+ }
222
+ if (sub === "add") {
223
+ if (!arg) throw new HostError("sk host add <exe>");
224
+ addHost(arg, (line) => console.log(line));
225
+ return 0;
226
+ }
227
+ const color = colorEnabled(process.stderr, colorFlag(flags));
228
+ if (sub === "fetch") {
229
+ const named = flags.variant === "both" || flags.variant === DEV_HOST ? flags.variant : variantOf(flags);
230
+ const variants = named === undefined ? [...VARIANTS, DEV_HOST] : named === "both" ? VARIANTS : [named];
231
+ const progress = progressFor(process.stderr, color);
232
+ try {
233
+ for (const variant of variants) {
234
+ progress.step(`${variant} host`);
235
+ await fetchHost({ variant, log: (line) => progress.detail(line) });
236
+ }
237
+ } finally {
238
+ progress.end();
239
+ }
240
+ return 0;
241
+ }
242
+ if (sub === "build") {
243
+ // cargo draws its own progress on the terminal: plain lines around it.
244
+ const lines = lineProgress((line) => console.error(line), color);
245
+ const v = flags.variant === "both" ? "both" : (variantOf(flags) ?? "both");
246
+ for (const variant of v === "both" ? VARIANTS : [v]) {
247
+ lines.step(`${variant} host`);
248
+ const built = buildHost(variant, logTo(lines));
249
+ lines.detail(built.path);
250
+ }
251
+ lines.end();
252
+ return 0;
253
+ }
254
+ throw new HostError("sk host info|path|fetch|add|build");
255
+ }
256
+
257
+ if (command === "create") {
258
+ const str = (k: string) => (typeof flags[k] === "string" ? (flags[k] as string) : undefined);
259
+ const yesNo = (k: string) => (flags[k] ? true : flags[`no-${k}`] ? false : undefined);
260
+ return await createCommand(args[0], {
261
+ name: str("name"),
262
+ os: str("os"),
263
+ without: str("without"),
264
+ devtools: yesNo("devtools"),
265
+ template: str("template"),
266
+ pm: str("pm"),
267
+ yes: flags.yes === true,
268
+ });
269
+ }
270
+
271
+ console.error(
272
+ `${paint(colorEnabled(process.stderr)).red("error")}: unknown command ${JSON.stringify(command)} (sk --help lists them)`,
273
+ );
274
+ return 1;
275
+ }
276
+
277
+ if (import.meta.main) {
278
+ main(process.argv.slice(2)).then(
279
+ (code) => process.exit(code),
280
+ (e) => {
281
+ const known = e instanceof ConfigError || e instanceof HostError;
282
+ const red = paint(colorEnabled(process.stderr)).red;
283
+ if (known || (e instanceof Error && !process.env.SK_DEBUG)) console.error(`${red("error")}: ${e.message}`);
284
+ else console.error(e);
285
+ process.exit(1);
286
+ },
287
+ );
288
+ }
289
+
290
+ export { main };
package/cli/skpk.ts ADDED
@@ -0,0 +1,268 @@
1
+ // SKPK v1: the one blob a packaged exe carries. The writer is here; the reader that matters is in
2
+ // Rust (`crates/sk-payload`), and both are held to `test/fixtures/golden.skpk`.
3
+ //
4
+ // header (64 bytes, little-endian, read BYTE-WISE: the blob is only 4-byte aligned in the image)
5
+ // 0 "SKPK" | 4 u16 format = 1 (a host refuses > 1) | 6 u16 flags (bit 0: has BYTECODE)
6
+ // 8 u32 entry_count | 12 u32 toc_off (= 64) | 16 u32 names_off | 20 u32 names_len
7
+ // 24 u32 skew: zero bytes between names and data, chosen so data_off lands on a page boundary
8
+ // IN THE MAPPED IMAGE | 28 u32 reserved | 32 u64 data_off (= names_off + names_len + skew)
9
+ // 40 u64 blob_len | 48 [16] reserved
10
+ // toc: entry_count x 32 bytes sorted by (kind, name bytes): u32 name_off (rel. names_off),
11
+ // u32 name_len, u64 off (rel. data_off), u64 len, u16 kind, u8 align_log2, u8 reserved, u32 crc32
12
+ // names: UTF-8, no terminators. data: each entry aligned to 2^align_log2 relative to data_off.
13
+ //
14
+ // No timestamps, so two builds of the same inputs are byte-identical. No compression: demand
15
+ // paging matters more than size.
16
+
17
+ export const MAGIC = "SKPK";
18
+ export const FORMAT = 1;
19
+ export const HEADER_SIZE = 64;
20
+ export const TOC_ENTRY_SIZE = 32;
21
+ export const PAGE = 4096;
22
+
23
+ export const KIND = {
24
+ META: 1,
25
+ WINDOW: 2,
26
+ SCRIPT: 3,
27
+ BYTECODE: 4,
28
+ ASSET: 16,
29
+ } as const;
30
+
31
+ export const NAMES = {
32
+ META: "sk/app.json",
33
+ WINDOW: "sk/window.json",
34
+ SCRIPT: "sk/app.js",
35
+ BYTECODE: "sk/app.bc",
36
+ } as const;
37
+
38
+ export const FLAG_HAS_BYTECODE = 1;
39
+
40
+ export interface SkpkInput {
41
+ name: string;
42
+ kind: number;
43
+ data: Uint8Array;
44
+ alignLog2?: number;
45
+ }
46
+
47
+ export interface SkpkEntry {
48
+ name: string;
49
+ kind: number;
50
+ start: number;
51
+ len: number;
52
+ alignLog2: number;
53
+ crc32: number;
54
+ }
55
+
56
+ export interface SkpkHeader {
57
+ format: number;
58
+ flags: number;
59
+ entryCount: number;
60
+ tocOff: number;
61
+ namesOff: number;
62
+ namesLen: number;
63
+ skew: number;
64
+ dataOff: number;
65
+ blobLen: number;
66
+ }
67
+
68
+ // crc32 (IEEE), for `sk verify` and the tests; the host never checks it at boot (it would fault in every page).
69
+
70
+ const CRC_TABLE = (() => {
71
+ const t = new Uint32Array(256);
72
+ for (let n = 0; n < 256; n++) {
73
+ let c = n;
74
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
75
+ t[n] = c >>> 0;
76
+ }
77
+ return t;
78
+ })();
79
+
80
+ export function crc32(bytes: Uint8Array, seed = 0): number {
81
+ let c = (seed ^ 0xffffffff) >>> 0;
82
+ for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]!) & 0xff]! ^ (c >>> 8);
83
+ return (c ^ 0xffffffff) >>> 0;
84
+ }
85
+
86
+ const utf8 = new TextEncoder();
87
+
88
+ export function compareBytes(a: Uint8Array, b: Uint8Array): number {
89
+ const n = Math.min(a.length, b.length);
90
+ for (let i = 0; i < n; i++) {
91
+ if (a[i] !== b[i]) return a[i]! - b[i]!;
92
+ }
93
+ return a.length - b.length;
94
+ }
95
+
96
+ const alignUp = (n: number, to: number) => Math.ceil(n / to) * to;
97
+
98
+ function defaultAlign(kind: number): number {
99
+ return kind === KIND.BYTECODE ? 12 : 4;
100
+ }
101
+
102
+ /** Lays the entries out and returns the blob. `skew: 0` is a valid payload, just not page-aligned. */
103
+ export function writeSkpk(inputs: SkpkInput[], options: { skew?: number } = {}): Uint8Array {
104
+ const skew = options.skew ?? 0;
105
+ if (!Number.isInteger(skew) || skew < 0 || skew >= PAGE) {
106
+ throw new Error(`skpk: skew must be an integer in [0, ${PAGE}), got ${skew}`);
107
+ }
108
+ const items = inputs.map((e) => ({
109
+ ...e,
110
+ nameBytes: utf8.encode(e.name),
111
+ alignLog2: e.alignLog2 ?? defaultAlign(e.kind),
112
+ }));
113
+ for (const e of items) {
114
+ if (!e.name) throw new Error("skpk: an entry has an empty name");
115
+ if (!Number.isInteger(e.kind) || e.kind < 1 || e.kind > 0xffff) {
116
+ throw new Error(`skpk: ${e.name}: kind ${e.kind} is not a u16`);
117
+ }
118
+ if (e.alignLog2 < 0 || e.alignLog2 > 16) throw new Error(`skpk: ${e.name}: align 2^${e.alignLog2}`);
119
+ }
120
+ items.sort((a, b) => a.kind - b.kind || compareBytes(a.nameBytes, b.nameBytes));
121
+ for (let i = 1; i < items.length; i++) {
122
+ const a = items[i - 1]!;
123
+ const b = items[i]!;
124
+ if (a.kind === b.kind && compareBytes(a.nameBytes, b.nameBytes) === 0) {
125
+ throw new Error(`skpk: duplicate entry ${JSON.stringify(b.name)} (kind ${b.kind})`);
126
+ }
127
+ }
128
+
129
+ const tocOff = HEADER_SIZE;
130
+ const namesOff = tocOff + items.length * TOC_ENTRY_SIZE;
131
+ const namesLen = items.reduce((n, e) => n + e.nameBytes.length, 0);
132
+ const dataOff = namesOff + namesLen + skew;
133
+
134
+ let cursor = 0;
135
+ const placed = items.map((e) => {
136
+ const off = alignUp(cursor, 1 << e.alignLog2);
137
+ cursor = off + e.data.length;
138
+ return off;
139
+ });
140
+ const blobLen = dataOff + cursor;
141
+ if (blobLen > 0xffff_ffff) {
142
+ throw new Error(`skpk: ${blobLen} bytes — a PE resource is limited to 4 GiB`);
143
+ }
144
+
145
+ const out = new Uint8Array(blobLen);
146
+ const dv = new DataView(out.buffer);
147
+ out.set(utf8.encode(MAGIC), 0);
148
+ dv.setUint16(4, FORMAT, true);
149
+ let flags = 0;
150
+ if (items.some((e) => e.kind === KIND.BYTECODE)) flags |= FLAG_HAS_BYTECODE;
151
+ dv.setUint16(6, flags, true);
152
+ dv.setUint32(8, items.length, true);
153
+ dv.setUint32(12, tocOff, true);
154
+ dv.setUint32(16, namesOff, true);
155
+ dv.setUint32(20, namesLen, true);
156
+ dv.setUint32(24, skew, true);
157
+ dv.setUint32(28, 0, true);
158
+ dv.setBigUint64(32, BigInt(dataOff), true);
159
+ dv.setBigUint64(40, BigInt(blobLen), true);
160
+
161
+ let nameCursor = 0;
162
+ items.forEach((e, i) => {
163
+ const t = tocOff + i * TOC_ENTRY_SIZE;
164
+ dv.setUint32(t + 0, nameCursor, true);
165
+ dv.setUint32(t + 4, e.nameBytes.length, true);
166
+ dv.setBigUint64(t + 8, BigInt(placed[i]!), true);
167
+ dv.setBigUint64(t + 16, BigInt(e.data.length), true);
168
+ dv.setUint16(t + 24, e.kind, true);
169
+ out[t + 26] = e.alignLog2;
170
+ out[t + 27] = 0;
171
+ dv.setUint32(t + 28, crc32(e.data), true);
172
+ out.set(e.nameBytes, namesOff + nameCursor);
173
+ nameCursor += e.nameBytes.length;
174
+ out.set(e.data, dataOff + placed[i]!);
175
+ });
176
+ return out;
177
+ }
178
+
179
+ /** The skew that puts `data_off` on a page boundary once the blob sits at image RVA `rva`. */
180
+ export function skewFor(rva: number, header: Pick<SkpkHeader, "namesOff" | "namesLen">): number {
181
+ const namesEnd = header.namesOff + header.namesLen;
182
+ return (PAGE - ((rva + namesEnd) % PAGE)) % PAGE;
183
+ }
184
+
185
+ export class SkpkError extends Error {}
186
+
187
+ export function readHeader(blob: Uint8Array): SkpkHeader {
188
+ if (blob.length < HEADER_SIZE) throw new SkpkError(`skpk: ${blob.length} bytes is shorter than a header`);
189
+ const magic = new TextDecoder().decode(blob.subarray(0, 4));
190
+ if (magic !== MAGIC) throw new SkpkError(`skpk: bad magic ${JSON.stringify(magic)}`);
191
+ const dv = new DataView(blob.buffer, blob.byteOffset, blob.byteLength);
192
+ const format = dv.getUint16(4, true);
193
+ if (format > FORMAT) {
194
+ throw new SkpkError(`skpk: format ${format} — this payload was built by a newer sk`);
195
+ }
196
+ return {
197
+ format,
198
+ flags: dv.getUint16(6, true),
199
+ entryCount: dv.getUint32(8, true),
200
+ tocOff: dv.getUint32(12, true),
201
+ namesOff: dv.getUint32(16, true),
202
+ namesLen: dv.getUint32(20, true),
203
+ skew: dv.getUint32(24, true),
204
+ dataOff: Number(dv.getBigUint64(32, true)),
205
+ blobLen: Number(dv.getBigUint64(40, true)),
206
+ };
207
+ }
208
+
209
+ export interface Skpk {
210
+ header: SkpkHeader;
211
+ entries: SkpkEntry[];
212
+ bytes(e: SkpkEntry): Uint8Array;
213
+ find(kind: number, name: string): SkpkEntry | undefined;
214
+ }
215
+
216
+ export function readSkpk(blob: Uint8Array): Skpk {
217
+ const header = readHeader(blob);
218
+ const dv = new DataView(blob.buffer, blob.byteOffset, blob.byteLength);
219
+ const within = (what: string, start: number, len: number) => {
220
+ if (start < 0 || len < 0 || start + len > blob.length) {
221
+ throw new SkpkError(`skpk: ${what} [${start}, +${len}) is outside the ${blob.length}-byte blob`);
222
+ }
223
+ };
224
+ within("toc", header.tocOff, header.entryCount * TOC_ENTRY_SIZE);
225
+ within("names", header.namesOff, header.namesLen);
226
+ within("data", header.dataOff, 0);
227
+ if (header.blobLen > blob.length) within("blob_len", 0, header.blobLen);
228
+ const decoder = new TextDecoder("utf-8", { fatal: true });
229
+ const entries: SkpkEntry[] = [];
230
+ for (let i = 0; i < header.entryCount; i++) {
231
+ const t = header.tocOff + i * TOC_ENTRY_SIZE;
232
+ const nameOff = dv.getUint32(t, true);
233
+ const nameLen = dv.getUint32(t + 4, true);
234
+ within(`entry ${i} name`, header.namesOff + nameOff, nameLen);
235
+ if (nameOff + nameLen > header.namesLen) throw new SkpkError(`skpk: entry ${i} name overruns names`);
236
+ const nameBytes = blob.subarray(header.namesOff + nameOff, header.namesOff + nameOff + nameLen);
237
+ let name: string;
238
+ try {
239
+ name = decoder.decode(nameBytes);
240
+ } catch {
241
+ throw new SkpkError(`skpk: entry ${i} name is not UTF-8`);
242
+ }
243
+ const off = Number(dv.getBigUint64(t + 8, true));
244
+ const len = Number(dv.getBigUint64(t + 16, true));
245
+ within(`entry ${i} (${name}) data`, header.dataOff + off, len);
246
+ entries.push({
247
+ name,
248
+ kind: dv.getUint16(t + 24, true),
249
+ alignLog2: blob[t + 26]!,
250
+ start: header.dataOff + off,
251
+ len,
252
+ crc32: dv.getUint32(t + 28, true),
253
+ });
254
+ }
255
+ const encoded = entries.map((e) => utf8.encode(e.name));
256
+ for (let i = 1; i < entries.length; i++) {
257
+ const a = entries[i - 1]!;
258
+ const b = entries[i]!;
259
+ const order = a.kind - b.kind || compareBytes(encoded[i - 1]!, encoded[i]!);
260
+ if (order >= 0) throw new SkpkError(`skpk: the toc is not sorted at entry ${i} (${b.name})`);
261
+ }
262
+ return {
263
+ header,
264
+ entries,
265
+ bytes: (e) => blob.subarray(e.start, e.start + e.len),
266
+ find: (kind, name) => entries.find((e) => e.kind === kind && e.name === name),
267
+ };
268
+ }