@akanjs/cli 3.2.0-rc.9 → 3.3.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 (143) hide show
  1. package/.build-stamp +2 -2
  2. package/CodeAgent-fx6088tv.js +11 -0
  3. package/{CodeTui-qstk5vpj.js → CodeTui-zee8atsr.js} +822 -666
  4. package/README.ko.md +7 -0
  5. package/README.md +7 -0
  6. package/TunnelShare-9ry4vh0y.js +18 -0
  7. package/agent.command-x65f2ags.js +61 -0
  8. package/akanCode.js +12 -12
  9. package/appExecutor-79azsb2w.js +11 -0
  10. package/{application.command-m4rq4wc2.js → application.command-azbd1pb2.js} +83 -37
  11. package/{applicationBuildRunner-df7rx3ra.js → applicationBuildRunner-trfxv3pd.js} +49 -18
  12. package/buildBatch.proc.js +25 -11
  13. package/{cloud.command-a0gy0qq2.js → cloud.command-gapp4634.js} +33 -29
  14. package/cloud.script-3b401efv.js +35 -0
  15. package/{code.command-5rsdqw8s.js → code.command-5smx61yf.js} +13 -9
  16. package/context.command-ym5jbkny.js +64 -0
  17. package/context.runner-kctbfsde.js +34 -0
  18. package/{dependencyScanner-78sq8m4q.js → dependencyScanner-ge10gb52.js} +2 -2
  19. package/{devTui-h77zrjv5.js → devTui-rf374y2w.js} +1 -1
  20. package/{fileSys-zpvt5gtf.js → fileSys-q22646yc.js} +1 -1
  21. package/{guideline.command-mffxknbr.js → guideline.command-zwypaqsh.js} +9 -5
  22. package/guidelines/agentRule/agentRule.instruction.md +25 -9
  23. package/guidelines/akanApi/akanApi.instruction.md +6 -4
  24. package/guidelines/conventions/core.md +23 -5
  25. package/guidelines/conventions/rules/app.md +4 -1
  26. package/guidelines/conventions/rules/page.md +5 -4
  27. package/guidelines/conventions/rules/ts.md +3 -3
  28. package/guidelines/errorCodes/errorCodes.instruction.md +165 -0
  29. package/guidelines/fieldRule/fieldRule.instruction.md +2 -1
  30. package/guidelines/mcpRule/mcpRule.instruction.md +225 -5
  31. package/guidelines/pageRule/pageRule.instruction.md +10 -1
  32. package/guidelines/queryRule/queryRule.instruction.md +3 -1
  33. package/guidelines/runtimeRule/runtimeRule.instruction.md +14 -8
  34. package/guidelines/transportRule/transportRule.instruction.md +31 -1
  35. package/incrementalBuilder.proc.js +577 -411
  36. package/{index-w15mg3km.js → index-0dm25wvf.js} +1 -1
  37. package/{index-0gg15zwa.js → index-0s7w2085.js} +6 -6
  38. package/{index-hj6w4ka1.js → index-1p81ecbz.js} +1 -1
  39. package/{index-swwjakt0.js → index-275a4r3n.js} +11 -11
  40. package/{index-j6gc8n14.js → index-2jmvfa62.js} +11 -9
  41. package/{index-qd7xn2bk.js → index-2ny1e95c.js} +2 -2
  42. package/{index-exn38bzx.js → index-2yn3r67f.js} +116 -54
  43. package/{index-34792nh7.js → index-3txdtztz.js} +1 -1
  44. package/{index-28x1aszt.js → index-41a03gkj.js} +149 -53
  45. package/{index-2mf1aen9.js → index-4ss4gkv3.js} +2 -2
  46. package/{index-an76bdrv.js → index-612fdtbk.js} +1 -1
  47. package/{index-5radqwn2.js → index-67sd09ag.js} +12 -12
  48. package/{index-0hbtve0a.js → index-6dzjer7p.js} +32 -28
  49. package/{index-3ghdb7p5.js → index-71y6176j.js} +2777 -3676
  50. package/{index-xyn02k0w.js → index-78y75t0a.js} +662 -433
  51. package/index-7wf8snar.js +80 -0
  52. package/{index-skmtj8rm.js → index-8jtqfye2.js} +27 -10
  53. package/{index-2mrn1mrg.js → index-9f3reh2y.js} +1 -1
  54. package/{index-nmvhjn8c.js → index-9wh04mqy.js} +93 -82
  55. package/{index-xvk2a75m.js → index-a860mx0m.js} +3 -3
  56. package/{index-5zwr4n6k.js → index-baccvws5.js} +65 -8
  57. package/{index-yf9wc28h.js → index-bejy9zyc.js} +1 -1
  58. package/{index-bns3wcpc.js → index-by2tvsq6.js} +1 -1
  59. package/{index-r0a604h4.js → index-c669pbyb.js} +5 -4
  60. package/{index-x40bdsca.js → index-dadwp2aw.js} +33 -98
  61. package/{index-vm0dn0mt.js → index-dmcpetwe.js} +200 -138
  62. package/{index-43f4h4cm.js → index-ebn9kgea.js} +6 -6
  63. package/{index-hqv34wzq.js → index-gt8phqpt.js} +10 -10
  64. package/{index-yckz5t8b.js → index-h901f24n.js} +516 -434
  65. package/{index-j3v29pq7.js → index-j0wr4e32.js} +219 -175
  66. package/{index-gcx48get.js → index-j592zfqc.js} +2 -2
  67. package/{index-grxs6fts.js → index-j6jjmn2r.js} +57 -31
  68. package/{index-w8yasvpc.js → index-jek2re5k.js} +2136 -2175
  69. package/{index-ny2k80mv.js → index-jf4vk1s0.js} +9 -2
  70. package/{index-gxav1bjz.js → index-k6vwww45.js} +9 -9
  71. package/{index-99qvtff2.js → index-kfvjzk8r.js} +5 -5
  72. package/{index-j6eeh5d7.js → index-knpm8sdm.js} +5 -5
  73. package/{index-2r9ff9qm.js → index-nc3br31y.js} +2 -2
  74. package/{index-35j83zkd.js → index-p5zh7pmc.js} +2 -2
  75. package/{index-cmg5ngqa.js → index-p7beqww9.js} +2 -2
  76. package/{index-b4qq3rq0.js → index-rwgqba9p.js} +1 -1
  77. package/{index-rfzp4pqs.js → index-s885g0jj.js} +3 -3
  78. package/{index-9p260r4e.js → index-trffs83s.js} +538 -250
  79. package/{index-k92x3vne.js → index-v7ajmsh3.js} +1 -1
  80. package/index-w1zexzpx.js +127 -0
  81. package/{index-h7hehkw6.js → index-xczjdng6.js} +3 -1
  82. package/{index-39jz41jb.js → index-xs9a3ddt.js} +3 -3
  83. package/{index-rp4yf32g.js → index-xwwex8rf.js} +36 -29
  84. package/{index-ra9fvn7s.js → index-ybcb9wc8.js} +74 -38
  85. package/index-z92zm3wd.js +788 -0
  86. package/{index-j9790rhk.js → index-z96ks033.js} +1509 -1121
  87. package/index-zfnz878d.js +30 -0
  88. package/{index-2vgv7fs7.js → index-zmd9xxgd.js} +727 -693
  89. package/{index-ygdbn9jn.js → index-zyb0ebm4.js} +1 -1
  90. package/index.js +28 -24
  91. package/libExecutor-jc6f8hm6.js +10 -0
  92. package/{library.command-bmd7zc5m.js → library.command-nxvesvhb.js} +12 -5
  93. package/{localRegistry.command-y6en1599.js → localRegistry.command-xz62e4ng.js} +29 -24
  94. package/{module.command-7exfffqw.js → module.command-aaws9byg.js} +11 -7
  95. package/{package.command-adskw2rj.js → package.command-j7hv26p0.js} +14 -10
  96. package/package.json +8 -8
  97. package/{page.command-dw01272p.js → page.command-7yffs7n9.js} +8 -4
  98. package/{pipeline.command-0b1r3y5r.js → pipeline.command-7yk0zcng.js} +15 -9
  99. package/pkgExecutor-arxmvx4t.js +10 -0
  100. package/{primitive.command-byw6vc04.js → primitive.command-7a1pt715.js} +12 -8
  101. package/{projectTypecheck-kkrpq60a.js → projectTypecheck-f4qhbecd.js} +1 -1
  102. package/{prompter-qrwx1p17.js → prompter-qyggfhqd.js} +2 -2
  103. package/{quality.command-6rqnhzct.js → quality.command-c6mvrjh1.js} +25 -16
  104. package/{recipeScanner-4b69ybe0.js → recipeScanner-rrx69awy.js} +1 -1
  105. package/{repair.command-rw5zymak.js → repair.command-093adzt9.js} +12 -8
  106. package/{routeSourceValidator-4h947v7c.js → routeSourceValidator-8n6j1vn7.js} +4 -2
  107. package/{scalar.command-2dyp9nh9.js → scalar.command-2ex84spb.js} +10 -6
  108. package/skills/akan-debug/SKILL.md +8 -5
  109. package/skills/akan-err/SKILL.md +7 -0
  110. package/skills/akan-mcp/SKILL.md +19 -1
  111. package/skills/akan-scaffold/SKILL.md +1 -1
  112. package/skills/akan-validate/SKILL.md +3 -3
  113. package/{subspace.command-111ynwv1.js → subspace.command-4n4n4jpv.js} +32 -24
  114. package/templates/app/page/_layout.tsx +13 -0
  115. package/templates/app/page/styles.css.template +40 -0
  116. package/templates/appSample/page/_index.tsx +9 -9
  117. package/templates/appSample/page/_layout.tsx +1 -0
  118. package/templates/appSample/page/styles.css.template +40 -5
  119. package/templates/appSample/ui/Recipe/jellyButton.ts +1 -1
  120. package/templates/biomeForm.ts +1 -1
  121. package/templates/env/_env.server.type.ts +1 -1
  122. package/templates/facetIndex/index.ts +2 -37
  123. package/templates/lib/sig.ts +0 -4
  124. package/templates/lib/useClient.ts +1 -1
  125. package/templates/workspaceRoot/.devcontainer/devcontainer.json.template +1 -1
  126. package/templates/workspaceRoot/AGENTS.md.template +2 -1
  127. package/templates/workspaceRoot/README.ts +4 -2
  128. package/{tunnel.command-2gcpfbdj.js → tunnel.command-f7ep1qfa.js} +17 -13
  129. package/{typeChecker-s640r6c0.js → typeChecker-7jt6abrs.js} +1 -1
  130. package/typecheck.proc.js +3 -2
  131. package/{verify.command-djgs86ma.js → verify.command-zrkxnvct.js} +21 -17
  132. package/{workflow.command-n0k2mxr5.js → workflow.command-ks16jegk.js} +21 -14
  133. package/{workspace.command-fh1qwxfx.js → workspace.command-ahhfpaag.js} +60 -54
  134. package/CodeAgent-x2p3a3e0.js +0 -11
  135. package/TunnelShare-c4xsfzg5.js +0 -15
  136. package/agent.command-9et2e27p.js +0 -52
  137. package/cloud.script-xze4zh7n.js +0 -31
  138. package/context.command-rk1dwrg4.js +0 -57
  139. package/context.runner-83ky5m1b.js +0 -30
  140. /package/templates/{appSample → app}/public/fonts/Pretendard-Bold.woff2 +0 -0
  141. /package/templates/{appSample → app}/public/fonts/Pretendard-Medium.woff2 +0 -0
  142. /package/templates/{appSample → app}/public/fonts/Pretendard-Regular.woff2 +0 -0
  143. /package/templates/{appSample → app}/public/fonts/Pretendard-SemiBold.woff2 +0 -0
@@ -1,11 +1,8 @@
1
1
  // @bun
2
- import {
3
- FileSys2
4
- } from "./index-bns3wcpc.js";
5
2
  import {
6
3
  SOURCE_EXTS,
7
4
  WatchRootResolver
8
- } from "./index-vm0dn0mt.js";
5
+ } from "./index-dmcpetwe.js";
9
6
  import {
10
7
  loaderFor,
11
8
  BarrelAnalyzer,
@@ -21,2010 +18,2294 @@ import {
21
18
  CsrDevPaths,
22
19
  PagesEntrySourceGenerator,
23
20
  PagesBundleBuilder
24
- } from "./index-nmvhjn8c.js";
21
+ } from "./index-9wh04mqy.js";
22
+ import {
23
+ FileSys2
24
+ } from "./index-by2tvsq6.js";
25
25
  import {
26
26
  AsyncDefaultExportDetector,
27
27
  StoreBootstrap,
28
28
  resolveSsrPageEntriesForApp
29
- } from "./index-3ghdb7p5.js";
29
+ } from "./index-z92zm3wd.js";
30
30
 
31
- // pkgs/@akanjs/devkit/frontendBuild/autoImportSync.ts
32
- import { readdir, readFile, stat } from "fs/promises";
31
+ // pkgs/@akanjs/devkit/frontendBuild/clientEntryDiscovery.ts
32
+ import fs from "fs";
33
33
  import path from "path";
34
- import ts from "typescript";
35
- var TEST_FILE_RE = /\.(test|spec)\.(ts|tsx)$/;
36
- var AKAN_BASE = {
37
- names: ["Int", "Float", "ID", "Any", "Upload", "enumOf", "dayjs"],
38
- specifier: "akanjs/base",
39
- kind: "named"
40
- };
41
- var AKAN_BASE_TYPES = { names: ["Dayjs"], specifier: "akanjs/base", kind: "named", typeOnly: true };
42
- var CNST_NS = { names: ["cnst"], specifier: "../cnst", kind: "namespace" };
43
- var DB_NS = { names: ["db"], specifier: "../db", kind: "namespace" };
44
- var SRV_NS = { names: ["srv"], specifier: "../srv", kind: "namespace" };
45
- var ERR_DICT = { names: ["Err"], specifier: "../dict", kind: "named" };
46
- var RULES = {
47
- constant: [AKAN_BASE, AKAN_BASE_TYPES, { names: ["via"], specifier: "akanjs/constant", kind: "named" }],
48
- document: [
49
- AKAN_BASE,
50
- AKAN_BASE_TYPES,
51
- CNST_NS,
52
- DB_NS,
53
- ERR_DICT,
54
- {
55
- names: ["by", "from", "into", "SchemaOf", "DataInputOf", "DocumentUpdateHelper", "documentQueryHelper", "Mdl"],
56
- specifier: "akanjs/document",
57
- kind: "named"
58
- }
59
- ],
60
- service: [
61
- AKAN_BASE,
62
- AKAN_BASE_TYPES,
63
- DB_NS,
64
- SRV_NS,
65
- CNST_NS,
66
- ERR_DICT,
67
- { names: ["serve"], specifier: "akanjs/service", kind: "named" },
68
- {
69
- names: ["DataInputOf", "ListQueryOption", "DatabaseRegistry", "getFilterInfoByKey"],
70
- specifier: "akanjs/document",
71
- kind: "named"
72
- }
73
- ],
74
- signal: [
75
- AKAN_BASE,
76
- AKAN_BASE_TYPES,
77
- SRV_NS,
78
- CNST_NS,
79
- ERR_DICT,
80
- {
81
- names: ["endpoint", "internal", "slice", "Public", "Req", "Ws", "None", "Res"],
82
- specifier: "akanjs/signal",
83
- kind: "named"
84
- }
85
- ],
86
- dictionary: [
87
- {
88
- names: ["modelDictionary", "scalarDictionary", "serviceDictionary"],
89
- specifier: "akanjs/dictionary",
90
- kind: "named"
91
- }
92
- ],
93
- srvkit: [
94
- AKAN_BASE,
95
- AKAN_BASE_TYPES,
96
- { names: ["Logger", "HttpClient", "sleep"], specifier: "akanjs/common", kind: "named" },
97
- { names: ["adapt"], specifier: "akanjs/service", kind: "named" },
98
- { names: ["SignalContext", "Guard", "InternalArg", "Middleware"], specifier: "akanjs/signal", kind: "named" }
99
- ],
100
- common: [AKAN_BASE, AKAN_BASE_TYPES],
101
- store: [
102
- CNST_NS,
103
- { names: ["store"], specifier: "akanjs/store", kind: "named" },
104
- { names: ["fetch", "usePage", "sig"], specifier: "../useClient", kind: "named" },
105
- { names: ["st"], specifier: "../st", kind: "named" },
106
- { names: ["RootStore"], specifier: "../st", kind: "named", typeOnly: true }
107
- ],
108
- client: [
109
- {
110
- names: ["cnst", "fetch", "st", "usePage"],
111
- specifier: (ctx) => `@${ctx.scope}/${ctx.project}/client`,
112
- kind: "named"
113
- }
114
- ]
115
- };
116
- var PASCAL_CASE_RE = /^[A-Z][A-Za-z0-9]*$/;
117
- var DOMAIN_ROLE_KINDS = {
118
- constant: ["constant"],
119
- dictionary: ["constant", "document", "signal"],
120
- common: ["constant"]
121
- };
122
- var LIB_BARRELS = {
123
- Err: { barrel: "dict", kind: "named" },
124
- db: { barrel: "db", kind: "namespace" },
125
- cnst: { barrel: "cnst", kind: "namespace" },
126
- srv: { barrel: "srv", kind: "namespace" }
127
- };
128
- var GLOBAL_NAMES = new Set(["fetch"]);
129
- var DOMAIN_DENYLIST = new Set([
130
- "Map",
131
- "Set",
132
- "WeakMap",
133
- "WeakSet",
134
- "Date",
135
- "Promise",
136
- "Array",
137
- "Object",
138
- "Error",
139
- "TypeError",
140
- "RangeError",
141
- "RegExp",
142
- "Symbol",
143
- "Proxy",
144
- "Reflect",
145
- "JSON",
146
- "Math",
147
- "Number",
148
- "BigInt",
149
- "Function",
150
- "Boolean",
151
- "String",
152
- "Record",
153
- "Partial",
154
- "Required",
155
- "Readonly",
156
- "Pick",
157
- "Omit",
158
- "Exclude",
159
- "Extract",
160
- "NonNullable",
161
- "ReturnType",
162
- "Parameters",
163
- "Awaited",
164
- "InstanceType"
165
- ]);
34
+ var USE_CLIENT_RE = /^\s*(?:\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/\s*|\/\/[^\n]*\n\s*)*["']use client["']/;
35
+ var NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
36
+ var AKANJS_NODE_MODULE_RE = /[\\/]node_modules[\\/]akanjs[\\/]/;
37
+ var NON_SOURCE_EXT_RE = /\.(css|scss|sass|less|json|svg|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf|mp3|mp4|wav)$/i;
38
+ var exportsKeyOf = (map) => JSON.stringify(map ? [...map].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0) : null);
39
+ var shouldSkipNodeModule = (absPath) => NODE_MODULES_RE.test(absPath) && !AKANJS_NODE_MODULE_RE.test(absPath);
166
40
 
167
- class AutoImportSync {
168
- #workspaceRoot;
169
- #domainCache = new Map;
170
- constructor({ workspaceRoot }) {
171
- this.#workspaceRoot = path.resolve(workspaceRoot);
41
+ class GraphClientEntryDiscovery {
42
+ #akanConfig;
43
+ #resolvePackage;
44
+ #analyzer;
45
+ #tsTranspiler = new Bun.Transpiler({ loader: "tsx" });
46
+ #fileExistsCache = new Map;
47
+ #factsCache = new Map;
48
+ #resolvedFileCache = new Map;
49
+ #resolvedSpecifierCache = new Map;
50
+ #reachableEntriesCache = new Map;
51
+ #swappedEntriesCaches = new WeakMap;
52
+ #readFiles = new Set;
53
+ #barrelImporters = new Map;
54
+ #reread = new Map;
55
+ #settled = Promise.resolve();
56
+ #epoch = 0;
57
+ constructor(akanConfig, resolvePackage) {
58
+ this.#akanConfig = akanConfig;
59
+ this.#resolvePackage = resolvePackage;
60
+ this.#analyzer = new BarrelAnalyzer({ resolvePackage });
172
61
  }
173
- async syncForBatch(files) {
174
- const changedFiles = [];
175
- const errors = [];
176
- const seen = new Set;
177
- for (const file of files) {
178
- const pkgRoot = this.#domainPkgRootOf(file);
179
- if (pkgRoot)
180
- this.#domainCache.delete(pkgRoot);
181
- }
182
- for (const file of files) {
183
- const abs = path.resolve(file);
184
- if (seen.has(abs))
185
- continue;
186
- seen.add(abs);
187
- const ctx = this.#contextFor(abs);
188
- if (!ctx)
189
- continue;
190
- try {
191
- const changed = await this.#syncFile(abs, ctx);
192
- if (changed)
193
- changedFiles.push(abs);
194
- } catch (err) {
195
- errors.push(`[auto-import] sync failed for ${file}: ${formatError(err)}`);
196
- }
62
+ static async create(app) {
63
+ return new GraphClientEntryDiscovery(await app.getConfig(), await createTsconfigPackageResolver(app));
64
+ }
65
+ async discover(seeds, { importsAs } = {}) {
66
+ this.#settled = this.#settled.then(() => this.#dropRenarrowed());
67
+ await this.#settled;
68
+ const entries = new Set;
69
+ const reachable = importsAs ? this.#swappedEntriesCache(importsAs) : this.#reachableEntriesCache;
70
+ for (const seed of seeds) {
71
+ const walk = { visiting: new Set, partial: new Set, memo: new Map, importsAs, reachable };
72
+ for (const entry of await this.#discoverFromFile(seed, walk))
73
+ entries.add(entry);
197
74
  }
198
- return { changedFiles, errors };
75
+ return Array.from(entries).sort();
199
76
  }
200
- #contextFor(abs) {
201
- const rel = path.relative(this.#workspaceRoot, abs);
202
- if (rel.startsWith("..") || path.isAbsolute(rel))
203
- return null;
204
- const base = path.basename(abs);
205
- if (TEST_FILE_RE.test(base) || base === "index.ts" || base === "index.tsx" || base.endsWith(".d.ts"))
206
- return null;
207
- const parts = rel.split(path.sep).filter(Boolean);
208
- const [scope, project, facet] = parts;
209
- if (scope !== "apps" && scope !== "libs" || !project || !facet)
210
- return null;
211
- if (facet === "lib" && parts[3] === "__lib")
212
- return null;
213
- const role = roleFor(facet, base);
214
- if (!role)
215
- return null;
216
- return { role, scope, project };
77
+ async resolveImport(spec, importerDir) {
78
+ const resolved = await this.#resolveSpecifier(spec, importerDir);
79
+ return resolved ? path.resolve(resolved) : null;
217
80
  }
218
- async#syncFile(abs, ctx) {
219
- const stats = await stat(abs).catch(() => null);
220
- if (!stats?.isFile())
221
- return false;
222
- const source = await readFile(abs, "utf8");
223
- const resolveExtra = await this.#extraResolverFor(abs, ctx);
224
- const next = transformSource(source, abs, ctx, resolveExtra);
225
- if (next === null || next === source)
226
- return false;
227
- await FileSys2.writeTextAtomic(abs, next);
228
- return true;
81
+ #swappedEntriesCache(importsAs) {
82
+ const cache = this.#swappedEntriesCaches.get(importsAs) ?? new Map;
83
+ this.#swappedEntriesCaches.set(importsAs, cache);
84
+ return cache;
229
85
  }
230
- async#extraResolverFor(abs, ctx) {
231
- const resolvers = [];
232
- if (ctx.role === "srvkit" || ctx.role === "common")
233
- resolvers.push(await this.#libBarrelResolver(abs, ctx));
234
- const kinds = DOMAIN_ROLE_KINDS[ctx.role];
235
- if (kinds)
236
- resolvers.push(await this.#domainResolver(abs, ctx, kinds));
237
- if (resolvers.length === 0)
86
+ invalidate(files) {
87
+ if (files.length === 0)
238
88
  return;
239
- return (symbol) => {
240
- for (const resolve of resolvers) {
241
- const target = resolve(symbol);
242
- if (target)
243
- return target;
244
- }
245
- return null;
246
- };
247
- }
248
- async#domainResolver(abs, ctx, kinds) {
249
- const index = await this.#domainIndex(path.join(this.#workspaceRoot, ctx.scope, ctx.project));
250
- const fileDir = path.dirname(abs);
251
- return (symbol) => {
252
- if (!PASCAL_CASE_RE.test(symbol) || DOMAIN_DENYLIST.has(symbol))
253
- return null;
254
- const entries = (index.get(symbol) ?? []).filter((entry) => kinds.includes(entry.kind));
255
- if (entries.length !== 1)
256
- return null;
257
- return { specifier: relativeSpecifier(fileDir, entries[0].file), kind: "named" };
258
- };
89
+ let moved = false;
90
+ for (const file of files) {
91
+ const absPath = path.resolve(file);
92
+ const exists = fs.existsSync(absPath);
93
+ if (exists !== this.#readFiles.has(absPath))
94
+ moved = true;
95
+ if (!exists)
96
+ this.#readFiles.delete(absPath);
97
+ this.#factsCache.delete(absPath);
98
+ this.#fileExistsCache.delete(absPath);
99
+ }
100
+ this.#epoch += 1;
101
+ this.#reachableEntriesCache.clear();
102
+ this.#swappedEntriesCaches = new WeakMap;
103
+ for (const [barrel, before] of this.#analyzer.forget(files))
104
+ if (!this.#reread.has(barrel))
105
+ this.#reread.set(barrel, before);
106
+ if (!moved)
107
+ return;
108
+ this.#fileExistsCache.clear();
109
+ this.#resolvedFileCache.clear();
110
+ this.#resolvedSpecifierCache.clear();
259
111
  }
260
- async#libBarrelResolver(abs, ctx) {
261
- const fileDir = path.dirname(abs);
262
- const libDir = path.join(this.#workspaceRoot, ctx.scope, ctx.project, "lib");
263
- const available = new Map;
264
- for (const [symbol, { barrel, kind }] of Object.entries(LIB_BARRELS)) {
265
- if (await fileExists(path.join(libDir, `${barrel}.ts`)))
266
- available.set(symbol, { specifier: relativeSpecifier(fileDir, path.join(libDir, barrel)), kind });
112
+ async#dropRenarrowed() {
113
+ const reread = [...this.#reread];
114
+ this.#reread.clear();
115
+ for (const [barrel, before] of reread) {
116
+ const [was, now] = await Promise.all([before, this.#analyzer.analyze(barrel)]);
117
+ if (exportsKeyOf(was) === exportsKeyOf(now))
118
+ continue;
119
+ for (const importer of this.#barrelImporters.get(barrel) ?? [])
120
+ this.#factsCache.delete(importer);
267
121
  }
268
- return (symbol) => available.get(symbol) ?? null;
269
122
  }
270
- async#domainIndex(pkgRoot) {
271
- const cached = this.#domainCache.get(pkgRoot);
272
- if (cached)
273
- return cached;
274
- const index = await buildDomainIndex(path.join(pkgRoot, "lib"));
275
- this.#domainCache.set(pkgRoot, index);
276
- return index;
123
+ #lookup(cache, key, run, isFound) {
124
+ const cached = cache.get(key);
125
+ if (cached && (cached.found || cached.epoch === this.#epoch))
126
+ return cached.promise;
127
+ const entry = { epoch: this.#epoch, promise: run() };
128
+ entry.promise.then((value) => {
129
+ entry.found = isFound(value);
130
+ }, () => {
131
+ entry.found = false;
132
+ });
133
+ cache.set(key, entry);
134
+ return entry.promise;
277
135
  }
278
- #domainPkgRootOf(file) {
279
- const rel = path.relative(this.#workspaceRoot, path.resolve(file));
280
- if (rel.startsWith("..") || path.isAbsolute(rel))
281
- return null;
282
- const [scope, project, facet] = rel.split(path.sep).filter(Boolean);
283
- if (scope !== "apps" && scope !== "libs" || !project || facet !== "lib")
284
- return null;
285
- if (!domainKindOf(path.basename(file)))
286
- return null;
287
- return path.join(this.#workspaceRoot, scope, project);
136
+ async#fileExists(p) {
137
+ const absPath = path.resolve(p);
138
+ return await this.#lookup(this.#fileExistsCache, absPath, () => Bun.file(absPath).exists(), (exists) => exists);
288
139
  }
289
- }
290
- var roleFor = (facet, base) => {
291
- if (facet === "lib") {
292
- if (base.endsWith(".constant.ts"))
293
- return "constant";
294
- if (base.endsWith(".document.ts"))
295
- return "document";
296
- if (base.endsWith(".service.ts"))
297
- return "service";
298
- if (base.endsWith(".signal.ts"))
299
- return "signal";
300
- if (base.endsWith(".dictionary.ts"))
301
- return "dictionary";
302
- if (base.endsWith(".store.ts"))
303
- return "store";
304
- if (base.endsWith(".tsx"))
305
- return "client";
306
- return null;
140
+ #facts(file) {
141
+ const absPath = path.resolve(file);
142
+ let cached = this.#factsCache.get(absPath);
143
+ if (!cached) {
144
+ cached = (async () => {
145
+ const content = await Bun.file(absPath).text().catch(() => null);
146
+ if (content === null)
147
+ return null;
148
+ this.#readFiles.add(absPath);
149
+ if (USE_CLIENT_RE.test(content))
150
+ return { isClientEntry: true, imports: [] };
151
+ return { isClientEntry: false, imports: this.#scanImports(await this.#rewrite(content, absPath)) };
152
+ })();
153
+ this.#factsCache.set(absPath, cached);
154
+ }
155
+ return cached;
307
156
  }
308
- if (facet === "ui" || facet === "page")
309
- return base.endsWith(".tsx") ? "client" : null;
310
- if (facet === "webkit")
311
- return base.endsWith(".ts") || base.endsWith(".tsx") ? "client" : null;
312
- if (facet === "srvkit")
313
- return base.endsWith(".ts") ? "srvkit" : null;
314
- if (facet === "common")
315
- return base.endsWith(".ts") || base.endsWith(".tsx") ? "common" : null;
316
- return null;
317
- };
318
- var targetFor = (symbol, ctx) => {
319
- for (const rule of RULES[ctx.role]) {
320
- if (!rule.names.includes(symbol))
321
- continue;
322
- const specifier = typeof rule.specifier === "function" ? rule.specifier(ctx) : rule.specifier;
323
- return { specifier, kind: rule.kind, typeOnly: rule.typeOnly };
157
+ async#rewrite(content, absPath) {
158
+ if (this.#akanConfig.barrelImports.length === 0)
159
+ return content;
160
+ for (const barrel of this.#akanConfig.barrelImports.filter((barrel) => content.includes(barrel)))
161
+ this.#barrelImporters.set(barrel, (this.#barrelImporters.get(barrel) ?? new Set).add(absPath));
162
+ try {
163
+ return await rewriteBarrelImports(content, this.#akanConfig.barrelImports, this.#analyzer) ?? content;
164
+ } catch {
165
+ return content;
166
+ }
324
167
  }
325
- return null;
326
- };
327
- var transformSource = (source, fileName, ctx, resolveExtra) => {
328
- const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, scriptKindFor(fileName));
329
- const bound = collectBoundNames(sf);
330
- const used = collectUsedReferences(sf);
331
- const bareGlobals = collectBareGlobalReferences(sf);
332
- const namedBySpecifier = new Map;
333
- const namespaceImports = [];
334
- for (const name of used) {
335
- if (bound.has(name) || bareGlobals.has(name))
336
- continue;
337
- const target = targetFor(name, ctx) ?? resolveExtra?.(name) ?? null;
338
- if (!target)
339
- continue;
340
- if (target.kind === "namespace")
341
- namespaceImports.push({ name, specifier: target.specifier });
342
- else {
343
- const names = namedBySpecifier.get(target.specifier) ?? new Map;
344
- names.set(name, target.typeOnly ?? false);
345
- namedBySpecifier.set(target.specifier, names);
168
+ #scanImports(source) {
169
+ try {
170
+ return this.#tsTranspiler.scanImports(source);
171
+ } catch {
172
+ return [];
346
173
  }
347
174
  }
348
- if (namedBySpecifier.size === 0 && namespaceImports.length === 0)
349
- return null;
350
- const importDecls = sf.statements.filter(ts.isImportDeclaration);
351
- const anchor = importDecls.at(-1) ?? null;
352
- const namedImportsBySpecifier = collectExistingNamedImports(importDecls);
353
- const edits = [];
354
- const newStatements = [];
355
- for (const [specifier, names] of namedBySpecifier) {
356
- const existing = namedImportsBySpecifier.get(specifier);
357
- if (existing) {
358
- const merged = new Map(existing.names);
359
- for (const [name, isType] of names)
360
- if (!merged.has(name))
361
- merged.set(name, isType);
362
- edits.push({
363
- start: existing.decl.getStart(sf),
364
- end: existing.decl.getEnd(),
365
- text: formatNamedImport(specifier, merged)
366
- });
367
- } else
368
- newStatements.push(formatNamedImport(specifier, names));
175
+ async#resolveFileCandidate(absPathNoExt) {
176
+ const cacheKey = path.resolve(absPathNoExt);
177
+ return await this.#lookup(this.#resolvedFileCache, cacheKey, async () => {
178
+ if (await this.#fileExists(cacheKey))
179
+ return cacheKey;
180
+ for (const ext of SOURCE_EXTS) {
181
+ const f = `${cacheKey}${ext}`;
182
+ if (await this.#fileExists(f))
183
+ return f;
184
+ }
185
+ for (const ext of SOURCE_EXTS) {
186
+ const f = path.join(cacheKey, `index${ext}`);
187
+ if (await this.#fileExists(f))
188
+ return f;
189
+ }
190
+ return null;
191
+ }, (file) => file !== null);
369
192
  }
370
- for (const ns of namespaceImports)
371
- newStatements.push(`import * as ${ns.name} from "${ns.specifier}";`);
372
- if (newStatements.length > 0) {
373
- const anchorEdit = anchor ? edits.find((edit) => edit.start === anchor.getStart(sf)) : undefined;
374
- if (anchorEdit)
375
- anchorEdit.text = `${anchorEdit.text}
376
- ${newStatements.join(`
377
- `)}`;
378
- else if (anchor)
379
- edits.push({ start: anchor.getEnd(), end: anchor.getEnd(), text: `
380
- ${newStatements.join(`
381
- `)}` });
382
- else {
383
- const prologueEnd = directivePrologueEnd(sf);
384
- if (prologueEnd >= 0)
385
- edits.push({ start: prologueEnd, end: prologueEnd, text: `
386
- ${newStatements.join(`
387
- `)}` });
388
- else
389
- edits.push({ start: 0, end: 0, text: `${newStatements.join(`
390
- `)}
391
-
392
- ` });
393
- }
193
+ async#resolveSpecifier(spec, importerDir) {
194
+ const cacheKey = `${importerDir}\x00${spec}`;
195
+ return await this.#lookup(this.#resolvedSpecifierCache, cacheKey, async () => {
196
+ if (spec.startsWith(".") || spec.startsWith("/")) {
197
+ const abs = spec.startsWith("/") ? spec : path.resolve(importerDir, spec);
198
+ return await this.#resolveFileCandidate(abs);
199
+ }
200
+ const pkg = await this.#resolvePackage(spec);
201
+ return pkg ? pkg.entryFile : null;
202
+ }, (file) => file !== null);
394
203
  }
395
- if (edits.length === 0)
396
- return null;
397
- edits.sort((a, b) => b.start - a.start);
398
- let out = source;
399
- for (const edit of edits)
400
- out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
401
- return out === source ? null : out;
402
- };
403
- var collectBoundNames = (sf) => {
404
- const names = new Set;
405
- const visit = (node) => {
406
- if (ts.isImportClause(node)) {
407
- if (node.name)
408
- names.add(node.name.text);
409
- const bindings = node.namedBindings;
410
- if (bindings && ts.isNamespaceImport(bindings))
411
- names.add(bindings.name.text);
412
- if (bindings && ts.isNamedImports(bindings))
413
- for (const el of bindings.elements)
414
- names.add(el.name.text);
204
+ async#discoverFromFile(file, walk) {
205
+ const epoch = this.#epoch;
206
+ const absPath = path.resolve(file);
207
+ const importsAs = walk.importsAs?.get(absPath);
208
+ const cached = walk.reachable.get(absPath);
209
+ if (cached)
210
+ return new Set(cached);
211
+ const memo = walk.memo.get(absPath);
212
+ if (memo) {
213
+ if (walk.partial.has(absPath))
214
+ for (const onPath of walk.visiting)
215
+ walk.partial.add(onPath);
216
+ return new Set(memo);
415
217
  }
416
- if ((ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isParameter(node) || ts.isBindingElement(node) || ts.isEnumDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isInterfaceDeclaration(node)) && node.name && ts.isIdentifier(node.name))
417
- names.add(node.name.text);
418
- ts.forEachChild(node, visit);
419
- };
420
- ts.forEachChild(sf, visit);
421
- return names;
422
- };
423
- var collectUsedReferences = (sf) => {
424
- const used = new Set;
425
- const visit = (node) => {
426
- if (ts.isIdentifier(node) && isReferencePosition(node))
427
- used.add(node.text);
428
- ts.forEachChild(node, visit);
429
- };
430
- ts.forEachChild(sf, visit);
431
- return used;
432
- };
433
- var collectBareGlobalReferences = (sf) => {
434
- const bare = new Set;
435
- const visit = (node) => {
436
- if (ts.isIdentifier(node) && GLOBAL_NAMES.has(node.text) && isReferencePosition(node)) {
437
- const parent = node.parent;
438
- if (!(parent && ts.isPropertyAccessExpression(parent) && parent.expression === node))
439
- bare.add(node.text);
218
+ if (walk.visiting.has(absPath)) {
219
+ let below = false;
220
+ for (const onPath of walk.visiting) {
221
+ if (below)
222
+ walk.partial.add(onPath);
223
+ else
224
+ below = onPath === absPath;
225
+ }
226
+ return new Set;
440
227
  }
441
- ts.forEachChild(node, visit);
442
- };
443
- ts.forEachChild(sf, visit);
444
- return bare;
445
- };
446
- var isReferencePosition = (node) => {
447
- const parent = node.parent;
448
- if (!parent)
449
- return true;
450
- if (ts.isPropertyAccessExpression(parent) && parent.name === node)
451
- return false;
452
- if (ts.isQualifiedName(parent) && parent.right === node)
453
- return false;
454
- if (ts.isPropertyAssignment(parent) && parent.name === node)
455
- return false;
456
- if (ts.isPropertySignature(parent) && parent.name === node)
457
- return false;
458
- if (ts.isBindingElement(parent) && parent.propertyName === node)
459
- return false;
460
- if (ts.isImportSpecifier(parent) || ts.isExportSpecifier(parent))
461
- return false;
462
- return true;
463
- };
464
- var collectExistingNamedImports = (importDecls) => {
465
- const map = new Map;
466
- for (const decl of importDecls) {
467
- const clause = decl.importClause;
468
- const bindings = clause?.namedBindings;
469
- if (!clause || !bindings || !ts.isNamedImports(bindings))
470
- continue;
471
- if (!ts.isStringLiteral(decl.moduleSpecifier))
472
- continue;
473
- const specifier = decl.moduleSpecifier.text;
474
- if (map.has(specifier))
475
- continue;
476
- const names = new Map;
477
- for (const el of bindings.elements)
478
- names.set(el.name.text, clause.isTypeOnly || el.isTypeOnly);
479
- map.set(specifier, { decl, names });
480
- }
481
- return map;
482
- };
483
- var formatNamedImport = (specifier, names) => {
484
- const entries = [...names.entries()].sort((a, b) => compareNames(a[0], b[0]));
485
- if (entries.every(([, isType]) => isType))
486
- return `import type { ${entries.map(([name]) => name).join(", ")} } from "${specifier}";`;
487
- const parts = entries.map(([name, isType]) => isType ? `type ${name}` : name);
488
- return `import { ${parts.join(", ")} } from "${specifier}";`;
489
- };
490
- var directivePrologueEnd = (sf) => {
491
- let end = -1;
492
- for (const stmt of sf.statements) {
493
- if (ts.isExpressionStatement(stmt) && ts.isStringLiteral(stmt.expression))
494
- end = stmt.getEnd();
495
- else
496
- break;
497
- }
498
- return end;
499
- };
500
- var scriptKindFor = (fileName) => fileName.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
501
- var compareNames = (a, b) => {
502
- const [la, lb] = [a.toLowerCase(), b.toLowerCase()];
503
- if (la !== lb)
504
- return la < lb ? -1 : 1;
505
- return a < b ? -1 : a > b ? 1 : 0;
506
- };
507
- var formatError = (err) => err instanceof Error ? err.message : String(err);
508
- var fileExists = async (file) => stat(file).then((s) => s.isFile()).catch(() => false);
509
- var domainKindOf = (base) => {
510
- if (base.endsWith(".constant.ts"))
511
- return "constant";
512
- if (base.endsWith(".document.ts"))
513
- return "document";
514
- if (base.endsWith(".signal.ts"))
515
- return "signal";
516
- return null;
517
- };
518
- var buildDomainIndex = async (libDir) => {
519
- const index = new Map;
520
- for (const file of await collectDomainFiles(libDir)) {
521
- const kind = domainKindOf(path.basename(file));
522
- if (!kind)
523
- continue;
524
- const src = await readFile(file, "utf8").catch(() => null);
525
- if (src === null)
526
- continue;
527
- for (const name of exportedPascalNames(src, file)) {
528
- const entries = index.get(name) ?? [];
529
- entries.push({ file, kind });
530
- index.set(name, entries);
228
+ if (shouldSkipNodeModule(absPath))
229
+ return new Set;
230
+ walk.visiting.add(absPath);
231
+ const entries = new Set;
232
+ const facts = await this.#facts(absPath);
233
+ if (!facts)
234
+ return this.#finishDiscovery(absPath, walk, entries, epoch);
235
+ if (facts.isClientEntry) {
236
+ entries.add(absPath);
237
+ return this.#finishDiscovery(absPath, walk, entries, epoch);
531
238
  }
532
- }
533
- return index;
534
- };
535
- var collectDomainFiles = async (dir) => {
536
- const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
537
- const files = [];
538
- for (const entry of entries) {
539
- if (entry.name.startsWith(".") || entry.name === "node_modules")
540
- continue;
541
- const full = path.join(dir, entry.name);
542
- if (entry.isDirectory())
543
- files.push(...await collectDomainFiles(full));
544
- else if (domainKindOf(entry.name) && !TEST_FILE_RE.test(entry.name))
545
- files.push(full);
546
- }
547
- return files;
548
- };
549
- var exportedPascalNames = (source, fileName) => {
550
- const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true);
551
- const isExported = (node) => ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
552
- const names = [];
553
- for (const stmt of sf.statements) {
554
- if ((ts.isClassDeclaration(stmt) || ts.isFunctionDeclaration(stmt) || ts.isEnumDeclaration(stmt)) && stmt.name) {
555
- if (isExported(stmt))
556
- names.push(stmt.name.text);
557
- } else if (ts.isVariableStatement(stmt) && isExported(stmt)) {
558
- for (const decl of stmt.declarationList.declarations)
559
- if (ts.isIdentifier(decl.name))
560
- names.push(decl.name.text);
561
- } else if (ts.isExportDeclaration(stmt) && stmt.exportClause && ts.isNamedExports(stmt.exportClause)) {
562
- for (const el of stmt.exportClause.elements)
563
- names.push(el.name.text);
239
+ const importerDir = path.dirname(absPath);
240
+ for (const imp of facts.imports) {
241
+ const swapped = importsAs?.get(imp.path);
242
+ const spec = swapped === undefined ? imp.path : swapped;
243
+ if (!spec)
244
+ continue;
245
+ if (NON_SOURCE_EXT_RE.test(spec))
246
+ continue;
247
+ const resolved = await this.#resolveSpecifier(spec, importerDir);
248
+ if (!resolved)
249
+ continue;
250
+ if (shouldSkipNodeModule(resolved))
251
+ continue;
252
+ for (const entry of await this.#discoverFromFile(resolved, walk))
253
+ entries.add(entry);
564
254
  }
255
+ return this.#finishDiscovery(absPath, walk, entries, epoch);
565
256
  }
566
- return names.filter((name) => PASCAL_CASE_RE.test(name));
567
- };
568
- var relativeSpecifier = (fromDir, toFile) => {
569
- const rel = path.relative(fromDir, toFile).replace(/\.tsx?$/, "").split(path.sep).join("/");
570
- return rel.startsWith(".") ? rel : `./${rel}`;
571
- };
257
+ #finishDiscovery(absPath, walk, entries, epoch) {
258
+ walk.visiting.delete(absPath);
259
+ walk.memo.set(absPath, entries);
260
+ if (epoch === this.#epoch && !walk.partial.has(absPath))
261
+ walk.reachable.set(absPath, entries);
262
+ return new Set(entries);
263
+ }
264
+ }
572
265
 
573
- // pkgs/@akanjs/devkit/frontendBuild/clientEntryDiscovery.ts
574
- import fs from "fs";
266
+ // pkgs/@akanjs/devkit/frontendBuild/routeClientBuilder.ts
267
+ import { mkdir } from "fs/promises";
268
+ import path3 from "path";
269
+ import { SSR_DEV_CHUNK, SSR_DEV_ID_PREFIX } from "akanjs/server/hmr/csrDevManifest";
270
+
271
+ // pkgs/@akanjs/devkit/frontendBuild/clientEntriesBundler.ts
272
+ import fs2 from "fs";
575
273
  import path2 from "path";
576
- var USE_CLIENT_RE = /^\s*(?:\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/\s*|\/\/[^\n]*\n\s*)*["']use client["']/;
577
- var NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
578
- var AKANJS_NODE_MODULE_RE = /[\\/]node_modules[\\/]akanjs[\\/]/;
579
- var NON_SOURCE_EXT_RE = /\.(css|scss|sass|less|json|svg|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf|mp3|mp4|wav)$/i;
580
- var exportsKeyOf = (map) => JSON.stringify(map ? [...map].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0) : null);
581
- var shouldSkipNodeModule = (absPath) => NODE_MODULES_RE.test(absPath) && !AKANJS_NODE_MODULE_RE.test(absPath);
582
274
 
583
- class GraphClientEntryDiscovery {
584
- #akanConfig;
585
- #resolvePackage;
586
- #analyzer;
587
- #tsTranspiler = new Bun.Transpiler({ loader: "tsx" });
588
- #fileExistsCache = new Map;
589
- #factsCache = new Map;
590
- #resolvedFileCache = new Map;
591
- #resolvedSpecifierCache = new Map;
592
- #reachableEntriesCache = new Map;
593
- #swappedEntriesCaches = new WeakMap;
594
- #readFiles = new Set;
595
- #barrelImporters = new Map;
596
- #reread = new Map;
597
- #settled = Promise.resolve();
598
- #epoch = 0;
599
- constructor(akanConfig, resolvePackage) {
600
- this.#akanConfig = akanConfig;
601
- this.#resolvePackage = resolvePackage;
602
- this.#analyzer = new BarrelAnalyzer({ resolvePackage });
275
+ // pkgs/@akanjs/devkit/frontendBuild/clientBuildTypes.ts
276
+ var CLIENT_BUNDLE_NAMING = {
277
+ entry: "[name]-[hash].[ext]",
278
+ chunk: "chunks/[hash].[ext]",
279
+ asset: "assets/[hash].[ext]"
280
+ };
281
+
282
+ // pkgs/@akanjs/devkit/frontendBuild/clientEntriesBundler.ts
283
+ class ClientEntriesBundler {
284
+ #app;
285
+ #entries;
286
+ #plugins;
287
+ #external;
288
+ #externalSubpaths;
289
+ #externalAliases;
290
+ #entryExports;
291
+ #command;
292
+ #target;
293
+ #outputSubdir;
294
+ #reactFastRefresh;
295
+ #outdir;
296
+ #servePrefix;
297
+ #manifest = {};
298
+ #ssrManifest = { moduleLoading: null, moduleMap: {} };
299
+ #entryUrlsByAbsPath = new Map;
300
+ #entryOutputAbsByAbsPath = new Map;
301
+ #entryDepsByAbsPath = new Map;
302
+ #entryChunkUrlsByAbsPath = new Map;
303
+ #clientReferenceIdByAbsPath = new Map;
304
+ #opaqueEntries = null;
305
+ #metafileOutputsByAbs = new Map;
306
+ #metafileInputs = {};
307
+ constructor(options) {
308
+ this.#app = options.app;
309
+ this.#entries = options.entries;
310
+ this.#plugins = options.plugins ?? [];
311
+ this.#external = options.external ?? [];
312
+ this.#externalSubpaths = options.externalSubpaths ?? [];
313
+ this.#externalAliases = options.externalAliases ?? {};
314
+ this.#entryExports = options.entryExports ?? {};
315
+ this.#command = options.command ?? "start";
316
+ this.#target = options.target ?? "browser";
317
+ this.#outputSubdir = options.outputSubdir ?? "client";
318
+ this.#reactFastRefresh = options.reactFastRefresh ?? false;
319
+ const artifactDir = `${this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath}/.akan/artifact`;
320
+ this.#outdir = `${artifactDir}/${this.#outputSubdir}`;
321
+ this.#servePrefix = `/_akan/${this.#outputSubdir}`;
322
+ }
323
+ async bundle() {
324
+ const akanConfig = await this.#app.getConfig();
325
+ this.#opaqueEntries = await this.#createOpaqueEntryAliases();
326
+ const result = await Bun.build({
327
+ entrypoints: this.#opaqueEntries.entries,
328
+ outdir: this.#outdir,
329
+ splitting: true,
330
+ target: this.#target,
331
+ format: "esm",
332
+ naming: CLIENT_BUNDLE_NAMING,
333
+ metafile: true,
334
+ define: bundleDefine(this.#app, this.#command, "ssr"),
335
+ conditions: bundleConditions(this.#command),
336
+ minify: this.#command === "build",
337
+ optimizeImports: akanConfig.optimizeImports,
338
+ reactFastRefresh: this.#command === "start" && this.#outputSubdir === "client" && this.#reactFastRefresh,
339
+ plugins: this.#external.length > 0 || this.#externalSubpaths.length > 0 || Object.keys(this.#externalAliases).length > 0 ? [...this.#plugins, this.#createExternalSpecifiersPlugin()] : this.#plugins
340
+ });
341
+ if (!result.success)
342
+ throw new AggregateError(result.logs, "[ClientEntriesBundler] Bun.build failed");
343
+ await this.#rewriteExternalImportSpecifiers(result.outputs);
344
+ const metafile = result.metafile;
345
+ if (!metafile)
346
+ throw new Error("[ClientEntriesBundler] metafile is missing");
347
+ this.#metafileOutputsByAbs = new Map(Object.entries(metafile.outputs).map(([k, v]) => [this.#absFromOutdir(k), v]));
348
+ this.#metafileInputs = metafile.inputs;
349
+ for (const artifact of result.outputs.filter((a) => a.kind === "entry-point"))
350
+ this.#addEntryArtifact(artifact.path);
351
+ this.#assertNarrowedExports();
352
+ return {
353
+ manifest: this.#manifest,
354
+ ssrManifest: this.#ssrManifest,
355
+ entryUrlsByAbsPath: this.#entryUrlsByAbsPath,
356
+ entryOutputAbsByAbsPath: this.#entryOutputAbsByAbsPath,
357
+ entryDepsByAbsPath: this.#entryDepsByAbsPath,
358
+ entryChunkUrlsByAbsPath: this.#entryChunkUrlsByAbsPath,
359
+ externalsByChunkUrl: this.#collectExternalsByChunkUrl(),
360
+ clientReferenceIdByAbsPath: this.#clientReferenceIdByAbsPath
361
+ };
362
+ }
363
+ async#createOpaqueEntryAliases() {
364
+ const aliasDir = path2.join(this.#app.cwdPath, ".akan", "generated", "client-entry-alias", this.#outputSubdir);
365
+ fs2.mkdirSync(aliasDir, { recursive: true });
366
+ const originalByAlias = new Map;
367
+ const aliasedEntries = await Promise.all(this.#entries.map(async (entry) => {
368
+ const absEntry = path2.resolve(entry);
369
+ const narrowed = this.#entryExports[absEntry];
370
+ const key = `${this.#app.name}
371
+ ${this.#outputSubdir}
372
+ ${absEntry}${narrowed ? `
373
+ narrowed` : ""}`;
374
+ const aliasPath = path2.join(aliasDir, `${Bun.hash(key).toString(36)}.tsx`);
375
+ await Bun.write(aliasPath, narrowed ? ClientEntriesBundler.narrowedAliasSource(absEntry, narrowed) : this.#createOpaqueEntryAliasSource(absEntry, await this.#scanEntryExportNames(absEntry)));
376
+ originalByAlias.set(path2.resolve(aliasPath), absEntry);
377
+ return aliasPath;
378
+ }));
379
+ return { entries: aliasedEntries, originalByAlias, aliasDir };
380
+ }
381
+ #createOpaqueEntryAliasSource(absEntry, exportNames) {
382
+ const entryLit = JSON.stringify(path2.resolve(absEntry));
383
+ if (exportNames.length === 0)
384
+ return `export * from ${entryLit};
385
+ `;
386
+ const namedExports = exportNames.filter((name) => name !== "default");
387
+ const lines = namedExports.length > 0 ? [`export { ${namedExports.join(", ")} } from ${entryLit};`] : [];
388
+ if (exportNames.includes("default"))
389
+ lines.push(`export { default } from ${entryLit};`);
390
+ return `${lines.join(`
391
+ `)}
392
+ `;
603
393
  }
604
- static async create(app) {
605
- return new GraphClientEntryDiscovery(await app.getConfig(), await createTsconfigPackageResolver(app));
394
+ static narrowedAliasSource(absEntry, names) {
395
+ const list = names.length > 0 ? `{ ${names.join(", ")} }` : "{}";
396
+ return `export ${list} from ${JSON.stringify(path2.resolve(absEntry))};
397
+ `;
606
398
  }
607
- async discover(seeds, { importsAs } = {}) {
608
- this.#settled = this.#settled.then(() => this.#dropRenarrowed());
609
- await this.#settled;
610
- const entries = new Set;
611
- const reachable = importsAs ? this.#swappedEntriesCache(importsAs) : this.#reachableEntriesCache;
612
- for (const seed of seeds) {
613
- const walk = { visiting: new Set, partial: new Set, memo: new Map, importsAs, reachable };
614
- for (const entry of await this.#discoverFromFile(seed, walk))
615
- entries.add(entry);
616
- }
617
- return Array.from(entries).sort();
399
+ #assertNarrowedExports() {
400
+ const missing = Object.entries(this.#entryExports).flatMap(([absEntry, names = []]) => {
401
+ const absOut = this.#entryOutputAbsByAbsPath.get(absEntry);
402
+ if (!absOut)
403
+ return [`${path2.basename(absEntry)}: no output`];
404
+ const exported = new Set(this.#metafileOutputsByAbs.get(absOut)?.exports);
405
+ const absent = names.filter((name) => !exported.has(name));
406
+ return absent.length > 0 ? [`${path2.basename(absEntry)}: ${absent.join(", ")}`] : [];
407
+ });
408
+ if (missing.length > 0)
409
+ throw new Error(`[ClientEntriesBundler] client code imports names its vendor does not export (${missing.join("; ")})`);
618
410
  }
619
- async resolveImport(spec, importerDir) {
620
- const resolved = await this.#resolveSpecifier(spec, importerDir);
621
- return resolved ? path2.resolve(resolved) : null;
411
+ async#scanEntryExportNames(absEntry) {
412
+ return scanUseClientExports(await Bun.file(absEntry).text(), absEntry, this.#app.workspace.workspaceRoot);
622
413
  }
623
- #swappedEntriesCache(importsAs) {
624
- const cache = this.#swappedEntriesCaches.get(importsAs) ?? new Map;
625
- this.#swappedEntriesCaches.set(importsAs, cache);
626
- return cache;
414
+ #createExternalSpecifiersPlugin() {
415
+ const set = new Set(this.#external);
416
+ const subpathSet = new Set(this.#externalSubpaths);
417
+ const aliases = this.#externalAliases;
418
+ const specifiers = [...new Set([...this.#external, ...this.#externalSubpaths, ...Object.keys(aliases)])];
419
+ const escaped = specifiers.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
420
+ const filter = new RegExp(`^(${escaped.join("|")})(?:/.*)?$`);
421
+ return {
422
+ name: "akan-externalize-specifiers",
423
+ setup(build) {
424
+ build.onResolve({ filter }, (args) => {
425
+ const alias = aliases[args.path];
426
+ if (alias)
427
+ return { path: alias, external: true };
428
+ if (!ClientEntriesBundler.#matchesExternalSpecifier(args.path, set, subpathSet))
429
+ return;
430
+ return { path: args.path, external: true };
431
+ });
432
+ }
433
+ };
627
434
  }
628
- invalidate(files) {
629
- if (files.length === 0)
630
- return;
631
- let moved = false;
632
- for (const file of files) {
633
- const absPath = path2.resolve(file);
634
- const exists = fs.existsSync(absPath);
635
- if (exists !== this.#readFiles.has(absPath))
636
- moved = true;
637
- if (!exists)
638
- this.#readFiles.delete(absPath);
639
- this.#factsCache.delete(absPath);
640
- this.#fileExistsCache.delete(absPath);
641
- }
642
- this.#epoch += 1;
643
- this.#reachableEntriesCache.clear();
644
- this.#swappedEntriesCaches = new WeakMap;
645
- for (const [barrel, before] of this.#analyzer.forget(files))
646
- if (!this.#reread.has(barrel))
647
- this.#reread.set(barrel, before);
648
- if (!moved)
435
+ static #matchesExternalSpecifier(specifier, exactExternals, subpathExternals) {
436
+ if (exactExternals.has(specifier) || subpathExternals.has(specifier))
437
+ return true;
438
+ for (const external of subpathExternals)
439
+ if (specifier.startsWith(`${external}/`))
440
+ return true;
441
+ return false;
442
+ }
443
+ async#rewriteExternalImportSpecifiers(outputs) {
444
+ if (Object.keys(this.#externalAliases).length === 0)
649
445
  return;
650
- this.#fileExistsCache.clear();
651
- this.#resolvedFileCache.clear();
652
- this.#resolvedSpecifierCache.clear();
446
+ await Promise.all(outputs.filter((output) => output.path.endsWith(".js")).map(async (output) => {
447
+ const source = await Bun.file(output.path).text();
448
+ const rewritten = ClientEntriesBundler.rewriteExternalImportSpecifiers(source, this.#externalAliases);
449
+ if (rewritten !== source)
450
+ await Bun.write(output.path, rewritten);
451
+ }));
653
452
  }
654
- async#dropRenarrowed() {
655
- const reread = [...this.#reread];
656
- this.#reread.clear();
657
- for (const [barrel, before] of reread) {
658
- const [was, now] = await Promise.all([before, this.#analyzer.analyze(barrel)]);
659
- if (exportsKeyOf(was) === exportsKeyOf(now))
453
+ static rewriteExternalImportSpecifiers(source, aliases) {
454
+ let rewritten = source;
455
+ for (const [specifier, alias] of Object.entries(aliases)) {
456
+ if (!alias)
660
457
  continue;
661
- for (const importer of this.#barrelImporters.get(barrel) ?? [])
662
- this.#factsCache.delete(importer);
458
+ const escaped = specifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
459
+ rewritten = rewritten.replace(new RegExp(`(\\bfrom\\s*["'])${escaped}(["'])`, "g"), (_match, prefix, suffix) => {
460
+ return `${prefix}${alias}${suffix}`;
461
+ }).replace(new RegExp(`(\\bimport\\s*["'])${escaped}(["'])`, "g"), (_match, prefix, suffix) => {
462
+ return `${prefix}${alias}${suffix}`;
463
+ });
663
464
  }
465
+ return rewritten;
664
466
  }
665
- #lookup(cache, key, run, isFound) {
666
- const cached = cache.get(key);
667
- if (cached && (cached.found || cached.epoch === this.#epoch))
668
- return cached.promise;
669
- const entry = { epoch: this.#epoch, promise: run() };
670
- entry.promise.then((value) => {
671
- entry.found = isFound(value);
672
- }, () => {
673
- entry.found = false;
674
- });
675
- cache.set(key, entry);
676
- return entry.promise;
677
- }
678
- async#fileExists(p) {
679
- const absPath = path2.resolve(p);
680
- return await this.#lookup(this.#fileExistsCache, absPath, () => Bun.file(absPath).exists(), (exists) => exists);
467
+ #toServeUrl(absOutPath) {
468
+ const rel = path2.relative(this.#outdir, absOutPath).split(path2.sep).join("/");
469
+ return `${this.#servePrefix}/${rel}`;
681
470
  }
682
- #facts(file) {
683
- const absPath = path2.resolve(file);
684
- let cached = this.#factsCache.get(absPath);
685
- if (!cached) {
686
- cached = (async () => {
687
- const content = await Bun.file(absPath).text().catch(() => null);
688
- if (content === null)
689
- return null;
690
- this.#readFiles.add(absPath);
691
- if (USE_CLIENT_RE.test(content))
692
- return { isClientEntry: true, imports: [] };
693
- return { isClientEntry: false, imports: this.#scanImports(await this.#rewrite(content, absPath)) };
694
- })();
695
- this.#factsCache.set(absPath, cached);
696
- }
697
- return cached;
471
+ #absFromOutdir(p) {
472
+ return path2.isAbsolute(p) ? p : path2.resolve(this.#outdir, p);
698
473
  }
699
- async#rewrite(content, absPath) {
700
- if (this.#akanConfig.barrelImports.length === 0)
701
- return content;
702
- for (const barrel of this.#akanConfig.barrelImports.filter((barrel) => content.includes(barrel)))
703
- this.#barrelImporters.set(barrel, (this.#barrelImporters.get(barrel) ?? new Set).add(absPath));
704
- try {
705
- return await rewriteBarrelImports(content, this.#akanConfig.barrelImports, this.#analyzer) ?? content;
706
- } catch {
707
- return content;
708
- }
474
+ #absFromEntryPoint(p) {
475
+ if (path2.isAbsolute(p))
476
+ return path2.resolve(p);
477
+ const candidates = [path2.resolve(process.cwd(), p), path2.resolve(this.#app.cwdPath, p)];
478
+ return candidates.find((candidate) => fs2.existsSync(candidate)) ?? candidates[0];
709
479
  }
710
- #scanImports(source) {
711
- try {
712
- return this.#tsTranspiler.scanImports(source);
713
- } catch {
480
+ #collectChunkUrls(absOutPath, visited = new Set) {
481
+ if (visited.has(absOutPath))
714
482
  return [];
483
+ visited.add(absOutPath);
484
+ const info = this.#metafileOutputsByAbs.get(absOutPath);
485
+ if (!info)
486
+ return [this.#toServeUrl(absOutPath)];
487
+ const urls = [this.#toServeUrl(absOutPath)];
488
+ for (const imp of info.imports) {
489
+ if (imp.kind === "dynamic-import")
490
+ continue;
491
+ const absImp = this.#absFromOutdir(imp.path);
492
+ if (!absImp.endsWith(".js"))
493
+ continue;
494
+ urls.push(...this.#collectChunkUrls(absImp, visited));
715
495
  }
496
+ return urls;
716
497
  }
717
- async#resolveFileCandidate(absPathNoExt) {
718
- const cacheKey = path2.resolve(absPathNoExt);
719
- return await this.#lookup(this.#resolvedFileCache, cacheKey, async () => {
720
- if (await this.#fileExists(cacheKey))
721
- return cacheKey;
722
- for (const ext of SOURCE_EXTS) {
723
- const f = `${cacheKey}${ext}`;
724
- if (await this.#fileExists(f))
725
- return f;
726
- }
727
- for (const ext of SOURCE_EXTS) {
728
- const f = path2.join(cacheKey, `index${ext}`);
729
- if (await this.#fileExists(f))
730
- return f;
731
- }
732
- return null;
733
- }, (file) => file !== null);
734
- }
735
- async#resolveSpecifier(spec, importerDir) {
736
- const cacheKey = `${importerDir}\x00${spec}`;
737
- return await this.#lookup(this.#resolvedSpecifierCache, cacheKey, async () => {
738
- if (spec.startsWith(".") || spec.startsWith("/")) {
739
- const abs = spec.startsWith("/") ? spec : path2.resolve(importerDir, spec);
740
- return await this.#resolveFileCandidate(abs);
741
- }
742
- const pkg = await this.#resolvePackage(spec);
743
- return pkg ? pkg.entryFile : null;
744
- }, (file) => file !== null);
745
- }
746
- async#discoverFromFile(file, walk) {
747
- const epoch = this.#epoch;
748
- const absPath = path2.resolve(file);
749
- const importsAs = walk.importsAs?.get(absPath);
750
- const cached = walk.reachable.get(absPath);
751
- if (cached)
752
- return new Set(cached);
753
- const memo = walk.memo.get(absPath);
754
- if (memo) {
755
- if (walk.partial.has(absPath))
756
- for (const onPath of walk.visiting)
757
- walk.partial.add(onPath);
758
- return new Set(memo);
759
- }
760
- if (walk.visiting.has(absPath)) {
761
- let below = false;
762
- for (const onPath of walk.visiting) {
763
- if (below)
764
- walk.partial.add(onPath);
765
- else
766
- below = onPath === absPath;
767
- }
768
- return new Set;
498
+ #collectExternalsByChunkUrl() {
499
+ const externalsByChunkUrl = new Map;
500
+ if (this.#command !== "build" || this.#target !== "browser")
501
+ return externalsByChunkUrl;
502
+ for (const [absOut, info] of this.#metafileOutputsByAbs) {
503
+ if (!absOut.endsWith(".js"))
504
+ continue;
505
+ const externals = new Set;
506
+ for (const input of Object.keys(info.inputs ?? {}))
507
+ for (const imp of this.#metafileInputs[input]?.imports ?? [])
508
+ if (imp.external && imp.kind !== "dynamic-import" && !/^[./]/.test(imp.path))
509
+ externals.add(imp.path);
510
+ externalsByChunkUrl.set(this.#toServeUrl(absOut), [...externals].sort());
769
511
  }
770
- if (shouldSkipNodeModule(absPath))
512
+ return externalsByChunkUrl;
513
+ }
514
+ #collectClientDeps(absOutPath, visited = new Set) {
515
+ if (visited.has(absOutPath))
771
516
  return new Set;
772
- walk.visiting.add(absPath);
773
- const entries = new Set;
774
- const facts = await this.#facts(absPath);
775
- if (!facts)
776
- return this.#finishDiscovery(absPath, walk, entries, epoch);
777
- if (facts.isClientEntry) {
778
- entries.add(absPath);
779
- return this.#finishDiscovery(absPath, walk, entries, epoch);
517
+ visited.add(absOutPath);
518
+ const deps = new Set;
519
+ const info = this.#metafileOutputsByAbs.get(absOutPath);
520
+ if (!info)
521
+ return deps;
522
+ if (!this.#opaqueEntries)
523
+ throw new Error("[ClientEntriesBundler] opaque entries are missing");
524
+ for (const input of Object.keys(info.inputs ?? {})) {
525
+ const absInput = this.#absFromEntryPoint(input);
526
+ if (!absInput.includes("node_modules") && !absInput.startsWith(this.#opaqueEntries.aliasDir))
527
+ deps.add(absInput);
780
528
  }
781
- const importerDir = path2.dirname(absPath);
782
- for (const imp of facts.imports) {
783
- const swapped = importsAs?.get(imp.path);
784
- const spec = swapped === undefined ? imp.path : swapped;
785
- if (!spec)
786
- continue;
787
- if (NON_SOURCE_EXT_RE.test(spec))
788
- continue;
789
- const resolved = await this.#resolveSpecifier(spec, importerDir);
790
- if (!resolved)
529
+ for (const imp of info.imports) {
530
+ if (imp.kind === "dynamic-import")
791
531
  continue;
792
- if (shouldSkipNodeModule(resolved))
532
+ const absImp = this.#absFromOutdir(imp.path);
533
+ if (!absImp.endsWith(".js"))
793
534
  continue;
794
- for (const entry of await this.#discoverFromFile(resolved, walk))
795
- entries.add(entry);
535
+ for (const dep of this.#collectClientDeps(absImp, visited))
536
+ deps.add(dep);
796
537
  }
797
- return this.#finishDiscovery(absPath, walk, entries, epoch);
538
+ return deps;
798
539
  }
799
- #finishDiscovery(absPath, walk, entries, epoch) {
800
- walk.visiting.delete(absPath);
801
- walk.memo.set(absPath, entries);
802
- if (epoch === this.#epoch && !walk.partial.has(absPath))
803
- walk.reachable.set(absPath, entries);
804
- return new Set(entries);
540
+ #addEntryArtifact(absOut) {
541
+ if (!this.#opaqueEntries)
542
+ throw new Error("[ClientEntriesBundler] opaque entries are missing");
543
+ const info = this.#metafileOutputsByAbs.get(absOut);
544
+ const buildEntryPointAbs = info?.entryPoint ? this.#absFromEntryPoint(info.entryPoint) : null;
545
+ const entryPointAbs = buildEntryPointAbs ? this.#opaqueEntries.originalByAlias.get(buildEntryPointAbs) ?? buildEntryPointAbs : null;
546
+ if (!entryPointAbs)
547
+ return;
548
+ const chunkUrls = this.#collectChunkUrls(absOut);
549
+ const entryUrl = chunkUrls[0] ?? this.#toServeUrl(absOut);
550
+ this.#entryUrlsByAbsPath.set(entryPointAbs, entryUrl);
551
+ this.#entryOutputAbsByAbsPath.set(entryPointAbs, absOut);
552
+ this.#entryDepsByAbsPath.set(entryPointAbs, [...this.#collectClientDeps(absOut)].sort());
553
+ this.#entryChunkUrlsByAbsPath.set(entryPointAbs, chunkUrls);
554
+ const clientReferenceId = toClientReferencePath(entryPointAbs, this.#app.workspace.workspaceRoot);
555
+ this.#clientReferenceIdByAbsPath.set(entryPointAbs, clientReferenceId);
556
+ const flatChunks = [];
557
+ for (const url of chunkUrls)
558
+ flatChunks.push(url, url);
559
+ const exportNames = info?.exports && info.exports.length > 0 ? info.exports : ["default"];
560
+ const ssrEntriesByName = {};
561
+ for (const name of exportNames) {
562
+ const key = `${clientReferenceId}#${name}`;
563
+ this.#manifest[key] = { id: entryUrl, chunks: flatChunks, name, async: true };
564
+ ssrEntriesByName[name] = { id: absOut, chunks: [absOut, absOut], name, async: true };
565
+ }
566
+ this.#ssrManifest.moduleMap[entryUrl] = ssrEntriesByName;
805
567
  }
806
568
  }
807
569
 
808
- // pkgs/@akanjs/devkit/frontendBuild/csrDevBundler.ts
809
- import { mkdir as mkdir3 } from "fs/promises";
810
- import path12 from "path";
811
- import { CSR_DEV_DIRNAME, CSR_DEV_ROUTE_PREFIX } from "akanjs/server/hmr/csrDevManifest";
570
+ // pkgs/@akanjs/devkit/frontendBuild/vendorSpecifiers.ts
571
+ var VENDOR_SPECIFIERS = [
572
+ "react",
573
+ "react-dom",
574
+ "react-dom/client",
575
+ "react/jsx-runtime",
576
+ "react/jsx-dev-runtime",
577
+ "react-refresh/runtime",
578
+ "scheduler",
579
+ "react-server-dom-webpack/client.browser",
580
+ "akanjs/store",
581
+ "akanjs/store/agent",
582
+ "akanjs/base",
583
+ "akanjs/common",
584
+ "akanjs/constant",
585
+ "akanjs/fetch",
586
+ "tailwind-merge"
587
+ ];
588
+ var NARROWABLE_VENDOR_SPECIFIERS = [
589
+ "akanjs/store",
590
+ "akanjs/store/agent",
591
+ "akanjs/base",
592
+ "akanjs/common",
593
+ "akanjs/constant",
594
+ "akanjs/fetch",
595
+ "tailwind-merge"
596
+ ];
812
597
 
813
- // pkgs/@akanjs/devkit/frontendBuild/devRegistryBundler.ts
814
- import fs7 from "fs";
815
- import path11 from "path";
816
- import { isAkanRuntimeMetadataFile } from "akanjs/server/hmr/runtimeMetadataFile";
598
+ // pkgs/@akanjs/devkit/frontendBuild/routeClientBuilder.ts
599
+ var SSR_CLIENT_ALIAS_EXTERNALS = [
600
+ "react",
601
+ "react-dom",
602
+ "react-dom/client",
603
+ "react/jsx-runtime",
604
+ "react/jsx-dev-runtime"
605
+ ];
606
+ var SSR_CLIENT_EXTERNALS = [...SSR_CLIENT_ALIAS_EXTERNALS, "akanjs/fetch"];
817
607
 
818
- // pkgs/@akanjs/devkit/frontendBuild/csrDevArtifactWriter.ts
819
- import fs2 from "fs";
820
- import { mkdir, readdir as readdir2, rm } from "fs/promises";
821
- import path3 from "path";
822
- import {
823
- appGenerationOf,
824
- CSR_DEV_APP_FILE,
825
- CSR_DEV_KEPT_PATCHES,
826
- CSR_DEV_MANIFEST_FILE,
827
- CSR_DEV_PATCHING_MARKER,
828
- csrDevModuleFile
829
- } from "akanjs/server/hmr/csrDevManifest";
830
- class CsrDevArtifactWriter {
831
- static #keptVendors = 3;
832
- static #buildingMarker = ".building";
833
- #outDir;
834
- #routePrefix;
835
- #library;
836
- constructor(outDir, { routePrefix, library = false }) {
837
- this.#outDir = outDir;
838
- this.#routePrefix = routePrefix;
839
- this.#library = library;
608
+ class RouteClientBuilder {
609
+ #app;
610
+ #seeds;
611
+ #graphSeeds;
612
+ #knownEntries;
613
+ #command;
614
+ #discovery;
615
+ #entries;
616
+ #browser;
617
+ constructor(options) {
618
+ this.#app = options.app;
619
+ this.#seeds = options.seeds;
620
+ this.#graphSeeds = options.graphSeeds;
621
+ this.#knownEntries = options.knownEntries ?? new Set;
622
+ this.#command = options.command ?? "start";
623
+ this.#discovery = options.discovery;
624
+ this.#entries = options.entries;
625
+ this.#browser = options.browser ?? (this.#command === "start" ? "registry" : "chunks");
626
+ }
627
+ async build() {
628
+ const discovered = this.#entries ?? await (await this.#getDiscovery()).discover(this.#seeds);
629
+ if (discovered.every((e) => this.#knownEntries.has(e)))
630
+ return this.#emptyResult(discovered);
631
+ const entries = this.#graphSeeds ? [...new Set([...discovered, ...await (await this.#getDiscovery()).discover(this.#graphSeeds)])].sort() : discovered.filter((e) => !this.#knownEntries.has(e));
632
+ const bootstrapEntries = await this.#createBootstrapEntries(entries);
633
+ const registry = this.#browser === "registry" ? new CsrDevPaths(this.#app.workspace.workspaceRoot) : null;
634
+ const browserBundle = registry ? null : await this.#buildBrowserBundle(bootstrapEntries);
635
+ const ssrBundle = await this.#buildSsrBundle(bootstrapEntries);
636
+ const referenceBundle = browserBundle ?? ssrBundle;
637
+ const acceptedEntries = new Set(entries);
638
+ const routeEntries = new Set(discovered);
639
+ const manifestDelta = {};
640
+ const ssrModuleMap = {};
641
+ const clientDeps = new Set;
642
+ const clientDepsByEntry = {};
643
+ for (const [key, bundleRow] of Object.entries(referenceBundle.manifest)) {
644
+ const manifestEntry = RouteClientBuilder.resolveOriginalManifestEntry(key, bootstrapEntries.originalByBuildEntry, referenceBundle.clientReferenceIdByAbsPath, this.#app.workspace.workspaceRoot);
645
+ if (!manifestEntry)
646
+ continue;
647
+ if (!acceptedEntries.has(manifestEntry.originalEntry))
648
+ continue;
649
+ const row = registry ? RouteClientBuilder.#registryRow(registry, manifestEntry.originalEntry, bundleRow) : bundleRow;
650
+ manifestDelta[manifestEntry.key] = row;
651
+ const ssrOutput = ssrBundle.entryOutputAbsByAbsPath.get(manifestEntry.buildEntry);
652
+ if (!ssrOutput)
653
+ continue;
654
+ ssrModuleMap[row.id] ??= {};
655
+ ssrModuleMap[row.id][row.name] = { id: ssrOutput, chunks: [ssrOutput, ssrOutput], name: row.name, async: true };
656
+ }
657
+ for (const entry of bootstrapEntries.buildEntries) {
658
+ const buildEntry = path3.resolve(entry);
659
+ const originalEntry = path3.resolve(bootstrapEntries.originalByBuildEntry.get(buildEntry) ?? buildEntry);
660
+ if (!acceptedEntries.has(originalEntry))
661
+ continue;
662
+ const deps = new Set([originalEntry]);
663
+ for (const dep of referenceBundle.entryDepsByAbsPath.get(buildEntry) ?? [])
664
+ deps.add(path3.resolve(dep));
665
+ const sortedDeps = [...deps].sort();
666
+ clientDepsByEntry[originalEntry] = sortedDeps;
667
+ if (routeEntries.has(originalEntry))
668
+ for (const dep of sortedDeps)
669
+ clientDeps.add(dep);
670
+ }
671
+ return {
672
+ manifestDelta,
673
+ ssrManifestDelta: { moduleLoading: null, moduleMap: ssrModuleMap },
674
+ newEntries: entries.filter((e) => !this.#knownEntries.has(e)),
675
+ discoveredEntries: discovered,
676
+ clientDeps: [...clientDeps].sort(),
677
+ clientDepsByEntry,
678
+ ...registry ? { registryEntries: [...acceptedEntries].sort() } : {},
679
+ ...browserBundle ? { externalsByChunkUrl: Object.fromEntries(browserBundle.externalsByChunkUrl) } : {}
680
+ };
681
+ }
682
+ static #registryRow(paths, entry, row) {
683
+ return {
684
+ id: `${SSR_DEV_ID_PREFIX}${paths.idOf(entry)}`,
685
+ chunks: [SSR_DEV_CHUNK, SSR_DEV_CHUNK],
686
+ name: row.name,
687
+ async: true
688
+ };
689
+ }
690
+ async#getDiscovery() {
691
+ this.#discovery ??= await GraphClientEntryDiscovery.create(this.#app);
692
+ return this.#discovery;
693
+ }
694
+ #emptyResult(discoveredEntries = []) {
695
+ return {
696
+ manifestDelta: {},
697
+ ssrManifestDelta: { moduleLoading: null, moduleMap: {} },
698
+ newEntries: [],
699
+ discoveredEntries,
700
+ clientDeps: [],
701
+ clientDepsByEntry: {}
702
+ };
703
+ }
704
+ async#buildBrowserBundle(bootstrapEntries) {
705
+ const reactFastRefresh = process.env.AKAN_REACT_FAST_REFRESH !== "0";
706
+ return new ClientEntriesBundler({
707
+ app: this.#app,
708
+ entries: bootstrapEntries.buildEntries,
709
+ plugins: [
710
+ await createBarrelImportsPlugin(this.#app, {
711
+ pipeAfter: reactFastRefresh ? RouteClientBuilder.normalizeNamedDefaultFunctionForFastRefresh : undefined,
712
+ external: VENDOR_SPECIFIERS
713
+ })
714
+ ],
715
+ external: VENDOR_SPECIFIERS,
716
+ command: this.#command,
717
+ reactFastRefresh
718
+ }).bundle();
719
+ }
720
+ async#buildSsrBundle(bootstrapEntries) {
721
+ return new ClientEntriesBundler({
722
+ app: this.#app,
723
+ entries: bootstrapEntries.buildEntries,
724
+ plugins: [await createBarrelImportsPlugin(this.#app)],
725
+ ...RouteClientBuilder.resolveSsrClientBundleOptions(this.#command),
726
+ outputSubdir: "client-ssr",
727
+ command: this.#command
728
+ }).bundle();
729
+ }
730
+ async#createBootstrapEntries(entries) {
731
+ if (!await Bun.file(path3.join(this.#app.cwdPath, "lib", "st.ts")).exists()) {
732
+ return { buildEntries: entries, originalByBuildEntry: new Map };
733
+ }
734
+ const outdir = path3.join(this.#app.cwdPath, ".akan", "generated", "client-entry-bootstrap");
735
+ await mkdir(outdir, { recursive: true });
736
+ const originalByBuildEntry = new Map;
737
+ const buildEntries = await Promise.all(entries.map(async (entry) => {
738
+ const absEntry = path3.resolve(entry);
739
+ const hash = Bun.hash(`${this.#app.name}
740
+ ${absEntry}`).toString(36);
741
+ const base = path3.basename(absEntry).replace(/[^A-Za-z0-9._-]/g, "_");
742
+ const wrapperEntry = path3.join(outdir, `${base}-${hash}.tsx`);
743
+ const exportNames = await this.#scanExportNames(absEntry);
744
+ await Bun.write(wrapperEntry, RouteClientBuilder.createStoreBootstrapEntrySource({
745
+ appName: this.#app.name,
746
+ originalEntry: absEntry,
747
+ exportNames
748
+ }));
749
+ originalByBuildEntry.set(path3.resolve(wrapperEntry), absEntry);
750
+ return wrapperEntry;
751
+ }));
752
+ return { buildEntries, originalByBuildEntry };
840
753
  }
841
- async markBuilding() {
842
- await Bun.write(path3.join(this.#outDir, CsrDevArtifactWriter.#buildingMarker), String(process.pid));
754
+ async#scanExportNames(absEntry) {
755
+ return scanUseClientExports(await Bun.file(absEntry).text(), absEntry, this.#app.workspace.workspaceRoot);
843
756
  }
844
- async clearBuilding() {
845
- await CsrDevArtifactWriter.#remove(path3.join(this.#outDir, CsrDevArtifactWriter.#buildingMarker));
757
+ static normalizeNamedDefaultFunctionForFastRefresh(source, { path: filePath } = {}) {
758
+ const declared = RouteClientBuilder.#declaredNamedDefaultFunctions(source, filePath);
759
+ if (declared.length === 0)
760
+ return null;
761
+ let next = "";
762
+ let cursor = 0;
763
+ for (const { index, text, lineStart, indent, asyncKeyword, name } of declared) {
764
+ next += `${source.slice(cursor, index)}${lineStart}${indent}${asyncKeyword}function ${name}`;
765
+ cursor = index + text.length;
766
+ }
767
+ next += source.slice(cursor);
768
+ return `${next}
769
+ ${declared.map(({ name }) => `export default ${name};`).join(`
770
+ `)}
771
+ `;
846
772
  }
847
- async isBuilding() {
848
- return await Bun.file(path3.join(this.#outDir, CsrDevArtifactWriter.#buildingMarker)).exists();
773
+ static #declaredNamedDefaultFunctions(source, filePath) {
774
+ const candidates = [
775
+ ...source.matchAll(/(^|\n)([^\S\n]*)export\s+default\s+(async\s+)?function\s+([A-Za-z_$][\w$]*)(?=\s*(?:<|\())/g)
776
+ ].map((match) => ({
777
+ index: match.index,
778
+ text: match[0],
779
+ lineStart: match[1] ?? "",
780
+ indent: match[2] ?? "",
781
+ asyncKeyword: match[3] ?? "",
782
+ name: match[4] ?? ""
783
+ }));
784
+ if (candidates.length === 0)
785
+ return [];
786
+ const probeName = (idx) => `__akanNamedDefault${idx}`;
787
+ let probe = "";
788
+ let cursor = 0;
789
+ candidates.forEach(({ index, text, lineStart, indent, asyncKeyword }, idx) => {
790
+ probe += `${source.slice(cursor, index)}${lineStart}${indent}export ${asyncKeyword}function ${probeName(idx)}`;
791
+ cursor = index + text.length;
792
+ });
793
+ probe += source.slice(cursor);
794
+ const exported = RouteClientBuilder.#scanExports(probe, filePath);
795
+ return candidates.filter((_, idx) => exported.has(probeName(idx)));
849
796
  }
850
- async forgetPatch(generation) {
851
- await Promise.all([`patch-${generation}.js`, `patch-${generation}.js.layout.json`].map((name) => CsrDevArtifactWriter.#remove(path3.join(this.#outDir, name))));
797
+ static #scanExports(source, filePath) {
798
+ try {
799
+ return new Set(new Bun.Transpiler({ loader: filePath ? loaderFor(filePath) : "tsx" }).scan(source).exports);
800
+ } catch {
801
+ return new Set;
802
+ }
852
803
  }
853
- async readJson(name) {
854
- const file = Bun.file(path3.join(this.#outDir, name));
855
- if (!await file.exists())
856
- return null;
857
- return await file.json().catch(() => null);
804
+ static resolveSsrClientRuntimeAliases() {
805
+ const serverEntry = RouteClientBuilder.resolveAkanServerEntry();
806
+ return { [Bun.resolveSync("akanjs/fetch", serverEntry)]: "akanjs/fetch" };
858
807
  }
859
- async writeJson(name, value) {
860
- await this.#writeAtomic(name, JSON.stringify(value));
808
+ static resolveSsrClientBundleOptions(command) {
809
+ if (command === "start") {
810
+ return {
811
+ target: "bun",
812
+ external: SSR_CLIENT_EXTERNALS,
813
+ externalSubpaths: ["akanjs/fetch"],
814
+ externalAliases: RouteClientBuilder.resolveSsrClientRuntimeAliases()
815
+ };
816
+ }
817
+ return { target: "bun", external: SSR_CLIENT_ALIAS_EXTERNALS };
861
818
  }
862
- async writeModules(compiled) {
863
- await mkdir(path3.join(this.#outDir, "modules"), { recursive: true });
864
- const helpers = new Map(compiled.flatMap((module) => module.helpers ? [[module.helpers.hash, module.helpers]] : []));
865
- await Promise.all([
866
- ...compiled.flatMap((module) => [
867
- Bun.write(this.#modulePath(module.id, ".js"), module.factory),
868
- ...module.sourceMap ? [Bun.write(this.#modulePath(module.id, ".js.map"), module.sourceMap)] : []
869
- ]),
870
- ...[...helpers.values()].map((shared) => Bun.write(this.#helpersPath(shared.hash), shared.definition))
871
- ]);
819
+ static resolveAkanServerEntry() {
820
+ try {
821
+ return Bun.resolveSync("akanjs/server", import.meta.dir);
822
+ } catch {
823
+ return path3.resolve(import.meta.dir, "../../../server/index.ts");
824
+ }
872
825
  }
873
- async readCode(graph) {
874
- const ids = Object.keys(graph.modules).filter((id) => !graph.modules[id]?.vendor && this.hasModule(id));
875
- const hashes = [...new Set(ids.flatMap((id) => graph.modules[id]?.helpers ?? []))];
876
- const [modules, helpers] = await Promise.all([
877
- Promise.all(ids.map(async (id) => [id, await Bun.file(this.#modulePath(id, ".js")).text()])),
878
- Promise.all(hashes.map(async (hash) => [hash, await Bun.file(this.#helpersPath(hash)).text()]))
879
- ]);
880
- return { modules: new Map(modules), helpers: new Map(helpers) };
826
+ static createStoreBootstrapEntrySource(args) {
827
+ const originalEntry = JSON.stringify(path3.resolve(args.originalEntry));
828
+ const namedExports = args.exportNames.filter((name) => name !== "default");
829
+ const lines = [
830
+ ...StoreBootstrap.importLines(args.appName),
831
+ ...namedExports.length > 0 ? [`export { ${namedExports.join(", ")} } from ${originalEntry};`] : []
832
+ ];
833
+ if (args.exportNames.includes("default"))
834
+ lines.push(`export { default } from ${originalEntry};`);
835
+ return `${lines.join(`
836
+ `)}
837
+ `;
881
838
  }
882
- hasModule(id) {
883
- return fs2.existsSync(this.#modulePath(id, ".js"));
839
+ static resolveOriginalManifestEntry(manifestKey, originalByBuildEntry, clientReferenceIdByBuildEntry = new Map, workspaceRoot = process.cwd()) {
840
+ const hashIdx = manifestKey.lastIndexOf("#");
841
+ if (hashIdx < 0)
842
+ return null;
843
+ const buildReferenceId = manifestKey.slice(0, hashIdx);
844
+ const name = manifestKey.slice(hashIdx + 1);
845
+ const buildEntry = [...clientReferenceIdByBuildEntry.entries()].find(([, referenceId]) => referenceId === buildReferenceId)?.[0] ?? buildReferenceId;
846
+ const originalEntry = originalByBuildEntry.get(buildEntry) ?? buildEntry;
847
+ const originalReferenceId = toClientReferencePath(originalEntry, workspaceRoot);
848
+ return { buildEntry, originalEntry, name, key: `${originalReferenceId}#${name}` };
884
849
  }
885
- async forgetModules(ids) {
886
- await Promise.all(ids.flatMap((id) => [
887
- CsrDevArtifactWriter.#remove(this.#modulePath(id, ".js")),
888
- CsrDevArtifactWriter.#remove(this.#modulePath(id, ".js.map"))
889
- ]));
850
+ }
851
+
852
+ // pkgs/@akanjs/devkit/frontendBuild/autoImportSync.ts
853
+ import { readdir, readFile, stat } from "fs/promises";
854
+ import path4 from "path";
855
+ import ts from "typescript";
856
+ var TEST_FILE_RE = /\.(test|spec)\.(ts|tsx)$/;
857
+ var AKAN_BASE = {
858
+ names: ["Int", "Float", "ID", "Any", "Upload", "enumOf", "dayjs"],
859
+ specifier: "akanjs/base",
860
+ kind: "named"
861
+ };
862
+ var AKAN_BASE_TYPES = { names: ["Dayjs"], specifier: "akanjs/base", kind: "named", typeOnly: true };
863
+ var CNST_NS = { names: ["cnst"], specifier: "../cnst", kind: "namespace" };
864
+ var DB_NS = { names: ["db"], specifier: "../db", kind: "namespace" };
865
+ var SRV_NS = { names: ["srv"], specifier: "../srv", kind: "namespace" };
866
+ var ERR_DICT = { names: ["Err"], specifier: "../dict", kind: "named" };
867
+ var RULES = {
868
+ constant: [AKAN_BASE, AKAN_BASE_TYPES, { names: ["via"], specifier: "akanjs/constant", kind: "named" }],
869
+ document: [
870
+ AKAN_BASE,
871
+ AKAN_BASE_TYPES,
872
+ CNST_NS,
873
+ DB_NS,
874
+ ERR_DICT,
875
+ {
876
+ names: ["by", "from", "into", "SchemaOf", "DataInputOf", "DocumentUpdateHelper", "documentQueryHelper", "Mdl"],
877
+ specifier: "akanjs/document",
878
+ kind: "named"
879
+ }
880
+ ],
881
+ service: [
882
+ AKAN_BASE,
883
+ AKAN_BASE_TYPES,
884
+ DB_NS,
885
+ SRV_NS,
886
+ CNST_NS,
887
+ ERR_DICT,
888
+ { names: ["serve"], specifier: "akanjs/service", kind: "named" },
889
+ {
890
+ names: ["DataInputOf", "ListQueryOption", "DatabaseRegistry", "getFilterInfoByKey"],
891
+ specifier: "akanjs/document",
892
+ kind: "named"
893
+ }
894
+ ],
895
+ signal: [
896
+ AKAN_BASE,
897
+ AKAN_BASE_TYPES,
898
+ SRV_NS,
899
+ CNST_NS,
900
+ ERR_DICT,
901
+ {
902
+ names: ["endpoint", "internal", "slice", "Public", "Req", "Ws", "None", "Res"],
903
+ specifier: "akanjs/signal",
904
+ kind: "named"
905
+ }
906
+ ],
907
+ dictionary: [
908
+ {
909
+ names: ["modelDictionary", "scalarDictionary", "serviceDictionary"],
910
+ specifier: "akanjs/dictionary",
911
+ kind: "named"
912
+ }
913
+ ],
914
+ srvkit: [
915
+ AKAN_BASE,
916
+ AKAN_BASE_TYPES,
917
+ { names: ["Logger", "HttpClient", "sleep"], specifier: "akanjs/common", kind: "named" },
918
+ { names: ["adapt"], specifier: "akanjs/service", kind: "named" },
919
+ { names: ["SignalContext", "Guard", "InternalArg", "Middleware"], specifier: "akanjs/signal", kind: "named" }
920
+ ],
921
+ common: [AKAN_BASE, AKAN_BASE_TYPES],
922
+ store: [
923
+ CNST_NS,
924
+ { names: ["store"], specifier: "akanjs/store", kind: "named" },
925
+ { names: ["fetch", "usePage", "sig"], specifier: "../useClient", kind: "named" },
926
+ { names: ["st"], specifier: "../st", kind: "named" },
927
+ { names: ["RootStore"], specifier: "../st", kind: "named", typeOnly: true }
928
+ ],
929
+ client: [
930
+ {
931
+ names: ["cnst", "fetch", "st", "usePage"],
932
+ specifier: (ctx) => `@${ctx.scope}/${ctx.project}/client`,
933
+ kind: "named"
934
+ }
935
+ ]
936
+ };
937
+ var PASCAL_CASE_RE = /^[A-Z][A-Za-z0-9]*$/;
938
+ var DOMAIN_ROLE_KINDS = {
939
+ constant: ["constant"],
940
+ dictionary: ["constant", "document", "signal"],
941
+ common: ["constant"]
942
+ };
943
+ var LIB_BARRELS = {
944
+ Err: { barrel: "dict", kind: "named" },
945
+ db: { barrel: "db", kind: "namespace" },
946
+ cnst: { barrel: "cnst", kind: "namespace" },
947
+ srv: { barrel: "srv", kind: "namespace" }
948
+ };
949
+ var GLOBAL_NAMES = new Set(["fetch"]);
950
+ var DOMAIN_DENYLIST = new Set([
951
+ "Map",
952
+ "Set",
953
+ "WeakMap",
954
+ "WeakSet",
955
+ "Date",
956
+ "Promise",
957
+ "Array",
958
+ "Object",
959
+ "Error",
960
+ "TypeError",
961
+ "RangeError",
962
+ "RegExp",
963
+ "Symbol",
964
+ "Proxy",
965
+ "Reflect",
966
+ "JSON",
967
+ "Math",
968
+ "Number",
969
+ "BigInt",
970
+ "Function",
971
+ "Boolean",
972
+ "String",
973
+ "Record",
974
+ "Partial",
975
+ "Required",
976
+ "Readonly",
977
+ "Pick",
978
+ "Omit",
979
+ "Exclude",
980
+ "Extract",
981
+ "NonNullable",
982
+ "ReturnType",
983
+ "Parameters",
984
+ "Awaited",
985
+ "InstanceType"
986
+ ]);
987
+
988
+ class AutoImportSync {
989
+ #workspaceRoot;
990
+ #domainCache = new Map;
991
+ constructor({ workspaceRoot }) {
992
+ this.#workspaceRoot = path4.resolve(workspaceRoot);
890
993
  }
891
- async writeVendor(graph) {
892
- const ids = Object.keys(graph.modules).filter((id) => graph.modules[id]?.vendor).sort();
893
- const stubs = new Set(Object.values(graph.modules).flatMap((module) => module.deps.filter(CsrDevPaths.isStub)));
894
- const lines = [await this.#helperDefinitions(graph, ids), ...await this.#defineLines(ids)];
895
- for (const stub of [...stubs].sort()) {
896
- if (stub.startsWith(CsrDevPaths.emptyStubPrefix)) {
897
- lines.push(`__akan.define(${JSON.stringify(stub)}, function () {});
898
- `);
994
+ async syncForBatch(files) {
995
+ const changedFiles = [];
996
+ const errors = [];
997
+ const seen = new Set;
998
+ for (const file of files) {
999
+ const pkgRoot = this.#domainPkgRootOf(file);
1000
+ if (pkgRoot)
1001
+ this.#domainCache.delete(pkgRoot);
1002
+ }
1003
+ for (const file of files) {
1004
+ const abs = path4.resolve(file);
1005
+ if (seen.has(abs))
1006
+ continue;
1007
+ seen.add(abs);
1008
+ const ctx = this.#contextFor(abs);
1009
+ if (!ctx)
899
1010
  continue;
1011
+ try {
1012
+ const changed = await this.#syncFile(abs, ctx);
1013
+ if (changed)
1014
+ changedFiles.push(abs);
1015
+ } catch (err) {
1016
+ errors.push(`[auto-import] sync failed for ${file}: ${formatError(err)}`);
900
1017
  }
901
- const message = `[akan-csr] ${stub.slice(CsrDevPaths.stubPrefix.length)} is a Node built-in the browser does not have`;
902
- lines.push(`__akan.define(${JSON.stringify(stub)}, function () {
903
- throw new Error(${JSON.stringify(message)});
904
- });
905
- `);
906
1018
  }
907
- const code = lines.join("");
908
- const vendorFile = `vendor-${Bun.hash(code).toString(36)}.js`;
909
- await this.#writeAtomic(vendorFile, code);
910
- return vendorFile;
911
- }
912
- async writeApp(graph, { generation, vendorFile, epoch }, code) {
913
- const ids = Object.keys(graph.modules).filter((id) => !graph.modules[id]?.vendor).sort();
914
- const lines = await this.#defineLines(ids, code);
915
- const blocks = ids.map((id, index) => [id, lines[index] ?? ""]);
916
- const start = this.#library ? `__akan.startLibrary(${JSON.stringify({ generation, refresh: graph.refresh, bootstrap: graph.entries[""], vendorFile, epoch })});
917
- ` : `__akan.start(${JSON.stringify({ generation, refresh: graph.refresh })});
918
- `;
919
- await this.#writeWithSourceMap(CSR_DEV_APP_FILE, await this.#helperDefinitions(graph, ids, code), blocks, start);
920
- }
921
- async writePatch(generation, modules) {
922
- const patchFile = `patch-${generation}.js`;
923
- const blocks = modules.map((module, index) => [module.id, `${JSON.stringify(module.id)}: ${module.factory}${index < modules.length - 1 ? `,
924
- ` : `
925
- `}`]);
926
- const helpers = new Map(modules.flatMap((module) => module.helpers ? [[module.helpers.hash, module.helpers]] : []));
927
- const header = `${[...helpers.values()].map((shared) => shared.definition).join("")}__akan.update(${generation}, {
928
- `;
929
- await this.#writeWithSourceMap(patchFile, header, blocks, `});
930
- `);
931
- return `${this.#routePrefix}${patchFile}`;
932
- }
933
- async writeState(graph, manifest) {
934
- await this.writeJson("graph.json", graph);
935
- await this.writeJson(CSR_DEV_MANIFEST_FILE, manifest);
936
- }
937
- async commitPatch(graph, manifest, announce, { modules, code }) {
938
- await this.writeJson(CSR_DEV_MANIFEST_FILE, manifest);
939
- announce();
940
- await CsrDevArtifactWriter.#appWriteDelay();
941
- await this.writeModules(modules);
942
- await this.writeJson("graph.json", graph);
943
- await this.writeApp(graph, manifest, code);
944
- await this.writeJson(CSR_DEV_MANIFEST_FILE, { ...manifest, appGeneration: manifest.generation });
945
- }
946
- async healApp(graph, manifest, code) {
947
- if (appGenerationOf(manifest) >= manifest.generation)
948
- return manifest;
949
- await this.writeApp(graph, manifest, code);
950
- const healed = { ...manifest, appGeneration: manifest.generation };
951
- await this.writeJson(CSR_DEV_MANIFEST_FILE, healed);
952
- return healed;
1019
+ return { changedFiles, errors };
953
1020
  }
954
- async prune(vendorFile, generation) {
955
- const names = await readdir2(this.#outDir);
956
- const stale = names.filter((name) => {
957
- const patch = /^patch-(\d+)\.js(?:\.layout\.json)?$/.exec(name);
958
- return patch ? Number(patch[1]) <= generation - CSR_DEV_KEPT_PATCHES : false;
959
- });
960
- const vendors = names.filter((name) => /^vendor-[\w-]+\.js$/.test(name) && name !== vendorFile).map((name) => ({ name, mtimeMs: CsrDevPaths.mtimeOf(path3.join(this.#outDir, name)) })).sort((a, b) => b.mtimeMs - a.mtimeMs).slice(CsrDevArtifactWriter.#keptVendors - 1).map(({ name }) => name);
961
- await Promise.all([...stale, ...vendors].map((name) => CsrDevArtifactWriter.#remove(path3.join(this.#outDir, name))));
1021
+ #contextFor(abs) {
1022
+ const rel = path4.relative(this.#workspaceRoot, abs);
1023
+ if (rel.startsWith("..") || path4.isAbsolute(rel))
1024
+ return null;
1025
+ const base = path4.basename(abs);
1026
+ if (TEST_FILE_RE.test(base) || base === "index.ts" || base === "index.tsx" || base.endsWith(".d.ts"))
1027
+ return null;
1028
+ const parts = rel.split(path4.sep).filter(Boolean);
1029
+ const [scope, project, facet] = parts;
1030
+ if (scope !== "apps" && scope !== "libs" || !project || !facet)
1031
+ return null;
1032
+ if (facet === "lib" && parts[3] === "__lib")
1033
+ return null;
1034
+ const role = roleFor(facet, base);
1035
+ if (!role)
1036
+ return null;
1037
+ return { role, scope, project };
962
1038
  }
963
- async pruneAfterFullBuild(graph, vendorFile, { generation, assets }) {
964
- const kept = new Set(Object.keys(graph.modules).flatMap((id) => [this.#modulePath(id, ".js"), this.#modulePath(id, ".js.map")]));
965
- for (const module of Object.values(graph.modules))
966
- if (module.helpers)
967
- kept.add(this.#helpersPath(module.helpers));
968
- for (const asset of assets)
969
- kept.add(path3.resolve(asset));
970
- const listed = async (dir) => (await readdir2(path3.join(this.#outDir, dir)).catch(() => [])).map((name) => path3.join(this.#outDir, dir, name));
971
- const stale = [
972
- ...(await listed("modules")).filter((file) => !kept.has(file)),
973
- ...(await listed("assets")).filter((file) => !kept.has(file)),
974
- ...(await listed(".")).filter((file) => {
975
- const name = path3.basename(file);
976
- return /^patch-\d+\.js(?:\.layout\.json)?$/.test(name) || name.endsWith(".tmp");
977
- }),
978
- path3.join(this.#outDir, CSR_DEV_PATCHING_MARKER)
979
- ];
980
- await Promise.all(stale.map((file) => CsrDevArtifactWriter.#remove(file)));
981
- await this.prune(vendorFile, generation);
1039
+ async#syncFile(abs, ctx) {
1040
+ const stats = await stat(abs).catch(() => null);
1041
+ if (!stats?.isFile())
1042
+ return false;
1043
+ const source = await readFile(abs, "utf8");
1044
+ const resolveExtra = await this.#extraResolverFor(abs, ctx);
1045
+ const next = transformSource(source, abs, ctx, resolveExtra);
1046
+ if (next === null || next === source)
1047
+ return false;
1048
+ await FileSys2.writeTextAtomic(abs, next);
1049
+ return true;
982
1050
  }
983
- async#helperDefinitions(graph, ids, code) {
984
- const hashes = [...new Set(ids.flatMap((id) => graph.modules[id]?.helpers ?? []))].sort();
985
- return (await Promise.all(hashes.map(async (hash) => code?.helpers.get(hash) ?? Bun.file(this.#helpersPath(hash)).text()))).join("");
1051
+ async#extraResolverFor(abs, ctx) {
1052
+ const resolvers = [];
1053
+ if (ctx.role === "srvkit" || ctx.role === "common")
1054
+ resolvers.push(await this.#libBarrelResolver(abs, ctx));
1055
+ const kinds = DOMAIN_ROLE_KINDS[ctx.role];
1056
+ if (kinds)
1057
+ resolvers.push(await this.#domainResolver(abs, ctx, kinds));
1058
+ if (resolvers.length === 0)
1059
+ return;
1060
+ return (symbol) => {
1061
+ for (const resolve of resolvers) {
1062
+ const target = resolve(symbol);
1063
+ if (target)
1064
+ return target;
1065
+ }
1066
+ return null;
1067
+ };
986
1068
  }
987
- async#defineLines(ids, code) {
988
- return await Promise.all(ids.map(async (id) => {
989
- const factory = code?.modules.get(id) ?? await Bun.file(this.#modulePath(id, ".js")).text();
990
- return `__akan.define(${JSON.stringify(id)}, ${factory});
991
- `;
992
- }));
1069
+ async#domainResolver(abs, ctx, kinds) {
1070
+ const index = await this.#domainIndex(path4.join(this.#workspaceRoot, ctx.scope, ctx.project));
1071
+ const fileDir = path4.dirname(abs);
1072
+ return (symbol) => {
1073
+ if (!PASCAL_CASE_RE.test(symbol) || DOMAIN_DENYLIST.has(symbol))
1074
+ return null;
1075
+ const entries = (index.get(symbol) ?? []).filter((entry) => kinds.includes(entry.kind));
1076
+ if (entries.length !== 1)
1077
+ return null;
1078
+ return { specifier: relativeSpecifier(fileDir, entries[0].file), kind: "named" };
1079
+ };
993
1080
  }
994
- async#writeWithSourceMap(name, header, blocks, footer) {
995
- const layout = { lineCount: 0, modules: [] };
996
- let line = CsrDevPaths.lineCount(header);
997
- for (const [id, text] of blocks) {
998
- layout.modules.push([id, line + 1]);
999
- line += CsrDevPaths.lineCount(text);
1081
+ async#libBarrelResolver(abs, ctx) {
1082
+ const fileDir = path4.dirname(abs);
1083
+ const libDir = path4.join(this.#workspaceRoot, ctx.scope, ctx.project, "lib");
1084
+ const available = new Map;
1085
+ for (const [symbol, { barrel, kind }] of Object.entries(LIB_BARRELS)) {
1086
+ if (await fileExists(path4.join(libDir, `${barrel}.ts`)))
1087
+ available.set(symbol, { specifier: relativeSpecifier(fileDir, path4.join(libDir, barrel)), kind });
1000
1088
  }
1001
- const code = `${header}${blocks.map(([, text]) => text).join("")}${footer}//# sourceMappingURL=${name}.map
1002
- `;
1003
- layout.lineCount = CsrDevPaths.lineCount(code);
1004
- await this.writeJson(`${name}.layout.json`, layout);
1005
- await this.#writeAtomic(name, code);
1089
+ return (symbol) => available.get(symbol) ?? null;
1006
1090
  }
1007
- async#writeAtomic(name, content) {
1008
- const target = path3.join(this.#outDir, name);
1009
- const temp = `${target}.${process.pid}.tmp`;
1010
- await Bun.write(temp, content);
1011
- await FileSys2.replace(temp, target);
1091
+ async#domainIndex(pkgRoot) {
1092
+ const cached = this.#domainCache.get(pkgRoot);
1093
+ if (cached)
1094
+ return cached;
1095
+ const index = await buildDomainIndex(path4.join(pkgRoot, "lib"));
1096
+ this.#domainCache.set(pkgRoot, index);
1097
+ return index;
1012
1098
  }
1013
- static async#remove(file) {
1014
- await rm(file, { force: true }).catch(() => {
1015
- return;
1016
- });
1099
+ #domainPkgRootOf(file) {
1100
+ const rel = path4.relative(this.#workspaceRoot, path4.resolve(file));
1101
+ if (rel.startsWith("..") || path4.isAbsolute(rel))
1102
+ return null;
1103
+ const [scope, project, facet] = rel.split(path4.sep).filter(Boolean);
1104
+ if (scope !== "apps" && scope !== "libs" || !project || facet !== "lib")
1105
+ return null;
1106
+ if (!domainKindOf(path4.basename(file)))
1107
+ return null;
1108
+ return path4.join(this.#workspaceRoot, scope, project);
1017
1109
  }
1018
- static async#appWriteDelay() {
1019
- const ms = Number(process.env.AKAN_CSR_DEV_APP_WRITE_DELAY_MS);
1020
- if (Number.isInteger(ms) && ms > 0)
1021
- await Bun.sleep(ms);
1110
+ }
1111
+ var roleFor = (facet, base) => {
1112
+ if (facet === "lib") {
1113
+ if (base.endsWith(".constant.ts"))
1114
+ return "constant";
1115
+ if (base.endsWith(".document.ts"))
1116
+ return "document";
1117
+ if (base.endsWith(".service.ts"))
1118
+ return "service";
1119
+ if (base.endsWith(".signal.ts"))
1120
+ return "signal";
1121
+ if (base.endsWith(".dictionary.ts"))
1122
+ return "dictionary";
1123
+ if (base.endsWith(".store.ts"))
1124
+ return "store";
1125
+ if (base.endsWith(".tsx"))
1126
+ return "client";
1127
+ return null;
1022
1128
  }
1023
- #modulePath(id, extension) {
1024
- return path3.join(this.#outDir, csrDevModuleFile(id, extension));
1129
+ if (facet === "ui" || facet === "page")
1130
+ return base.endsWith(".tsx") ? "client" : null;
1131
+ if (facet === "webkit")
1132
+ return base.endsWith(".ts") || base.endsWith(".tsx") ? "client" : null;
1133
+ if (facet === "srvkit")
1134
+ return base.endsWith(".ts") ? "srvkit" : null;
1135
+ if (facet === "common")
1136
+ return base.endsWith(".ts") || base.endsWith(".tsx") ? "common" : null;
1137
+ return null;
1138
+ };
1139
+ var targetFor = (symbol, ctx) => {
1140
+ for (const rule of RULES[ctx.role]) {
1141
+ if (!rule.names.includes(symbol))
1142
+ continue;
1143
+ const specifier = typeof rule.specifier === "function" ? rule.specifier(ctx) : rule.specifier;
1144
+ return { specifier, kind: rule.kind, typeOnly: rule.typeOnly };
1145
+ }
1146
+ return null;
1147
+ };
1148
+ var transformSource = (source, fileName, ctx, resolveExtra) => {
1149
+ const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, scriptKindFor(fileName));
1150
+ const bound = collectBoundNames(sf);
1151
+ const used = collectUsedReferences(sf);
1152
+ const bareGlobals = collectBareGlobalReferences(sf);
1153
+ const namedBySpecifier = new Map;
1154
+ const namespaceImports = [];
1155
+ for (const name of used) {
1156
+ if (bound.has(name) || bareGlobals.has(name))
1157
+ continue;
1158
+ const target = targetFor(name, ctx) ?? resolveExtra?.(name) ?? null;
1159
+ if (!target)
1160
+ continue;
1161
+ if (target.kind === "namespace")
1162
+ namespaceImports.push({ name, specifier: target.specifier });
1163
+ else {
1164
+ const names = namedBySpecifier.get(target.specifier) ?? new Map;
1165
+ names.set(name, target.typeOnly ?? false);
1166
+ namedBySpecifier.set(target.specifier, names);
1167
+ }
1025
1168
  }
1026
- #helpersPath(hash) {
1027
- return path3.join(this.#outDir, "modules", `helpers-${hash}.js`);
1169
+ if (namedBySpecifier.size === 0 && namespaceImports.length === 0)
1170
+ return null;
1171
+ const importDecls = sf.statements.filter(ts.isImportDeclaration);
1172
+ const anchor = importDecls.at(-1) ?? null;
1173
+ const namedImportsBySpecifier = collectExistingNamedImports(importDecls);
1174
+ const edits = [];
1175
+ const newStatements = [];
1176
+ for (const [specifier, names] of namedBySpecifier) {
1177
+ const existing = namedImportsBySpecifier.get(specifier);
1178
+ if (existing) {
1179
+ const merged = new Map(existing.names);
1180
+ for (const [name, isType] of names)
1181
+ if (!merged.has(name))
1182
+ merged.set(name, isType);
1183
+ edits.push({
1184
+ start: existing.decl.getStart(sf),
1185
+ end: existing.decl.getEnd(),
1186
+ text: formatNamedImport(specifier, merged)
1187
+ });
1188
+ } else
1189
+ newStatements.push(formatNamedImport(specifier, names));
1028
1190
  }
1029
- }
1030
-
1031
- // pkgs/@akanjs/devkit/frontendBuild/csrDevModuleCompiler.ts
1032
- import path8 from "path";
1191
+ for (const ns of namespaceImports)
1192
+ newStatements.push(`import * as ${ns.name} from "${ns.specifier}";`);
1193
+ if (newStatements.length > 0) {
1194
+ const anchorEdit = anchor ? edits.find((edit) => edit.start === anchor.getStart(sf)) : undefined;
1195
+ if (anchorEdit)
1196
+ anchorEdit.text = `${anchorEdit.text}
1197
+ ${newStatements.join(`
1198
+ `)}`;
1199
+ else if (anchor)
1200
+ edits.push({ start: anchor.getEnd(), end: anchor.getEnd(), text: `
1201
+ ${newStatements.join(`
1202
+ `)}` });
1203
+ else {
1204
+ const prologueEnd = directivePrologueEnd(sf);
1205
+ if (prologueEnd >= 0)
1206
+ edits.push({ start: prologueEnd, end: prologueEnd, text: `
1207
+ ${newStatements.join(`
1208
+ `)}` });
1209
+ else
1210
+ edits.push({ start: 0, end: 0, text: `${newStatements.join(`
1211
+ `)}
1033
1212
 
1034
- // pkgs/@akanjs/devkit/frontendBuild/csrDevFactoryCheck.ts
1035
- class CsrDevFactoryCheck {
1036
- static #parsed = new Set;
1037
- static problemOf(factory, helperDefinition = "") {
1038
- const key = Bun.hash(`${helperDefinition}\x00${factory}`);
1039
- if (CsrDevFactoryCheck.#parsed.has(key))
1040
- return null;
1041
- const problem = CsrDevFactoryCheck.#syntaxError(`${helperDefinition}return (${factory});`);
1042
- if (problem === null) {
1043
- CsrDevFactoryCheck.#parsed.add(key);
1044
- return null;
1045
- }
1046
- if (problem.includes("import.meta")) {
1047
- const line = factory.split(`
1048
- `).findIndex((text) => /(?<![\w$.])import\.meta\b/.test(text));
1049
- return `import.meta is left in it${line > 0 ? ` (compiled line ${line})` : ""}, which a classic script cannot hold: ${problem}`;
1213
+ ` });
1050
1214
  }
1051
- if (CsrDevFactoryCheck.#syntaxError(`${helperDefinition}return (async ${factory});`) === null)
1052
- return `a top-level await is left in it, which a CommonJS factory cannot wait on: ${problem}`;
1053
- return problem;
1054
- }
1055
- static thrower(id, problem) {
1056
- const message = `[akan-csr] ${id} was left out of the dev registry: ${problem}`;
1057
- return `function () {
1058
- throw new Error(${JSON.stringify(message)});
1059
- }`;
1060
1215
  }
1061
- static #syntaxError(source) {
1062
- try {
1063
- new Function(source);
1064
- return null;
1065
- } catch (error) {
1066
- return error instanceof Error ? error.message : String(error);
1216
+ if (edits.length === 0)
1217
+ return null;
1218
+ edits.sort((a, b) => b.start - a.start);
1219
+ let out = source;
1220
+ for (const edit of edits)
1221
+ out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
1222
+ return out === source ? null : out;
1223
+ };
1224
+ var collectBoundNames = (sf) => {
1225
+ const names = new Set;
1226
+ const visit = (node) => {
1227
+ if (ts.isImportClause(node)) {
1228
+ if (node.name)
1229
+ names.add(node.name.text);
1230
+ const bindings = node.namedBindings;
1231
+ if (bindings && ts.isNamespaceImport(bindings))
1232
+ names.add(bindings.name.text);
1233
+ if (bindings && ts.isNamedImports(bindings))
1234
+ for (const el of bindings.elements)
1235
+ names.add(el.name.text);
1236
+ }
1237
+ if ((ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isParameter(node) || ts.isBindingElement(node) || ts.isEnumDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isInterfaceDeclaration(node)) && node.name && ts.isIdentifier(node.name))
1238
+ names.add(node.name.text);
1239
+ ts.forEachChild(node, visit);
1240
+ };
1241
+ ts.forEachChild(sf, visit);
1242
+ return names;
1243
+ };
1244
+ var collectUsedReferences = (sf) => {
1245
+ const used = new Set;
1246
+ const visit = (node) => {
1247
+ if (ts.isIdentifier(node) && isReferencePosition(node))
1248
+ used.add(node.text);
1249
+ ts.forEachChild(node, visit);
1250
+ };
1251
+ ts.forEachChild(sf, visit);
1252
+ return used;
1253
+ };
1254
+ var collectBareGlobalReferences = (sf) => {
1255
+ const bare = new Set;
1256
+ const visit = (node) => {
1257
+ if (ts.isIdentifier(node) && GLOBAL_NAMES.has(node.text) && isReferencePosition(node)) {
1258
+ const parent = node.parent;
1259
+ if (!(parent && ts.isPropertyAccessExpression(parent) && parent.expression === node))
1260
+ bare.add(node.text);
1067
1261
  }
1262
+ ts.forEachChild(node, visit);
1263
+ };
1264
+ ts.forEachChild(sf, visit);
1265
+ return bare;
1266
+ };
1267
+ var isReferencePosition = (node) => {
1268
+ const parent = node.parent;
1269
+ if (!parent)
1270
+ return true;
1271
+ if (ts.isPropertyAccessExpression(parent) && parent.name === node)
1272
+ return false;
1273
+ if (ts.isQualifiedName(parent) && parent.right === node)
1274
+ return false;
1275
+ if (ts.isPropertyAssignment(parent) && parent.name === node)
1276
+ return false;
1277
+ if (ts.isPropertySignature(parent) && parent.name === node)
1278
+ return false;
1279
+ if (ts.isBindingElement(parent) && parent.propertyName === node)
1280
+ return false;
1281
+ if (ts.isImportSpecifier(parent) || ts.isExportSpecifier(parent))
1282
+ return false;
1283
+ return true;
1284
+ };
1285
+ var collectExistingNamedImports = (importDecls) => {
1286
+ const map = new Map;
1287
+ for (const decl of importDecls) {
1288
+ const clause = decl.importClause;
1289
+ const bindings = clause?.namedBindings;
1290
+ if (!clause || !bindings || !ts.isNamedImports(bindings))
1291
+ continue;
1292
+ if (!ts.isStringLiteral(decl.moduleSpecifier))
1293
+ continue;
1294
+ const specifier = decl.moduleSpecifier.text;
1295
+ if (map.has(specifier))
1296
+ continue;
1297
+ const names = new Map;
1298
+ for (const el of bindings.elements)
1299
+ names.set(el.name.text, clause.isTypeOnly || el.isTypeOnly);
1300
+ map.set(specifier, { decl, names });
1068
1301
  }
1069
- }
1070
-
1071
- // pkgs/@akanjs/devkit/frontendBuild/csrDevResolver.ts
1072
- import fs3 from "fs";
1073
- import path4 from "path";
1074
- class CsrDevResolver {
1075
- static inline = "inline";
1076
- #paths;
1077
- #context;
1078
- #entryFiles;
1079
- #resolution = new Map;
1080
- #fallbacks = new Set;
1081
- #runtimeResolved = new Map;
1082
- #browserMaps = new Map;
1083
- #loaded = new Set;
1084
- #startedAt;
1085
- #prepassDone = false;
1086
- constructor({
1087
- paths,
1088
- context,
1089
- entryFiles,
1090
- resolution = {},
1091
- runtimeResolved = {},
1092
- startedAt = Date.now() - process.uptime() * 1000
1093
- }) {
1094
- this.#paths = paths;
1095
- this.#startedAt = startedAt;
1096
- this.#context = context;
1097
- this.#entryFiles = entryFiles;
1098
- for (const [importer, specifiers] of Object.entries(runtimeResolved))
1099
- this.#runtimeResolved.set(paths.fileOf(importer), new Set(specifiers));
1100
- for (const [importer, bySpecifier] of Object.entries(resolution))
1101
- this.#resolution.set(paths.fileOf(importer), new Map(Object.entries(bySpecifier).map(([specifier, target]) => [
1102
- specifier,
1103
- CsrDevPaths.isStub(target) ? target : paths.fileOf(target)
1104
- ])));
1302
+ return map;
1303
+ };
1304
+ var formatNamedImport = (specifier, names) => {
1305
+ const entries = [...names.entries()].sort((a, b) => compareNames(a[0], b[0]));
1306
+ if (entries.every(([, isType]) => isType))
1307
+ return `import type { ${entries.map(([name]) => name).join(", ")} } from "${specifier}";`;
1308
+ const parts = entries.map(([name, isType]) => isType ? `type ${name}` : name);
1309
+ return `import { ${parts.join(", ")} } from "${specifier}";`;
1310
+ };
1311
+ var directivePrologueEnd = (sf) => {
1312
+ let end = -1;
1313
+ for (const stmt of sf.statements) {
1314
+ if (ts.isExpressionStatement(stmt) && ts.isStringLiteral(stmt.expression))
1315
+ end = stmt.getEnd();
1316
+ else
1317
+ break;
1105
1318
  }
1106
- get prepassDone() {
1107
- return this.#prepassDone;
1319
+ return end;
1320
+ };
1321
+ var scriptKindFor = (fileName) => fileName.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
1322
+ var compareNames = (a, b) => {
1323
+ const [la, lb] = [a.toLowerCase(), b.toLowerCase()];
1324
+ if (la !== lb)
1325
+ return la < lb ? -1 : 1;
1326
+ return a < b ? -1 : a > b ? 1 : 0;
1327
+ };
1328
+ var formatError = (err) => err instanceof Error ? err.message : String(err);
1329
+ var fileExists = async (file) => stat(file).then((s) => s.isFile()).catch(() => false);
1330
+ var domainKindOf = (base) => {
1331
+ if (base.endsWith(".constant.ts"))
1332
+ return "constant";
1333
+ if (base.endsWith(".document.ts"))
1334
+ return "document";
1335
+ if (base.endsWith(".signal.ts"))
1336
+ return "signal";
1337
+ return null;
1338
+ };
1339
+ var buildDomainIndex = async (libDir) => {
1340
+ const index = new Map;
1341
+ for (const file of await collectDomainFiles(libDir)) {
1342
+ const kind = domainKindOf(path4.basename(file));
1343
+ if (!kind)
1344
+ continue;
1345
+ const src = await readFile(file, "utf8").catch(() => null);
1346
+ if (src === null)
1347
+ continue;
1348
+ for (const name of exportedPascalNames(src, file)) {
1349
+ const entries = index.get(name) ?? [];
1350
+ entries.push({ file, kind });
1351
+ index.set(name, entries);
1352
+ }
1108
1353
  }
1109
- get fallbacks() {
1110
- return this.#fallbacks;
1354
+ return index;
1355
+ };
1356
+ var collectDomainFiles = async (dir) => {
1357
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
1358
+ const files = [];
1359
+ for (const entry of entries) {
1360
+ if (entry.name.startsWith(".") || entry.name === "node_modules")
1361
+ continue;
1362
+ const full = path4.join(dir, entry.name);
1363
+ if (entry.isDirectory())
1364
+ files.push(...await collectDomainFiles(full));
1365
+ else if (domainKindOf(entry.name) && !TEST_FILE_RE.test(entry.name))
1366
+ files.push(full);
1111
1367
  }
1112
- async prepass() {
1113
- const result = await Bun.build({
1114
- entrypoints: [...this.#entryFiles, ...this.#context.refreshFile ? [this.#context.refreshFile] : []],
1115
- target: "browser",
1116
- metafile: true,
1117
- external: [...this.#context.externals ?? []],
1118
- define: this.#context.define,
1119
- optimizeImports: this.#context.optimizeImports,
1120
- plugins: [PagesBundleBuilder.createCssStubPlugin()]
1121
- });
1122
- this.#record(result.metafile.inputs);
1123
- this.#prepassDone = true;
1368
+ return files;
1369
+ };
1370
+ var exportedPascalNames = (source, fileName) => {
1371
+ const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true);
1372
+ const isExported = (node) => ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
1373
+ const names = [];
1374
+ for (const stmt of sf.statements) {
1375
+ if ((ts.isClassDeclaration(stmt) || ts.isFunctionDeclaration(stmt) || ts.isEnumDeclaration(stmt)) && stmt.name) {
1376
+ if (isExported(stmt))
1377
+ names.push(stmt.name.text);
1378
+ } else if (ts.isVariableStatement(stmt) && isExported(stmt)) {
1379
+ for (const decl of stmt.declarationList.declarations)
1380
+ if (ts.isIdentifier(decl.name))
1381
+ names.push(decl.name.text);
1382
+ } else if (ts.isExportDeclaration(stmt) && stmt.exportClause && ts.isNamedExports(stmt.exportClause)) {
1383
+ for (const el of stmt.exportClause.elements)
1384
+ names.push(el.name.text);
1385
+ }
1124
1386
  }
1125
- async cover(files) {
1126
- if (!this.#prepassDone)
1127
- return;
1128
- const pending = files.filter((file) => CsrDevPaths.isScript(file) && !this.#loaded.has(file));
1129
- if (pending.length === 0)
1130
- return;
1131
- for (const file of pending)
1132
- this.#loaded.add(file);
1133
- const entries = new Set(pending);
1134
- const result = await Bun.build({
1135
- entrypoints: pending,
1136
- target: "browser",
1137
- metafile: true,
1138
- throw: false,
1139
- external: [...this.#context.externals ?? []],
1140
- define: this.#context.define,
1141
- plugins: [
1142
- {
1143
- name: "akan-csr-cover",
1144
- setup: (build) => {
1145
- build.onLoad({ filter: /.*/ }, (args) => entries.has(CsrDevPaths.realpath(args.path)) ? undefined : { contents: "module.exports = {};", loader: "js" });
1146
- }
1147
- }
1148
- ]
1149
- });
1150
- if (result.metafile)
1151
- this.#record(result.metafile.inputs, entries);
1387
+ return names.filter((name) => PASCAL_CASE_RE.test(name));
1388
+ };
1389
+ var relativeSpecifier = (fromDir, toFile) => {
1390
+ const rel = path4.relative(fromDir, toFile).replace(/\.tsx?$/, "").split(path4.sep).join("/");
1391
+ return rel.startsWith(".") ? rel : `./${rel}`;
1392
+ };
1393
+
1394
+ // pkgs/@akanjs/devkit/frontendBuild/devChangePlanner.ts
1395
+ import path5 from "path";
1396
+ var CONFIG_BASENAMES = new Set(["akan.config.ts", "bunfig.toml", "tsconfig.json", "package.json"]);
1397
+ var BARREL_FACETS = new Set(["common", "srvkit", "ui", "webkit", "plugin"]);
1398
+ var CLIENT_SUFFIXES = [".Template.tsx", ".Unit.tsx", ".Util.tsx", ".View.tsx", ".Zone.tsx", ".store.ts"];
1399
+ var SHARED_SUFFIXES = [".constant.ts", ".dictionary.ts", ".signal.ts"];
1400
+ var SERVER_SUFFIXES = [".service.ts", ".document.ts"];
1401
+ var RUNTIME_METADATA_BASENAMES = new Set(["dict.ts", "sig.ts", "useClient.ts", "useServer.ts"]);
1402
+
1403
+ class DevChangePlanner {
1404
+ #workspaceRoot;
1405
+ constructor({ workspaceRoot }) {
1406
+ this.#workspaceRoot = path5.resolve(workspaceRoot);
1152
1407
  }
1153
- #record(inputs, only) {
1154
- for (const [input, { imports }] of Object.entries(inputs)) {
1155
- const importer = CsrDevPaths.realpath(path4.resolve(input));
1156
- if (only && !only.has(importer))
1157
- continue;
1158
- if (imports.every((record) => record.original))
1159
- this.#loaded.add(importer);
1160
- for (const record of imports) {
1161
- if (!record.original)
1162
- continue;
1163
- if (record.external) {
1164
- if (record.original.startsWith("node:"))
1165
- this.#remember(importer, record.original, `${CsrDevPaths.stubPrefix}${record.original}`);
1166
- continue;
1167
- }
1168
- const target = path4.resolve(record.path);
1169
- if (!fs3.existsSync(target))
1170
- continue;
1171
- this.#remember(importer, record.original, CsrDevPaths.realpath(target));
1172
- this.#runtimeResolved.get(importer)?.delete(record.original);
1408
+ plan({ generation, files, kinds, generatedFiles = [] }) {
1409
+ const fileList = uniqueResolved([...files, ...generatedFiles]);
1410
+ const generatedSet = new Set(generatedFiles.map((file) => path5.resolve(file)));
1411
+ const kindSet = new Set(kinds);
1412
+ const roles = new Set;
1413
+ const actions = new Set;
1414
+ const reasonByFile = {};
1415
+ for (const kind of kindSet) {
1416
+ if (kind === "css") {
1417
+ roles.add("css");
1418
+ actions.add("rebuild-css");
1419
+ }
1420
+ if (kind === "config") {
1421
+ roles.add("config");
1422
+ actions.add("restart-dev-host");
1173
1423
  }
1174
1424
  }
1425
+ for (const file of fileList) {
1426
+ const reasons = new Set;
1427
+ const fileRoles = this.#rolesForFile(file, { isGenerated: generatedSet.has(path5.resolve(file)), reasons });
1428
+ for (const role of fileRoles)
1429
+ roles.add(role);
1430
+ if (reasons.has("runtime-metadata"))
1431
+ actions.add("restart-builder");
1432
+ if (reasons.size > 0)
1433
+ reasonByFile[path5.resolve(file)] = [...reasons].sort();
1434
+ }
1435
+ if (roles.has("barrel"))
1436
+ actions.add("sync-generated");
1437
+ if (roles.has("server") || roles.has("shared"))
1438
+ actions.add("restart-backend");
1439
+ if (roles.has("client") || roles.has("shared"))
1440
+ actions.add("rebuild-client");
1441
+ if (roles.has("css"))
1442
+ actions.add("rebuild-css");
1443
+ return {
1444
+ generation,
1445
+ files: fileList,
1446
+ generatedFiles: uniqueResolved(generatedFiles),
1447
+ roles: [...roles].sort(),
1448
+ actions: [...actions].sort(),
1449
+ reasonByFile
1450
+ };
1175
1451
  }
1176
- resolve(importer, specifier, kind = "import") {
1177
- if (this.#isInlineSpecifier(specifier))
1178
- return CsrDevResolver.inline;
1179
- const disabled = this.#disabledInBrowser(importer, specifier, kind);
1180
- if (disabled)
1181
- return disabled;
1182
- const known = this.#resolution.get(importer)?.get(specifier);
1183
- const usable = known && this.#stillAnswers(importer, specifier, known, kind) ? known : null;
1184
- const target = usable ?? this.#resolveUnknown(importer, specifier, kind);
1185
- if (target === null || CsrDevPaths.isStub(target))
1186
- return target;
1187
- if (!CsrDevPaths.isScript(target))
1188
- return CsrDevResolver.inline;
1189
- if (!usable)
1190
- this.#remember(importer, specifier, target);
1191
- return target;
1192
- }
1193
- #stillAnswers(importer, specifier, known, kind) {
1194
- if (CsrDevPaths.isStub(known))
1195
- return true;
1196
- if (!fs3.existsSync(known))
1197
- return false;
1198
- if (!specifier.startsWith(".") || CsrDevPaths.isVendorFile(importer))
1199
- return true;
1200
- if (this.#hasBrowserMap(path4.dirname(importer)))
1201
- return true;
1202
- const onDisk = CsrDevPaths.resolveRelative(path4.dirname(importer), specifier, kind);
1203
- return onDisk !== null && CsrDevPaths.realpath(onDisk) === known;
1452
+ #rolesForFile(file, { isGenerated, reasons }) {
1453
+ const roles = new Set;
1454
+ const abs = path5.resolve(file);
1455
+ const base = path5.basename(abs);
1456
+ const ext = path5.extname(abs).toLowerCase();
1457
+ const isSource = SOURCE_EXTS.has(ext);
1458
+ const rel = path5.relative(this.#workspaceRoot, abs);
1459
+ const parts = rel.split(path5.sep).filter(Boolean);
1460
+ if (CONFIG_BASENAMES.has(base)) {
1461
+ roles.add("config");
1462
+ reasons.add("config-file");
1463
+ }
1464
+ if (ext === ".css") {
1465
+ roles.add("css");
1466
+ reasons.add("css-file");
1467
+ }
1468
+ if (isGenerated || isSource && this.#isBarrelFacetChild(parts)) {
1469
+ roles.add("barrel");
1470
+ reasons.add(isGenerated ? "generated-index" : "barrel-facet-child");
1471
+ }
1472
+ if (isSource && this.#isServerBiased(base, parts)) {
1473
+ roles.add("server");
1474
+ reasons.add("server-path");
1475
+ }
1476
+ if (isSource && this.#isClientBiased(base, parts)) {
1477
+ roles.add("client");
1478
+ reasons.add("client-path");
1479
+ }
1480
+ if (isSource && this.#isSharedBiased(base, parts)) {
1481
+ roles.add("shared");
1482
+ reasons.add("shared-path");
1483
+ }
1484
+ if (isSource && this.#isRuntimeMetadataFile(parts, base)) {
1485
+ reasons.add("runtime-metadata");
1486
+ }
1487
+ if (roles.has("server") && roles.has("client")) {
1488
+ roles.delete("server");
1489
+ roles.delete("client");
1490
+ roles.add("shared");
1491
+ reasons.add("server-client-overlap");
1492
+ }
1493
+ if (roles.size === 0 && SOURCE_EXTS.has(ext) && this.#isWorkspaceSource(rel)) {
1494
+ roles.add("shared");
1495
+ reasons.add("workspace-source-fallback");
1496
+ }
1497
+ return roles;
1204
1498
  }
1205
- isRegistryModule(file) {
1206
- if (!CsrDevPaths.isScript(file))
1207
- return false;
1208
- const packageName = CsrDevResolver.#packageNameOf(file);
1209
- if (packageName === null)
1210
- return true;
1211
- return !this.#context.optimizeImports.some((pattern) => {
1212
- const base = CsrDevResolver.#patternBase(pattern);
1213
- return base === packageName || base.startsWith(`${packageName}/`);
1214
- });
1499
+ #isServerBiased(base, parts) {
1500
+ return parts.includes("srvkit") || SERVER_SUFFIXES.some((suffix) => base.endsWith(suffix)) || base === "main.ts" || base === "server.ts";
1215
1501
  }
1216
- #disabledInBrowser(importer, specifier, kind) {
1217
- const map = this.#browserMapOf(path4.dirname(importer));
1218
- if (!map || map.offFiles.size === 0 && map.offNames.size === 0)
1219
- return null;
1220
- if (!specifier.startsWith(".") && !path4.isAbsolute(specifier))
1221
- return map.offNames.has(specifier) ? `${CsrDevPaths.emptyStubPrefix}${specifier}` : null;
1222
- const target = CsrDevPaths.resolveRelative(path4.dirname(importer), specifier, kind);
1223
- return target && map.offFiles.has(CsrDevPaths.realpath(target)) ? `${CsrDevPaths.emptyStubPrefix}${this.#paths.idOf(target)}` : null;
1502
+ #isClientBiased(base, parts) {
1503
+ return parts.includes("ui") || parts.includes("webkit") || parts.includes("page") || CLIENT_SUFFIXES.some((suffix) => base.endsWith(suffix));
1224
1504
  }
1225
- #hasBrowserMap(dir) {
1226
- return this.#browserMapOf(dir) !== null;
1505
+ #isSharedBiased(base, parts) {
1506
+ return parts.includes("common") || SHARED_SUFFIXES.some((suffix) => base.endsWith(suffix)) || RUNTIME_METADATA_BASENAMES.has(base);
1227
1507
  }
1228
- #browserMapOf(dir) {
1229
- const cached = this.#browserMaps.get(dir);
1230
- if (cached !== undefined)
1231
- return cached;
1232
- const pkgFile = path4.join(dir, "package.json");
1233
- const parent = path4.dirname(dir);
1234
- let map = null;
1235
- if (fs3.existsSync(pkgFile)) {
1236
- try {
1237
- const browser = JSON.parse(fs3.readFileSync(pkgFile, "utf8")).browser;
1238
- if (typeof browser === "object" && browser !== null) {
1239
- const off = Object.entries(browser).filter(([, target]) => target === false).map(([key]) => key);
1240
- const files = off.filter((key) => key.startsWith(".")).map((key) => CsrDevPaths.resolveRelative(dir, key)).filter((file) => !!file);
1241
- map = {
1242
- offFiles: new Set(files.map((file) => CsrDevPaths.realpath(file))),
1243
- offNames: new Set(off.filter((key) => !key.startsWith(".")))
1244
- };
1245
- }
1246
- } catch {}
1247
- } else if (parent !== dir)
1248
- map = this.#browserMapOf(parent);
1249
- this.#browserMaps.set(dir, map);
1250
- return map;
1508
+ #isRuntimeMetadataFile(parts, base) {
1509
+ const parent = parts.at(-2);
1510
+ if (parent === "lib" && RUNTIME_METADATA_BASENAMES.has(base))
1511
+ return true;
1512
+ const libIndex = parts.lastIndexOf("lib");
1513
+ if (libIndex < 0 || parts.length <= libIndex + 1)
1514
+ return false;
1515
+ return base.endsWith(".dictionary.ts") || base.endsWith(".signal.ts");
1251
1516
  }
1252
- forget(importer) {
1253
- this.#resolution.delete(importer);
1254
- this.#runtimeResolved.delete(importer);
1517
+ #isBarrelFacetChild(parts) {
1518
+ if (parts.length < 4)
1519
+ return false;
1520
+ const [scope, , facet, child] = parts;
1521
+ if (scope !== "apps" && scope !== "libs")
1522
+ return false;
1523
+ if (!facet || !BARREL_FACETS.has(facet))
1524
+ return false;
1525
+ if (!child || child.startsWith(".") || child === "index.ts" || child === "index.tsx")
1526
+ return false;
1527
+ return true;
1255
1528
  }
1256
- serializeRuntimeResolved() {
1257
- return Object.fromEntries([...this.#runtimeResolved].filter(([, specifiers]) => specifiers.size > 0).map(([importer, specifiers]) => [this.#paths.idOf(importer), [...specifiers].sort()]));
1529
+ #isWorkspaceSource(rel) {
1530
+ if (!rel || rel.startsWith("..") || path5.isAbsolute(rel))
1531
+ return false;
1532
+ const [scope] = rel.split(path5.sep);
1533
+ return scope === "apps" || scope === "libs" || scope === "pkgs";
1258
1534
  }
1259
- serialize() {
1260
- return Object.fromEntries([...this.#resolution].map(([importer, bySpecifier]) => [
1261
- this.#paths.idOf(importer),
1262
- Object.fromEntries([...bySpecifier].filter(([, target]) => CsrDevPaths.isStub(target) || fs3.existsSync(target)).map(([specifier, target]) => [specifier, CsrDevPaths.isStub(target) ? target : this.#paths.idOf(target)]))
1263
- ]));
1535
+ }
1536
+ var uniqueResolved = (files) => [...new Set(files.map((file) => path5.resolve(file)))].sort();
1537
+
1538
+ // pkgs/@akanjs/devkit/frontendBuild/devGeneratedIndexSync.ts
1539
+ import { mkdir as mkdir2, readdir as readdir2, readFile as readFile2, rm, stat as stat2 } from "fs/promises";
1540
+ import path6 from "path";
1541
+ import { barrelFacetDirs, capitalize, facetBarrelOf } from "akanjs/common";
1542
+ var BARREL_FACETS2 = new Set(barrelFacetDirs);
1543
+ var MODULE_UI_TYPES = ["Template", "Unit", "Util", "View", "Zone"];
1544
+ var SERVICE_UI_TYPES = ["Util", "Zone"];
1545
+ var SCALAR_UI_TYPES = ["Template", "Unit"];
1546
+
1547
+ class DevGeneratedIndexSync {
1548
+ #workspaceRoot;
1549
+ constructor({ workspaceRoot }) {
1550
+ this.#workspaceRoot = path6.resolve(workspaceRoot);
1264
1551
  }
1265
- #resolveUnknown(importer, specifier, kind) {
1266
- if (specifier.startsWith("node:"))
1267
- return `${CsrDevPaths.stubPrefix}${specifier}`;
1268
- const relative = specifier.startsWith(".") || path4.isAbsolute(specifier);
1269
- const cannotResolve = () => new Error(`[csr-dev] cannot resolve "${specifier}" from ${this.#paths.idOf(importer)}`);
1270
- if (relative) {
1271
- const onDisk = CsrDevPaths.resolveRelative(path4.dirname(importer), specifier, kind) ?? CsrDevResolver.#onDisk(CsrDevPaths.tryResolve(specifier, path4.dirname(importer)));
1272
- if (!onDisk)
1273
- throw cannotResolve();
1274
- return CsrDevPaths.realpath(onDisk);
1275
- }
1276
- const sibling = this.#resolvedBySibling(importer, specifier);
1277
- if (sibling)
1278
- return sibling;
1279
- const resolved = CsrDevPaths.tryResolve(specifier, path4.dirname(importer));
1280
- const moved = resolved !== null && path4.isAbsolute(resolved) && !fs3.existsSync(resolved);
1281
- const installed = resolved === null && CsrDevPaths.installedSince(specifier, path4.dirname(importer), this.#startedAt);
1282
- if (!this.#prepassDone || moved) {
1283
- if (resolved === null && !installed && !CsrDevPaths.isVendorFile(importer))
1284
- throw cannotResolve();
1285
- return null;
1286
- }
1287
- if (!resolved) {
1288
- if (installed)
1552
+ async syncForBatch(files) {
1553
+ const indexPaths = new Set;
1554
+ const errors = [];
1555
+ for (const file of files) {
1556
+ const facetIndex = this.#facetIndexFor(file);
1557
+ if (facetIndex)
1558
+ indexPaths.add(facetIndex);
1559
+ const moduleIndex = await this.#moduleIndexForDirectoryEvent(file).catch((err) => {
1560
+ errors.push(`[generated-index] module detection failed for ${file}: ${formatError2(err)}`);
1289
1561
  return null;
1290
- throw cannotResolve();
1562
+ });
1563
+ if (moduleIndex)
1564
+ indexPaths.add(moduleIndex);
1291
1565
  }
1292
- if (!path4.isAbsolute(resolved))
1293
- return `${CsrDevPaths.stubPrefix}${specifier}`;
1294
- this.#fallbacks.add(specifier);
1295
- this.#runtimeResolved.set(importer, (this.#runtimeResolved.get(importer) ?? new Set).add(specifier));
1296
- return CsrDevPaths.realpath(resolved);
1566
+ const changedFiles = [];
1567
+ for (const indexPath of [...indexPaths].sort()) {
1568
+ try {
1569
+ const changed = await this.#syncIndex(indexPath);
1570
+ if (changed)
1571
+ changedFiles.push(indexPath);
1572
+ } catch (err) {
1573
+ errors.push(`[generated-index] sync failed for ${indexPath}: ${formatError2(err)}`);
1574
+ }
1575
+ }
1576
+ return { changedFiles, errors };
1297
1577
  }
1298
- static #onDisk(resolved) {
1299
- return resolved && path4.isAbsolute(resolved) && fs3.existsSync(resolved) ? resolved : null;
1578
+ #facetIndexFor(file) {
1579
+ const abs = path6.resolve(file);
1580
+ const rel = path6.relative(this.#workspaceRoot, abs);
1581
+ if (rel.startsWith("..") || path6.isAbsolute(rel))
1582
+ return null;
1583
+ const parts = rel.split(path6.sep).filter(Boolean);
1584
+ if (parts.length < 4)
1585
+ return null;
1586
+ const [scope, project, facet, child] = parts;
1587
+ if (scope !== "apps" && scope !== "libs" || !project || !facet || !BARREL_FACETS2.has(facet))
1588
+ return null;
1589
+ if (!child || child.startsWith(".") || child === "index.ts" || child === "index.tsx")
1590
+ return null;
1591
+ return path6.join(this.#workspaceRoot, scope, project, facet, "index.ts");
1300
1592
  }
1301
- #resolvedBySibling(importer, specifier) {
1302
- const scope = CsrDevResolver.#packageScopeOf(importer);
1303
- for (const [other, bySpecifier] of this.#resolution) {
1304
- const target = bySpecifier.get(specifier);
1305
- if (!target || other === importer || this.#runtimeResolved.get(other)?.has(specifier))
1306
- continue;
1307
- if (!CsrDevPaths.isStub(target) && !fs3.existsSync(target))
1308
- continue;
1309
- if (CsrDevResolver.#packageScopeOf(other) === scope)
1310
- return target;
1593
+ async#moduleIndexForDirectoryEvent(file) {
1594
+ const abs = path6.resolve(file);
1595
+ const rel = path6.relative(this.#workspaceRoot, abs);
1596
+ if (rel.startsWith("..") || path6.isAbsolute(rel))
1597
+ return null;
1598
+ const parts = rel.split(path6.sep).filter(Boolean);
1599
+ if (parts.length !== 4 && parts.length !== 5)
1600
+ return null;
1601
+ const [scope, project, libSegment, moduleSegment, scalarSegment] = parts;
1602
+ if (scope !== "apps" && scope !== "libs" || !project || libSegment !== "lib")
1603
+ return null;
1604
+ const isExistingDirectory = await stat2(abs).then((s) => s.isDirectory()).catch(() => false);
1605
+ const looksLikeDeletedDirectory = !path6.extname(abs);
1606
+ if (!isExistingDirectory && !looksLikeDeletedDirectory)
1607
+ return null;
1608
+ if (moduleSegment === "__scalar" && scalarSegment) {
1609
+ return path6.join(this.#workspaceRoot, scope, project, "lib", "__scalar", scalarSegment, "index.ts");
1311
1610
  }
1312
- return null;
1313
- }
1314
- #remember(importer, specifier, target) {
1315
- const byImporter = this.#resolution.get(importer) ?? new Map;
1316
- this.#resolution.set(importer, byImporter.set(specifier, target));
1611
+ if (!moduleSegment || moduleSegment === "__scalar")
1612
+ return null;
1613
+ return path6.join(this.#workspaceRoot, scope, project, "lib", moduleSegment, "index.ts");
1317
1614
  }
1318
- #isInlineSpecifier(specifier) {
1319
- if (specifier.startsWith(".") || path4.isAbsolute(specifier) || specifier.startsWith("node:"))
1615
+ async#syncIndex(indexPath) {
1616
+ const dir = path6.dirname(indexPath);
1617
+ const content = await this.#contentForIndex(indexPath);
1618
+ if (content === null) {
1619
+ if (!await exists(indexPath))
1620
+ return false;
1621
+ await rm(indexPath, { force: true });
1622
+ return true;
1623
+ }
1624
+ const current = await readFile2(indexPath, "utf8").catch(() => null);
1625
+ if (current === content)
1320
1626
  return false;
1321
- return this.#context.optimizeImports.some((pattern) => {
1322
- const base = CsrDevResolver.#patternBase(pattern);
1323
- return specifier === base || specifier.startsWith(`${base}/`);
1324
- });
1627
+ await mkdir2(dir, { recursive: true });
1628
+ await FileSys2.writeTextAtomic(indexPath, content);
1629
+ return true;
1325
1630
  }
1326
- static #patternBase(pattern) {
1327
- return pattern.endsWith("/*") ? pattern.slice(0, -2) : pattern;
1631
+ async#contentForIndex(indexPath) {
1632
+ const parts = path6.relative(this.#workspaceRoot, indexPath).split(path6.sep).filter(Boolean);
1633
+ const facet = parts.at(-2);
1634
+ if (facet && BARREL_FACETS2.has(facet))
1635
+ return this.#facetContent(path6.dirname(indexPath));
1636
+ return this.#moduleContent(path6.dirname(indexPath));
1328
1637
  }
1329
- static #packageNameOf(file) {
1330
- const marker = `${path4.sep}node_modules${path4.sep}`;
1331
- const index = file.lastIndexOf(marker);
1332
- if (index < 0)
1638
+ async#facetContent(dir) {
1639
+ const entries = await readdir2(dir, { withFileTypes: true }).catch(() => null);
1640
+ if (!entries)
1333
1641
  return null;
1334
- const [scope, name] = file.slice(index + marker.length).split(path4.sep);
1335
- return (scope?.startsWith("@") ? `${scope}/${name}` : scope) || null;
1642
+ const files = entries.filter((entry) => entry.isFile()).map((entry) => entry.name);
1643
+ const dirs = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
1644
+ return facetBarrelOf(path6.basename(dir), files, dirs);
1336
1645
  }
1337
- static #packageScopeOf(file) {
1338
- const marker = `${path4.sep}node_modules${path4.sep}`;
1339
- const index = file.lastIndexOf(marker);
1340
- if (index < 0)
1341
- return "";
1342
- const [scope, name] = file.slice(index + marker.length).split(path4.sep);
1343
- return file.slice(0, index + marker.length) + (scope?.startsWith("@") ? `${scope}${path4.sep}${name}` : scope);
1646
+ async#moduleContent(dir) {
1647
+ const rel = path6.relative(this.#workspaceRoot, dir);
1648
+ const parts = rel.split(path6.sep).filter(Boolean);
1649
+ const moduleSegment = parts.at(-1);
1650
+ if (!moduleSegment)
1651
+ return null;
1652
+ const isScalar = parts.at(-2) === "__scalar";
1653
+ const rawModel = moduleSegment.startsWith("_") ? moduleSegment.slice(1) : moduleSegment;
1654
+ if (!rawModel)
1655
+ return null;
1656
+ const modelName = capitalize(rawModel);
1657
+ const allowedTypes = isScalar ? SCALAR_UI_TYPES : moduleSegment.startsWith("_") ? SERVICE_UI_TYPES : MODULE_UI_TYPES;
1658
+ const fileTypes = [];
1659
+ for (const type of allowedTypes) {
1660
+ if (await exists(path6.join(dir, `${modelName}.${type}.tsx`)))
1661
+ fileTypes.push(type);
1662
+ }
1663
+ if (fileTypes.length === 0)
1664
+ return null;
1665
+ return `${fileTypes.map((type) => `import * as ${type} from "./${modelName}.${type}";`).join(`
1666
+ `)}
1667
+
1668
+ export const ${modelName} = { ${fileTypes.join(", ")} };
1669
+ `;
1344
1670
  }
1345
1671
  }
1672
+ var exists = async (file) => stat2(file).then(() => true).catch(() => false);
1673
+ var formatError2 = (err) => err instanceof Error ? err.message : String(err);
1346
1674
 
1347
- // pkgs/@akanjs/devkit/frontendBuild/devBarrelImports.ts
1348
- import path5 from "path";
1349
- class DevBarrelImports {
1350
- #barrels;
1351
- #resolvePackage;
1352
- #analyzer;
1353
- #packages = new Map;
1354
- constructor(barrels, resolvePackage) {
1355
- this.#barrels = [...barrels];
1356
- this.#resolvePackage = resolvePackage;
1357
- this.#analyzer = new BarrelAnalyzer({ resolvePackage });
1675
+ // pkgs/@akanjs/devkit/frontendBuild/csrDevBundler.ts
1676
+ import { mkdir as mkdir4 } from "fs/promises";
1677
+ import path14 from "path";
1678
+ import { CSR_DEV_DIRNAME, CSR_DEV_ROUTE_PREFIX } from "akanjs/server/hmr/csrDevManifest";
1679
+
1680
+ // pkgs/@akanjs/devkit/frontendBuild/devRegistryBundler.ts
1681
+ import fs7 from "fs";
1682
+ import path13 from "path";
1683
+ import { isAkanRuntimeMetadataFile } from "akanjs/server/hmr/runtimeMetadataFile";
1684
+
1685
+ // pkgs/@akanjs/devkit/frontendBuild/csrDevArtifactWriter.ts
1686
+ import fs3 from "fs";
1687
+ import { mkdir as mkdir3, readdir as readdir3, rm as rm2 } from "fs/promises";
1688
+ import path7 from "path";
1689
+ import {
1690
+ appGenerationOf,
1691
+ CSR_DEV_APP_FILE,
1692
+ CSR_DEV_KEPT_PATCHES,
1693
+ CSR_DEV_MANIFEST_FILE,
1694
+ CSR_DEV_PATCHING_MARKER,
1695
+ csrDevModuleFile
1696
+ } from "akanjs/server/hmr/csrDevManifest";
1697
+ class CsrDevArtifactWriter {
1698
+ static #keptVendors = 3;
1699
+ static #buildingMarker = ".building";
1700
+ #outDir;
1701
+ #routePrefix;
1702
+ #library;
1703
+ constructor(outDir, { routePrefix, library = false }) {
1704
+ this.#outDir = outDir;
1705
+ this.#routePrefix = routePrefix;
1706
+ this.#library = library;
1358
1707
  }
1359
- static async create(app, barrels) {
1360
- if (barrels.length === 0)
1361
- return null;
1362
- return new DevBarrelImports(barrels, await createTsconfigPackageResolver(app));
1708
+ async markBuilding() {
1709
+ await Bun.write(path7.join(this.#outDir, CsrDevArtifactWriter.#buildingMarker), String(process.pid));
1363
1710
  }
1364
- async rewrite(source, importer) {
1365
- const named = this.#barrels.filter((barrel) => source.includes(barrel));
1366
- if (named.length === 0)
1711
+ async clearBuilding() {
1712
+ await CsrDevArtifactWriter.#remove(path7.join(this.#outDir, CsrDevArtifactWriter.#buildingMarker));
1713
+ }
1714
+ async isBuilding() {
1715
+ return await Bun.file(path7.join(this.#outDir, CsrDevArtifactWriter.#buildingMarker)).exists();
1716
+ }
1717
+ async forgetPatch(generation) {
1718
+ await Promise.all([`patch-${generation}.js`, `patch-${generation}.js.layout.json`].map((name) => CsrDevArtifactWriter.#remove(path7.join(this.#outDir, name))));
1719
+ }
1720
+ async readJson(name) {
1721
+ const file = Bun.file(path7.join(this.#outDir, name));
1722
+ if (!await file.exists())
1367
1723
  return null;
1368
- const packages = await this.#packagesOf(named);
1369
- const from = path5.dirname(CsrDevPaths.realpath(importer));
1370
- const names = new Map;
1371
- const contents = await rewriteBarrelImports(source, named, this.#analyzer, {
1372
- keepLines: true,
1373
- specifierOf: (subpath) => DevBarrelImports.#relative(subpath, from, packages),
1374
- onImport: (barrel, imported) => names.set(barrel, new Set([...names.get(barrel) ?? [], ...imported]))
1375
- });
1376
- const narrowed = await Promise.all([...names].map(async ([barrel, set]) => {
1377
- const sorted = [...set].sort();
1378
- return [barrel, { names: sorted, hash: await this.fingerprint(barrel, sorted) }];
1379
- }));
1380
- return { contents, narrowed: Object.fromEntries(narrowed) };
1724
+ return await file.json().catch(() => null);
1725
+ }
1726
+ async writeJson(name, value) {
1727
+ await this.#writeAtomic(name, JSON.stringify(value));
1728
+ }
1729
+ async writeModules(compiled) {
1730
+ await mkdir3(path7.join(this.#outDir, "modules"), { recursive: true });
1731
+ const helpers = new Map(compiled.flatMap((module) => module.helpers ? [[module.helpers.hash, module.helpers]] : []));
1732
+ await Promise.all([
1733
+ ...compiled.flatMap((module) => [
1734
+ Bun.write(this.#modulePath(module.id, ".js"), module.factory),
1735
+ ...module.sourceMap ? [Bun.write(this.#modulePath(module.id, ".js.map"), module.sourceMap)] : []
1736
+ ]),
1737
+ ...[...helpers.values()].map((shared) => Bun.write(this.#helpersPath(shared.hash), shared.definition))
1738
+ ]);
1381
1739
  }
1382
- async fingerprint(barrel, names) {
1383
- const packages = await this.#packagesOf([barrel]);
1384
- const aliased = names.map((name, index) => `${name} as _${index}`).join(", ");
1385
- const narrowed = await rewriteBarrelImports(`import { ${aliased} } from ${JSON.stringify(barrel)};`, [barrel], this.#analyzer, { specifierOf: (subpath) => DevBarrelImports.#fileOf(subpath, packages) ?? subpath });
1386
- return Bun.hash(narrowed ?? "").toString(36);
1740
+ async readCode(graph) {
1741
+ const ids = Object.keys(graph.modules).filter((id) => !graph.modules[id]?.vendor && this.hasModule(id));
1742
+ const hashes = [...new Set(ids.flatMap((id) => graph.modules[id]?.helpers ?? []))];
1743
+ const [modules, helpers] = await Promise.all([
1744
+ Promise.all(ids.map(async (id) => [id, await Bun.file(this.#modulePath(id, ".js")).text()])),
1745
+ Promise.all(hashes.map(async (hash) => [hash, await Bun.file(this.#helpersPath(hash)).text()]))
1746
+ ]);
1747
+ return { modules: new Map(modules), helpers: new Map(helpers) };
1387
1748
  }
1388
- async stamps(barrels, idOf) {
1389
- const stamped = await Promise.all([...barrels].map(async (barrel) => {
1390
- const files = await this.#analyzer.filesOf(barrel);
1391
- const read = [...new Set([...files, ...files.map((file) => path5.dirname(file))])];
1392
- const stamp = {
1393
- read: Object.fromEntries(read.map((file) => [idOf(file), CsrDevPaths.mtimeOf(file)])),
1394
- digest: await this.#digest(barrel)
1395
- };
1396
- return [barrel, stamp];
1397
- }));
1398
- return Object.fromEntries(stamped);
1749
+ hasModule(id) {
1750
+ return fs3.existsSync(this.#modulePath(id, ".js"));
1399
1751
  }
1400
- async#digest(barrel) {
1401
- const map = await this.#analyzer.analyze(barrel);
1402
- const packages = await this.#packagesOf([barrel]);
1403
- const files = new Map;
1404
- const fileOf = (subpath) => {
1405
- let file = files.get(subpath);
1406
- if (file === undefined) {
1407
- file = DevBarrelImports.#fileOf(subpath, packages) ?? subpath;
1408
- files.set(subpath, file);
1752
+ async forgetModules(ids) {
1753
+ await Promise.all(ids.flatMap((id) => [
1754
+ CsrDevArtifactWriter.#remove(this.#modulePath(id, ".js")),
1755
+ CsrDevArtifactWriter.#remove(this.#modulePath(id, ".js.map"))
1756
+ ]));
1757
+ }
1758
+ async writeVendor(graph) {
1759
+ const ids = Object.keys(graph.modules).filter((id) => graph.modules[id]?.vendor).sort();
1760
+ const stubs = new Set(Object.values(graph.modules).flatMap((module) => module.deps.filter(CsrDevPaths.isStub)));
1761
+ const lines = [await this.#helperDefinitions(graph, ids), ...await this.#defineLines(ids)];
1762
+ for (const stub of [...stubs].sort()) {
1763
+ if (stub.startsWith(CsrDevPaths.emptyStubPrefix)) {
1764
+ lines.push(`__akan.define(${JSON.stringify(stub)}, function () {});
1765
+ `);
1766
+ continue;
1409
1767
  }
1410
- return file;
1411
- };
1412
- const exports = [...map ?? []].map(([name, target]) => [name, target.originalName, !!target.namespace, fileOf(target.subpath)]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1413
- return Bun.hash(JSON.stringify([fileOf(barrel), map === null, exports])).toString(36);
1768
+ const message = `[akan-csr] ${stub.slice(CsrDevPaths.stubPrefix.length)} is a Node built-in the browser does not have`;
1769
+ lines.push(`__akan.define(${JSON.stringify(stub)}, function () {
1770
+ throw new Error(${JSON.stringify(message)});
1771
+ });
1772
+ `);
1773
+ }
1774
+ const code = lines.join("");
1775
+ const vendorFile = `vendor-${Bun.hash(code).toString(36)}.js`;
1776
+ await this.#writeAtomic(vendorFile, code);
1777
+ return vendorFile;
1414
1778
  }
1415
- async#packagesOf(barrels) {
1416
- return (await Promise.all(barrels.map((barrel) => this.#packageOf(barrel)))).filter((pkg) => pkg !== null).sort((a, b) => b.pkgName.length - a.pkgName.length);
1779
+ async writeApp(graph, { generation, vendorFile, epoch }, code) {
1780
+ const ids = Object.keys(graph.modules).filter((id) => !graph.modules[id]?.vendor).sort();
1781
+ const lines = await this.#defineLines(ids, code);
1782
+ const blocks = ids.map((id, index) => [id, lines[index] ?? ""]);
1783
+ const start = this.#library ? `__akan.startLibrary(${JSON.stringify({ generation, refresh: graph.refresh, bootstrap: graph.entries[""], vendorFile, epoch })});
1784
+ ` : `__akan.start(${JSON.stringify({ generation, refresh: graph.refresh })});
1785
+ `;
1786
+ await this.#writeWithSourceMap(CSR_DEV_APP_FILE, await this.#helperDefinitions(graph, ids, code), blocks, start);
1417
1787
  }
1418
- #packageOf(barrel) {
1419
- let pkg = this.#packages.get(barrel);
1420
- if (!pkg) {
1421
- pkg = this.#resolvePackage(barrel);
1422
- this.#packages.set(barrel, pkg);
1423
- }
1424
- return pkg;
1788
+ async writePatch(generation, modules) {
1789
+ const patchFile = `patch-${generation}.js`;
1790
+ const blocks = modules.map((module, index) => [module.id, `${JSON.stringify(module.id)}: ${module.factory}${index < modules.length - 1 ? `,
1791
+ ` : `
1792
+ `}`]);
1793
+ const helpers = new Map(modules.flatMap((module) => module.helpers ? [[module.helpers.hash, module.helpers]] : []));
1794
+ const header = `${[...helpers.values()].map((shared) => shared.definition).join("")}__akan.update(${generation}, {
1795
+ `;
1796
+ await this.#writeWithSourceMap(patchFile, header, blocks, `});
1797
+ `);
1798
+ return `${this.#routePrefix}${patchFile}`;
1425
1799
  }
1426
- static #fileOf(subpath, packages) {
1427
- const pkg = packages.find(({ pkgName }) => subpath === pkgName || subpath.startsWith(`${pkgName}/`));
1428
- if (!pkg)
1429
- return null;
1430
- const file = CsrDevPaths.resolveOnDisk(path5.join(pkg.pkgDir, subpath.slice(pkg.pkgName.length)));
1431
- return file ? CsrDevPaths.realpath(file) : null;
1800
+ async writeState(graph, manifest) {
1801
+ await this.writeJson("graph.json", graph);
1802
+ await this.writeJson(CSR_DEV_MANIFEST_FILE, manifest);
1432
1803
  }
1433
- static #relative(subpath, from, packages) {
1434
- const file = DevBarrelImports.#fileOf(subpath, packages);
1435
- if (!file)
1436
- return subpath;
1437
- const relative = path5.relative(from, file);
1438
- if (path5.isAbsolute(relative))
1439
- return file.split(path5.sep).join("/");
1440
- const posix = relative.split(path5.sep).join("/");
1441
- return posix.startsWith("../") ? posix : `./${posix}`;
1804
+ async commitPatch(graph, manifest, announce, { modules, code }) {
1805
+ await this.writeJson(CSR_DEV_MANIFEST_FILE, manifest);
1806
+ announce();
1807
+ await CsrDevArtifactWriter.#appWriteDelay();
1808
+ await this.writeModules(modules);
1809
+ await this.writeJson("graph.json", graph);
1810
+ await this.writeApp(graph, manifest, code);
1811
+ await this.writeJson(CSR_DEV_MANIFEST_FILE, { ...manifest, appGeneration: manifest.generation });
1442
1812
  }
1443
- }
1444
-
1445
- // pkgs/@akanjs/devkit/frontendBuild/routeClientBuilder.ts
1446
- import { mkdir as mkdir2 } from "fs/promises";
1447
- import path7 from "path";
1448
- import { SSR_DEV_CHUNK, SSR_DEV_ID_PREFIX } from "akanjs/server/hmr/csrDevManifest";
1449
-
1450
- // pkgs/@akanjs/devkit/frontendBuild/clientEntriesBundler.ts
1451
- import fs4 from "fs";
1452
- import path6 from "path";
1453
-
1454
- // pkgs/@akanjs/devkit/frontendBuild/clientBuildTypes.ts
1455
- var CLIENT_BUNDLE_NAMING = {
1456
- entry: "[name]-[hash].[ext]",
1457
- chunk: "chunks/[hash].[ext]",
1458
- asset: "assets/[hash].[ext]"
1459
- };
1460
-
1461
- // pkgs/@akanjs/devkit/frontendBuild/clientEntriesBundler.ts
1462
- class ClientEntriesBundler {
1463
- #app;
1464
- #entries;
1465
- #plugins;
1466
- #external;
1467
- #externalSubpaths;
1468
- #externalAliases;
1469
- #entryExports;
1470
- #command;
1471
- #target;
1472
- #outputSubdir;
1473
- #reactFastRefresh;
1474
- #outdir;
1475
- #servePrefix;
1476
- #manifest = {};
1477
- #ssrManifest = { moduleLoading: null, moduleMap: {} };
1478
- #entryUrlsByAbsPath = new Map;
1479
- #entryOutputAbsByAbsPath = new Map;
1480
- #entryDepsByAbsPath = new Map;
1481
- #entryChunkUrlsByAbsPath = new Map;
1482
- #clientReferenceIdByAbsPath = new Map;
1483
- #opaqueEntries = null;
1484
- #metafileOutputsByAbs = new Map;
1485
- #metafileInputs = {};
1486
- constructor(options) {
1487
- this.#app = options.app;
1488
- this.#entries = options.entries;
1489
- this.#plugins = options.plugins ?? [];
1490
- this.#external = options.external ?? [];
1491
- this.#externalSubpaths = options.externalSubpaths ?? [];
1492
- this.#externalAliases = options.externalAliases ?? {};
1493
- this.#entryExports = options.entryExports ?? {};
1494
- this.#command = options.command ?? "start";
1495
- this.#target = options.target ?? "browser";
1496
- this.#outputSubdir = options.outputSubdir ?? "client";
1497
- this.#reactFastRefresh = options.reactFastRefresh ?? false;
1498
- const artifactDir = `${this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath}/.akan/artifact`;
1499
- this.#outdir = `${artifactDir}/${this.#outputSubdir}`;
1500
- this.#servePrefix = `/_akan/${this.#outputSubdir}`;
1813
+ async healApp(graph, manifest, code) {
1814
+ if (appGenerationOf(manifest) >= manifest.generation)
1815
+ return manifest;
1816
+ await this.writeApp(graph, manifest, code);
1817
+ const healed = { ...manifest, appGeneration: manifest.generation };
1818
+ await this.writeJson(CSR_DEV_MANIFEST_FILE, healed);
1819
+ return healed;
1501
1820
  }
1502
- async bundle() {
1503
- const akanConfig = await this.#app.getConfig();
1504
- this.#opaqueEntries = await this.#createOpaqueEntryAliases();
1505
- const result = await Bun.build({
1506
- entrypoints: this.#opaqueEntries.entries,
1507
- outdir: this.#outdir,
1508
- splitting: true,
1509
- target: this.#target,
1510
- format: "esm",
1511
- naming: CLIENT_BUNDLE_NAMING,
1512
- metafile: true,
1513
- define: bundleDefine(this.#app, this.#command, "ssr"),
1514
- conditions: bundleConditions(this.#command),
1515
- minify: this.#command === "build",
1516
- optimizeImports: akanConfig.optimizeImports,
1517
- reactFastRefresh: this.#command === "start" && this.#outputSubdir === "client" && this.#reactFastRefresh,
1518
- plugins: this.#external.length > 0 || this.#externalSubpaths.length > 0 || Object.keys(this.#externalAliases).length > 0 ? [...this.#plugins, this.#createExternalSpecifiersPlugin()] : this.#plugins
1821
+ async prune(vendorFile, generation) {
1822
+ const names = await readdir3(this.#outDir);
1823
+ const stale = names.filter((name) => {
1824
+ const patch = /^patch-(\d+)\.js(?:\.layout\.json)?$/.exec(name);
1825
+ return patch ? Number(patch[1]) <= generation - CSR_DEV_KEPT_PATCHES : false;
1519
1826
  });
1520
- if (!result.success)
1521
- throw new AggregateError(result.logs, "[ClientEntriesBundler] Bun.build failed");
1522
- await this.#rewriteExternalImportSpecifiers(result.outputs);
1523
- const metafile = result.metafile;
1524
- if (!metafile)
1525
- throw new Error("[ClientEntriesBundler] metafile is missing");
1526
- this.#metafileOutputsByAbs = new Map(Object.entries(metafile.outputs).map(([k, v]) => [this.#absFromOutdir(k), v]));
1527
- this.#metafileInputs = metafile.inputs;
1528
- for (const artifact of result.outputs.filter((a) => a.kind === "entry-point"))
1529
- this.#addEntryArtifact(artifact.path);
1530
- this.#assertNarrowedExports();
1531
- return {
1532
- manifest: this.#manifest,
1533
- ssrManifest: this.#ssrManifest,
1534
- entryUrlsByAbsPath: this.#entryUrlsByAbsPath,
1535
- entryOutputAbsByAbsPath: this.#entryOutputAbsByAbsPath,
1536
- entryDepsByAbsPath: this.#entryDepsByAbsPath,
1537
- entryChunkUrlsByAbsPath: this.#entryChunkUrlsByAbsPath,
1538
- externalsByChunkUrl: this.#collectExternalsByChunkUrl(),
1539
- clientReferenceIdByAbsPath: this.#clientReferenceIdByAbsPath
1540
- };
1827
+ const vendors = names.filter((name) => /^vendor-[\w-]+\.js$/.test(name) && name !== vendorFile).map((name) => ({ name, mtimeMs: CsrDevPaths.mtimeOf(path7.join(this.#outDir, name)) })).sort((a, b) => b.mtimeMs - a.mtimeMs).slice(CsrDevArtifactWriter.#keptVendors - 1).map(({ name }) => name);
1828
+ await Promise.all([...stale, ...vendors].map((name) => CsrDevArtifactWriter.#remove(path7.join(this.#outDir, name))));
1541
1829
  }
1542
- async#createOpaqueEntryAliases() {
1543
- const aliasDir = path6.join(this.#app.cwdPath, ".akan", "generated", "client-entry-alias", this.#outputSubdir);
1544
- fs4.mkdirSync(aliasDir, { recursive: true });
1545
- const originalByAlias = new Map;
1546
- const aliasedEntries = await Promise.all(this.#entries.map(async (entry) => {
1547
- const absEntry = path6.resolve(entry);
1548
- const narrowed = this.#entryExports[absEntry];
1549
- const key = `${this.#app.name}
1550
- ${this.#outputSubdir}
1551
- ${absEntry}${narrowed ? `
1552
- narrowed` : ""}`;
1553
- const aliasPath = path6.join(aliasDir, `${Bun.hash(key).toString(36)}.tsx`);
1554
- await Bun.write(aliasPath, narrowed ? ClientEntriesBundler.narrowedAliasSource(absEntry, narrowed) : this.#createOpaqueEntryAliasSource(absEntry, await this.#scanEntryExportNames(absEntry)));
1555
- originalByAlias.set(path6.resolve(aliasPath), absEntry);
1556
- return aliasPath;
1830
+ async pruneAfterFullBuild(graph, vendorFile, { generation, assets }) {
1831
+ const kept = new Set(Object.keys(graph.modules).flatMap((id) => [this.#modulePath(id, ".js"), this.#modulePath(id, ".js.map")]));
1832
+ for (const module of Object.values(graph.modules))
1833
+ if (module.helpers)
1834
+ kept.add(this.#helpersPath(module.helpers));
1835
+ for (const asset of assets)
1836
+ kept.add(path7.resolve(asset));
1837
+ const listed = async (dir) => (await readdir3(path7.join(this.#outDir, dir)).catch(() => [])).map((name) => path7.join(this.#outDir, dir, name));
1838
+ const stale = [
1839
+ ...(await listed("modules")).filter((file) => !kept.has(file)),
1840
+ ...(await listed("assets")).filter((file) => !kept.has(file)),
1841
+ ...(await listed(".")).filter((file) => {
1842
+ const name = path7.basename(file);
1843
+ return /^patch-\d+\.js(?:\.layout\.json)?$/.test(name) || name.endsWith(".tmp");
1844
+ }),
1845
+ path7.join(this.#outDir, CSR_DEV_PATCHING_MARKER)
1846
+ ];
1847
+ await Promise.all(stale.map((file) => CsrDevArtifactWriter.#remove(file)));
1848
+ await this.prune(vendorFile, generation);
1849
+ }
1850
+ async#helperDefinitions(graph, ids, code) {
1851
+ const hashes = [...new Set(ids.flatMap((id) => graph.modules[id]?.helpers ?? []))].sort();
1852
+ return (await Promise.all(hashes.map(async (hash) => code?.helpers.get(hash) ?? Bun.file(this.#helpersPath(hash)).text()))).join("");
1853
+ }
1854
+ async#defineLines(ids, code) {
1855
+ return await Promise.all(ids.map(async (id) => {
1856
+ const factory = code?.modules.get(id) ?? await Bun.file(this.#modulePath(id, ".js")).text();
1857
+ return `__akan.define(${JSON.stringify(id)}, ${factory});
1858
+ `;
1557
1859
  }));
1558
- return { entries: aliasedEntries, originalByAlias, aliasDir };
1559
1860
  }
1560
- #createOpaqueEntryAliasSource(absEntry, exportNames) {
1561
- const entryLit = JSON.stringify(path6.resolve(absEntry));
1562
- if (exportNames.length === 0)
1563
- return `export * from ${entryLit};
1564
- `;
1565
- const namedExports = exportNames.filter((name) => name !== "default");
1566
- const lines = namedExports.length > 0 ? [`export { ${namedExports.join(", ")} } from ${entryLit};`] : [];
1567
- if (exportNames.includes("default"))
1568
- lines.push(`export { default } from ${entryLit};`);
1569
- return `${lines.join(`
1570
- `)}
1861
+ async#writeWithSourceMap(name, header, blocks, footer) {
1862
+ const layout = { lineCount: 0, modules: [] };
1863
+ let line = CsrDevPaths.lineCount(header);
1864
+ for (const [id, text] of blocks) {
1865
+ layout.modules.push([id, line + 1]);
1866
+ line += CsrDevPaths.lineCount(text);
1867
+ }
1868
+ const code = `${header}${blocks.map(([, text]) => text).join("")}${footer}//# sourceMappingURL=${name}.map
1571
1869
  `;
1870
+ layout.lineCount = CsrDevPaths.lineCount(code);
1871
+ await this.writeJson(`${name}.layout.json`, layout);
1872
+ await this.#writeAtomic(name, code);
1572
1873
  }
1573
- static narrowedAliasSource(absEntry, names) {
1574
- const list = names.length > 0 ? `{ ${names.join(", ")} }` : "{}";
1575
- return `export ${list} from ${JSON.stringify(path6.resolve(absEntry))};
1576
- `;
1874
+ async#writeAtomic(name, content) {
1875
+ const target = path7.join(this.#outDir, name);
1876
+ const temp = `${target}.${process.pid}.tmp`;
1877
+ await Bun.write(temp, content);
1878
+ await FileSys2.replace(temp, target);
1577
1879
  }
1578
- #assertNarrowedExports() {
1579
- const missing = Object.entries(this.#entryExports).flatMap(([absEntry, names = []]) => {
1580
- const absOut = this.#entryOutputAbsByAbsPath.get(absEntry);
1581
- if (!absOut)
1582
- return [`${path6.basename(absEntry)}: no output`];
1583
- const exported = new Set(this.#metafileOutputsByAbs.get(absOut)?.exports);
1584
- const absent = names.filter((name) => !exported.has(name));
1585
- return absent.length > 0 ? [`${path6.basename(absEntry)}: ${absent.join(", ")}`] : [];
1880
+ static async#remove(file) {
1881
+ await rm2(file, { force: true }).catch(() => {
1882
+ return;
1586
1883
  });
1587
- if (missing.length > 0)
1588
- throw new Error(`[ClientEntriesBundler] client code imports names its vendor does not export (${missing.join("; ")})`);
1589
1884
  }
1590
- async#scanEntryExportNames(absEntry) {
1591
- return scanUseClientExports(await Bun.file(absEntry).text(), absEntry, this.#app.workspace.workspaceRoot);
1885
+ static async#appWriteDelay() {
1886
+ const ms = Number(process.env.AKAN_CSR_DEV_APP_WRITE_DELAY_MS);
1887
+ if (Number.isInteger(ms) && ms > 0)
1888
+ await Bun.sleep(ms);
1592
1889
  }
1593
- #createExternalSpecifiersPlugin() {
1594
- const set = new Set(this.#external);
1595
- const subpathSet = new Set(this.#externalSubpaths);
1596
- const aliases = this.#externalAliases;
1597
- const specifiers = [...new Set([...this.#external, ...this.#externalSubpaths, ...Object.keys(aliases)])];
1598
- const escaped = specifiers.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
1599
- const filter = new RegExp(`^(${escaped.join("|")})(?:/.*)?$`);
1600
- return {
1601
- name: "akan-externalize-specifiers",
1602
- setup(build) {
1603
- build.onResolve({ filter }, (args) => {
1604
- const alias = aliases[args.path];
1605
- if (alias)
1606
- return { path: alias, external: true };
1607
- if (!ClientEntriesBundler.#matchesExternalSpecifier(args.path, set, subpathSet))
1608
- return;
1609
- return { path: args.path, external: true };
1610
- });
1890
+ #modulePath(id, extension) {
1891
+ return path7.join(this.#outDir, csrDevModuleFile(id, extension));
1892
+ }
1893
+ #helpersPath(hash) {
1894
+ return path7.join(this.#outDir, "modules", `helpers-${hash}.js`);
1895
+ }
1896
+ }
1897
+
1898
+ // pkgs/@akanjs/devkit/frontendBuild/csrDevModuleCompiler.ts
1899
+ import path10 from "path";
1900
+
1901
+ // pkgs/@akanjs/devkit/frontendBuild/csrDevFactoryCheck.ts
1902
+ class CsrDevFactoryCheck {
1903
+ static #parsed = new Set;
1904
+ static problemOf(factory, helperDefinition = "") {
1905
+ const key = Bun.hash(`${helperDefinition}\x00${factory}`);
1906
+ if (CsrDevFactoryCheck.#parsed.has(key))
1907
+ return null;
1908
+ const problem = CsrDevFactoryCheck.#syntaxError(`${helperDefinition}return (${factory});`);
1909
+ if (problem === null) {
1910
+ CsrDevFactoryCheck.#parsed.add(key);
1911
+ return null;
1912
+ }
1913
+ if (problem.includes("import.meta")) {
1914
+ const line = factory.split(`
1915
+ `).findIndex((text) => /(?<![\w$.])import\.meta\b/.test(text));
1916
+ return `import.meta is left in it${line > 0 ? ` (compiled line ${line})` : ""}, which a classic script cannot hold: ${problem}`;
1917
+ }
1918
+ if (CsrDevFactoryCheck.#syntaxError(`${helperDefinition}return (async ${factory});`) === null)
1919
+ return `a top-level await is left in it, which a CommonJS factory cannot wait on: ${problem}`;
1920
+ return problem;
1921
+ }
1922
+ static thrower(id, problem) {
1923
+ const message = `[akan-csr] ${id} was left out of the dev registry: ${problem}`;
1924
+ return `function () {
1925
+ throw new Error(${JSON.stringify(message)});
1926
+ }`;
1927
+ }
1928
+ static #syntaxError(source) {
1929
+ try {
1930
+ new Function(source);
1931
+ return null;
1932
+ } catch (error) {
1933
+ return error instanceof Error ? error.message : String(error);
1934
+ }
1935
+ }
1936
+ }
1937
+
1938
+ // pkgs/@akanjs/devkit/frontendBuild/csrDevResolver.ts
1939
+ import fs4 from "fs";
1940
+ import path8 from "path";
1941
+ class CsrDevResolver {
1942
+ static inline = "inline";
1943
+ #paths;
1944
+ #context;
1945
+ #entryFiles;
1946
+ #resolution = new Map;
1947
+ #fallbacks = new Set;
1948
+ #runtimeResolved = new Map;
1949
+ #browserMaps = new Map;
1950
+ #loaded = new Set;
1951
+ #startedAt;
1952
+ #prepassDone = false;
1953
+ constructor({
1954
+ paths,
1955
+ context,
1956
+ entryFiles,
1957
+ resolution = {},
1958
+ runtimeResolved = {},
1959
+ startedAt = Date.now() - process.uptime() * 1000
1960
+ }) {
1961
+ this.#paths = paths;
1962
+ this.#startedAt = startedAt;
1963
+ this.#context = context;
1964
+ this.#entryFiles = entryFiles;
1965
+ for (const [importer, specifiers] of Object.entries(runtimeResolved))
1966
+ this.#runtimeResolved.set(paths.fileOf(importer), new Set(specifiers));
1967
+ for (const [importer, bySpecifier] of Object.entries(resolution))
1968
+ this.#resolution.set(paths.fileOf(importer), new Map(Object.entries(bySpecifier).map(([specifier, target]) => [
1969
+ specifier,
1970
+ CsrDevPaths.isStub(target) ? target : paths.fileOf(target)
1971
+ ])));
1972
+ }
1973
+ get prepassDone() {
1974
+ return this.#prepassDone;
1975
+ }
1976
+ get fallbacks() {
1977
+ return this.#fallbacks;
1978
+ }
1979
+ async prepass() {
1980
+ const result = await Bun.build({
1981
+ entrypoints: [...this.#entryFiles, ...this.#context.refreshFile ? [this.#context.refreshFile] : []],
1982
+ target: "browser",
1983
+ metafile: true,
1984
+ external: [...this.#context.externals ?? []],
1985
+ define: this.#context.define,
1986
+ optimizeImports: this.#context.optimizeImports,
1987
+ plugins: [PagesBundleBuilder.createCssStubPlugin()]
1988
+ });
1989
+ this.#record(result.metafile.inputs);
1990
+ this.#prepassDone = true;
1991
+ }
1992
+ async cover(files) {
1993
+ if (!this.#prepassDone)
1994
+ return;
1995
+ const pending = files.filter((file) => CsrDevPaths.isScript(file) && !this.#loaded.has(file));
1996
+ if (pending.length === 0)
1997
+ return;
1998
+ for (const file of pending)
1999
+ this.#loaded.add(file);
2000
+ const entries = new Set(pending);
2001
+ const result = await Bun.build({
2002
+ entrypoints: pending,
2003
+ target: "browser",
2004
+ metafile: true,
2005
+ throw: false,
2006
+ external: [...this.#context.externals ?? []],
2007
+ define: this.#context.define,
2008
+ plugins: [
2009
+ {
2010
+ name: "akan-csr-cover",
2011
+ setup: (build) => {
2012
+ build.onLoad({ filter: /.*/ }, (args) => entries.has(CsrDevPaths.realpath(args.path)) ? undefined : { contents: "module.exports = {};", loader: "js" });
2013
+ }
2014
+ }
2015
+ ]
2016
+ });
2017
+ if (result.metafile)
2018
+ this.#record(result.metafile.inputs, entries);
2019
+ }
2020
+ #record(inputs, only) {
2021
+ for (const [input, { imports }] of Object.entries(inputs)) {
2022
+ const importer = CsrDevPaths.realpath(path8.resolve(input));
2023
+ if (only && !only.has(importer))
2024
+ continue;
2025
+ if (imports.every((record) => record.original))
2026
+ this.#loaded.add(importer);
2027
+ for (const record of imports) {
2028
+ if (!record.original)
2029
+ continue;
2030
+ if (record.external) {
2031
+ if (record.original.startsWith("node:"))
2032
+ this.#remember(importer, record.original, `${CsrDevPaths.stubPrefix}${record.original}`);
2033
+ continue;
2034
+ }
2035
+ const target = path8.resolve(record.path);
2036
+ if (!fs4.existsSync(target))
2037
+ continue;
2038
+ this.#remember(importer, record.original, CsrDevPaths.realpath(target));
2039
+ this.#runtimeResolved.get(importer)?.delete(record.original);
1611
2040
  }
1612
- };
2041
+ }
1613
2042
  }
1614
- static #matchesExternalSpecifier(specifier, exactExternals, subpathExternals) {
1615
- if (exactExternals.has(specifier) || subpathExternals.has(specifier))
2043
+ resolve(importer, specifier, kind = "import") {
2044
+ if (this.#isInlineSpecifier(specifier))
2045
+ return CsrDevResolver.inline;
2046
+ const disabled = this.#disabledInBrowser(importer, specifier, kind);
2047
+ if (disabled)
2048
+ return disabled;
2049
+ const known = this.#resolution.get(importer)?.get(specifier);
2050
+ const usable = known && this.#stillAnswers(importer, specifier, known, kind) ? known : null;
2051
+ const target = usable ?? this.#resolveUnknown(importer, specifier, kind);
2052
+ if (target === null || CsrDevPaths.isStub(target))
2053
+ return target;
2054
+ if (!CsrDevPaths.isScript(target))
2055
+ return CsrDevResolver.inline;
2056
+ if (!usable)
2057
+ this.#remember(importer, specifier, target);
2058
+ return target;
2059
+ }
2060
+ #stillAnswers(importer, specifier, known, kind) {
2061
+ if (CsrDevPaths.isStub(known))
1616
2062
  return true;
1617
- for (const external of subpathExternals)
1618
- if (specifier.startsWith(`${external}/`))
1619
- return true;
1620
- return false;
2063
+ if (!fs4.existsSync(known))
2064
+ return false;
2065
+ if (!specifier.startsWith(".") || CsrDevPaths.isVendorFile(importer))
2066
+ return true;
2067
+ if (this.#hasBrowserMap(path8.dirname(importer)))
2068
+ return true;
2069
+ const onDisk = CsrDevPaths.resolveRelative(path8.dirname(importer), specifier, kind);
2070
+ return onDisk !== null && CsrDevPaths.realpath(onDisk) === known;
1621
2071
  }
1622
- async#rewriteExternalImportSpecifiers(outputs) {
1623
- if (Object.keys(this.#externalAliases).length === 0)
1624
- return;
1625
- await Promise.all(outputs.filter((output) => output.path.endsWith(".js")).map(async (output) => {
1626
- const source = await Bun.file(output.path).text();
1627
- const rewritten = ClientEntriesBundler.rewriteExternalImportSpecifiers(source, this.#externalAliases);
1628
- if (rewritten !== source)
1629
- await Bun.write(output.path, rewritten);
1630
- }));
2072
+ isRegistryModule(file) {
2073
+ if (!CsrDevPaths.isScript(file))
2074
+ return false;
2075
+ const packageName = CsrDevResolver.#packageNameOf(file);
2076
+ if (packageName === null)
2077
+ return true;
2078
+ return !this.#context.optimizeImports.some((pattern) => {
2079
+ const base = CsrDevResolver.#patternBase(pattern);
2080
+ return base === packageName || base.startsWith(`${packageName}/`);
2081
+ });
1631
2082
  }
1632
- static rewriteExternalImportSpecifiers(source, aliases) {
1633
- let rewritten = source;
1634
- for (const [specifier, alias] of Object.entries(aliases)) {
1635
- if (!alias)
1636
- continue;
1637
- const escaped = specifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1638
- rewritten = rewritten.replace(new RegExp(`(\\bfrom\\s*["'])${escaped}(["'])`, "g"), (_match, prefix, suffix) => {
1639
- return `${prefix}${alias}${suffix}`;
1640
- }).replace(new RegExp(`(\\bimport\\s*["'])${escaped}(["'])`, "g"), (_match, prefix, suffix) => {
1641
- return `${prefix}${alias}${suffix}`;
1642
- });
1643
- }
1644
- return rewritten;
2083
+ #disabledInBrowser(importer, specifier, kind) {
2084
+ const map = this.#browserMapOf(path8.dirname(importer));
2085
+ if (!map || map.offFiles.size === 0 && map.offNames.size === 0)
2086
+ return null;
2087
+ if (!specifier.startsWith(".") && !path8.isAbsolute(specifier))
2088
+ return map.offNames.has(specifier) ? `${CsrDevPaths.emptyStubPrefix}${specifier}` : null;
2089
+ const target = CsrDevPaths.resolveRelative(path8.dirname(importer), specifier, kind);
2090
+ return target && map.offFiles.has(CsrDevPaths.realpath(target)) ? `${CsrDevPaths.emptyStubPrefix}${this.#paths.idOf(target)}` : null;
1645
2091
  }
1646
- #toServeUrl(absOutPath) {
1647
- const rel = path6.relative(this.#outdir, absOutPath).split(path6.sep).join("/");
1648
- return `${this.#servePrefix}/${rel}`;
2092
+ #hasBrowserMap(dir) {
2093
+ return this.#browserMapOf(dir) !== null;
1649
2094
  }
1650
- #absFromOutdir(p) {
1651
- return path6.isAbsolute(p) ? p : path6.resolve(this.#outdir, p);
2095
+ #browserMapOf(dir) {
2096
+ const cached = this.#browserMaps.get(dir);
2097
+ if (cached !== undefined)
2098
+ return cached;
2099
+ const pkgFile = path8.join(dir, "package.json");
2100
+ const parent = path8.dirname(dir);
2101
+ let map = null;
2102
+ if (fs4.existsSync(pkgFile)) {
2103
+ try {
2104
+ const browser = JSON.parse(fs4.readFileSync(pkgFile, "utf8")).browser;
2105
+ if (typeof browser === "object" && browser !== null) {
2106
+ const off = Object.entries(browser).filter(([, target]) => target === false).map(([key]) => key);
2107
+ const files = off.filter((key) => key.startsWith(".")).map((key) => CsrDevPaths.resolveRelative(dir, key)).filter((file) => !!file);
2108
+ map = {
2109
+ offFiles: new Set(files.map((file) => CsrDevPaths.realpath(file))),
2110
+ offNames: new Set(off.filter((key) => !key.startsWith(".")))
2111
+ };
2112
+ }
2113
+ } catch {}
2114
+ } else if (parent !== dir)
2115
+ map = this.#browserMapOf(parent);
2116
+ this.#browserMaps.set(dir, map);
2117
+ return map;
1652
2118
  }
1653
- #absFromEntryPoint(p) {
1654
- if (path6.isAbsolute(p))
1655
- return path6.resolve(p);
1656
- const candidates = [path6.resolve(process.cwd(), p), path6.resolve(this.#app.cwdPath, p)];
1657
- return candidates.find((candidate) => fs4.existsSync(candidate)) ?? candidates[0];
2119
+ forget(importer) {
2120
+ this.#resolution.delete(importer);
2121
+ this.#runtimeResolved.delete(importer);
1658
2122
  }
1659
- #collectChunkUrls(absOutPath, visited = new Set) {
1660
- if (visited.has(absOutPath))
1661
- return [];
1662
- visited.add(absOutPath);
1663
- const info = this.#metafileOutputsByAbs.get(absOutPath);
1664
- if (!info)
1665
- return [this.#toServeUrl(absOutPath)];
1666
- const urls = [this.#toServeUrl(absOutPath)];
1667
- for (const imp of info.imports) {
1668
- if (imp.kind === "dynamic-import")
1669
- continue;
1670
- const absImp = this.#absFromOutdir(imp.path);
1671
- if (!absImp.endsWith(".js"))
1672
- continue;
1673
- urls.push(...this.#collectChunkUrls(absImp, visited));
1674
- }
1675
- return urls;
2123
+ serializeRuntimeResolved() {
2124
+ return Object.fromEntries([...this.#runtimeResolved].filter(([, specifiers]) => specifiers.size > 0).map(([importer, specifiers]) => [this.#paths.idOf(importer), [...specifiers].sort()]));
1676
2125
  }
1677
- #collectExternalsByChunkUrl() {
1678
- const externalsByChunkUrl = new Map;
1679
- if (this.#command !== "build" || this.#target !== "browser")
1680
- return externalsByChunkUrl;
1681
- for (const [absOut, info] of this.#metafileOutputsByAbs) {
1682
- if (!absOut.endsWith(".js"))
1683
- continue;
1684
- const externals = new Set;
1685
- for (const input of Object.keys(info.inputs ?? {}))
1686
- for (const imp of this.#metafileInputs[input]?.imports ?? [])
1687
- if (imp.external && imp.kind !== "dynamic-import" && !/^[./]/.test(imp.path))
1688
- externals.add(imp.path);
1689
- externalsByChunkUrl.set(this.#toServeUrl(absOut), [...externals].sort());
1690
- }
1691
- return externalsByChunkUrl;
2126
+ serialize() {
2127
+ return Object.fromEntries([...this.#resolution].map(([importer, bySpecifier]) => [
2128
+ this.#paths.idOf(importer),
2129
+ Object.fromEntries([...bySpecifier].filter(([, target]) => CsrDevPaths.isStub(target) || fs4.existsSync(target)).map(([specifier, target]) => [specifier, CsrDevPaths.isStub(target) ? target : this.#paths.idOf(target)]))
2130
+ ]));
1692
2131
  }
1693
- #collectClientDeps(absOutPath, visited = new Set) {
1694
- if (visited.has(absOutPath))
1695
- return new Set;
1696
- visited.add(absOutPath);
1697
- const deps = new Set;
1698
- const info = this.#metafileOutputsByAbs.get(absOutPath);
1699
- if (!info)
1700
- return deps;
1701
- if (!this.#opaqueEntries)
1702
- throw new Error("[ClientEntriesBundler] opaque entries are missing");
1703
- for (const input of Object.keys(info.inputs ?? {})) {
1704
- const absInput = this.#absFromEntryPoint(input);
1705
- if (!absInput.includes("node_modules") && !absInput.startsWith(this.#opaqueEntries.aliasDir))
1706
- deps.add(absInput);
2132
+ #resolveUnknown(importer, specifier, kind) {
2133
+ if (specifier.startsWith("node:"))
2134
+ return `${CsrDevPaths.stubPrefix}${specifier}`;
2135
+ const relative = specifier.startsWith(".") || path8.isAbsolute(specifier);
2136
+ const cannotResolve = () => new Error(`[csr-dev] cannot resolve "${specifier}" from ${this.#paths.idOf(importer)}`);
2137
+ if (relative) {
2138
+ const onDisk = CsrDevPaths.resolveRelative(path8.dirname(importer), specifier, kind) ?? CsrDevResolver.#onDisk(CsrDevPaths.tryResolve(specifier, path8.dirname(importer)));
2139
+ if (!onDisk)
2140
+ throw cannotResolve();
2141
+ return CsrDevPaths.realpath(onDisk);
1707
2142
  }
1708
- for (const imp of info.imports) {
1709
- if (imp.kind === "dynamic-import")
1710
- continue;
1711
- const absImp = this.#absFromOutdir(imp.path);
1712
- if (!absImp.endsWith(".js"))
1713
- continue;
1714
- for (const dep of this.#collectClientDeps(absImp, visited))
1715
- deps.add(dep);
2143
+ const sibling = this.#resolvedBySibling(importer, specifier);
2144
+ if (sibling)
2145
+ return sibling;
2146
+ const resolved = CsrDevPaths.tryResolve(specifier, path8.dirname(importer));
2147
+ const moved = resolved !== null && path8.isAbsolute(resolved) && !fs4.existsSync(resolved);
2148
+ const installed = resolved === null && CsrDevPaths.installedSince(specifier, path8.dirname(importer), this.#startedAt);
2149
+ if (!this.#prepassDone || moved) {
2150
+ if (resolved === null && !installed && !CsrDevPaths.isVendorFile(importer))
2151
+ throw cannotResolve();
2152
+ return null;
1716
2153
  }
1717
- return deps;
1718
- }
1719
- #addEntryArtifact(absOut) {
1720
- if (!this.#opaqueEntries)
1721
- throw new Error("[ClientEntriesBundler] opaque entries are missing");
1722
- const info = this.#metafileOutputsByAbs.get(absOut);
1723
- const buildEntryPointAbs = info?.entryPoint ? this.#absFromEntryPoint(info.entryPoint) : null;
1724
- const entryPointAbs = buildEntryPointAbs ? this.#opaqueEntries.originalByAlias.get(buildEntryPointAbs) ?? buildEntryPointAbs : null;
1725
- if (!entryPointAbs)
1726
- return;
1727
- const chunkUrls = this.#collectChunkUrls(absOut);
1728
- const entryUrl = chunkUrls[0] ?? this.#toServeUrl(absOut);
1729
- this.#entryUrlsByAbsPath.set(entryPointAbs, entryUrl);
1730
- this.#entryOutputAbsByAbsPath.set(entryPointAbs, absOut);
1731
- this.#entryDepsByAbsPath.set(entryPointAbs, [...this.#collectClientDeps(absOut)].sort());
1732
- this.#entryChunkUrlsByAbsPath.set(entryPointAbs, chunkUrls);
1733
- const clientReferenceId = toClientReferencePath(entryPointAbs, this.#app.workspace.workspaceRoot);
1734
- this.#clientReferenceIdByAbsPath.set(entryPointAbs, clientReferenceId);
1735
- const flatChunks = [];
1736
- for (const url of chunkUrls)
1737
- flatChunks.push(url, url);
1738
- const exportNames = info?.exports && info.exports.length > 0 ? info.exports : ["default"];
1739
- const ssrEntriesByName = {};
1740
- for (const name of exportNames) {
1741
- const key = `${clientReferenceId}#${name}`;
1742
- this.#manifest[key] = { id: entryUrl, chunks: flatChunks, name, async: true };
1743
- ssrEntriesByName[name] = { id: absOut, chunks: [absOut, absOut], name, async: true };
2154
+ if (!resolved) {
2155
+ if (installed)
2156
+ return null;
2157
+ throw cannotResolve();
1744
2158
  }
1745
- this.#ssrManifest.moduleMap[entryUrl] = ssrEntriesByName;
2159
+ if (!path8.isAbsolute(resolved))
2160
+ return `${CsrDevPaths.stubPrefix}${specifier}`;
2161
+ this.#fallbacks.add(specifier);
2162
+ this.#runtimeResolved.set(importer, (this.#runtimeResolved.get(importer) ?? new Set).add(specifier));
2163
+ return CsrDevPaths.realpath(resolved);
1746
2164
  }
1747
- }
1748
-
1749
- // pkgs/@akanjs/devkit/frontendBuild/vendorSpecifiers.ts
1750
- var VENDOR_SPECIFIERS = [
1751
- "react",
1752
- "react-dom",
1753
- "react-dom/client",
1754
- "react/jsx-runtime",
1755
- "react/jsx-dev-runtime",
1756
- "react-refresh/runtime",
1757
- "scheduler",
1758
- "react-server-dom-webpack/client.browser",
1759
- "akanjs/store",
1760
- "akanjs/store/agent",
1761
- "akanjs/base",
1762
- "akanjs/common",
1763
- "akanjs/constant",
1764
- "akanjs/fetch",
1765
- "tailwind-merge"
1766
- ];
1767
- var NARROWABLE_VENDOR_SPECIFIERS = [
1768
- "akanjs/store",
1769
- "akanjs/store/agent",
1770
- "akanjs/base",
1771
- "akanjs/common",
1772
- "akanjs/constant",
1773
- "akanjs/fetch",
1774
- "tailwind-merge"
1775
- ];
1776
-
1777
- // pkgs/@akanjs/devkit/frontendBuild/routeClientBuilder.ts
1778
- var SSR_CLIENT_ALIAS_EXTERNALS = [
1779
- "react",
1780
- "react-dom",
1781
- "react-dom/client",
1782
- "react/jsx-runtime",
1783
- "react/jsx-dev-runtime"
1784
- ];
1785
- var SSR_CLIENT_EXTERNALS = [...SSR_CLIENT_ALIAS_EXTERNALS, "akanjs/fetch"];
1786
-
1787
- class RouteClientBuilder {
1788
- #app;
1789
- #seeds;
1790
- #graphSeeds;
1791
- #knownEntries;
1792
- #command;
1793
- #discovery;
1794
- #entries;
1795
- #browser;
1796
- constructor(options) {
1797
- this.#app = options.app;
1798
- this.#seeds = options.seeds;
1799
- this.#graphSeeds = options.graphSeeds;
1800
- this.#knownEntries = options.knownEntries ?? new Set;
1801
- this.#command = options.command ?? "start";
1802
- this.#discovery = options.discovery;
1803
- this.#entries = options.entries;
1804
- this.#browser = options.browser ?? (this.#command === "start" ? "registry" : "chunks");
2165
+ static #onDisk(resolved) {
2166
+ return resolved && path8.isAbsolute(resolved) && fs4.existsSync(resolved) ? resolved : null;
1805
2167
  }
1806
- async build() {
1807
- const discovered = this.#entries ?? await (await this.#getDiscovery()).discover(this.#seeds);
1808
- if (discovered.every((e) => this.#knownEntries.has(e)))
1809
- return this.#emptyResult(discovered);
1810
- const entries = this.#graphSeeds ? [...new Set([...discovered, ...await (await this.#getDiscovery()).discover(this.#graphSeeds)])].sort() : discovered.filter((e) => !this.#knownEntries.has(e));
1811
- const bootstrapEntries = await this.#createBootstrapEntries(entries);
1812
- const registry = this.#browser === "registry" ? new CsrDevPaths(this.#app.workspace.workspaceRoot) : null;
1813
- const browserBundle = registry ? null : await this.#buildBrowserBundle(bootstrapEntries);
1814
- const ssrBundle = await this.#buildSsrBundle(bootstrapEntries);
1815
- const referenceBundle = browserBundle ?? ssrBundle;
1816
- const acceptedEntries = new Set(entries);
1817
- const routeEntries = new Set(discovered);
1818
- const manifestDelta = {};
1819
- const ssrModuleMap = {};
1820
- const clientDeps = new Set;
1821
- const clientDepsByEntry = {};
1822
- for (const [key, bundleRow] of Object.entries(referenceBundle.manifest)) {
1823
- const manifestEntry = RouteClientBuilder.resolveOriginalManifestEntry(key, bootstrapEntries.originalByBuildEntry, referenceBundle.clientReferenceIdByAbsPath, this.#app.workspace.workspaceRoot);
1824
- if (!manifestEntry)
1825
- continue;
1826
- if (!acceptedEntries.has(manifestEntry.originalEntry))
1827
- continue;
1828
- const row = registry ? RouteClientBuilder.#registryRow(registry, manifestEntry.originalEntry, bundleRow) : bundleRow;
1829
- manifestDelta[manifestEntry.key] = row;
1830
- const ssrOutput = ssrBundle.entryOutputAbsByAbsPath.get(manifestEntry.buildEntry);
1831
- if (!ssrOutput)
2168
+ #resolvedBySibling(importer, specifier) {
2169
+ const scope = CsrDevResolver.#packageScopeOf(importer);
2170
+ for (const [other, bySpecifier] of this.#resolution) {
2171
+ const target = bySpecifier.get(specifier);
2172
+ if (!target || other === importer || this.#runtimeResolved.get(other)?.has(specifier))
1832
2173
  continue;
1833
- ssrModuleMap[row.id] ??= {};
1834
- ssrModuleMap[row.id][row.name] = { id: ssrOutput, chunks: [ssrOutput, ssrOutput], name: row.name, async: true };
1835
- }
1836
- for (const entry of bootstrapEntries.buildEntries) {
1837
- const buildEntry = path7.resolve(entry);
1838
- const originalEntry = path7.resolve(bootstrapEntries.originalByBuildEntry.get(buildEntry) ?? buildEntry);
1839
- if (!acceptedEntries.has(originalEntry))
2174
+ if (!CsrDevPaths.isStub(target) && !fs4.existsSync(target))
1840
2175
  continue;
1841
- const deps = new Set([originalEntry]);
1842
- for (const dep of referenceBundle.entryDepsByAbsPath.get(buildEntry) ?? [])
1843
- deps.add(path7.resolve(dep));
1844
- const sortedDeps = [...deps].sort();
1845
- clientDepsByEntry[originalEntry] = sortedDeps;
1846
- if (routeEntries.has(originalEntry))
1847
- for (const dep of sortedDeps)
1848
- clientDeps.add(dep);
2176
+ if (CsrDevResolver.#packageScopeOf(other) === scope)
2177
+ return target;
1849
2178
  }
1850
- return {
1851
- manifestDelta,
1852
- ssrManifestDelta: { moduleLoading: null, moduleMap: ssrModuleMap },
1853
- newEntries: entries.filter((e) => !this.#knownEntries.has(e)),
1854
- discoveredEntries: discovered,
1855
- clientDeps: [...clientDeps].sort(),
1856
- clientDepsByEntry,
1857
- ...registry ? { registryEntries: [...acceptedEntries].sort() } : {},
1858
- ...browserBundle ? { externalsByChunkUrl: Object.fromEntries(browserBundle.externalsByChunkUrl) } : {}
1859
- };
1860
- }
1861
- static #registryRow(paths, entry, row) {
1862
- return {
1863
- id: `${SSR_DEV_ID_PREFIX}${paths.idOf(entry)}`,
1864
- chunks: [SSR_DEV_CHUNK, SSR_DEV_CHUNK],
1865
- name: row.name,
1866
- async: true
1867
- };
2179
+ return null;
1868
2180
  }
1869
- async#getDiscovery() {
1870
- this.#discovery ??= await GraphClientEntryDiscovery.create(this.#app);
1871
- return this.#discovery;
2181
+ #remember(importer, specifier, target) {
2182
+ const byImporter = this.#resolution.get(importer) ?? new Map;
2183
+ this.#resolution.set(importer, byImporter.set(specifier, target));
1872
2184
  }
1873
- #emptyResult(discoveredEntries = []) {
1874
- return {
1875
- manifestDelta: {},
1876
- ssrManifestDelta: { moduleLoading: null, moduleMap: {} },
1877
- newEntries: [],
1878
- discoveredEntries,
1879
- clientDeps: [],
1880
- clientDepsByEntry: {}
1881
- };
2185
+ #isInlineSpecifier(specifier) {
2186
+ if (specifier.startsWith(".") || path8.isAbsolute(specifier) || specifier.startsWith("node:"))
2187
+ return false;
2188
+ return this.#context.optimizeImports.some((pattern) => {
2189
+ const base = CsrDevResolver.#patternBase(pattern);
2190
+ return specifier === base || specifier.startsWith(`${base}/`);
2191
+ });
1882
2192
  }
1883
- async#buildBrowserBundle(bootstrapEntries) {
1884
- const reactFastRefresh = process.env.AKAN_REACT_FAST_REFRESH !== "0";
1885
- return new ClientEntriesBundler({
1886
- app: this.#app,
1887
- entries: bootstrapEntries.buildEntries,
1888
- plugins: [
1889
- await createBarrelImportsPlugin(this.#app, {
1890
- pipeAfter: reactFastRefresh ? RouteClientBuilder.normalizeNamedDefaultFunctionForFastRefresh : undefined,
1891
- external: VENDOR_SPECIFIERS
1892
- })
1893
- ],
1894
- external: VENDOR_SPECIFIERS,
1895
- command: this.#command,
1896
- reactFastRefresh
1897
- }).bundle();
2193
+ static #patternBase(pattern) {
2194
+ return pattern.endsWith("/*") ? pattern.slice(0, -2) : pattern;
1898
2195
  }
1899
- async#buildSsrBundle(bootstrapEntries) {
1900
- return new ClientEntriesBundler({
1901
- app: this.#app,
1902
- entries: bootstrapEntries.buildEntries,
1903
- plugins: [await createBarrelImportsPlugin(this.#app)],
1904
- ...RouteClientBuilder.resolveSsrClientBundleOptions(this.#command),
1905
- outputSubdir: "client-ssr",
1906
- command: this.#command
1907
- }).bundle();
2196
+ static #packageNameOf(file) {
2197
+ const marker = `${path8.sep}node_modules${path8.sep}`;
2198
+ const index = file.lastIndexOf(marker);
2199
+ if (index < 0)
2200
+ return null;
2201
+ const [scope, name] = file.slice(index + marker.length).split(path8.sep);
2202
+ return (scope?.startsWith("@") ? `${scope}/${name}` : scope) || null;
1908
2203
  }
1909
- async#createBootstrapEntries(entries) {
1910
- if (!await Bun.file(path7.join(this.#app.cwdPath, "lib", "st.ts")).exists()) {
1911
- return { buildEntries: entries, originalByBuildEntry: new Map };
1912
- }
1913
- const outdir = path7.join(this.#app.cwdPath, ".akan", "generated", "client-entry-bootstrap");
1914
- await mkdir2(outdir, { recursive: true });
1915
- const originalByBuildEntry = new Map;
1916
- const buildEntries = await Promise.all(entries.map(async (entry) => {
1917
- const absEntry = path7.resolve(entry);
1918
- const hash = Bun.hash(`${this.#app.name}
1919
- ${absEntry}`).toString(36);
1920
- const base = path7.basename(absEntry).replace(/[^A-Za-z0-9._-]/g, "_");
1921
- const wrapperEntry = path7.join(outdir, `${base}-${hash}.tsx`);
1922
- const exportNames = await this.#scanExportNames(absEntry);
1923
- await Bun.write(wrapperEntry, RouteClientBuilder.createStoreBootstrapEntrySource({
1924
- appName: this.#app.name,
1925
- originalEntry: absEntry,
1926
- exportNames
1927
- }));
1928
- originalByBuildEntry.set(path7.resolve(wrapperEntry), absEntry);
1929
- return wrapperEntry;
1930
- }));
1931
- return { buildEntries, originalByBuildEntry };
2204
+ static #packageScopeOf(file) {
2205
+ const marker = `${path8.sep}node_modules${path8.sep}`;
2206
+ const index = file.lastIndexOf(marker);
2207
+ if (index < 0)
2208
+ return "";
2209
+ const [scope, name] = file.slice(index + marker.length).split(path8.sep);
2210
+ return file.slice(0, index + marker.length) + (scope?.startsWith("@") ? `${scope}${path8.sep}${name}` : scope);
1932
2211
  }
1933
- async#scanExportNames(absEntry) {
1934
- return scanUseClientExports(await Bun.file(absEntry).text(), absEntry, this.#app.workspace.workspaceRoot);
2212
+ }
2213
+
2214
+ // pkgs/@akanjs/devkit/frontendBuild/devBarrelImports.ts
2215
+ import path9 from "path";
2216
+ class DevBarrelImports {
2217
+ #barrels;
2218
+ #resolvePackage;
2219
+ #analyzer;
2220
+ #packages = new Map;
2221
+ constructor(barrels, resolvePackage) {
2222
+ this.#barrels = [...barrels];
2223
+ this.#resolvePackage = resolvePackage;
2224
+ this.#analyzer = new BarrelAnalyzer({ resolvePackage });
1935
2225
  }
1936
- static normalizeNamedDefaultFunctionForFastRefresh(source, { path: filePath } = {}) {
1937
- const declared = RouteClientBuilder.#declaredNamedDefaultFunctions(source, filePath);
1938
- if (declared.length === 0)
2226
+ static async create(app, barrels) {
2227
+ if (barrels.length === 0)
1939
2228
  return null;
1940
- let next = "";
1941
- let cursor = 0;
1942
- for (const { index, text, lineStart, indent, asyncKeyword, name } of declared) {
1943
- next += `${source.slice(cursor, index)}${lineStart}${indent}${asyncKeyword}function ${name}`;
1944
- cursor = index + text.length;
1945
- }
1946
- next += source.slice(cursor);
1947
- return `${next}
1948
- ${declared.map(({ name }) => `export default ${name};`).join(`
1949
- `)}
1950
- `;
2229
+ return new DevBarrelImports(barrels, await createTsconfigPackageResolver(app));
1951
2230
  }
1952
- static #declaredNamedDefaultFunctions(source, filePath) {
1953
- const candidates = [
1954
- ...source.matchAll(/(^|\n)([^\S\n]*)export\s+default\s+(async\s+)?function\s+([A-Za-z_$][\w$]*)(?=\s*(?:<|\())/g)
1955
- ].map((match) => ({
1956
- index: match.index,
1957
- text: match[0],
1958
- lineStart: match[1] ?? "",
1959
- indent: match[2] ?? "",
1960
- asyncKeyword: match[3] ?? "",
1961
- name: match[4] ?? ""
1962
- }));
1963
- if (candidates.length === 0)
1964
- return [];
1965
- const probeName = (idx) => `__akanNamedDefault${idx}`;
1966
- let probe = "";
1967
- let cursor = 0;
1968
- candidates.forEach(({ index, text, lineStart, indent, asyncKeyword }, idx) => {
1969
- probe += `${source.slice(cursor, index)}${lineStart}${indent}export ${asyncKeyword}function ${probeName(idx)}`;
1970
- cursor = index + text.length;
2231
+ async rewrite(source, importer) {
2232
+ const named = this.#barrels.filter((barrel) => source.includes(barrel));
2233
+ if (named.length === 0)
2234
+ return null;
2235
+ const packages = await this.#packagesOf(named);
2236
+ const from = path9.dirname(CsrDevPaths.realpath(importer));
2237
+ const names = new Map;
2238
+ const contents = await rewriteBarrelImports(source, named, this.#analyzer, {
2239
+ keepLines: true,
2240
+ specifierOf: (subpath) => DevBarrelImports.#relative(subpath, from, packages),
2241
+ onImport: (barrel, imported) => names.set(barrel, new Set([...names.get(barrel) ?? [], ...imported]))
1971
2242
  });
1972
- probe += source.slice(cursor);
1973
- const exported = RouteClientBuilder.#scanExports(probe, filePath);
1974
- return candidates.filter((_, idx) => exported.has(probeName(idx)));
1975
- }
1976
- static #scanExports(source, filePath) {
1977
- try {
1978
- return new Set(new Bun.Transpiler({ loader: filePath ? loaderFor(filePath) : "tsx" }).scan(source).exports);
1979
- } catch {
1980
- return new Set;
1981
- }
2243
+ const narrowed = await Promise.all([...names].map(async ([barrel, set]) => {
2244
+ const sorted = [...set].sort();
2245
+ return [barrel, { names: sorted, hash: await this.fingerprint(barrel, sorted) }];
2246
+ }));
2247
+ return { contents, narrowed: Object.fromEntries(narrowed) };
1982
2248
  }
1983
- static resolveSsrClientRuntimeAliases() {
1984
- const serverEntry = RouteClientBuilder.resolveAkanServerEntry();
1985
- return { [Bun.resolveSync("akanjs/fetch", serverEntry)]: "akanjs/fetch" };
2249
+ async fingerprint(barrel, names) {
2250
+ const packages = await this.#packagesOf([barrel]);
2251
+ const aliased = names.map((name, index) => `${name} as _${index}`).join(", ");
2252
+ const narrowed = await rewriteBarrelImports(`import { ${aliased} } from ${JSON.stringify(barrel)};`, [barrel], this.#analyzer, { specifierOf: (subpath) => DevBarrelImports.#fileOf(subpath, packages) ?? subpath });
2253
+ return Bun.hash(narrowed ?? "").toString(36);
1986
2254
  }
1987
- static resolveSsrClientBundleOptions(command) {
1988
- if (command === "start") {
1989
- return {
1990
- target: "bun",
1991
- external: SSR_CLIENT_EXTERNALS,
1992
- externalSubpaths: ["akanjs/fetch"],
1993
- externalAliases: RouteClientBuilder.resolveSsrClientRuntimeAliases()
2255
+ async stamps(barrels, idOf) {
2256
+ const stamped = await Promise.all([...barrels].map(async (barrel) => {
2257
+ const files = await this.#analyzer.filesOf(barrel);
2258
+ const read = [...new Set([...files, ...files.map((file) => path9.dirname(file))])];
2259
+ const stamp = {
2260
+ read: Object.fromEntries(read.map((file) => [idOf(file), CsrDevPaths.mtimeOf(file)])),
2261
+ digest: await this.#digest(barrel)
1994
2262
  };
1995
- }
1996
- return { target: "bun", external: SSR_CLIENT_ALIAS_EXTERNALS };
2263
+ return [barrel, stamp];
2264
+ }));
2265
+ return Object.fromEntries(stamped);
1997
2266
  }
1998
- static resolveAkanServerEntry() {
1999
- try {
2000
- return Bun.resolveSync("akanjs/server", import.meta.dir);
2001
- } catch {
2002
- return path7.resolve(import.meta.dir, "../../../server/index.ts");
2003
- }
2267
+ async#digest(barrel) {
2268
+ const map = await this.#analyzer.analyze(barrel);
2269
+ const packages = await this.#packagesOf([barrel]);
2270
+ const files = new Map;
2271
+ const fileOf = (subpath) => {
2272
+ let file = files.get(subpath);
2273
+ if (file === undefined) {
2274
+ file = DevBarrelImports.#fileOf(subpath, packages) ?? subpath;
2275
+ files.set(subpath, file);
2276
+ }
2277
+ return file;
2278
+ };
2279
+ const exports = [...map ?? []].map(([name, target]) => [name, target.originalName, !!target.namespace, fileOf(target.subpath)]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
2280
+ return Bun.hash(JSON.stringify([fileOf(barrel), map === null, exports])).toString(36);
2004
2281
  }
2005
- static createStoreBootstrapEntrySource(args) {
2006
- const originalEntry = JSON.stringify(path7.resolve(args.originalEntry));
2007
- const namedExports = args.exportNames.filter((name) => name !== "default");
2008
- const lines = [
2009
- ...StoreBootstrap.importLines(args.appName),
2010
- ...namedExports.length > 0 ? [`export { ${namedExports.join(", ")} } from ${originalEntry};`] : []
2011
- ];
2012
- if (args.exportNames.includes("default"))
2013
- lines.push(`export { default } from ${originalEntry};`);
2014
- return `${lines.join(`
2015
- `)}
2016
- `;
2282
+ async#packagesOf(barrels) {
2283
+ return (await Promise.all(barrels.map((barrel) => this.#packageOf(barrel)))).filter((pkg) => pkg !== null).sort((a, b) => b.pkgName.length - a.pkgName.length);
2017
2284
  }
2018
- static resolveOriginalManifestEntry(manifestKey, originalByBuildEntry, clientReferenceIdByBuildEntry = new Map, workspaceRoot = process.cwd()) {
2019
- const hashIdx = manifestKey.lastIndexOf("#");
2020
- if (hashIdx < 0)
2285
+ #packageOf(barrel) {
2286
+ let pkg = this.#packages.get(barrel);
2287
+ if (!pkg) {
2288
+ pkg = this.#resolvePackage(barrel);
2289
+ this.#packages.set(barrel, pkg);
2290
+ }
2291
+ return pkg;
2292
+ }
2293
+ static #fileOf(subpath, packages) {
2294
+ const pkg = packages.find(({ pkgName }) => subpath === pkgName || subpath.startsWith(`${pkgName}/`));
2295
+ if (!pkg)
2021
2296
  return null;
2022
- const buildReferenceId = manifestKey.slice(0, hashIdx);
2023
- const name = manifestKey.slice(hashIdx + 1);
2024
- const buildEntry = [...clientReferenceIdByBuildEntry.entries()].find(([, referenceId]) => referenceId === buildReferenceId)?.[0] ?? buildReferenceId;
2025
- const originalEntry = originalByBuildEntry.get(buildEntry) ?? buildEntry;
2026
- const originalReferenceId = toClientReferencePath(originalEntry, workspaceRoot);
2027
- return { buildEntry, originalEntry, name, key: `${originalReferenceId}#${name}` };
2297
+ const file = CsrDevPaths.resolveOnDisk(path9.join(pkg.pkgDir, subpath.slice(pkg.pkgName.length)));
2298
+ return file ? CsrDevPaths.realpath(file) : null;
2299
+ }
2300
+ static #relative(subpath, from, packages) {
2301
+ const file = DevBarrelImports.#fileOf(subpath, packages);
2302
+ if (!file)
2303
+ return subpath;
2304
+ const relative = path9.relative(from, file);
2305
+ if (path9.isAbsolute(relative))
2306
+ return file.split(path9.sep).join("/");
2307
+ const posix = relative.split(path9.sep).join("/");
2308
+ return posix.startsWith("../") ? posix : `./${posix}`;
2028
2309
  }
2029
2310
  }
2030
2311
 
@@ -2147,7 +2428,7 @@ class CsrDevModuleCompiler {
2147
2428
  const tangled = [];
2148
2429
  for (const artifact of result.outputs) {
2149
2430
  if (artifact.kind === "asset") {
2150
- const assetPath = path8.join(this.#outDir, artifact.path);
2431
+ const assetPath = path10.join(this.#outDir, artifact.path);
2151
2432
  await Bun.write(assetPath, artifact);
2152
2433
  this.#assets.add(assetPath);
2153
2434
  continue;
@@ -2157,8 +2438,8 @@ class CsrDevModuleCompiler {
2157
2438
  const meta = outputs[artifact.path];
2158
2439
  if (!meta?.entryPoint)
2159
2440
  throw new Error(`[csr-dev] no entry point recorded for ${artifact.path}`);
2160
- const file = CsrDevPaths.realpath(path8.resolve(meta.entryPoint));
2161
- const inputs = Object.keys(meta.inputs).map((input) => CsrDevPaths.realpath(path8.resolve(input)));
2441
+ const file = CsrDevPaths.realpath(path10.resolve(meta.entryPoint));
2442
+ const inputs = Object.keys(meta.inputs).map((input) => CsrDevPaths.realpath(path10.resolve(input)));
2162
2443
  if (inputs.some((input) => input !== file && this.#resolver.isRegistryModule(input))) {
2163
2444
  tangled.push(file);
2164
2445
  continue;
@@ -2193,7 +2474,7 @@ class CsrDevModuleCompiler {
2193
2474
  const reasons = new Map;
2194
2475
  for (const message of error.errors) {
2195
2476
  const file = message.position?.file;
2196
- if (typeof file !== "string" || !path8.isAbsolute(file))
2477
+ if (typeof file !== "string" || !path10.isAbsolute(file))
2197
2478
  continue;
2198
2479
  const real = CsrDevPaths.realpath(file);
2199
2480
  const at = message.position?.line ? `:${message.position.line}` : "";
@@ -2302,7 +2583,7 @@ class CsrDevModuleCompiler {
2302
2583
  }
2303
2584
  #rebaseSourceMap(text) {
2304
2585
  const map = JSON.parse(text);
2305
- const files = map.sources.map((source) => path8.resolve(source));
2586
+ const files = map.sources.map((source) => path10.resolve(source));
2306
2587
  map.sources = files.map((file) => `/${this.#paths.idOf(file)}`);
2307
2588
  map.sourcesContent = files.map((file, index) => CsrDevPaths.isVendorFile(file) ? null : map.sourcesContent?.[index] ?? null);
2308
2589
  return JSON.stringify(map);
@@ -2367,7 +2648,7 @@ ${preamble}return { ${names.join(", ")} };
2367
2648
 
2368
2649
  // pkgs/@akanjs/devkit/frontendBuild/csrDevPatcher.ts
2369
2650
  import fs5 from "fs";
2370
- import path9 from "path";
2651
+ import path11 from "path";
2371
2652
  import { appGenerationOf as appGenerationOf2, CSR_DEV_MANIFEST_FILE as CSR_DEV_MANIFEST_FILE2 } from "akanjs/server/hmr/csrDevManifest";
2372
2653
  class CsrDevPatcher {
2373
2654
  #bundler;
@@ -2402,7 +2683,7 @@ class CsrDevPatcher {
2402
2683
  return this.#handBack("the dev bundle config changed", generation, context);
2403
2684
  const metadataFile = changedFiles.find((file) => this.#bundler.isMetadataFile(file));
2404
2685
  if (metadataFile)
2405
- return this.#handBack(`${path9.basename(metadataFile)} changed`, generation, context);
2686
+ return this.#handBack(`${path11.basename(metadataFile)} changed`, generation, context);
2406
2687
  if (!resident && state.graph.metadata !== await this.#bundler.metadataFingerprint())
2407
2688
  return this.#handBack("signal or dictionary metadata changed since the registry was built", generation, context);
2408
2689
  this.#state = this.#resident ? state : null;
@@ -2504,7 +2785,7 @@ class CsrDevPatcher {
2504
2785
  CsrDevPatcher.#remember(code, compiled);
2505
2786
  const changedIds = compiled.filter((module) => !module.vendor).map((module) => module.id);
2506
2787
  const constantId = changedIds.find((id) => id.endsWith(".constant.ts"));
2507
- const reason = vendorJoined ? "an npm module joined the graph" : routesMoved ? "the route table changed" : constantId ? `${path9.basename(constantId)} changed` : undefined;
2788
+ const reason = vendorJoined ? "an npm module joined the graph" : routesMoved ? "the route table changed" : constantId ? `${path11.basename(constantId)} changed` : undefined;
2508
2789
  if (compiled.length === 0 && !reason) {
2509
2790
  await writer.writeJson("graph.json", graph);
2510
2791
  await writer.forgetModules(forgotten);
@@ -2619,9 +2900,9 @@ class CsrDevPatcher {
2619
2900
  const messages = error instanceof AggregateError ? error.errors : [];
2620
2901
  const named = messages.flatMap((message) => {
2621
2902
  const text = String(message.message ?? "");
2622
- const bases = [process.cwd(), ...failing.map((file) => path9.dirname(file))];
2903
+ const bases = [process.cwd(), ...failing.map((file) => path11.dirname(file))];
2623
2904
  return [...text.matchAll(/"([^"\n]+)"/g)].flatMap(([, quoted = ""]) => {
2624
- const found = bases.map((base) => path9.resolve(base, quoted)).find((file) => CsrDevPaths.isScript(file) && fs5.existsSync(file));
2905
+ const found = bases.map((base) => path11.resolve(base, quoted)).find((file) => CsrDevPaths.isScript(file) && fs5.existsSync(file));
2625
2906
  return found ? [CsrDevPaths.realpath(found)] : [];
2626
2907
  });
2627
2908
  });
@@ -2629,7 +2910,7 @@ class CsrDevPatcher {
2629
2910
  }
2630
2911
  static #failingFiles(error) {
2631
2912
  const messages = error instanceof AggregateError ? error.errors : [];
2632
- return messages.map((message) => message.position?.file).filter((file) => typeof file === "string" && path9.isAbsolute(file)).map((file) => CsrDevPaths.realpath(file));
2913
+ return messages.map((message) => message.position?.file).filter((file) => typeof file === "string" && path11.isAbsolute(file)).map((file) => CsrDevPaths.realpath(file));
2633
2914
  }
2634
2915
  async#carriedRoots(graph, changed, present) {
2635
2916
  const { paths } = this.#bundler;
@@ -2758,16 +3039,16 @@ class CsrDevPatcher {
2758
3039
  #shadowedImporters(graph, changedFiles) {
2759
3040
  const { paths } = this.#bundler;
2760
3041
  const bases = new Set(changedFiles.map((file) => CsrDevPaths.realpath(file)).filter((file) => !graph.modules[paths.idOf(file)] && CsrDevPaths.isScript(file) && fs5.existsSync(file)).flatMap((file) => {
2761
- const stem = file.slice(0, file.length - path9.extname(file).length);
2762
- return path9.basename(stem) === "index" ? [stem, path9.dirname(stem)] : [stem];
3042
+ const stem = file.slice(0, file.length - path11.extname(file).length);
3043
+ return path11.basename(stem) === "index" ? [stem, path11.dirname(stem)] : [stem];
2763
3044
  }));
2764
3045
  if (bases.size === 0)
2765
3046
  return [];
2766
3047
  return Object.entries(graph.resolution).filter(([importer, bySpecifier]) => {
2767
3048
  if (!graph.modules[importer] || graph.modules[importer]?.vendor)
2768
3049
  return false;
2769
- const dir = path9.dirname(paths.fileOf(importer));
2770
- return Object.keys(bySpecifier).some((specifier) => specifier.startsWith(".") && bases.has(path9.resolve(dir, specifier)));
3050
+ const dir = path11.dirname(paths.fileOf(importer));
3051
+ return Object.keys(bySpecifier).some((specifier) => specifier.startsWith(".") && bases.has(path11.resolve(dir, specifier)));
2771
3052
  }).map(([importer]) => importer);
2772
3053
  }
2773
3054
  #forgetDeletedModules({ graph, code }, present) {
@@ -2783,7 +3064,7 @@ class CsrDevPatcher {
2783
3064
 
2784
3065
  // pkgs/@akanjs/devkit/frontendBuild/registryMetadataFingerprint.ts
2785
3066
  import fs6 from "fs";
2786
- import path10 from "path";
3067
+ import path12 from "path";
2787
3068
 
2788
3069
  class RegistryMetadataFingerprint {
2789
3070
  static #sources = new Bun.Glob("**/*.{signal,dictionary}.ts");
@@ -2791,12 +3072,12 @@ class RegistryMetadataFingerprint {
2791
3072
  static async of(roots, isMetadataFile) {
2792
3073
  const stamps = [];
2793
3074
  for (const root of new Set(roots)) {
2794
- const libDir = path10.join(root, "lib");
3075
+ const libDir = path12.join(root, "lib");
2795
3076
  if (!fs6.existsSync(libDir))
2796
3077
  continue;
2797
- const files = RegistryMetadataFingerprint.#libFiles.map((name) => path10.join(libDir, name));
3078
+ const files = RegistryMetadataFingerprint.#libFiles.map((name) => path12.join(libDir, name));
2798
3079
  for await (const relative of RegistryMetadataFingerprint.#sources.scan({ cwd: libDir, onlyFiles: true }))
2799
- files.push(path10.join(libDir, relative));
3080
+ files.push(path12.join(libDir, relative));
2800
3081
  for (const file of files) {
2801
3082
  if (!isMetadataFile(file))
2802
3083
  continue;
@@ -2822,8 +3103,8 @@ class DevRegistryBundler {
2822
3103
  this.app = app;
2823
3104
  this.routePrefix = routePrefix;
2824
3105
  this.paths = new CsrDevPaths(app.workspace.workspaceRoot);
2825
- this.outDir = path11.join(app.cwdPath, ".akan/artifact", dirName);
2826
- this.entryDir = path11.join(app.cwdPath, ".akan/generated", dirName);
3106
+ this.outDir = path13.join(app.cwdPath, ".akan/artifact", dirName);
3107
+ this.entryDir = path13.join(app.cwdPath, ".akan/generated", dirName);
2827
3108
  this.writer = new CsrDevArtifactWriter(this.outDir, { routePrefix, library });
2828
3109
  }
2829
3110
  async update(changedFiles = [], options = {}) {
@@ -2861,10 +3142,10 @@ class DevRegistryBundler {
2861
3142
  return isAkanRuntimeMetadataFile(file);
2862
3143
  }
2863
3144
  async metadataFingerprint() {
2864
- const libsContainer = path11.resolve(this.app.workspace.workspaceRoot, "libs");
3145
+ const libsContainer = path13.resolve(this.app.workspace.workspaceRoot, "libs");
2865
3146
  const roots = await new WatchRootResolver(this.app).resolve();
2866
- const libRoots = roots.includes(libsContainer) ? fs7.readdirSync(libsContainer).map((name) => path11.join(libsContainer, name)) : roots.filter((root) => path11.dirname(root) === libsContainer);
2867
- return await RegistryMetadataFingerprint.of([path11.resolve(this.app.cwdPath), ...libRoots], (file) => this.isMetadataFile(file));
3147
+ const libRoots = roots.includes(libsContainer) ? fs7.readdirSync(libsContainer).map((name) => path13.join(libsContainer, name)) : roots.filter((root) => path13.dirname(root) === libsContainer);
3148
+ return await RegistryMetadataFingerprint.of([path13.resolve(this.app.cwdPath), ...libRoots], (file) => this.isMetadataFile(file));
2868
3149
  }
2869
3150
  async fullBuild(context, generation, reason) {
2870
3151
  const metadata = await this.metadataFingerprint();
@@ -2968,11 +3249,11 @@ class CsrDevBundler extends DevRegistryBundler {
2968
3249
  };
2969
3250
  }
2970
3251
  async writeEntries(context) {
2971
- await mkdir3(this.entryDir, { recursive: true });
3252
+ await mkdir4(this.entryDir, { recursive: true });
2972
3253
  const files = {};
2973
3254
  const changed = [];
2974
3255
  for (const basePath of context.htmlBasePaths) {
2975
- const file = path12.join(this.entryDir, CsrEntryFiles.entryFilename(basePath));
3256
+ const file = path14.join(this.entryDir, CsrEntryFiles.entryFilename(basePath));
2976
3257
  const entryPages = CsrEntryFiles.pageEntriesForBasePath(context.pageEntries, basePath, context.basePaths);
2977
3258
  const generator = new PagesEntrySourceGenerator(entryPages, {
2978
3259
  isAsyncDefault: (moduleAbsPath) => this.#isAsyncDefault(moduleAbsPath)
@@ -3011,7 +3292,7 @@ ${hot}`;
3011
3292
  }
3012
3293
  #resolveRefreshRuntime() {
3013
3294
  const akanWebkit = CsrDevPaths.tryResolve("akanjs/webkit", this.app.cwdPath);
3014
- const bases = [this.app.cwdPath, this.paths.root, ...akanWebkit ? [path12.dirname(path12.dirname(akanWebkit))] : []];
3295
+ const bases = [this.app.cwdPath, this.paths.root, ...akanWebkit ? [path14.dirname(path14.dirname(akanWebkit))] : []];
3015
3296
  for (const base of bases) {
3016
3297
  const resolved = CsrDevPaths.tryResolve("react-refresh/runtime", base);
3017
3298
  if (resolved)
@@ -3021,326 +3302,6 @@ ${hot}`;
3021
3302
  }
3022
3303
  }
3023
3304
 
3024
- // pkgs/@akanjs/devkit/frontendBuild/devChangePlanner.ts
3025
- import path13 from "path";
3026
- var CONFIG_BASENAMES = new Set(["akan.config.ts", "bunfig.toml", "tsconfig.json", "package.json"]);
3027
- var BARREL_FACETS = new Set(["common", "srvkit", "ui", "webkit", "plugin"]);
3028
- var CLIENT_SUFFIXES = [".Template.tsx", ".Unit.tsx", ".Util.tsx", ".View.tsx", ".Zone.tsx", ".store.ts"];
3029
- var SHARED_SUFFIXES = [".constant.ts", ".dictionary.ts", ".signal.ts"];
3030
- var SERVER_SUFFIXES = [".service.ts", ".document.ts"];
3031
- var RUNTIME_METADATA_BASENAMES = new Set(["dict.ts", "sig.ts", "useClient.ts", "useServer.ts"]);
3032
-
3033
- class DevChangePlanner {
3034
- #workspaceRoot;
3035
- constructor({ workspaceRoot }) {
3036
- this.#workspaceRoot = path13.resolve(workspaceRoot);
3037
- }
3038
- plan({ generation, files, kinds, generatedFiles = [] }) {
3039
- const fileList = uniqueResolved([...files, ...generatedFiles]);
3040
- const generatedSet = new Set(generatedFiles.map((file) => path13.resolve(file)));
3041
- const kindSet = new Set(kinds);
3042
- const roles = new Set;
3043
- const actions = new Set;
3044
- const reasonByFile = {};
3045
- for (const kind of kindSet) {
3046
- if (kind === "css") {
3047
- roles.add("css");
3048
- actions.add("rebuild-css");
3049
- }
3050
- if (kind === "config") {
3051
- roles.add("config");
3052
- actions.add("restart-dev-host");
3053
- }
3054
- }
3055
- for (const file of fileList) {
3056
- const reasons = new Set;
3057
- const fileRoles = this.#rolesForFile(file, { isGenerated: generatedSet.has(path13.resolve(file)), reasons });
3058
- for (const role of fileRoles)
3059
- roles.add(role);
3060
- if (reasons.has("runtime-metadata"))
3061
- actions.add("restart-builder");
3062
- if (reasons.size > 0)
3063
- reasonByFile[path13.resolve(file)] = [...reasons].sort();
3064
- }
3065
- if (roles.has("barrel"))
3066
- actions.add("sync-generated");
3067
- if (roles.has("server") || roles.has("shared"))
3068
- actions.add("restart-backend");
3069
- if (roles.has("client") || roles.has("shared"))
3070
- actions.add("rebuild-client");
3071
- if (roles.has("css"))
3072
- actions.add("rebuild-css");
3073
- return {
3074
- generation,
3075
- files: fileList,
3076
- generatedFiles: uniqueResolved(generatedFiles),
3077
- roles: [...roles].sort(),
3078
- actions: [...actions].sort(),
3079
- reasonByFile
3080
- };
3081
- }
3082
- #rolesForFile(file, { isGenerated, reasons }) {
3083
- const roles = new Set;
3084
- const abs = path13.resolve(file);
3085
- const base = path13.basename(abs);
3086
- const ext = path13.extname(abs).toLowerCase();
3087
- const isSource = SOURCE_EXTS.has(ext);
3088
- const rel = path13.relative(this.#workspaceRoot, abs);
3089
- const parts = rel.split(path13.sep).filter(Boolean);
3090
- if (CONFIG_BASENAMES.has(base)) {
3091
- roles.add("config");
3092
- reasons.add("config-file");
3093
- }
3094
- if (ext === ".css") {
3095
- roles.add("css");
3096
- reasons.add("css-file");
3097
- }
3098
- if (isGenerated || isSource && this.#isBarrelFacetChild(parts)) {
3099
- roles.add("barrel");
3100
- reasons.add(isGenerated ? "generated-index" : "barrel-facet-child");
3101
- }
3102
- if (isSource && this.#isServerBiased(base, parts)) {
3103
- roles.add("server");
3104
- reasons.add("server-path");
3105
- }
3106
- if (isSource && this.#isClientBiased(base, parts)) {
3107
- roles.add("client");
3108
- reasons.add("client-path");
3109
- }
3110
- if (isSource && this.#isSharedBiased(base, parts)) {
3111
- roles.add("shared");
3112
- reasons.add("shared-path");
3113
- }
3114
- if (isSource && this.#isRuntimeMetadataFile(parts, base)) {
3115
- reasons.add("runtime-metadata");
3116
- }
3117
- if (roles.has("server") && roles.has("client")) {
3118
- roles.delete("server");
3119
- roles.delete("client");
3120
- roles.add("shared");
3121
- reasons.add("server-client-overlap");
3122
- }
3123
- if (roles.size === 0 && SOURCE_EXTS.has(ext) && this.#isWorkspaceSource(rel)) {
3124
- roles.add("shared");
3125
- reasons.add("workspace-source-fallback");
3126
- }
3127
- return roles;
3128
- }
3129
- #isServerBiased(base, parts) {
3130
- return parts.includes("srvkit") || SERVER_SUFFIXES.some((suffix) => base.endsWith(suffix)) || base === "main.ts" || base === "server.ts";
3131
- }
3132
- #isClientBiased(base, parts) {
3133
- return parts.includes("ui") || parts.includes("webkit") || parts.includes("page") || CLIENT_SUFFIXES.some((suffix) => base.endsWith(suffix));
3134
- }
3135
- #isSharedBiased(base, parts) {
3136
- return parts.includes("common") || SHARED_SUFFIXES.some((suffix) => base.endsWith(suffix)) || RUNTIME_METADATA_BASENAMES.has(base);
3137
- }
3138
- #isRuntimeMetadataFile(parts, base) {
3139
- const parent = parts.at(-2);
3140
- if (parent === "lib" && RUNTIME_METADATA_BASENAMES.has(base))
3141
- return true;
3142
- const libIndex = parts.lastIndexOf("lib");
3143
- if (libIndex < 0 || parts.length <= libIndex + 1)
3144
- return false;
3145
- return base.endsWith(".dictionary.ts") || base.endsWith(".signal.ts");
3146
- }
3147
- #isBarrelFacetChild(parts) {
3148
- if (parts.length < 4)
3149
- return false;
3150
- const [scope, , facet, child] = parts;
3151
- if (scope !== "apps" && scope !== "libs")
3152
- return false;
3153
- if (!facet || !BARREL_FACETS.has(facet))
3154
- return false;
3155
- if (!child || child.startsWith(".") || child === "index.ts" || child === "index.tsx")
3156
- return false;
3157
- return true;
3158
- }
3159
- #isWorkspaceSource(rel) {
3160
- if (!rel || rel.startsWith("..") || path13.isAbsolute(rel))
3161
- return false;
3162
- const [scope] = rel.split(path13.sep);
3163
- return scope === "apps" || scope === "libs" || scope === "pkgs";
3164
- }
3165
- }
3166
- var uniqueResolved = (files) => [...new Set(files.map((file) => path13.resolve(file)))].sort();
3167
-
3168
- // pkgs/@akanjs/devkit/frontendBuild/devGeneratedIndexSync.ts
3169
- import { mkdir as mkdir4, readdir as readdir3, readFile as readFile2, rm as rm2, stat as stat2 } from "fs/promises";
3170
- import path14 from "path";
3171
- import { capitalize } from "akanjs/common";
3172
- var BARREL_FACETS2 = new Set(["common", "srvkit", "ui", "webkit", "plugin"]);
3173
- var FACET_SOURCE_FILE_RE = /\.(ts|tsx)$/;
3174
- var FACET_EXCLUDED_FILE_RE = /(^index\.tsx?$|\.d\.ts$|\.(test|spec)\.(ts|tsx)$|\.css$|\.scss$|\.sass$)/;
3175
- var FACET_PASCAL_CASE_RE = /^[A-Z][A-Za-z0-9]*$/;
3176
- var FACET_CAMEL_CASE_RE = /^[a-z][A-Za-z0-9]*$/;
3177
- var MODULE_UI_TYPES = ["Template", "Unit", "Util", "View", "Zone"];
3178
- var SERVICE_UI_TYPES = ["Util", "Zone"];
3179
- var SCALAR_UI_TYPES = ["Template", "Unit"];
3180
-
3181
- class DevGeneratedIndexSync {
3182
- #workspaceRoot;
3183
- constructor({ workspaceRoot }) {
3184
- this.#workspaceRoot = path14.resolve(workspaceRoot);
3185
- }
3186
- async syncForBatch(files) {
3187
- const indexPaths = new Set;
3188
- const errors = [];
3189
- for (const file of files) {
3190
- const facetIndex = this.#facetIndexFor(file);
3191
- if (facetIndex)
3192
- indexPaths.add(facetIndex);
3193
- const moduleIndex = await this.#moduleIndexForDirectoryEvent(file).catch((err) => {
3194
- errors.push(`[generated-index] module detection failed for ${file}: ${formatError2(err)}`);
3195
- return null;
3196
- });
3197
- if (moduleIndex)
3198
- indexPaths.add(moduleIndex);
3199
- }
3200
- const changedFiles = [];
3201
- for (const indexPath of [...indexPaths].sort()) {
3202
- try {
3203
- const changed = await this.#syncIndex(indexPath);
3204
- if (changed)
3205
- changedFiles.push(indexPath);
3206
- } catch (err) {
3207
- errors.push(`[generated-index] sync failed for ${indexPath}: ${formatError2(err)}`);
3208
- }
3209
- }
3210
- return { changedFiles, errors };
3211
- }
3212
- #facetIndexFor(file) {
3213
- const abs = path14.resolve(file);
3214
- const rel = path14.relative(this.#workspaceRoot, abs);
3215
- if (rel.startsWith("..") || path14.isAbsolute(rel))
3216
- return null;
3217
- const parts = rel.split(path14.sep).filter(Boolean);
3218
- if (parts.length < 4)
3219
- return null;
3220
- const [scope, project, facet, child] = parts;
3221
- if (scope !== "apps" && scope !== "libs" || !project || !facet || !BARREL_FACETS2.has(facet))
3222
- return null;
3223
- if (!child || child.startsWith(".") || child === "index.ts" || child === "index.tsx")
3224
- return null;
3225
- return path14.join(this.#workspaceRoot, scope, project, facet, "index.ts");
3226
- }
3227
- async#moduleIndexForDirectoryEvent(file) {
3228
- const abs = path14.resolve(file);
3229
- const rel = path14.relative(this.#workspaceRoot, abs);
3230
- if (rel.startsWith("..") || path14.isAbsolute(rel))
3231
- return null;
3232
- const parts = rel.split(path14.sep).filter(Boolean);
3233
- if (parts.length !== 4 && parts.length !== 5)
3234
- return null;
3235
- const [scope, project, libSegment, moduleSegment, scalarSegment] = parts;
3236
- if (scope !== "apps" && scope !== "libs" || !project || libSegment !== "lib")
3237
- return null;
3238
- const isExistingDirectory = await stat2(abs).then((s) => s.isDirectory()).catch(() => false);
3239
- const looksLikeDeletedDirectory = !path14.extname(abs);
3240
- if (!isExistingDirectory && !looksLikeDeletedDirectory)
3241
- return null;
3242
- if (moduleSegment === "__scalar" && scalarSegment) {
3243
- return path14.join(this.#workspaceRoot, scope, project, "lib", "__scalar", scalarSegment, "index.ts");
3244
- }
3245
- if (!moduleSegment || moduleSegment === "__scalar")
3246
- return null;
3247
- return path14.join(this.#workspaceRoot, scope, project, "lib", moduleSegment, "index.ts");
3248
- }
3249
- async#syncIndex(indexPath) {
3250
- const dir = path14.dirname(indexPath);
3251
- const content = await this.#contentForIndex(indexPath);
3252
- if (content === null) {
3253
- if (!await exists(indexPath))
3254
- return false;
3255
- await rm2(indexPath, { force: true });
3256
- return true;
3257
- }
3258
- const current = await readFile2(indexPath, "utf8").catch(() => null);
3259
- if (current === content)
3260
- return false;
3261
- await mkdir4(dir, { recursive: true });
3262
- await FileSys2.writeTextAtomic(indexPath, content);
3263
- return true;
3264
- }
3265
- async#contentForIndex(indexPath) {
3266
- const parts = path14.relative(this.#workspaceRoot, indexPath).split(path14.sep).filter(Boolean);
3267
- const facet = parts.at(-2);
3268
- if (facet && BARREL_FACETS2.has(facet))
3269
- return this.#facetContent(path14.dirname(indexPath));
3270
- return this.#moduleContent(path14.dirname(indexPath));
3271
- }
3272
- async#facetContent(dir) {
3273
- const nameCasePattern = path14.basename(dir) === "ui" ? FACET_PASCAL_CASE_RE : FACET_CAMEL_CASE_RE;
3274
- const entries = await readdir3(dir, { withFileTypes: true }).catch(() => null);
3275
- if (!entries)
3276
- return null;
3277
- const exportNames = entries.flatMap((entry) => {
3278
- const name = entry.name;
3279
- if (name.startsWith("."))
3280
- return [];
3281
- if (entry.isDirectory())
3282
- return nameCasePattern.test(name) ? [name] : [];
3283
- if (!entry.isFile())
3284
- return [];
3285
- if (!FACET_SOURCE_FILE_RE.test(name) || FACET_EXCLUDED_FILE_RE.test(name))
3286
- return [];
3287
- const exportName = name.replace(FACET_SOURCE_FILE_RE, "");
3288
- return nameCasePattern.test(exportName) ? [exportName] : [];
3289
- }).sort(compareExportNames);
3290
- if (exportNames.length === 0)
3291
- return `export {};
3292
- `;
3293
- return `${exportNames.map((name) => `export * from "./${name}";`).join(`
3294
- `)}
3295
- `;
3296
- }
3297
- async#moduleContent(dir) {
3298
- const rel = path14.relative(this.#workspaceRoot, dir);
3299
- const parts = rel.split(path14.sep).filter(Boolean);
3300
- const moduleSegment = parts.at(-1);
3301
- if (!moduleSegment)
3302
- return null;
3303
- const isScalar = parts.at(-2) === "__scalar";
3304
- const rawModel = moduleSegment.startsWith("_") ? moduleSegment.slice(1) : moduleSegment;
3305
- if (!rawModel)
3306
- return null;
3307
- const modelName = capitalize(rawModel);
3308
- const allowedTypes = isScalar ? SCALAR_UI_TYPES : moduleSegment.startsWith("_") ? SERVICE_UI_TYPES : MODULE_UI_TYPES;
3309
- const fileTypes = [];
3310
- for (const type of allowedTypes) {
3311
- if (await exists(path14.join(dir, `${modelName}.${type}.tsx`)))
3312
- fileTypes.push(type);
3313
- }
3314
- if (fileTypes.length === 0)
3315
- return null;
3316
- return `${fileTypes.map((type) => `import * as ${type} from "./${modelName}.${type}";`).join(`
3317
- `)}
3318
-
3319
- export const ${modelName} = { ${fileTypes.join(", ")} };
3320
- `;
3321
- }
3322
- }
3323
- var letterRankOf = (char) => char.toLowerCase().charCodeAt(0) * 2 + (char === char.toLowerCase() ? 1 : 0);
3324
- var digitRunAt = (name, idx) => /^\d+/.exec(name.slice(idx))?.[0] ?? "";
3325
- var compareExportNames = (a, b) => {
3326
- for (let idx = 0;idx < a.length && idx < b.length; ) {
3327
- const [runA, runB] = [digitRunAt(a, idx), digitRunAt(b, idx)];
3328
- if (runA && runB && runA !== runB)
3329
- return runA.length - runB.length || (runA < runB ? -1 : 1);
3330
- if (runA && runB)
3331
- idx += runA.length;
3332
- else if (runA || runB)
3333
- return runA ? -1 : 1;
3334
- else if (a.charAt(idx) !== b.charAt(idx))
3335
- return letterRankOf(a.charAt(idx)) - letterRankOf(b.charAt(idx));
3336
- else
3337
- idx++;
3338
- }
3339
- return a.length - b.length;
3340
- };
3341
- var exists = async (file) => stat2(file).then(() => true).catch(() => false);
3342
- var formatError2 = (err) => err instanceof Error ? err.message : String(err);
3343
-
3344
3305
  // pkgs/@akanjs/devkit/frontendBuild/ssrDevBundler.ts
3345
3306
  import { mkdir as mkdir5 } from "fs/promises";
3346
3307
  import path16 from "path";