@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.
Files changed (118) hide show
  1. package/.build-stamp +1 -1
  2. package/{CodeAgent-z34p8m91.js → CodeAgent-h6g8dg3a.js} +2 -2
  3. package/{CodeTui-nvd9fk3g.js → CodeTui-n9gacepn.js} +1 -1
  4. package/README.ko.md +9 -0
  5. package/README.md +9 -0
  6. package/TunnelShare-k3ja4w9x.js +14 -0
  7. package/{agent.command-962mp3kg.js → agent.command-2f657613.js} +19 -17
  8. package/akanCode.js +2 -2
  9. package/{application.command-1nr0bqq1.js → application.command-yb8v177e.js} +35 -21
  10. package/{applicationBuildRunner-xy7hnfzq.js → applicationBuildRunner-sctcmkyx.js} +55 -16
  11. package/buildBatch.proc.js +7 -7
  12. package/{cloud.command-cj7b3m6y.js → cloud.command-et06ja22.js} +35 -18
  13. package/cloud.script-s6rbrwer.js +30 -0
  14. package/{code.command-asq7xrr6.js → code.command-7m67c7zc.js} +6 -6
  15. package/commandManifest.json +1 -1
  16. package/{context.command-fw4g2pw1.js → context.command-569z0rqf.js} +20 -19
  17. package/context.runner-ms8v1rxy.js +29 -0
  18. package/{guideline.command-43gfjsjv.js → guideline.command-gnv3e8p8.js} +2 -2
  19. package/guidelines/akanApi/akanApi.instruction.md +317 -0
  20. package/guidelines/conventions/rules/app.md +5 -5
  21. package/guidelines/conventions/rules/config.md +1 -1
  22. package/guidelines/conventions/rules/gates.md +10 -5
  23. package/incrementalBuilder.proc.js +69 -39
  24. package/{index-0tkj05cz.js → index-0fb3cpbt.js} +3 -3
  25. package/{index-6t7fkx73.js → index-1q1cjn8s.js} +21 -11
  26. package/{index-90q0w90q.js → index-3wjbhj2n.js} +1 -1
  27. package/{index-6zgt7zmx.js → index-48d5qsj3.js} +4 -4
  28. package/{index-z47rw9ez.js → index-5w9my9qe.js} +8 -8
  29. package/{index-qwe079ww.js → index-6wpaq392.js} +61 -15
  30. package/{index-kc871vpc.js → index-7xdpww43.js} +69 -12
  31. package/index-7y5yghjg.js +2969 -0
  32. package/{index-38patcx6.js → index-8g7tdsk4.js} +249 -696
  33. package/{index-kdswbvys.js → index-8pb9yvp8.js} +63 -21
  34. package/{index-hmj94es2.js → index-8ts9774g.js} +4 -4
  35. package/{index-r0q2ka2b.js → index-93ewzmp6.js} +43 -14
  36. package/{index-y0y0pnx8.js → index-9tbgb4d8.js} +1 -1
  37. package/index-abgh0jve.js +126 -0
  38. package/{index-t0hk1kxq.js → index-aj3ehkcx.js} +1 -1
  39. package/{index-demt944k.js → index-d4n1wmrz.js} +37 -4
  40. package/{index-sra1a5f8.js → index-drz9e84d.js} +22 -8
  41. package/{index-gfh90r3t.js → index-e3vmjtph.js} +2 -2
  42. package/{index-k64mhwbw.js → index-eajbmk10.js} +2 -1
  43. package/{index-g0yds382.js → index-ed6ea0qp.js} +1 -1
  44. package/{index-ap6ac70m.js → index-fjr4d6yd.js} +444 -368
  45. package/index-hqrkqxx2.js +176 -0
  46. package/{index-jzpeny42.js → index-jdamtr7e.js} +3 -3
  47. package/{index-ampz4vgv.js → index-kpdv34rq.js} +4 -4
  48. package/{index-kc6ffq0s.js → index-ktb3wcqz.js} +73 -34
  49. package/{index-dcm66hss.js → index-mmym5xmb.js} +4 -2
  50. package/{index-8d9r465x.js → index-mqntfzv5.js} +2 -2
  51. package/{index-4am4dvmf.js → index-ny2k80mv.js} +15 -3
  52. package/index-p6hjwt2d.js +1668 -0
  53. package/{index-53h0053j.js → index-rc5fvqj2.js} +12 -14
  54. package/{index-r8t5sq7z.js → index-ryrm5z2c.js} +66 -19
  55. package/{index-jzz6ye8x.js → index-s2grpzef.js} +40 -8
  56. package/{index-38by07nw.js → index-sr5da35e.js} +32 -9
  57. package/{index-qev8p5wp.js → index-sy481q2x.js} +1 -1
  58. package/{index-ck64kxrn.js → index-thckcabc.js} +2 -2
  59. package/{index-wymcdsas.js → index-vkzfk7qt.js} +25 -23
  60. package/{index-vkpqe29t.js → index-w639tvkd.js} +24 -125
  61. package/index-ygdbn9jn.js +122 -0
  62. package/{index-w60zxxye.js → index-zpv14wpy.js} +3 -3
  63. package/{index-2yan1ajk.js → index-zxsygkda.js} +18 -9
  64. package/index.js +24 -23
  65. package/{library.command-zh29tjdd.js → library.command-1gp5qe3r.js} +3 -3
  66. package/{localRegistry.command-k9pn9ahj.js → localRegistry.command-v3g21rex.js} +25 -16
  67. package/{module.command-dgpqs9fz.js → module.command-4xz9he6h.js} +6 -6
  68. package/{package.command-1je4hsca.js → package.command-s7qpnn1g.js} +12 -3
  69. package/package.json +2 -2
  70. package/{page.command-cgsasanh.js → page.command-fan34c49.js} +3 -3
  71. package/{pipeline.command-tb46sa8v.js → pipeline.command-ph4fnn9w.js} +2 -2
  72. package/{primitive.command-bzsy23x5.js → primitive.command-3fqh8emf.js} +7 -7
  73. package/{projectTypecheck-h8rgaczy.js → projectTypecheck-vkb40hjc.js} +1 -1
  74. package/{quality.command-120m9h6v.js → quality.command-ecj6exsh.js} +15 -10
  75. package/{repair.command-6m4wd0qv.js → repair.command-fe9jw719.js} +6 -6
  76. package/{scalar.command-3dn5hsc6.js → scalar.command-cnvfhk0n.js} +5 -5
  77. package/skills/akan-debug/SKILL.md +2 -1
  78. package/skills/akan-page/SKILL.md +16 -7
  79. package/skills/akan-service/SKILL.md +48 -19
  80. package/{subspace.command-s8nyfqbn.js → subspace.command-yxtt3v3e.js} +8 -8
  81. package/templates/app/lib/___appName__/__appName__.abstract.md.template +6 -0
  82. package/templates/app/page/_index.tsx +4 -284
  83. package/templates/app/page/_layout.tsx +1 -26
  84. package/templates/app/page/styles.css.template +58 -318
  85. package/templates/appSample/page/_index.tsx +281 -0
  86. package/templates/appSample/page/_layout.tsx +55 -0
  87. package/templates/appSample/page/styles.css.template +327 -0
  88. package/templates/libRoot/lib/___libName__/__libName__.abstract.md.template +6 -0
  89. package/templates/workspaceRoot/package.json.template +1 -12
  90. package/{tunnel.command-8mwrqkr3.js → tunnel.command-ggj38mqf.js} +7 -7
  91. package/{verify.command-2pspfy7k.js → verify.command-w9ttxkdz.js} +16 -14
  92. package/{workflow.command-7sy5vnsj.js → workflow.command-ss8devj0.js} +12 -12
  93. package/{workspace.command-x518tdv4.js → workspace.command-rw1p0xeq.js} +50 -38
  94. package/TunnelShare-jwbb50kz.js +0 -14
  95. package/cloud.script-8kr7qgfa.js +0 -27
  96. package/context.runner-p6m5cxk3.js +0 -28
  97. package/index-d894868w.js +0 -842
  98. package/index-re2kfscb.js +0 -1363
  99. /package/templates/{app → appSample}/page/_overrides.tsx +0 -0
  100. /package/templates/{app → appSample}/public/fonts/Pretendard-Black.woff2 +0 -0
  101. /package/templates/{app → appSample}/public/fonts/Pretendard-Bold.woff2 +0 -0
  102. /package/templates/{app → appSample}/public/fonts/Pretendard-ExtraBold.woff2 +0 -0
  103. /package/templates/{app → appSample}/public/fonts/Pretendard-ExtraLight.woff2 +0 -0
  104. /package/templates/{app → appSample}/public/fonts/Pretendard-Light.woff2 +0 -0
  105. /package/templates/{app → appSample}/public/fonts/Pretendard-Medium.woff2 +0 -0
  106. /package/templates/{app → appSample}/public/fonts/Pretendard-Regular.woff2 +0 -0
  107. /package/templates/{app → appSample}/public/fonts/Pretendard-SemiBold.woff2 +0 -0
  108. /package/templates/{app → appSample}/public/fonts/Pretendard-Thin.woff2 +0 -0
  109. /package/templates/{app → appSample}/public/jelly/cloud.webp +0 -0
  110. /package/templates/{app → appSample}/public/jelly/comet.webp +0 -0
  111. /package/templates/{app → appSample}/public/jelly/moon.webp +0 -0
  112. /package/templates/{app → appSample}/public/jelly/planet.webp +0 -0
  113. /package/templates/{app → appSample}/public/jelly/rocket.webp +0 -0
  114. /package/templates/{app → appSample}/public/jelly/star.webp +0 -0
  115. /package/templates/{app → appSample}/public/jelly/sugar.webp +0 -0
  116. /package/templates/{app → appSample}/public/logo.png +0 -0
  117. /package/templates/{app → appSample}/ui/Recipe/index.ts +0 -0
  118. /package/templates/{app → appSample}/ui/Recipe/jellyButton.ts +0 -0
@@ -1,7 +1,7 @@
1
1
  // @bun
2
2
  import {
3
3
  resolveSsrPageEntriesForApp
4
- } from "./index-38by07nw.js";
4
+ } from "./index-sr5da35e.js";
5
5
  import {
6
6
  computeRouteSeedIndex,
7
7
  saveRouteSeedIndex,
@@ -9,17 +9,20 @@ import {
9
9
  ClientEntriesBundler,
10
10
  VENDOR_SPECIFIERS,
11
11
  RouteClientBuilder
12
- } from "./index-kc871vpc.js";
12
+ } from "./index-7xdpww43.js";
13
13
  import {
14
- SOURCE_EXTS
15
- } from "./index-d894868w.js";
14
+ SOURCE_EXTS,
15
+ FontOptimizer,
16
+ FontPruner
17
+ } from "./index-p6hjwt2d.js";
16
18
  import {
17
19
  BarrelAnalyzer,
18
20
  createTsconfigPackageResolver,
19
21
  rewriteBarrelImports,
20
22
  CsrEntryFiles,
23
+ toClientReferencePath,
21
24
  PagesBundleBuilder
22
- } from "./index-6t7fkx73.js";
25
+ } from "./index-1q1cjn8s.js";
23
26
  import {
24
27
  CssBlockParser
25
28
  } from "./index-62md4dwy.js";
@@ -28,6 +31,38 @@ var __require = import.meta.require;
28
31
  // pkgs/@akanjs/devkit/frontendBuild/allRoutesBuilder.ts
29
32
  import path from "path";
30
33
 
34
+ // pkgs/@akanjs/devkit/frontendBuild/routeModulePreloads.ts
35
+ import { ModulePreloadPlan } from "akanjs/server/artifact/modulePreloadPlan";
36
+ class RouteModulePreloads {
37
+ table;
38
+ #input;
39
+ #chunksByReferenceId = new Map;
40
+ constructor(input) {
41
+ this.#input = input;
42
+ for (const [key, row] of Object.entries(input.clientManifest)) {
43
+ const chunks = this.#chunksByReferenceId.getOrInsert(key.slice(0, key.lastIndexOf("#")), new Set);
44
+ for (const url of row.chunks)
45
+ chunks.add(url);
46
+ }
47
+ this.table = {
48
+ ...input.runtimeChunks,
49
+ chunkVendors: Object.fromEntries(Object.entries(input.externalsByChunkUrl).map(([url, specifiers]) => [
50
+ url,
51
+ specifiers.filter((specifier) => (specifier in input.runtimeChunks.vendors))
52
+ ]).filter(([, specifiers]) => specifiers.length > 0))
53
+ };
54
+ }
55
+ modulesByRoute() {
56
+ const plan = new ModulePreloadPlan(this.table);
57
+ return Object.fromEntries([...this.#input.entriesByRoute].map(([routeId, entries]) => [
58
+ routeId,
59
+ plan.urlsOf(entries.flatMap((entry) => [
60
+ ...this.#chunksByReferenceId.get(toClientReferencePath(entry, this.#input.workspaceRoot)) ?? []
61
+ ]))
62
+ ]));
63
+ }
64
+ }
65
+
31
66
  // pkgs/@akanjs/devkit/frontendBuild/routesManifestArtifactSerializer.ts
32
67
  import { RoutesManifestStore } from "akanjs/server/artifact/routesManifestStore";
33
68
 
@@ -54,7 +89,6 @@ class RoutesManifestArtifactSerializer {
54
89
  // pkgs/@akanjs/devkit/frontendBuild/allRoutesBuilder.ts
55
90
  class AllRoutesBuilder {
56
91
  #app;
57
- #artifact;
58
92
  #command;
59
93
  #artifactDir;
60
94
  #merged = {
@@ -64,10 +98,11 @@ class AllRoutesBuilder {
64
98
  };
65
99
  #knownSet = new Set;
66
100
  #routeIds = [];
101
+ #entriesByRoute = new Map;
102
+ #externalsByChunkUrl = {};
67
103
  #discovery = null;
68
- constructor(app, artifact, command = "start") {
104
+ constructor(app, command = "start") {
69
105
  this.#app = app;
70
- this.#artifact = artifact;
71
106
  this.#command = command;
72
107
  this.#artifactDir = `${command === "build" ? app.dist.cwdPath : app.cwdPath}/.akan/artifact`;
73
108
  }
@@ -80,25 +115,43 @@ class AllRoutesBuilder {
80
115
  const allEntries = new Set;
81
116
  for (const entry of seedIndex.entries) {
82
117
  const seeds = Array.from(new Set([...seedIndex.globalLayoutFiles, ...entry.seeds]));
83
- for (const discovered of await this.#discovery.discover(seeds))
118
+ const routeEntries = await this.#discovery.discover(seeds);
119
+ for (const discovered of routeEntries)
84
120
  allEntries.add(discovered);
121
+ this.#entriesByRoute.set(entry.routeId, routeEntries);
85
122
  this.#routeIds.push(entry.routeId);
86
123
  }
87
124
  this.#app.verbose(`[build-all] ${allEntries.size} client entries across ${this.#routeIds.length} routes`);
88
125
  const delta = await this.#buildEntries([...allEntries]);
89
126
  this.#mergeDelta(delta);
90
127
  this.#merged.knownEntries = Array.from(this.#knownSet);
128
+ this.#externalsByChunkUrl = delta.externalsByChunkUrl ?? {};
91
129
  const manifest = {
92
130
  routeIds: this.#routeIds,
93
131
  ...this.#merged
94
132
  };
133
+ const manifestPath = await this.#writeManifest(manifest);
134
+ this.#app.verbose(`[build-all] wrote ${manifestPath} routes=${this.#routeIds.length} entries=${this.#merged.knownEntries.length}`);
135
+ return { manifest, manifestPath, seedIndex };
136
+ }
137
+ async writeModulePreloads(runtimeChunks) {
138
+ const preloads = new RouteModulePreloads({
139
+ runtimeChunks,
140
+ entriesByRoute: this.#entriesByRoute,
141
+ clientManifest: this.#merged.clientManifest,
142
+ externalsByChunkUrl: this.#externalsByChunkUrl,
143
+ workspaceRoot: this.#app.workspace.workspaceRoot
144
+ });
145
+ await this.#writeManifest({ routeIds: this.#routeIds, ...this.#merged, modulePreloads: preloads.table });
146
+ return preloads;
147
+ }
148
+ async#writeManifest(manifest) {
95
149
  const manifestPath = path.join(path.resolve(this.#artifactDir), "routes-manifest.json");
96
150
  await Bun.write(manifestPath, `${JSON.stringify(RoutesManifestArtifactSerializer.serialize(manifest, this.#artifactDir, {
97
151
  production: this.#command === "build"
98
152
  }), null, 2)}
99
153
  `);
100
- this.#app.verbose(`[build-all] wrote ${manifestPath} routes=${this.#routeIds.length} entries=${this.#merged.knownEntries.length}`);
101
- return { manifest, manifestPath, seedIndex };
154
+ return manifestPath;
102
155
  }
103
156
  async#buildEntries(entries) {
104
157
  if (!this.#discovery)
@@ -115,7 +168,6 @@ class AllRoutesBuilder {
115
168
  app: this.#app,
116
169
  seeds: [],
117
170
  entries,
118
- artifact: this.#artifact,
119
171
  knownEntries: this.#knownSet,
120
172
  discovery: this.#discovery,
121
173
  command: this.#command
@@ -666,661 +718,9 @@ function declaredCustomProperties(css) {
666
718
  function getPageKeyBasePath(pageKey, basePaths) {
667
719
  return CsrEntryFiles.basePathOfPageKey(pageKey, basePaths);
668
720
  }
669
- // pkgs/@akanjs/devkit/frontendBuild/fontOptimizer.ts
670
- import { mkdir, stat as stat2 } from "fs/promises";
671
- import path4 from "path";
672
- import ts from "typescript";
673
- var FONT_URL_PREFIX = "/_akan/fonts";
674
- var DEFAULT_FONT_SUBSETS = ["latin"];
675
-
676
- class FontOptimizer {
677
- #app;
678
- #command;
679
- #artifactRoot;
680
- #files = [];
681
- #cssParts = [];
682
- #woff2Ready = null;
683
- static #ksX1001Text = null;
684
- static #cacheVersion = 2;
685
- constructor(app, command = "start") {
686
- this.#app = app;
687
- this.#command = command;
688
- this.#artifactRoot = path4.join(command === "build" ? app.dist.cwdPath : app.cwdPath, ".akan/artifact");
689
- }
690
- async optimize() {
691
- const fonts = await this.discoverFonts();
692
- const cacheKey = await this.#buildCacheKey(fonts);
693
- const cached = cacheKey ? await this.#readCache(cacheKey) : null;
694
- if (cached) {
695
- this.#app.verbose(`[font] reused ${cached.files.length} cached file(s); skipped subsetting`);
696
- return { css: cached.css, fonts, files: cached.files };
697
- }
698
- for (const font of fonts) {
699
- if (!this.#isFontOptimizationEnabled(font))
700
- continue;
701
- await this.#optimizeFont(font);
702
- }
703
- const fontUtilityCss = this.#buildFontUtilityRules(fonts);
704
- if (fontUtilityCss)
705
- this.#cssParts.push(fontUtilityCss);
706
- const result = { css: this.#cssParts.join(`
707
- `), fonts, files: this.#files };
708
- if (cacheKey)
709
- await this.#writeCache(cacheKey, result);
710
- return result;
711
- }
712
- get #cachePath() {
713
- return path4.join(this.#artifactRoot, "fontCache.json");
714
- }
715
- async#buildCacheKey(fonts) {
716
- const sources = [];
717
- for (const font of fonts) {
718
- if (!this.#isFontOptimizationEnabled(font))
719
- continue;
720
- for (const face of this.#getFontFaces(font)) {
721
- const sourcePath = await this.#resolveFontSourcePath(face.src);
722
- const stamp = sourcePath ? await this.#fileStamp(sourcePath) : null;
723
- if (!stamp)
724
- return null;
725
- sources.push({ optimizedSrc: face.optimizedSrc, ...stamp });
726
- }
727
- for (const filePath of font.subsetFiles ?? []) {
728
- const abs = path4.isAbsolute(filePath) ? filePath : path4.join(this.#app.cwdPath, filePath);
729
- const stamp = await this.#fileStamp(abs);
730
- if (!stamp)
731
- return null;
732
- sources.push({ subsetFile: filePath, ...stamp });
733
- }
734
- if (this.#getFontSubsets(font).includes("auto"))
735
- sources.push({ autoSubsetText: this.#cacheDigest(await this.#collectAutoSubsetText()) });
736
- }
737
- return this.#cacheDigest({ version: FontOptimizer.#cacheVersion, fonts, sources });
738
- }
739
- #cacheDigest(value) {
740
- return new Bun.CryptoHasher("sha256").update(this.#stableStringify(value)).digest("hex");
741
- }
742
- async#fileStamp(filePath) {
743
- try {
744
- const stats = await stat2(filePath);
745
- return { mtimeMs: Math.round(stats.mtimeMs), size: stats.size };
746
- } catch {
747
- return null;
748
- }
749
- }
750
- async#readCache(key) {
751
- const cache = await Bun.file(this.#cachePath).json().catch(() => null);
752
- if (cache?.version !== FontOptimizer.#cacheVersion || cache.key !== key)
753
- return null;
754
- const files = cache.files.map((relativePath) => path4.join(this.#artifactRoot, relativePath));
755
- for (const filePath of files) {
756
- if (!await Bun.file(filePath).exists())
757
- return null;
758
- }
759
- return { css: cache.css, files };
760
- }
761
- async#writeCache(key, result) {
762
- const cache = {
763
- version: FontOptimizer.#cacheVersion,
764
- key,
765
- css: result.css,
766
- files: result.files.map((filePath) => path4.relative(this.#artifactRoot, filePath))
767
- };
768
- await Bun.write(this.#cachePath, JSON.stringify(cache));
769
- }
770
- async discoverFonts() {
771
- const pageKeys = await this.#app.getPageKeys();
772
- const fonts = [];
773
- await Promise.all(pageKeys.map(async (key) => {
774
- const filePath = path4.resolve(this.#app.cwdPath, "page", key);
775
- const file = Bun.file(filePath);
776
- if (!await file.exists())
777
- return;
778
- const source = await file.text();
779
- if (!source.includes("fonts"))
780
- return;
781
- fonts.push(...this.#extractFontsExport(source, filePath));
782
- }));
783
- return [...new Map(fonts.map((font) => [JSON.stringify(font), font])).values()];
784
- }
785
- async#optimizeFont(font) {
786
- const faceCss = [];
787
- for (const face of this.#getFontFaces(font)) {
788
- const sourcePath = await this.#resolveFontSourcePath(face.src);
789
- if (!sourcePath) {
790
- this.#app.logger.warn(`[font] source not found: ${face.src}`);
791
- continue;
792
- }
793
- const outputPath = path4.join(this.#artifactRoot, face.optimizedSrc.replace(/^\/_akan\//, ""));
794
- await mkdir(path4.dirname(outputPath), { recursive: true });
795
- const sourceBuffer = Buffer.from(await Bun.file(sourcePath).arrayBuffer());
796
- const outputBuffer = await this.#buildFontBuffer(font, sourceBuffer, sourcePath);
797
- await Bun.write(outputPath, outputBuffer);
798
- this.#files.push(outputPath);
799
- faceCss.push(this.#buildOptimizedFontFaceRule(font, face));
800
- const fallbackCss = await this.#buildFontaineFallbackCss(font, face, outputPath);
801
- if (fallbackCss)
802
- faceCss.push(fallbackCss);
803
- }
804
- if (faceCss.length > 0)
805
- this.#cssParts.push(...faceCss, this.#buildRootVariableRule(font));
806
- }
807
- #extractFontsExport(source, filePath) {
808
- const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
809
- const declaration = this.#findFontsDeclaration(sourceFile);
810
- if (!declaration)
811
- return [];
812
- const value = this.#literalToValue(declaration);
813
- const entries = Array.isArray(value) ? value : [];
814
- const fonts = entries.filter((entry) => this.#isReadableFont(entry));
815
- if (fonts.length !== entries.length || !Array.isArray(value))
816
- this.#app.logger.warn(`[font] ${path4.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`);
817
- return fonts.map((font) => ({ ...font, subsets: font.subsets ?? [...DEFAULT_FONT_SUBSETS] }));
818
- }
819
- #isReadableFont(value) {
820
- if (!value || typeof value !== "object")
821
- return false;
822
- const font = value;
823
- return typeof font.name === "string" && Array.isArray(font.paths);
824
- }
825
- #findFontsDeclaration(sourceFile) {
826
- for (const statement of sourceFile.statements) {
827
- if (ts.isExportAssignment(statement)) {
828
- if (statement.isExportEquals)
829
- continue;
830
- const stage = this.#findChainStageArgument(statement.expression, "fonts");
831
- if (stage)
832
- return stage;
833
- continue;
834
- }
835
- if (!ts.isVariableStatement(statement))
836
- continue;
837
- const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined;
838
- if (!modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword))
839
- continue;
840
- for (const declaration of statement.declarationList.declarations) {
841
- if (!ts.isIdentifier(declaration.name) || declaration.name.text !== "fonts")
842
- continue;
843
- if (declaration.initializer)
844
- return declaration.initializer;
845
- }
846
- }
847
- return null;
848
- }
849
- #findChainStageArgument(expression, stageName) {
850
- let node = this.#unwrapExpression(expression);
851
- let argument = null;
852
- while (node && ts.isCallExpression(node)) {
853
- const callee = this.#unwrapExpression(node.expression);
854
- if (!callee)
855
- return null;
856
- if (ts.isIdentifier(callee))
857
- return callee.text === "rootLayout" ? argument : null;
858
- if (!ts.isPropertyAccessExpression(callee))
859
- return null;
860
- if (callee.name.text === stageName)
861
- argument ??= node.arguments[0] ?? null;
862
- node = this.#unwrapExpression(callee.expression);
863
- }
864
- return null;
865
- }
866
- #unwrapExpression(expression) {
867
- let current = expression;
868
- while (current && (ts.isAsExpression(current) || ts.isSatisfiesExpression(current) || ts.isParenthesizedExpression(current))) {
869
- current = current.expression;
870
- }
871
- return current;
872
- }
873
- #literalToValue(node) {
874
- if (ts.isStringLiteralLike(node))
875
- return node.text;
876
- if (ts.isNumericLiteral(node))
877
- return Number(node.text);
878
- if (node.kind === ts.SyntaxKind.TrueKeyword)
879
- return true;
880
- if (node.kind === ts.SyntaxKind.FalseKeyword)
881
- return false;
882
- if (ts.isArrayLiteralExpression(node))
883
- return node.elements.map((element) => this.#literalToValue(element));
884
- if (ts.isObjectLiteralExpression(node)) {
885
- const obj = {};
886
- for (const prop of node.properties) {
887
- if (!ts.isPropertyAssignment(prop))
888
- continue;
889
- const name = this.#getPropertyName(prop.name);
890
- if (!name)
891
- continue;
892
- obj[name] = this.#literalToValue(prop.initializer);
893
- }
894
- return obj;
895
- }
896
- if (ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isParenthesizedExpression(node)) {
897
- return this.#literalToValue(node.expression);
898
- }
899
- return;
900
- }
901
- #getPropertyName(name) {
902
- if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name))
903
- return name.text;
904
- return null;
905
- }
906
- #getFontSubsets(font) {
907
- return font.subsets ?? DEFAULT_FONT_SUBSETS;
908
- }
909
- #getFontVariableName(font) {
910
- return font.variable ?? `--font-${font.name}`;
911
- }
912
- #getFontFallbackName(font) {
913
- return font.fallbackName ?? `${font.name} fallback`;
914
- }
915
- #isFontOptimizationEnabled(font) {
916
- return font.optimize !== false;
917
- }
918
- #getFontFaces(font) {
919
- const enabledStyles = new Set(font.styles?.length ? font.styles : ["normal"]);
920
- return font.paths.map((fontPath) => {
921
- const style = fontPath.style ?? "normal";
922
- return {
923
- font,
924
- path: fontPath,
925
- src: fontPath.src,
926
- weight: fontPath.weight,
927
- style,
928
- optimizedSrc: this.#getOptimizedFontSrc(font, fontPath)
929
- };
930
- }).filter((face) => enabledStyles.has(face.style));
931
- }
932
- #getOptimizedFontSrc(font, fontPath) {
933
- const style = fontPath.style ?? "normal";
934
- const hash = this.#hashFontConfig({
935
- name: font.name,
936
- src: fontPath.src,
937
- weight: fontPath.weight,
938
- style,
939
- display: font.display,
940
- subset: font.subset,
941
- subsets: this.#getFontSubsets(font),
942
- subsetText: font.subsetText,
943
- subsetFiles: font.subsetFiles,
944
- declarations: [...font.declarations ?? [], ...fontPath.declarations ?? []]
945
- });
946
- return `${FONT_URL_PREFIX}/${this.#slugFontPart(font.name)}-${this.#slugFontPart(String(fontPath.weight))}-${style}-${hash}.woff2`;
947
- }
948
- #hashFontConfig(value) {
949
- const input = this.#stableStringify(value);
950
- let hash = 2166136261;
951
- for (let i = 0;i < input.length; i++) {
952
- hash ^= input.charCodeAt(i);
953
- hash = Math.imul(hash, 16777619);
954
- }
955
- return (hash >>> 0).toString(36);
956
- }
957
- #stableStringify(value) {
958
- if (Array.isArray(value))
959
- return `[${value.map((item) => this.#stableStringify(item)).join(",")}]`;
960
- if (value && typeof value === "object") {
961
- const entries = Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a.localeCompare(b));
962
- return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${this.#stableStringify(v)}`).join(",")}}`;
963
- }
964
- return JSON.stringify(value);
965
- }
966
- #slugFontPart(value) {
967
- return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "font";
968
- }
969
- async#resolveFontSourcePath(src) {
970
- if (!src.startsWith("/"))
971
- return null;
972
- const rel = src.replace(/^\//, "");
973
- const candidates = [
974
- this.#command === "build" ? path4.join(this.#app.dist.cwdPath, "public", rel) : null,
975
- path4.join(this.#app.cwdPath, "public", rel),
976
- this.#resolveWorkspacePublicPath(rel)
977
- ].filter(Boolean);
978
- for (const candidate of candidates) {
979
- if (await Bun.file(candidate).exists())
980
- return candidate;
981
- }
982
- return null;
983
- }
984
- async#buildFontBuffer(font, sourceBuffer, sourcePath) {
985
- if (font.subset === false)
986
- return this.#convertToWoff2(sourceBuffer, sourcePath);
987
- const { default: subsetFont } = await import("subset-font");
988
- return subsetFont(sourceBuffer, await this.#getSubsetText(font), { targetFormat: "woff2" });
989
- }
990
- async#convertToWoff2(buffer, sourcePath) {
991
- const { createFont } = await import("fonteditor-core");
992
- this.#woff2Ready ??= import("fonteditor-core").then(({ woff2 }) => woff2.init()).then(() => {
993
- return;
994
- });
995
- await this.#woff2Ready;
996
- const font = createFont(buffer, { type: this.#getFontType(sourcePath, buffer) });
997
- return font.write({ type: "woff2", toBuffer: true });
998
- }
999
- #getFontType(sourcePath, buffer) {
1000
- const signature = buffer.toString("ascii", 0, 4);
1001
- if (signature === "wOFF")
1002
- return "woff";
1003
- if (signature === "wOF2")
1004
- return "woff2";
1005
- if (signature === "OTTO")
1006
- return "otf";
1007
- const ext = path4.extname(sourcePath).slice(1).toLowerCase();
1008
- if (ext === "otf" || ext === "woff" || ext === "woff2")
1009
- return ext;
1010
- return "ttf";
1011
- }
1012
- #resolveWorkspacePublicPath(rel) {
1013
- const [root, dep, ...rest] = rel.split("/");
1014
- if (root !== "libs" || !dep || rest.length === 0)
1015
- return null;
1016
- return path4.join(this.#app.workspace.workspaceRoot, "libs", dep, "public", ...rest);
1017
- }
1018
- async#getSubsetText(font) {
1019
- const parts = new Set;
1020
- const subsets = this.#getFontSubsets(font);
1021
- for (const subset of subsets)
1022
- parts.add(await this.#getSubsetPresetText(subset));
1023
- if (font.subsetText)
1024
- parts.add(font.subsetText);
1025
- for (const filePath of font.subsetFiles ?? []) {
1026
- const abs = path4.isAbsolute(filePath) ? filePath : path4.join(this.#app.cwdPath, filePath);
1027
- const file = Bun.file(abs);
1028
- if (await file.exists())
1029
- parts.add(await file.text());
1030
- }
1031
- return [...parts].join("");
1032
- }
1033
- async#getSubsetPresetText(subset) {
1034
- if (subset === "latin")
1035
- return FontOptimizer.#rangeText(32, 126);
1036
- if (subset === "latin-ext")
1037
- return `${FontOptimizer.#rangeText(32, 126)}${FontOptimizer.#rangeText(160, 591)}`;
1038
- if (subset === "ks-x-1001")
1039
- return FontOptimizer.#getKsX1001Text();
1040
- if (subset === "auto")
1041
- return this.#collectAutoSubsetText();
1042
- return "";
1043
- }
1044
- async#collectAutoSubsetText() {
1045
- const libPageRoots = (await this.#app.getPageRoots()).filter((root) => root.keyPrefix).map((root) => root.dir);
1046
- const roots = [...["page", "ui", "lib"].map((dir) => path4.join(this.#app.cwdPath, dir)), ...libPageRoots];
1047
- const glob = new Bun.Glob("**/*.{ts,tsx,js,jsx,html,md}");
1048
- const parts = [];
1049
- for (const root of [...new Set(roots)].sort()) {
1050
- const isDir = await stat2(root).then((entry) => entry.isDirectory(), () => false);
1051
- if (!isDir)
1052
- continue;
1053
- const filePaths = [];
1054
- for await (const filePath of glob.scan({ cwd: root, absolute: true }))
1055
- filePaths.push(filePath);
1056
- for (const filePath of filePaths.sort((a, b) => a < b ? -1 : a > b ? 1 : 0))
1057
- parts.push(await Bun.file(filePath).text());
1058
- }
1059
- return parts.join("");
1060
- }
1061
- static #getKsX1001Text() {
1062
- if (FontOptimizer.#ksX1001Text)
1063
- return FontOptimizer.#ksX1001Text;
1064
- try {
1065
- const decoder = new TextDecoder("euc-kr");
1066
- const chars = new Set;
1067
- for (let lead = 161;lead <= 254; lead++) {
1068
- for (let trail = 161;trail <= 254; trail++) {
1069
- const char = decoder.decode(Uint8Array.of(lead, trail));
1070
- if (char && char !== "\uFFFD")
1071
- chars.add(char);
1072
- }
1073
- }
1074
- FontOptimizer.#ksX1001Text = [...chars].join("");
1075
- } catch {
1076
- FontOptimizer.#ksX1001Text = FontOptimizer.#rangeText(44032, 55203);
1077
- }
1078
- return FontOptimizer.#ksX1001Text;
1079
- }
1080
- static #rangeText(start, end) {
1081
- let text = "";
1082
- for (let code = start;code <= end; code++)
1083
- text += String.fromCodePoint(code);
1084
- return text;
1085
- }
1086
- #buildOptimizedFontFaceRule(font, face) {
1087
- const declarations = [
1088
- ["font-family", this.#quote(font.name)],
1089
- ["src", `url(${this.#quote(face.optimizedSrc)}) format("woff2")`],
1090
- ["font-weight", String(face.weight)],
1091
- ["font-style", face.style],
1092
- ["font-display", font.display ?? "swap"],
1093
- ...this.#toDeclarationEntries(font.declarations),
1094
- ...this.#toDeclarationEntries(face.path.declarations)
1095
- ];
1096
- return `@font-face {
1097
- ${declarations.map(([prop, value]) => ` ${prop}: ${value};`).join(`
1098
- `)}
1099
- }`;
1100
- }
1101
- async#buildFontaineFallbackCss(font, face, outputPath) {
1102
- if (font.adjustFontFallback === false)
1103
- return "";
1104
- const { generateFontFace, getMetricsForFamily, readMetrics, resolveCategoryFallbacks } = await import("fontaine");
1105
- const metrics = await readMetrics(outputPath).catch(() => null);
1106
- if (!metrics)
1107
- return "";
1108
- const fallbacks = resolveCategoryFallbacks({
1109
- fontFamily: font.name,
1110
- fallbacks: font.fallbacks ?? {},
1111
- metrics: { ...metrics, category: font.category }
1112
- });
1113
- const css = [];
1114
- for (let i = fallbacks.length - 1;i >= 0; i--) {
1115
- const fallback = fallbacks[i];
1116
- const fallbackMetrics = await getMetricsForFamily(fallback);
1117
- if (!fallbackMetrics)
1118
- continue;
1119
- css.push(generateFontFace({ ...metrics, category: font.category }, {
1120
- name: this.#getFontFallbackName(font),
1121
- font: fallback,
1122
- metrics: fallbackMetrics,
1123
- "font-weight": String(face.weight),
1124
- "font-style": face.style
1125
- }));
1126
- }
1127
- return css.join("");
1128
- }
1129
- #buildRootVariableRule(font) {
1130
- return `:root { ${this.#getFontVariableName(font)}: ${this.#quote(font.name)}, ${this.#quote(this.#getFontFallbackName(font))}; }`;
1131
- }
1132
- #buildFontUtilityRules(fonts) {
1133
- const rules = [];
1134
- const seen = new Set;
1135
- for (const font of fonts) {
1136
- const className = font.className || `font-${font.name}`;
1137
- const selector = `.${this.#escapeCssClassName(className)}`;
1138
- const rule = `${selector} { font-family: var(${this.#getFontVariableName(font)}); }`;
1139
- if (seen.has(rule))
1140
- continue;
1141
- seen.add(rule);
1142
- rules.push(rule);
1143
- }
1144
- return rules.join(`
1145
- `);
1146
- }
1147
- #escapeCssClassName(value) {
1148
- return value.replace(/^-?\d|[^a-zA-Z0-9_-]/g, (part) => [...part].map((char) => `\\${char.codePointAt(0)?.toString(16)} `).join(""));
1149
- }
1150
- #toDeclarationEntries(declarations = []) {
1151
- return declarations.map((declaration) => [declaration.prop, declaration.value]);
1152
- }
1153
- #quote(value) {
1154
- return JSON.stringify(value);
1155
- }
1156
- }
1157
- // pkgs/@akanjs/devkit/frontendBuild/fontPruner.ts
1158
- import { rm, rmdir, stat as stat3 } from "fs/promises";
1159
- import path5 from "path";
1160
- import { isFontOptimizationEnabled } from "akanjs/client";
1161
- var FONT_GLOB = "**/*.{woff2,woff,ttf,otf,ttc,eot}";
1162
- var REFERRER_GLOB = "**/*.{css,js,mjs,cjs,json,html,htm,svg,xml,webmanifest}";
1163
-
1164
- class FontPruner {
1165
- #app;
1166
- #keepGlobs;
1167
- #publicRoot;
1168
- #artifactRoot;
1169
- constructor(app, { keepFonts = [] } = {}) {
1170
- this.#app = app;
1171
- this.#keepGlobs = keepFonts;
1172
- this.#publicRoot = path5.join(app.dist.cwdPath, "public");
1173
- this.#artifactRoot = path5.join(app.dist.cwdPath, ".akan/artifact");
1174
- }
1175
- async prune() {
1176
- const empty = { removed: [], kept: [], freedBytes: 0 };
1177
- if (!await this.#isDirectory(this.#publicRoot))
1178
- return empty;
1179
- const candidates = await this.#collectCandidates();
1180
- if (!candidates.length)
1181
- return empty;
1182
- const fonts = await new FontOptimizer(this.#app, "build").discoverFonts();
1183
- const unoptimizedSrcs = new Set;
1184
- const optimizedSrcs = new Set;
1185
- for (const font of fonts) {
1186
- const target = isFontOptimizationEnabled(font) ? optimizedSrcs : unoptimizedSrcs;
1187
- for (const fontPath of font.paths)
1188
- target.add(path5.posix.basename(fontPath.src));
1189
- }
1190
- const result = { removed: [], kept: [], freedBytes: 0 };
1191
- const undecided = [];
1192
- for (const candidate of candidates) {
1193
- const reason = this.#staticKeepReason(candidate, unoptimizedSrcs);
1194
- if (reason)
1195
- result.kept.push({ file: candidate.rel, bytes: candidate.bytes, reason });
1196
- else
1197
- undecided.push(candidate);
1198
- }
1199
- if (undecided.length) {
1200
- const referrers = await this.#findReferrers(undecided, optimizedSrcs);
1201
- for (const candidate of undecided) {
1202
- const referrer = referrers.get(candidate.rel);
1203
- if (referrer)
1204
- result.kept.push({ file: candidate.rel, bytes: candidate.bytes, reason: { kind: "referenced", referrer } });
1205
- else
1206
- result.removed.push({ file: candidate.rel, bytes: candidate.bytes });
1207
- }
1208
- }
1209
- await this.#remove(result.removed.map(({ file }) => file));
1210
- result.freedBytes = result.removed.reduce((total, { bytes }) => total + bytes, 0);
1211
- this.#report(result);
1212
- return result;
1213
- }
1214
- #staticKeepReason(candidate, unoptimizedSrcs) {
1215
- if (unoptimizedSrcs.has(candidate.basename))
1216
- return { kind: "unoptimized" };
1217
- for (const glob of this.#keepGlobs) {
1218
- if (new Bun.Glob(glob).match(candidate.rel))
1219
- return { kind: "declared", glob };
1220
- }
1221
- return null;
1222
- }
1223
- async#collectCandidates() {
1224
- const candidates = [];
1225
- for await (const rel of new Bun.Glob(FONT_GLOB).scan({ cwd: this.#publicRoot, dot: false })) {
1226
- const entry = await stat3(path5.join(this.#publicRoot, rel)).catch(() => null);
1227
- if (!entry?.isFile())
1228
- continue;
1229
- candidates.push({ rel: rel.split(path5.sep).join("/"), basename: path5.basename(rel), bytes: entry.size });
1230
- }
1231
- return candidates;
1232
- }
1233
- async#findReferrers(candidates, optimizedSrcs) {
1234
- const referrers = new Map;
1235
- const authoritative = candidates;
1236
- const bundled = candidates.filter((candidate) => !optimizedSrcs.has(candidate.basename));
1237
- const roots = [
1238
- { dir: this.#publicRoot, label: "public", needles: authoritative },
1239
- { dir: path5.join(this.#artifactRoot, "styles"), label: ".akan/artifact/styles", needles: authoritative },
1240
- { dir: path5.join(this.#artifactRoot, "client"), label: ".akan/artifact/client", needles: bundled },
1241
- { dir: path5.join(this.#artifactRoot, "client-ssr"), label: ".akan/artifact/client-ssr", needles: bundled },
1242
- { dir: path5.join(this.#artifactRoot, "server"), label: ".akan/artifact/server", needles: bundled },
1243
- { dir: path5.join(this.#app.dist.cwdPath, "csr"), label: "csr", needles: bundled },
1244
- { dir: path5.join(this.#app.dist.cwdPath, "mcp-apps"), label: "mcp-apps", needles: bundled }
1245
- ];
1246
- for (const root of roots) {
1247
- const pending = root.needles.filter((candidate) => !referrers.has(candidate.rel));
1248
- if (!pending.length || !await this.#isDirectory(root.dir))
1249
- continue;
1250
- await this.#scanRoot(root, pending, referrers);
1251
- }
1252
- return referrers;
1253
- }
1254
- async#scanRoot(root, pending, referrers) {
1255
- const needles = pending.map((candidate) => ({
1256
- rel: candidate.rel,
1257
- forms: [...new Set([candidate.basename, encodeURIComponent(candidate.basename)])]
1258
- }));
1259
- for await (const rel of new Bun.Glob(REFERRER_GLOB).scan({ cwd: root.dir, dot: false })) {
1260
- const remaining = needles.filter((needle) => !referrers.has(needle.rel));
1261
- if (!remaining.length)
1262
- return;
1263
- const text = await Bun.file(path5.join(root.dir, rel)).text().catch(() => "");
1264
- if (!text)
1265
- continue;
1266
- for (const needle of remaining) {
1267
- if (needle.forms.some((form) => text.includes(form)))
1268
- referrers.set(needle.rel, `${root.label}/${rel.split(path5.sep).join("/")}`);
1269
- }
1270
- }
1271
- }
1272
- async#remove(files) {
1273
- await Promise.all(files.map((file) => rm(path5.join(this.#publicRoot, file), { force: true })));
1274
- const dirs = [...new Set(files.map((file) => path5.posix.dirname(file)))].filter((dir) => dir !== "." && dir !== "/").sort((a, b) => b.length - a.length);
1275
- for (const dir of dirs)
1276
- await rmdir(path5.join(this.#publicRoot, dir)).catch(() => {
1277
- return;
1278
- });
1279
- }
1280
- #report(result) {
1281
- if (!result.removed.length && !result.kept.length)
1282
- return;
1283
- for (const { file, bytes } of result.removed)
1284
- this.#app.verbose(`[font-prune] dropped public/${file} (${FontPruner.formatBytes(bytes)})`);
1285
- for (const { file, reason } of result.kept)
1286
- this.#app.verbose(`[font-prune] kept public/${file} \u2014 ${FontPruner.describe(reason)}`);
1287
- const byReferrer = new Map;
1288
- for (const { bytes, reason } of result.kept) {
1289
- if (reason.kind !== "referenced")
1290
- continue;
1291
- const entry = byReferrer.get(reason.referrer) ?? { files: 0, bytes: 0 };
1292
- entry.files += 1;
1293
- entry.bytes += bytes;
1294
- byReferrer.set(reason.referrer, entry);
1295
- }
1296
- if (!byReferrer.size)
1297
- return;
1298
- const ranked = [...byReferrer.entries()].sort(([, a], [, b]) => b.bytes - a.bytes);
1299
- const named = ranked.slice(0, 3).map(([referrer, { files, bytes }]) => `${referrer} (${files}, ${FontPruner.formatBytes(bytes)})`);
1300
- const rest = ranked.length - named.length;
1301
- 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` : ""}`);
1302
- }
1303
- static describe(reason) {
1304
- if (reason.kind === "unoptimized")
1305
- return "declared with optimize: false, so the runtime CSS serves it";
1306
- if (reason.kind === "declared")
1307
- return `kept by assets.keepFonts "${reason.glob}"`;
1308
- return `referenced by ${reason.referrer}`;
1309
- }
1310
- static formatBytes(bytes) {
1311
- if (bytes < 1024)
1312
- return `${bytes}B`;
1313
- if (bytes < 1024 * 1024)
1314
- return `${(bytes / 1024).toFixed(1)}KB`;
1315
- return `${(bytes / 1024 / 1024).toFixed(1)}MB`;
1316
- }
1317
- async#isDirectory(dir) {
1318
- return await stat3(dir).then((entry) => entry.isDirectory(), () => false);
1319
- }
1320
- }
1321
721
  // pkgs/@akanjs/devkit/frontendBuild/precompressArtifacts.ts
1322
722
  import fs from "fs";
1323
- import path6 from "path";
723
+ import path4 from "path";
1324
724
  import zlib from "zlib";
1325
725
  var COMPRESSIBLE_EXTS = new Set([".css", ".html", ".js", ".json", ".svg"]);
1326
726
  var MIN_COMPRESS_BYTES = 1024;
@@ -1330,11 +730,11 @@ var DEFAULT_BROTLI_QUALITY = 9;
1330
730
  var GZIP_LEVEL = 9;
1331
731
  var { formatBytes } = FontPruner;
1332
732
  async function precompressArtifacts(app) {
1333
- const artifactDir = path6.join(app.dist.cwdPath, ".akan/artifact");
733
+ const artifactDir = path4.join(app.dist.cwdPath, ".akan/artifact");
1334
734
  const roots = [
1335
- { root: path6.join(artifactDir, "client") },
1336
- { root: path6.join(artifactDir, "styles") },
1337
- { root: path6.join(artifactDir, "dict"), brotliQuality: MAX_BROTLI_QUALITY }
735
+ { root: path4.join(artifactDir, "client") },
736
+ { root: path4.join(artifactDir, "styles") },
737
+ { root: path4.join(artifactDir, "dict"), brotliQuality: MAX_BROTLI_QUALITY }
1338
738
  ];
1339
739
  const result = { files: 0, inputBytes: 0, outputBytes: 0, brotliBytes: 0 };
1340
740
  await Promise.all(roots.map(({ root, brotliQuality }) => precompressRoot(root, result, brotliQuality)));
@@ -1353,7 +753,7 @@ async function precompressRoot(root, result, brotliQuality) {
1353
753
  const bytes = await Bun.file(filePath).bytes();
1354
754
  const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
1355
755
  const gz = Bun.gzipSync(buffer, { level: GZIP_LEVEL });
1356
- const br = brotliCompress(buffer, brotliQuality ?? brotliQualityOf(path6.extname(filePath).toLowerCase()));
756
+ const br = brotliCompress(buffer, brotliQuality ?? brotliQualityOf(path4.extname(filePath).toLowerCase()));
1357
757
  await Promise.all([Bun.write(`${filePath}.gz`, gz), Bun.write(`${filePath}.br`, br)]);
1358
758
  result.files += 1;
1359
759
  result.inputBytes += bytes.byteLength;
@@ -1375,7 +775,7 @@ function brotliCompress(buffer, quality) {
1375
775
  async function shouldPrecompress(filePath) {
1376
776
  if (filePath.endsWith(".gz") || filePath.endsWith(".br"))
1377
777
  return false;
1378
- if (!COMPRESSIBLE_EXTS.has(path6.extname(filePath).toLowerCase()))
778
+ if (!COMPRESSIBLE_EXTS.has(path4.extname(filePath).toLowerCase()))
1379
779
  return false;
1380
780
  const file = Bun.file(filePath);
1381
781
  if (!await file.exists())
@@ -1383,11 +783,11 @@ async function shouldPrecompress(filePath) {
1383
783
  return file.size >= MIN_COMPRESS_BYTES;
1384
784
  }
1385
785
  // pkgs/@akanjs/devkit/frontendBuild/ssrBaseArtifactBuilder.ts
1386
- import path8 from "path";
786
+ import path7 from "path";
1387
787
  import { optimize } from "@tailwindcss/node";
1388
788
 
1389
789
  // pkgs/@akanjs/devkit/frontendBuild/dictionaryAssetBuilder.ts
1390
- import path7 from "path";
790
+ import path5 from "path";
1391
791
  import { Translator } from "akanjs/client";
1392
792
 
1393
793
  class DictionaryAssetBuilder {
@@ -1407,7 +807,7 @@ class DictionaryAssetBuilder {
1407
807
  return Object.fromEntries(assets);
1408
808
  }
1409
809
  async#loadAllDictionary() {
1410
- const dictPath = path7.resolve(this.#app.cwdPath, "lib", "dict.ts");
810
+ const dictPath = path5.resolve(this.#app.cwdPath, "lib", "dict.ts");
1411
811
  if (!await Bun.file(dictPath).exists())
1412
812
  return null;
1413
813
  const { getAllDictionary } = await import(dictPath);
@@ -1417,7 +817,7 @@ class DictionaryAssetBuilder {
1417
817
  const source = DictionaryAssetBuilder.source(lang, dictionary);
1418
818
  const name = `${lang}-${Bun.hash(source).toString(36)}.js`;
1419
819
  const relPath = `dict/${name}`;
1420
- await Bun.write(path7.join(this.#absArtifactDir, relPath), source);
820
+ await Bun.write(path5.join(this.#absArtifactDir, relPath), source);
1421
821
  return [lang, { url: `${DictionaryAssetBuilder.urlPrefix}/${name}`, relPath }];
1422
822
  }
1423
823
  static source(lang, dictionary) {
@@ -1427,6 +827,58 @@ export default JSON.parse(${JSON.stringify(JSON.stringify(dictionary))});
1427
827
  }
1428
828
  }
1429
829
 
830
+ // pkgs/@akanjs/devkit/frontendBuild/vendorNarrowing.ts
831
+ import fs2 from "fs";
832
+ import path6 from "path";
833
+ var deprecatedReexports = { "akanjs/store": "store/deprecatedAgent.ts" };
834
+
835
+ class VendorNarrowing {
836
+ #akanjsRoot;
837
+ #vendorExports;
838
+ static entriesIn(akanServerPath) {
839
+ return VENDOR_SPECIFIERS.map((specifier) => ({
840
+ specifier,
841
+ absPath: path6.resolve(akanServerPath, "vendor", `${specifier.replaceAll("/", "-").replaceAll(".", "-")}.ts`)
842
+ })).filter(({ absPath }) => fs2.existsSync(absPath));
843
+ }
844
+ constructor(akanjsRoot, vendorExports) {
845
+ this.#akanjsRoot = akanjsRoot;
846
+ const current = Object.values(deprecatedReexports).every((file) => fs2.existsSync(path6.join(akanjsRoot, file)));
847
+ this.#vendorExports = current ? vendorExports : {};
848
+ }
849
+ entryExports(vendorEntries) {
850
+ return Object.fromEntries(vendorEntries.flatMap(({ specifier, absPath }) => {
851
+ const names = this.#vendorExports[specifier];
852
+ return names ? [[absPath, names]] : [];
853
+ }));
854
+ }
855
+ async plugins() {
856
+ const blanked = [];
857
+ for (const [specifier, file] of Object.entries(deprecatedReexports)) {
858
+ const used = this.#vendorExports[specifier];
859
+ if (!used)
860
+ continue;
861
+ const source = await Bun.file(path6.join(this.#akanjsRoot, file)).text();
862
+ const names = new Bun.Transpiler({ loader: "ts" }).scan(source).exports;
863
+ if (!names.some((name) => used.includes(name)))
864
+ blanked.push(`akanjs/${file}`);
865
+ }
866
+ if (blanked.length === 0)
867
+ return [];
868
+ const escaped = blanked.map((file) => file.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replaceAll("/", "[\\\\/]"));
869
+ const filter = new RegExp(`[\\\\/](?:${escaped.join("|")})$`);
870
+ return [
871
+ {
872
+ name: "akan-blank-deprecated-reexports",
873
+ setup(build) {
874
+ build.onLoad({ filter }, () => ({ contents: `export {};
875
+ `, loader: "ts" }));
876
+ }
877
+ }
878
+ ];
879
+ }
880
+ }
881
+
1430
882
  // pkgs/@akanjs/devkit/frontendBuild/ssrBaseArtifactBuilder.ts
1431
883
  function prepareCssAsset(command, basePath, cssText) {
1432
884
  return optimize(cssText, { file: `${basePath || "root"}.css`, minify: command === "build" }).code;
@@ -1439,19 +891,24 @@ class SsrBaseArtifactBuilder {
1439
891
  #absArtifactDir;
1440
892
  #started = Date.now();
1441
893
  #serverEnv;
1442
- constructor(app, command = "start", { serverEnv } = {}) {
894
+ #vendorExports;
895
+ constructor(app, command = "start", {
896
+ serverEnv,
897
+ vendorExports = {}
898
+ } = {}) {
1443
899
  this.#app = app;
1444
900
  this.#command = command;
1445
901
  this.#serverEnv = serverEnv;
902
+ this.#vendorExports = vendorExports;
1446
903
  this.#artifactDir = `${command === "build" ? app.dist.cwdPath : app.cwdPath}/.akan/artifact`;
1447
- this.#absArtifactDir = path8.resolve(this.#artifactDir);
904
+ this.#absArtifactDir = path7.resolve(this.#artifactDir);
1448
905
  }
1449
906
  static servedWeb(command, web) {
1450
907
  return command === "start" ? { ssr: true, csr: true } : web;
1451
908
  }
1452
909
  async build() {
1453
910
  const akanConfig = await this.#app.getConfig();
1454
- const { rscClientUrl, rscRuntimeClientManifest, rscRuntimeSsrManifest, vendorMap } = await this.#buildRuntimeClientEntries();
911
+ const { rscClientUrl, rscRuntimeClientManifest, rscRuntimeSsrManifest, vendorMap, runtimeChunks } = await this.#buildRuntimeClientEntries();
1455
912
  const pageKeys = await this.#app.getPageKeys();
1456
913
  this.#app.verbose(`[base-artifact] discovered ${pageKeys.length} route files under ${this.#app.cwdPath}/page`);
1457
914
  const pageEntries = await resolveSsrPageEntriesForApp(this.#app, pageKeys);
@@ -1471,7 +928,7 @@ class SsrBaseArtifactBuilder {
1471
928
  vendorMap,
1472
929
  cssAssets,
1473
930
  dictAssets,
1474
- pagesBundlePath: this.#command === "build" ? path8.relative(this.#absArtifactDir, pagesBundle.bundlePath) : pagesBundle.bundlePath,
931
+ pagesBundlePath: this.#command === "build" ? path7.relative(this.#absArtifactDir, pagesBundle.bundlePath) : pagesBundle.bundlePath,
1475
932
  pagesBundleBuildId: pagesBundle.buildId,
1476
933
  domains: [...akanConfig.domains],
1477
934
  subRoutes: Object.fromEntries(Array.from(akanConfig.subRoutes.entries()).map(([basePath, domains]) => [basePath, [...domains]])),
@@ -1489,21 +946,25 @@ class SsrBaseArtifactBuilder {
1489
946
  androidSha256CertFingerprints: target.android?.sha256CertFingerprints
1490
947
  }))
1491
948
  };
1492
- await Bun.write(path8.join(this.#absArtifactDir, "base-artifact.json"), `${JSON.stringify(artifact, null, 2)}
949
+ await Bun.write(path7.join(this.#absArtifactDir, "base-artifact.json"), `${JSON.stringify(artifact, null, 2)}
1493
950
  `);
1494
951
  this.#app.verbose(`[base-artifact] complete in ${Date.now() - this.#started}ms`);
1495
- return { artifact, seedIndex, cssCompiler, optimizedFonts };
952
+ return { artifact, seedIndex, cssCompiler, optimizedFonts, runtimeChunks };
1496
953
  }
1497
954
  async#buildRuntimeClientEntries() {
1498
955
  const akanServerPath = await this.#resolveAkanServerPath();
1499
- const rscClientEntry = path8.resolve(akanServerPath, "rscClient.tsx");
1500
- const rscSegmentOutletEntry = path8.resolve(akanServerPath, "rscSegmentOutlet.tsx");
1501
- const vendorEntries = VENDOR_SPECIFIERS.map((specifier) => ({
1502
- specifier,
1503
- absPath: path8.resolve(akanServerPath, "vendor", `${specifier.replaceAll("/", "-").replaceAll(".", "-")}.ts`)
1504
- }));
956
+ const rscClientEntry = path7.resolve(akanServerPath, "rscClient.tsx");
957
+ const rscSegmentOutletEntry = path7.resolve(akanServerPath, "rscSegmentOutlet.tsx");
958
+ const vendorEntries = VendorNarrowing.entriesIn(akanServerPath);
1505
959
  const entries = [rscClientEntry, rscSegmentOutletEntry, ...vendorEntries.map((v) => v.absPath)];
1506
- const clientBundle = await new ClientEntriesBundler({ app: this.#app, entries, command: this.#command }).bundle();
960
+ const narrowing = new VendorNarrowing(path7.dirname(akanServerPath), this.#vendorExports);
961
+ const clientBundle = await new ClientEntriesBundler({
962
+ app: this.#app,
963
+ entries,
964
+ command: this.#command,
965
+ entryExports: narrowing.entryExports(vendorEntries),
966
+ plugins: await narrowing.plugins()
967
+ }).bundle();
1507
968
  const ssrBundle = await new ClientEntriesBundler({
1508
969
  app: this.#app,
1509
970
  entries: [rscSegmentOutletEntry],
@@ -1527,25 +988,30 @@ class SsrBaseArtifactBuilder {
1527
988
  };
1528
989
  const vendorMap = Object.fromEntries(vendorEntries.map(({ specifier, absPath }) => [specifier, clientBundle.entryUrlsByAbsPath.get(absPath) ?? ""]));
1529
990
  this.#app.verbose(`[base-artifact] rscClientUrl=${rscClientUrl} vendors=${Object.keys(vendorMap).length}`);
991
+ const chunksOf = (absPath) => clientBundle.entryChunkUrlsByAbsPath.get(absPath) ?? [];
1530
992
  return {
1531
993
  rscClientUrl,
1532
994
  rscRuntimeClientManifest: clientBundle.manifest,
1533
995
  rscRuntimeSsrManifest,
1534
- vendorMap
996
+ vendorMap,
997
+ runtimeChunks: {
998
+ runtime: [...new Set([...chunksOf(rscClientEntry), ...chunksOf(rscSegmentOutletEntry)])],
999
+ vendors: Object.fromEntries(vendorEntries.map(({ specifier, absPath }) => [specifier, chunksOf(absPath)]))
1000
+ }
1535
1001
  };
1536
1002
  }
1537
1003
  async#resolveAkanServerPath() {
1538
1004
  const candidates = [];
1539
1005
  try {
1540
- candidates.push(path8.dirname(Bun.resolveSync("akanjs/server", this.#app.workspace.workspaceRoot)));
1006
+ candidates.push(path7.dirname(Bun.resolveSync("akanjs/server", this.#app.workspace.workspaceRoot)));
1541
1007
  } catch {}
1542
- candidates.push(path8.join(this.#app.workspace.workspaceRoot, "pkgs/akanjs/server"), path8.join(this.#app.workspace.workspaceRoot, "node_modules/akanjs/server"));
1008
+ candidates.push(path7.join(this.#app.workspace.workspaceRoot, "pkgs/akanjs/server"), path7.join(this.#app.workspace.workspaceRoot, "node_modules/akanjs/server"));
1543
1009
  try {
1544
- candidates.push(path8.dirname(Bun.resolveSync("akanjs/server", path8.dirname(Bun.main))));
1010
+ candidates.push(path7.dirname(Bun.resolveSync("akanjs/server", path7.dirname(Bun.main))));
1545
1011
  } catch {}
1546
- candidates.push(path8.join(path8.dirname(Bun.main), "node_modules/akanjs/server"), path8.join(path8.dirname(Bun.main), "../../akanjs/server"), path8.resolve(import.meta.dir, "../../server"), path8.resolve(import.meta.dir, "../server"));
1012
+ candidates.push(path7.join(path7.dirname(Bun.main), "node_modules/akanjs/server"), path7.join(path7.dirname(Bun.main), "../../akanjs/server"), path7.resolve(import.meta.dir, "../../server"), path7.resolve(import.meta.dir, "../server"));
1547
1013
  for (const candidate of candidates) {
1548
- if (await Bun.file(path8.join(candidate, "rscClient.tsx")).exists())
1014
+ if (await Bun.file(path7.join(candidate, "rscClient.tsx")).exists())
1549
1015
  return candidate;
1550
1016
  }
1551
1017
  throw new Error(`[base-artifact] failed to locate akanjs/server; looked in: ${candidates.join(", ")}`);
@@ -1574,7 +1040,7 @@ ${preparedCssText}`).toString(36);
1574
1040
  `styles/${cssAssetName}-${cssHash}.css`,
1575
1041
  `/_akan/styles/${cssAssetName}-${cssHash}.css`
1576
1042
  ];
1577
- await Bun.write(path8.join(this.#absArtifactDir, cssRelPath), preparedCssText);
1043
+ await Bun.write(path7.join(this.#absArtifactDir, cssRelPath), preparedCssText);
1578
1044
  SsrBaseArtifactBuilder.#warnDroppedImports(this.#app, cssRelPath, preparedCssText, imported);
1579
1045
  this.#app.verbose(`[base-artifact] wrote ${preparedCssText.length} bytes of CSS for ${basePath} -> ${cssRelPath}`);
1580
1046
  return [basePath, { cssUrl, cssRelPath }];
@@ -1590,4 +1056,91 @@ ${preparedCssText}`).toString(36);
1590
1056
  }
1591
1057
  }
1592
1058
  }
1593
- export { AllRoutesBuilder, CssCompiler, FontOptimizer, FontPruner, precompressArtifacts, SsrBaseArtifactBuilder };
1059
+ // pkgs/@akanjs/devkit/frontendBuild/vendorImportScanner.ts
1060
+ import fs3 from "fs";
1061
+ import path8 from "path";
1062
+ import ts from "typescript";
1063
+
1064
+ class VendorImportScanner {
1065
+ #specifiers;
1066
+ #names = new Map;
1067
+ #whole = new Set;
1068
+ constructor(specifiers) {
1069
+ this.#specifiers = new Set(specifiers);
1070
+ for (const specifier of specifiers)
1071
+ this.#names.set(specifier, new Set);
1072
+ }
1073
+ static async exportsUsedIn(dir, specifiers) {
1074
+ const scanner = new VendorImportScanner(specifiers);
1075
+ if (!fs3.existsSync(dir))
1076
+ return scanner.usedExports();
1077
+ for await (const relative of new Bun.Glob("**/*.js").scan({ cwd: dir }))
1078
+ scanner.scan(await Bun.file(path8.join(dir, relative)).text(), relative);
1079
+ return scanner.usedExports();
1080
+ }
1081
+ scan(source, fileName = "chunk.js") {
1082
+ if (![...this.#specifiers].some((specifier) => source.includes(specifier)))
1083
+ return this;
1084
+ const file = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, false, ts.ScriptKind.JS);
1085
+ const visit = (node) => {
1086
+ if (ts.isImportDeclaration(node))
1087
+ this.#readImport(node);
1088
+ else if (ts.isExportDeclaration(node))
1089
+ this.#readExport(node);
1090
+ else if (ts.isCallExpression(node))
1091
+ this.#readCall(node);
1092
+ ts.forEachChild(node, visit);
1093
+ };
1094
+ visit(file);
1095
+ return this;
1096
+ }
1097
+ usedExports() {
1098
+ return Object.fromEntries([...this.#names].filter(([specifier]) => !this.#whole.has(specifier)).map(([specifier, names]) => [specifier, [...names].sort()]));
1099
+ }
1100
+ #specifierOf(node) {
1101
+ if (!node || !ts.isStringLiteralLike(node))
1102
+ return null;
1103
+ return this.#specifiers.has(node.text) ? node.text : null;
1104
+ }
1105
+ #readImport(node) {
1106
+ const specifier = this.#specifierOf(node.moduleSpecifier);
1107
+ const clause = node.importClause;
1108
+ if (!specifier || !clause)
1109
+ return;
1110
+ if (clause.name)
1111
+ this.#add(specifier, "default");
1112
+ const bindings = clause.namedBindings;
1113
+ if (!bindings)
1114
+ return;
1115
+ if (ts.isNamespaceImport(bindings))
1116
+ this.#whole.add(specifier);
1117
+ else
1118
+ for (const element of bindings.elements)
1119
+ this.#add(specifier, (element.propertyName ?? element.name).text);
1120
+ }
1121
+ #readExport(node) {
1122
+ const specifier = this.#specifierOf(node.moduleSpecifier);
1123
+ if (!specifier)
1124
+ return;
1125
+ const clause = node.exportClause;
1126
+ if (!clause || ts.isNamespaceExport(clause))
1127
+ this.#whole.add(specifier);
1128
+ else
1129
+ for (const element of clause.elements)
1130
+ this.#add(specifier, (element.propertyName ?? element.name).text);
1131
+ }
1132
+ #readCall(node) {
1133
+ if (node.expression.kind !== ts.SyntaxKind.ImportKeyword)
1134
+ return;
1135
+ const specifier = this.#specifierOf(node.arguments[0]);
1136
+ if (specifier)
1137
+ this.#whole.add(specifier);
1138
+ }
1139
+ #add(specifier, name) {
1140
+ if (!/^[A-Za-z_$][\w$]*$/.test(name))
1141
+ this.#whole.add(specifier);
1142
+ else
1143
+ this.#names.get(specifier)?.add(name);
1144
+ }
1145
+ }
1146
+ export { AllRoutesBuilder, CssCompiler, precompressArtifacts, SsrBaseArtifactBuilder, VendorImportScanner };