@skathi-native/cli 0.0.0-stage → 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/aot-inputs.ts +294 -0
- package/ascii.ts +397 -0
- package/build.ts +1236 -0
- package/check/builtins.json +1219 -0
- package/check/builtins.ts +112 -0
- package/check/codes.ts +178 -0
- package/check/command.ts +105 -0
- package/check/config.ts +76 -0
- package/check/finding.ts +30 -0
- package/check/graph.ts +69 -0
- package/check/highlight.ts +40 -0
- package/check/index.ts +308 -0
- package/check/packages.ts +54 -0
- package/check/program.ts +209 -0
- package/check/report.ts +219 -0
- package/check/rules.ts +307 -0
- package/check/schema.ts +69 -0
- package/check/typing.ts +703 -0
- package/cli/assets.ts +114 -0
- package/cli/build-app.ts +587 -0
- package/cli/config.ts +646 -0
- package/cli/create.ts +411 -0
- package/cli/dev.ts +92 -0
- package/cli/elf.ts +142 -0
- package/cli/host-fetch.ts +178 -0
- package/cli/host.ts +378 -0
- package/cli/icon.ts +303 -0
- package/cli/macos-bundle.ts +451 -0
- package/cli/pe.ts +429 -0
- package/cli/platform.ts +74 -0
- package/cli/sk.ts +356 -0
- package/cli/skpk.ts +268 -0
- package/cli/stamp.ts +254 -0
- package/cli/term.ts +176 -0
- package/cli/versioninfo.ts +123 -0
- package/css-prefixes.ts +118 -0
- package/devtools/apps.ts +68 -0
- package/devtools/commands.ts +860 -0
- package/devtools/ctl.ts +166 -0
- package/package.json +58 -4
- package/prod.ts +701 -0
- package/runtime-path.ts +24 -0
- package/tailwind.ts +76 -0
- package/vitecompat.ts +1151 -0
- package/README.md +0 -3
package/prod.ts
ADDED
|
@@ -0,0 +1,701 @@
|
|
|
1
|
+
// Production builder: one self-contained IIFE, no loader, no HMR.
|
|
2
|
+
// Usage: bun prod.ts [app-entry.js] [out-file] [--config <path>] [--app-root <path>] [--define=KEY=VALUE ...]
|
|
3
|
+
// [--graph <path>]: write the bundle's module graph as JSON (for `sk check`) instead of the bundle
|
|
4
|
+
//
|
|
5
|
+
// dist/app.prod.js IIFE: runtime + every app module + every SFC <style>, minified, __DEV__ = false.
|
|
6
|
+
// `sk build` (cli/build-app.ts) packs it into the SKPK payload.
|
|
7
|
+
// dist/window.json the `window` block of sk.config.json
|
|
8
|
+
// dist/assets.json [{ key, path }]: every file imported by URL, packed into the payload under key
|
|
9
|
+
//
|
|
10
|
+
// Unlike build.ts: "vue" and "@skathi-native/runtime" alias to src/runtime.ts, inlineTemplate is true (no HMR),
|
|
11
|
+
// styles go to (globalThis.__SK_CSS__ ??= []) ahead of the bundle, no HMR epilogue.
|
|
12
|
+
//
|
|
13
|
+
// DEBT: compileVue() and the style pipeline are a ~100-line copy of build.ts; merge into a shared sfc.ts.
|
|
14
|
+
|
|
15
|
+
import { parse, compileScript, compileTemplate, compileStyle, registerTS } from "@vue/compiler-sfc";
|
|
16
|
+
import { createRequire } from "module";
|
|
17
|
+
import { resolve, dirname, join, relative, sep } from "path";
|
|
18
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
|
|
19
|
+
|
|
20
|
+
import { asciiOnly, checkAscii, nonAsciiCount } from "./ascii";
|
|
21
|
+
import { AotInputs, aotEngineIdentity } from "./aot-inputs";
|
|
22
|
+
import type { ModuleGraph } from "./check/graph";
|
|
23
|
+
import { pruneVendorPrefixes } from "./css-prefixes";
|
|
24
|
+
import {
|
|
25
|
+
RUNTIME_DIR,
|
|
26
|
+
RUNTIME_ENTRY,
|
|
27
|
+
RUNTIME_MODULES_DIR,
|
|
28
|
+
RUNTIME_SRC_DIR,
|
|
29
|
+
isPreseeded,
|
|
30
|
+
runtimeRequire,
|
|
31
|
+
} from "./runtime-path";
|
|
32
|
+
import { TW_ID, declaresUtilities, findConfig, generate as generateTailwind, needsTailwindPass } from "./tailwind";
|
|
33
|
+
import {
|
|
34
|
+
GLOB_TRIPWIRE,
|
|
35
|
+
SFC_FS,
|
|
36
|
+
appDefines,
|
|
37
|
+
frameworkDep,
|
|
38
|
+
htmlPreludeModule,
|
|
39
|
+
inlineCssImports,
|
|
40
|
+
liftIndexHtml,
|
|
41
|
+
readPackageJson,
|
|
42
|
+
svgDefaultOf,
|
|
43
|
+
tagModuleNamespaces,
|
|
44
|
+
takeDefineArgs,
|
|
45
|
+
transformSource,
|
|
46
|
+
viteShapesPlugin,
|
|
47
|
+
type CssPiece,
|
|
48
|
+
type LiftedHtml,
|
|
49
|
+
} from "./vitecompat";
|
|
50
|
+
|
|
51
|
+
const { defines: cliDefines, rest: argv } = takeDefineArgs(process.argv.slice(2));
|
|
52
|
+
let configOverride: string | undefined;
|
|
53
|
+
let appRootOverride: string | undefined;
|
|
54
|
+
let aotInputsDir: string | undefined;
|
|
55
|
+
let graphOut: string | undefined;
|
|
56
|
+
let minify = true;
|
|
57
|
+
const positional: string[] = [];
|
|
58
|
+
for (let i = 0; i < argv.length; i++) {
|
|
59
|
+
const arg = argv[i]!;
|
|
60
|
+
const flag = arg.split("=", 1)[0];
|
|
61
|
+
if (arg === "--no-minify") minify = false;
|
|
62
|
+
else if (flag === "--config" || flag === "--app-root" || flag === "--aot-inputs" || flag === "--graph") {
|
|
63
|
+
const value = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : argv[++i];
|
|
64
|
+
if (!value?.trim() || value.startsWith("--")) throw new Error(`${flag} needs a path`);
|
|
65
|
+
if (flag === "--config") configOverride = resolve(value);
|
|
66
|
+
else if (flag === "--aot-inputs") aotInputsDir = resolve(value);
|
|
67
|
+
else if (flag === "--graph") graphOut = resolve(value);
|
|
68
|
+
else appRootOverride = resolve(value);
|
|
69
|
+
} else if (!arg.startsWith("--")) positional.push(arg);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const PKG_DIR = import.meta.dir; // .../packages/cli
|
|
73
|
+
const WS_ROOT = resolve(PKG_DIR, "../.."); // repo root — module ids are relative to this
|
|
74
|
+
|
|
75
|
+
const ENTRY_ABS = resolve(positional[0] ?? join(WS_ROOT, "apps/hello/src/main.ts"));
|
|
76
|
+
const APP_SRC_DIR = dirname(ENTRY_ABS);
|
|
77
|
+
const OUT_FILE = resolve(positional[1] ?? join(PKG_DIR, "dist", "app.prod.js"));
|
|
78
|
+
|
|
79
|
+
// The `window` block of sk.config.json, emitted as `window.json`: the host reads it before opening
|
|
80
|
+
// the window, so it cannot ride inside the bundle. Read from next to `src/`, not APP_ROOT.
|
|
81
|
+
const SK_CONFIG_DIR = appRootOverride ?? (APP_SRC_DIR.endsWith(`${sep}src`) ? dirname(APP_SRC_DIR) : APP_SRC_DIR);
|
|
82
|
+
const SK_CONFIG_PATH = configOverride ?? join(SK_CONFIG_DIR, "sk.config.json");
|
|
83
|
+
const WINDOW_JSON = join(dirname(OUT_FILE), "window.json");
|
|
84
|
+
const ASSETS_JSON = join(dirname(OUT_FILE), "assets.json");
|
|
85
|
+
|
|
86
|
+
function readSkConfig(): Record<string, unknown> {
|
|
87
|
+
const path = SK_CONFIG_PATH;
|
|
88
|
+
if (!existsSync(path)) {
|
|
89
|
+
if (configOverride) throw new Error(`${path}: no such config file`);
|
|
90
|
+
return {};
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
const cfg = JSON.parse(readFileSync(path, "utf8"));
|
|
94
|
+
if (cfg && typeof cfg === "object" && !Array.isArray(cfg)) return cfg;
|
|
95
|
+
if (configOverride) throw new Error("not a JSON object");
|
|
96
|
+
return {};
|
|
97
|
+
} catch (e) {
|
|
98
|
+
if (configOverride) throw new Error(`${path}: ${e}`);
|
|
99
|
+
console.error(`[prod] ${path}: ${e}`);
|
|
100
|
+
return {};
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const SK_CONFIG = readSkConfig();
|
|
104
|
+
|
|
105
|
+
function windowConfig(): string {
|
|
106
|
+
const cfg = SK_CONFIG;
|
|
107
|
+
const win = { ...((cfg.window as Record<string, unknown> | undefined) ?? {}) };
|
|
108
|
+
// Top-level "devtools": false folds into the window block; a window block that sets it wins.
|
|
109
|
+
if (typeof cfg.devtools === "boolean" && typeof win.devtools !== "boolean") {
|
|
110
|
+
win.devtools = cfg.devtools;
|
|
111
|
+
}
|
|
112
|
+
// "httpCache" folds in the same way.
|
|
113
|
+
if (cfg.httpCache !== undefined && win.httpCache === undefined) {
|
|
114
|
+
win.httpCache = cfg.httpCache;
|
|
115
|
+
}
|
|
116
|
+
return JSON.stringify(win, null, 2);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const TW_CONFIG = findConfig(APP_SRC_DIR, WS_ROOT);
|
|
120
|
+
|
|
121
|
+
function findAppRoot(startDir: string, stopDir: string): string {
|
|
122
|
+
let dir = startDir;
|
|
123
|
+
for (;;) {
|
|
124
|
+
// The workspace root's package.json is the SDK's, not an app's.
|
|
125
|
+
if (dir === stopDir) return startDir;
|
|
126
|
+
if (existsSync(join(dir, "package.json")) || existsSync(join(dir, "node_modules"))) return dir;
|
|
127
|
+
const parent = dirname(dir);
|
|
128
|
+
if (parent === dir) return startDir;
|
|
129
|
+
dir = parent;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const APP_ROOT = findAppRoot(APP_SRC_DIR, WS_ROOT);
|
|
133
|
+
const appRequire = createRequire(join(APP_ROOT, "package.json"));
|
|
134
|
+
const cliRequire = createRequire(join(PKG_DIR, "package.json"));
|
|
135
|
+
const APP_PKG = APP_ROOT === PKG_DIR ? null : readPackageJson(APP_ROOT);
|
|
136
|
+
|
|
137
|
+
try {
|
|
138
|
+
const ts = appRequire("typescript");
|
|
139
|
+
registerTS(() => ts);
|
|
140
|
+
} catch {}
|
|
141
|
+
|
|
142
|
+
const toId = (abs: string) => relative(WS_ROOT, abs).split(sep).join("/");
|
|
143
|
+
const J = (v: unknown) => JSON.stringify(v);
|
|
144
|
+
|
|
145
|
+
const advisories = new Set<string>();
|
|
146
|
+
const advise = (m: string) => advisories.add(m);
|
|
147
|
+
|
|
148
|
+
const APP_DEFINES = appDefines(SK_CONFIG.define, cliDefines, SK_CONFIG_PATH);
|
|
149
|
+
if (APP_DEFINES.errors.length) {
|
|
150
|
+
for (const e of APP_DEFINES.errors) console.error(`[prod] ${e}`);
|
|
151
|
+
process.exit(1);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const VITE_ENV_PROD: Record<string, unknown> = {
|
|
155
|
+
MODE: "production",
|
|
156
|
+
DEV: false,
|
|
157
|
+
PROD: true,
|
|
158
|
+
SSR: false,
|
|
159
|
+
BASE_URL: "/",
|
|
160
|
+
SK: true,
|
|
161
|
+
};
|
|
162
|
+
for (const [k, v] of Object.entries(APP_DEFINES.defines)) {
|
|
163
|
+
if (!k.startsWith("import.meta.env.")) continue;
|
|
164
|
+
try {
|
|
165
|
+
VITE_ENV_PROD[k.slice("import.meta.env.".length)] = JSON.parse(v);
|
|
166
|
+
} catch {}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const DEFINES: Record<string, string> = {
|
|
170
|
+
__DEV__: "false",
|
|
171
|
+
"process.env.NODE_ENV": '"production"',
|
|
172
|
+
__VUE_PROD_DEVTOOLS__: "false",
|
|
173
|
+
__FEATURE_SUSPENSE__: "true",
|
|
174
|
+
__COMPAT__: "false",
|
|
175
|
+
__BROWSER__: "false",
|
|
176
|
+
__ESM_BUNDLER__: "true",
|
|
177
|
+
__GLOBAL__: "false",
|
|
178
|
+
__NODE_JS__: "false",
|
|
179
|
+
__SSR__: "false",
|
|
180
|
+
__TEST__: "false",
|
|
181
|
+
__VERSION__: '"3.5"',
|
|
182
|
+
// `import.meta` is a SyntaxError in a classic script and Bun leaves it verbatim in iife output,
|
|
183
|
+
// so substitute the production values Vite would inline; the tripwire in `build()` catches survivors.
|
|
184
|
+
"import.meta.env.MODE": '"production"',
|
|
185
|
+
"import.meta.env.DEV": "false",
|
|
186
|
+
"import.meta.env.PROD": "true",
|
|
187
|
+
"import.meta.env.SSR": "false",
|
|
188
|
+
"import.meta.env.BASE_URL": '"/"',
|
|
189
|
+
"import.meta.env.SK": "true",
|
|
190
|
+
"import.meta.env": JSON.stringify(VITE_ENV_PROD),
|
|
191
|
+
"import.meta.hot": "undefined",
|
|
192
|
+
"import.meta.url": '"sk://app.prod.js"',
|
|
193
|
+
// An unexpanded `import.meta.glob` would become `{env,url}.glob(...)` and fail at eval; define it
|
|
194
|
+
// to a findable name so it fails the build.
|
|
195
|
+
"import.meta.glob": GLOB_TRIPWIRE,
|
|
196
|
+
"import.meta": JSON.stringify({ env: VITE_ENV_PROD, url: "sk://app.prod.js" }),
|
|
197
|
+
...APP_DEFINES.defines,
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
function writeAtomic(path: string, text: string) {
|
|
201
|
+
const tmp = path + ".tmp";
|
|
202
|
+
writeFileSync(tmp, text);
|
|
203
|
+
renameSync(tmp, path);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const INDEX_HTML = join(SK_CONFIG_DIR, "index.html");
|
|
207
|
+
const LIFTED: LiftedHtml | null = existsSync(INDEX_HTML) ? liftIndexHtml(INDEX_HTML, SK_CONFIG_DIR) : null;
|
|
208
|
+
const HTML_PRELUDE =
|
|
209
|
+
LIFTED &&
|
|
210
|
+
(LIFTED.scripts.length ||
|
|
211
|
+
LIFTED.rootClasses.length ||
|
|
212
|
+
Object.keys(LIFTED.rootAttrs).length ||
|
|
213
|
+
LIFTED.svgDefinitions?.length)
|
|
214
|
+
? htmlPreludeModule(LIFTED)
|
|
215
|
+
: null;
|
|
216
|
+
if (LIFTED) {
|
|
217
|
+
for (const a of LIFTED.advisories) advise(`index.html: ${a}`);
|
|
218
|
+
for (const s of LIFTED.scripts) {
|
|
219
|
+
try {
|
|
220
|
+
new Function(s.text);
|
|
221
|
+
} catch (e) {
|
|
222
|
+
advise(`${s.label}: the inline <script> does not parse (${(e as Error).message}) — it will throw at startup`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const scopeIdOf = (id: string) => Bun.hash(id).toString(16).slice(0, 8);
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Template comments are dropped in production, as in Vite. The dev compiler loaded here keeps
|
|
231
|
+
* them, which compiled a comment-first template to a fragment root and lost fallthrough attrs.
|
|
232
|
+
*/
|
|
233
|
+
const PROD_TEMPLATE_COMMENTS = false;
|
|
234
|
+
|
|
235
|
+
const cssById = new Map<string, string>();
|
|
236
|
+
|
|
237
|
+
async function viteCss(text: string, from: string, label: string): Promise<string> {
|
|
238
|
+
let css = inlineCssImports(text, from, SK_CONFIG_DIR, advise, undefined, ASSETS);
|
|
239
|
+
if (TW_CONFIG && needsTailwindPass(css)) {
|
|
240
|
+
try {
|
|
241
|
+
css = await generateTailwind(TW_CONFIG, { text: css, from: from.replace(/\?.*$/, "") });
|
|
242
|
+
} catch (e) {
|
|
243
|
+
throw new Error(`${label}: tailwind: ${(e as Error).message}`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return css;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async function compileVue(absPath: string, source: string): Promise<{ contents: string; loader: "js" | "ts" }> {
|
|
250
|
+
const id = toId(absPath);
|
|
251
|
+
const { descriptor, errors } = parse(source, {
|
|
252
|
+
filename: absPath,
|
|
253
|
+
templateParseOptions: { comments: PROD_TEMPLATE_COMMENTS },
|
|
254
|
+
});
|
|
255
|
+
if (errors.length) {
|
|
256
|
+
throw new Error(`${id}: ${errors.map((e) => e.message).join("; ")}`);
|
|
257
|
+
}
|
|
258
|
+
const shortId = scopeIdOf(id);
|
|
259
|
+
const scopeId = `data-v-${shortId}`;
|
|
260
|
+
const hasScoped = descriptor.styles.some((s) => s.scoped);
|
|
261
|
+
// compileScript leaves TS syntax: hand the chunk to Bun with the matching loader. RETURNED, not
|
|
262
|
+
// stashed, because the style pass awaits and compiles interleave.
|
|
263
|
+
const isTS = /^tsx?$/.test(descriptor.scriptSetup?.lang ?? descriptor.script?.lang ?? "");
|
|
264
|
+
|
|
265
|
+
const chunks: string[] = [];
|
|
266
|
+
|
|
267
|
+
if (descriptor.scriptSetup || descriptor.script) {
|
|
268
|
+
const compiled = compileScript(descriptor, {
|
|
269
|
+
id: shortId,
|
|
270
|
+
isProd: true,
|
|
271
|
+
fs: SFC_FS,
|
|
272
|
+
inlineTemplate: true,
|
|
273
|
+
genDefaultAs: "_sfc_main",
|
|
274
|
+
templateOptions: {
|
|
275
|
+
compilerOptions: {
|
|
276
|
+
// compileTemplate defaults this to true then spreads compilerOptions over it, so ours wins.
|
|
277
|
+
hoistStatic: false,
|
|
278
|
+
isCustomElement: (tag: string) => tag === "lottie" || tag.startsWith("sk-"),
|
|
279
|
+
comments: PROD_TEMPLATE_COMMENTS,
|
|
280
|
+
},
|
|
281
|
+
},
|
|
282
|
+
});
|
|
283
|
+
chunks.push(compiled.content);
|
|
284
|
+
} else {
|
|
285
|
+
chunks.push("const _sfc_main = {};");
|
|
286
|
+
if (descriptor.template) {
|
|
287
|
+
const t = compileTemplate({
|
|
288
|
+
source: descriptor.template.content,
|
|
289
|
+
filename: absPath,
|
|
290
|
+
id: shortId,
|
|
291
|
+
isProd: true,
|
|
292
|
+
scoped: hasScoped,
|
|
293
|
+
slotted: descriptor.slotted,
|
|
294
|
+
compilerOptions: {
|
|
295
|
+
hoistStatic: false,
|
|
296
|
+
expressionPlugins: isTS ? ["typescript"] : [],
|
|
297
|
+
isCustomElement: (tag: string) => tag === "lottie" || tag.startsWith("sk-"),
|
|
298
|
+
comments: PROD_TEMPLATE_COMMENTS,
|
|
299
|
+
},
|
|
300
|
+
});
|
|
301
|
+
if (t.errors.length) {
|
|
302
|
+
throw new Error(`${id} <template>: ${t.errors.map(String).join("; ")}`);
|
|
303
|
+
}
|
|
304
|
+
chunks.push(t.code);
|
|
305
|
+
chunks.push("_sfc_main.render = render;");
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Scoped styles are matched in Rust by the data-v bucket the renderer stamps via setScopeId.
|
|
310
|
+
if (hasScoped) chunks.push(`_sfc_main.__scopeId = ${J(scopeId)};`);
|
|
311
|
+
chunks.push("export default _sfc_main;");
|
|
312
|
+
|
|
313
|
+
// hoistStatic tripwire: createStaticVNode needs insertStaticContent, which the host lacks.
|
|
314
|
+
// Checked on the SFC, not the bundle, which holds runtime-core's own definition of it.
|
|
315
|
+
let code = chunks.join("\n");
|
|
316
|
+
if (/\bcreateStaticVNode\b/.test(code)) {
|
|
317
|
+
throw new Error(`${id}: emitted createStaticVNode — hoistStatic leaked back on (F7)`);
|
|
318
|
+
}
|
|
319
|
+
code = transformSource(code, absPath, SHAPES) ?? code;
|
|
320
|
+
|
|
321
|
+
const cssChunks: string[] = [];
|
|
322
|
+
for (const style of descriptor.styles) {
|
|
323
|
+
let text = style.content;
|
|
324
|
+
if (!style.lang || style.lang === "css" || style.lang === "postcss") {
|
|
325
|
+
text = await viteCss(text, absPath, `${id} <style>`);
|
|
326
|
+
} else {
|
|
327
|
+
advise(`${id}: <style lang="${style.lang}"> is not preprocessed by Skathi — it is compiled as plain CSS`);
|
|
328
|
+
}
|
|
329
|
+
if (style.module) {
|
|
330
|
+
advise(`${id}: <style module> — CSS modules are not supported yet; useCssModule() answers {}`);
|
|
331
|
+
}
|
|
332
|
+
const out = compileStyle({
|
|
333
|
+
source: text,
|
|
334
|
+
filename: absPath,
|
|
335
|
+
id: scopeId,
|
|
336
|
+
scoped: style.scoped ?? false,
|
|
337
|
+
trim: true,
|
|
338
|
+
// MUST match compileScript's `isProd`: both hash a v-bind() variable's name from it.
|
|
339
|
+
isProd: true,
|
|
340
|
+
});
|
|
341
|
+
if (out.errors.length) throw new Error(`${id} <style>: ${out.errors.join("; ")}`);
|
|
342
|
+
cssChunks.push(out.code);
|
|
343
|
+
}
|
|
344
|
+
if (cssChunks.length) cssById.set(id, cssChunks.join("\n"));
|
|
345
|
+
|
|
346
|
+
AOT_INPUTS?.vue(
|
|
347
|
+
absPath,
|
|
348
|
+
source,
|
|
349
|
+
code,
|
|
350
|
+
isTS ? "ts" : "js",
|
|
351
|
+
[descriptor.script?.content, descriptor.scriptSetup?.content].filter(Boolean).join("\n"),
|
|
352
|
+
);
|
|
353
|
+
return { contents: code, loader: isTS ? "ts" : "js" };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const cssEntryIds: string[] = [];
|
|
357
|
+
let appOwnsUtilities = false;
|
|
358
|
+
|
|
359
|
+
const ASSETS = new Map<string, string>();
|
|
360
|
+
|
|
361
|
+
const FRAMEWORK = new Map(
|
|
362
|
+
["vue-router", "pinia"].map((name) => {
|
|
363
|
+
const dep = frameworkDep(
|
|
364
|
+
name,
|
|
365
|
+
APP_PKG,
|
|
366
|
+
(s) => appRequire.resolve(s),
|
|
367
|
+
(s) => runtimeRequire.resolve(s),
|
|
368
|
+
);
|
|
369
|
+
if (dep.warning) advise(dep.warning);
|
|
370
|
+
return [name, dep] as const;
|
|
371
|
+
}),
|
|
372
|
+
);
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* sk.config.json `"aliases"`: a bare module name and the app file standing in for it, relative to
|
|
376
|
+
* the app root: the JS half of a native extension. It wins over the npm package everywhere.
|
|
377
|
+
*/
|
|
378
|
+
function appAliases(raw: unknown): Map<string, string> {
|
|
379
|
+
const out = new Map<string, string>();
|
|
380
|
+
if (raw === undefined) return out;
|
|
381
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
382
|
+
throw new Error(`${SK_CONFIG_PATH}: "aliases" must be an object of { "module": "file" }`);
|
|
383
|
+
}
|
|
384
|
+
for (const [name, target] of Object.entries(raw as Record<string, unknown>)) {
|
|
385
|
+
if (!/^(@[\w.-]+\/)?[\w.-]+(\/[\w.-]+)*$/.test(name) || name.startsWith(".")) {
|
|
386
|
+
throw new Error(`${SK_CONFIG_PATH}: alias "${name}" is not a bare module name`);
|
|
387
|
+
}
|
|
388
|
+
if (isPreseeded(name)) {
|
|
389
|
+
throw new Error(`${SK_CONFIG_PATH}: "${name}" is the engine's own module and cannot be aliased`);
|
|
390
|
+
}
|
|
391
|
+
if (typeof target !== "string" || !target.trim()) {
|
|
392
|
+
throw new Error(`${SK_CONFIG_PATH}: alias "${name}" needs a file path`);
|
|
393
|
+
}
|
|
394
|
+
const file = resolve(SK_CONFIG_DIR, target.trim());
|
|
395
|
+
if (!existsSync(file)) throw new Error(`${SK_CONFIG_PATH}: alias "${name}" → ${file}: no such file`);
|
|
396
|
+
out.set(name, file);
|
|
397
|
+
}
|
|
398
|
+
return out;
|
|
399
|
+
}
|
|
400
|
+
const APP_ALIASES = appAliases(SK_CONFIG.aliases);
|
|
401
|
+
|
|
402
|
+
const AOT_INPUTS = aotInputsDir
|
|
403
|
+
? new AotInputs({
|
|
404
|
+
out: aotInputsDir,
|
|
405
|
+
appRoot: SK_CONFIG_DIR,
|
|
406
|
+
entry: ENTRY_ABS,
|
|
407
|
+
typescript: cliRequire("typescript"),
|
|
408
|
+
aliases: {
|
|
409
|
+
vue: RUNTIME_ENTRY,
|
|
410
|
+
"@skathi-native/runtime": RUNTIME_ENTRY,
|
|
411
|
+
...Object.fromEntries(APP_ALIASES),
|
|
412
|
+
...Object.fromEntries([...FRAMEWORK].map(([name, dependency]) => [name, dependency.path])),
|
|
413
|
+
},
|
|
414
|
+
sourceRoots: { sdk: RUNTIME_DIR, "sdk-modules": RUNTIME_MODULES_DIR },
|
|
415
|
+
declarations: [...new Bun.Glob("*.d.ts").scanSync({ cwd: RUNTIME_SRC_DIR, absolute: true })],
|
|
416
|
+
})
|
|
417
|
+
: null;
|
|
418
|
+
|
|
419
|
+
/** `--graph`: every .js/.ts/.vue file the build loaded, by absolute path. */
|
|
420
|
+
const GRAPH_LOADED = new Set<string>();
|
|
421
|
+
const SHAPE_NOTES = new Map<string, number>();
|
|
422
|
+
const SHAPES = {
|
|
423
|
+
sourceLoaded:
|
|
424
|
+
AOT_INPUTS || graphOut
|
|
425
|
+
? (file: string, source: string, transformed: string) => {
|
|
426
|
+
GRAPH_LOADED.add(file);
|
|
427
|
+
AOT_INPUTS?.source(file, source, transformed);
|
|
428
|
+
}
|
|
429
|
+
: undefined,
|
|
430
|
+
docRoot: SK_CONFIG_DIR,
|
|
431
|
+
wsRoot: WS_ROOT,
|
|
432
|
+
svgDefault: svgDefaultOf(APP_PKG),
|
|
433
|
+
compileSfc: (absPath: string, source: string) => compileVue(absPath, source),
|
|
434
|
+
assets: ASSETS,
|
|
435
|
+
notes: SHAPE_NOTES,
|
|
436
|
+
};
|
|
437
|
+
|
|
438
|
+
const vuePlugin = {
|
|
439
|
+
name: "vue-sfc-prod",
|
|
440
|
+
setup(build: Bun.PluginBuilder) {
|
|
441
|
+
// `import "./index.css"`: Bun would treat the .css as an asset; it becomes an empty module and
|
|
442
|
+
// its content goes into the stylesheet.
|
|
443
|
+
build.onLoad({ filter: /\.css$/ }, async (args: Bun.OnLoadArgs) => {
|
|
444
|
+
const id = toId(args.path);
|
|
445
|
+
if (!cssById.has(id)) {
|
|
446
|
+
const source = await Bun.file(args.path).text();
|
|
447
|
+
if (declaresUtilities(source)) appOwnsUtilities = true;
|
|
448
|
+
cssById.set(id, await viteCss(source, args.path, id));
|
|
449
|
+
cssEntryIds.push(id);
|
|
450
|
+
}
|
|
451
|
+
return { contents: "", loader: "js" };
|
|
452
|
+
});
|
|
453
|
+
build.onResolve({ filter: /^(vue|@skathi-native\/runtime)$/ }, () => ({ path: RUNTIME_ENTRY }));
|
|
454
|
+
if (APP_ALIASES.size) {
|
|
455
|
+
const names = [...APP_ALIASES.keys()].map((name) => name.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&"));
|
|
456
|
+
build.onResolve({ filter: new RegExp(`^(${names.join("|")})$`) }, (args: Bun.OnResolveArgs) => ({
|
|
457
|
+
path: APP_ALIASES.get(args.path)!,
|
|
458
|
+
}));
|
|
459
|
+
}
|
|
460
|
+
build.onResolve({ filter: /^(vue-router|pinia)$/ }, (args: Bun.OnResolveArgs) => ({
|
|
461
|
+
path: FRAMEWORK.get(args.path)!.path,
|
|
462
|
+
}));
|
|
463
|
+
build.onLoad({ filter: /\.vue$/ }, async (args: Bun.OnLoadArgs) => {
|
|
464
|
+
const source = await Bun.file(args.path).text();
|
|
465
|
+
if (graphOut) GRAPH_LOADED.add(args.path);
|
|
466
|
+
return compileVue(args.path, source);
|
|
467
|
+
});
|
|
468
|
+
},
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
const ENTRY_ID = "sk-entry:main";
|
|
472
|
+
const entryPlugin = {
|
|
473
|
+
name: "sk-html-entry",
|
|
474
|
+
setup(build: Bun.PluginBuilder) {
|
|
475
|
+
build.onResolve({ filter: /^sk-(entry|html):/ }, (args: Bun.OnResolveArgs) => ({
|
|
476
|
+
path: args.path,
|
|
477
|
+
namespace: "sk-html",
|
|
478
|
+
}));
|
|
479
|
+
build.onLoad({ filter: /.*/, namespace: "sk-html" }, (args: Bun.OnLoadArgs) => {
|
|
480
|
+
if (args.path === ENTRY_ID) {
|
|
481
|
+
return {
|
|
482
|
+
contents: `import "sk-html:prelude";\nimport ${J(ENTRY_ABS.split(sep).join("/"))};\n`,
|
|
483
|
+
loader: "js",
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
return { contents: HTML_PRELUDE ?? "", loader: "js" };
|
|
487
|
+
});
|
|
488
|
+
},
|
|
489
|
+
};
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* The bundle with every non-ASCII character escaped (ascii.ts): one such character makes
|
|
493
|
+
* JavaScriptCore keep the whole source as UTF-16. Never fails the build: if the result does not
|
|
494
|
+
* lex or parse the same, the bundle is written as is with an advisory. `SK_BUNDLE_UTF8=1` skips it.
|
|
495
|
+
*/
|
|
496
|
+
function asciiBundle(code: string): string {
|
|
497
|
+
const before = nonAsciiCount(code);
|
|
498
|
+
if (!before || process.env.SK_BUNDLE_UTF8 === "1") return code;
|
|
499
|
+
const extraMB = (chars: number) => (chars / 1048576).toFixed(1);
|
|
500
|
+
const r = asciiOnly(code);
|
|
501
|
+
const problem = r.failed ?? checkAscii(code, r.code);
|
|
502
|
+
if (problem) {
|
|
503
|
+
advise(
|
|
504
|
+
`the bundle stays UTF-8 with ${before} non-ASCII characters, so the host holds its source as UTF-16 ` +
|
|
505
|
+
`(~${extraMB(code.length)} MB more): the ASCII pass ${r.failed ? "could not lex it" : "was refused"} - ${problem}`,
|
|
506
|
+
);
|
|
507
|
+
return code;
|
|
508
|
+
}
|
|
509
|
+
if (r.kept) {
|
|
510
|
+
advise(
|
|
511
|
+
`${r.kept} non-ASCII characters in tagged templates are kept as written (a tag can read \`raw\`), so the ` +
|
|
512
|
+
`host still holds the bundle's source as UTF-16 (~${extraMB(r.code.length)} MB more)`,
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
return r.code;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
async function writeGraph(out: string) {
|
|
519
|
+
const result = await Bun.build({
|
|
520
|
+
entrypoints: [HTML_PRELUDE ? ENTRY_ID : ENTRY_ABS],
|
|
521
|
+
format: "iife",
|
|
522
|
+
target: "browser",
|
|
523
|
+
define: DEFINES,
|
|
524
|
+
plugins: [viteShapesPlugin(SHAPES), vuePlugin, entryPlugin],
|
|
525
|
+
minify: minify ? { whitespace: true, identifiers: true, syntax: true } : false,
|
|
526
|
+
sourcemap: "none",
|
|
527
|
+
metafile: true,
|
|
528
|
+
throw: false,
|
|
529
|
+
});
|
|
530
|
+
// Metafile keys are relative, to a base that varies between runs ("node_modules/…", "../../C:/…"):
|
|
531
|
+
// match them against the absolute paths the plugins loaded.
|
|
532
|
+
const byName = new Map<string, { key: string; path: string }[]>();
|
|
533
|
+
for (const path of GRAPH_LOADED) {
|
|
534
|
+
const key = resolve(path).split(sep).join("/").toLowerCase();
|
|
535
|
+
const name = key.slice(key.lastIndexOf("/") + 1);
|
|
536
|
+
byName.set(name, [...(byName.get(name) ?? []), { key, path: resolve(path) }]);
|
|
537
|
+
}
|
|
538
|
+
const modules = new Set<string>();
|
|
539
|
+
for (const output of Object.values(result.metafile?.outputs ?? {})) {
|
|
540
|
+
for (const [key, input] of Object.entries(output.inputs)) {
|
|
541
|
+
if (input.bytesInOutput <= 0) continue;
|
|
542
|
+
const tail = `/${key.replace(/^(?:\.\.\/)+/, "").replace(/^[A-Za-z]:\//, "")}`.toLowerCase();
|
|
543
|
+
for (const loaded of byName.get(tail.slice(tail.lastIndexOf("/") + 1)) ?? [])
|
|
544
|
+
if (loaded.key.endsWith(tail)) modules.add(loaded.path);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
const graph: ModuleGraph = {
|
|
548
|
+
schema: "skathi.module-graph",
|
|
549
|
+
version: 1,
|
|
550
|
+
entry: ENTRY_ABS,
|
|
551
|
+
appRoot: SK_CONFIG_DIR,
|
|
552
|
+
aliases: {
|
|
553
|
+
vue: RUNTIME_ENTRY,
|
|
554
|
+
"@skathi-native/runtime": RUNTIME_ENTRY,
|
|
555
|
+
...Object.fromEntries(APP_ALIASES),
|
|
556
|
+
...Object.fromEntries([...FRAMEWORK].map(([name, dependency]) => [name, dependency.path])),
|
|
557
|
+
},
|
|
558
|
+
declarations: [...new Bun.Glob("*.d.ts").scanSync({ cwd: RUNTIME_SRC_DIR, absolute: true })],
|
|
559
|
+
modules: [...modules].sort(),
|
|
560
|
+
errors: result.logs
|
|
561
|
+
.filter((log) => log.level === "error")
|
|
562
|
+
.map((log) => ({
|
|
563
|
+
message: log.message,
|
|
564
|
+
file: log.position?.file ? resolve(log.position.file) : null,
|
|
565
|
+
line: log.position && log.position.line > 0 ? log.position.line : null,
|
|
566
|
+
column: log.position && log.position.column >= 0 ? log.position.column : null,
|
|
567
|
+
specifier: log.name === "ResolveMessage" ? log.specifier : null,
|
|
568
|
+
})),
|
|
569
|
+
};
|
|
570
|
+
writeAtomic(out, JSON.stringify(graph) + "\n");
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
async function build() {
|
|
574
|
+
const t0 = Date.now();
|
|
575
|
+
let tailwindMs = 0;
|
|
576
|
+
mkdirSync(dirname(OUT_FILE), { recursive: true });
|
|
577
|
+
cssById.clear();
|
|
578
|
+
cssEntryIds.length = 0;
|
|
579
|
+
appOwnsUtilities = false;
|
|
580
|
+
|
|
581
|
+
const result = await Bun.build({
|
|
582
|
+
entrypoints: [HTML_PRELUDE ? ENTRY_ID : ENTRY_ABS],
|
|
583
|
+
format: "iife",
|
|
584
|
+
target: "browser",
|
|
585
|
+
define: DEFINES,
|
|
586
|
+
plugins: [viteShapesPlugin(SHAPES), vuePlugin, entryPlugin],
|
|
587
|
+
minify: minify ? { whitespace: true, identifiers: true, syntax: true } : false,
|
|
588
|
+
sourcemap: "none",
|
|
589
|
+
});
|
|
590
|
+
if (!result.success) {
|
|
591
|
+
for (const log of result.logs) console.error(log);
|
|
592
|
+
throw new Error("prod build failed");
|
|
593
|
+
}
|
|
594
|
+
const body = tagModuleNamespaces(await result.outputs[0]!.text()).code;
|
|
595
|
+
|
|
596
|
+
if (/\b__DEV__\b/.test(body)) {
|
|
597
|
+
throw new Error("__DEV__ survived minification — the define block did not apply");
|
|
598
|
+
}
|
|
599
|
+
const glob = new RegExp(`\\b${GLOB_TRIPWIRE}\\b`).exec(body);
|
|
600
|
+
if (glob) {
|
|
601
|
+
throw new Error(
|
|
602
|
+
`an import.meta.glob(...) survived the build and would throw at startup: …${body.slice(Math.max(0, glob.index - 80), glob.index + 80)}…`,
|
|
603
|
+
);
|
|
604
|
+
}
|
|
605
|
+
// The bundle must also PARSE as a classic script (a surviving `import.meta` is a SyntaxError at
|
|
606
|
+
// eval): parse rather than grep, since a string literal may mention it.
|
|
607
|
+
try {
|
|
608
|
+
new Function(body);
|
|
609
|
+
} catch (e) {
|
|
610
|
+
if (!(e instanceof SyntaxError)) throw e;
|
|
611
|
+
const meta = /\bimport\s*\.\s*meta\b/.exec(body);
|
|
612
|
+
const near = meta ? `: …${body.slice(Math.max(0, meta.index - 60), meta.index + 60)}…` : "";
|
|
613
|
+
throw new Error(
|
|
614
|
+
`the bundle is not a valid classic script (${e.message})${near}` +
|
|
615
|
+
(meta ? " — prod.ts defines import.meta.env/url/hot; anything else needs a define of its own" : ""),
|
|
616
|
+
);
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
const htmlCss = async (pieces: CssPiece[]) => {
|
|
620
|
+
const out: string[] = [];
|
|
621
|
+
for (const p of pieces) {
|
|
622
|
+
if (declaresUtilities(p.text)) appOwnsUtilities = true;
|
|
623
|
+
out.push(await viteCss(p.text, p.from, toId(p.from)));
|
|
624
|
+
}
|
|
625
|
+
return out;
|
|
626
|
+
};
|
|
627
|
+
const headCss = LIFTED ? await htmlCss(LIFTED.headCss) : [];
|
|
628
|
+
const bodyCss = LIFTED ? await htmlCss(LIFTED.bodyCss) : [];
|
|
629
|
+
|
|
630
|
+
// Styles run before the bundle (first paint is styled), sorted by module id to match the dev
|
|
631
|
+
// loader's cascade; the Tailwind sheet (".sk/tailwind.css") sorts first unless an app stylesheet
|
|
632
|
+
// declares `@tailwind utilities`. index.html's sheets bracket it: <head> before, <body> after.
|
|
633
|
+
if (TW_CONFIG && !appOwnsUtilities) {
|
|
634
|
+
const t = Date.now();
|
|
635
|
+
cssById.set(TW_ID, await generateTailwind(TW_CONFIG));
|
|
636
|
+
tailwindMs = Date.now() - t;
|
|
637
|
+
}
|
|
638
|
+
const sheets = [
|
|
639
|
+
...headCss,
|
|
640
|
+
...Array.from(cssById.keys())
|
|
641
|
+
.sort()
|
|
642
|
+
.map((id) => cssById.get(id)!),
|
|
643
|
+
...bodyCss,
|
|
644
|
+
].map(pruneVendorPrefixes);
|
|
645
|
+
const css = sheets.map((text) => `(globalThis.__SK_CSS__ ??= []).push(${J(text)});`).join("\n");
|
|
646
|
+
|
|
647
|
+
const out = asciiBundle(
|
|
648
|
+
[
|
|
649
|
+
`// Skathi production bundle - entry ${toId(ENTRY_ABS)}`,
|
|
650
|
+
`// generated by packages/cli/prod.ts; do not edit`,
|
|
651
|
+
css,
|
|
652
|
+
body,
|
|
653
|
+
].join("\n"),
|
|
654
|
+
);
|
|
655
|
+
writeAtomic(OUT_FILE, out);
|
|
656
|
+
writeAtomic(WINDOW_JSON, windowConfig() + "\n");
|
|
657
|
+
const assets = Array.from(ASSETS.entries())
|
|
658
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
659
|
+
.map(([key, path]) => ({ key, path }));
|
|
660
|
+
writeAtomic(ASSETS_JSON, JSON.stringify(assets, null, 2) + "\n");
|
|
661
|
+
if (AOT_INPUTS) {
|
|
662
|
+
const pinsPath = join(WS_ROOT, "vendor", "redjs", "pins.txt");
|
|
663
|
+
const engine = aotEngineIdentity(existsSync(pinsPath) ? readFileSync(pinsPath, "utf8") : null);
|
|
664
|
+
const manifest = AOT_INPUTS.write({
|
|
665
|
+
script: out,
|
|
666
|
+
scriptUrl: "sk://app.prod.js",
|
|
667
|
+
defines: DEFINES,
|
|
668
|
+
engine,
|
|
669
|
+
sdkVersion: runtimeRequire("./package.json").version,
|
|
670
|
+
});
|
|
671
|
+
console.log(`[prod] typed AOT inputs: ${manifest} (source archive; native AOT compilation not enabled)`);
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
for (const [what, n] of SHAPE_NOTES) console.log(`[prod] ${what}: ${n}`);
|
|
675
|
+
if (LIFTED) {
|
|
676
|
+
console.log(
|
|
677
|
+
`[prod] index.html: ${LIFTED.headCss.length + LIFTED.bodyCss.length} stylesheet(s), ` +
|
|
678
|
+
`${LIFTED.scripts.length} inline script(s) lifted`,
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
for (const [name, dep] of FRAMEWORK) {
|
|
682
|
+
if (dep.from === "app") console.log(`[prod] ${name} ${dep.version}: the app's own copy`);
|
|
683
|
+
}
|
|
684
|
+
for (const a of advisories) console.log(`[prod] advisory: ${a}`);
|
|
685
|
+
|
|
686
|
+
const sfcs = cssById.size - cssEntryIds.length - (cssById.has(TW_ID) ? 1 : 0);
|
|
687
|
+
console.log(
|
|
688
|
+
`prod build: ${(out.length / 1024) | 0} KB (${sfcs} styled SFC${sfcs === 1 ? "" : "s"}` +
|
|
689
|
+
(cssEntryIds.length ? ` + ${cssEntryIds.length} css entr${cssEntryIds.length === 1 ? "y" : "ies"}` : "") +
|
|
690
|
+
(cssById.has(TW_ID)
|
|
691
|
+
? ` + ${((cssById.get(TW_ID)?.length ?? 0) / 1024).toFixed(1)} KB tailwind in ${tailwindMs} ms`
|
|
692
|
+
: "") +
|
|
693
|
+
(assets.length ? ` + ${assets.length} asset${assets.length === 1 ? "" : "s"}` : "") +
|
|
694
|
+
`) -> ${relative(WS_ROOT, OUT_FILE).split(sep).join("/")} in ${Date.now() - t0} ms`,
|
|
695
|
+
);
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
await (graphOut ? writeGraph(graphOut) : build()).catch((e) => {
|
|
699
|
+
console.error(e);
|
|
700
|
+
process.exit(1);
|
|
701
|
+
});
|