@skathi-native/cli 0.0.0 → 0.1.0-beta.1

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/build.ts ADDED
@@ -0,0 +1,1236 @@
1
+ // Dev builder: two-tier output for Vue HMR.
2
+ // Usage: bun build.ts [app-entry.js] [dist-dir] [--watch]
3
+ //
4
+ // dist/vendor.js IIFE: @vue/runtime-core + src/runtime.ts + src/loader.ts.
5
+ // dist/modules/<enc>.js one classic script per app module; <enc> is the id with "/" -> "__".
6
+ // dist/manifest.json { rev, vendorRev, entry, modules, deps }
7
+ // dist/changes.json { rev, vendorRev, changed: [{ id, kind }] }
8
+ //
9
+ // Module ids are workspace-relative POSIX paths. Change kind: script or <style> scoped/module/lang
10
+ // shape changed -> "reload"; template -> "rerender" (state survives); <style> text only ->
11
+ // "css-only"; non-.vue source -> "reload".
12
+ // hoistStatic and inlineTemplate are forced off: the host has no insertStaticContent, and an inline
13
+ // render inside setup() could not be swapped without losing state.
14
+ // npm dependencies are one shared module per package entry (inlining per importer breaks
15
+ // module-scope identity such as reka-ui's Symbol() injection keys); vue, @skathi-native/runtime, vue-router
16
+ // and pinia stay external so libraries land on our runtime.
17
+
18
+ import { parse, compileScript, compileTemplate, compileStyle, registerTS } from "@vue/compiler-sfc";
19
+ import type { BindingMetadata, SFCBlock, SFCDescriptor } from "@vue/compiler-sfc";
20
+ import { createRequire } from "module";
21
+ import { resolve, dirname, isAbsolute, join, relative, sep } from "path";
22
+ import {
23
+ existsSync,
24
+ mkdirSync,
25
+ readdirSync,
26
+ readFileSync,
27
+ realpathSync,
28
+ renameSync,
29
+ statSync,
30
+ writeFileSync,
31
+ rmSync,
32
+ } from "fs";
33
+
34
+ import { TW_ID, declaresUtilities, findConfig, generate as generateTailwind, needsTailwindPass } from "./tailwind";
35
+ import { pruneVendorPrefixes } from "./css-prefixes";
36
+ import { LOADER_ENTRY, RUNTIME_ENTRY, RUNTIME_SRC_DIR, isPreseeded, runtimeRequire } from "./runtime-path";
37
+ import {
38
+ GLOB_TRIPWIRE,
39
+ LEAF_IMPORT,
40
+ SFC_FS,
41
+ appDefines,
42
+ devEsmInterop,
43
+ devImportsPlugin,
44
+ frameworkDep,
45
+ importerDir,
46
+ inlineCssImports,
47
+ readPackageJson,
48
+ resolveImport,
49
+ svgDefaultOf,
50
+ tagModuleNamespaces,
51
+ takeDefineArgs,
52
+ transformSource,
53
+ viteShapesPlugin,
54
+ } from "./vitecompat";
55
+ import { colorEnabled, paint } from "./cli/term";
56
+
57
+ const C = paint(colorEnabled(process.stdout));
58
+ const styled = (rest: (text: string) => string) => (text: string) => {
59
+ const m = /^(\[[^\]]*\]) ([\s\S]*)$/.exec(text);
60
+ return m ? `${C.dim(m[1]!)} ${rest(m[2]!)}` : rest(text);
61
+ };
62
+ const say = (text: string) => console.log(styled((t) => t)(text));
63
+ const warn = (text: string) => console.warn(styled(C.yellow)(text));
64
+ const fail = (text: string, ...rest: unknown[]) => console.error(styled(C.red)(text), ...rest);
65
+
66
+ const { defines: cliDefines, rest: argv } = takeDefineArgs(process.argv.slice(2));
67
+ const positional = argv.filter((a) => !a.startsWith("--"));
68
+ const WATCH = argv.includes("--watch");
69
+
70
+ const PKG_DIR = import.meta.dir; // .../packages/cli
71
+ const WS_ROOT = resolve(PKG_DIR, "../.."); // the checkout root, when this package is in one
72
+
73
+ const ENTRY_ABS = resolve(positional[0] ?? join(WS_ROOT, "apps/hello/src/main.ts"));
74
+ const APP_SRC_DIR = dirname(ENTRY_ABS);
75
+ const DIST = resolve(positional[1] ?? join(PKG_DIR, "dist"));
76
+ const MODULES_DIR = join(DIST, "modules");
77
+
78
+ const SOURCE_EXT = /\.(vue|js|ts|mjs)$/;
79
+
80
+ // The window block of sk.config.json is copied verbatim into the manifest: the host reads it
81
+ // before the window opens, the only time creation-time options can be set without a flash.
82
+ const SK_CONFIG_DIR = APP_SRC_DIR.endsWith(`${sep}src`) ? dirname(APP_SRC_DIR) : APP_SRC_DIR;
83
+ const SK_CONFIG_PATH = join(SK_CONFIG_DIR, "sk.config.json");
84
+
85
+ function readSkConfig(): Record<string, unknown> | undefined {
86
+ if (!existsSync(SK_CONFIG_PATH)) return undefined;
87
+ try {
88
+ const cfg = JSON.parse(readFileSync(SK_CONFIG_PATH, "utf8"));
89
+ return cfg && typeof cfg === "object" ? cfg : undefined;
90
+ } catch (e) {
91
+ // A malformed config must not fail the build, but must not be silently ignored either.
92
+ fail(`[build] ${SK_CONFIG_PATH}: ${e}`);
93
+ return undefined;
94
+ }
95
+ }
96
+
97
+ // Top-level "devtools": false goes inside the window block (the host reads it before the window
98
+ // exists); a window block that sets it itself wins.
99
+ function foldDevtoolsFlag(
100
+ cfg: Record<string, unknown> | undefined,
101
+ win: Record<string, unknown> | undefined,
102
+ ): Record<string, unknown> | undefined {
103
+ if (!cfg || typeof cfg.devtools !== "boolean") return win;
104
+ if (win && typeof win.devtools === "boolean") return win;
105
+ return { ...(win ?? {}), devtools: cfg.devtools };
106
+ }
107
+
108
+ function foldHttpCache(
109
+ cfg: Record<string, unknown> | undefined,
110
+ win: Record<string, unknown> | undefined,
111
+ ): Record<string, unknown> | undefined {
112
+ if (!cfg || cfg.httpCache === undefined) return win;
113
+ if (win && win.httpCache !== undefined) return win;
114
+ return { ...(win ?? {}), httpCache: cfg.httpCache };
115
+ }
116
+
117
+ function readWindowConfig(): Record<string, unknown> | undefined {
118
+ const cfg = readSkConfig();
119
+ const win = cfg && typeof cfg.window === "object" && cfg.window ? (cfg.window as Record<string, unknown>) : undefined;
120
+ return foldHttpCache(cfg, foldDevtoolsFlag(cfg, win));
121
+ }
122
+
123
+ function readAppName(): string | undefined {
124
+ const cfg = readSkConfig();
125
+ const name = cfg?.name;
126
+ return typeof name === "string" && name.trim() ? name.trim() : undefined;
127
+ }
128
+
129
+ // Launch keys the host reads before anything else; only well-typed keys are copied (`sk build`
130
+ // is where a wrong one is an error).
131
+ function readLaunchConfig(): Record<string, unknown> | undefined {
132
+ const cfg = readSkConfig();
133
+ if (!cfg) return undefined;
134
+ const out: Record<string, unknown> = {};
135
+ if (typeof cfg.id === "string" && cfg.id.trim()) out.id = cfg.id.trim();
136
+ if (typeof cfg.singleInstance === "boolean") out.singleInstance = cfg.singleInstance;
137
+ if (typeof cfg.raiseOnSecondInstance === "boolean") out.raiseOnSecondInstance = cfg.raiseOnSecondInstance;
138
+ if (Array.isArray(cfg.protocols)) {
139
+ out.protocols = cfg.protocols.filter((p): p is string => typeof p === "string" && p.trim() !== "");
140
+ }
141
+ for (const key of ["id", "singleInstance", "raiseOnSecondInstance", "protocols"]) {
142
+ if (cfg[key] !== undefined && out[key] === undefined) {
143
+ fail(`[build] ${SK_CONFIG_PATH}: "${key}" has the wrong type and was ignored`);
144
+ }
145
+ }
146
+ return Object.keys(out).length ? out : undefined;
147
+ }
148
+
149
+ // Ids are relative to the checkout for its own apps, else to the app: an app elsewhere (or a package
150
+ // installed outside its tree) must not get ids that climb out of it. A file on another drive keeps its
151
+ // absolute path, minus the drive's colon, which a module file name cannot hold.
152
+ const toId = (abs: string) =>
153
+ relative(ID_ROOT, abs)
154
+ .split(sep)
155
+ .join("/")
156
+ .replace(/^([A-Za-z]):/, "$1");
157
+ const encId = (id: string) => id.split("/").join("__") + ".js";
158
+ const J = (v: unknown) => JSON.stringify(v);
159
+
160
+ function findAppRoot(startDir: string, stopDir: string): string {
161
+ let dir = startDir;
162
+ for (;;) {
163
+ // The workspace root's package.json is the SDK's, not an app's.
164
+ if (dir === stopDir) return startDir;
165
+ if (existsSync(join(dir, "package.json")) || existsSync(join(dir, "node_modules"))) return dir;
166
+ const parent = dirname(dir);
167
+ if (parent === dir) return startDir;
168
+ dir = parent;
169
+ }
170
+ }
171
+ const appRootArg = argv.find((arg) => arg.startsWith("--app-root="))?.slice("--app-root=".length);
172
+ const APP_ROOT = appRootArg ? resolve(appRootArg) : findAppRoot(APP_SRC_DIR, WS_ROOT);
173
+ if (appRootArg && !existsSync(join(APP_ROOT, "package.json"))) {
174
+ throw new Error(`--app-root must name an application with package.json: ${APP_ROOT}`);
175
+ }
176
+ const inside = (dir: string, root: string) => {
177
+ const rel = relative(root, dir);
178
+ return !rel.startsWith("..") && !isAbsolute(rel);
179
+ };
180
+ const ID_ROOT = inside(APP_ROOT, WS_ROOT) ? WS_ROOT : APP_ROOT;
181
+ const appRequire = createRequire(join(APP_ROOT, "package.json"));
182
+ const APP_PKG = APP_ROOT === PKG_DIR ? null : readPackageJson(APP_ROOT);
183
+ const FRAMEWORK = new Map(
184
+ ["vue-router", "pinia"].map(
185
+ (name) =>
186
+ [
187
+ name,
188
+ frameworkDep(
189
+ name,
190
+ APP_PKG,
191
+ (spec) => appRequire.resolve(spec),
192
+ (spec) => runtimeRequire.resolve(spec),
193
+ ),
194
+ ] as const,
195
+ ),
196
+ );
197
+
198
+ /** Resolves a bare specifier from the app root with browser/ESM conditions; createRequire cannot see ESM-only `exports` maps. */
199
+ function resolveFromApp(spec: string): string {
200
+ try {
201
+ return Bun.resolveSync(spec, APP_ROOT);
202
+ } catch {
203
+ return appRequire.resolve(spec);
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Entry files to try for an npm package, best first: what a bundler picks for a browser build
209
+ * (`require` before `import`: reka-ui's ESM entry breaks under Bun's CJS output), then Node's CJS
210
+ * entry, then Bun's. A candidate whose build fails falls through.
211
+ */
212
+ async function entryCandidates(spec: string, from = APP_ROOT): Promise<string[]> {
213
+ const out: string[] = [];
214
+ for (const kind of ["require", "import"] as const) {
215
+ const hit = await bundlerResolve(spec, from, kind);
216
+ if (hit && !out.includes(hit)) out.push(hit);
217
+ }
218
+ try {
219
+ const req = from === APP_ROOT ? appRequire : createRequire(join(from, "package.json"));
220
+ const cjs = req.resolve(spec);
221
+ if (isAbsolute(cjs) && !out.includes(cjs)) out.push(cjs);
222
+ } catch {}
223
+ try {
224
+ const esm = Bun.resolveSync(spec, from);
225
+ if (isAbsolute(esm) && !out.includes(esm)) out.push(esm);
226
+ } catch {}
227
+ return out;
228
+ }
229
+
230
+ async function bundlerResolve(spec: string, from: string, kind: "require" | "import"): Promise<string | null> {
231
+ const probe = join(from, "__sk_resolve_probe__.js"); // never written: onLoad answers for it
232
+ let hit: string | null = null;
233
+ await Bun.build({
234
+ entrypoints: [probe],
235
+ target: "browser",
236
+ format: "cjs",
237
+ plugins: [
238
+ {
239
+ name: "sk-resolve-probe",
240
+ setup(b: Bun.PluginBuilder) {
241
+ b.onResolve({ filter: /__sk_resolve_probe__\.js$/ }, () => ({ path: probe }));
242
+ b.onLoad({ filter: /.*/ }, (args: Bun.OnLoadArgs) => {
243
+ if (args.path === probe) {
244
+ return { contents: kind === "require" ? `require(${J(spec)});` : `import ${J(spec)};`, loader: "js" };
245
+ }
246
+ hit ??= args.path;
247
+ return { contents: "", loader: "js" };
248
+ });
249
+ },
250
+ },
251
+ ],
252
+ }).catch(() => null);
253
+ return hit && isAbsolute(hit) ? hit : null;
254
+ }
255
+
256
+ // compileScript needs `fs` (Bun is not detected as Node) and `registerTS` (cross-package type
257
+ // resolution loads typescript from the app's node_modules). SFC_FS answers fileExists for files
258
+ // only: compiler-sfc probes ./types before ./types.ts.
259
+
260
+ const TS_AVAILABLE = (() => {
261
+ try {
262
+ const ts = appRequire("typescript");
263
+ registerTS(() => ts);
264
+ return true;
265
+ } catch {
266
+ return false;
267
+ }
268
+ })();
269
+
270
+ {
271
+ const aliases = readSkConfig()?.aliases;
272
+ if (aliases && typeof aliases === "object" && Object.keys(aliases).length) {
273
+ warn(
274
+ `[build] sk.config.json "aliases" (${Object.keys(aliases).join(", ")}) are applied by sk build only; this dev build resolves them from node_modules`,
275
+ );
276
+ }
277
+ }
278
+
279
+ // The app's defines: sk.config.json "define" plus `--define K=V`, with Vite semantics.
280
+ const APP_DEFINES = appDefines(readSkConfig()?.define, cliDefines, SK_CONFIG_PATH);
281
+ if (APP_DEFINES.errors.length) {
282
+ for (const e of APP_DEFINES.errors) fail(`[build] ${e}`);
283
+ process.exit(1);
284
+ }
285
+
286
+ const VITE_ENV_DEV: Record<string, unknown> = {
287
+ MODE: "development",
288
+ DEV: true,
289
+ PROD: false,
290
+ SSR: false,
291
+ BASE_URL: "/",
292
+ SK: true,
293
+ };
294
+ for (const [k, v] of Object.entries(APP_DEFINES.defines)) {
295
+ if (!k.startsWith("import.meta.env.")) continue;
296
+ try {
297
+ VITE_ENV_DEV[k.slice("import.meta.env.".length)] = JSON.parse(v);
298
+ } catch {}
299
+ }
300
+
301
+ const DEFINES: Record<string, string> = {
302
+ __DEV__: "true",
303
+ "process.env.NODE_ENV": '"development"',
304
+ __FEATURE_SUSPENSE__: "true",
305
+ __COMPAT__: "false",
306
+ __BROWSER__: "false",
307
+ __ESM_BUNDLER__: "true",
308
+ __GLOBAL__: "false",
309
+ __NODE_JS__: "false",
310
+ __SSR__: "false",
311
+ __TEST__: "false",
312
+ __VERSION__: '"3.5"',
313
+ // `import.meta` is a SyntaxError in a classic script, so substitute what Vite would inline.
314
+ // Dotted forms first (Bun matches the longest key). Object values are JSON.stringify'd: Bun
315
+ // parses a define value as JSON or an identifier and inserts anything else as a string.
316
+ "import.meta.env.MODE": '"development"',
317
+ "import.meta.env.DEV": "true",
318
+ "import.meta.env.PROD": "false",
319
+ "import.meta.env.SSR": "false",
320
+ "import.meta.env.BASE_URL": '"/"',
321
+ // `true` in every Skathi build, undefined under Vite: `if (!import.meta.env.SK)` is dropped
322
+ // by Bun while parsing.
323
+ "import.meta.env.SK": "true",
324
+ "import.meta.env": JSON.stringify(VITE_ENV_DEV),
325
+ // Library code guards on it; undefined means "not a dev server" (our HMR rides __VUE_HMR_RUNTIME__).
326
+ "import.meta.hot": "undefined",
327
+ "import.meta.url": '"sk://module"',
328
+ // Leftover import.meta.glob calls are defined to a findable name so buildModule can fail clearly.
329
+ "import.meta.glob": GLOB_TRIPWIRE,
330
+ "import.meta": JSON.stringify({ env: VITE_ENV_DEV, url: "sk://module" }),
331
+ ...APP_DEFINES.defines,
332
+ };
333
+
334
+ function writeAtomic(path: string, text: string) {
335
+ const tmp = path + ".tmp";
336
+ writeFileSync(tmp, text);
337
+ renameSync(tmp, path);
338
+ }
339
+
340
+ function ensureDirs() {
341
+ mkdirSync(MODULES_DIR, { recursive: true });
342
+ }
343
+
344
+ async function buildVendor() {
345
+ for (const [name, dep] of FRAMEWORK) {
346
+ if (dep.warning) devAdvise(dep.warning);
347
+ say(`${stamp()} ${name} ${dep.version ?? "unknown"}: the ${dep.from === "app" ? "app's" : "runtime's"} copy`);
348
+ }
349
+ const result = await Bun.build({
350
+ entrypoints: [LOADER_ENTRY],
351
+ format: "iife",
352
+ target: "browser",
353
+ define: DEFINES,
354
+ plugins: [
355
+ {
356
+ // vue-router and others import from "vue": that must be our runtime. Exact-match filter only:
357
+ // bun 1.4 crashes on catch-all onResolve filters.
358
+ name: "vendor-vue-alias",
359
+ setup(b: Bun.PluginBuilder) {
360
+ b.onResolve({ filter: /^vue$/ }, () => ({ path: RUNTIME_ENTRY }));
361
+ // The app owns these packages in dev and prod; mixing majors breaks store/router identity.
362
+ b.onResolve({ filter: /^(vue-router|pinia)$/ }, (args: Bun.OnResolveArgs) => ({
363
+ path: FRAMEWORK.get(args.path)!.path,
364
+ }));
365
+ },
366
+ },
367
+ ],
368
+ });
369
+ if (!result.success) {
370
+ for (const log of result.logs) console.error(log);
371
+ throw new Error("vendor build failed");
372
+ }
373
+ const text = await result.outputs[0]!.text();
374
+ // The pre-seeded "vue" namespace must still carry the compiler helpers; if Bun tree-shakes the
375
+ // `export *` re-export, templates die with "not a function".
376
+ for (const sym of ["openBlock", "createElementBlock", "createElementVNode", "toDisplayString"]) {
377
+ if (!text.includes(sym)) throw new Error(`vendor bundle is missing ${sym}`);
378
+ }
379
+ writeAtomic(join(DIST, "vendor.js"), text);
380
+ // vendorRev is a CONTENT hash: restarting the watcher must not make a running host believe its
381
+ // already-evaluated vendor.js is stale.
382
+ vendorRev = Number(BigInt.asUintN(48, BigInt(Bun.hash(text))));
383
+ return text.length;
384
+ }
385
+
386
+ const scopeIdOf = (id: string) => Bun.hash(id).toString(16).slice(0, 8);
387
+
388
+ let capturedCss: string | null = null;
389
+
390
+ const devAdvised = new Set<string>();
391
+ function devAdvise(m: string) {
392
+ if (devAdvised.has(m)) return;
393
+ devAdvised.add(m);
394
+ warn(`${stamp()} advisory: ${m}`);
395
+ }
396
+
397
+ async function viteCss(text: string, from: string, label: string): Promise<string> {
398
+ const css = inlineCssImports(text, from, SK_CONFIG_DIR, devAdvise);
399
+ if (!TW_CONFIG || !needsTailwindPass(css)) return css;
400
+ try {
401
+ return await generateTailwind(TW_CONFIG, { text: css, from });
402
+ } catch (e) {
403
+ fail(`${stamp()} ${label}: tailwind pass failed — emitting the source verbatim`, e);
404
+ return css;
405
+ }
406
+ }
407
+
408
+ async function compileVue(
409
+ absPath: string,
410
+ source: string,
411
+ captureCss = true,
412
+ ): Promise<{ contents: string; loader: "js" | "ts" }> {
413
+ const id = toId(absPath);
414
+ const { descriptor, errors } = parse(source, { filename: absPath });
415
+ if (errors.length) {
416
+ throw new Error(`${id}: ${errors.map((e) => e.message).join("; ")}`);
417
+ }
418
+ const shortId = scopeIdOf(id);
419
+ const scopeId = `data-v-${shortId}`;
420
+ const hasScoped = descriptor.styles.some((s) => s.scoped);
421
+ // compileScript leaves TS syntax in place, so the loader must follow the block's lang. RETURNED,
422
+ // not stashed: the style pass awaits and compiles can interleave.
423
+ const isTS = /^tsx?$/.test(descriptor.scriptSetup?.lang ?? descriptor.script?.lang ?? "");
424
+
425
+ const chunks: string[] = [];
426
+ let bindings: BindingMetadata | undefined;
427
+
428
+ if (descriptor.scriptSetup || descriptor.script) {
429
+ const compiled = compileScript(descriptor, {
430
+ id: shortId,
431
+ inlineTemplate: false, // REQUIRED for rerender-based HMR
432
+ genDefaultAs: "_sfc_main",
433
+ fs: SFC_FS, // imported-type resolution — see SFC_FS above
434
+ });
435
+ bindings = compiled.bindings;
436
+ chunks.push(compiled.content);
437
+ } else {
438
+ chunks.push("const _sfc_main = {};");
439
+ }
440
+
441
+ if (descriptor.template) {
442
+ const t = compileTemplate({
443
+ source: descriptor.template.content,
444
+ filename: absPath,
445
+ id: shortId,
446
+ scoped: hasScoped,
447
+ slotted: descriptor.slotted,
448
+ compilerOptions: {
449
+ hoistStatic: false, // compileTemplate force-sets true; our spread wins (F7)
450
+ ...(bindings && { bindingMetadata: bindings }),
451
+ expressionPlugins: isTS ? ["typescript"] : [],
452
+ // Skathi host elements missing from the HTML tag list: otherwise the SFC compiler warns
453
+ // on every render. Keep in lockstep with prod.ts and crates/sk-tree/src/render.rs.
454
+ isCustomElement: (tag: string) => tag === "lottie" || tag.startsWith("sk-"),
455
+ },
456
+ });
457
+ if (t.errors.length) {
458
+ throw new Error(`${id} <template>: ${t.errors.map(String).join("; ")}`);
459
+ }
460
+ chunks.push(t.code);
461
+ chunks.push("_sfc_main.render = render;");
462
+ }
463
+
464
+ if (hasScoped) chunks.push(`_sfc_main.__scopeId = ${J(scopeId)};`);
465
+ chunks.push(`_sfc_main.__file = ${J(id)};`);
466
+
467
+ // Replaces plugin-vue's import.meta.hot epilogue; createRecord is idempotent, so re-evaluating a
468
+ // module keeps the record that holds the live instances.
469
+ chunks.push(`_sfc_main.__hmrId = ${J(id)};`);
470
+ chunks.push(`if (typeof __VUE_HMR_RUNTIME__ !== "undefined") __VUE_HMR_RUNTIME__.createRecord(${J(id)}, _sfc_main);`);
471
+ chunks.push("export default _sfc_main;");
472
+
473
+ const cssChunks: string[] = [];
474
+ for (const style of descriptor.styles) {
475
+ let text = style.content;
476
+ if (!style.lang || style.lang === "css" || style.lang === "postcss") {
477
+ text = await viteCss(text, absPath, `${id} <style>`);
478
+ } else {
479
+ devAdvise(`${id}: <style lang="${style.lang}"> is not preprocessed by Skathi — it is compiled as plain CSS`);
480
+ }
481
+ if (style.module) {
482
+ devAdvise(`${id}: <style module> — CSS modules are not supported yet; useCssModule() answers {}`);
483
+ }
484
+ // `isProd` left at its default (false) on both this and compileScript:
485
+ // they hash a `v-bind()` variable's name from it and must agree.
486
+ const out = compileStyle({
487
+ source: text,
488
+ filename: absPath,
489
+ id: scopeId,
490
+ scoped: style.scoped ?? false,
491
+ });
492
+ if (out.errors.length) throw new Error(`${id} <style>: ${out.errors.join("; ")}`);
493
+ cssChunks.push(out.code);
494
+ }
495
+ if (captureCss) capturedCss = cssChunks.length ? pruneVendorPrefixes(cssChunks.join("\n")) : null;
496
+
497
+ return { contents: chunks.join("\n"), loader: isTS ? "ts" : "js" };
498
+ }
499
+
500
+ const vuePlugin = {
501
+ name: "vue-sfc",
502
+ setup(build: Bun.PluginBuilder) {
503
+ build.onLoad({ filter: /\.vue$/ }, async (args: Bun.OnLoadArgs) => {
504
+ const source = await Bun.file(args.path).text();
505
+ return compileVue(args.path, source);
506
+ });
507
+ },
508
+ };
509
+
510
+ // Vite import shapes (vitecompat.ts), shared with prod.ts. In dev, import.meta.glob imports by
511
+ // importer-relative path.
512
+
513
+ const SHAPE_NOTES = new Map<string, number>();
514
+ let inlinedNow: Set<string> | null = null;
515
+ const noteInlined = (abs: string) => void inlinedNow?.add(abs);
516
+
517
+ const DEV_ASSET_FILES = new Map<string, string>();
518
+ const shapesOptions = (dev: boolean) => ({
519
+ docRoot: SK_CONFIG_DIR,
520
+ wsRoot: ID_ROOT,
521
+ svgDefault: svgDefaultOf(APP_PKG),
522
+ compileSfc: (absPath: string, source: string) => compileVue(absPath, source, false),
523
+ assets: DEV_ASSET_FILES,
524
+ notes: SHAPE_NOTES,
525
+ dev,
526
+ inlined: dev ? noteInlined : undefined,
527
+ });
528
+ const DEV_SHAPES = shapesOptions(true);
529
+ const devShapesPlugin = viteShapesPlugin(DEV_SHAPES);
530
+ const npmShapesPlugin = viteShapesPlugin(shapesOptions(false));
531
+ const devImports = devImportsPlugin({
532
+ srcDir: APP_SRC_DIR,
533
+ preseeded: isPreseeded,
534
+ inlined: noteInlined,
535
+ npmId: (spec, abs, from) => npmIdOf(spec, abs, from),
536
+ });
537
+
538
+ const appModulePlugin = {
539
+ name: "sk-dev-app-module",
540
+ setup(build: Bun.PluginBuilder) {
541
+ build.onLoad({ filter: /\.vue$/ }, async (args: Bun.OnLoadArgs) => {
542
+ const out = await compileVue(args.path, await Bun.file(args.path).text());
543
+ const code = transformSource(out.contents, args.path, DEV_SHAPES);
544
+ return code === null ? out : { ...out, contents: code };
545
+ });
546
+ },
547
+ };
548
+
549
+ // Every module is built with external:"*", so each import survives as a literal require("<spec>")
550
+ // and deps are read from the emitted body. Pre-seeded bare specifiers and npm packages stay out
551
+ // of the graph.
552
+
553
+ const REQUIRE_RE = /\brequire\(\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*\)/g;
554
+
555
+ const CANDIDATE_EXTS = ["", ".js", ".ts", ".mjs", ".vue", "/index.js", "/index.ts", "/index.vue"];
556
+
557
+ function normalizeId(path: string): string {
558
+ const out: string[] = [];
559
+ for (const seg of path.split("/")) {
560
+ if (seg === "" || seg === ".") continue;
561
+ if (seg === "..") {
562
+ if (out.length && out[out.length - 1] !== "..") out.pop();
563
+ else out.push("..");
564
+ continue;
565
+ }
566
+ out.push(seg);
567
+ }
568
+ return out.join("/");
569
+ }
570
+
571
+ function unquote(raw: string): string | null {
572
+ try {
573
+ if (raw.charCodeAt(0) === 34 /* " */) return JSON.parse(raw);
574
+ const inner = raw.slice(1, -1).replace(/\\'/g, "'").replace(/"/g, '\\"');
575
+ return JSON.parse('"' + inner + '"');
576
+ } catch {
577
+ return null;
578
+ }
579
+ }
580
+
581
+ function depsOf(id: string, body: string, ids: Set<string>, skip: Set<string>): string[] {
582
+ const slash = id.lastIndexOf("/");
583
+ const dir = slash < 0 ? "" : id.slice(0, slash);
584
+ const found: string[] = [];
585
+ REQUIRE_RE.lastIndex = 0;
586
+ for (let m = REQUIRE_RE.exec(body); m; m = REQUIRE_RE.exec(body)) {
587
+ const spec = unquote(m[1]!);
588
+ if (spec === null || spec.charCodeAt(0) !== 46 /* . */) continue; // bare -> vendor
589
+ if (skip.has(spec)) continue; // a stylesheet: its own synthetic module
590
+ const base = normalizeId((dir ? dir + "/" : "") + spec);
591
+ const hit = CANDIDATE_EXTS.map((ext) => base + ext).find((cand) => ids.has(cand));
592
+ if (!hit) {
593
+ warn(`${stamp()} ${id}: import ${J(spec)} resolves to no built module — ` + `require() will throw at runtime`);
594
+ continue;
595
+ }
596
+ if (hit !== id && !found.includes(hit)) found.push(hit);
597
+ }
598
+ return found;
599
+ }
600
+
601
+ function bareOf(body: string, skip: Set<string>): string[] {
602
+ const found: string[] = [];
603
+ REQUIRE_RE.lastIndex = 0;
604
+ for (let m = REQUIRE_RE.exec(body); m; m = REQUIRE_RE.exec(body)) {
605
+ const spec = unquote(m[1]!);
606
+ if (spec === null) continue;
607
+ const c = spec.charCodeAt(0);
608
+ if (c === 46 /* . */ || c === 47 /* / */) continue; // relative/absolute -> graph
609
+ if (isPreseeded(spec) || found.includes(spec) || skip.has(spec)) continue;
610
+ found.push(spec);
611
+ }
612
+ return found;
613
+ }
614
+
615
+ const moduleDeps = new Map<string, string[]>(); // id -> dep ids
616
+ const moduleBare = new Map<string, string[]>(); // app module id -> npm module ids it requires
617
+
618
+ // CSS entries are emitted as css-only synthetic modules (the Tailwind transport), not into a JS body.
619
+
620
+ const cssModules = new Map<string, string>();
621
+ const cssEmitted = new Map<string, string>();
622
+
623
+ function cssImportsOf(absPath: string, body: string, cssSpecs: Set<string>): string[] {
624
+ const dir = dirname(absPath);
625
+ const found: string[] = [];
626
+ REQUIRE_RE.lastIndex = 0;
627
+ for (let m = REQUIRE_RE.exec(body); m; m = REQUIRE_RE.exec(body)) {
628
+ const spec = unquote(m[1]!);
629
+ if (spec === null) continue;
630
+ const relative_ = spec.charCodeAt(0) === 46; /* . */
631
+ let abs: string;
632
+ if (relative_) {
633
+ if (!spec.endsWith(".css")) continue;
634
+ abs = resolve(dir, spec);
635
+ } else {
636
+ if (isPreseeded(spec)) continue;
637
+ try {
638
+ abs = resolveFromApp(spec);
639
+ } catch {
640
+ continue;
641
+ }
642
+ if (!abs.endsWith(".css")) continue;
643
+ }
644
+ if (!existsSync(abs)) {
645
+ warn(`${stamp()} ${toId(absPath)}: import ${J(spec)} names no file — skipped`);
646
+ continue;
647
+ }
648
+ cssSpecs.add(spec);
649
+ const id = relative_ ? toId(abs) : spec;
650
+ cssModules.set(id, abs);
651
+ if (!found.includes(id)) found.push(id);
652
+ }
653
+ return found;
654
+ }
655
+
656
+ const cssIds = () => Array.from(cssModules.keys());
657
+
658
+ /**
659
+ * Writes one CSS-only module script; true when the sheet moved. With a Tailwind config the sheet
660
+ * goes through Tailwind with itself as the entry, otherwise it is emitted byte-for-byte.
661
+ */
662
+ async function buildCssModule(id: string): Promise<boolean> {
663
+ const abs = cssModules.get(id)!;
664
+ let css = inlineCssImports(readFileSync(abs, "utf-8"), abs, SK_CONFIG_DIR, devAdvise);
665
+ if (TW_CONFIG && needsTailwindPass(css)) {
666
+ const t0 = Date.now();
667
+ try {
668
+ css = await generateTailwind(TW_CONFIG, { text: css, from: abs });
669
+ say(`${stamp()} css ${id}: ${(css.length / 1024).toFixed(1)} KB through tailwind in ${Date.now() - t0} ms`);
670
+ } catch (e) {
671
+ fail(`${stamp()} css ${id}: tailwind pass failed — emitting the source verbatim`, e);
672
+ }
673
+ } else {
674
+ say(`${stamp()} css ${id}: ${(css.length / 1024).toFixed(1)} KB`);
675
+ }
676
+ css = pruneVendorPrefixes(css);
677
+ moduleDeps.set(id, []);
678
+ if (cssEmitted.get(id) === css) return false;
679
+ cssEmitted.set(id, css);
680
+ writeAtomic(
681
+ join(MODULES_DIR, encId(id)),
682
+ [
683
+ `// Skathi module: ${id} (synthetic — CSS entry)`,
684
+ `// source: ${toId(abs)}; do not edit`,
685
+ `__SK__.setCss(${J(id)}, ${J(css)});`,
686
+ `__SK__.setDeps && __SK__.setDeps(${J(id)}, []);`,
687
+ // Empty factory: the import is a side effect; the constant body hash keeps a CSS edit inert.
688
+ `__SK__.define(${J(id)}, function (require, module, exports) {`,
689
+ `}, ${J(TW_HASH)});`,
690
+ ].join("\n"),
691
+ );
692
+ return true;
693
+ }
694
+
695
+ async function syncCssModules(): Promise<string[]> {
696
+ const changed: string[] = [];
697
+ for (const id of cssIds()) {
698
+ if (await buildCssModule(id)) changed.push(id);
699
+ }
700
+ return changed;
701
+ }
702
+
703
+ const appOwnsUtilities = () =>
704
+ Array.from(cssEmitted.keys()).some((id) => {
705
+ const abs = cssModules.get(id);
706
+ return !!abs && declaresUtilities(readFileSync(abs, "utf-8"));
707
+ });
708
+
709
+ const moduleInlined = new Map<string, Map<string, number>>();
710
+
711
+ const mtimeOf = (abs: string) => {
712
+ try {
713
+ return statSync(abs).mtimeMs;
714
+ } catch {
715
+ return -1;
716
+ }
717
+ };
718
+
719
+ function inlinedMoved(abs: string): boolean {
720
+ for (const [file, mtime] of moduleInlined.get(abs) ?? []) if (mtimeOf(file) !== mtime) return true;
721
+ return false;
722
+ }
723
+
724
+ async function buildModule(absPath: string, ids: Set<string>) {
725
+ const id = toId(absPath);
726
+ capturedCss = null;
727
+ const inlined = (inlinedNow = new Set());
728
+ let result: Awaited<ReturnType<typeof Bun.build>>;
729
+ try {
730
+ result = await Bun.build({
731
+ entrypoints: [absPath],
732
+ format: "cjs",
733
+ target: "node",
734
+ external: ["*"],
735
+ plugins: [devShapesPlugin, devImports, appModulePlugin],
736
+ define: DEFINES,
737
+ });
738
+ } finally {
739
+ inlinedNow = null;
740
+ }
741
+ if (!result.success) {
742
+ for (const log of result.logs) console.error(log);
743
+ throw new Error(`module build failed: ${id}`);
744
+ }
745
+ moduleInlined.set(absPath, new Map(Array.from(inlined, (f) => [f, mtimeOf(f)])));
746
+ // Bundler ESM semantics rather than Node's (vitecompat.ts devEsmInterop).
747
+ const interop = devEsmInterop(tagModuleNamespaces(await result.outputs[0]!.text()).code);
748
+ const body = interop.code;
749
+ if (interop.unresolved) {
750
+ warn(
751
+ `${stamp()} ${id}: ${interop.unresolved} import(…) with a computed specifier — the dev loader resolves ` +
752
+ `only a string literal, so that promise rejects (prod.ts bundles it)`,
753
+ );
754
+ }
755
+ if (/\bcreateStaticVNode\b/.test(body)) {
756
+ throw new Error(`${id}: emitted createStaticVNode — hoistStatic leaked back on (F7)`);
757
+ }
758
+ if (new RegExp(`\\b${GLOB_TRIPWIRE}\\b`).test(body)) {
759
+ throw new Error(
760
+ `${id}: an import.meta.glob the expansion did not see (not a call with literal arguments) — ` +
761
+ `the dev builder would emit a call that throws at eval`,
762
+ );
763
+ }
764
+
765
+ const cssSpecs = new Set<string>();
766
+ const css = cssImportsOf(absPath, body, cssSpecs);
767
+ const deps = depsOf(id, body, ids, cssSpecs).concat(css);
768
+ moduleDeps.set(id, deps);
769
+ moduleBare.set(id, bareOf(body, cssSpecs));
770
+
771
+ const out: string[] = [`// Skathi module: ${id}`];
772
+ if (capturedCss !== null) out.push(`__SK__.setCss(${J(id)}, ${J(capturedCss)});`);
773
+ out.push(`__SK__.setDeps && __SK__.setDeps(${J(id)}, ${J(deps)});`);
774
+ out.push(`__SK__.define(${J(id)}, function (require, module, exports) {`);
775
+ out.push(body);
776
+ out.push(`}, ${J(Bun.hash(body).toString(16))});`);
777
+ writeAtomic(join(MODULES_DIR, encId(id)), out.join("\n"));
778
+ }
779
+
780
+ // npm modules: one per package ENTRY, keyed on the resolved directory (not the name), so every
781
+ // importer of a directory shares it and a nested copy at another version stays separate. The id
782
+ // is the specifier when the app resolves it to that directory, else `<spec>~<hash of the directory>`.
783
+
784
+ const npmBuilt = new Map<string, number>();
785
+ const npmFailed = new Set<string>();
786
+ const npmEntries = new Map<string, { spec: string; from: string }>();
787
+ const npmBare = new Map<string, string[]>();
788
+
789
+ function splitSpec(spec: string): [string, string] {
790
+ const parts = spec.split("/");
791
+ const n = spec.startsWith("@") ? 2 : 1;
792
+ const rest = parts.slice(n).join("/");
793
+ return [parts.slice(0, n).join("/"), rest ? `./${rest}` : "."];
794
+ }
795
+
796
+ const pkgNameAt = new Map<string, string | null>();
797
+ function packageRootOf(file: string, name: string): string | null {
798
+ for (let dir = dirname(file); ;) {
799
+ let found = pkgNameAt.get(dir);
800
+ if (found === undefined) {
801
+ found = null;
802
+ try {
803
+ const n = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8")).name;
804
+ if (typeof n === "string") found = n;
805
+ } catch {}
806
+ pkgNameAt.set(dir, found);
807
+ }
808
+ if (found === name) return dir;
809
+ const up = dirname(dir);
810
+ if (up === dir) return null;
811
+ dir = up;
812
+ }
813
+ }
814
+
815
+ function npmKey(spec: string, abs: string): string {
816
+ const [name, sub] = splitSpec(spec);
817
+ const root = packageRootOf(abs, name);
818
+ return root ? `${toId(root)}|${sub}` : toId(abs);
819
+ }
820
+
821
+ const appKeys = new Map<string, string | null>();
822
+
823
+ function npmIdOf(spec: string, abs: string, from: string): string {
824
+ const key = npmKey(spec, abs);
825
+ let appKey = appKeys.get(spec);
826
+ if (appKey === undefined) {
827
+ let appAbs: string | null = null;
828
+ try {
829
+ appAbs = resolveFromApp(spec);
830
+ } catch {}
831
+ appKey = appAbs && isAbsolute(appAbs) ? npmKey(spec, appAbs) : null;
832
+ appKeys.set(spec, appKey);
833
+ }
834
+ const id = key === appKey ? spec : `${spec}~${Bun.hash(key).toString(16).slice(0, 8)}`;
835
+ if (!npmEntries.has(id)) npmEntries.set(id, { spec, from: id === spec ? APP_ROOT : from });
836
+ return id;
837
+ }
838
+
839
+ function npmSharePlugin(selfKey: string, found: Set<string>) {
840
+ return {
841
+ name: "sk-dev-npm-share",
842
+ setup(build: Bun.PluginBuilder) {
843
+ build.onResolve({ filter: /^(?!node:)[^./\\]/ }, (args: Bun.OnResolveArgs) => {
844
+ if (args.kind === "entry-point-build" || isAbsolute(args.path) || isPreseeded(args.path)) return undefined;
845
+ const from = importerDir(args, APP_ROOT);
846
+ const abs = resolveImport(args.path, from);
847
+ if (abs === null || !isAbsolute(abs) || /\.css$/i.test(abs) || LEAF_IMPORT.test(abs)) return undefined;
848
+ if (npmKey(args.path, abs) === selfKey) return undefined;
849
+ const id = npmIdOf(args.path, abs, from);
850
+ found.add(id);
851
+ return { path: id, external: true };
852
+ });
853
+ },
854
+ };
855
+ }
856
+
857
+ async function buildNpmModule(id: string): Promise<boolean> {
858
+ const { spec, from } = npmEntries.get(id) ?? { spec: id, from: APP_ROOT };
859
+ const candidates = await entryCandidates(spec, from);
860
+ if (!candidates.length) {
861
+ if (!npmFailed.has(id)) {
862
+ npmFailed.add(id);
863
+ const alias = !/^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(?:\/|$)/i.test(spec);
864
+ warn(
865
+ `${stamp()} cannot resolve ${J(spec)} from ${toId(from)} — ` +
866
+ `require(${J(id)}) will throw at runtime ` +
867
+ (alias
868
+ ? "(an import alias resolves through tsconfig.json compilerOptions.paths, as in sk build; " +
869
+ "a vite.config resolve.alias is not read)"
870
+ : "(is it installed?)"),
871
+ );
872
+ }
873
+ return false;
874
+ }
875
+ const selfKey = npmKey(spec, candidates[0]!);
876
+ const requires = new Set<string>();
877
+ let result: Awaited<ReturnType<typeof Bun.build>> | null = null;
878
+ let entry = candidates[0]!;
879
+ for (const [i, candidate] of candidates.entries()) {
880
+ entry = candidate;
881
+ requires.clear();
882
+ result = await Bun.build({
883
+ entrypoints: [candidate],
884
+ format: "cjs",
885
+ target: "browser", // picks the browser/ESM conditions, not node builtins
886
+ // Pre-seeded ids plus every other package entry stay external. A dependency can ship raw .vue
887
+ // source: without the SFC plugin Bun treats it as an asset and the import silently renders
888
+ // nothing.
889
+ plugins: [npmShapesPlugin, npmSharePlugin(selfKey, requires), vuePlugin],
890
+ define: DEFINES,
891
+ }).catch(() => null);
892
+ if (result?.success) break;
893
+ if (i + 1 < candidates.length) {
894
+ warn(`${stamp()} npm ${id}: ${toId(candidate)} did not build — retrying with ` + `${toId(candidates[i + 1]!)}`);
895
+ }
896
+ }
897
+ if (!result?.success) {
898
+ for (const log of result?.logs ?? []) console.error(log);
899
+ throw new Error(`npm module build failed: ${id}`);
900
+ }
901
+ const body = tagModuleNamespaces(await result.outputs[0]!.text()).code;
902
+ moduleDeps.set(id, []);
903
+ npmBare.set(id, Array.from(requires).sort());
904
+ writeAtomic(
905
+ join(MODULES_DIR, encId(id)),
906
+ [
907
+ `// Skathi module: ${id} (npm dependency, bundled from ${toId(entry)})`,
908
+ `__SK__.setDeps && __SK__.setDeps(${J(id)}, []);`,
909
+ `__SK__.define(${J(id)}, function (require, module, exports) {`,
910
+ body,
911
+ // Constant unless the package changes, so a rebuild never invalidates module-scope singletons.
912
+ `}, ${J(Bun.hash(body).toString(16))});`,
913
+ ].join("\n"),
914
+ );
915
+ npmBuilt.set(id, body.length);
916
+ return true;
917
+ }
918
+
919
+ const npmIds = () => Array.from(npmBuilt.keys()).sort();
920
+
921
+ function wantedNpm(): Set<string> {
922
+ const wanted = new Set<string>();
923
+ const queue: string[] = [];
924
+ for (const list of moduleBare.values()) queue.push(...list);
925
+ for (let id = queue.pop(); id !== undefined; id = queue.pop()) {
926
+ if (wanted.has(id)) continue;
927
+ wanted.add(id);
928
+ queue.push(...(npmBare.get(id) ?? []));
929
+ }
930
+ return wanted;
931
+ }
932
+
933
+ async function syncNpmModules(): Promise<string[]> {
934
+ const added: string[] = [];
935
+ const tried = new Set<string>();
936
+ for (;;) {
937
+ const todo = Array.from(wantedNpm())
938
+ .filter((id) => !npmBuilt.has(id) && !tried.has(id))
939
+ .sort();
940
+ if (!todo.length) break;
941
+ for (const id of todo) {
942
+ tried.add(id);
943
+ const t0 = Date.now();
944
+ if (!(await buildNpmModule(id))) continue;
945
+ added.push(id);
946
+ say(`${stamp()} npm ${id}: ${((npmBuilt.get(id) ?? 0) / 1024) | 0} KB in ${Date.now() - t0} ms`);
947
+ }
948
+ }
949
+
950
+ const wanted = wantedNpm();
951
+ for (const id of Array.from(npmBuilt.keys())) {
952
+ if (wanted.has(id)) continue;
953
+ npmBuilt.delete(id);
954
+ npmBare.delete(id);
955
+ moduleDeps.delete(id);
956
+ try {
957
+ rmSync(join(MODULES_DIR, encId(id)));
958
+ } catch {}
959
+ }
960
+ return added.filter((id) => npmBuilt.has(id));
961
+ }
962
+
963
+ const TW_CONFIG = findConfig(appRootArg ? APP_ROOT : APP_SRC_DIR, ID_ROOT);
964
+ let twCss: string | null = null;
965
+ const TW_HASH = Bun.hash("").toString(16);
966
+
967
+ async function buildTailwind(): Promise<boolean> {
968
+ if (!TW_CONFIG) return false;
969
+ const t0 = Date.now();
970
+ const css = pruneVendorPrefixes(await generateTailwind(TW_CONFIG));
971
+ moduleDeps.set(TW_ID, []);
972
+ if (css === twCss) return false;
973
+ twCss = css;
974
+ writeAtomic(
975
+ join(MODULES_DIR, encId(TW_ID)),
976
+ [
977
+ `// Skathi module: ${TW_ID} (synthetic — Tailwind utilities, generated)`,
978
+ `// source: ${toId(TW_CONFIG)}; do not edit`,
979
+ `__SK__.setCss(${J(TW_ID)}, ${J(css)});`,
980
+ `__SK__.setDeps && __SK__.setDeps(${J(TW_ID)}, []);`,
981
+ `__SK__.define(${J(TW_ID)}, function (require, module, exports) {`,
982
+ `}, ${J(TW_HASH)});`,
983
+ ].join("\n"),
984
+ );
985
+ say(`${stamp()} tailwind: ${(css.length / 1024).toFixed(1)} KB of utilities in ${Date.now() - t0} ms`);
986
+ return true;
987
+ }
988
+
989
+ type Blocks = { src: string; script: string; template: string; styleShape: string; styleText: string };
990
+ type Kind = "reload" | "rerender" | "css-only";
991
+
992
+ const prevBlocks = new Map<string, Blocks>(); // abs path -> blocks
993
+
994
+ function blocksOf(absPath: string, src: string): Blocks {
995
+ if (!absPath.endsWith(".vue")) {
996
+ return { src, script: src, template: "", styleShape: "", styleText: "" };
997
+ }
998
+ let d: SFCDescriptor;
999
+ try {
1000
+ d = parse(src, { filename: absPath }).descriptor;
1001
+ } catch {
1002
+ return { src, script: src, template: "", styleShape: "", styleText: "" };
1003
+ }
1004
+ const blockKey = (b: SFCBlock | null) => (b ? JSON.stringify([b.content, b.lang ?? "", b.attrs]) : "");
1005
+ return {
1006
+ src,
1007
+ script: blockKey(d.script) + "" + blockKey(d.scriptSetup),
1008
+ template: d.template ? d.template.content : "",
1009
+ styleShape: JSON.stringify(d.styles.map((s) => [!!s.scoped, !!s.module, s.lang ?? ""])),
1010
+ styleText: d.styles.map((s) => s.content).join(""),
1011
+ };
1012
+ }
1013
+
1014
+ function classify(prev: Blocks | undefined, next: Blocks): Kind | null {
1015
+ if (!prev) return "reload"; // new file
1016
+ if (prev.src === next.src) return null;
1017
+ if (prev.script !== next.script || prev.styleShape !== next.styleShape) return "reload";
1018
+ if (prev.template !== next.template) return "rerender";
1019
+ if (prev.styleText !== next.styleText) return "css-only";
1020
+ return null; // whitespace between blocks etc.
1021
+ }
1022
+
1023
+ function scanSources(dir: string, out: string[] = []): string[] {
1024
+ for (const name of readdirSync(dir)) {
1025
+ if (name === "node_modules" || name === "dist" || name.startsWith(".")) continue;
1026
+ const abs = join(dir, name);
1027
+ const st = statSync(abs);
1028
+ if (st.isDirectory()) scanSources(abs, out);
1029
+ else if (SOURCE_EXT.test(name)) out.push(abs);
1030
+ }
1031
+ return out.sort();
1032
+ }
1033
+
1034
+ let rev = 0;
1035
+ let vendorRev = 0; // content hash of vendor.js, set by buildVendor()
1036
+
1037
+ function writeManifest(files: string[]) {
1038
+ // Order matters: the host evals modules in order and cssOrder is first-setCss-wins. Tailwind
1039
+ // utilities, npm modules, app stylesheets, then component styles; an app stylesheet carrying
1040
+ // `@tailwind utilities` makes the synthetic module redundant.
1041
+ const wantTw = TW_CONFIG && !appOwnsUtilities();
1042
+ const ids = (wantTw ? [TW_ID] : []).concat(cssIds(), npmIds(), files.map(toId));
1043
+ const seen = new Set<string>();
1044
+ for (const id of ids) {
1045
+ const enc = encId(id);
1046
+ if (seen.has(enc)) throw new Error(`module filename collision for ${id} -> ${enc}`);
1047
+ seen.add(enc);
1048
+ }
1049
+ const deps: Record<string, string[]> = {};
1050
+ for (const id of ids) deps[id] = moduleDeps.get(id) ?? [];
1051
+ writeAtomic(
1052
+ join(DIST, "manifest.json"),
1053
+ JSON.stringify(
1054
+ {
1055
+ rev,
1056
+ vendorRev,
1057
+ entry: toId(ENTRY_ABS),
1058
+ name: readAppName(),
1059
+ modules: ids,
1060
+ assetFiles: Object.fromEntries(
1061
+ [...DEV_ASSET_FILES]
1062
+ .filter(([key, path]) => key.startsWith("_vn/fs/") && existsSync(path))
1063
+ .map(([key, path]): [string, string] => [key, realpathSync(path)])
1064
+ .sort(([a], [b]) => a.localeCompare(b)),
1065
+ ),
1066
+ deps,
1067
+ window: readWindowConfig(),
1068
+ launch: readLaunchConfig(),
1069
+ },
1070
+ null,
1071
+ 2,
1072
+ ) + "\n",
1073
+ );
1074
+ }
1075
+
1076
+ function writeChanges(changed: { id: string; kind: Kind }[]) {
1077
+ // Written LAST, and it is the file the host polls: once its mtime moves, every module script
1078
+ // and the manifest are already on disk.
1079
+ writeAtomic(join(DIST, "changes.json"), JSON.stringify({ rev, vendorRev, changed }) + "\n");
1080
+ }
1081
+
1082
+ const stamp = () => `[${new Date().toLocaleTimeString()}]`;
1083
+
1084
+ async function fullBuild(reason: string) {
1085
+ DEV_ASSET_FILES.clear();
1086
+ ensureDirs();
1087
+ const t0 = Date.now();
1088
+ const bytes = await buildVendor(); // also refreshes vendorRev
1089
+ const files = scanSources(APP_SRC_DIR);
1090
+ const ids = new Set(files.map(toId));
1091
+ prevBlocks.clear();
1092
+ moduleDeps.clear();
1093
+ moduleBare.clear();
1094
+ npmBuilt.clear(); // force a rewrite: the module files may not exist yet
1095
+ npmBare.clear();
1096
+ npmEntries.clear();
1097
+ appKeys.clear();
1098
+ pkgNameAt.clear();
1099
+ cssModules.clear();
1100
+ cssEmitted.clear();
1101
+ moduleInlined.clear();
1102
+ SHAPE_NOTES.clear();
1103
+ twCss = null; // ditto
1104
+ await buildTailwind();
1105
+ for (const abs of files) {
1106
+ const src = await Bun.file(abs).text();
1107
+ await buildModule(abs, ids);
1108
+ prevBlocks.set(abs, blocksOf(abs, src));
1109
+ }
1110
+ await syncNpmModules(); // needs every module's `require`s to be known first
1111
+ await syncCssModules(); // ditto: discovered while scanning each module's body
1112
+ rev++;
1113
+ writeManifest(files);
1114
+ writeChanges([]);
1115
+ const npmBytes = Array.from(npmBuilt.values()).reduce((a, b) => a + b, 0);
1116
+ say(
1117
+ `${stamp()} full build (${reason}): vendor ${(bytes / 1024) | 0} KB + ${files.length} modules` +
1118
+ (npmBuilt.size ? ` + ${npmBuilt.size} npm (${(npmBytes / 1024) | 0} KB)` : "") +
1119
+ (TW_CONFIG ? ` + tailwind (${toId(TW_CONFIG)})` : "") +
1120
+ // Cross-package `defineProps<T>()` silently depends on this; say so once per build.
1121
+ (TS_AVAILABLE ? " [ts type resolution on]" : "") +
1122
+ ` in ${Date.now() - t0} ms`,
1123
+ );
1124
+ for (const [what, n] of SHAPE_NOTES) say(`${stamp()} ${what}: ${n}`);
1125
+ SHAPE_NOTES.clear(); // an incremental pass rebuilds one file: its counts would mislead
1126
+ }
1127
+
1128
+ async function incrementalBuild() {
1129
+ ensureDirs();
1130
+ const files = scanSources(APP_SRC_DIR);
1131
+ const ids = new Set(files.map(toId));
1132
+ const changed: { id: string; kind: Kind }[] = [];
1133
+ let structural = false;
1134
+
1135
+ for (const abs of files) {
1136
+ const src = await Bun.file(abs).text();
1137
+ const next = blocksOf(abs, src);
1138
+ const isNew = !prevBlocks.has(abs);
1139
+ const kind = classify(prevBlocks.get(abs), next) ?? (inlinedMoved(abs) ? "reload" : null);
1140
+ prevBlocks.set(abs, next);
1141
+ if (!kind) continue;
1142
+ if (isNew) structural = true;
1143
+ try {
1144
+ await buildModule(abs, ids);
1145
+ } catch (e) {
1146
+ fail(`${stamp()} ${String(e)}`);
1147
+ return; // leave dist untouched; the app keeps running the last good build
1148
+ }
1149
+ changed.push({ id: toId(abs), kind });
1150
+ }
1151
+
1152
+ const alive = new Set(files);
1153
+ for (const abs of Array.from(prevBlocks.keys())) {
1154
+ if (alive.has(abs)) continue;
1155
+ prevBlocks.delete(abs);
1156
+ moduleDeps.delete(toId(abs));
1157
+ moduleBare.delete(toId(abs));
1158
+ moduleInlined.delete(abs);
1159
+ try {
1160
+ rmSync(join(MODULES_DIR, encId(toId(abs))));
1161
+ } catch {}
1162
+ structural = true;
1163
+ }
1164
+
1165
+ for (const spec of await syncNpmModules()) {
1166
+ changed.push({ id: spec, kind: "reload" });
1167
+ structural = true;
1168
+ }
1169
+
1170
+ // Always re-run Tailwind: any content file can add a utility, and a stylesheet that went
1171
+ // through Tailwind is re-emitted on the same signal.
1172
+ for (const id of await syncCssModules()) changed.push({ id, kind: "css-only" });
1173
+
1174
+ if (!changed.length && !structural) return;
1175
+ rev++;
1176
+ writeManifest(files);
1177
+ writeChanges(changed);
1178
+ say(
1179
+ `${stamp()} ${C.green(`rev ${rev}`)}: ` +
1180
+ (changed.map((c) => `${c.kind} ${c.id}`).join(", ") || "module set changed"),
1181
+ );
1182
+ }
1183
+
1184
+ await fullBuild("startup").catch((e) => {
1185
+ console.error(e);
1186
+ if (!WATCH) process.exit(1);
1187
+ });
1188
+
1189
+ if (WATCH) {
1190
+ const { watch } = await import("fs");
1191
+ let timer: ReturnType<typeof setTimeout> | undefined;
1192
+ let vendorTouched = false;
1193
+ const schedule = (isRuntime: boolean) => (_evt: string, file: string | null) => {
1194
+ const name = String(file ?? "");
1195
+ if (name.endsWith(".tmp")) return;
1196
+ if (isRuntime) vendorTouched = true;
1197
+ clearTimeout(timer);
1198
+ timer = setTimeout(async () => {
1199
+ const full = vendorTouched;
1200
+ vendorTouched = false;
1201
+ try {
1202
+ if (full) await fullBuild("runtime source changed");
1203
+ else await incrementalBuild();
1204
+ } catch (e) {
1205
+ fail(`${stamp()} ${String(e)}`);
1206
+ }
1207
+ }, 60);
1208
+ };
1209
+ watch(APP_SRC_DIR, { recursive: true }, schedule(false));
1210
+ watch(RUNTIME_SRC_DIR, { recursive: true }, schedule(true));
1211
+ const watched = [APP_SRC_DIR, RUNTIME_SRC_DIR];
1212
+ if (TW_CONFIG) {
1213
+ // The config lives outside the source tree: one non-recursive watch on its directory,
1214
+ // filtered to the config file.
1215
+ const configDir = dirname(TW_CONFIG);
1216
+ const configName = relative(configDir, TW_CONFIG);
1217
+ watch(configDir, { recursive: false }, (evt, file) => {
1218
+ if (String(file ?? "") !== configName) return;
1219
+ schedule(false)(evt, file);
1220
+ });
1221
+ watched.push(TW_CONFIG);
1222
+ }
1223
+ console.log(`${C.green("watching")} ${C.dim(watched.join(", "))}`);
1224
+ // SK_OWNER_PID: exit once the process that started the watcher is gone, however it ended (the
1225
+ // host does the same, crates/sk-app/src/owner.rs).
1226
+ const owner = Number(process.env.SK_OWNER_PID);
1227
+ if (Number.isInteger(owner) && owner > 0) {
1228
+ setInterval(() => {
1229
+ try {
1230
+ process.kill(owner, 0);
1231
+ } catch (e) {
1232
+ if ((e as NodeJS.ErrnoException).code === "ESRCH") process.exit(0);
1233
+ }
1234
+ }, 1000);
1235
+ }
1236
+ }