@skathi-native/cli 0.2.0 → 0.3.0

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.
package/check/index.ts CHANGED
@@ -1,20 +1,21 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { createRequire } from "node:module";
3
- import { isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { isAbsolute, join, resolve } from "node:path";
4
4
  import { loadAppConfig } from "../cli/config";
5
5
  import { appShadersDir, compileAppEffects, EffectsError, hasAppEffects } from "../effects/compile";
6
6
  import { resolveCompiler } from "../effects/redslangc";
7
7
  import { quietProgress, type Progress } from "../cli/term";
8
8
  import { Builtins } from "./builtins";
9
- import { codeInfo, REGISTRY } from "./codes";
10
- import { parseCheckConfig, Suppressions } from "./config";
11
- import { rangeOf, ZERO_RANGE, type Finding } from "./finding";
9
+ import { REGISTRY } from "./codes";
10
+ import { parseCheckConfig } from "./config";
11
+ import { cssFindings, readStyleSources } from "./css";
12
+ import { diagnosticsOf, PLATFORM, posix, rangeOf, ZERO_RANGE, type Finding } from "./finding";
12
13
  import { BundleLiveness } from "./bundle";
13
14
  import { buildGraph, GraphFailure, type ModuleGraph } from "./graph";
14
15
  import { Packages } from "./packages";
15
16
  import { buildProgram, readUnits, type TypeScript } from "./program";
16
17
  import { Rules } from "./rules";
17
- import type { CheckReport, Diagnostic } from "./schema";
18
+ import type { CheckReport } from "./schema";
18
19
  import { Typing } from "./typing";
19
20
 
20
21
  export type { CheckReport, Diagnostic } from "./schema";
@@ -22,16 +23,6 @@ export { explain, formatPretty, listCodes } from "./report";
22
23
 
23
24
  const PROD_TS = join(import.meta.dir, "..", "prod.ts");
24
25
 
25
- /** Packages the SDK provides and answers for under AOT; an app cannot swap or retype them. */
26
- const PLATFORM = new Set([
27
- "vue",
28
- "@vue/runtime-core",
29
- "@vue/runtime-dom",
30
- "@vue/reactivity",
31
- "@vue/shared",
32
- "@skathi-native/runtime",
33
- ]);
34
-
35
26
  export class CheckSetupError extends Error {}
36
27
 
37
28
  export interface CheckOptions {
@@ -58,6 +49,10 @@ export interface AnalyzeInput {
58
49
  progress?: Progress | undefined;
59
50
  /** The production bundle: a rule finding in code it cannot run is not reported. */
60
51
  bundle?: ModuleGraph["bundle"];
52
+ /** Stylesheets and pages whose CSS the build includes, besides the components in `modules`. */
53
+ styles?: string[];
54
+ /** The build runs Tailwind over the app's CSS. */
55
+ tailwind?: boolean;
61
56
  }
62
57
 
63
58
  export function loadTypeScript(appRoot: string): TypeScript {
@@ -69,8 +64,6 @@ export function loadTypeScript(appRoot: string): TypeScript {
69
64
  throw new CheckSetupError("sk check needs the typescript package: add it to the app (bun add -d typescript)");
70
65
  }
71
66
 
72
- const posix = (path: string) => path.split(sep).join("/");
73
-
74
67
  export async function runCheck(options: CheckOptions): Promise<CheckReport> {
75
68
  const progress = options.progress ?? quietProgress;
76
69
  const config = loadAppConfig(options.target, { configPath: options.configPath });
@@ -142,6 +135,8 @@ export async function runCheck(options: CheckOptions): Promise<CheckReport> {
142
135
  aliases: graph.aliases,
143
136
  declarations: graph.declarations,
144
137
  bundle: graph.bundle,
138
+ styles: graph.styles ?? [],
139
+ tailwind: graph.tailwind ?? false,
145
140
  allow: checkConfig.allow,
146
141
  deps: options.deps ?? true,
147
142
  findings,
@@ -205,6 +200,13 @@ export function analyze(input: AnalyzeInput): CheckReport {
205
200
  });
206
201
 
207
202
  const analysed = deps ? units : units.filter((u) => !u.owner);
203
+ const styled = [...input.modules.filter((m) => /\.(vue|svelte)$/i.test(m)), ...(input.styles ?? [])];
204
+ if (styled.length) {
205
+ progress.step("CSS");
206
+ findings.push(
207
+ ...cssFindings({ sources: readStyleSources(styled), packages, deps, tailwind: input.tailwind ?? false }),
208
+ );
209
+ }
208
210
  if (units.length) {
209
211
  progress.step("TypeScript program", units.length);
210
212
  const built = buildProgram({
@@ -288,42 +290,12 @@ function report(
288
290
  files: number,
289
291
  scores: ReturnType<Typing["results"]>,
290
292
  ): CheckReport {
291
- const rel = (file: string) => posix(relative(root, file));
292
- const suppress = new Suppressions(input.allow ?? new Map());
293
- const diagnostics: Diagnostic[] = [];
293
+ const { diagnostics, suppressed } = diagnosticsOf(findings, root, packages, input.allow ?? new Map());
294
294
  const owners = new Set<string>();
295
- let suppressed = 0;
296
- for (const f of findings) {
297
- const info = codeInfo(f.code);
298
- const owner = packages.ownerOf(f.file);
299
- if (owner && PLATFORM.has(owner.name)) continue;
300
- const file = rel(f.file);
301
- if (!info.fatal && suppress.matches(f.code, file, owner?.name ?? null)) {
302
- suppressed++;
303
- continue;
304
- }
305
- diagnostics.push({
306
- code: f.code,
307
- severity: info.severity,
308
- message: f.message,
309
- file,
310
- package: owner ? { name: owner.name, version: owner.version } : null,
311
- range: f.range,
312
- help: f.help ?? info.fix,
313
- related: f.related.map((r) => ({ file: rel(r.file), range: r.range, message: r.message })),
314
- });
315
- }
316
295
  for (const u of input.modules) {
317
296
  const owner = packages.ownerOf(u);
318
297
  if (owner && !PLATFORM.has(owner.name) && (input.deps ?? true)) owners.add(`${owner.name}@${owner.version}`);
319
298
  }
320
- diagnostics.sort(
321
- (a, b) =>
322
- (a.file < b.file ? -1 : a.file > b.file ? 1 : 0) ||
323
- a.range.start.line - b.range.start.line ||
324
- a.range.start.character - b.range.start.character ||
325
- a.code.localeCompare(b.code),
326
- );
327
299
  const typing = scores
328
300
  .filter((s) => !(s.owner && PLATFORM.has(s.owner.name)))
329
301
  .map((s) => ({
package/cli/aot-build.ts CHANGED
@@ -12,6 +12,7 @@ import { join, resolve } from "node:path";
12
12
  import { AotError, compileNative, compilerInfo, compilerMismatch, nativeManifest, repoSkAot } from "../aot/native";
13
13
  import type { CompilerInfo } from "../aot/pin";
14
14
  import { TRANSFORM } from "../aot/transform";
15
+ import { diagnosticLine } from "../check/finding";
15
16
  import { exitCode, formatPretty, runCheck, type CheckReport } from "../check/index";
16
17
  import { ConfigError } from "./config";
17
18
  import { CLI_VERSION, HostError, REPO_ROOT, type HostAot, type ResolvedHost } from "./host";
@@ -113,11 +114,6 @@ export async function resolveAotCompiler(
113
114
  return { path: fetched.path, info: await compilerInfo(fetched.path), source: "release" };
114
115
  }
115
116
 
116
- /** One line per diagnostic, for warnings that do not stop the build. */
117
- export function checkLine(d: CheckReport["diagnostics"][number]): string {
118
- return `${d.file}:${d.range.start.line + 1}:${d.range.start.character + 1} ${d.code} ${d.message}`;
119
- }
120
-
121
117
  /** `sk check` over the app: errors (and fatal findings) refuse the build with the report; warnings are printed. */
122
118
  export async function aotCheck(
123
119
  target: string,
@@ -133,7 +129,7 @@ export async function aotCheck(
133
129
  "Fix the errors (sk explain <CODE> says how), or build with --no-aot.",
134
130
  );
135
131
  }
136
- for (const d of report.diagnostics) progress.warn(checkLine(d));
132
+ for (const d of report.diagnostics) progress.warn(diagnosticLine(d));
137
133
  return report;
138
134
  }
139
135
 
package/cli/build-app.ts CHANGED
@@ -15,6 +15,10 @@
15
15
  import { createHash } from "node:crypto";
16
16
  import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
17
17
  import { join, relative, resolve, sep } from "node:path";
18
+ import { parseCheckConfig } from "../check/config";
19
+ import { cssDiagnostics, readStyleSources } from "../check/css";
20
+ import { diagnosticLine } from "../check/finding";
21
+ import type { BuildStyles } from "../check/graph";
18
22
  import { aotCheck, aotPlatformProblem, buildNative, hostAot, type NativeBuild } from "./aot-build";
19
23
  import { collectAssets, type AssetFile } from "./assets";
20
24
  import { ConfigError, loadAppConfig, parseVariant, type AppConfig, type PackConfig, type Variant } from "./config";
@@ -100,6 +104,18 @@ function readBuilderAssets(path: string): BuilderAsset[] {
100
104
  );
101
105
  }
102
106
 
107
+ /** SK4001–SK4005 over the CSS the bundle includes, one line each; `--aot` has them from its full check. */
108
+ function cssWarnings(config: AppConfig, stylesJson: string): string[] {
109
+ if (!existsSync(stylesJson)) return [];
110
+ const styles = JSON.parse(readFileSync(stylesJson, "utf8")) as BuildStyles;
111
+ return cssDiagnostics({
112
+ root: config.appRoot,
113
+ sources: readStyleSources(styles.files),
114
+ allow: parseCheckConfig(config.raw.check).allow,
115
+ tailwind: styles.tailwind,
116
+ }).map(diagnosticLine);
117
+ }
118
+
103
119
  export interface MacBundle extends AppBundleResult {
104
120
  bundleId: string;
105
121
  iconSizes: number[];
@@ -411,8 +427,10 @@ async function build(options: BuildOptions, progress: Progress): Promise<BuildRe
411
427
 
412
428
  const jsOut = join(work, "app.prod.js");
413
429
  const assetsJson = join(work, "assets.json");
430
+ const stylesJson = join(work, "styles.json");
414
431
  // A stale list from an older build must not survive a builder that wrote none.
415
432
  rmSync(assetsJson, { force: true });
433
+ rmSync(stylesJson, { force: true });
416
434
  const tb = performance.now();
417
435
  const defineArgs = (options.defines ?? []).map((d) => `--define=${d}`);
418
436
  const pathArgs = [
@@ -447,6 +465,7 @@ async function build(options: BuildOptions, progress: Progress): Promise<BuildRe
447
465
  const windowJson = readFileSync(join(work, "window.json"));
448
466
  const msBundle = performance.now() - tb;
449
467
  if (aot) await aotCheck(options.target, options.configPath, progress, options.color ?? false);
468
+ else for (const line of cssWarnings(config, stylesJson)) progress.warn(line);
450
469
 
451
470
  progress.step("assets");
452
471
  const ta = performance.now();
package/cli/create.ts CHANGED
@@ -2,9 +2,9 @@
2
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
- // 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, the Skathi
7
- // icon as icon.png and a tsconfig.json that type-checks against the runtime.
5
+ // It copies the template (templates/<template>/ here, or the gallery repo's) with the placeholders filled
6
+ // in, and writes package.json (the app root the builders resolve npm dependencies from), sk.config.json, icon.png (the
7
+ // template's own, else the Skathi icon) 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";
@@ -12,6 +12,7 @@ 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
14
  import { ConfigError, sanitizeExeName } from "./config";
15
+ import { fetchGallery, galleryDir } from "./gallery";
15
16
  import { CLI_VERSION } from "./host";
16
17
  import { currentPlatform, parsePlatform, type Platform } from "./platform";
17
18
  import { colorEnabled, paint } from "./term";
@@ -19,7 +20,7 @@ import { colorEnabled, paint } from "./term";
19
20
  export const PACKAGE_MANAGERS = ["bun", "npm", "pnpm", "yarn"] as const;
20
21
  export type PackageManager = (typeof PACKAGE_MANAGERS)[number];
21
22
 
22
- export const TEMPLATES = ["showcase", "minimal", "svelte"] as const;
23
+ export const TEMPLATES = ["showcase", "minimal", "svelte", "player", "weather"] as const;
23
24
  export type Template = (typeof TEMPLATES)[number];
24
25
 
25
26
  interface Checker {
@@ -30,6 +31,11 @@ interface Checker {
30
31
  }
31
32
 
32
33
  const VUE_TSC: Checker = { script: "vue-tsc --noEmit", devDependencies: { "vue-tsc": "^3" }, sources: "src/**/*.vue" };
34
+ const SVELTE_CHECK: Checker = {
35
+ script: "svelte-check",
36
+ devDependencies: { "svelte-check": "^4" },
37
+ sources: "src/**/*.svelte",
38
+ };
33
39
 
34
40
  interface TemplateInfo {
35
41
  hint: string;
@@ -58,12 +64,41 @@ const TEMPLATE_INFO: Record<Template, TemplateInfo> = {
58
64
  hint: "the minimal app in Svelte 5",
59
65
  dependencies: ["svelte"],
60
66
  window: { width: 760, height: 520, titleBarStyle: "default" },
61
- checker: { script: "svelte-check", devDependencies: { "svelte-check": "^4" }, sources: "src/**/*.svelte" },
67
+ checker: SVELTE_CHECK,
68
+ },
69
+ player: {
70
+ hint: "a music player in Svelte 5, dressed in shaders",
71
+ dependencies: ["svelte"],
72
+ window: { width: 1240, height: 800, minWidth: 480, minHeight: 600, titleBarStyle: "hidden", titleBarHeight: 44 },
73
+ packs: [{ name: "media", match: ["assets/music/**", "assets/covers/**"] }],
74
+ checker: SVELTE_CHECK,
75
+ },
76
+ weather: {
77
+ hint: "a weather app in Vue, its sky and rain drawn by shaders",
78
+ dependencies: [],
79
+ window: { width: 1180, height: 880, minWidth: 980, minHeight: 780, titleBarStyle: "hidden", titleBarHeight: 72 },
80
+ packs: [{ name: "textures", match: ["assets/textures/**"] }],
81
+ checker: VUE_TSC,
62
82
  },
63
83
  };
64
84
 
65
85
  export const TEMPLATES_DIR = resolve(import.meta.dir, "..", "templates");
66
86
 
87
+ /** Templates kept in the skathi-templates repo rather than in this package. */
88
+ const GALLERY: ReadonlySet<Template> = new Set(["player", "weather"]);
89
+
90
+ function templateDir(template: Template): string {
91
+ if (!GALLERY.has(template)) return join(TEMPLATES_DIR, template);
92
+ const dir = galleryDir(template);
93
+ if (!dir) throw new ConfigError(`sk create: the ${template} template has not been downloaded`);
94
+ return dir;
95
+ }
96
+
97
+ /** Downloads the template first when it lives in the gallery repo. */
98
+ export async function prepareTemplate(template: Template): Promise<void> {
99
+ if (GALLERY.has(template)) await fetchGallery(template);
100
+ }
101
+
67
102
  export const CONFIG_SCHEMA = "./node_modules/@skathi-native/runtime/sk.config.schema.json";
68
103
 
69
104
  /** Files whose text has its `{{key}}` placeholders filled in; anything else is copied byte for byte. */
@@ -97,7 +132,7 @@ function listFiles(dir: string, prefix = ""): string[] {
97
132
 
98
133
  /** The template's files, keyed by app-relative path; `{{key}}` is replaced in text files, escaped for a string literal except in .txt. */
99
134
  export function templateFiles(template: Template, values: Record<string, string>): Record<string, string | Uint8Array> {
100
- const dir = join(TEMPLATES_DIR, template);
135
+ const dir = templateDir(template);
101
136
  const out: Record<string, string | Uint8Array> = {};
102
137
  for (const rel of listFiles(dir)) {
103
138
  const bytes = readFileSync(join(dir, rel));
@@ -140,6 +175,7 @@ export function create(target: string, options: CreateOptions = {}): string[] {
140
175
  const sdk = `^${CLI_VERSION}`;
141
176
 
142
177
  const files: Record<string, string | Uint8Array> = {
178
+ "icon.png": readFileSync(join(TEMPLATES_DIR, "icon.png")),
143
179
  ...templateFiles(template, { name, productName }),
144
180
  "package.json": json({
145
181
  name: slug,
@@ -157,7 +193,7 @@ export function create(target: string, options: CreateOptions = {}): string[] {
157
193
  "@skathi-native/runtime": sdk,
158
194
  ...Object.fromEntries(info.dependencies.map((dep) => [dep, runtimeDeps[dep]])),
159
195
  },
160
- devDependencies: { "@skathi-native/cli": sdk, typescript: "^5", ...info.checker.devDependencies },
196
+ devDependencies: { "@skathi-native/cli": sdk, typescript: "^6", ...info.checker.devDependencies },
161
197
  }),
162
198
  "sk.config.json": json({
163
199
  $schema: CONFIG_SCHEMA,
@@ -172,7 +208,6 @@ export function create(target: string, options: CreateOptions = {}): string[] {
172
208
  windows: { exeName, icon: "icon.png" },
173
209
  ...(platforms.includes("macos") ? { macos: { bundleId: `com.example.${slug}` } } : {}),
174
210
  }),
175
- "icon.png": readFileSync(join(TEMPLATES_DIR, "icon.png")),
176
211
  "tsconfig.json": json({
177
212
  extends: "@skathi-native/runtime/tsconfig.app.json",
178
213
  include: ["src/**/*.ts", info.checker.sources],
@@ -293,6 +328,7 @@ export async function createCommand(target: string | undefined, flags: CreateFla
293
328
 
294
329
  dir ??= "my-app";
295
330
  const pm = options.packageManager ?? detectPackageManager();
331
+ await prepareTemplate(options.template ?? "showcase");
296
332
  create(dir, options);
297
333
  const where = relative(process.cwd(), resolve(dir)) || ".";
298
334
  const next = [...(where === "." ? [] : [`cd ${where}`]), `${pm} install`, runScript(pm, "dev")].join("\n");
package/cli/dev.ts CHANGED
@@ -5,10 +5,10 @@
5
5
  // -p sk-app`); the cached dev host of this version; a download of it from the release (host-fetch.ts).
6
6
  //
7
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.
8
+ // SK_EFFECTS_DIR, and recompiled on every change, the first shader of an app that had none too. A
9
+ // good rebuild reaches the running app as a message beside the HMR changes.json and replaces its
10
+ // effects in place; a host that predates that (its --sk-host-info has no `devReload: ["effects"]`)
11
+ // is restarted. A failed rebuild prints the diagnostics and keeps the last good build running.
12
12
 
13
13
  import { spawn, type ChildProcess } from "node:child_process";
14
14
  import { existsSync, mkdirSync } from "node:fs";
@@ -137,12 +137,17 @@ export async function dev(
137
137
  let host = start();
138
138
  let restarting = false;
139
139
  let effectsWatch: EffectsWatch | null = null;
140
- if (compiler) {
140
+ if (!overridden) {
141
+ const shaderCompiler = async (): Promise<string> => {
142
+ compiler ??= (await resolveCompiler({ named: options.shaderCompiler, log: (line) => console.log(c.dim(line)) }))
143
+ .path;
144
+ return compiler;
145
+ };
141
146
  effectsWatch = devEffectsWatch({
142
147
  appRoot: config.appRoot,
143
148
  dist,
144
149
  out: effectsDir,
145
- compiler,
150
+ compiler: shaderCompiler,
146
151
  inPlace: reloadsEffects(exe),
147
152
  restart: () => {
148
153
  restarting = true;
package/cli/effects.ts CHANGED
@@ -2,8 +2,8 @@
2
2
  // (HLSL, WGSL, MSL), so a build made on one OS runs on all three. `sk build` puts them into the payload
3
3
  // as `sk/effects/*` entries; `sk dev` writes them to dist/.sk-dev/effects and points the dev host there.
4
4
 
5
- import { watch, writeFileSync, type FSWatcher } from "node:fs";
6
- import { join } from "node:path";
5
+ import { existsSync, watch, writeFileSync, type FSWatcher } from "node:fs";
6
+ import { basename, join } from "node:path";
7
7
  import {
8
8
  appShadersDir,
9
9
  compileAppEffects,
@@ -69,12 +69,13 @@ export interface EffectsWatch {
69
69
  close(): void;
70
70
  }
71
71
 
72
- /// Recompiles into `out` when a `.slang` under shaders/ changes, debounced. A failed compile keeps the
73
- /// last good files and reports through `onError`.
72
+ /// Recompiles into `out` when a `.slang` under shaders/ changes, debounced; an app without shaders/
73
+ /// is watched for one. A failed compile keeps the last good files and reports through `onError`.
74
+ /// `compiler` may be resolved on the first rebuild, so an app without shaders never fetches one.
74
75
  export function watchAppEffects(options: {
75
76
  appRoot: string;
76
77
  out: string;
77
- compiler: string;
78
+ compiler: string | (() => Promise<string>);
78
79
  onBuilt: (effects: AppEffects) => void;
79
80
  onError: (message: string) => void;
80
81
  debounceMs?: number;
@@ -90,7 +91,8 @@ export function watchAppEffects(options: {
90
91
  }
91
92
  running = true;
92
93
  try {
93
- const effects = await compileAppEffects(options.appRoot, options.compiler);
94
+ const compiler = typeof options.compiler === "string" ? options.compiler : await options.compiler();
95
+ const effects = await compileAppEffects(options.appRoot, compiler);
94
96
  writeEffectFiles(options.out, effects.files);
95
97
  options.onBuilt(effects);
96
98
  } catch (e) {
@@ -105,18 +107,37 @@ export function watchAppEffects(options: {
105
107
  }
106
108
  }
107
109
  };
110
+ const schedule = () => {
111
+ if (timer) clearTimeout(timer);
112
+ timer = setTimeout(() => {
113
+ timer = null;
114
+ void rebuild();
115
+ }, options.debounceMs ?? 120);
116
+ };
108
117
  let watcher: FSWatcher | null = null;
109
- try {
110
- watcher = watch(dir, { recursive: true }, (_event, file) => {
111
- if (file && !String(file).endsWith(".slang")) return;
112
- if (timer) clearTimeout(timer);
113
- timer = setTimeout(() => {
114
- timer = null;
115
- void rebuild();
116
- }, options.debounceMs ?? 120);
117
- });
118
- } catch (e) {
119
- options.onError(`cannot watch ${dir}: ${e instanceof Error ? e.message : String(e)}`);
118
+ const watchShaders = () => {
119
+ try {
120
+ watcher = watch(dir, { recursive: true }, (_event, file) => {
121
+ if (file && !String(file).endsWith(".slang")) return;
122
+ schedule();
123
+ });
124
+ } catch (e) {
125
+ options.onError(`cannot watch ${dir}: ${e instanceof Error ? e.message : String(e)}`);
126
+ }
127
+ };
128
+ if (existsSync(dir)) {
129
+ watchShaders();
130
+ } else {
131
+ try {
132
+ watcher = watch(options.appRoot, (_event, file) => {
133
+ if (file !== basename(dir) || !existsSync(dir)) return;
134
+ watcher?.close();
135
+ watchShaders();
136
+ schedule();
137
+ });
138
+ } catch (e) {
139
+ options.onError(`cannot watch ${options.appRoot}: ${e instanceof Error ? e.message : String(e)}`);
140
+ }
120
141
  }
121
142
  return {
122
143
  close() {
@@ -135,7 +156,7 @@ export function devEffectsWatch(options: {
135
156
  appRoot: string;
136
157
  dist: string;
137
158
  out: string;
138
- compiler: string;
159
+ compiler: string | (() => Promise<string>);
139
160
  inPlace: boolean;
140
161
  restart: () => void;
141
162
  log: (line: string) => void;
package/cli/gallery.ts ADDED
@@ -0,0 +1,106 @@
1
+ // Templates that live in github.com/argon-chat/skathi-templates. A Skathi checkout has them in its
2
+ // templates/ submodule; an installed CLI downloads the commit it was released with, which the release
3
+ // writes into gallery.json beside package.json.
4
+
5
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
+ import { dirname, join, resolve } from "node:path";
7
+ import { ConfigError } from "./config";
8
+ import { cacheRoot } from "./host";
9
+
10
+ export const GALLERY_REPO = "argon-chat/skathi-templates";
11
+
12
+ const CHECKOUT = resolve(import.meta.dir, "../../../templates");
13
+ const PIN = resolve(import.meta.dir, "../gallery.json");
14
+
15
+ function pinnedCommit(): string | null {
16
+ try {
17
+ const commit: unknown = JSON.parse(readFileSync(PIN, "utf8")).commit;
18
+ return typeof commit === "string" && /^[0-9a-f]{40}$/.test(commit) ? commit : null;
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ const cachedGallery = (commit: string) => join(dirname(cacheRoot()), "templates", commit);
25
+
26
+ /** Where the template's files are, or null when they still have to be downloaded. */
27
+ export function galleryDir(template: string): string | null {
28
+ const local = join(CHECKOUT, template);
29
+ if (existsSync(local)) return local;
30
+ const commit = pinnedCommit();
31
+ const cached = commit ? join(cachedGallery(commit), template) : null;
32
+ return cached && existsSync(cached) ? cached : null;
33
+ }
34
+
35
+ /** Downloads the pinned templates unless they are already here. */
36
+ export async function fetchGallery(template: string): Promise<string> {
37
+ const ready = galleryDir(template);
38
+ if (ready) return ready;
39
+ const commit = pinnedCommit();
40
+ if (!commit) {
41
+ throw new ConfigError(
42
+ `sk create: the ${template} template comes from github.com/${GALLERY_REPO}; in a Skathi checkout run ` +
43
+ "`git submodule update --init templates`",
44
+ );
45
+ }
46
+ const url = `https://codeload.github.com/${GALLERY_REPO}/tar.gz/${commit}`;
47
+ const res = await fetch(url, { headers: { "User-Agent": "skathi-cli" } });
48
+ if (!res.ok) throw new ConfigError(`sk create: downloading the ${template} template from ${url}: HTTP ${res.status}`);
49
+ const files = untar(Bun.gunzipSync(new Uint8Array(await res.arrayBuffer())));
50
+
51
+ const root = cachedGallery(commit);
52
+ const part = `${root}.part-${process.pid}`;
53
+ rmSync(part, { recursive: true, force: true });
54
+ for (const [path, bytes] of files) {
55
+ const rel = path.split("/").slice(1).join("/");
56
+ if (!rel) continue;
57
+ const dest = join(part, rel);
58
+ mkdirSync(dirname(dest), { recursive: true });
59
+ writeFileSync(dest, bytes);
60
+ }
61
+ rmSync(root, { recursive: true, force: true });
62
+ renameSync(part, root);
63
+
64
+ const dir = galleryDir(template);
65
+ if (!dir) throw new ConfigError(`sk create: github.com/${GALLERY_REPO} at ${commit} has no ${template} template`);
66
+ return dir;
67
+ }
68
+
69
+ /** The regular files of a tar archive, by path. */
70
+ export function untar(tar: Uint8Array): Map<string, Uint8Array> {
71
+ const decoder = new TextDecoder();
72
+ const text = (from: number, length: number) => {
73
+ const field = tar.subarray(from, from + length);
74
+ const end = field.indexOf(0);
75
+ return decoder.decode(end < 0 ? field : field.subarray(0, end));
76
+ };
77
+ const out = new Map<string, Uint8Array>();
78
+ let longName: string | null = null;
79
+ for (let at = 0; at + 512 <= tar.length;) {
80
+ const name = text(at, 100);
81
+ if (!name) break;
82
+ const size = Number.parseInt(text(at + 124, 12).trim() || "0", 8);
83
+ const type = tar[at + 156] ?? 0;
84
+ const prefix = text(at + 345, 155);
85
+ const body = tar.subarray(at + 512, at + 512 + size);
86
+ at += 512 + Math.ceil(size / 512) * 512;
87
+
88
+ if (type === 0x78 /* x: pax */) {
89
+ longName = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(decoder.decode(body))?.[1] ?? null;
90
+ continue;
91
+ }
92
+ if (type === 0x4c /* L: GNU long name */) {
93
+ longName = decoder.decode(body).replace(/\0+$/, "");
94
+ continue;
95
+ }
96
+ const path = longName ?? (prefix ? `${prefix}/${name}` : name);
97
+ longName = null;
98
+ if (type !== 0x30 && type !== 0) continue;
99
+ if (path.split("/").some((part) => part === ".." || part === "")) {
100
+ if (!path.endsWith("/")) throw new ConfigError(`the template archive has an unsafe path: ${path}`);
101
+ continue;
102
+ }
103
+ out.set(path, body);
104
+ }
105
+ return out;
106
+ }
package/cli/sk.ts CHANGED
@@ -140,7 +140,10 @@ export function cli(run: Run): Command {
140
140
  .description("Start a new app. In a terminal it asks for whatever the options leave open.")
141
141
  .argument("[dir]")
142
142
  .option("--name <name>", "The app's name (default: the directory's)")
143
- .option("--template <name>", "showcase (every feature) or minimal")
143
+ .option(
144
+ "--template <name>",
145
+ "showcase (every feature), minimal, svelte, player (a Svelte music player) or weather (a Vue weather app)",
146
+ )
144
147
  .option("--os <list>", "What to package for: windows, macos, linux")
145
148
  .option("--devtools", "Keep devtools (F12) in published builds")
146
149
  .addOption(hidden("--no-devtools"))
@@ -165,7 +168,7 @@ export function cli(run: Run): Command {
165
168
  .command("dev")
166
169
  .summary("Run the app with hot reload")
167
170
  .description(
168
- "Run the app with hot reload: edits to .vue, .ts and .css apply without a restart; an edit to a shaders/*.slang effect recompiles it and restarts the app.",
171
+ "Run the app with hot reload: edits to .vue, .ts and .css apply without a restart; an edit to a shaders/*.slang effect recompiles it and reloads it in the running app.",
169
172
  )
170
173
  .argument("[app]")
171
174
  .option("--exe <workload>", "Run this dev workload instead of the cached one")
@@ -407,7 +407,7 @@ export const COMMANDS: CommandSpec[] = [
407
407
  {
408
408
  cmd: "screenshot",
409
409
  description:
410
- "Capture the app window to a PNG. Default backend is gpui's render_to_image readback: the " +
410
+ "Capture the app window (or the one `window` names) to a PNG. Default backend is gpui's render_to_image readback: the " +
411
411
  "CLIENT area exactly (clientX/clientY come back 0), works unfocused, occluded, off-screen " +
412
412
  "and minimized, and never raises or activates the window — but it cannot see a mica/acrylic " +
413
413
  "backdrop, which DWM composites under the app. Pass backend=print_window for the composed " +
package/devtools/ctl.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
 
12
12
  import { connect } from "node:net";
13
- import { readFileSync } from "node:fs";
13
+ import { existsSync, readFileSync } from "node:fs";
14
14
  import { resolve, dirname, join } from "node:path";
15
15
  import { fileURLToPath } from "node:url";
16
16
 
@@ -18,7 +18,8 @@ import { buildRequest, usageBlock, UsageError, splitArgs } from "./commands";
18
18
  import { appSlot } from "./apps";
19
19
 
20
20
  const HERE = dirname(fileURLToPath(import.meta.url));
21
- const DEFAULT_DIST = resolve(HERE, "..", "dist");
21
+ const APP_DIST = resolve("dist", ".sk-dev");
22
+ const DEFAULT_DIST = existsSync(join(APP_DIST, "devtools.json")) ? APP_DIST : resolve(HERE, "..", "dist");
22
23
  /** A wedged pump must never hang the caller. Overridable with --timeout <ms>. */
23
24
  const DEFAULT_TIMEOUT_MS = 10_000;
24
25
 
@@ -71,7 +72,7 @@ function readHandshake(dir: string): Handshake {
71
72
  } catch {
72
73
  die(
73
74
  `no devtools.json at ${path} — is a dev host running with this dist?\n` +
74
- ` start one: SK_DIST=${dir} target/x86_64-pc-windows-msvc/debug/sk-app.exe\n` +
75
+ ` start one: run \`sk dev\` in the app's folder, then run this from the same folder\n` +
75
76
  ` or point at another slot: --dist <dir>`,
76
77
  );
77
78
  }
package/effects/sk.slang CHANGED
@@ -213,6 +213,11 @@ public struct SkBackdropRadiusAttribute
213
213
  /// `input.time` (a speed), so `speed: 0` costs nothing. At most one per
214
214
  /// effect; an effect with no `[SkAnimated]` parameter never repaints on its
215
215
  /// own.
216
+ ///
217
+ /// Use it only as a factor of `input.time` (`input.time * speed`): the host
218
+ /// integrates the speed per element and hands the shader the value that makes
219
+ /// that product the phase reached so far, so a change of speed (or a
220
+ /// transition of it) carries on from where the motion is instead of jumping.
216
221
  [__AttributeUsage(_AttributeTargets.Var)]
217
222
  public struct SkAnimatedAttribute
218
223
  {
@@ -299,7 +304,7 @@ public struct SkCorners
299
304
  public float bottom_left;
300
305
  };
301
306
 
302
- /// Keep in sync with `gpui::EffectQuad` (vendor/zed/crates/gpui/src/scene.rs),
307
+ /// Keep in sync with `gpui::EffectQuad` (vendor/gpui/crates/gpui/src/scene.rs),
303
308
  /// `struct EffectQuad` in gpui_windows/src/effects.hlsl and in
304
309
  /// gpui_wgpu/src/shaders_effects.wgsl. 56 words / 224 bytes.
305
310
  ///
package/gallery.json ADDED
@@ -0,0 +1 @@
1
+ { "commit": "e0197b7ed18fa944aeca6f3960b9d20fb54f5ffb" }