@akanjs/cli 3.1.2-rc.4 → 3.2.0-rc.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/.build-stamp +1 -1
- package/{CodeAgent-z34p8m91.js → CodeAgent-h6g8dg3a.js} +2 -2
- package/{CodeTui-nvd9fk3g.js → CodeTui-n9gacepn.js} +1 -1
- package/README.ko.md +9 -0
- package/README.md +9 -0
- package/TunnelShare-k3ja4w9x.js +14 -0
- package/{agent.command-962mp3kg.js → agent.command-2f657613.js} +19 -17
- package/akanCode.js +2 -2
- package/{application.command-1nr0bqq1.js → application.command-yb8v177e.js} +35 -21
- package/{applicationBuildRunner-xy7hnfzq.js → applicationBuildRunner-sctcmkyx.js} +55 -16
- package/buildBatch.proc.js +7 -7
- package/{cloud.command-cj7b3m6y.js → cloud.command-et06ja22.js} +35 -18
- package/cloud.script-s6rbrwer.js +30 -0
- package/{code.command-asq7xrr6.js → code.command-7m67c7zc.js} +6 -6
- package/commandManifest.json +1 -1
- package/{context.command-fw4g2pw1.js → context.command-569z0rqf.js} +20 -19
- package/context.runner-ms8v1rxy.js +29 -0
- package/{guideline.command-43gfjsjv.js → guideline.command-gnv3e8p8.js} +2 -2
- package/guidelines/akanApi/akanApi.instruction.md +317 -0
- package/guidelines/conventions/rules/app.md +5 -5
- package/guidelines/conventions/rules/config.md +1 -1
- package/guidelines/conventions/rules/gates.md +10 -5
- package/incrementalBuilder.proc.js +69 -39
- package/{index-0tkj05cz.js → index-0fb3cpbt.js} +3 -3
- package/{index-6t7fkx73.js → index-1q1cjn8s.js} +21 -11
- package/{index-90q0w90q.js → index-3wjbhj2n.js} +1 -1
- package/{index-6zgt7zmx.js → index-48d5qsj3.js} +4 -4
- package/{index-z47rw9ez.js → index-5w9my9qe.js} +8 -8
- package/{index-qwe079ww.js → index-6wpaq392.js} +61 -15
- package/{index-kc871vpc.js → index-7xdpww43.js} +69 -12
- package/index-7y5yghjg.js +2969 -0
- package/{index-38patcx6.js → index-8g7tdsk4.js} +249 -696
- package/{index-kdswbvys.js → index-8pb9yvp8.js} +63 -21
- package/{index-hmj94es2.js → index-8ts9774g.js} +4 -4
- package/{index-r0q2ka2b.js → index-93ewzmp6.js} +43 -14
- package/{index-y0y0pnx8.js → index-9tbgb4d8.js} +1 -1
- package/index-abgh0jve.js +126 -0
- package/{index-t0hk1kxq.js → index-aj3ehkcx.js} +1 -1
- package/{index-demt944k.js → index-d4n1wmrz.js} +37 -4
- package/{index-sra1a5f8.js → index-drz9e84d.js} +22 -8
- package/{index-gfh90r3t.js → index-e3vmjtph.js} +2 -2
- package/{index-k64mhwbw.js → index-eajbmk10.js} +2 -1
- package/{index-g0yds382.js → index-ed6ea0qp.js} +1 -1
- package/{index-ap6ac70m.js → index-fjr4d6yd.js} +444 -368
- package/index-hqrkqxx2.js +176 -0
- package/{index-jzpeny42.js → index-jdamtr7e.js} +3 -3
- package/{index-ampz4vgv.js → index-kpdv34rq.js} +4 -4
- package/{index-kc6ffq0s.js → index-ktb3wcqz.js} +73 -34
- package/{index-dcm66hss.js → index-mmym5xmb.js} +4 -2
- package/{index-8d9r465x.js → index-mqntfzv5.js} +2 -2
- package/{index-4am4dvmf.js → index-ny2k80mv.js} +15 -3
- package/index-p6hjwt2d.js +1668 -0
- package/{index-53h0053j.js → index-rc5fvqj2.js} +12 -14
- package/{index-r8t5sq7z.js → index-ryrm5z2c.js} +66 -19
- package/{index-jzz6ye8x.js → index-s2grpzef.js} +40 -8
- package/{index-38by07nw.js → index-sr5da35e.js} +32 -9
- package/{index-qev8p5wp.js → index-sy481q2x.js} +1 -1
- package/{index-ck64kxrn.js → index-thckcabc.js} +2 -2
- package/{index-wymcdsas.js → index-vkzfk7qt.js} +25 -23
- package/{index-vkpqe29t.js → index-w639tvkd.js} +24 -125
- package/index-ygdbn9jn.js +122 -0
- package/{index-w60zxxye.js → index-zpv14wpy.js} +3 -3
- package/{index-2yan1ajk.js → index-zxsygkda.js} +18 -9
- package/index.js +24 -23
- package/{library.command-zh29tjdd.js → library.command-1gp5qe3r.js} +3 -3
- package/{localRegistry.command-k9pn9ahj.js → localRegistry.command-v3g21rex.js} +25 -16
- package/{module.command-dgpqs9fz.js → module.command-4xz9he6h.js} +6 -6
- package/{package.command-1je4hsca.js → package.command-s7qpnn1g.js} +12 -3
- package/package.json +2 -2
- package/{page.command-cgsasanh.js → page.command-fan34c49.js} +3 -3
- package/{pipeline.command-tb46sa8v.js → pipeline.command-ph4fnn9w.js} +2 -2
- package/{primitive.command-bzsy23x5.js → primitive.command-3fqh8emf.js} +7 -7
- package/{projectTypecheck-h8rgaczy.js → projectTypecheck-vkb40hjc.js} +1 -1
- package/{quality.command-120m9h6v.js → quality.command-ecj6exsh.js} +15 -10
- package/{repair.command-6m4wd0qv.js → repair.command-fe9jw719.js} +6 -6
- package/{scalar.command-3dn5hsc6.js → scalar.command-cnvfhk0n.js} +5 -5
- package/skills/akan-debug/SKILL.md +2 -1
- package/skills/akan-page/SKILL.md +16 -7
- package/skills/akan-service/SKILL.md +48 -19
- package/{subspace.command-s8nyfqbn.js → subspace.command-yxtt3v3e.js} +8 -8
- package/templates/app/lib/___appName__/__appName__.abstract.md.template +6 -0
- package/templates/app/page/_index.tsx +4 -284
- package/templates/app/page/_layout.tsx +1 -26
- package/templates/app/page/styles.css.template +58 -318
- package/templates/appSample/page/_index.tsx +281 -0
- package/templates/appSample/page/_layout.tsx +55 -0
- package/templates/appSample/page/styles.css.template +327 -0
- package/templates/libRoot/lib/___libName__/__libName__.abstract.md.template +6 -0
- package/templates/workspaceRoot/package.json.template +1 -12
- package/{tunnel.command-8mwrqkr3.js → tunnel.command-ggj38mqf.js} +7 -7
- package/{verify.command-2pspfy7k.js → verify.command-w9ttxkdz.js} +16 -14
- package/{workflow.command-7sy5vnsj.js → workflow.command-ss8devj0.js} +12 -12
- package/{workspace.command-x518tdv4.js → workspace.command-rw1p0xeq.js} +50 -38
- package/TunnelShare-jwbb50kz.js +0 -14
- package/cloud.script-8kr7qgfa.js +0 -27
- package/context.runner-p6m5cxk3.js +0 -28
- package/index-d894868w.js +0 -842
- package/index-re2kfscb.js +0 -1363
- /package/templates/{app → appSample}/page/_overrides.tsx +0 -0
- /package/templates/{app → appSample}/public/fonts/Pretendard-Black.woff2 +0 -0
- /package/templates/{app → appSample}/public/fonts/Pretendard-Bold.woff2 +0 -0
- /package/templates/{app → appSample}/public/fonts/Pretendard-ExtraBold.woff2 +0 -0
- /package/templates/{app → appSample}/public/fonts/Pretendard-ExtraLight.woff2 +0 -0
- /package/templates/{app → appSample}/public/fonts/Pretendard-Light.woff2 +0 -0
- /package/templates/{app → appSample}/public/fonts/Pretendard-Medium.woff2 +0 -0
- /package/templates/{app → appSample}/public/fonts/Pretendard-Regular.woff2 +0 -0
- /package/templates/{app → appSample}/public/fonts/Pretendard-SemiBold.woff2 +0 -0
- /package/templates/{app → appSample}/public/fonts/Pretendard-Thin.woff2 +0 -0
- /package/templates/{app → appSample}/public/jelly/cloud.webp +0 -0
- /package/templates/{app → appSample}/public/jelly/comet.webp +0 -0
- /package/templates/{app → appSample}/public/jelly/moon.webp +0 -0
- /package/templates/{app → appSample}/public/jelly/planet.webp +0 -0
- /package/templates/{app → appSample}/public/jelly/rocket.webp +0 -0
- /package/templates/{app → appSample}/public/jelly/star.webp +0 -0
- /package/templates/{app → appSample}/public/jelly/sugar.webp +0 -0
- /package/templates/{app → appSample}/public/logo.png +0 -0
- /package/templates/{app → appSample}/ui/Recipe/index.ts +0 -0
- /package/templates/{app → appSample}/ui/Recipe/jellyButton.ts +0 -0
|
@@ -0,0 +1,1668 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
JsonFormatter
|
|
4
|
+
} from "./index-sr5da35e.js";
|
|
5
|
+
|
|
6
|
+
// pkgs/@akanjs/devkit/applicationBuildReporter.ts
|
|
7
|
+
import { realpathSync } from "fs";
|
|
8
|
+
import path4 from "path";
|
|
9
|
+
import { Logger } from "akanjs/common";
|
|
10
|
+
|
|
11
|
+
// pkgs/@akanjs/devkit/routeJsBudget.ts
|
|
12
|
+
import path3 from "path";
|
|
13
|
+
import { toError } from "akanjs/common";
|
|
14
|
+
|
|
15
|
+
// pkgs/@akanjs/devkit/frontendBuild/fontPruner.ts
|
|
16
|
+
import { rm, rmdir, stat as stat2 } from "fs/promises";
|
|
17
|
+
import path2 from "path";
|
|
18
|
+
import { isFontOptimizationEnabled } from "akanjs/client";
|
|
19
|
+
|
|
20
|
+
// pkgs/@akanjs/devkit/frontendBuild/fontOptimizer.ts
|
|
21
|
+
import { mkdir, stat } from "fs/promises";
|
|
22
|
+
import path from "path";
|
|
23
|
+
import ts from "typescript";
|
|
24
|
+
var FONT_URL_PREFIX = "/_akan/fonts";
|
|
25
|
+
var DEFAULT_FONT_SUBSETS = ["latin"];
|
|
26
|
+
|
|
27
|
+
class FontOptimizer {
|
|
28
|
+
#app;
|
|
29
|
+
#command;
|
|
30
|
+
#artifactRoot;
|
|
31
|
+
#files = [];
|
|
32
|
+
#cssParts = [];
|
|
33
|
+
#woff2Ready = null;
|
|
34
|
+
static #ksX1001Text = null;
|
|
35
|
+
static #cacheVersion = 3;
|
|
36
|
+
constructor(app, command = "start") {
|
|
37
|
+
this.#app = app;
|
|
38
|
+
this.#command = command;
|
|
39
|
+
this.#artifactRoot = path.join(command === "build" ? app.dist.cwdPath : app.cwdPath, ".akan/artifact");
|
|
40
|
+
}
|
|
41
|
+
async optimize() {
|
|
42
|
+
const fonts = await this.discoverFonts();
|
|
43
|
+
const cacheKey = await this.#buildCacheKey(fonts);
|
|
44
|
+
const cached = cacheKey ? await this.#readCache(cacheKey) : null;
|
|
45
|
+
if (cached) {
|
|
46
|
+
this.#app.verbose(`[font] reused ${cached.files.length} cached file(s); skipped subsetting`);
|
|
47
|
+
return { css: cached.css, fonts, files: cached.files };
|
|
48
|
+
}
|
|
49
|
+
for (const font of fonts) {
|
|
50
|
+
if (!this.#isFontOptimizationEnabled(font))
|
|
51
|
+
continue;
|
|
52
|
+
await this.#optimizeFont(font);
|
|
53
|
+
}
|
|
54
|
+
const fontUtilityCss = this.#buildFontUtilityRules(fonts);
|
|
55
|
+
if (fontUtilityCss)
|
|
56
|
+
this.#cssParts.push(fontUtilityCss);
|
|
57
|
+
const result = { css: this.#cssParts.join(`
|
|
58
|
+
`), fonts, files: this.#files };
|
|
59
|
+
if (cacheKey)
|
|
60
|
+
await this.#writeCache(cacheKey, result);
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
get #cachePath() {
|
|
64
|
+
return path.join(this.#artifactRoot, "fontCache.json");
|
|
65
|
+
}
|
|
66
|
+
async#buildCacheKey(fonts) {
|
|
67
|
+
const sources = [];
|
|
68
|
+
for (const font of fonts) {
|
|
69
|
+
if (!this.#isFontOptimizationEnabled(font))
|
|
70
|
+
continue;
|
|
71
|
+
for (const face of this.#getFontFaces(font)) {
|
|
72
|
+
const sourcePath = await this.#resolveFontSourcePath(face.src);
|
|
73
|
+
const stamp = sourcePath ? await this.#fileStamp(sourcePath) : null;
|
|
74
|
+
if (!stamp)
|
|
75
|
+
return null;
|
|
76
|
+
sources.push({ optimizedSrc: face.optimizedSrc, ...stamp });
|
|
77
|
+
}
|
|
78
|
+
for (const filePath of font.subsetFiles ?? []) {
|
|
79
|
+
const abs = path.isAbsolute(filePath) ? filePath : path.join(this.#app.cwdPath, filePath);
|
|
80
|
+
const stamp = await this.#fileStamp(abs);
|
|
81
|
+
if (!stamp)
|
|
82
|
+
return null;
|
|
83
|
+
sources.push({ subsetFile: filePath, ...stamp });
|
|
84
|
+
}
|
|
85
|
+
if (this.#getFontSubsets(font).includes("auto"))
|
|
86
|
+
sources.push({ autoSubsetText: this.#cacheDigest(await this.#collectAutoSubsetText()) });
|
|
87
|
+
}
|
|
88
|
+
return this.#cacheDigest({ version: FontOptimizer.#cacheVersion, fonts, sources });
|
|
89
|
+
}
|
|
90
|
+
#cacheDigest(value) {
|
|
91
|
+
return new Bun.CryptoHasher("sha256").update(this.#stableStringify(value)).digest("hex");
|
|
92
|
+
}
|
|
93
|
+
async#fileStamp(filePath) {
|
|
94
|
+
try {
|
|
95
|
+
const stats = await stat(filePath);
|
|
96
|
+
return { mtimeMs: Math.round(stats.mtimeMs), size: stats.size };
|
|
97
|
+
} catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
async#readCache(key) {
|
|
102
|
+
const cache = await Bun.file(this.#cachePath).json().catch(() => null);
|
|
103
|
+
if (cache?.version !== FontOptimizer.#cacheVersion || cache.key !== key)
|
|
104
|
+
return null;
|
|
105
|
+
const files = cache.files.map((relativePath) => path.join(this.#artifactRoot, relativePath));
|
|
106
|
+
for (const filePath of files) {
|
|
107
|
+
if (!await Bun.file(filePath).exists())
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
return { css: cache.css, files };
|
|
111
|
+
}
|
|
112
|
+
async#writeCache(key, result) {
|
|
113
|
+
const cache = {
|
|
114
|
+
version: FontOptimizer.#cacheVersion,
|
|
115
|
+
key,
|
|
116
|
+
css: result.css,
|
|
117
|
+
files: result.files.map((filePath) => path.relative(this.#artifactRoot, filePath))
|
|
118
|
+
};
|
|
119
|
+
await Bun.write(this.#cachePath, JSON.stringify(cache));
|
|
120
|
+
}
|
|
121
|
+
async discoverFonts() {
|
|
122
|
+
const pageKeys = await this.#app.getPageKeys();
|
|
123
|
+
const fonts = [];
|
|
124
|
+
await Promise.all(pageKeys.map(async (key) => {
|
|
125
|
+
const filePath = path.resolve(this.#app.cwdPath, "page", key);
|
|
126
|
+
const file = Bun.file(filePath);
|
|
127
|
+
if (!await file.exists())
|
|
128
|
+
return;
|
|
129
|
+
const source = await file.text();
|
|
130
|
+
if (!source.includes("fonts"))
|
|
131
|
+
return;
|
|
132
|
+
fonts.push(...this.#extractFontsExport(source, filePath));
|
|
133
|
+
}));
|
|
134
|
+
return [...new Map(fonts.map((font) => [JSON.stringify(font), font])).values()];
|
|
135
|
+
}
|
|
136
|
+
async#optimizeFont(font) {
|
|
137
|
+
const faceCss = [];
|
|
138
|
+
for (const face of this.#getFontFaces(font)) {
|
|
139
|
+
const sourcePath = await this.#resolveFontSourcePath(face.src);
|
|
140
|
+
if (!sourcePath) {
|
|
141
|
+
this.#app.logger.warn(`[font] source not found: ${face.src}`);
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const outputPath = path.join(this.#artifactRoot, face.optimizedSrc.replace(/^\/_akan\//, ""));
|
|
145
|
+
await mkdir(path.dirname(outputPath), { recursive: true });
|
|
146
|
+
const sourceBuffer = Buffer.from(await Bun.file(sourcePath).arrayBuffer());
|
|
147
|
+
const outputBuffer = await this.#buildFontBuffer(font, sourceBuffer, sourcePath);
|
|
148
|
+
await Bun.write(outputPath, outputBuffer);
|
|
149
|
+
this.#files.push(outputPath);
|
|
150
|
+
faceCss.push(this.#buildOptimizedFontFaceRule(font, face));
|
|
151
|
+
const fallbackCss = await this.#buildFontaineFallbackCss(font, face, sourcePath);
|
|
152
|
+
if (fallbackCss)
|
|
153
|
+
faceCss.push(fallbackCss);
|
|
154
|
+
}
|
|
155
|
+
if (faceCss.length > 0)
|
|
156
|
+
this.#cssParts.push(...faceCss, this.#buildRootVariableRule(font));
|
|
157
|
+
}
|
|
158
|
+
#extractFontsExport(source, filePath) {
|
|
159
|
+
const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
160
|
+
const declaration = this.#findFontsDeclaration(sourceFile);
|
|
161
|
+
if (!declaration)
|
|
162
|
+
return [];
|
|
163
|
+
const value = this.#literalToValue(declaration);
|
|
164
|
+
const entries = Array.isArray(value) ? value : [];
|
|
165
|
+
const fonts = entries.filter((entry) => this.#isReadableFont(entry));
|
|
166
|
+
if (fonts.length !== entries.length || !Array.isArray(value))
|
|
167
|
+
this.#app.logger.warn(`[font] ${path.relative(this.#app.cwdPath, filePath)} declares fonts the build cannot read without evaluating the module \u2014 write the list inline, or nothing is subset for it and every /_akan/fonts request 404s`);
|
|
168
|
+
return fonts.map((font) => ({ ...font, subsets: font.subsets ?? [...DEFAULT_FONT_SUBSETS] }));
|
|
169
|
+
}
|
|
170
|
+
#isReadableFont(value) {
|
|
171
|
+
if (!value || typeof value !== "object")
|
|
172
|
+
return false;
|
|
173
|
+
const font = value;
|
|
174
|
+
return typeof font.name === "string" && Array.isArray(font.paths);
|
|
175
|
+
}
|
|
176
|
+
#findFontsDeclaration(sourceFile) {
|
|
177
|
+
for (const statement of sourceFile.statements) {
|
|
178
|
+
if (ts.isExportAssignment(statement)) {
|
|
179
|
+
if (statement.isExportEquals)
|
|
180
|
+
continue;
|
|
181
|
+
const stage = this.#findChainStageArgument(statement.expression, "fonts");
|
|
182
|
+
if (stage)
|
|
183
|
+
return stage;
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
if (!ts.isVariableStatement(statement))
|
|
187
|
+
continue;
|
|
188
|
+
const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined;
|
|
189
|
+
if (!modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword))
|
|
190
|
+
continue;
|
|
191
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
192
|
+
if (!ts.isIdentifier(declaration.name) || declaration.name.text !== "fonts")
|
|
193
|
+
continue;
|
|
194
|
+
if (declaration.initializer)
|
|
195
|
+
return declaration.initializer;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
#findChainStageArgument(expression, stageName) {
|
|
201
|
+
let node = this.#unwrapExpression(expression);
|
|
202
|
+
let argument = null;
|
|
203
|
+
while (node && ts.isCallExpression(node)) {
|
|
204
|
+
const callee = this.#unwrapExpression(node.expression);
|
|
205
|
+
if (!callee)
|
|
206
|
+
return null;
|
|
207
|
+
if (ts.isIdentifier(callee))
|
|
208
|
+
return callee.text === "rootLayout" ? argument : null;
|
|
209
|
+
if (!ts.isPropertyAccessExpression(callee))
|
|
210
|
+
return null;
|
|
211
|
+
if (callee.name.text === stageName)
|
|
212
|
+
argument ??= node.arguments[0] ?? null;
|
|
213
|
+
node = this.#unwrapExpression(callee.expression);
|
|
214
|
+
}
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
#unwrapExpression(expression) {
|
|
218
|
+
let current = expression;
|
|
219
|
+
while (current && (ts.isAsExpression(current) || ts.isSatisfiesExpression(current) || ts.isParenthesizedExpression(current))) {
|
|
220
|
+
current = current.expression;
|
|
221
|
+
}
|
|
222
|
+
return current;
|
|
223
|
+
}
|
|
224
|
+
#literalToValue(node) {
|
|
225
|
+
if (ts.isStringLiteralLike(node))
|
|
226
|
+
return node.text;
|
|
227
|
+
if (ts.isNumericLiteral(node))
|
|
228
|
+
return Number(node.text);
|
|
229
|
+
if (node.kind === ts.SyntaxKind.TrueKeyword)
|
|
230
|
+
return true;
|
|
231
|
+
if (node.kind === ts.SyntaxKind.FalseKeyword)
|
|
232
|
+
return false;
|
|
233
|
+
if (ts.isArrayLiteralExpression(node))
|
|
234
|
+
return node.elements.map((element) => this.#literalToValue(element));
|
|
235
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
236
|
+
const obj = {};
|
|
237
|
+
for (const prop of node.properties) {
|
|
238
|
+
if (!ts.isPropertyAssignment(prop))
|
|
239
|
+
continue;
|
|
240
|
+
const name = this.#getPropertyName(prop.name);
|
|
241
|
+
if (!name)
|
|
242
|
+
continue;
|
|
243
|
+
obj[name] = this.#literalToValue(prop.initializer);
|
|
244
|
+
}
|
|
245
|
+
return obj;
|
|
246
|
+
}
|
|
247
|
+
if (ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isParenthesizedExpression(node)) {
|
|
248
|
+
return this.#literalToValue(node.expression);
|
|
249
|
+
}
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
#getPropertyName(name) {
|
|
253
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name))
|
|
254
|
+
return name.text;
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
#getFontSubsets(font) {
|
|
258
|
+
return font.subsets ?? DEFAULT_FONT_SUBSETS;
|
|
259
|
+
}
|
|
260
|
+
#getFontVariableName(font) {
|
|
261
|
+
return font.variable ?? `--font-${font.name}`;
|
|
262
|
+
}
|
|
263
|
+
#getFontFallbackName(font) {
|
|
264
|
+
return font.fallbackName ?? `${font.name} fallback`;
|
|
265
|
+
}
|
|
266
|
+
#isFontOptimizationEnabled(font) {
|
|
267
|
+
return font.optimize !== false;
|
|
268
|
+
}
|
|
269
|
+
#getFontFaces(font) {
|
|
270
|
+
const enabledStyles = new Set(font.styles?.length ? font.styles : ["normal"]);
|
|
271
|
+
return font.paths.map((fontPath) => {
|
|
272
|
+
const style = fontPath.style ?? "normal";
|
|
273
|
+
return {
|
|
274
|
+
font,
|
|
275
|
+
path: fontPath,
|
|
276
|
+
src: fontPath.src,
|
|
277
|
+
weight: fontPath.weight,
|
|
278
|
+
style,
|
|
279
|
+
optimizedSrc: this.#getOptimizedFontSrc(font, fontPath)
|
|
280
|
+
};
|
|
281
|
+
}).filter((face) => enabledStyles.has(face.style));
|
|
282
|
+
}
|
|
283
|
+
#getOptimizedFontSrc(font, fontPath) {
|
|
284
|
+
const style = fontPath.style ?? "normal";
|
|
285
|
+
const hash = this.#hashFontConfig({
|
|
286
|
+
name: font.name,
|
|
287
|
+
src: fontPath.src,
|
|
288
|
+
weight: fontPath.weight,
|
|
289
|
+
style,
|
|
290
|
+
display: font.display,
|
|
291
|
+
subset: font.subset,
|
|
292
|
+
subsets: this.#getFontSubsets(font),
|
|
293
|
+
subsetText: font.subsetText,
|
|
294
|
+
subsetFiles: font.subsetFiles,
|
|
295
|
+
declarations: [...font.declarations ?? [], ...fontPath.declarations ?? []]
|
|
296
|
+
});
|
|
297
|
+
return `${FONT_URL_PREFIX}/${this.#slugFontPart(font.name)}-${this.#slugFontPart(String(fontPath.weight))}-${style}-${hash}.woff2`;
|
|
298
|
+
}
|
|
299
|
+
#hashFontConfig(value) {
|
|
300
|
+
const input = this.#stableStringify(value);
|
|
301
|
+
let hash = 2166136261;
|
|
302
|
+
for (let i = 0;i < input.length; i++) {
|
|
303
|
+
hash ^= input.charCodeAt(i);
|
|
304
|
+
hash = Math.imul(hash, 16777619);
|
|
305
|
+
}
|
|
306
|
+
return (hash >>> 0).toString(36);
|
|
307
|
+
}
|
|
308
|
+
#stableStringify(value) {
|
|
309
|
+
if (Array.isArray(value))
|
|
310
|
+
return `[${value.map((item) => this.#stableStringify(item)).join(",")}]`;
|
|
311
|
+
if (value && typeof value === "object") {
|
|
312
|
+
const entries = Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a.localeCompare(b));
|
|
313
|
+
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${this.#stableStringify(v)}`).join(",")}}`;
|
|
314
|
+
}
|
|
315
|
+
return JSON.stringify(value);
|
|
316
|
+
}
|
|
317
|
+
#slugFontPart(value) {
|
|
318
|
+
return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "font";
|
|
319
|
+
}
|
|
320
|
+
async#resolveFontSourcePath(src) {
|
|
321
|
+
if (!src.startsWith("/"))
|
|
322
|
+
return null;
|
|
323
|
+
const rel = src.replace(/^\//, "");
|
|
324
|
+
const candidates = [
|
|
325
|
+
this.#command === "build" ? path.join(this.#app.dist.cwdPath, "public", rel) : null,
|
|
326
|
+
path.join(this.#app.cwdPath, "public", rel),
|
|
327
|
+
this.#resolveWorkspacePublicPath(rel)
|
|
328
|
+
].filter(Boolean);
|
|
329
|
+
for (const candidate of candidates) {
|
|
330
|
+
if (await Bun.file(candidate).exists())
|
|
331
|
+
return candidate;
|
|
332
|
+
}
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
async#buildFontBuffer(font, sourceBuffer, sourcePath) {
|
|
336
|
+
if (font.subset === false)
|
|
337
|
+
return this.#convertToWoff2(sourceBuffer, sourcePath);
|
|
338
|
+
const { default: subsetFont } = await import("subset-font");
|
|
339
|
+
return subsetFont(sourceBuffer, await this.#getSubsetText(font), { targetFormat: "woff2" });
|
|
340
|
+
}
|
|
341
|
+
async#convertToWoff2(buffer, sourcePath) {
|
|
342
|
+
const { createFont } = await import("fonteditor-core");
|
|
343
|
+
this.#woff2Ready ??= import("fonteditor-core").then(({ woff2 }) => woff2.init()).then(() => {
|
|
344
|
+
return;
|
|
345
|
+
});
|
|
346
|
+
await this.#woff2Ready;
|
|
347
|
+
const font = createFont(buffer, { type: this.#getFontType(sourcePath, buffer) });
|
|
348
|
+
return font.write({ type: "woff2", toBuffer: true });
|
|
349
|
+
}
|
|
350
|
+
#getFontType(sourcePath, buffer) {
|
|
351
|
+
const signature = buffer.toString("ascii", 0, 4);
|
|
352
|
+
if (signature === "wOFF")
|
|
353
|
+
return "woff";
|
|
354
|
+
if (signature === "wOF2")
|
|
355
|
+
return "woff2";
|
|
356
|
+
if (signature === "OTTO")
|
|
357
|
+
return "otf";
|
|
358
|
+
const ext = path.extname(sourcePath).slice(1).toLowerCase();
|
|
359
|
+
if (ext === "otf" || ext === "woff" || ext === "woff2")
|
|
360
|
+
return ext;
|
|
361
|
+
return "ttf";
|
|
362
|
+
}
|
|
363
|
+
#resolveWorkspacePublicPath(rel) {
|
|
364
|
+
const [root, dep, ...rest] = rel.split("/");
|
|
365
|
+
if (root !== "libs" || !dep || rest.length === 0)
|
|
366
|
+
return null;
|
|
367
|
+
return path.join(this.#app.workspace.workspaceRoot, "libs", dep, "public", ...rest);
|
|
368
|
+
}
|
|
369
|
+
async#getSubsetText(font) {
|
|
370
|
+
const parts = new Set;
|
|
371
|
+
const subsets = this.#getFontSubsets(font);
|
|
372
|
+
for (const subset of subsets)
|
|
373
|
+
parts.add(await this.#getSubsetPresetText(subset));
|
|
374
|
+
if (font.subsetText)
|
|
375
|
+
parts.add(font.subsetText);
|
|
376
|
+
for (const filePath of font.subsetFiles ?? []) {
|
|
377
|
+
const abs = path.isAbsolute(filePath) ? filePath : path.join(this.#app.cwdPath, filePath);
|
|
378
|
+
const file = Bun.file(abs);
|
|
379
|
+
if (await file.exists())
|
|
380
|
+
parts.add(await file.text());
|
|
381
|
+
}
|
|
382
|
+
return [...parts].join("");
|
|
383
|
+
}
|
|
384
|
+
async#getSubsetPresetText(subset) {
|
|
385
|
+
if (subset === "latin")
|
|
386
|
+
return FontOptimizer.#rangeText(32, 126);
|
|
387
|
+
if (subset === "latin-ext")
|
|
388
|
+
return `${FontOptimizer.#rangeText(32, 126)}${FontOptimizer.#rangeText(160, 591)}`;
|
|
389
|
+
if (subset === "ks-x-1001")
|
|
390
|
+
return FontOptimizer.#getKsX1001Text();
|
|
391
|
+
if (subset === "auto")
|
|
392
|
+
return this.#collectAutoSubsetText();
|
|
393
|
+
return "";
|
|
394
|
+
}
|
|
395
|
+
async#collectAutoSubsetText() {
|
|
396
|
+
const libPageRoots = (await this.#app.getPageRoots()).filter((root) => root.keyPrefix).map((root) => root.dir);
|
|
397
|
+
const roots = [...["page", "ui", "lib"].map((dir) => path.join(this.#app.cwdPath, dir)), ...libPageRoots];
|
|
398
|
+
const glob = new Bun.Glob("**/*.{ts,tsx,js,jsx,html,md}");
|
|
399
|
+
const parts = [];
|
|
400
|
+
for (const root of [...new Set(roots)].sort()) {
|
|
401
|
+
const isDir = await stat(root).then((entry) => entry.isDirectory(), () => false);
|
|
402
|
+
if (!isDir)
|
|
403
|
+
continue;
|
|
404
|
+
const filePaths = [];
|
|
405
|
+
for await (const filePath of glob.scan({ cwd: root, absolute: true }))
|
|
406
|
+
filePaths.push(filePath);
|
|
407
|
+
for (const filePath of filePaths.sort((a, b) => a < b ? -1 : a > b ? 1 : 0))
|
|
408
|
+
parts.push(await Bun.file(filePath).text());
|
|
409
|
+
}
|
|
410
|
+
return parts.join("");
|
|
411
|
+
}
|
|
412
|
+
static #getKsX1001Text() {
|
|
413
|
+
if (FontOptimizer.#ksX1001Text)
|
|
414
|
+
return FontOptimizer.#ksX1001Text;
|
|
415
|
+
try {
|
|
416
|
+
const decoder = new TextDecoder("euc-kr");
|
|
417
|
+
const chars = new Set;
|
|
418
|
+
for (let lead = 161;lead <= 254; lead++) {
|
|
419
|
+
for (let trail = 161;trail <= 254; trail++) {
|
|
420
|
+
const char = decoder.decode(Uint8Array.of(lead, trail));
|
|
421
|
+
if (char && char !== "\uFFFD")
|
|
422
|
+
chars.add(char);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
FontOptimizer.#ksX1001Text = [...chars].join("");
|
|
426
|
+
} catch {
|
|
427
|
+
FontOptimizer.#ksX1001Text = FontOptimizer.#rangeText(44032, 55203);
|
|
428
|
+
}
|
|
429
|
+
return FontOptimizer.#ksX1001Text;
|
|
430
|
+
}
|
|
431
|
+
static #rangeText(start, end) {
|
|
432
|
+
let text = "";
|
|
433
|
+
for (let code = start;code <= end; code++)
|
|
434
|
+
text += String.fromCodePoint(code);
|
|
435
|
+
return text;
|
|
436
|
+
}
|
|
437
|
+
#buildOptimizedFontFaceRule(font, face) {
|
|
438
|
+
const declarations = [
|
|
439
|
+
["font-family", this.#quote(font.name)],
|
|
440
|
+
["src", `url(${this.#quote(face.optimizedSrc)}) format("woff2")`],
|
|
441
|
+
["font-weight", String(face.weight)],
|
|
442
|
+
["font-style", face.style],
|
|
443
|
+
["font-display", font.display ?? "swap"],
|
|
444
|
+
...this.#toDeclarationEntries(font.declarations),
|
|
445
|
+
...this.#toDeclarationEntries(face.path.declarations)
|
|
446
|
+
];
|
|
447
|
+
return `@font-face {
|
|
448
|
+
${declarations.map(([prop, value]) => ` ${prop}: ${value};`).join(`
|
|
449
|
+
`)}
|
|
450
|
+
}`;
|
|
451
|
+
}
|
|
452
|
+
async#buildFontaineFallbackCss(font, face, sourcePath) {
|
|
453
|
+
if (font.adjustFontFallback === false)
|
|
454
|
+
return "";
|
|
455
|
+
const { generateFontFace, getMetricsForFamily, readMetrics, resolveCategoryFallbacks } = await import("fontaine");
|
|
456
|
+
const metrics = await readMetrics(Bun.pathToFileURL(sourcePath)).catch(() => null);
|
|
457
|
+
if (!metrics)
|
|
458
|
+
return "";
|
|
459
|
+
const fallbacks = resolveCategoryFallbacks({
|
|
460
|
+
fontFamily: font.name,
|
|
461
|
+
fallbacks: font.fallbacks ?? {},
|
|
462
|
+
metrics: { ...metrics, category: font.category }
|
|
463
|
+
});
|
|
464
|
+
const css = [];
|
|
465
|
+
for (let i = fallbacks.length - 1;i >= 0; i--) {
|
|
466
|
+
const fallback = fallbacks[i];
|
|
467
|
+
const fallbackMetrics = await getMetricsForFamily(fallback);
|
|
468
|
+
if (!fallbackMetrics)
|
|
469
|
+
continue;
|
|
470
|
+
css.push(generateFontFace({ ...metrics, category: font.category }, {
|
|
471
|
+
name: this.#getFontFallbackName(font),
|
|
472
|
+
font: fallback,
|
|
473
|
+
metrics: fallbackMetrics,
|
|
474
|
+
"font-weight": String(face.weight),
|
|
475
|
+
"font-style": face.style
|
|
476
|
+
}));
|
|
477
|
+
}
|
|
478
|
+
return css.join("");
|
|
479
|
+
}
|
|
480
|
+
#buildRootVariableRule(font) {
|
|
481
|
+
return `:root { ${this.#getFontVariableName(font)}: ${this.#quote(font.name)}, ${this.#quote(this.#getFontFallbackName(font))}; }`;
|
|
482
|
+
}
|
|
483
|
+
#buildFontUtilityRules(fonts) {
|
|
484
|
+
const rules = [];
|
|
485
|
+
const seen = new Set;
|
|
486
|
+
for (const font of fonts) {
|
|
487
|
+
const className = font.className || `font-${font.name}`;
|
|
488
|
+
const selector = `.${this.#escapeCssClassName(className)}`;
|
|
489
|
+
const rule = `${selector} { font-family: var(${this.#getFontVariableName(font)}); }`;
|
|
490
|
+
if (seen.has(rule))
|
|
491
|
+
continue;
|
|
492
|
+
seen.add(rule);
|
|
493
|
+
rules.push(rule);
|
|
494
|
+
}
|
|
495
|
+
return rules.join(`
|
|
496
|
+
`);
|
|
497
|
+
}
|
|
498
|
+
#escapeCssClassName(value) {
|
|
499
|
+
return value.replace(/^-?\d|[^a-zA-Z0-9_-]/g, (part) => [...part].map((char) => `\\${char.codePointAt(0)?.toString(16)} `).join(""));
|
|
500
|
+
}
|
|
501
|
+
#toDeclarationEntries(declarations = []) {
|
|
502
|
+
return declarations.map((declaration) => [declaration.prop, declaration.value]);
|
|
503
|
+
}
|
|
504
|
+
#quote(value) {
|
|
505
|
+
return JSON.stringify(value);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// pkgs/@akanjs/devkit/frontendBuild/fontPruner.ts
|
|
510
|
+
var FONT_GLOB = "**/*.{woff2,woff,ttf,otf,ttc,eot}";
|
|
511
|
+
var REFERRER_GLOB = "**/*.{css,js,mjs,cjs,json,html,htm,svg,xml,webmanifest}";
|
|
512
|
+
|
|
513
|
+
class FontPruner {
|
|
514
|
+
#app;
|
|
515
|
+
#keepGlobs;
|
|
516
|
+
#publicRoot;
|
|
517
|
+
#artifactRoot;
|
|
518
|
+
constructor(app, { keepFonts = [] } = {}) {
|
|
519
|
+
this.#app = app;
|
|
520
|
+
this.#keepGlobs = keepFonts;
|
|
521
|
+
this.#publicRoot = path2.join(app.dist.cwdPath, "public");
|
|
522
|
+
this.#artifactRoot = path2.join(app.dist.cwdPath, ".akan/artifact");
|
|
523
|
+
}
|
|
524
|
+
async prune() {
|
|
525
|
+
const empty = { removed: [], kept: [], freedBytes: 0 };
|
|
526
|
+
if (!await this.#isDirectory(this.#publicRoot))
|
|
527
|
+
return empty;
|
|
528
|
+
const candidates = await this.#collectCandidates();
|
|
529
|
+
if (!candidates.length)
|
|
530
|
+
return empty;
|
|
531
|
+
const fonts = await new FontOptimizer(this.#app, "build").discoverFonts();
|
|
532
|
+
const unoptimizedSrcs = new Set;
|
|
533
|
+
const optimizedSrcs = new Set;
|
|
534
|
+
for (const font of fonts) {
|
|
535
|
+
const target = isFontOptimizationEnabled(font) ? optimizedSrcs : unoptimizedSrcs;
|
|
536
|
+
for (const fontPath of font.paths)
|
|
537
|
+
target.add(path2.posix.basename(fontPath.src));
|
|
538
|
+
}
|
|
539
|
+
const result = { removed: [], kept: [], freedBytes: 0 };
|
|
540
|
+
const undecided = [];
|
|
541
|
+
for (const candidate of candidates) {
|
|
542
|
+
const reason = this.#staticKeepReason(candidate, unoptimizedSrcs);
|
|
543
|
+
if (reason)
|
|
544
|
+
result.kept.push({ file: candidate.rel, bytes: candidate.bytes, reason });
|
|
545
|
+
else
|
|
546
|
+
undecided.push(candidate);
|
|
547
|
+
}
|
|
548
|
+
if (undecided.length) {
|
|
549
|
+
const referrers = await this.#findReferrers(undecided, optimizedSrcs);
|
|
550
|
+
for (const candidate of undecided) {
|
|
551
|
+
const referrer = referrers.get(candidate.rel);
|
|
552
|
+
if (referrer)
|
|
553
|
+
result.kept.push({ file: candidate.rel, bytes: candidate.bytes, reason: { kind: "referenced", referrer } });
|
|
554
|
+
else
|
|
555
|
+
result.removed.push({ file: candidate.rel, bytes: candidate.bytes });
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
await this.#remove(result.removed.map(({ file }) => file));
|
|
559
|
+
result.freedBytes = result.removed.reduce((total, { bytes }) => total + bytes, 0);
|
|
560
|
+
this.#report(result);
|
|
561
|
+
return result;
|
|
562
|
+
}
|
|
563
|
+
#staticKeepReason(candidate, unoptimizedSrcs) {
|
|
564
|
+
if (unoptimizedSrcs.has(candidate.basename))
|
|
565
|
+
return { kind: "unoptimized" };
|
|
566
|
+
for (const glob of this.#keepGlobs) {
|
|
567
|
+
if (new Bun.Glob(glob).match(candidate.rel))
|
|
568
|
+
return { kind: "declared", glob };
|
|
569
|
+
}
|
|
570
|
+
return null;
|
|
571
|
+
}
|
|
572
|
+
async#collectCandidates() {
|
|
573
|
+
const candidates = [];
|
|
574
|
+
for await (const rel of new Bun.Glob(FONT_GLOB).scan({ cwd: this.#publicRoot, dot: false })) {
|
|
575
|
+
const entry = await stat2(path2.join(this.#publicRoot, rel)).catch(() => null);
|
|
576
|
+
if (!entry?.isFile())
|
|
577
|
+
continue;
|
|
578
|
+
candidates.push({ rel: rel.split(path2.sep).join("/"), basename: path2.basename(rel), bytes: entry.size });
|
|
579
|
+
}
|
|
580
|
+
return candidates;
|
|
581
|
+
}
|
|
582
|
+
async#findReferrers(candidates, optimizedSrcs) {
|
|
583
|
+
const referrers = new Map;
|
|
584
|
+
const authoritative = candidates;
|
|
585
|
+
const bundled = candidates.filter((candidate) => !optimizedSrcs.has(candidate.basename));
|
|
586
|
+
const roots = [
|
|
587
|
+
{ dir: this.#publicRoot, label: "public", needles: authoritative },
|
|
588
|
+
{ dir: path2.join(this.#artifactRoot, "styles"), label: ".akan/artifact/styles", needles: authoritative },
|
|
589
|
+
{ dir: path2.join(this.#artifactRoot, "client"), label: ".akan/artifact/client", needles: bundled },
|
|
590
|
+
{ dir: path2.join(this.#artifactRoot, "client-ssr"), label: ".akan/artifact/client-ssr", needles: bundled },
|
|
591
|
+
{ dir: path2.join(this.#artifactRoot, "server"), label: ".akan/artifact/server", needles: bundled },
|
|
592
|
+
{ dir: path2.join(this.#app.dist.cwdPath, "csr"), label: "csr", needles: bundled },
|
|
593
|
+
{ dir: path2.join(this.#app.dist.cwdPath, "mcp-apps"), label: "mcp-apps", needles: bundled }
|
|
594
|
+
];
|
|
595
|
+
for (const root of roots) {
|
|
596
|
+
const pending = root.needles.filter((candidate) => !referrers.has(candidate.rel));
|
|
597
|
+
if (!pending.length || !await this.#isDirectory(root.dir))
|
|
598
|
+
continue;
|
|
599
|
+
await this.#scanRoot(root, pending, referrers);
|
|
600
|
+
}
|
|
601
|
+
return referrers;
|
|
602
|
+
}
|
|
603
|
+
async#scanRoot(root, pending, referrers) {
|
|
604
|
+
const needles = pending.map((candidate) => ({
|
|
605
|
+
rel: candidate.rel,
|
|
606
|
+
forms: [...new Set([candidate.basename, encodeURIComponent(candidate.basename)])]
|
|
607
|
+
}));
|
|
608
|
+
for await (const rel of new Bun.Glob(REFERRER_GLOB).scan({ cwd: root.dir, dot: false })) {
|
|
609
|
+
const remaining = needles.filter((needle) => !referrers.has(needle.rel));
|
|
610
|
+
if (!remaining.length)
|
|
611
|
+
return;
|
|
612
|
+
const text = await Bun.file(path2.join(root.dir, rel)).text().catch(() => "");
|
|
613
|
+
if (!text)
|
|
614
|
+
continue;
|
|
615
|
+
for (const needle of remaining) {
|
|
616
|
+
if (needle.forms.some((form) => text.includes(form)))
|
|
617
|
+
referrers.set(needle.rel, `${root.label}/${rel.split(path2.sep).join("/")}`);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
async#remove(files) {
|
|
622
|
+
await Promise.all(files.map((file) => rm(path2.join(this.#publicRoot, file), { force: true })));
|
|
623
|
+
const dirs = [...new Set(files.map((file) => path2.posix.dirname(file)))].filter((dir) => dir !== "." && dir !== "/").sort((a, b) => b.length - a.length);
|
|
624
|
+
for (const dir of dirs)
|
|
625
|
+
await rmdir(path2.join(this.#publicRoot, dir)).catch(() => {
|
|
626
|
+
return;
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
#report(result) {
|
|
630
|
+
if (!result.removed.length && !result.kept.length)
|
|
631
|
+
return;
|
|
632
|
+
for (const { file, bytes } of result.removed)
|
|
633
|
+
this.#app.verbose(`[font-prune] dropped public/${file} (${FontPruner.formatBytes(bytes)})`);
|
|
634
|
+
for (const { file, reason } of result.kept)
|
|
635
|
+
this.#app.verbose(`[font-prune] kept public/${file} \u2014 ${FontPruner.describe(reason)}`);
|
|
636
|
+
const byReferrer = new Map;
|
|
637
|
+
for (const { bytes, reason } of result.kept) {
|
|
638
|
+
if (reason.kind !== "referenced")
|
|
639
|
+
continue;
|
|
640
|
+
const entry = byReferrer.get(reason.referrer) ?? { files: 0, bytes: 0 };
|
|
641
|
+
entry.files += 1;
|
|
642
|
+
entry.bytes += bytes;
|
|
643
|
+
byReferrer.set(reason.referrer, entry);
|
|
644
|
+
}
|
|
645
|
+
if (!byReferrer.size)
|
|
646
|
+
return;
|
|
647
|
+
const ranked = [...byReferrer.entries()].sort(([, a], [, b]) => b.bytes - a.bytes);
|
|
648
|
+
const named = ranked.slice(0, 3).map(([referrer, { files, bytes }]) => `${referrer} (${files}, ${FontPruner.formatBytes(bytes)})`);
|
|
649
|
+
const rest = ranked.length - named.length;
|
|
650
|
+
this.#app.logger.info(`[font-prune] kept ${FontPruner.formatBytes(ranked.reduce((total, [, entry]) => total + entry.bytes, 0))} of fonts in public/ because these reference them: ${named.join(", ")}${rest > 0 ? ` and ${rest} more` : ""}`);
|
|
651
|
+
}
|
|
652
|
+
static describe(reason) {
|
|
653
|
+
if (reason.kind === "unoptimized")
|
|
654
|
+
return "declared with optimize: false, so the runtime CSS serves it";
|
|
655
|
+
if (reason.kind === "declared")
|
|
656
|
+
return `kept by assets.keepFonts "${reason.glob}"`;
|
|
657
|
+
return `referenced by ${reason.referrer}`;
|
|
658
|
+
}
|
|
659
|
+
static formatBytes(bytes) {
|
|
660
|
+
if (bytes < 1024)
|
|
661
|
+
return `${bytes}B`;
|
|
662
|
+
if (bytes < 1024 * 1024)
|
|
663
|
+
return `${(bytes / 1024).toFixed(1)}KB`;
|
|
664
|
+
return `${(bytes / 1024 / 1024).toFixed(1)}MB`;
|
|
665
|
+
}
|
|
666
|
+
async#isDirectory(dir) {
|
|
667
|
+
return await stat2(dir).then((entry) => entry.isDirectory(), () => false);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// pkgs/@akanjs/devkit/routeJsBudget.ts
|
|
672
|
+
class RouteJsBudget {
|
|
673
|
+
kbByRoute;
|
|
674
|
+
env;
|
|
675
|
+
static fileName = "akan.budget.json";
|
|
676
|
+
static section = "routeJsBrotliKB";
|
|
677
|
+
static tableRows = 10;
|
|
678
|
+
static #relativeSlack = 0.01;
|
|
679
|
+
static #absoluteSlack = 4096;
|
|
680
|
+
static async measure(artifactDir, modulesByRoute) {
|
|
681
|
+
const sizeByUrl = new Map;
|
|
682
|
+
const sizeOf = async (url) => {
|
|
683
|
+
const file = path3.join(artifactDir, url.replace(/^\/_akan\//, ""));
|
|
684
|
+
const raw = Bun.file(file).size;
|
|
685
|
+
const sidecar = Bun.file(`${file}.br`);
|
|
686
|
+
return { raw, brotli: await sidecar.exists() ? sidecar.size : raw };
|
|
687
|
+
};
|
|
688
|
+
for (const url of new Set(Object.values(modulesByRoute).flat()))
|
|
689
|
+
sizeByUrl.set(url, await sizeOf(url));
|
|
690
|
+
return Object.entries(modulesByRoute).map(([routeId, urls]) => ({
|
|
691
|
+
routeId,
|
|
692
|
+
files: urls.length,
|
|
693
|
+
rawBytes: urls.reduce((total, url) => total + (sizeByUrl.get(url)?.raw ?? 0), 0),
|
|
694
|
+
brotliBytes: urls.reduce((total, url) => total + (sizeByUrl.get(url)?.brotli ?? 0), 0)
|
|
695
|
+
})).sort((a, b) => b.brotliBytes - a.brotliBytes || RouteJsBudget.#byCodeUnit(a.routeId, b.routeId));
|
|
696
|
+
}
|
|
697
|
+
static async load(filePath, source = filePath) {
|
|
698
|
+
const file = Bun.file(filePath);
|
|
699
|
+
if (!await file.exists())
|
|
700
|
+
return null;
|
|
701
|
+
return RouteJsBudget.parse(await file.text(), source);
|
|
702
|
+
}
|
|
703
|
+
static async check(sizes, { mode, budgetPath, source, environment }) {
|
|
704
|
+
const { committed, unreadable } = await RouteJsBudget.#loadFor(mode, budgetPath, source);
|
|
705
|
+
const budget = mode === "update" ? (committed ?? new RouteJsBudget).tightenedBy(sizes, environment) : committed;
|
|
706
|
+
if (mode === "update" && budget)
|
|
707
|
+
await Bun.write(budgetPath, budget.stringify());
|
|
708
|
+
const overages = budget?.overages(sizes) ?? [];
|
|
709
|
+
const envNote = committed?.envNote(environment) ?? "";
|
|
710
|
+
if (overages.length && mode !== "report")
|
|
711
|
+
throw new Error(RouteJsBudget.formatOverages(overages, source, envNote));
|
|
712
|
+
const unbudgeted = budget?.unbudgeted(sizes).length ?? 0;
|
|
713
|
+
if (mode === "update")
|
|
714
|
+
return { summary: `${source} ${unreadable ? `rewritten (${unreadable})` : "updated"}` };
|
|
715
|
+
if (unreadable)
|
|
716
|
+
return {
|
|
717
|
+
summary: `${unreadable}, not checked`,
|
|
718
|
+
warnings: [
|
|
719
|
+
{
|
|
720
|
+
file: source,
|
|
721
|
+
message: `${unreadable}; akan build fails on it`,
|
|
722
|
+
fix: "correct it, or rewrite it with akan build <app> --update-budget"
|
|
723
|
+
}
|
|
724
|
+
]
|
|
725
|
+
};
|
|
726
|
+
if (!budget)
|
|
727
|
+
return { summary: `no ${RouteJsBudget.fileName}` };
|
|
728
|
+
if (overages.length)
|
|
729
|
+
return {
|
|
730
|
+
summary: `${overages.length} route(s) over ${source}${envNote}, reported only: ${overages.map(({ routeId }) => routeId).join(", ")}`,
|
|
731
|
+
warnings: overages.map(({ routeId, brotliBytes, limitBytes }) => ({
|
|
732
|
+
file: source,
|
|
733
|
+
message: `${routeId} loads ${RouteJsBudget.#bytes(brotliBytes)} bytes brotli, over its limit of ${RouteJsBudget.#bytes(limitBytes)}${envNote}; akan build fails on it`,
|
|
734
|
+
fix: "shrink what the route loads, or raise its entry by hand in the same change"
|
|
735
|
+
}))
|
|
736
|
+
};
|
|
737
|
+
return { summary: `within ${source}${envNote}${unbudgeted ? `, ${unbudgeted} route(s) without an entry` : ""}` };
|
|
738
|
+
}
|
|
739
|
+
static async#loadFor(mode, budgetPath, source) {
|
|
740
|
+
try {
|
|
741
|
+
return { committed: await RouteJsBudget.load(budgetPath, source), unreadable: null };
|
|
742
|
+
} catch (error) {
|
|
743
|
+
if (mode === "enforce")
|
|
744
|
+
throw error;
|
|
745
|
+
return { committed: null, unreadable: toError(error).message.replace(/\.$/, "") };
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
static parse(text, source = RouteJsBudget.fileName) {
|
|
749
|
+
let json;
|
|
750
|
+
try {
|
|
751
|
+
json = JSON.parse(text);
|
|
752
|
+
} catch {
|
|
753
|
+
throw new Error(`${source} is not valid JSON.`);
|
|
754
|
+
}
|
|
755
|
+
const record = typeof json === "object" && json !== null && !Array.isArray(json) ? json : {};
|
|
756
|
+
const section = record[RouteJsBudget.section];
|
|
757
|
+
const entries = typeof section === "object" && section !== null && !Array.isArray(section) ? section : null;
|
|
758
|
+
if (!entries || !Object.values(entries).every((kb) => Number.isInteger(kb) && kb > 0))
|
|
759
|
+
throw new Error(`${source}: "${RouteJsBudget.section}" maps each route id to a whole number of KB.`);
|
|
760
|
+
if (record.env !== undefined && typeof record.env !== "string")
|
|
761
|
+
throw new Error(`${source}: "env" names the environment the entries were measured for.`);
|
|
762
|
+
return new RouteJsBudget(new Map(Object.entries(entries)), record.env);
|
|
763
|
+
}
|
|
764
|
+
static kbOf(bytes) {
|
|
765
|
+
return Math.ceil(bytes / 1024);
|
|
766
|
+
}
|
|
767
|
+
static limitOf(budgetKB) {
|
|
768
|
+
const bytes = budgetKB * 1024;
|
|
769
|
+
return bytes + Math.max(Math.ceil(bytes * RouteJsBudget.#relativeSlack), RouteJsBudget.#absoluteSlack);
|
|
770
|
+
}
|
|
771
|
+
static formatTable(sizes) {
|
|
772
|
+
const shown = sizes.slice(0, RouteJsBudget.tableRows);
|
|
773
|
+
const width = Math.max(...shown.map(({ routeId }) => routeId.length));
|
|
774
|
+
const { formatBytes } = FontPruner;
|
|
775
|
+
return [
|
|
776
|
+
"Route JS, largest first (brotli / raw):",
|
|
777
|
+
...shown.map(({ routeId, brotliBytes, rawBytes }) => ` ${routeId.padEnd(width)} ${formatBytes(brotliBytes).padStart(8)} ${formatBytes(rawBytes).padStart(8)}`),
|
|
778
|
+
...sizes.length > shown.length ? [` \u2026and ${sizes.length - shown.length} more`] : []
|
|
779
|
+
];
|
|
780
|
+
}
|
|
781
|
+
static formatOverages(overages, source, envNote = "") {
|
|
782
|
+
const bytes = RouteJsBudget.#bytes;
|
|
783
|
+
return [
|
|
784
|
+
`${overages.length} route${overages.length === 1 ? "" : "s"} over the JS budget in ${source}${envNote}:`,
|
|
785
|
+
...overages.map(({ routeId, brotliBytes, budgetKB, limitBytes }) => ` ${routeId}: ${bytes(brotliBytes)} bytes brotli, over its limit of ${bytes(limitBytes)} (${budgetKB}KB + the larger of 1% and 4KB)`),
|
|
786
|
+
"Shrink what the route loads. If the growth is intended, raise its entry by hand in the same change."
|
|
787
|
+
].join(`
|
|
788
|
+
`);
|
|
789
|
+
}
|
|
790
|
+
static #bytes(value) {
|
|
791
|
+
return value.toLocaleString("en-US");
|
|
792
|
+
}
|
|
793
|
+
static #byCodeUnit(a, b) {
|
|
794
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
795
|
+
}
|
|
796
|
+
constructor(kbByRoute = new Map, env) {
|
|
797
|
+
this.kbByRoute = kbByRoute;
|
|
798
|
+
this.env = env;
|
|
799
|
+
}
|
|
800
|
+
overages(sizes) {
|
|
801
|
+
return sizes.flatMap(({ routeId, brotliBytes }) => {
|
|
802
|
+
const budgetKB = this.kbByRoute.get(routeId);
|
|
803
|
+
if (budgetKB === undefined)
|
|
804
|
+
return [];
|
|
805
|
+
const limitBytes = RouteJsBudget.limitOf(budgetKB);
|
|
806
|
+
return brotliBytes > limitBytes ? [{ routeId, brotliBytes, budgetKB, limitBytes }] : [];
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
envNote(environment) {
|
|
810
|
+
return this.env && this.env !== environment ? ` (recorded for ${this.env}, built for ${environment})` : "";
|
|
811
|
+
}
|
|
812
|
+
unbudgeted(sizes) {
|
|
813
|
+
return sizes.filter(({ routeId }) => !this.kbByRoute.has(routeId)).map(({ routeId }) => routeId);
|
|
814
|
+
}
|
|
815
|
+
tightenedBy(sizes, env) {
|
|
816
|
+
return new RouteJsBudget(new Map(sizes.map(({ routeId, brotliBytes }) => {
|
|
817
|
+
const measured = RouteJsBudget.kbOf(brotliBytes);
|
|
818
|
+
return [routeId, Math.min(this.kbByRoute.get(routeId) ?? measured, measured)];
|
|
819
|
+
})), env ?? this.env);
|
|
820
|
+
}
|
|
821
|
+
stringify() {
|
|
822
|
+
const entries = [...this.kbByRoute].sort(([a], [b]) => RouteJsBudget.#byCodeUnit(a, b));
|
|
823
|
+
return JsonFormatter.stringify({ ...this.env ? { env: this.env } : {}, [RouteJsBudget.section]: Object.fromEntries(entries) }, RouteJsBudget.fileName);
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
// pkgs/@akanjs/devkit/applicationBuildReporter.ts
|
|
828
|
+
class ApplicationBuildReporter {
|
|
829
|
+
static create() {
|
|
830
|
+
return {
|
|
831
|
+
phaseDone: (phase) => Logger.rawLog(ApplicationBuildReporter.formatPhaseLine(phase))
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
static printSummary(result) {
|
|
835
|
+
Logger.rawLog("");
|
|
836
|
+
if (result.routeJs?.length) {
|
|
837
|
+
for (const line of RouteJsBudget.formatTable(result.routeJs))
|
|
838
|
+
Logger.rawLog(line);
|
|
839
|
+
Logger.rawLog("");
|
|
840
|
+
}
|
|
841
|
+
Logger.rawLog(`Route artifacts: ${result.artifactDir}`);
|
|
842
|
+
Logger.rawLog(`Server output: ${result.outputDir}`);
|
|
843
|
+
Logger.rawLog(`Done in ${ApplicationBuildReporter.formatDuration(result.durationMs)}`);
|
|
844
|
+
if (result.environment === "local")
|
|
845
|
+
Logger.rawLog(ApplicationBuildReporter.localBuildNotice);
|
|
846
|
+
}
|
|
847
|
+
static localBuildNotice = "Built for local: the server runs without endpoint rate limits, and boots on local defaults (Redis on localhost, the first database mode) where a deployment would stop to ask. For a host others can reach, run `akan build <app> --env main` with AKAN_PUBLIC_REPO_NAME and AKAN_PUBLIC_SERVE_DOMAIN set in the shell or the workspace .env.";
|
|
848
|
+
static formatError(error, workspaceRoot = process.cwd()) {
|
|
849
|
+
if (error instanceof AggregateError) {
|
|
850
|
+
const nestedMessages = error.errors.map((nestedError, index) => ApplicationBuildReporter.formatError(nestedError, workspaceRoot).trim() || `Unknown error ${index + 1}`).map((message) => message.replace(/^/gm, " ")).join(`
|
|
851
|
+
`);
|
|
852
|
+
return nestedMessages ? `${error.message}
|
|
853
|
+
${nestedMessages}` : error.message;
|
|
854
|
+
}
|
|
855
|
+
if (error instanceof Error) {
|
|
856
|
+
const causeMessage = error.cause ? `
|
|
857
|
+
Caused by: ${ApplicationBuildReporter.formatError(error.cause, workspaceRoot)}` : "";
|
|
858
|
+
return `${ApplicationBuildReporter.#withLocation(error.message, error, workspaceRoot)}${causeMessage}`;
|
|
859
|
+
}
|
|
860
|
+
if (typeof error === "object" && error !== null && "message" in error)
|
|
861
|
+
return ApplicationBuildReporter.#withLocation(String(error.message), error, workspaceRoot);
|
|
862
|
+
return String(error);
|
|
863
|
+
}
|
|
864
|
+
static #withLocation(message, error, workspaceRoot) {
|
|
865
|
+
const { position } = error;
|
|
866
|
+
if (!position?.file)
|
|
867
|
+
return message;
|
|
868
|
+
const file = ApplicationBuildReporter.#relativeToWorkspace(position.file, workspaceRoot);
|
|
869
|
+
const location = position.line > 0 ? `${file}:${position.line}:${position.column}` : file;
|
|
870
|
+
return message.includes(location) ? message : message.replace(/^.*/, (headline) => `${headline} (${location})`);
|
|
871
|
+
}
|
|
872
|
+
static #relativeToWorkspace(file, workspaceRoot) {
|
|
873
|
+
if (!path4.isAbsolute(file))
|
|
874
|
+
return file;
|
|
875
|
+
for (const root of [workspaceRoot, ApplicationBuildReporter.#realpathOf(workspaceRoot)]) {
|
|
876
|
+
const relative = path4.relative(root, file);
|
|
877
|
+
if (!relative.startsWith(`..${path4.sep}`) && !path4.isAbsolute(relative))
|
|
878
|
+
return relative.replaceAll(path4.sep, "/");
|
|
879
|
+
}
|
|
880
|
+
return file;
|
|
881
|
+
}
|
|
882
|
+
static #realpathOf(dir) {
|
|
883
|
+
try {
|
|
884
|
+
return realpathSync(dir);
|
|
885
|
+
} catch {
|
|
886
|
+
return dir;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
static formatDuration(ms) {
|
|
890
|
+
if (ms < 1000)
|
|
891
|
+
return `${ms}ms`;
|
|
892
|
+
if (ms < 60000)
|
|
893
|
+
return `${Math.round(ms / 100) / 10}s`;
|
|
894
|
+
const seconds = Math.floor(ms / 1000);
|
|
895
|
+
return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
|
|
896
|
+
}
|
|
897
|
+
static formatPhaseLine(phase) {
|
|
898
|
+
const summary = phase.summary ? `: ${phase.summary}` : "";
|
|
899
|
+
return `\u2713 ${phase.label}${summary} (${ApplicationBuildReporter.formatDuration(phase.durationMs)})`;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
// pkgs/@akanjs/devkit/akanApp/devHostPolicy.ts
|
|
904
|
+
import path5 from "path";
|
|
905
|
+
var UNAVAILABLE_REDIS_HOST = "redis-tunnel-unavailable.invalid";
|
|
906
|
+
var redisTunnelPolicy = ({
|
|
907
|
+
environment,
|
|
908
|
+
databaseMode
|
|
909
|
+
}) => environment === "local" ? "none" : databaseMode === "single" ? "optional" : "required";
|
|
910
|
+
var BACKEND_RECOVERY_MAX_ATTEMPTS = 5;
|
|
911
|
+
var HELD_BUILDER_REQUEST_LIMIT = 64;
|
|
912
|
+
var BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS = 30000;
|
|
913
|
+
var BUILDER_TIGHT_RSS_REPORT_LIMIT = 2;
|
|
914
|
+
var BUILDER_RSS_HARD_MULTIPLE = 1.5;
|
|
915
|
+
var DEV_IDLE_SUSPEND_MS = 300000;
|
|
916
|
+
var DEV_IDLE_MIN_UPTIME_MS = 30000;
|
|
917
|
+
var SOURCE_EXTS = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]);
|
|
918
|
+
var SERVER_SUFFIXES = [".service.ts", ".document.ts"];
|
|
919
|
+
var SHARED_SUFFIXES = [".constant.ts", ".dictionary.ts", ".signal.ts"];
|
|
920
|
+
var RUNTIME_METADATA_BASENAMES = new Set(["dict.ts", "sig.ts", "useClient.ts", "useServer.ts"]);
|
|
921
|
+
var shouldRestartBackendByDevPlan = (message) => {
|
|
922
|
+
if (!message.devPlan)
|
|
923
|
+
return null;
|
|
924
|
+
if (message.devPlan.actions.includes("report-error"))
|
|
925
|
+
return false;
|
|
926
|
+
if (message.devPlan.actions.includes("restart-builder"))
|
|
927
|
+
return false;
|
|
928
|
+
return message.devPlan.actions.includes("restart-backend");
|
|
929
|
+
};
|
|
930
|
+
var shouldRestartBuilderByDevPlan = (message) => message.devPlan?.actions.includes("restart-builder") ?? false;
|
|
931
|
+
var shouldAbandonBackendRecovery = (attempts, maxAttempts = BACKEND_RECOVERY_MAX_ATTEMPTS) => attempts >= maxAttempts;
|
|
932
|
+
var normalizeBackendReportedGeneration = (generation) => generation >= 0 ? generation : undefined;
|
|
933
|
+
var shouldRestartDevHostByDevPlan = (message) => message.devPlan?.actions.includes("restart-dev-host") ?? message.kinds.includes("config");
|
|
934
|
+
var devHostStateByBackendState = {
|
|
935
|
+
starting: "starting",
|
|
936
|
+
ready: "ready",
|
|
937
|
+
"restart-pending": "restarting",
|
|
938
|
+
recovering: "recovering",
|
|
939
|
+
stopping: "stopped",
|
|
940
|
+
stopped: "stopped"
|
|
941
|
+
};
|
|
942
|
+
var devHostStateOf = (state, gaveUp) => state === "stopped" && gaveUp ? "failed" : devHostStateByBackendState[state];
|
|
943
|
+
var RESTART_ROLE_ORDER = ["server", "shared", "barrel", "config"];
|
|
944
|
+
var generationValue = (generation) => generation ?? -1;
|
|
945
|
+
var isLegacyBackendFallbackFile = (file, workspaceRoot) => {
|
|
946
|
+
const abs = path5.resolve(file);
|
|
947
|
+
const ext = path5.extname(abs).toLowerCase();
|
|
948
|
+
if (!SOURCE_EXTS.has(ext))
|
|
949
|
+
return false;
|
|
950
|
+
const rel = path5.relative(path5.resolve(workspaceRoot), abs);
|
|
951
|
+
if (!rel || rel.startsWith("..") || path5.isAbsolute(rel))
|
|
952
|
+
return false;
|
|
953
|
+
const parts = rel.split(path5.sep).filter(Boolean);
|
|
954
|
+
const [scope] = parts;
|
|
955
|
+
if (scope !== "apps" && scope !== "libs" && scope !== "pkgs")
|
|
956
|
+
return false;
|
|
957
|
+
const base = path5.basename(abs);
|
|
958
|
+
return parts.includes("srvkit") || parts.includes("common") || SERVER_SUFFIXES.some((suffix) => base.endsWith(suffix)) || SHARED_SUFFIXES.some((suffix) => base.endsWith(suffix)) || RUNTIME_METADATA_BASENAMES.has(base) || base === "main.ts" || base === "server.ts";
|
|
959
|
+
};
|
|
960
|
+
var shouldMarkBuildPhaseRecovered = (previousByPhase, status) => {
|
|
961
|
+
const previous = previousByPhase.get(status.phase);
|
|
962
|
+
if (!previous || previous.ok || !status.ok)
|
|
963
|
+
return false;
|
|
964
|
+
const generation = generationValue(status.generation);
|
|
965
|
+
if (status.phase === "route" && status.scope !== undefined && previous.scope !== undefined)
|
|
966
|
+
return status.scope === previous.scope && generation >= previous.generation;
|
|
967
|
+
if (generation !== previous.generation)
|
|
968
|
+
return generation > previous.generation;
|
|
969
|
+
return status.phase === "backend";
|
|
970
|
+
};
|
|
971
|
+
var shouldKeepBuildFailure = (previousByPhase, status) => status.ok && previousByPhase.get(status.phase)?.ok === false && !shouldMarkBuildPhaseRecovered(previousByPhase, status);
|
|
972
|
+
var createBackendBuildStatus = ({
|
|
973
|
+
generation,
|
|
974
|
+
ok,
|
|
975
|
+
files = [],
|
|
976
|
+
message
|
|
977
|
+
}) => ({
|
|
978
|
+
generation,
|
|
979
|
+
phase: "backend",
|
|
980
|
+
ok,
|
|
981
|
+
files,
|
|
982
|
+
message
|
|
983
|
+
});
|
|
984
|
+
var backendRestartReasonFromMessage = (message) => {
|
|
985
|
+
const roleSet = new Set;
|
|
986
|
+
for (const role of message.devPlan?.roles ?? []) {
|
|
987
|
+
if (role === "server" || role === "shared" || role === "barrel" || role === "config")
|
|
988
|
+
roleSet.add(role);
|
|
989
|
+
}
|
|
990
|
+
return {
|
|
991
|
+
generation: message.devPlan?.generation ?? message.generation,
|
|
992
|
+
files: [...new Set(message.files)].sort(),
|
|
993
|
+
roles: RESTART_ROLE_ORDER.filter((role) => roleSet.has(role))
|
|
994
|
+
};
|
|
995
|
+
};
|
|
996
|
+
var mergeBackendRestartReasons = (current, next) => ({
|
|
997
|
+
generation: generationValue(next.generation) >= generationValue(current?.generation) ? next.generation : current?.generation,
|
|
998
|
+
files: [...new Set([...current?.files ?? [], ...next.files])].sort(),
|
|
999
|
+
roles: RESTART_ROLE_ORDER.filter((role) => current?.roles.includes(role) || next.roles.includes(role))
|
|
1000
|
+
});
|
|
1001
|
+
var shouldReplaceLastGoodMessage = (current, next) => !current || generationValue(next.data.generation) >= generationValue(current.data.generation);
|
|
1002
|
+
var shouldQueueBuildStatusReplay = (backendReady, pendingReplayCount) => !backendReady || pendingReplayCount > 0;
|
|
1003
|
+
var hasBuildFailureForGeneration = (statusByPhase, generation) => {
|
|
1004
|
+
if (typeof generation !== "number")
|
|
1005
|
+
return false;
|
|
1006
|
+
for (const status of statusByPhase.values()) {
|
|
1007
|
+
if (!status.ok && status.phase !== "route" && status.generation === generation)
|
|
1008
|
+
return true;
|
|
1009
|
+
}
|
|
1010
|
+
return false;
|
|
1011
|
+
};
|
|
1012
|
+
var decideBuilderRssRecycle = ({
|
|
1013
|
+
rssBytes,
|
|
1014
|
+
ceilingBytes,
|
|
1015
|
+
buildFailed,
|
|
1016
|
+
msSinceLastRecycle,
|
|
1017
|
+
minIntervalMs = BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS
|
|
1018
|
+
}) => {
|
|
1019
|
+
if (!ceilingBytes)
|
|
1020
|
+
return "unbounded";
|
|
1021
|
+
if (rssBytes < ceilingBytes)
|
|
1022
|
+
return "below-ceiling";
|
|
1023
|
+
if (buildFailed)
|
|
1024
|
+
return "build-failed";
|
|
1025
|
+
if (msSinceLastRecycle !== null && msSinceLastRecycle < minIntervalMs)
|
|
1026
|
+
return "too-soon";
|
|
1027
|
+
return "recycle";
|
|
1028
|
+
};
|
|
1029
|
+
var decideBuilderRssSettle = ({
|
|
1030
|
+
rssBytes,
|
|
1031
|
+
ceilingBytes,
|
|
1032
|
+
hardMultiple = BUILDER_RSS_HARD_MULTIPLE
|
|
1033
|
+
}) => rssBytes >= ceilingBytes * hardMultiple ? "recycle-now" : "wait-and-recheck";
|
|
1034
|
+
var decideIdleSuspend = ({
|
|
1035
|
+
enabled,
|
|
1036
|
+
suspended,
|
|
1037
|
+
builderReady,
|
|
1038
|
+
backendReady,
|
|
1039
|
+
buildFailed,
|
|
1040
|
+
restartPending,
|
|
1041
|
+
msSinceWake,
|
|
1042
|
+
minUptimeMs = DEV_IDLE_MIN_UPTIME_MS
|
|
1043
|
+
}) => {
|
|
1044
|
+
if (!enabled)
|
|
1045
|
+
return "disabled";
|
|
1046
|
+
if (suspended)
|
|
1047
|
+
return "already-suspended";
|
|
1048
|
+
if (!builderReady)
|
|
1049
|
+
return "builder-not-ready";
|
|
1050
|
+
if (!backendReady)
|
|
1051
|
+
return "backend-not-ready";
|
|
1052
|
+
if (buildFailed)
|
|
1053
|
+
return "build-failed";
|
|
1054
|
+
if (restartPending)
|
|
1055
|
+
return "restart-pending";
|
|
1056
|
+
if (msSinceWake !== null && msSinceWake < minUptimeMs)
|
|
1057
|
+
return "too-soon";
|
|
1058
|
+
return "suspend";
|
|
1059
|
+
};
|
|
1060
|
+
var resolveIdleSuspendMs = (raw) => {
|
|
1061
|
+
if (raw === undefined || raw === "")
|
|
1062
|
+
return DEV_IDLE_SUSPEND_MS;
|
|
1063
|
+
const parsed = Number(raw);
|
|
1064
|
+
if (!Number.isFinite(parsed) || parsed <= 0)
|
|
1065
|
+
return null;
|
|
1066
|
+
return Math.round(parsed);
|
|
1067
|
+
};
|
|
1068
|
+
var hasAnyBuildFailure = (statusByPhase) => [...statusByPhase.values()].some((status) => !status.ok && status.phase !== "route");
|
|
1069
|
+
var shouldRefreshConfigOnIdleWake = (batch) => !!batch && batch.kinds.has("config");
|
|
1070
|
+
var RETURNING_BUILDER_STATUSES = new Set(["starting", "recycling", "restarting"]);
|
|
1071
|
+
var shouldHoldForReturningBuilder = ({
|
|
1072
|
+
status,
|
|
1073
|
+
heldCount,
|
|
1074
|
+
limit = HELD_BUILDER_REQUEST_LIMIT
|
|
1075
|
+
}) => RETURNING_BUILDER_STATUSES.has(status) && heldCount < limit;
|
|
1076
|
+
var shouldWarnBuilderRssCeilingTight = (reportsSinceRecycle, limit = BUILDER_TIGHT_RSS_REPORT_LIMIT) => reportsSinceRecycle >= limit;
|
|
1077
|
+
var isRssCeilingUnreachable = (freshRssBytes, ceilingBytes) => freshRssBytes !== null && ceilingBytes !== null && freshRssBytes >= ceilingBytes;
|
|
1078
|
+
var shouldRelayRecycledFrontendState = (current, next) => {
|
|
1079
|
+
if (!current || current.type !== next.type)
|
|
1080
|
+
return true;
|
|
1081
|
+
if (current.type === "pages-updated" && next.type === "pages-updated")
|
|
1082
|
+
return current.data.bundlePath !== next.data.bundlePath;
|
|
1083
|
+
if (current.type === "css-updated" && next.type === "css-updated")
|
|
1084
|
+
return JSON.stringify(current.data.cssAssets) !== JSON.stringify(next.data.cssAssets);
|
|
1085
|
+
return true;
|
|
1086
|
+
};
|
|
1087
|
+
var mergeDevPlans = (current, next) => {
|
|
1088
|
+
if (!current)
|
|
1089
|
+
return next;
|
|
1090
|
+
if (!next)
|
|
1091
|
+
return current;
|
|
1092
|
+
const reasonByFile = { ...current.reasonByFile };
|
|
1093
|
+
for (const [file, reasons] of Object.entries(next.reasonByFile)) {
|
|
1094
|
+
reasonByFile[file] = [...new Set([...reasonByFile[file] ?? [], ...reasons])].sort();
|
|
1095
|
+
}
|
|
1096
|
+
return {
|
|
1097
|
+
generation: Math.max(current.generation, next.generation),
|
|
1098
|
+
files: [...new Set([...current.files, ...next.files])].sort(),
|
|
1099
|
+
generatedFiles: [...new Set([...current.generatedFiles, ...next.generatedFiles])].sort(),
|
|
1100
|
+
roles: [...new Set([...current.roles, ...next.roles])].sort(),
|
|
1101
|
+
actions: [...new Set([...current.actions, ...next.actions])].sort(),
|
|
1102
|
+
reasonByFile
|
|
1103
|
+
};
|
|
1104
|
+
};
|
|
1105
|
+
var mergeInvalidateMessages = (current, next) => {
|
|
1106
|
+
const generation = Math.max(generationValue(current.generation), generationValue(next.generation));
|
|
1107
|
+
return {
|
|
1108
|
+
type: "invalidate",
|
|
1109
|
+
kinds: [...new Set([...current.kinds, ...next.kinds])].sort(),
|
|
1110
|
+
files: [...new Set([...current.files, ...next.files])].sort(),
|
|
1111
|
+
generation: generation >= 0 ? generation : undefined,
|
|
1112
|
+
devPlan: mergeDevPlans(current.devPlan, next.devPlan)
|
|
1113
|
+
};
|
|
1114
|
+
};
|
|
1115
|
+
var buildStatusReplaySequence = (pendingReplay, latestByPhase) => [...pendingReplay, ...latestByPhase.values()];
|
|
1116
|
+
var filesChangedSince = (before, after) => [...before].filter(([file, stamp]) => after.get(file) !== stamp).map(([file]) => file);
|
|
1117
|
+
|
|
1118
|
+
// pkgs/@akanjs/devkit/frontendBuild/watchRootResolver.ts
|
|
1119
|
+
import fs from "fs";
|
|
1120
|
+
import { readFile } from "fs/promises";
|
|
1121
|
+
import path6 from "path";
|
|
1122
|
+
|
|
1123
|
+
class WatchRootResolver {
|
|
1124
|
+
#app;
|
|
1125
|
+
constructor(app) {
|
|
1126
|
+
this.#app = app;
|
|
1127
|
+
}
|
|
1128
|
+
async resolve() {
|
|
1129
|
+
const tsconfig = await this.#app.getTsConfig();
|
|
1130
|
+
const appDir = path6.resolve(this.#app.cwdPath);
|
|
1131
|
+
const appsContainer = path6.dirname(appDir);
|
|
1132
|
+
const libsContainer = path6.resolve(this.#app.workspace.workspaceRoot, "libs");
|
|
1133
|
+
const libRoots = (await this.#resolveLibDeps(libsContainer))?.map((name) => path6.join(libsContainer, name)).filter((dir) => fs.existsSync(dir));
|
|
1134
|
+
const set = new Set;
|
|
1135
|
+
set.add(path6.resolve(`${this.#app.cwdPath}/page`));
|
|
1136
|
+
for (const targets of Object.values(tsconfig.compilerOptions.paths ?? {})) {
|
|
1137
|
+
for (const target of targets) {
|
|
1138
|
+
if (!target)
|
|
1139
|
+
continue;
|
|
1140
|
+
if (path6.isAbsolute(target))
|
|
1141
|
+
continue;
|
|
1142
|
+
const cleaned = target.replace(/\/?\*+.*$/, "").replace(/\/[^/]+\.[^/]+$/, "");
|
|
1143
|
+
const resolved = path6.resolve(this.#app.workspace.workspaceRoot, cleaned);
|
|
1144
|
+
if (resolved === libsContainer && libRoots) {
|
|
1145
|
+
for (const root of libRoots)
|
|
1146
|
+
set.add(root);
|
|
1147
|
+
continue;
|
|
1148
|
+
}
|
|
1149
|
+
const root = resolved === appsContainer ? appDir : resolved;
|
|
1150
|
+
if (fs.existsSync(root))
|
|
1151
|
+
set.add(root);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
return [...set];
|
|
1155
|
+
}
|
|
1156
|
+
async#resolveLibDeps(libsContainer) {
|
|
1157
|
+
const scanInfo = this.#app.getScanInfo({ allowEmpty: true });
|
|
1158
|
+
if (scanInfo?.type === "app")
|
|
1159
|
+
return scanInfo.libDeps;
|
|
1160
|
+
const direct = await WatchRootResolver.#readManifestLibDeps(path6.join(this.#app.cwdPath, "akan.app.json"));
|
|
1161
|
+
if (!direct)
|
|
1162
|
+
return null;
|
|
1163
|
+
const closure = new Set;
|
|
1164
|
+
const queue = [...direct];
|
|
1165
|
+
while (queue.length > 0) {
|
|
1166
|
+
const name = queue.shift();
|
|
1167
|
+
if (!name || closure.has(name))
|
|
1168
|
+
continue;
|
|
1169
|
+
closure.add(name);
|
|
1170
|
+
const nested = await WatchRootResolver.#readManifestLibDeps(path6.join(libsContainer, name, "akan.lib.json"));
|
|
1171
|
+
if (!nested)
|
|
1172
|
+
return null;
|
|
1173
|
+
queue.push(...nested);
|
|
1174
|
+
}
|
|
1175
|
+
return [...closure];
|
|
1176
|
+
}
|
|
1177
|
+
static async#readManifestLibDeps(manifestPath) {
|
|
1178
|
+
try {
|
|
1179
|
+
const parsed = JSON.parse(await readFile(manifestPath, "utf8"));
|
|
1180
|
+
if (!Array.isArray(parsed.libDeps))
|
|
1181
|
+
return null;
|
|
1182
|
+
return parsed.libDeps.filter((name) => typeof name === "string" && name.length > 0);
|
|
1183
|
+
} catch {
|
|
1184
|
+
return null;
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// pkgs/@akanjs/devkit/frontendBuild/hmrWatcher.ts
|
|
1190
|
+
import fs2 from "fs";
|
|
1191
|
+
import path9 from "path";
|
|
1192
|
+
|
|
1193
|
+
// pkgs/@akanjs/devkit/frontendBuild/hmrChangeClassifier.ts
|
|
1194
|
+
import path7 from "path";
|
|
1195
|
+
var CSS_EXTS = new Set([".css"]);
|
|
1196
|
+
var CONFIG_BASENAMES = new Set(["akan.config.ts", "bunfig.toml", "tsconfig.json", "package.json"]);
|
|
1197
|
+
|
|
1198
|
+
class HmrChangeClassifier {
|
|
1199
|
+
classify(abs) {
|
|
1200
|
+
if (this.#isUninteresting(abs))
|
|
1201
|
+
return "ignore";
|
|
1202
|
+
const base = path7.basename(abs);
|
|
1203
|
+
if (CONFIG_BASENAMES.has(base))
|
|
1204
|
+
return "config";
|
|
1205
|
+
const ext = path7.extname(abs).toLowerCase();
|
|
1206
|
+
if (CSS_EXTS.has(ext))
|
|
1207
|
+
return "css";
|
|
1208
|
+
if (SOURCE_EXTS.has(ext))
|
|
1209
|
+
return "code";
|
|
1210
|
+
return "ignore";
|
|
1211
|
+
}
|
|
1212
|
+
#isUninteresting(abs) {
|
|
1213
|
+
const base = path7.basename(abs);
|
|
1214
|
+
if (!base)
|
|
1215
|
+
return true;
|
|
1216
|
+
if (base.startsWith("."))
|
|
1217
|
+
return true;
|
|
1218
|
+
if (base.endsWith("~") || base.endsWith(".swp") || base.endsWith(".swx") || base.endsWith(".tmp"))
|
|
1219
|
+
return true;
|
|
1220
|
+
if (abs.includes(`${path7.sep}node_modules${path7.sep}`))
|
|
1221
|
+
return true;
|
|
1222
|
+
if (abs.includes(`${path7.sep}.akan${path7.sep}`))
|
|
1223
|
+
return true;
|
|
1224
|
+
return false;
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
// pkgs/@akanjs/devkit/frontendBuild/sourceMtimeIndex.ts
|
|
1229
|
+
import { readdir, stat as stat3 } from "fs/promises";
|
|
1230
|
+
import path8 from "path";
|
|
1231
|
+
var UNREADABLE = Number.NaN;
|
|
1232
|
+
|
|
1233
|
+
class SourceMtimeIndex {
|
|
1234
|
+
static #defaultDirSettleMs = 20;
|
|
1235
|
+
#dirSettleMs;
|
|
1236
|
+
#roots;
|
|
1237
|
+
#classifier;
|
|
1238
|
+
#files = new Map;
|
|
1239
|
+
#dirs = new Map;
|
|
1240
|
+
#unreadable = new Map;
|
|
1241
|
+
#unsettled = new Set;
|
|
1242
|
+
#primed = false;
|
|
1243
|
+
#queue = Promise.resolve();
|
|
1244
|
+
constructor({ roots, classifier, dirSettleMs }) {
|
|
1245
|
+
this.#roots = SourceMtimeIndex.#pruneNestedRoots(roots);
|
|
1246
|
+
this.#classifier = classifier ?? new HmrChangeClassifier;
|
|
1247
|
+
this.#dirSettleMs = dirSettleMs ?? SourceMtimeIndex.#defaultDirSettleMs;
|
|
1248
|
+
}
|
|
1249
|
+
get primed() {
|
|
1250
|
+
return this.#primed;
|
|
1251
|
+
}
|
|
1252
|
+
get trackedFileCount() {
|
|
1253
|
+
return this.#files.size;
|
|
1254
|
+
}
|
|
1255
|
+
get coverageGaps() {
|
|
1256
|
+
return [...this.#unreadable].map(([file, code]) => ({ path: file, code }));
|
|
1257
|
+
}
|
|
1258
|
+
get hasUnsettledDirs() {
|
|
1259
|
+
return this.#unsettled.size > 0;
|
|
1260
|
+
}
|
|
1261
|
+
async prime() {
|
|
1262
|
+
await this.#serialize(async () => {
|
|
1263
|
+
this.#files.clear();
|
|
1264
|
+
this.#dirs.clear();
|
|
1265
|
+
this.#unreadable.clear();
|
|
1266
|
+
this.#unsettled.clear();
|
|
1267
|
+
await Promise.all(this.#roots.map((root) => this.#walk(root, null)));
|
|
1268
|
+
this.#primed = true;
|
|
1269
|
+
});
|
|
1270
|
+
}
|
|
1271
|
+
async collectChanges() {
|
|
1272
|
+
return this.#serialize(async () => {
|
|
1273
|
+
if (!this.#primed)
|
|
1274
|
+
return [];
|
|
1275
|
+
const changed = new Set;
|
|
1276
|
+
await this.#collectFileChanges(changed);
|
|
1277
|
+
await this.#collectDirChanges(changed);
|
|
1278
|
+
return [...changed];
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1281
|
+
async#serialize(work) {
|
|
1282
|
+
const run = this.#queue.then(work, work);
|
|
1283
|
+
this.#queue = run.catch(() => {
|
|
1284
|
+
return;
|
|
1285
|
+
});
|
|
1286
|
+
return run;
|
|
1287
|
+
}
|
|
1288
|
+
async absorb(paths) {
|
|
1289
|
+
await this.#serialize(async () => {
|
|
1290
|
+
if (!this.#primed)
|
|
1291
|
+
return;
|
|
1292
|
+
await Promise.all(paths.map(async (file) => {
|
|
1293
|
+
const abs = path8.resolve(file);
|
|
1294
|
+
const stats = await stat3(abs).catch(() => null);
|
|
1295
|
+
if (!stats?.isFile()) {
|
|
1296
|
+
this.#files.delete(abs);
|
|
1297
|
+
return;
|
|
1298
|
+
}
|
|
1299
|
+
this.#files.set(abs, { mtimeMs: stats.mtimeMs, size: stats.size });
|
|
1300
|
+
}));
|
|
1301
|
+
});
|
|
1302
|
+
}
|
|
1303
|
+
async#collectFileChanges(changed) {
|
|
1304
|
+
await Promise.all([...this.#files.keys()].map(async (abs) => {
|
|
1305
|
+
const { stats, err } = await SourceMtimeIndex.#statPath(abs);
|
|
1306
|
+
if (!stats) {
|
|
1307
|
+
if (err && !SourceMtimeIndex.#isMissing(err)) {
|
|
1308
|
+
this.#unreadable.set(abs, err.code ?? "EUNKNOWN");
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1311
|
+
this.#files.delete(abs);
|
|
1312
|
+
this.#unreadable.delete(abs);
|
|
1313
|
+
changed.add(abs);
|
|
1314
|
+
return;
|
|
1315
|
+
}
|
|
1316
|
+
this.#unreadable.delete(abs);
|
|
1317
|
+
if (!stats.isFile()) {
|
|
1318
|
+
this.#files.delete(abs);
|
|
1319
|
+
changed.add(abs);
|
|
1320
|
+
return;
|
|
1321
|
+
}
|
|
1322
|
+
const known = this.#files.get(abs);
|
|
1323
|
+
if (known && known.mtimeMs === stats.mtimeMs && known.size === stats.size)
|
|
1324
|
+
return;
|
|
1325
|
+
this.#files.set(abs, { mtimeMs: stats.mtimeMs, size: stats.size });
|
|
1326
|
+
changed.add(abs);
|
|
1327
|
+
}));
|
|
1328
|
+
}
|
|
1329
|
+
async#collectDirChanges(changed) {
|
|
1330
|
+
const moved = new Set;
|
|
1331
|
+
const gone = [];
|
|
1332
|
+
await Promise.all([...this.#dirs.entries()].map(async ([dir, mtimeMs]) => {
|
|
1333
|
+
const { stats, err } = await SourceMtimeIndex.#statPath(dir);
|
|
1334
|
+
if (!stats?.isDirectory()) {
|
|
1335
|
+
if (err && !SourceMtimeIndex.#isMissing(err)) {
|
|
1336
|
+
this.#markUnreadable(dir, err);
|
|
1337
|
+
return;
|
|
1338
|
+
}
|
|
1339
|
+
gone.push(dir);
|
|
1340
|
+
return;
|
|
1341
|
+
}
|
|
1342
|
+
if (stats.mtimeMs !== mtimeMs)
|
|
1343
|
+
moved.add(dir);
|
|
1344
|
+
}));
|
|
1345
|
+
for (const dir of this.#unsettled)
|
|
1346
|
+
if (this.#dirs.has(dir))
|
|
1347
|
+
moved.add(dir);
|
|
1348
|
+
for (const dir of gone)
|
|
1349
|
+
this.#forget(dir);
|
|
1350
|
+
for (const dir of moved)
|
|
1351
|
+
await this.#walk(dir, changed);
|
|
1352
|
+
}
|
|
1353
|
+
async#walk(dir, changed) {
|
|
1354
|
+
const [listing, dirStat] = await Promise.all([SourceMtimeIndex.#readdirPath(dir), SourceMtimeIndex.#statPath(dir)]);
|
|
1355
|
+
const entries = listing.entries;
|
|
1356
|
+
const dirStats = dirStat.stats;
|
|
1357
|
+
if (!entries || !dirStats?.isDirectory()) {
|
|
1358
|
+
const err = listing.err ?? dirStat.err;
|
|
1359
|
+
if (err && !SourceMtimeIndex.#isMissing(err)) {
|
|
1360
|
+
this.#markUnreadable(dir, err);
|
|
1361
|
+
return;
|
|
1362
|
+
}
|
|
1363
|
+
this.#forget(dir);
|
|
1364
|
+
return;
|
|
1365
|
+
}
|
|
1366
|
+
const known = this.#dirs.has(dir);
|
|
1367
|
+
this.#dirs.set(dir, dirStats.mtimeMs);
|
|
1368
|
+
this.#unreadable.delete(dir);
|
|
1369
|
+
if (this.#isUnsettled(dirStats.mtimeMs))
|
|
1370
|
+
this.#unsettled.add(dir);
|
|
1371
|
+
else
|
|
1372
|
+
this.#unsettled.delete(dir);
|
|
1373
|
+
const descend = [];
|
|
1374
|
+
const present = new Set;
|
|
1375
|
+
let blind = false;
|
|
1376
|
+
for (const entry of entries) {
|
|
1377
|
+
if (SourceMtimeIndex.#skipDirent(entry.name))
|
|
1378
|
+
continue;
|
|
1379
|
+
const abs = path8.join(dir, entry.name);
|
|
1380
|
+
if (entry.isDirectory()) {
|
|
1381
|
+
descend.push(abs);
|
|
1382
|
+
continue;
|
|
1383
|
+
}
|
|
1384
|
+
if (!entry.isFile())
|
|
1385
|
+
continue;
|
|
1386
|
+
if (this.#classifier.classify(abs) === "ignore")
|
|
1387
|
+
continue;
|
|
1388
|
+
present.add(abs);
|
|
1389
|
+
const { stats, err } = await SourceMtimeIndex.#statPath(abs);
|
|
1390
|
+
if (!stats?.isFile()) {
|
|
1391
|
+
if (err && !SourceMtimeIndex.#isMissing(err)) {
|
|
1392
|
+
this.#unreadable.set(abs, err.code ?? "EUNKNOWN");
|
|
1393
|
+
blind = true;
|
|
1394
|
+
}
|
|
1395
|
+
continue;
|
|
1396
|
+
}
|
|
1397
|
+
this.#unreadable.delete(abs);
|
|
1398
|
+
const previous = this.#files.get(abs);
|
|
1399
|
+
if (previous && previous.mtimeMs === stats.mtimeMs && previous.size === stats.size)
|
|
1400
|
+
continue;
|
|
1401
|
+
this.#files.set(abs, { mtimeMs: stats.mtimeMs, size: stats.size });
|
|
1402
|
+
changed?.add(abs);
|
|
1403
|
+
}
|
|
1404
|
+
if (known) {
|
|
1405
|
+
for (const abs of [...this.#files.keys()]) {
|
|
1406
|
+
if (present.has(abs) || path8.dirname(abs) !== dir)
|
|
1407
|
+
continue;
|
|
1408
|
+
this.#files.delete(abs);
|
|
1409
|
+
changed?.add(abs);
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
if (blind) {
|
|
1413
|
+
this.#dirs.set(dir, UNREADABLE);
|
|
1414
|
+
this.#unsettled.delete(dir);
|
|
1415
|
+
}
|
|
1416
|
+
await Promise.all(descend.filter((sub) => !this.#dirs.has(sub)).map((sub) => this.#walk(sub, changed)));
|
|
1417
|
+
}
|
|
1418
|
+
#markUnreadable(dir, err) {
|
|
1419
|
+
this.#dirs.set(dir, UNREADABLE);
|
|
1420
|
+
this.#unreadable.set(dir, err.code ?? "EUNKNOWN");
|
|
1421
|
+
this.#unsettled.delete(dir);
|
|
1422
|
+
}
|
|
1423
|
+
#forget(dir) {
|
|
1424
|
+
const prefix = `${dir}${path8.sep}`;
|
|
1425
|
+
this.#dirs.delete(dir);
|
|
1426
|
+
this.#unreadable.delete(dir);
|
|
1427
|
+
this.#unsettled.delete(dir);
|
|
1428
|
+
for (const known of [...this.#dirs.keys()])
|
|
1429
|
+
if (known.startsWith(prefix))
|
|
1430
|
+
this.#dirs.delete(known);
|
|
1431
|
+
for (const known of [...this.#unreadable.keys()])
|
|
1432
|
+
if (known.startsWith(prefix))
|
|
1433
|
+
this.#unreadable.delete(known);
|
|
1434
|
+
for (const known of [...this.#unsettled])
|
|
1435
|
+
if (known.startsWith(prefix))
|
|
1436
|
+
this.#unsettled.delete(known);
|
|
1437
|
+
}
|
|
1438
|
+
#isUnsettled(mtimeMs) {
|
|
1439
|
+
return Math.abs(Date.now() - mtimeMs) < this.#dirSettleMs;
|
|
1440
|
+
}
|
|
1441
|
+
static async#statPath(abs) {
|
|
1442
|
+
try {
|
|
1443
|
+
return { stats: await stat3(abs), err: null };
|
|
1444
|
+
} catch (err) {
|
|
1445
|
+
return { stats: null, err };
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
static async#readdirPath(dir) {
|
|
1449
|
+
try {
|
|
1450
|
+
return { entries: await readdir(dir, { withFileTypes: true }), err: null };
|
|
1451
|
+
} catch (err) {
|
|
1452
|
+
return { entries: null, err };
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
static #isMissing(err) {
|
|
1456
|
+
return err.code === "ENOENT" || err.code === "ENOTDIR";
|
|
1457
|
+
}
|
|
1458
|
+
static #skipDirent(name) {
|
|
1459
|
+
return !name || name.startsWith(".") || name === "node_modules";
|
|
1460
|
+
}
|
|
1461
|
+
static #pruneNestedRoots(roots) {
|
|
1462
|
+
const resolved = [...new Set(roots.map((root) => path8.resolve(root)))].sort();
|
|
1463
|
+
return resolved.filter((root) => !resolved.some((other) => other !== root && root.startsWith(`${other}${path8.sep}`)));
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
// pkgs/@akanjs/devkit/frontendBuild/hmrWatcher.ts
|
|
1468
|
+
class HmrWatcher {
|
|
1469
|
+
#roots;
|
|
1470
|
+
#debounceMs;
|
|
1471
|
+
#verifyDelayMs;
|
|
1472
|
+
#onBatch;
|
|
1473
|
+
#logger;
|
|
1474
|
+
#watchers = [];
|
|
1475
|
+
#pending = new Map;
|
|
1476
|
+
#hinted = new Set;
|
|
1477
|
+
#classifier = new HmrChangeClassifier;
|
|
1478
|
+
#index;
|
|
1479
|
+
#timer = null;
|
|
1480
|
+
#verifyTimer = null;
|
|
1481
|
+
#windowStartedAt = null;
|
|
1482
|
+
#stopped = false;
|
|
1483
|
+
#flushing = false;
|
|
1484
|
+
#unreportedChanges = 0;
|
|
1485
|
+
#reportedCompensating = false;
|
|
1486
|
+
#reportedGaps = "";
|
|
1487
|
+
constructor(opts) {
|
|
1488
|
+
this.#roots = [...new Set(opts.roots.map((r) => path9.resolve(r)))];
|
|
1489
|
+
this.#debounceMs = opts.debounceMs ?? HmrWatcher.#envDebounceMs() ?? 30;
|
|
1490
|
+
this.#verifyDelayMs = opts.verifyDelayMs ?? 250;
|
|
1491
|
+
this.#onBatch = opts.onBatch;
|
|
1492
|
+
this.#logger = opts.logger;
|
|
1493
|
+
this.#index = new SourceMtimeIndex({ roots: this.#roots, classifier: this.#classifier });
|
|
1494
|
+
}
|
|
1495
|
+
get unreportedChanges() {
|
|
1496
|
+
return this.#unreportedChanges;
|
|
1497
|
+
}
|
|
1498
|
+
async start() {
|
|
1499
|
+
for (const root of this.#roots) {
|
|
1500
|
+
try {
|
|
1501
|
+
const w = fs2.watch(root, { recursive: true, persistent: false }, (_event, filename) => {
|
|
1502
|
+
if (!filename)
|
|
1503
|
+
return;
|
|
1504
|
+
const abs = path9.resolve(root, filename.toString());
|
|
1505
|
+
this.#queue(abs);
|
|
1506
|
+
});
|
|
1507
|
+
w.on("error", (err) => {
|
|
1508
|
+
if (err.code === "EACCES" || err.code === "EPERM")
|
|
1509
|
+
this.#logger.verbose(`[hmr] ${err.message}`);
|
|
1510
|
+
else
|
|
1511
|
+
this.#logger.warn(`[hmr] watcher error under ${root}: ${err.message}`);
|
|
1512
|
+
});
|
|
1513
|
+
this.#watchers.push(w);
|
|
1514
|
+
this.#logger.verbose(`[hmr] watching ${root}`);
|
|
1515
|
+
} catch (err) {
|
|
1516
|
+
this.#logger.error(`[hmr] failed to watch ${root}: ${err.message}`);
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
try {
|
|
1520
|
+
await this.#index.prime();
|
|
1521
|
+
this.#reportCoverageGaps();
|
|
1522
|
+
this.#logger.verbose(`[hmr] tracking ${this.#index.trackedFileCount} source files for change verification`);
|
|
1523
|
+
} catch (err) {
|
|
1524
|
+
this.#logger.error(`[hmr] mtime index unavailable; falling back to watcher events alone, which drop concurrent saves: ${err.message}`);
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
stop() {
|
|
1528
|
+
this.#stopped = true;
|
|
1529
|
+
if (this.#timer)
|
|
1530
|
+
clearTimeout(this.#timer);
|
|
1531
|
+
if (this.#verifyTimer)
|
|
1532
|
+
clearTimeout(this.#verifyTimer);
|
|
1533
|
+
for (const w of this.#watchers) {
|
|
1534
|
+
try {
|
|
1535
|
+
w.close();
|
|
1536
|
+
} catch {}
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
async absorb(paths) {
|
|
1540
|
+
if (paths.length === 0)
|
|
1541
|
+
return;
|
|
1542
|
+
await this.#index.absorb(paths);
|
|
1543
|
+
}
|
|
1544
|
+
#queue(abs) {
|
|
1545
|
+
const kind = this.#classifier.classify(abs);
|
|
1546
|
+
if (!this.#index.primed) {
|
|
1547
|
+
if (kind === "ignore")
|
|
1548
|
+
return;
|
|
1549
|
+
this.#pending.set(abs, kind);
|
|
1550
|
+
this.#scheduleFlush();
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
if (kind === "ignore") {
|
|
1554
|
+
this.#scheduleVerify();
|
|
1555
|
+
return;
|
|
1556
|
+
}
|
|
1557
|
+
this.#hinted.add(abs);
|
|
1558
|
+
this.#scheduleFlush();
|
|
1559
|
+
}
|
|
1560
|
+
#scheduleFlush() {
|
|
1561
|
+
this.#windowStartedAt ??= Date.now();
|
|
1562
|
+
if (this.#flushing)
|
|
1563
|
+
return;
|
|
1564
|
+
if (this.#timer)
|
|
1565
|
+
clearTimeout(this.#timer);
|
|
1566
|
+
this.#timer = setTimeout(() => this.#flush(), this.#debounceMs);
|
|
1567
|
+
}
|
|
1568
|
+
#flush() {
|
|
1569
|
+
this.#timer = null;
|
|
1570
|
+
if (this.#stopped || this.#flushing)
|
|
1571
|
+
return;
|
|
1572
|
+
this.#drain();
|
|
1573
|
+
}
|
|
1574
|
+
async#drain() {
|
|
1575
|
+
this.#flushing = true;
|
|
1576
|
+
try {
|
|
1577
|
+
while (!this.#stopped) {
|
|
1578
|
+
await this.#mergeDetectedChanges();
|
|
1579
|
+
if (this.#pending.size === 0) {
|
|
1580
|
+
this.#windowStartedAt = null;
|
|
1581
|
+
break;
|
|
1582
|
+
}
|
|
1583
|
+
const files = Array.from(this.#pending.keys());
|
|
1584
|
+
const kinds = new Set(this.#pending.values());
|
|
1585
|
+
const flushAt = Date.now();
|
|
1586
|
+
const trace = { eventAt: this.#windowStartedAt ?? flushAt, flushAt };
|
|
1587
|
+
this.#windowStartedAt = null;
|
|
1588
|
+
this.#pending.clear();
|
|
1589
|
+
this.#hinted.clear();
|
|
1590
|
+
try {
|
|
1591
|
+
await this.#onBatch({ files, kinds, trace });
|
|
1592
|
+
} catch (e) {
|
|
1593
|
+
this.#logger.error(`[hmr] onBatch error: ${e.message}`);
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
} finally {
|
|
1597
|
+
this.#flushing = false;
|
|
1598
|
+
if (!this.#stopped && this.#pending.size > 0)
|
|
1599
|
+
this.#timer = setTimeout(() => this.#flush(), this.#debounceMs);
|
|
1600
|
+
else
|
|
1601
|
+
this.#scheduleVerify();
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
async#mergeDetectedChanges() {
|
|
1605
|
+
const detected = await this.#index.collectChanges().catch((err) => {
|
|
1606
|
+
this.#logger.error(`[hmr] mtime scan failed: ${err.message}`);
|
|
1607
|
+
return [];
|
|
1608
|
+
});
|
|
1609
|
+
this.#reportCoverageGaps();
|
|
1610
|
+
let unreported = 0;
|
|
1611
|
+
for (const abs of detected) {
|
|
1612
|
+
const kind = this.#classifier.classify(abs);
|
|
1613
|
+
if (kind === "ignore")
|
|
1614
|
+
continue;
|
|
1615
|
+
if (!this.#hinted.has(abs))
|
|
1616
|
+
unreported += 1;
|
|
1617
|
+
this.#pending.set(abs, kind);
|
|
1618
|
+
}
|
|
1619
|
+
if (unreported === 0)
|
|
1620
|
+
return;
|
|
1621
|
+
this.#unreportedChanges += unreported;
|
|
1622
|
+
if (!this.#reportedCompensating) {
|
|
1623
|
+
this.#reportedCompensating = true;
|
|
1624
|
+
this.#logger.verbose(`[hmr] recovered ${unreported} change(s) that fs.watch did not report; Bun coalesces concurrent saves and drops all but one, so changes are resolved by mtime`);
|
|
1625
|
+
}
|
|
1626
|
+
this.#logger.verbose(`[hmr] mtime scan found ${unreported} change(s) fs.watch never reported (${this.#unreportedChanges} total)`);
|
|
1627
|
+
}
|
|
1628
|
+
#reportCoverageGaps() {
|
|
1629
|
+
const gaps = this.#index.coverageGaps;
|
|
1630
|
+
const key = gaps.map((gap) => `${gap.code}:${gap.path}`).sort((a, b) => a < b ? -1 : a > b ? 1 : 0).join("|");
|
|
1631
|
+
if (key === this.#reportedGaps)
|
|
1632
|
+
return;
|
|
1633
|
+
this.#reportedGaps = key;
|
|
1634
|
+
if (gaps.length === 0) {
|
|
1635
|
+
this.#logger.info("[hmr] all watch roots readable again; change detection is complete");
|
|
1636
|
+
return;
|
|
1637
|
+
}
|
|
1638
|
+
const shown = gaps.slice(0, 3).map((gap) => `${gap.path} (${gap.code})`).join(", ");
|
|
1639
|
+
const rest = gaps.length > 3 ? ` and ${gaps.length - 3} more` : "";
|
|
1640
|
+
this.#logger.warn(`[hmr] cannot read ${gaps.length} path(s), so edits underneath them will not rebuild: ${shown}${rest}`);
|
|
1641
|
+
}
|
|
1642
|
+
static #envDebounceMs() {
|
|
1643
|
+
const raw = process.env.AKAN_DEV_WATCH_DEBOUNCE_MS;
|
|
1644
|
+
const ms = raw ? Number(raw) : Number.NaN;
|
|
1645
|
+
return Number.isInteger(ms) && ms >= 0 ? ms : null;
|
|
1646
|
+
}
|
|
1647
|
+
#scheduleVerify() {
|
|
1648
|
+
if (this.#stopped || this.#verifyDelayMs <= 0)
|
|
1649
|
+
return;
|
|
1650
|
+
if (this.#verifyTimer)
|
|
1651
|
+
clearTimeout(this.#verifyTimer);
|
|
1652
|
+
this.#verifyTimer = setTimeout(() => {
|
|
1653
|
+
this.#verifyTimer = null;
|
|
1654
|
+
this.#verify();
|
|
1655
|
+
}, this.#verifyDelayMs);
|
|
1656
|
+
}
|
|
1657
|
+
async#verify() {
|
|
1658
|
+
if (this.#stopped || this.#flushing)
|
|
1659
|
+
return;
|
|
1660
|
+
await this.#mergeDetectedChanges();
|
|
1661
|
+
if (this.#pending.size > 0)
|
|
1662
|
+
await this.#drain();
|
|
1663
|
+
else if (this.#index.hasUnsettledDirs)
|
|
1664
|
+
this.#scheduleVerify();
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
export { UNAVAILABLE_REDIS_HOST, redisTunnelPolicy, BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS, SOURCE_EXTS, shouldRestartBackendByDevPlan, shouldRestartBuilderByDevPlan, shouldAbandonBackendRecovery, normalizeBackendReportedGeneration, shouldRestartDevHostByDevPlan, devHostStateOf, isLegacyBackendFallbackFile, shouldMarkBuildPhaseRecovered, shouldKeepBuildFailure, createBackendBuildStatus, backendRestartReasonFromMessage, mergeBackendRestartReasons, shouldReplaceLastGoodMessage, shouldQueueBuildStatusReplay, hasBuildFailureForGeneration, decideBuilderRssRecycle, decideBuilderRssSettle, decideIdleSuspend, resolveIdleSuspendMs, hasAnyBuildFailure, shouldRefreshConfigOnIdleWake, shouldHoldForReturningBuilder, shouldWarnBuilderRssCeilingTight, isRssCeilingUnreachable, shouldRelayRecycledFrontendState, mergeInvalidateMessages, buildStatusReplaySequence, filesChangedSince, HmrWatcher, WatchRootResolver, FontOptimizer, FontPruner, RouteJsBudget, ApplicationBuildReporter };
|