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

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 (50) 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/check/codes.ts +19 -0
  7. package/check/command.ts +5 -3
  8. package/check/index.ts +44 -1
  9. package/cli/aot-build.ts +192 -0
  10. package/cli/build-app.ts +102 -31
  11. package/cli/config.ts +45 -102
  12. package/cli/create.ts +12 -54
  13. package/cli/dev.ts +109 -19
  14. package/cli/effects.ts +162 -0
  15. package/cli/elf.ts +3 -2
  16. package/cli/help.ts +56 -148
  17. package/cli/host-fetch.ts +116 -54
  18. package/cli/host.ts +59 -39
  19. package/cli/sk.ts +440 -246
  20. package/cli/skpk.ts +6 -0
  21. package/cli/stamp.ts +2 -2
  22. package/cli/term.ts +169 -38
  23. package/cli/workload-cache.ts +258 -0
  24. package/effects/compile.ts +952 -0
  25. package/effects/redslangc.json +23 -0
  26. package/effects/redslangc.ts +220 -0
  27. package/effects/sk.slang +558 -0
  28. package/package.json +6 -2
  29. package/templates/icon.png +0 -0
  30. package/templates/minimal/.vscode/settings.json +3 -0
  31. package/templates/minimal/src/App.vue +2 -2
  32. package/templates/showcase/.vscode/settings.json +3 -0
  33. package/templates/showcase/shaders/sheen.slang +23 -0
  34. package/templates/showcase/src/components/Titlebar.vue +7 -3
  35. package/templates/showcase/src/engine.ts +3 -26
  36. package/templates/showcase/src/pages/AudioPage.vue +6 -9
  37. package/templates/showcase/src/pages/FilesPage.vue +11 -15
  38. package/templates/showcase/src/pages/FormsPage.vue +2 -3
  39. package/templates/showcase/src/pages/GraphicsPage.vue +13 -15
  40. package/templates/showcase/src/pages/HomePage.vue +1 -2
  41. package/templates/showcase/src/pages/LocalePage.vue +2 -2
  42. package/templates/showcase/src/pages/MediaPage.vue +1 -1
  43. package/templates/showcase/src/pages/MotionPage.vue +1 -1
  44. package/templates/showcase/src/pages/NetworkPage.vue +6 -5
  45. package/templates/showcase/src/pages/PermissionsPage.vue +2 -2
  46. package/templates/showcase/src/pages/StoragePage.vue +23 -36
  47. package/templates/showcase/src/pages/StylesPage.vue +9 -1
  48. package/templates/showcase/src/pages/SystemPage.vue +3 -3
  49. package/templates/showcase/src/styles.css +2 -2
  50. package/templates/showcase/src/components/Missing.vue +0 -26
package/cli/config.ts CHANGED
@@ -8,8 +8,9 @@
8
8
  // "packs": [{ "name": "fonts", "match": ["**/*.woff2"] }, { "name": "assets" }]
9
9
  // assets in their own .skpk files, in order; no "match" takes the rest
10
10
  // "define", "aliases" Vite's `define`; a bare module name -> the app's own stand-in file
11
- // "windows": { exeName, icon, company, copyright, description, console,
12
- // without | features | host } engine parts left out / taken / a whole variant by name
11
+ // "publishDevtools": true sk publish keeps devtools (the standard host instead of no-devtools)
12
+ // "aot": true sk build and sk publish compile the app to a native image (Windows x64)
13
+ // "windows": { exeName, icon, company, copyright, description, console }
13
14
  // "macos": { bundleId, exeName, icon, category, minimumSystemVersion, copyright,
14
15
  // microphoneUsageDescription, cameraUsageDescription, sign }
15
16
  //
@@ -21,82 +22,26 @@ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
21
22
  import type { Platform } from "./platform";
22
23
  import { numericVersion } from "./versioninfo";
23
24
 
24
- /**
25
- * The parts of the engine a host can be built WITHOUT: the same list and order as `OPTIONAL` in
26
- * crates/sk-app/src/payload.rs. `devtools` is the listener, inspector and F12; the rest are cargo features of sk-app.
27
- */
28
- export const OPTIONAL = ["devtools", "audio", "clipboard", "storages", "indexeddb", "webgpu"] as const;
29
- export type Part = (typeof OPTIONAL)[number];
30
-
31
- /** A host's name: `standard`, else the parts left out as `no-<part>` joined by `+` in {@link OPTIONAL}'s order. The host cache is keyed by it. */
25
+ /** A prod host's name, the key the host cache and the release find it by: the whole engine, with or without devtools. */
32
26
  export type Variant = string;
33
- export const VARIANTS: Variant[] = ["standard", "no-devtools"];
34
-
35
- const isPart = (p: unknown): p is Part => typeof p === "string" && (OPTIONAL as readonly string[]).includes(p);
36
-
37
- export function variantFor(without: Iterable<Part>): Variant {
38
- const off = new Set(without);
39
- const names = OPTIONAL.filter((p) => off.has(p)).map((p) => `no-${p}`);
40
- return names.length ? names.join("+") : "standard";
41
- }
42
-
43
- export function partsLeftOut(variant: Variant): Part[] {
44
- if (variant === "standard") return [];
45
- const off = new Set<Part>();
46
- for (const name of variant.split("+")) {
47
- const p = name.startsWith("no-") ? name.slice(3) : "";
48
- if (!isPart(p)) {
49
- throw new ConfigError(
50
- `${JSON.stringify(variant)} is not a host variant — "standard", or the parts left out as no-<part> joined by "+" ` +
51
- `(parts: ${OPTIONAL.join(", ")})`,
52
- );
53
- }
54
- off.add(p);
55
- }
56
- return OPTIONAL.filter((p) => off.has(p));
57
- }
27
+ export const VARIANTS: readonly Variant[] = ["standard", "no-devtools"];
58
28
 
59
- /** A list of part names: `"audio,clipboard"` or an array; spaces separate too (PowerShell passes an unquoted `audio,clipboard` as `"audio clipboard"`). */
60
- export function parseParts(list: unknown, where: string): Part[] {
61
- const items = typeof list === "string" ? list.split(/[\s,]+/).filter(Boolean) : list;
62
- if (!Array.isArray(items)) throw new ConfigError(`${where} must be a list of parts (${OPTIONAL.join(", ")})`);
63
- const out = new Set<Part>();
64
- for (const p of items) {
65
- if (!isPart(p))
66
- throw new ConfigError(`${where}: ${JSON.stringify(p)} is not a part — known parts are ${OPTIONAL.join(", ")}`);
67
- out.add(p);
68
- }
69
- return OPTIONAL.filter((p) => out.has(p));
70
- }
29
+ /** The cargo features of sk-app every published host carries (crates/sk-app/src/payload.rs `OPTIONAL`, after devtools). */
30
+ export const ENGINE_FEATURES = ["audio", "clipboard", "storages", "indexeddb", "webgpu"] as const;
71
31
 
72
- /** The variant a selection asks for (`host` is the legacy whole-variant spelling). */
73
- export function selectVariant(
74
- sel: { features?: Part[] | undefined; without?: Part[] | undefined; host?: Variant | undefined },
75
- where: string,
76
- ): Variant {
77
- const given = [sel.features && "features", sel.without && "without", sel.host && "host"].filter(Boolean);
78
- if (given.length > 1) throw new ConfigError(`${where}: give one of ${given.join(" / ")}, not several`);
79
- if (sel.features) return variantFor(OPTIONAL.filter((p) => !sel.features!.includes(p)));
80
- if (sel.without) return variantFor(sel.without);
81
- if (sel.host) return variantFor(partsLeftOut(sel.host));
82
- return "standard";
83
- }
32
+ export const PARTS_NOT_SELECTABLE =
33
+ "engine parts are no longer selectable: every published app carries the whole engine. " +
34
+ '"publishDevtools": true in sk.config.json keeps devtools in sk publish builds; ' +
35
+ "to trim the engine, embed it with the sk-app crate (sk_app::embed) and its cargo features";
84
36
 
85
- export function variantWarnings(variant: Variant): string[] {
86
- const off = new Set(partsLeftOut(variant));
87
- const out: string[] = [];
88
- if (!off.has("indexeddb") && off.has("storages")) {
89
- out.push("the host has indexedDB but no storages: its databases are in memory and nothing survives a restart");
90
- }
91
- return out;
37
+ export function parseVariant(v: unknown, where: string): Variant {
38
+ const name = typeof v === "string" ? v.trim() : "";
39
+ if (VARIANTS.includes(name)) return name;
40
+ throw new ConfigError(`${where}: ${JSON.stringify(v)} is not a workload variant — ${VARIANTS.join(" or ")}`);
92
41
  }
93
42
 
94
43
  export function cargoFeatureArgs(variant: Variant): string[] {
95
- const off = partsLeftOut(variant);
96
- const features = ["prod", ...(off.includes("devtools") ? ["no-devtools"] : [])];
97
- const defaults = OPTIONAL.filter((p) => p !== "devtools");
98
- if (!off.some((p) => p !== "devtools")) return ["--features", features.join(",")];
99
- return ["--no-default-features", "--features", [...features, ...defaults.filter((p) => !off.includes(p))].join(",")];
44
+ return ["--features", parseVariant(variant, "cargo") === "no-devtools" ? "prod,no-devtools" : "prod"];
100
45
  }
101
46
 
102
47
  export interface WindowsConfig {
@@ -106,12 +51,6 @@ export interface WindowsConfig {
106
51
  copyright?: string | undefined;
107
52
  description?: string | undefined;
108
53
  console?: boolean;
109
- host?: Variant;
110
- features?: Part[];
111
- without?: Part[];
112
- variant: Variant;
113
- /** Whether the config chose the engine parts (`host`, `features` or `without`). */
114
- selected?: boolean;
115
54
  }
116
55
 
117
56
  /** `"macos"`, defaults applied. Read on every platform, so a typo fails a Windows build too. */
@@ -144,6 +83,10 @@ export interface AppConfig {
144
83
  assetsDeclared: boolean;
145
84
  publicDir: string | null;
146
85
  packs: PackConfig[];
86
+ /** Whether `sk build` and `sk publish` compile the app to a native image (`--aot` / `--no-aot` win). */
87
+ aot: boolean;
88
+ /** Whether `sk publish` stamps the standard host (devtools in) instead of no-devtools. */
89
+ publishDevtools: boolean;
147
90
  windows: WindowsConfig;
148
91
  macos: MacConfig;
149
92
  exeName: string;
@@ -162,6 +105,7 @@ export interface PackConfig {
162
105
  }
163
106
 
164
107
  const PACK_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
108
+ export const PACK_KEYS: ReadonlySet<string> = new Set(["name", "match"]);
165
109
 
166
110
  function parsePacks(raw: unknown): PackConfig[] {
167
111
  if (raw === undefined) return [];
@@ -170,11 +114,11 @@ function parsePacks(raw: unknown): PackConfig[] {
170
114
  const seen = new Set<string>();
171
115
  return raw.map((p, i) => {
172
116
  if (!p || typeof p !== "object" || Array.isArray(p)) throw bad(`entry ${i} must be an object`);
173
- const { name, match, ...rest } = p as Record<string, unknown>;
174
- const extra = Object.keys(rest).filter((k) => !k.startsWith("$"));
117
+ const { name, match } = p as Record<string, unknown>;
118
+ const extra = Object.keys(p).filter((k) => !k.startsWith("$") && !PACK_KEYS.has(k));
175
119
  if (extra.length)
176
120
  throw bad(
177
- `entry ${i} has unknown key(s) ${extra.map((k) => JSON.stringify(k)).join(", ")} — known keys are name, match`,
121
+ `entry ${i} has unknown key(s) ${extra.map((k) => JSON.stringify(k)).join(", ")} — known keys are ${[...PACK_KEYS].join(", ")}`,
178
122
  );
179
123
  if (typeof name !== "string" || !PACK_NAME.test(name) || name === "app") {
180
124
  throw bad(
@@ -202,13 +146,15 @@ export interface LaunchConfig {
202
146
  protocols: string[];
203
147
  }
204
148
 
205
- const TOP_LEVEL = new Set([
149
+ export const TOP_LEVEL: ReadonlySet<string> = new Set([
206
150
  "name",
207
151
  "platforms",
208
152
  "productName",
209
153
  "version",
210
154
  "window",
211
155
  "devtools",
156
+ "publishDevtools",
157
+ "aot",
212
158
  "httpCache",
213
159
  "assets",
214
160
  "publicDir",
@@ -285,18 +231,16 @@ function readLaunch(raw: Record<string, unknown>, name: string): LaunchConfig {
285
231
  protocols,
286
232
  };
287
233
  }
288
- const WINDOWS_KEYS = new Set([
234
+ export const WINDOWS_KEYS: ReadonlySet<string> = new Set([
289
235
  "exeName",
290
236
  "icon",
291
237
  "company",
292
238
  "copyright",
293
239
  "description",
294
240
  "console",
295
- "host",
296
- "features",
297
- "without",
298
241
  ]);
299
- const MACOS_KEYS = new Set([
242
+ const REMOVED_WINDOWS_KEYS = new Set(["host", "features", "without"]);
243
+ export const MACOS_KEYS: ReadonlySet<string> = new Set([
300
244
  "bundleId",
301
245
  "exeName",
302
246
  "icon",
@@ -362,7 +306,7 @@ function readMacos(
362
306
  const [wantMaj = 0, wantMinor = 0] = MACOS_MINIMUM.split(".").map(Number);
363
307
  if (maj < wantMaj || (maj === wantMaj && minor < wantMinor)) {
364
308
  warnings.push(
365
- `sk.config.json "macos.minimumSystemVersion" ${min} is below ${MACOS_MINIMUM}, which the host is built for — ` +
309
+ `sk.config.json "macos.minimumSystemVersion" ${min} is below ${MACOS_MINIMUM}, which the workload is built for — ` +
366
310
  "an older macOS will offer to open the app and then fail to load it",
367
311
  );
368
312
  }
@@ -539,7 +483,15 @@ export function loadAppConfig(
539
483
  throw new ConfigError('sk.config.json "define" must be an object of { "NAME": value }');
540
484
  }
541
485
 
542
- const windows: WindowsConfig = { variant: "standard" };
486
+ if (raw.publishDevtools !== undefined && typeof raw.publishDevtools !== "boolean") {
487
+ throw new ConfigError('sk.config.json "publishDevtools" must be true or false');
488
+ }
489
+ const publishDevtools = raw.publishDevtools === true;
490
+ if (raw.aot !== undefined && typeof raw.aot !== "boolean") {
491
+ throw new ConfigError('sk.config.json "aot" must be true or false');
492
+ }
493
+
494
+ const windows: WindowsConfig = {};
543
495
  if (raw.windows !== undefined) {
544
496
  if (!raw.windows || typeof raw.windows !== "object" || Array.isArray(raw.windows)) {
545
497
  throw new ConfigError('sk.config.json "windows" must be an object');
@@ -547,6 +499,9 @@ export function loadAppConfig(
547
499
  const w = raw.windows as Record<string, unknown>;
548
500
  for (const key of Object.keys(w)) {
549
501
  if (key.startsWith("$")) continue;
502
+ if (REMOVED_WINDOWS_KEYS.has(key)) {
503
+ throw new ConfigError(`sk.config.json "windows.${key}": ${PARTS_NOT_SELECTABLE}`);
504
+ }
550
505
  if (!WINDOWS_KEYS.has(key)) {
551
506
  throw new ConfigError(
552
507
  `sk.config.json "windows": unknown key ${JSON.stringify(key)} — known keys are ${[...WINDOWS_KEYS].join(", ")}`,
@@ -563,20 +518,6 @@ export function loadAppConfig(
563
518
  throw new ConfigError('sk.config.json "windows.console" must be true or false');
564
519
  windows.console = w.console;
565
520
  }
566
- if (w.host !== undefined) {
567
- if (typeof w.host !== "string")
568
- throw new ConfigError('sk.config.json "windows.host" must be a host variant, e.g. "no-devtools"');
569
- try {
570
- partsLeftOut(w.host);
571
- } catch (e) {
572
- throw new ConfigError(`sk.config.json "windows.host": ${(e as Error).message}`);
573
- }
574
- windows.host = w.host;
575
- }
576
- if (w.features !== undefined) windows.features = parseParts(w.features, where("windows.features"));
577
- if (w.without !== undefined) windows.without = parseParts(w.without, where("windows.without"));
578
- windows.variant = selectVariant(windows, where('"windows"'));
579
- windows.selected = windows.host !== undefined || windows.features !== undefined || windows.without !== undefined;
580
521
  }
581
522
 
582
523
  if (raw.httpCache !== undefined && raw.httpCache !== false) {
@@ -624,6 +565,8 @@ export function loadAppConfig(
624
565
  assetsDeclared,
625
566
  publicDir,
626
567
  packs,
568
+ publishDevtools,
569
+ aot: raw.aot === true,
627
570
  windows,
628
571
  macos,
629
572
  exeName,
package/cli/create.ts CHANGED
@@ -1,19 +1,18 @@
1
1
  // `sk create [dir]`: a new app. In a terminal it asks for what the flags do not say: the directory, the
2
- // name, the template, the OSes to package for, the engine parts, whether published builds keep devtools,
2
+ // name, the template, the OSes to package for, whether published builds keep devtools,
3
3
  // and the package manager. `--yes` (or no terminal) takes the defaults.
4
4
  //
5
5
  // It copies templates/<template>/ (src/, assets/) with the placeholders filled in, and writes
6
- // package.json (the app root the builders resolve npm dependencies from), sk.config.json, a generated
7
- // 256² icon.png and a tsconfig.json that type-checks against the runtime.
6
+ // package.json (the app root the builders resolve npm dependencies from), sk.config.json, the Skathi
7
+ // icon as icon.png and a tsconfig.json that type-checks against the runtime.
8
8
  // Nothing is overwritten: an existing file is an error, not a merge.
9
9
 
10
10
  import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
11
11
  import { basename, extname, join, relative, resolve } from "node:path";
12
12
  import * as p from "@clack/prompts";
13
13
  import { runtimeRequire } from "../runtime-path";
14
- import { ConfigError, OPTIONAL, parseParts, sanitizeExeName, type Part } from "./config";
14
+ import { ConfigError, sanitizeExeName } from "./config";
15
15
  import { CLI_VERSION } from "./host";
16
- import { encodePng } from "./icon";
17
16
  import { currentPlatform, parsePlatform, type Platform } from "./platform";
18
17
  import { colorEnabled, paint } from "./term";
19
18
 
@@ -47,6 +46,8 @@ const TEMPLATE_INFO: Record<Template, TemplateInfo> = {
47
46
 
48
47
  export const TEMPLATES_DIR = resolve(import.meta.dir, "..", "templates");
49
48
 
49
+ export const CONFIG_SCHEMA = "./node_modules/@skathi-native/runtime/sk.config.schema.json";
50
+
50
51
  /** Files whose text has its `{{key}}` placeholders filled in; anything else is copied byte for byte. */
51
52
  const TEXT_FILES = new Set([".vue", ".ts", ".css", ".txt", ".json", ".html", ".svg"]);
52
53
 
@@ -54,21 +55,11 @@ export interface CreateOptions {
54
55
  name?: string | undefined;
55
56
  template?: Template | undefined;
56
57
  platforms?: Platform[] | undefined;
57
- /** Engine parts left out of every build; devtools is {@link CreateOptions.keepDevtools}'s. */
58
- without?: Part[] | undefined;
59
58
  /** Whether `sk publish` keeps devtools (`sk build` always has them). */
60
59
  keepDevtools?: boolean | undefined;
61
60
  packageManager?: PackageManager | undefined;
62
61
  }
63
62
 
64
- const ENGINE_PARTS: { value: Exclude<Part, "devtools">; label: string; hint: string }[] = [
65
- { value: "audio", label: "Audio", hint: "Web Audio, <audio>, sound from <video>" },
66
- { value: "clipboard", label: "Clipboard", hint: "navigator.clipboard" },
67
- { value: "storages", label: "Storage on disk", hint: "localStorage and IndexedDB that survive a restart" },
68
- { value: "indexeddb", label: "IndexedDB", hint: "indexedDB" },
69
- { value: "webgpu", label: "WebGPU", hint: "navigator.gpu" },
70
- ];
71
-
72
63
  /** The package manager this was started from (`npm_config_user_agent`), else bun. */
73
64
  export function detectPackageManager(agent = process.env.npm_config_user_agent ?? ""): PackageManager {
74
65
  return PACKAGE_MANAGERS.find((pm) => agent.startsWith(`${pm}/`)) ?? "bun";
@@ -77,26 +68,6 @@ export function detectPackageManager(agent = process.env.npm_config_user_agent ?
77
68
  export const runScript = (pm: PackageManager, script: string) =>
78
69
  pm === "npm" || pm === "bun" ? `${pm} run ${script}` : `${pm} ${script}`;
79
70
 
80
- function icon(): Uint8Array {
81
- const size = 256;
82
- const data = new Uint8Array(size * size * 4);
83
- const r = 56;
84
- for (let y = 0; y < size; y++) {
85
- for (let x = 0; x < size; x++) {
86
- const dx = Math.max(0, Math.abs(x - 127.5) - (128 - r));
87
- const dy = Math.max(0, Math.abs(y - 127.5) - (128 - r));
88
- const inside = dx * dx + dy * dy <= r * r;
89
- const t = (x + y) / (2 * size);
90
- const o = (y * size + x) * 4;
91
- data[o] = Math.round(0x42 + (0x2f - 0x42) * t);
92
- data[o + 1] = Math.round(0xb8 + (0x6f - 0xb8) * t);
93
- data[o + 2] = Math.round(0x83 + (0xd8 - 0x83) * t);
94
- data[o + 3] = inside ? 255 : 0;
95
- }
96
- }
97
- return encodePng({ width: size, height: size, data });
98
- }
99
-
100
71
  const json = (v: unknown) => JSON.stringify(v, null, 2) + "\n";
101
72
 
102
73
  function listFiles(dir: string, prefix = ""): string[] {
@@ -143,9 +114,6 @@ export function create(target: string, options: CreateOptions = {}): string[] {
143
114
  const template = options.template ?? "showcase";
144
115
  const info = TEMPLATE_INFO[template];
145
116
  const platforms = options.platforms?.length ? options.platforms : [currentPlatform()];
146
- const without: Part[] = OPTIONAL.filter((part) =>
147
- part === "devtools" ? !options.keepDevtools : (options.without ?? []).includes(part),
148
- );
149
117
  const runtimeDeps = (runtimeRequire("./package.json") as { dependencies: Record<string, string> }).dependencies;
150
118
  const sdk = `^${CLI_VERSION}`;
151
119
 
@@ -170,17 +138,19 @@ export function create(target: string, options: CreateOptions = {}): string[] {
170
138
  devDependencies: { "@skathi-native/cli": sdk, typescript: "^5", "vue-tsc": "^3" },
171
139
  }),
172
140
  "sk.config.json": json({
141
+ $schema: CONFIG_SCHEMA,
173
142
  name,
174
143
  productName,
175
144
  version: "0.1.0",
176
145
  platforms,
146
+ publishDevtools: options.keepDevtools === true,
177
147
  window: { title: productName, ...info.window, backdrop: "mica" },
178
148
  assets: ["assets"],
179
149
  ...(info.packs ? { packs: info.packs } : {}),
180
- windows: { exeName, icon: "icon.png", without },
150
+ windows: { exeName, icon: "icon.png" },
181
151
  ...(platforms.includes("macos") ? { macos: { bundleId: `com.example.${slug}` } } : {}),
182
152
  }),
183
- "icon.png": icon(),
153
+ "icon.png": readFileSync(join(TEMPLATES_DIR, "icon.png")),
184
154
  "tsconfig.json": json({
185
155
  extends: "@skathi-native/runtime/tsconfig.app.json",
186
156
  include: ["src/**/*.ts", "src/**/*.vue"],
@@ -206,10 +176,10 @@ export interface CreateFlags {
206
176
  name?: string | undefined;
207
177
  template?: string | undefined;
208
178
  os?: string | undefined;
209
- without?: string | undefined;
210
179
  devtools?: boolean | undefined;
211
180
  pm?: string | undefined;
212
181
  yes?: boolean | undefined;
182
+ color?: boolean | undefined;
213
183
  }
214
184
 
215
185
  function parsePm(v: string): PackageManager {
@@ -242,7 +212,6 @@ export async function createCommand(target: string | undefined, flags: CreateFla
242
212
  ?.split(/[\s,]+/)
243
213
  .filter(Boolean)
244
214
  .map(parsePlatform),
245
- without: flags.without !== undefined ? parseParts(flags.without, "--without") : undefined,
246
215
  keepDevtools: flags.devtools,
247
216
  packageManager: flags.pm !== undefined ? parsePm(flags.pm) : undefined,
248
217
  };
@@ -285,17 +254,6 @@ export async function createCommand(target: string | undefined, flags: CreateFla
285
254
  required: true,
286
255
  }),
287
256
  );
288
- if (!options.without) {
289
- const kept = answered(
290
- await p.multiselect<Exclude<Part, "devtools">>({
291
- message: "Engine parts (leaving one out makes the exe smaller)",
292
- options: ENGINE_PARTS,
293
- initialValues: ENGINE_PARTS.map((e) => e.value),
294
- required: false,
295
- }),
296
- );
297
- options.without = ENGINE_PARTS.map((e) => e.value).filter((v) => !kept.includes(v));
298
- }
299
257
  options.keepDevtools ??= answered(
300
258
  await p.confirm({
301
259
  message: "Keep devtools (F12) in published builds? sk build always has them",
@@ -320,7 +278,7 @@ export async function createCommand(target: string | undefined, flags: CreateFla
320
278
  p.note(next, "Next");
321
279
  p.outro(`${options.name ?? basename(resolve(dir))} is ready`);
322
280
  } else {
323
- const c = paint(colorEnabled(process.stdout));
281
+ const c = paint(colorEnabled(process.stdout, flags.color));
324
282
  console.log(`${c.green("✓")} created ${c.cyan(resolve(dir))}\n ${c.dim("next:")} ${next.replace(/\n/g, " && ")}`);
325
283
  }
326
284
  return 0;
package/cli/dev.ts CHANGED
@@ -3,23 +3,32 @@
3
3
  //
4
4
  // The dev host, first hit wins: `--exe` or SK_DEV_HOST; in a checkout, its debug sk-app (`cargo build
5
5
  // -p sk-app`); the cached dev host of this version; a download of it from the release (host-fetch.ts).
6
+ //
7
+ // An app with shaders/*.slang has them compiled into <dist>/effects, which the host reads through
8
+ // SK_EFFECTS_DIR, and recompiled on every change. A good rebuild reaches the running app as a message
9
+ // beside the HMR changes.json and replaces its effects in place; a host that predates that (its
10
+ // --sk-host-info has no `devReload: ["effects"]`) is restarted. A failed rebuild prints the
11
+ // diagnostics and keeps the last good build running.
6
12
 
7
- import { spawn } from "node:child_process";
13
+ import { spawn, type ChildProcess } from "node:child_process";
8
14
  import { existsSync, mkdirSync } from "node:fs";
9
15
  import { join } from "node:path";
16
+ import { compileAppEffects, EffectsError, formatProblems, hasAppEffects, writeEffectFiles } from "../effects/compile";
17
+ import { resolveCompiler } from "../effects/redslangc";
10
18
  import { loadAppConfig } from "./config";
19
+ import { devEffectsWatch, type EffectsWatch } from "./effects";
11
20
  import { cachedHost, checkHost, DEV_HOST, HostError, hostInfo, PKG_DIR, REPO_ROOT, CLI_VERSION } from "./host";
12
- import { fetchHost } from "./host-fetch";
21
+ import { fetchHost, type OnBytes } from "./host-fetch";
13
22
  import { currentPlatform, hostsFor, repoHostExe } from "./platform";
14
23
  import { colorEnabled, paint, progressFor } from "./term";
15
24
 
16
25
  export async function devHost(
17
- options: { exe?: string | undefined; log?: (line: string) => void } = {},
26
+ options: { exe?: string | undefined; log?: (line: string) => void; onBytes?: OnBytes } = {},
18
27
  ): Promise<string> {
19
28
  const log = options.log ?? console.log;
20
29
  const named = options.exe ?? process.env.SK_DEV_HOST;
21
30
  if (named) {
22
- if (!existsSync(named)) throw new HostError(`no dev host at ${named}`);
31
+ if (!existsSync(named)) throw new HostError(`no dev workload at ${named}`);
23
32
  return named;
24
33
  }
25
34
  if (REPO_ROOT) {
@@ -37,26 +46,70 @@ export async function devHost(
37
46
  if (!usable()) {
38
47
  if (process.env.SK_HOST_OFFLINE === "1") {
39
48
  throw new HostError(
40
- `no dev host: ${cached} is missing or unusable and SK_HOST_OFFLINE=1 forbids a download — ` +
41
- "pass --exe <dev host>" +
49
+ `no dev workload: ${cached} is missing or unusable and SK_HOST_OFFLINE=1 forbids a download — ` +
50
+ "pass --exe <dev workload>" +
42
51
  (REPO_ROOT
43
52
  ? `, or build one with \`${["cargo build -p sk-app", ...hostsFor(currentPlatform()).cargoTarget].join(" ")}\``
44
53
  : ""),
45
54
  );
46
55
  }
47
- await fetchHost({ variant: DEV_HOST, log });
56
+ await fetchHost({ variant: DEV_HOST, log, onBytes: options.onBytes });
48
57
  }
49
58
  return cached;
50
59
  }
51
60
 
52
- export async function dev(target: string, options: { exe?: string | undefined } = {}): Promise<number> {
61
+ function reloadsEffects(exe: string): boolean {
62
+ try {
63
+ return hostInfo(exe).devReload?.includes("effects") ?? false;
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ export async function dev(
70
+ target: string,
71
+ options: { exe?: string | undefined; shaderCompiler?: string | undefined; color?: boolean | undefined } = {},
72
+ ): Promise<number> {
53
73
  const config = loadAppConfig(target);
54
- const c = paint(colorEnabled(process.stdout));
55
- const progress = progressFor(process.stderr);
56
- progress.step("dev host");
57
- const exe = await devHost({ ...options, log: (line) => progress.detail(line) }).finally(() => progress.end());
74
+ const c = paint(colorEnabled(process.stdout, options.color));
75
+ const progress = progressFor(process.stderr, colorEnabled(process.stderr, options.color));
76
+ progress.step("dev workload");
77
+ const exe = await devHost({
78
+ ...options,
79
+ log: (line) => progress.detail(line),
80
+ onBytes: (done, total) => progress.bytes(done, total),
81
+ }).catch((e: unknown) => {
82
+ progress.fail();
83
+ throw e;
84
+ });
58
85
  const dist = join(config.appRoot, "dist", ".sk-dev");
59
86
  mkdirSync(dist, { recursive: true });
87
+
88
+ const effectsDir = join(dist, "effects");
89
+ const overridden = !!process.env.SK_EFFECTS_DIR;
90
+ let compiler: string | null = null;
91
+ if (hasAppEffects(config.appRoot) && !overridden) {
92
+ progress.step("effects");
93
+ try {
94
+ compiler = (
95
+ await resolveCompiler({
96
+ named: options.shaderCompiler,
97
+ log: (line) => progress.info(line),
98
+ onBytes: (done, total) => progress.bytes(done, total),
99
+ })
100
+ ).path;
101
+ const effects = await compileAppEffects(config.appRoot, compiler);
102
+ writeEffectFiles(effectsDir, effects.files);
103
+ progress.detail(effects.compiled.map((e) => e.effect.name).join(", "));
104
+ } catch (e) {
105
+ progress.fail();
106
+ const text = e instanceof EffectsError ? formatProblems(e.problems) : e instanceof Error ? e.message : String(e);
107
+ console.error(`${c.red("effects")}: ${text}`);
108
+ if (existsSync(join(effectsDir, "effects.json"))) console.error(c.dim("the app starts with the last good build"));
109
+ }
110
+ }
111
+ progress.end();
112
+
60
113
  const watcher = spawn(process.execPath, [join(PKG_DIR, "build.ts"), config.entry, dist, "--watch"], {
61
114
  cwd: PKG_DIR,
62
115
  stdio: "inherit",
@@ -68,13 +121,42 @@ export async function dev(target: string, options: { exe?: string | undefined }
68
121
  if (Date.now() > deadline) throw new Error("bun build.ts produced no manifest within 2 minutes");
69
122
  await Bun.sleep(100);
70
123
  }
71
- console.log(`${c.green("▶")} ${c.bold(config.name)} ${c.dim(`dist ${dist}, host ${exe}`)}`);
72
- const host = spawn(exe, [], {
73
- stdio: "inherit",
74
- // SK_OWNER_PID: the host dies with this process however it ends (crates/sk-app/src/owner.rs).
75
- env: { ...process.env, SK_DIST: dist, SK_APP_ROOT: config.appRoot, SK_OWNER_PID: String(process.pid) },
76
- });
124
+ console.log(`${c.green("▶")} ${c.bold(config.name)} ${c.dim(`dist ${dist}, workload ${exe}`)}`);
125
+ const start = (): ChildProcess =>
126
+ spawn(exe, [], {
127
+ stdio: "inherit",
128
+ // SK_OWNER_PID: the host dies with this process however it ends (crates/sk-app/src/owner.rs).
129
+ env: {
130
+ ...process.env,
131
+ SK_DIST: dist,
132
+ SK_APP_ROOT: config.appRoot,
133
+ SK_OWNER_PID: String(process.pid),
134
+ ...(!overridden && existsSync(join(effectsDir, "effects.json")) ? { SK_EFFECTS_DIR: effectsDir } : {}),
135
+ },
136
+ });
137
+ let host = start();
138
+ let restarting = false;
139
+ let effectsWatch: EffectsWatch | null = null;
140
+ if (compiler) {
141
+ effectsWatch = devEffectsWatch({
142
+ appRoot: config.appRoot,
143
+ dist,
144
+ out: effectsDir,
145
+ compiler,
146
+ inPlace: reloadsEffects(exe),
147
+ restart: () => {
148
+ restarting = true;
149
+ host.kill();
150
+ },
151
+ log: (line) => console.log(`${c.cyan("↻")} ${line}`),
152
+ onError: (text) => {
153
+ console.error(`${c.red("effects")}: ${text}`);
154
+ console.error(c.dim("the app keeps running the last good build"));
155
+ },
156
+ });
157
+ }
77
158
  const stop = () => {
159
+ effectsWatch?.close();
78
160
  try {
79
161
  watcher.kill();
80
162
  } catch {}
@@ -86,7 +168,15 @@ export async function dev(target: string, options: { exe?: string | undefined }
86
168
  stop();
87
169
  process.exit(130);
88
170
  });
89
- const code: number = await new Promise((done) => host.on("exit", (c) => done(c ?? 0)));
171
+ const code: number = await new Promise((done) => {
172
+ const exited = (status: number | null) => {
173
+ if (!restarting) return done(status ?? 0);
174
+ restarting = false;
175
+ host = start();
176
+ host.on("exit", exited);
177
+ };
178
+ host.on("exit", exited);
179
+ });
90
180
  stop();
91
181
  return code;
92
182
  }