@akanjs/cli 3.2.0-rc.2 → 3.2.0-rc.21

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 (132) hide show
  1. package/.build-stamp +2 -1
  2. package/CodeAgent-faqv7t4g.js +11 -0
  3. package/{CodeTui-zyc7zaq6.js → CodeTui-vqck9tet.js} +822 -666
  4. package/README.ko.md +26 -1
  5. package/README.md +26 -1
  6. package/TunnelShare-bwe3ddv7.js +18 -0
  7. package/agent.command-p75jvgrd.js +56 -0
  8. package/akanCode.js +12 -12
  9. package/appExecutor-020cyesq.js +11 -0
  10. package/{application.command-vb278qnq.js → application.command-ta2knqxm.js} +72 -34
  11. package/{applicationBuildRunner-bqbyeg84.js → applicationBuildRunner-gkh82j2b.js} +18 -13
  12. package/buildBatch.proc.js +26 -11
  13. package/{cloud.command-ca777ee2.js → cloud.command-v3jhfvm5.js} +31 -28
  14. package/cloud.script-be9s1432.js +35 -0
  15. package/{code.command-j08txqcd.js → code.command-mh7dh1st.js} +14 -9
  16. package/{context.command-2fa6egp9.js → context.command-1ycfjkdd.js} +28 -23
  17. package/context.runner-333jkz86.js +34 -0
  18. package/{dependencyScanner-78sq8m4q.js → dependencyScanner-ge10gb52.js} +2 -2
  19. package/{devTui-w38ch13a.js → devTui-rf374y2w.js} +1 -1
  20. package/{fileSys-zpvt5gtf.js → fileSys-q22646yc.js} +1 -1
  21. package/{guideline.command-w6yqpdec.js → guideline.command-w1grfwh7.js} +9 -4
  22. package/guidelines/agentRule/agentRule.instruction.md +17 -5
  23. package/guidelines/akanApi/akanApi.instruction.md +5 -3
  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 -0
  27. package/guidelines/errorCodes/errorCodes.instruction.md +158 -0
  28. package/guidelines/fieldRule/fieldRule.instruction.md +2 -1
  29. package/guidelines/mcpRule/mcpRule.instruction.md +86 -2
  30. package/guidelines/pageRule/pageRule.instruction.md +11 -1
  31. package/guidelines/runtimeRule/runtimeRule.instruction.md +7 -2
  32. package/guidelines/transportRule/transportRule.instruction.md +8 -1
  33. package/incrementalBuilder.proc.js +574 -410
  34. package/{index-c5ymqb05.js → index-013n6z7m.js} +12 -12
  35. package/{index-w15mg3km.js → index-0dm25wvf.js} +1 -1
  36. package/{index-8nbx607g.js → index-0hj82f9w.js} +136 -48
  37. package/{index-ebwkh7bt.js → index-1c0mjc2b.js} +25 -7
  38. package/{index-6h775rv3.js → index-1jk52ffq.js} +53 -12
  39. package/{index-hj6w4ka1.js → index-1p81ecbz.js} +1 -1
  40. package/{index-ygrdw6jw.js → index-1pjwsh2g.js} +65 -8
  41. package/{index-cbcwxp5v.js → index-22g3jq43.js} +9 -7
  42. package/{index-466z5931.js → index-2d9nm03s.js} +580 -364
  43. package/{index-0fj9ra3q.js → index-2k6mve6a.js} +18 -11
  44. package/{index-qd7xn2bk.js → index-2ny1e95c.js} +2 -2
  45. package/{index-j7p0jgaq.js → index-52w4jb87.js} +6 -6
  46. package/{index-e22zedc2.js → index-5h888r6j.js} +3 -3
  47. package/{index-7kmbqp0b.js → index-6pxmcaq8.js} +1 -1
  48. package/{index-xa0289eg.js → index-6zb17wcm.js} +16 -9
  49. package/{index-qgazn58x.js → index-7a07tdap.js} +50 -38
  50. package/{index-m5sg5spm.js → index-7ehdht84.js} +565 -187
  51. package/{index-y725zb1a.js → index-7v7tvgt7.js} +196 -168
  52. package/{index-pq5rjkch.js → index-88s746ns.js} +7 -2
  53. package/{index-r0a604h4.js → index-99kjwyma.js} +1 -1
  54. package/{index-2mrn1mrg.js → index-9f3reh2y.js} +1 -1
  55. package/{index-386canwe.js → index-9rv2zt48.js} +186 -121
  56. package/{index-wr9magsr.js → index-9zswcze5.js} +3 -3
  57. package/{index-xq97me1h.js → index-a41vv4cy.js} +811 -697
  58. package/{index-yf9wc28h.js → index-bejy9zyc.js} +1 -1
  59. package/{index-bdmgqzb5.js → index-bket1068.js} +58 -29
  60. package/{index-bns3wcpc.js → index-by2tvsq6.js} +1 -1
  61. package/{index-1cb9apzn.js → index-czf94w8c.js} +2 -2
  62. package/{index-65b6ms4c.js → index-d3178asw.js} +15 -11
  63. package/index-dss3ds74.js +127 -0
  64. package/{index-annxfpgz.js → index-eyfty8kk.js} +9 -9
  65. package/{index-ny2k80mv.js → index-ffa52fwf.js} +1 -1
  66. package/{index-8jpc5fqv.js → index-g7jgd4xs.js} +2 -2
  67. package/{index-abfbf01s.js → index-gwsesvqc.js} +2 -2
  68. package/{index-kcpk2d20.js → index-h1w4wqgd.js} +1474 -1139
  69. package/{index-j1hjb477.js → index-hp2c7xc2.js} +1 -1
  70. package/index-j4yvgfhr.js +70 -0
  71. package/{index-84c2pgak.js → index-jx2jcw1r.js} +89 -78
  72. package/{index-j6eeh5d7.js → index-knpm8sdm.js} +5 -5
  73. package/{index-2gees180.js → index-mpp4aas6.js} +62 -33
  74. package/index-na8r4a27.js +30 -0
  75. package/{index-0mqga3h9.js → index-nmxszh6x.js} +525 -440
  76. package/{index-35j83zkd.js → index-p5zh7pmc.js} +2 -2
  77. package/{index-20wvskt8.js → index-pt0agdck.js} +1 -1
  78. package/{index-htxck0pn.js → index-q444k260.js} +15 -10
  79. package/{index-wfmpxke3.js → index-qssq2d41.js} +2775 -3677
  80. package/{index-23860fej.js → index-rwgqba9p.js} +24 -9
  81. package/{index-v50xjbbe.js → index-t4d0ckde.js} +1 -1
  82. package/index-va90m8nd.js +25 -0
  83. package/index-vjbne22r.js +80 -0
  84. package/{index-djc5nxpy.js → index-w23tf30e.js} +6 -6
  85. package/{index-mvwvxgtd.js → index-wa01phm9.js} +289 -210
  86. package/{index-h7hehkw6.js → index-xczjdng6.js} +3 -1
  87. package/{index-vbhx60x5.js → index-xwe7y0gf.js} +2140 -2165
  88. package/index-ze48c0vd.js +788 -0
  89. package/{index-dk4g0x0d.js → index-zttyg7tg.js} +27 -16
  90. package/{index-ygdbn9jn.js → index-zyb0ebm4.js} +1 -1
  91. package/index.js +29 -24
  92. package/libExecutor-tq994592.js +10 -0
  93. package/{library.command-8d03a0pq.js → library.command-x219mhcx.js} +9 -4
  94. package/{localRegistry.command-vyv5k6t0.js → localRegistry.command-4p17wa9t.js} +30 -24
  95. package/{module.command-vy3kg965.js → module.command-tjthnvvr.js} +17 -8
  96. package/{package.command-qjh13rs9.js → package.command-c6df2hxx.js} +13 -8
  97. package/package.json +2 -2
  98. package/{page.command-t0nx1jat.js → page.command-gf06paq2.js} +9 -4
  99. package/{pipeline.command-2yjeas7m.js → pipeline.command-y07dgj9b.js} +14 -8
  100. package/pkgExecutor-stde3yc3.js +10 -0
  101. package/{primitive.command-8vm49279.js → primitive.command-0enfygxn.js} +13 -8
  102. package/{projectTypecheck-s9hhe5sa.js → projectTypecheck-mk8wefvd.js} +2 -1
  103. package/{prompter-qrwx1p17.js → prompter-qyggfhqd.js} +2 -2
  104. package/{quality.command-v76fev72.js → quality.command-dkbdztad.js} +23 -16
  105. package/{recipeScanner-4b69ybe0.js → recipeScanner-rrx69awy.js} +1 -1
  106. package/{repair.command-fp4m3w03.js → repair.command-g5vd95ax.js} +13 -8
  107. package/{routeSourceValidator-4h947v7c.js → routeSourceValidator-8n6j1vn7.js} +4 -2
  108. package/{scalar.command-hxe6try8.js → scalar.command-7909pg0d.js} +11 -6
  109. package/skills/akan-debug/SKILL.md +10 -3
  110. package/skills/akan-err/SKILL.md +7 -0
  111. package/skills/akan-mcp/SKILL.md +13 -2
  112. package/skills/akan-scaffold/SKILL.md +2 -2
  113. package/skills/akan-transport/SKILL.md +2 -0
  114. package/skills/akan-validate/SKILL.md +1 -0
  115. package/{subspace.command-q42n1844.js → subspace.command-at4jt1fb.js} +29 -23
  116. package/templates/biomeForm.ts +1 -1
  117. package/templates/env/_env.server.type.ts +1 -1
  118. package/templates/facetIndex/index.ts +2 -37
  119. package/templates/lib/sig.ts +0 -4
  120. package/templates/lib/useClient.ts +1 -1
  121. package/templates/workspaceRoot/AGENTS.md.template +2 -1
  122. package/{tunnel.command-22g11n0x.js → tunnel.command-91h92dwr.js} +17 -12
  123. package/{typeChecker-s640r6c0.js → typeChecker-bfrd1n9n.js} +1 -1
  124. package/typecheck.proc.js +6 -3
  125. package/{verify.command-rx43bha1.js → verify.command-pzky05ts.js} +26 -20
  126. package/{workflow.command-yg0d8mmq.js → workflow.command-mqqe4n12.js} +37 -19
  127. package/{workspace.command-fcfztvn5.js → workspace.command-y4rznvhx.js} +64 -53
  128. package/CodeAgent-6cpjtj25.js +0 -11
  129. package/TunnelShare-zkfkrw8w.js +0 -14
  130. package/agent.command-kf1g3nh4.js +0 -51
  131. package/cloud.script-agpxzq6j.js +0 -30
  132. package/context.runner-ftv8373t.js +0 -29
@@ -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-y725zb1a.js";
5
+ } from "./index-7v7tvgt7.js";
9
6
  import {
10
7
  loaderFor,
11
8
  BarrelAnalyzer,
@@ -21,1996 +18,2294 @@ import {
21
18
  CsrDevPaths,
22
19
  PagesEntrySourceGenerator,
23
20
  PagesBundleBuilder
24
- } from "./index-84c2pgak.js";
21
+ } from "./index-jx2jcw1r.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-wfmpxke3.js";
29
+ } from "./index-ze48c0vd.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
- };
259
- }
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 });
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);
267
99
  }
268
- return (symbol) => available.get(symbol) ?? null;
269
- }
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;
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();
277
111
  }
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);
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);
121
+ }
288
122
  }
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;
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;
307
135
  }
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 };
136
+ async#fileExists(p) {
137
+ const absPath = path.resolve(p);
138
+ return await this.#lookup(this.#fileExistsCache, absPath, () => Bun.file(absPath).exists(), (exists) => exists);
324
139
  }
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);
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);
346
154
  }
155
+ return cached;
347
156
  }
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));
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
+ }
369
167
  }
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
- ` });
168
+ #scanImports(source) {
169
+ try {
170
+ return this.#tsTranspiler.scanImports(source);
171
+ } catch {
172
+ return [];
393
173
  }
394
174
  }
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);
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);
192
+ }
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);
203
+ }
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
- #readFiles = new Set;
594
- #barrelImporters = new Map;
595
- #reread = new Map;
596
- #settled = Promise.resolve();
597
- #epoch = 0;
598
- constructor(akanConfig, resolvePackage) {
599
- this.#akanConfig = akanConfig;
600
- this.#resolvePackage = resolvePackage;
601
- 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 };
602
380
  }
603
- static async create(app) {
604
- return new GraphClientEntryDiscovery(await app.getConfig(), await createTsconfigPackageResolver(app));
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
+ `;
605
393
  }
606
- async discover(seeds) {
607
- this.#settled = this.#settled.then(() => this.#dropRenarrowed());
608
- await this.#settled;
609
- const entries = new Set;
610
- for (const seed of seeds) {
611
- const walk = { visiting: new Set, partial: new Set, memo: new Map };
612
- for (const entry of await this.#discoverFromFile(seed, walk))
613
- entries.add(entry);
614
- }
615
- return Array.from(entries).sort();
394
+ static narrowedAliasSource(absEntry, names) {
395
+ const list = names.length > 0 ? `{ ${names.join(", ")} }` : "{}";
396
+ return `export ${list} from ${JSON.stringify(path2.resolve(absEntry))};
397
+ `;
616
398
  }
617
- invalidate(files) {
618
- if (files.length === 0)
619
- return;
620
- let moved = false;
621
- for (const file of files) {
622
- const absPath = path2.resolve(file);
623
- const exists = fs.existsSync(absPath);
624
- if (exists !== this.#readFiles.has(absPath))
625
- moved = true;
626
- if (!exists)
627
- this.#readFiles.delete(absPath);
628
- this.#factsCache.delete(absPath);
629
- this.#fileExistsCache.delete(absPath);
630
- }
631
- this.#epoch += 1;
632
- this.#reachableEntriesCache.clear();
633
- for (const [barrel, before] of this.#analyzer.forget(files))
634
- if (!this.#reread.has(barrel))
635
- this.#reread.set(barrel, before);
636
- if (!moved)
637
- return;
638
- this.#fileExistsCache.clear();
639
- this.#resolvedFileCache.clear();
640
- this.#resolvedSpecifierCache.clear();
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("; ")})`);
641
410
  }
642
- async#dropRenarrowed() {
643
- const reread = [...this.#reread];
644
- this.#reread.clear();
645
- for (const [barrel, before] of reread) {
646
- const [was, now] = await Promise.all([before, this.#analyzer.analyze(barrel)]);
647
- if (exportsKeyOf(was) === exportsKeyOf(now))
648
- continue;
649
- for (const importer of this.#barrelImporters.get(barrel) ?? [])
650
- this.#factsCache.delete(importer);
651
- }
411
+ async#scanEntryExportNames(absEntry) {
412
+ return scanUseClientExports(await Bun.file(absEntry).text(), absEntry, this.#app.workspace.workspaceRoot);
652
413
  }
653
- #lookup(cache, key, run, isFound) {
654
- const cached = cache.get(key);
655
- if (cached && (cached.found || cached.epoch === this.#epoch))
656
- return cached.promise;
657
- const entry = { epoch: this.#epoch, promise: run() };
658
- entry.promise.then((value) => {
659
- entry.found = isFound(value);
660
- }, () => {
661
- entry.found = false;
662
- });
663
- cache.set(key, entry);
664
- return entry.promise;
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
+ };
665
434
  }
666
- async#fileExists(p) {
667
- const absPath = path2.resolve(p);
668
- return await this.#lookup(this.#fileExistsCache, absPath, () => Bun.file(absPath).exists(), (exists) => exists);
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;
669
442
  }
670
- #facts(file) {
671
- const absPath = path2.resolve(file);
672
- let cached = this.#factsCache.get(absPath);
673
- if (!cached) {
674
- cached = (async () => {
675
- const content = await Bun.file(absPath).text().catch(() => null);
676
- if (content === null)
677
- return null;
678
- this.#readFiles.add(absPath);
679
- if (USE_CLIENT_RE.test(content))
680
- return { isClientEntry: true, imports: [] };
681
- return { isClientEntry: false, imports: this.#scanImports(await this.#rewrite(content, absPath)) };
682
- })();
683
- this.#factsCache.set(absPath, cached);
684
- }
685
- return cached;
443
+ async#rewriteExternalImportSpecifiers(outputs) {
444
+ if (Object.keys(this.#externalAliases).length === 0)
445
+ return;
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
+ }));
686
452
  }
687
- async#rewrite(content, absPath) {
688
- if (this.#akanConfig.barrelImports.length === 0)
689
- return content;
690
- for (const barrel of this.#akanConfig.barrelImports.filter((barrel) => content.includes(barrel)))
691
- this.#barrelImporters.set(barrel, (this.#barrelImporters.get(barrel) ?? new Set).add(absPath));
692
- try {
693
- return await rewriteBarrelImports(content, this.#akanConfig.barrelImports, this.#analyzer) ?? content;
694
- } catch {
695
- return content;
453
+ static rewriteExternalImportSpecifiers(source, aliases) {
454
+ let rewritten = source;
455
+ for (const [specifier, alias] of Object.entries(aliases)) {
456
+ if (!alias)
457
+ continue;
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
+ });
696
464
  }
465
+ return rewritten;
697
466
  }
698
- #scanImports(source) {
699
- try {
700
- return this.#tsTranspiler.scanImports(source);
701
- } catch {
702
- return [];
703
- }
467
+ #toServeUrl(absOutPath) {
468
+ const rel = path2.relative(this.#outdir, absOutPath).split(path2.sep).join("/");
469
+ return `${this.#servePrefix}/${rel}`;
704
470
  }
705
- async#resolveFileCandidate(absPathNoExt) {
706
- const cacheKey = path2.resolve(absPathNoExt);
707
- return await this.#lookup(this.#resolvedFileCache, cacheKey, async () => {
708
- if (await this.#fileExists(cacheKey))
709
- return cacheKey;
710
- for (const ext of SOURCE_EXTS) {
711
- const f = `${cacheKey}${ext}`;
712
- if (await this.#fileExists(f))
713
- return f;
714
- }
715
- for (const ext of SOURCE_EXTS) {
716
- const f = path2.join(cacheKey, `index${ext}`);
717
- if (await this.#fileExists(f))
718
- return f;
719
- }
720
- return null;
721
- }, (file) => file !== null);
471
+ #absFromOutdir(p) {
472
+ return path2.isAbsolute(p) ? p : path2.resolve(this.#outdir, p);
722
473
  }
723
- async#resolveSpecifier(spec, importerDir) {
724
- const cacheKey = `${importerDir}\x00${spec}`;
725
- return await this.#lookup(this.#resolvedSpecifierCache, cacheKey, async () => {
726
- if (spec.startsWith(".") || spec.startsWith("/")) {
727
- const abs = spec.startsWith("/") ? spec : path2.resolve(importerDir, spec);
728
- return await this.#resolveFileCandidate(abs);
729
- }
730
- const pkg = await this.#resolvePackage(spec);
731
- return pkg ? pkg.entryFile : null;
732
- }, (file) => file !== null);
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];
733
479
  }
734
- async#discoverFromFile(file, walk) {
735
- const epoch = this.#epoch;
736
- const absPath = path2.resolve(file);
737
- const cached = this.#reachableEntriesCache.get(absPath);
738
- if (cached)
739
- return new Set(cached);
740
- const memo = walk.memo.get(absPath);
741
- if (memo) {
742
- if (walk.partial.has(absPath))
743
- for (const onPath of walk.visiting)
744
- walk.partial.add(onPath);
745
- return new Set(memo);
480
+ #collectChunkUrls(absOutPath, visited = new Set) {
481
+ if (visited.has(absOutPath))
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));
746
495
  }
747
- if (walk.visiting.has(absPath)) {
748
- let below = false;
749
- for (const onPath of walk.visiting) {
750
- if (below)
751
- walk.partial.add(onPath);
752
- else
753
- below = onPath === absPath;
754
- }
755
- return new Set;
496
+ return urls;
497
+ }
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());
756
511
  }
757
- if (shouldSkipNodeModule(absPath))
758
- return new Set;
759
- walk.visiting.add(absPath);
760
- const entries = new Set;
761
- const facts = await this.#facts(absPath);
762
- if (!facts)
763
- return this.#finishDiscovery(absPath, walk, entries, epoch);
764
- if (facts.isClientEntry) {
765
- entries.add(absPath);
766
- return this.#finishDiscovery(absPath, walk, entries, epoch);
512
+ return externalsByChunkUrl;
513
+ }
514
+ #collectClientDeps(absOutPath, visited = new Set) {
515
+ if (visited.has(absOutPath))
516
+ return new Set;
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);
767
528
  }
768
- const importerDir = path2.dirname(absPath);
769
- for (const imp of facts.imports) {
770
- const spec = imp.path;
771
- if (!spec)
772
- continue;
773
- if (NON_SOURCE_EXT_RE.test(spec))
774
- continue;
775
- const resolved = await this.#resolveSpecifier(spec, importerDir);
776
- if (!resolved)
529
+ for (const imp of info.imports) {
530
+ if (imp.kind === "dynamic-import")
777
531
  continue;
778
- if (shouldSkipNodeModule(resolved))
532
+ const absImp = this.#absFromOutdir(imp.path);
533
+ if (!absImp.endsWith(".js"))
779
534
  continue;
780
- for (const entry of await this.#discoverFromFile(resolved, walk))
781
- entries.add(entry);
535
+ for (const dep of this.#collectClientDeps(absImp, visited))
536
+ deps.add(dep);
782
537
  }
783
- return this.#finishDiscovery(absPath, walk, entries, epoch);
538
+ return deps;
784
539
  }
785
- #finishDiscovery(absPath, walk, entries, epoch) {
786
- walk.visiting.delete(absPath);
787
- walk.memo.set(absPath, entries);
788
- if (epoch === this.#epoch && !walk.partial.has(absPath))
789
- this.#reachableEntriesCache.set(absPath, entries);
790
- 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;
791
567
  }
792
568
  }
793
569
 
794
- // pkgs/@akanjs/devkit/frontendBuild/csrDevBundler.ts
795
- import { mkdir as mkdir3 } from "fs/promises";
796
- import path12 from "path";
797
- 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
+ ];
798
597
 
799
- // pkgs/@akanjs/devkit/frontendBuild/devRegistryBundler.ts
800
- import fs7 from "fs";
801
- import path11 from "path";
802
- 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"];
803
607
 
804
- // pkgs/@akanjs/devkit/frontendBuild/csrDevArtifactWriter.ts
805
- import fs2 from "fs";
806
- import { mkdir, readdir as readdir2, rm } from "fs/promises";
807
- import path3 from "path";
808
- import {
809
- appGenerationOf,
810
- CSR_DEV_APP_FILE,
811
- CSR_DEV_KEPT_PATCHES,
812
- CSR_DEV_MANIFEST_FILE,
813
- CSR_DEV_PATCHING_MARKER,
814
- csrDevModuleFile
815
- } from "akanjs/server/hmr/csrDevManifest";
816
- class CsrDevArtifactWriter {
817
- static #keptVendors = 3;
818
- static #buildingMarker = ".building";
819
- #outDir;
820
- #routePrefix;
821
- #library;
822
- constructor(outDir, { routePrefix, library = false }) {
823
- this.#outDir = outDir;
824
- this.#routePrefix = routePrefix;
825
- 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 };
826
753
  }
827
- async markBuilding() {
828
- 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);
829
756
  }
830
- async clearBuilding() {
831
- 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
+ `;
832
772
  }
833
- async isBuilding() {
834
- 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)));
835
796
  }
836
- async forgetPatch(generation) {
837
- 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
+ }
838
803
  }
839
- async readJson(name) {
840
- const file = Bun.file(path3.join(this.#outDir, name));
841
- if (!await file.exists())
842
- return null;
843
- return await file.json().catch(() => null);
804
+ static resolveSsrClientRuntimeAliases() {
805
+ const serverEntry = RouteClientBuilder.resolveAkanServerEntry();
806
+ return { [Bun.resolveSync("akanjs/fetch", serverEntry)]: "akanjs/fetch" };
844
807
  }
845
- async writeJson(name, value) {
846
- 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 };
847
818
  }
848
- async writeModules(compiled) {
849
- await mkdir(path3.join(this.#outDir, "modules"), { recursive: true });
850
- const helpers = new Map(compiled.flatMap((module) => module.helpers ? [[module.helpers.hash, module.helpers]] : []));
851
- await Promise.all([
852
- ...compiled.flatMap((module) => [
853
- Bun.write(this.#modulePath(module.id, ".js"), module.factory),
854
- ...module.sourceMap ? [Bun.write(this.#modulePath(module.id, ".js.map"), module.sourceMap)] : []
855
- ]),
856
- ...[...helpers.values()].map((shared) => Bun.write(this.#helpersPath(shared.hash), shared.definition))
857
- ]);
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
+ }
858
825
  }
859
- async readCode(graph) {
860
- const ids = Object.keys(graph.modules).filter((id) => !graph.modules[id]?.vendor && this.hasModule(id));
861
- const hashes = [...new Set(ids.flatMap((id) => graph.modules[id]?.helpers ?? []))];
862
- const [modules, helpers] = await Promise.all([
863
- Promise.all(ids.map(async (id) => [id, await Bun.file(this.#modulePath(id, ".js")).text()])),
864
- Promise.all(hashes.map(async (hash) => [hash, await Bun.file(this.#helpersPath(hash)).text()]))
865
- ]);
866
- 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
+ `;
867
838
  }
868
- hasModule(id) {
869
- 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}` };
870
849
  }
871
- async forgetModules(ids) {
872
- await Promise.all(ids.flatMap((id) => [
873
- CsrDevArtifactWriter.#remove(this.#modulePath(id, ".js")),
874
- CsrDevArtifactWriter.#remove(this.#modulePath(id, ".js.map"))
875
- ]));
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);
876
993
  }
877
- async writeVendor(graph) {
878
- const ids = Object.keys(graph.modules).filter((id) => graph.modules[id]?.vendor).sort();
879
- const stubs = new Set(Object.values(graph.modules).flatMap((module) => module.deps.filter(CsrDevPaths.isStub)));
880
- const lines = [await this.#helperDefinitions(graph, ids), ...await this.#defineLines(ids)];
881
- for (const stub of [...stubs].sort()) {
882
- if (stub.startsWith(CsrDevPaths.emptyStubPrefix)) {
883
- lines.push(`__akan.define(${JSON.stringify(stub)}, function () {});
884
- `);
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)
885
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)}`);
886
1017
  }
887
- const message = `[akan-csr] ${stub.slice(CsrDevPaths.stubPrefix.length)} is a Node built-in the browser does not have`;
888
- lines.push(`__akan.define(${JSON.stringify(stub)}, function () {
889
- throw new Error(${JSON.stringify(message)});
890
- });
891
- `);
892
1018
  }
893
- const code = lines.join("");
894
- const vendorFile = `vendor-${Bun.hash(code).toString(36)}.js`;
895
- await this.#writeAtomic(vendorFile, code);
896
- return vendorFile;
897
- }
898
- async writeApp(graph, { generation, vendorFile, epoch }, code) {
899
- const ids = Object.keys(graph.modules).filter((id) => !graph.modules[id]?.vendor).sort();
900
- const lines = await this.#defineLines(ids, code);
901
- const blocks = ids.map((id, index) => [id, lines[index] ?? ""]);
902
- const start = this.#library ? `__akan.startLibrary(${JSON.stringify({ generation, refresh: graph.refresh, bootstrap: graph.entries[""], vendorFile, epoch })});
903
- ` : `__akan.start(${JSON.stringify({ generation, refresh: graph.refresh })});
904
- `;
905
- await this.#writeWithSourceMap(CSR_DEV_APP_FILE, await this.#helperDefinitions(graph, ids, code), blocks, start);
906
- }
907
- async writePatch(generation, modules) {
908
- const patchFile = `patch-${generation}.js`;
909
- const blocks = modules.map((module, index) => [module.id, `${JSON.stringify(module.id)}: ${module.factory}${index < modules.length - 1 ? `,
910
- ` : `
911
- `}`]);
912
- const helpers = new Map(modules.flatMap((module) => module.helpers ? [[module.helpers.hash, module.helpers]] : []));
913
- const header = `${[...helpers.values()].map((shared) => shared.definition).join("")}__akan.update(${generation}, {
914
- `;
915
- await this.#writeWithSourceMap(patchFile, header, blocks, `});
916
- `);
917
- return `${this.#routePrefix}${patchFile}`;
918
- }
919
- async writeState(graph, manifest) {
920
- await this.writeJson("graph.json", graph);
921
- await this.writeJson(CSR_DEV_MANIFEST_FILE, manifest);
922
- }
923
- async commitPatch(graph, manifest, announce, { modules, code }) {
924
- await this.writeJson(CSR_DEV_MANIFEST_FILE, manifest);
925
- announce();
926
- await CsrDevArtifactWriter.#appWriteDelay();
927
- await this.writeModules(modules);
928
- await this.writeJson("graph.json", graph);
929
- await this.writeApp(graph, manifest, code);
930
- await this.writeJson(CSR_DEV_MANIFEST_FILE, { ...manifest, appGeneration: manifest.generation });
931
- }
932
- async healApp(graph, manifest, code) {
933
- if (appGenerationOf(manifest) >= manifest.generation)
934
- return manifest;
935
- await this.writeApp(graph, manifest, code);
936
- const healed = { ...manifest, appGeneration: manifest.generation };
937
- await this.writeJson(CSR_DEV_MANIFEST_FILE, healed);
938
- return healed;
1019
+ return { changedFiles, errors };
939
1020
  }
940
- async prune(vendorFile, generation) {
941
- const names = await readdir2(this.#outDir);
942
- const stale = names.filter((name) => {
943
- const patch = /^patch-(\d+)\.js(?:\.layout\.json)?$/.exec(name);
944
- return patch ? Number(patch[1]) <= generation - CSR_DEV_KEPT_PATCHES : false;
945
- });
946
- 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);
947
- 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 };
948
1038
  }
949
- async pruneAfterFullBuild(graph, vendorFile, { generation, assets }) {
950
- const kept = new Set(Object.keys(graph.modules).flatMap((id) => [this.#modulePath(id, ".js"), this.#modulePath(id, ".js.map")]));
951
- for (const module of Object.values(graph.modules))
952
- if (module.helpers)
953
- kept.add(this.#helpersPath(module.helpers));
954
- for (const asset of assets)
955
- kept.add(path3.resolve(asset));
956
- const listed = async (dir) => (await readdir2(path3.join(this.#outDir, dir)).catch(() => [])).map((name) => path3.join(this.#outDir, dir, name));
957
- const stale = [
958
- ...(await listed("modules")).filter((file) => !kept.has(file)),
959
- ...(await listed("assets")).filter((file) => !kept.has(file)),
960
- ...(await listed(".")).filter((file) => {
961
- const name = path3.basename(file);
962
- return /^patch-\d+\.js(?:\.layout\.json)?$/.test(name) || name.endsWith(".tmp");
963
- }),
964
- path3.join(this.#outDir, CSR_DEV_PATCHING_MARKER)
965
- ];
966
- await Promise.all(stale.map((file) => CsrDevArtifactWriter.#remove(file)));
967
- 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;
968
1050
  }
969
- async#helperDefinitions(graph, ids, code) {
970
- const hashes = [...new Set(ids.flatMap((id) => graph.modules[id]?.helpers ?? []))].sort();
971
- 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
+ };
972
1068
  }
973
- async#defineLines(ids, code) {
974
- return await Promise.all(ids.map(async (id) => {
975
- const factory = code?.modules.get(id) ?? await Bun.file(this.#modulePath(id, ".js")).text();
976
- return `__akan.define(${JSON.stringify(id)}, ${factory});
977
- `;
978
- }));
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
+ };
979
1080
  }
980
- async#writeWithSourceMap(name, header, blocks, footer) {
981
- const layout = { lineCount: 0, modules: [] };
982
- let line = CsrDevPaths.lineCount(header);
983
- for (const [id, text] of blocks) {
984
- layout.modules.push([id, line + 1]);
985
- 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 });
986
1088
  }
987
- const code = `${header}${blocks.map(([, text]) => text).join("")}${footer}//# sourceMappingURL=${name}.map
988
- `;
989
- layout.lineCount = CsrDevPaths.lineCount(code);
990
- await this.writeJson(`${name}.layout.json`, layout);
991
- await this.#writeAtomic(name, code);
1089
+ return (symbol) => available.get(symbol) ?? null;
992
1090
  }
993
- async#writeAtomic(name, content) {
994
- const target = path3.join(this.#outDir, name);
995
- const temp = `${target}.${process.pid}.tmp`;
996
- await Bun.write(temp, content);
997
- 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;
998
1098
  }
999
- static async#remove(file) {
1000
- await rm(file, { force: true }).catch(() => {
1001
- return;
1002
- });
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);
1003
1109
  }
1004
- static async#appWriteDelay() {
1005
- const ms = Number(process.env.AKAN_CSR_DEV_APP_WRITE_DELAY_MS);
1006
- if (Number.isInteger(ms) && ms > 0)
1007
- 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;
1008
1128
  }
1009
- #modulePath(id, extension) {
1010
- 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
+ }
1011
1168
  }
1012
- #helpersPath(hash) {
1013
- 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));
1014
1190
  }
1015
- }
1016
-
1017
- // pkgs/@akanjs/devkit/frontendBuild/csrDevModuleCompiler.ts
1018
- 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
+ `)}
1019
1212
 
1020
- // pkgs/@akanjs/devkit/frontendBuild/csrDevFactoryCheck.ts
1021
- class CsrDevFactoryCheck {
1022
- static #parsed = new Set;
1023
- static problemOf(factory, helperDefinition = "") {
1024
- const key = Bun.hash(`${helperDefinition}\x00${factory}`);
1025
- if (CsrDevFactoryCheck.#parsed.has(key))
1026
- return null;
1027
- const problem = CsrDevFactoryCheck.#syntaxError(`${helperDefinition}return (${factory});`);
1028
- if (problem === null) {
1029
- CsrDevFactoryCheck.#parsed.add(key);
1030
- return null;
1031
- }
1032
- if (problem.includes("import.meta")) {
1033
- const line = factory.split(`
1034
- `).findIndex((text) => /(?<![\w$.])import\.meta\b/.test(text));
1035
- return `import.meta is left in it${line > 0 ? ` (compiled line ${line})` : ""}, which a classic script cannot hold: ${problem}`;
1213
+ ` });
1036
1214
  }
1037
- if (CsrDevFactoryCheck.#syntaxError(`${helperDefinition}return (async ${factory});`) === null)
1038
- return `a top-level await is left in it, which a CommonJS factory cannot wait on: ${problem}`;
1039
- return problem;
1040
- }
1041
- static thrower(id, problem) {
1042
- const message = `[akan-csr] ${id} was left out of the dev registry: ${problem}`;
1043
- return `function () {
1044
- throw new Error(${JSON.stringify(message)});
1045
- }`;
1046
1215
  }
1047
- static #syntaxError(source) {
1048
- try {
1049
- new Function(source);
1050
- return null;
1051
- } catch (error) {
1052
- 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);
1053
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 });
1054
1301
  }
1055
- }
1056
-
1057
- // pkgs/@akanjs/devkit/frontendBuild/csrDevResolver.ts
1058
- import fs3 from "fs";
1059
- import path4 from "path";
1060
- class CsrDevResolver {
1061
- static inline = "inline";
1062
- #paths;
1063
- #context;
1064
- #entryFiles;
1065
- #resolution = new Map;
1066
- #fallbacks = new Set;
1067
- #runtimeResolved = new Map;
1068
- #browserMaps = new Map;
1069
- #loaded = new Set;
1070
- #startedAt;
1071
- #prepassDone = false;
1072
- constructor({
1073
- paths,
1074
- context,
1075
- entryFiles,
1076
- resolution = {},
1077
- runtimeResolved = {},
1078
- startedAt = Date.now() - process.uptime() * 1000
1079
- }) {
1080
- this.#paths = paths;
1081
- this.#startedAt = startedAt;
1082
- this.#context = context;
1083
- this.#entryFiles = entryFiles;
1084
- for (const [importer, specifiers] of Object.entries(runtimeResolved))
1085
- this.#runtimeResolved.set(paths.fileOf(importer), new Set(specifiers));
1086
- for (const [importer, bySpecifier] of Object.entries(resolution))
1087
- this.#resolution.set(paths.fileOf(importer), new Map(Object.entries(bySpecifier).map(([specifier, target]) => [
1088
- specifier,
1089
- CsrDevPaths.isStub(target) ? target : paths.fileOf(target)
1090
- ])));
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;
1091
1318
  }
1092
- get prepassDone() {
1093
- 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
+ }
1094
1353
  }
1095
- get fallbacks() {
1096
- 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);
1097
1367
  }
1098
- async prepass() {
1099
- const result = await Bun.build({
1100
- entrypoints: [...this.#entryFiles, ...this.#context.refreshFile ? [this.#context.refreshFile] : []],
1101
- target: "browser",
1102
- metafile: true,
1103
- external: [...this.#context.externals ?? []],
1104
- define: this.#context.define,
1105
- optimizeImports: this.#context.optimizeImports,
1106
- plugins: [PagesBundleBuilder.createCssStubPlugin()]
1107
- });
1108
- this.#record(result.metafile.inputs);
1109
- 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
+ }
1110
1386
  }
1111
- async cover(files) {
1112
- if (!this.#prepassDone)
1113
- return;
1114
- const pending = files.filter((file) => CsrDevPaths.isScript(file) && !this.#loaded.has(file));
1115
- if (pending.length === 0)
1116
- return;
1117
- for (const file of pending)
1118
- this.#loaded.add(file);
1119
- const entries = new Set(pending);
1120
- const result = await Bun.build({
1121
- entrypoints: pending,
1122
- target: "browser",
1123
- metafile: true,
1124
- throw: false,
1125
- external: [...this.#context.externals ?? []],
1126
- define: this.#context.define,
1127
- plugins: [
1128
- {
1129
- name: "akan-csr-cover",
1130
- setup: (build) => {
1131
- build.onLoad({ filter: /.*/ }, (args) => entries.has(CsrDevPaths.realpath(args.path)) ? undefined : { contents: "module.exports = {};", loader: "js" });
1132
- }
1133
- }
1134
- ]
1135
- });
1136
- if (result.metafile)
1137
- 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);
1138
1407
  }
1139
- #record(inputs, only) {
1140
- for (const [input, { imports }] of Object.entries(inputs)) {
1141
- const importer = CsrDevPaths.realpath(path4.resolve(input));
1142
- if (only && !only.has(importer))
1143
- continue;
1144
- if (imports.every((record) => record.original))
1145
- this.#loaded.add(importer);
1146
- for (const record of imports) {
1147
- if (!record.original)
1148
- continue;
1149
- if (record.external) {
1150
- if (record.original.startsWith("node:"))
1151
- this.#remember(importer, record.original, `${CsrDevPaths.stubPrefix}${record.original}`);
1152
- continue;
1153
- }
1154
- const target = path4.resolve(record.path);
1155
- if (!fs3.existsSync(target))
1156
- continue;
1157
- this.#remember(importer, record.original, CsrDevPaths.realpath(target));
1158
- 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");
1159
1423
  }
1160
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
+ };
1161
1451
  }
1162
- resolve(importer, specifier, kind = "import") {
1163
- if (this.#isInlineSpecifier(specifier))
1164
- return CsrDevResolver.inline;
1165
- const disabled = this.#disabledInBrowser(importer, specifier, kind);
1166
- if (disabled)
1167
- return disabled;
1168
- const known = this.#resolution.get(importer)?.get(specifier);
1169
- const usable = known && this.#stillAnswers(importer, specifier, known, kind) ? known : null;
1170
- const target = usable ?? this.#resolveUnknown(importer, specifier, kind);
1171
- if (target === null || CsrDevPaths.isStub(target))
1172
- return target;
1173
- if (!CsrDevPaths.isScript(target))
1174
- return CsrDevResolver.inline;
1175
- if (!usable)
1176
- this.#remember(importer, specifier, target);
1177
- return target;
1178
- }
1179
- #stillAnswers(importer, specifier, known, kind) {
1180
- if (CsrDevPaths.isStub(known))
1181
- return true;
1182
- if (!fs3.existsSync(known))
1183
- return false;
1184
- if (!specifier.startsWith(".") || CsrDevPaths.isVendorFile(importer))
1185
- return true;
1186
- if (this.#hasBrowserMap(path4.dirname(importer)))
1187
- return true;
1188
- const onDisk = CsrDevPaths.resolveRelative(path4.dirname(importer), specifier, kind);
1189
- 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;
1190
1498
  }
1191
- isRegistryModule(file) {
1192
- if (!CsrDevPaths.isScript(file))
1193
- return false;
1194
- const packageName = CsrDevResolver.#packageNameOf(file);
1195
- if (packageName === null)
1196
- return true;
1197
- return !this.#context.optimizeImports.some((pattern) => {
1198
- const base = CsrDevResolver.#patternBase(pattern);
1199
- return base === packageName || base.startsWith(`${packageName}/`);
1200
- });
1499
+ #isServerBiased(base, parts) {
1500
+ return parts.includes("srvkit") || SERVER_SUFFIXES.some((suffix) => base.endsWith(suffix)) || base === "main.ts" || base === "server.ts";
1201
1501
  }
1202
- #disabledInBrowser(importer, specifier, kind) {
1203
- const map = this.#browserMapOf(path4.dirname(importer));
1204
- if (!map || map.offFiles.size === 0 && map.offNames.size === 0)
1205
- return null;
1206
- if (!specifier.startsWith(".") && !path4.isAbsolute(specifier))
1207
- return map.offNames.has(specifier) ? `${CsrDevPaths.emptyStubPrefix}${specifier}` : null;
1208
- const target = CsrDevPaths.resolveRelative(path4.dirname(importer), specifier, kind);
1209
- 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));
1210
1504
  }
1211
- #hasBrowserMap(dir) {
1212
- 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);
1213
1507
  }
1214
- #browserMapOf(dir) {
1215
- const cached = this.#browserMaps.get(dir);
1216
- if (cached !== undefined)
1217
- return cached;
1218
- const pkgFile = path4.join(dir, "package.json");
1219
- const parent = path4.dirname(dir);
1220
- let map = null;
1221
- if (fs3.existsSync(pkgFile)) {
1222
- try {
1223
- const browser = JSON.parse(fs3.readFileSync(pkgFile, "utf8")).browser;
1224
- if (typeof browser === "object" && browser !== null) {
1225
- const off = Object.entries(browser).filter(([, target]) => target === false).map(([key]) => key);
1226
- const files = off.filter((key) => key.startsWith(".")).map((key) => CsrDevPaths.resolveRelative(dir, key)).filter((file) => !!file);
1227
- map = {
1228
- offFiles: new Set(files.map((file) => CsrDevPaths.realpath(file))),
1229
- offNames: new Set(off.filter((key) => !key.startsWith(".")))
1230
- };
1231
- }
1232
- } catch {}
1233
- } else if (parent !== dir)
1234
- map = this.#browserMapOf(parent);
1235
- this.#browserMaps.set(dir, map);
1236
- 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");
1237
1516
  }
1238
- forget(importer) {
1239
- this.#resolution.delete(importer);
1240
- 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;
1241
1528
  }
1242
- serializeRuntimeResolved() {
1243
- 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";
1244
1534
  }
1245
- serialize() {
1246
- return Object.fromEntries([...this.#resolution].map(([importer, bySpecifier]) => [
1247
- this.#paths.idOf(importer),
1248
- Object.fromEntries([...bySpecifier].filter(([, target]) => CsrDevPaths.isStub(target) || fs3.existsSync(target)).map(([specifier, target]) => [specifier, CsrDevPaths.isStub(target) ? target : this.#paths.idOf(target)]))
1249
- ]));
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);
1250
1551
  }
1251
- #resolveUnknown(importer, specifier, kind) {
1252
- if (specifier.startsWith("node:"))
1253
- return `${CsrDevPaths.stubPrefix}${specifier}`;
1254
- const relative = specifier.startsWith(".") || path4.isAbsolute(specifier);
1255
- const cannotResolve = () => new Error(`[csr-dev] cannot resolve "${specifier}" from ${this.#paths.idOf(importer)}`);
1256
- if (relative) {
1257
- const onDisk = CsrDevPaths.resolveRelative(path4.dirname(importer), specifier, kind) ?? CsrDevResolver.#onDisk(CsrDevPaths.tryResolve(specifier, path4.dirname(importer)));
1258
- if (!onDisk)
1259
- throw cannotResolve();
1260
- return CsrDevPaths.realpath(onDisk);
1261
- }
1262
- const sibling = this.#resolvedBySibling(importer, specifier);
1263
- if (sibling)
1264
- return sibling;
1265
- const resolved = CsrDevPaths.tryResolve(specifier, path4.dirname(importer));
1266
- const moved = resolved !== null && path4.isAbsolute(resolved) && !fs3.existsSync(resolved);
1267
- const installed = resolved === null && CsrDevPaths.installedSince(specifier, path4.dirname(importer), this.#startedAt);
1268
- if (!this.#prepassDone || moved) {
1269
- if (resolved === null && !installed && !CsrDevPaths.isVendorFile(importer))
1270
- throw cannotResolve();
1271
- return null;
1272
- }
1273
- if (!resolved) {
1274
- 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)}`);
1275
1561
  return null;
1276
- throw cannotResolve();
1562
+ });
1563
+ if (moduleIndex)
1564
+ indexPaths.add(moduleIndex);
1277
1565
  }
1278
- if (!path4.isAbsolute(resolved))
1279
- return `${CsrDevPaths.stubPrefix}${specifier}`;
1280
- this.#fallbacks.add(specifier);
1281
- this.#runtimeResolved.set(importer, (this.#runtimeResolved.get(importer) ?? new Set).add(specifier));
1282
- 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 };
1283
1577
  }
1284
- static #onDisk(resolved) {
1285
- 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");
1286
1592
  }
1287
- #resolvedBySibling(importer, specifier) {
1288
- const scope = CsrDevResolver.#packageScopeOf(importer);
1289
- for (const [other, bySpecifier] of this.#resolution) {
1290
- const target = bySpecifier.get(specifier);
1291
- if (!target || other === importer || this.#runtimeResolved.get(other)?.has(specifier))
1292
- continue;
1293
- if (!CsrDevPaths.isStub(target) && !fs3.existsSync(target))
1294
- continue;
1295
- if (CsrDevResolver.#packageScopeOf(other) === scope)
1296
- 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");
1297
1610
  }
1298
- return null;
1299
- }
1300
- #remember(importer, specifier, target) {
1301
- const byImporter = this.#resolution.get(importer) ?? new Map;
1302
- 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");
1303
1614
  }
1304
- #isInlineSpecifier(specifier) {
1305
- 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)
1306
1626
  return false;
1307
- return this.#context.optimizeImports.some((pattern) => {
1308
- const base = CsrDevResolver.#patternBase(pattern);
1309
- return specifier === base || specifier.startsWith(`${base}/`);
1310
- });
1627
+ await mkdir2(dir, { recursive: true });
1628
+ await FileSys2.writeTextAtomic(indexPath, content);
1629
+ return true;
1311
1630
  }
1312
- static #patternBase(pattern) {
1313
- 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));
1314
1637
  }
1315
- static #packageNameOf(file) {
1316
- const marker = `${path4.sep}node_modules${path4.sep}`;
1317
- const index = file.lastIndexOf(marker);
1318
- if (index < 0)
1638
+ async#facetContent(dir) {
1639
+ const entries = await readdir2(dir, { withFileTypes: true }).catch(() => null);
1640
+ if (!entries)
1319
1641
  return null;
1320
- const [scope, name] = file.slice(index + marker.length).split(path4.sep);
1321
- 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);
1322
1645
  }
1323
- static #packageScopeOf(file) {
1324
- const marker = `${path4.sep}node_modules${path4.sep}`;
1325
- const index = file.lastIndexOf(marker);
1326
- if (index < 0)
1327
- return "";
1328
- const [scope, name] = file.slice(index + marker.length).split(path4.sep);
1329
- 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
+ `;
1330
1670
  }
1331
1671
  }
1672
+ var exists = async (file) => stat2(file).then(() => true).catch(() => false);
1673
+ var formatError2 = (err) => err instanceof Error ? err.message : String(err);
1332
1674
 
1333
- // pkgs/@akanjs/devkit/frontendBuild/devBarrelImports.ts
1334
- import path5 from "path";
1335
- class DevBarrelImports {
1336
- #barrels;
1337
- #resolvePackage;
1338
- #analyzer;
1339
- #packages = new Map;
1340
- constructor(barrels, resolvePackage) {
1341
- this.#barrels = [...barrels];
1342
- this.#resolvePackage = resolvePackage;
1343
- 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;
1344
1707
  }
1345
- static async create(app, barrels) {
1346
- if (barrels.length === 0)
1347
- return null;
1348
- return new DevBarrelImports(barrels, await createTsconfigPackageResolver(app));
1708
+ async markBuilding() {
1709
+ await Bun.write(path7.join(this.#outDir, CsrDevArtifactWriter.#buildingMarker), String(process.pid));
1349
1710
  }
1350
- async rewrite(source, importer) {
1351
- const named = this.#barrels.filter((barrel) => source.includes(barrel));
1352
- 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())
1353
1723
  return null;
1354
- const packages = await this.#packagesOf(named);
1355
- const from = path5.dirname(CsrDevPaths.realpath(importer));
1356
- const names = new Map;
1357
- const contents = await rewriteBarrelImports(source, named, this.#analyzer, {
1358
- keepLines: true,
1359
- specifierOf: (subpath) => DevBarrelImports.#relative(subpath, from, packages),
1360
- onImport: (barrel, imported) => names.set(barrel, new Set([...names.get(barrel) ?? [], ...imported]))
1361
- });
1362
- const narrowed = await Promise.all([...names].map(async ([barrel, set]) => {
1363
- const sorted = [...set].sort();
1364
- return [barrel, { names: sorted, hash: await this.fingerprint(barrel, sorted) }];
1365
- }));
1366
- 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
+ ]);
1367
1739
  }
1368
- async fingerprint(barrel, names) {
1369
- const packages = await this.#packagesOf([barrel]);
1370
- const aliased = names.map((name, index) => `${name} as _${index}`).join(", ");
1371
- const narrowed = await rewriteBarrelImports(`import { ${aliased} } from ${JSON.stringify(barrel)};`, [barrel], this.#analyzer, { specifierOf: (subpath) => DevBarrelImports.#fileOf(subpath, packages) ?? subpath });
1372
- 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) };
1373
1748
  }
1374
- async stamps(barrels, idOf) {
1375
- const stamped = await Promise.all([...barrels].map(async (barrel) => {
1376
- const files = await this.#analyzer.filesOf(barrel);
1377
- const read = [...new Set([...files, ...files.map((file) => path5.dirname(file))])];
1378
- const stamp = {
1379
- read: Object.fromEntries(read.map((file) => [idOf(file), CsrDevPaths.mtimeOf(file)])),
1380
- digest: await this.#digest(barrel)
1381
- };
1382
- return [barrel, stamp];
1383
- }));
1384
- return Object.fromEntries(stamped);
1749
+ hasModule(id) {
1750
+ return fs3.existsSync(this.#modulePath(id, ".js"));
1385
1751
  }
1386
- async#digest(barrel) {
1387
- const map = await this.#analyzer.analyze(barrel);
1388
- const packages = await this.#packagesOf([barrel]);
1389
- const files = new Map;
1390
- const fileOf = (subpath) => {
1391
- let file = files.get(subpath);
1392
- if (file === undefined) {
1393
- file = DevBarrelImports.#fileOf(subpath, packages) ?? subpath;
1394
- 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;
1395
1767
  }
1396
- return file;
1397
- };
1398
- const exports = [...map ?? []].map(([name, target]) => [name, target.originalName, !!target.namespace, fileOf(target.subpath)]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1399
- 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;
1400
1778
  }
1401
- async#packagesOf(barrels) {
1402
- 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);
1403
1787
  }
1404
- #packageOf(barrel) {
1405
- let pkg = this.#packages.get(barrel);
1406
- if (!pkg) {
1407
- pkg = this.#resolvePackage(barrel);
1408
- this.#packages.set(barrel, pkg);
1409
- }
1410
- 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}`;
1411
1799
  }
1412
- static #fileOf(subpath, packages) {
1413
- const pkg = packages.find(({ pkgName }) => subpath === pkgName || subpath.startsWith(`${pkgName}/`));
1414
- if (!pkg)
1415
- return null;
1416
- const file = CsrDevPaths.resolveOnDisk(path5.join(pkg.pkgDir, subpath.slice(pkg.pkgName.length)));
1417
- 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);
1418
1803
  }
1419
- static #relative(subpath, from, packages) {
1420
- const file = DevBarrelImports.#fileOf(subpath, packages);
1421
- if (!file)
1422
- return subpath;
1423
- const relative = path5.relative(from, file);
1424
- if (path5.isAbsolute(relative))
1425
- return file.split(path5.sep).join("/");
1426
- const posix = relative.split(path5.sep).join("/");
1427
- 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 });
1428
1812
  }
1429
- }
1430
-
1431
- // pkgs/@akanjs/devkit/frontendBuild/routeClientBuilder.ts
1432
- import { mkdir as mkdir2 } from "fs/promises";
1433
- import path7 from "path";
1434
- import { SSR_DEV_CHUNK, SSR_DEV_ID_PREFIX } from "akanjs/server/hmr/csrDevManifest";
1435
-
1436
- // pkgs/@akanjs/devkit/frontendBuild/clientEntriesBundler.ts
1437
- import fs4 from "fs";
1438
- import path6 from "path";
1439
-
1440
- // pkgs/@akanjs/devkit/frontendBuild/clientBuildTypes.ts
1441
- var CLIENT_BUNDLE_NAMING = {
1442
- entry: "[name]-[hash].[ext]",
1443
- chunk: "chunks/[hash].[ext]",
1444
- asset: "assets/[hash].[ext]"
1445
- };
1446
-
1447
- // pkgs/@akanjs/devkit/frontendBuild/clientEntriesBundler.ts
1448
- class ClientEntriesBundler {
1449
- #app;
1450
- #entries;
1451
- #plugins;
1452
- #external;
1453
- #externalSubpaths;
1454
- #externalAliases;
1455
- #entryExports;
1456
- #command;
1457
- #target;
1458
- #outputSubdir;
1459
- #reactFastRefresh;
1460
- #outdir;
1461
- #servePrefix;
1462
- #manifest = {};
1463
- #ssrManifest = { moduleLoading: null, moduleMap: {} };
1464
- #entryUrlsByAbsPath = new Map;
1465
- #entryOutputAbsByAbsPath = new Map;
1466
- #entryDepsByAbsPath = new Map;
1467
- #entryChunkUrlsByAbsPath = new Map;
1468
- #clientReferenceIdByAbsPath = new Map;
1469
- #opaqueEntries = null;
1470
- #metafileOutputsByAbs = new Map;
1471
- #metafileInputs = {};
1472
- constructor(options) {
1473
- this.#app = options.app;
1474
- this.#entries = options.entries;
1475
- this.#plugins = options.plugins ?? [];
1476
- this.#external = options.external ?? [];
1477
- this.#externalSubpaths = options.externalSubpaths ?? [];
1478
- this.#externalAliases = options.externalAliases ?? {};
1479
- this.#entryExports = options.entryExports ?? {};
1480
- this.#command = options.command ?? "start";
1481
- this.#target = options.target ?? "browser";
1482
- this.#outputSubdir = options.outputSubdir ?? "client";
1483
- this.#reactFastRefresh = options.reactFastRefresh ?? false;
1484
- const artifactDir = `${this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath}/.akan/artifact`;
1485
- this.#outdir = `${artifactDir}/${this.#outputSubdir}`;
1486
- 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;
1487
1820
  }
1488
- async bundle() {
1489
- const akanConfig = await this.#app.getConfig();
1490
- this.#opaqueEntries = await this.#createOpaqueEntryAliases();
1491
- const result = await Bun.build({
1492
- entrypoints: this.#opaqueEntries.entries,
1493
- outdir: this.#outdir,
1494
- splitting: true,
1495
- target: this.#target,
1496
- format: "esm",
1497
- naming: CLIENT_BUNDLE_NAMING,
1498
- metafile: true,
1499
- define: bundleDefine(this.#app, this.#command, "ssr"),
1500
- conditions: bundleConditions(this.#command),
1501
- minify: this.#command === "build",
1502
- optimizeImports: akanConfig.optimizeImports,
1503
- reactFastRefresh: this.#command === "start" && this.#outputSubdir === "client" && this.#reactFastRefresh,
1504
- 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;
1505
1826
  });
1506
- if (!result.success)
1507
- throw new AggregateError(result.logs, "[ClientEntriesBundler] Bun.build failed");
1508
- await this.#rewriteExternalImportSpecifiers(result.outputs);
1509
- const metafile = result.metafile;
1510
- if (!metafile)
1511
- throw new Error("[ClientEntriesBundler] metafile is missing");
1512
- this.#metafileOutputsByAbs = new Map(Object.entries(metafile.outputs).map(([k, v]) => [this.#absFromOutdir(k), v]));
1513
- this.#metafileInputs = metafile.inputs;
1514
- for (const artifact of result.outputs.filter((a) => a.kind === "entry-point"))
1515
- this.#addEntryArtifact(artifact.path);
1516
- this.#assertNarrowedExports();
1517
- return {
1518
- manifest: this.#manifest,
1519
- ssrManifest: this.#ssrManifest,
1520
- entryUrlsByAbsPath: this.#entryUrlsByAbsPath,
1521
- entryOutputAbsByAbsPath: this.#entryOutputAbsByAbsPath,
1522
- entryDepsByAbsPath: this.#entryDepsByAbsPath,
1523
- entryChunkUrlsByAbsPath: this.#entryChunkUrlsByAbsPath,
1524
- externalsByChunkUrl: this.#collectExternalsByChunkUrl(),
1525
- clientReferenceIdByAbsPath: this.#clientReferenceIdByAbsPath
1526
- };
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))));
1527
1829
  }
1528
- async#createOpaqueEntryAliases() {
1529
- const aliasDir = path6.join(this.#app.cwdPath, ".akan", "generated", "client-entry-alias", this.#outputSubdir);
1530
- fs4.mkdirSync(aliasDir, { recursive: true });
1531
- const originalByAlias = new Map;
1532
- const aliasedEntries = await Promise.all(this.#entries.map(async (entry) => {
1533
- const absEntry = path6.resolve(entry);
1534
- const narrowed = this.#entryExports[absEntry];
1535
- const key = `${this.#app.name}
1536
- ${this.#outputSubdir}
1537
- ${absEntry}${narrowed ? `
1538
- narrowed` : ""}`;
1539
- const aliasPath = path6.join(aliasDir, `${Bun.hash(key).toString(36)}.tsx`);
1540
- await Bun.write(aliasPath, narrowed ? ClientEntriesBundler.narrowedAliasSource(absEntry, narrowed) : this.#createOpaqueEntryAliasSource(absEntry, await this.#scanEntryExportNames(absEntry)));
1541
- originalByAlias.set(path6.resolve(aliasPath), absEntry);
1542
- 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
+ `;
1543
1859
  }));
1544
- return { entries: aliasedEntries, originalByAlias, aliasDir };
1545
1860
  }
1546
- #createOpaqueEntryAliasSource(absEntry, exportNames) {
1547
- const entryLit = JSON.stringify(path6.resolve(absEntry));
1548
- if (exportNames.length === 0)
1549
- return `export * from ${entryLit};
1550
- `;
1551
- const namedExports = exportNames.filter((name) => name !== "default");
1552
- const lines = namedExports.length > 0 ? [`export { ${namedExports.join(", ")} } from ${entryLit};`] : [];
1553
- if (exportNames.includes("default"))
1554
- lines.push(`export { default } from ${entryLit};`);
1555
- return `${lines.join(`
1556
- `)}
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
1557
1869
  `;
1870
+ layout.lineCount = CsrDevPaths.lineCount(code);
1871
+ await this.writeJson(`${name}.layout.json`, layout);
1872
+ await this.#writeAtomic(name, code);
1558
1873
  }
1559
- static narrowedAliasSource(absEntry, names) {
1560
- const list = names.length > 0 ? `{ ${names.join(", ")} }` : "{}";
1561
- return `export ${list} from ${JSON.stringify(path6.resolve(absEntry))};
1562
- `;
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);
1563
1879
  }
1564
- #assertNarrowedExports() {
1565
- const missing = Object.entries(this.#entryExports).flatMap(([absEntry, names = []]) => {
1566
- const absOut = this.#entryOutputAbsByAbsPath.get(absEntry);
1567
- if (!absOut)
1568
- return [`${path6.basename(absEntry)}: no output`];
1569
- const exported = new Set(this.#metafileOutputsByAbs.get(absOut)?.exports);
1570
- const absent = names.filter((name) => !exported.has(name));
1571
- return absent.length > 0 ? [`${path6.basename(absEntry)}: ${absent.join(", ")}`] : [];
1880
+ static async#remove(file) {
1881
+ await rm2(file, { force: true }).catch(() => {
1882
+ return;
1572
1883
  });
1573
- if (missing.length > 0)
1574
- throw new Error(`[ClientEntriesBundler] client code imports names its vendor does not export (${missing.join("; ")})`);
1575
1884
  }
1576
- async#scanEntryExportNames(absEntry) {
1577
- 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);
1578
1889
  }
1579
- #createExternalSpecifiersPlugin() {
1580
- const set = new Set(this.#external);
1581
- const subpathSet = new Set(this.#externalSubpaths);
1582
- const aliases = this.#externalAliases;
1583
- const specifiers = [...new Set([...this.#external, ...this.#externalSubpaths, ...Object.keys(aliases)])];
1584
- const escaped = specifiers.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
1585
- const filter = new RegExp(`^(${escaped.join("|")})(?:/.*)?$`);
1586
- return {
1587
- name: "akan-externalize-specifiers",
1588
- setup(build) {
1589
- build.onResolve({ filter }, (args) => {
1590
- const alias = aliases[args.path];
1591
- if (alias)
1592
- return { path: alias, external: true };
1593
- if (!ClientEntriesBundler.#matchesExternalSpecifier(args.path, set, subpathSet))
1594
- return;
1595
- return { path: args.path, external: true };
1596
- });
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);
1597
2040
  }
1598
- };
2041
+ }
1599
2042
  }
1600
- static #matchesExternalSpecifier(specifier, exactExternals, subpathExternals) {
1601
- 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))
1602
2062
  return true;
1603
- for (const external of subpathExternals)
1604
- if (specifier.startsWith(`${external}/`))
1605
- return true;
1606
- 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;
1607
2071
  }
1608
- async#rewriteExternalImportSpecifiers(outputs) {
1609
- if (Object.keys(this.#externalAliases).length === 0)
1610
- return;
1611
- await Promise.all(outputs.filter((output) => output.path.endsWith(".js")).map(async (output) => {
1612
- const source = await Bun.file(output.path).text();
1613
- const rewritten = ClientEntriesBundler.rewriteExternalImportSpecifiers(source, this.#externalAliases);
1614
- if (rewritten !== source)
1615
- await Bun.write(output.path, rewritten);
1616
- }));
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
+ });
1617
2082
  }
1618
- static rewriteExternalImportSpecifiers(source, aliases) {
1619
- let rewritten = source;
1620
- for (const [specifier, alias] of Object.entries(aliases)) {
1621
- if (!alias)
1622
- continue;
1623
- const escaped = specifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1624
- rewritten = rewritten.replace(new RegExp(`(\\bfrom\\s*["'])${escaped}(["'])`, "g"), (_match, prefix, suffix) => {
1625
- return `${prefix}${alias}${suffix}`;
1626
- }).replace(new RegExp(`(\\bimport\\s*["'])${escaped}(["'])`, "g"), (_match, prefix, suffix) => {
1627
- return `${prefix}${alias}${suffix}`;
1628
- });
1629
- }
1630
- 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;
1631
2091
  }
1632
- #toServeUrl(absOutPath) {
1633
- const rel = path6.relative(this.#outdir, absOutPath).split(path6.sep).join("/");
1634
- return `${this.#servePrefix}/${rel}`;
2092
+ #hasBrowserMap(dir) {
2093
+ return this.#browserMapOf(dir) !== null;
1635
2094
  }
1636
- #absFromOutdir(p) {
1637
- 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;
1638
2118
  }
1639
- #absFromEntryPoint(p) {
1640
- if (path6.isAbsolute(p))
1641
- return path6.resolve(p);
1642
- const candidates = [path6.resolve(process.cwd(), p), path6.resolve(this.#app.cwdPath, p)];
1643
- return candidates.find((candidate) => fs4.existsSync(candidate)) ?? candidates[0];
2119
+ forget(importer) {
2120
+ this.#resolution.delete(importer);
2121
+ this.#runtimeResolved.delete(importer);
1644
2122
  }
1645
- #collectChunkUrls(absOutPath, visited = new Set) {
1646
- if (visited.has(absOutPath))
1647
- return [];
1648
- visited.add(absOutPath);
1649
- const info = this.#metafileOutputsByAbs.get(absOutPath);
1650
- if (!info)
1651
- return [this.#toServeUrl(absOutPath)];
1652
- const urls = [this.#toServeUrl(absOutPath)];
1653
- for (const imp of info.imports) {
1654
- if (imp.kind === "dynamic-import")
1655
- continue;
1656
- const absImp = this.#absFromOutdir(imp.path);
1657
- if (!absImp.endsWith(".js"))
1658
- continue;
1659
- urls.push(...this.#collectChunkUrls(absImp, visited));
1660
- }
1661
- return urls;
2123
+ serializeRuntimeResolved() {
2124
+ return Object.fromEntries([...this.#runtimeResolved].filter(([, specifiers]) => specifiers.size > 0).map(([importer, specifiers]) => [this.#paths.idOf(importer), [...specifiers].sort()]));
1662
2125
  }
1663
- #collectExternalsByChunkUrl() {
1664
- const externalsByChunkUrl = new Map;
1665
- if (this.#command !== "build" || this.#target !== "browser")
1666
- return externalsByChunkUrl;
1667
- for (const [absOut, info] of this.#metafileOutputsByAbs) {
1668
- if (!absOut.endsWith(".js"))
1669
- continue;
1670
- const externals = new Set;
1671
- for (const input of Object.keys(info.inputs ?? {}))
1672
- for (const imp of this.#metafileInputs[input]?.imports ?? [])
1673
- if (imp.external && imp.kind !== "dynamic-import" && !/^[./]/.test(imp.path))
1674
- externals.add(imp.path);
1675
- externalsByChunkUrl.set(this.#toServeUrl(absOut), [...externals].sort());
1676
- }
1677
- 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
+ ]));
1678
2131
  }
1679
- #collectClientDeps(absOutPath, visited = new Set) {
1680
- if (visited.has(absOutPath))
1681
- return new Set;
1682
- visited.add(absOutPath);
1683
- const deps = new Set;
1684
- const info = this.#metafileOutputsByAbs.get(absOutPath);
1685
- if (!info)
1686
- return deps;
1687
- if (!this.#opaqueEntries)
1688
- throw new Error("[ClientEntriesBundler] opaque entries are missing");
1689
- for (const input of Object.keys(info.inputs ?? {})) {
1690
- const absInput = this.#absFromEntryPoint(input);
1691
- if (!absInput.includes("node_modules") && !absInput.startsWith(this.#opaqueEntries.aliasDir))
1692
- 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);
1693
2142
  }
1694
- for (const imp of info.imports) {
1695
- if (imp.kind === "dynamic-import")
1696
- continue;
1697
- const absImp = this.#absFromOutdir(imp.path);
1698
- if (!absImp.endsWith(".js"))
1699
- continue;
1700
- for (const dep of this.#collectClientDeps(absImp, visited))
1701
- 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;
1702
2153
  }
1703
- return deps;
1704
- }
1705
- #addEntryArtifact(absOut) {
1706
- if (!this.#opaqueEntries)
1707
- throw new Error("[ClientEntriesBundler] opaque entries are missing");
1708
- const info = this.#metafileOutputsByAbs.get(absOut);
1709
- const buildEntryPointAbs = info?.entryPoint ? this.#absFromEntryPoint(info.entryPoint) : null;
1710
- const entryPointAbs = buildEntryPointAbs ? this.#opaqueEntries.originalByAlias.get(buildEntryPointAbs) ?? buildEntryPointAbs : null;
1711
- if (!entryPointAbs)
1712
- return;
1713
- const chunkUrls = this.#collectChunkUrls(absOut);
1714
- const entryUrl = chunkUrls[0] ?? this.#toServeUrl(absOut);
1715
- this.#entryUrlsByAbsPath.set(entryPointAbs, entryUrl);
1716
- this.#entryOutputAbsByAbsPath.set(entryPointAbs, absOut);
1717
- this.#entryDepsByAbsPath.set(entryPointAbs, [...this.#collectClientDeps(absOut)].sort());
1718
- this.#entryChunkUrlsByAbsPath.set(entryPointAbs, chunkUrls);
1719
- const clientReferenceId = toClientReferencePath(entryPointAbs, this.#app.workspace.workspaceRoot);
1720
- this.#clientReferenceIdByAbsPath.set(entryPointAbs, clientReferenceId);
1721
- const flatChunks = [];
1722
- for (const url of chunkUrls)
1723
- flatChunks.push(url, url);
1724
- const exportNames = info?.exports && info.exports.length > 0 ? info.exports : ["default"];
1725
- const ssrEntriesByName = {};
1726
- for (const name of exportNames) {
1727
- const key = `${clientReferenceId}#${name}`;
1728
- this.#manifest[key] = { id: entryUrl, chunks: flatChunks, name, async: true };
1729
- ssrEntriesByName[name] = { id: absOut, chunks: [absOut, absOut], name, async: true };
2154
+ if (!resolved) {
2155
+ if (installed)
2156
+ return null;
2157
+ throw cannotResolve();
1730
2158
  }
1731
- 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);
1732
2164
  }
1733
- }
1734
-
1735
- // pkgs/@akanjs/devkit/frontendBuild/vendorSpecifiers.ts
1736
- var VENDOR_SPECIFIERS = [
1737
- "react",
1738
- "react-dom",
1739
- "react-dom/client",
1740
- "react/jsx-runtime",
1741
- "react/jsx-dev-runtime",
1742
- "react-refresh/runtime",
1743
- "scheduler",
1744
- "react-server-dom-webpack/client.browser",
1745
- "akanjs/store",
1746
- "akanjs/store/agent",
1747
- "akanjs/base",
1748
- "akanjs/common",
1749
- "akanjs/constant",
1750
- "akanjs/fetch",
1751
- "tailwind-merge"
1752
- ];
1753
- var NARROWABLE_VENDOR_SPECIFIERS = [
1754
- "akanjs/store",
1755
- "akanjs/store/agent",
1756
- "akanjs/base",
1757
- "akanjs/common",
1758
- "akanjs/constant",
1759
- "akanjs/fetch",
1760
- "tailwind-merge"
1761
- ];
1762
-
1763
- // pkgs/@akanjs/devkit/frontendBuild/routeClientBuilder.ts
1764
- var SSR_CLIENT_ALIAS_EXTERNALS = [
1765
- "react",
1766
- "react-dom",
1767
- "react-dom/client",
1768
- "react/jsx-runtime",
1769
- "react/jsx-dev-runtime"
1770
- ];
1771
- var SSR_CLIENT_EXTERNALS = [...SSR_CLIENT_ALIAS_EXTERNALS, "akanjs/fetch"];
1772
-
1773
- class RouteClientBuilder {
1774
- #app;
1775
- #seeds;
1776
- #graphSeeds;
1777
- #knownEntries;
1778
- #command;
1779
- #discovery;
1780
- #entries;
1781
- #browser;
1782
- constructor(options) {
1783
- this.#app = options.app;
1784
- this.#seeds = options.seeds;
1785
- this.#graphSeeds = options.graphSeeds;
1786
- this.#knownEntries = options.knownEntries ?? new Set;
1787
- this.#command = options.command ?? "start";
1788
- this.#discovery = options.discovery;
1789
- this.#entries = options.entries;
1790
- this.#browser = options.browser ?? (this.#command === "start" ? "registry" : "chunks");
2165
+ static #onDisk(resolved) {
2166
+ return resolved && path8.isAbsolute(resolved) && fs4.existsSync(resolved) ? resolved : null;
1791
2167
  }
1792
- async build() {
1793
- const discovered = this.#entries ?? await (await this.#getDiscovery()).discover(this.#seeds);
1794
- if (discovered.every((e) => this.#knownEntries.has(e)))
1795
- return this.#emptyResult(discovered);
1796
- const entries = this.#graphSeeds ? [...new Set([...discovered, ...await (await this.#getDiscovery()).discover(this.#graphSeeds)])].sort() : discovered.filter((e) => !this.#knownEntries.has(e));
1797
- const bootstrapEntries = await this.#createBootstrapEntries(entries);
1798
- const registry = this.#browser === "registry" ? new CsrDevPaths(this.#app.workspace.workspaceRoot) : null;
1799
- const browserBundle = registry ? null : await this.#buildBrowserBundle(bootstrapEntries);
1800
- const ssrBundle = await this.#buildSsrBundle(bootstrapEntries);
1801
- const referenceBundle = browserBundle ?? ssrBundle;
1802
- const acceptedEntries = new Set(entries);
1803
- const routeEntries = new Set(discovered);
1804
- const manifestDelta = {};
1805
- const ssrModuleMap = {};
1806
- const clientDeps = new Set;
1807
- const clientDepsByEntry = {};
1808
- for (const [key, bundleRow] of Object.entries(referenceBundle.manifest)) {
1809
- const manifestEntry = RouteClientBuilder.resolveOriginalManifestEntry(key, bootstrapEntries.originalByBuildEntry, referenceBundle.clientReferenceIdByAbsPath, this.#app.workspace.workspaceRoot);
1810
- if (!manifestEntry)
1811
- continue;
1812
- if (!acceptedEntries.has(manifestEntry.originalEntry))
1813
- continue;
1814
- const row = registry ? RouteClientBuilder.#registryRow(registry, manifestEntry.originalEntry, bundleRow) : bundleRow;
1815
- manifestDelta[manifestEntry.key] = row;
1816
- const ssrOutput = ssrBundle.entryOutputAbsByAbsPath.get(manifestEntry.buildEntry);
1817
- 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))
1818
2173
  continue;
1819
- ssrModuleMap[row.id] ??= {};
1820
- ssrModuleMap[row.id][row.name] = { id: ssrOutput, chunks: [ssrOutput, ssrOutput], name: row.name, async: true };
1821
- }
1822
- for (const entry of bootstrapEntries.buildEntries) {
1823
- const buildEntry = path7.resolve(entry);
1824
- const originalEntry = path7.resolve(bootstrapEntries.originalByBuildEntry.get(buildEntry) ?? buildEntry);
1825
- if (!acceptedEntries.has(originalEntry))
2174
+ if (!CsrDevPaths.isStub(target) && !fs4.existsSync(target))
1826
2175
  continue;
1827
- const deps = new Set([originalEntry]);
1828
- for (const dep of referenceBundle.entryDepsByAbsPath.get(buildEntry) ?? [])
1829
- deps.add(path7.resolve(dep));
1830
- const sortedDeps = [...deps].sort();
1831
- clientDepsByEntry[originalEntry] = sortedDeps;
1832
- if (routeEntries.has(originalEntry))
1833
- for (const dep of sortedDeps)
1834
- clientDeps.add(dep);
2176
+ if (CsrDevResolver.#packageScopeOf(other) === scope)
2177
+ return target;
1835
2178
  }
1836
- return {
1837
- manifestDelta,
1838
- ssrManifestDelta: { moduleLoading: null, moduleMap: ssrModuleMap },
1839
- newEntries: entries.filter((e) => !this.#knownEntries.has(e)),
1840
- discoveredEntries: discovered,
1841
- clientDeps: [...clientDeps].sort(),
1842
- clientDepsByEntry,
1843
- ...registry ? { registryEntries: [...acceptedEntries].sort() } : {},
1844
- ...browserBundle ? { externalsByChunkUrl: Object.fromEntries(browserBundle.externalsByChunkUrl) } : {}
1845
- };
1846
- }
1847
- static #registryRow(paths, entry, row) {
1848
- return {
1849
- id: `${SSR_DEV_ID_PREFIX}${paths.idOf(entry)}`,
1850
- chunks: [SSR_DEV_CHUNK, SSR_DEV_CHUNK],
1851
- name: row.name,
1852
- async: true
1853
- };
2179
+ return null;
1854
2180
  }
1855
- async#getDiscovery() {
1856
- this.#discovery ??= await GraphClientEntryDiscovery.create(this.#app);
1857
- 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));
1858
2184
  }
1859
- #emptyResult(discoveredEntries = []) {
1860
- return {
1861
- manifestDelta: {},
1862
- ssrManifestDelta: { moduleLoading: null, moduleMap: {} },
1863
- newEntries: [],
1864
- discoveredEntries,
1865
- clientDeps: [],
1866
- clientDepsByEntry: {}
1867
- };
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
+ });
1868
2192
  }
1869
- async#buildBrowserBundle(bootstrapEntries) {
1870
- const reactFastRefresh = process.env.AKAN_REACT_FAST_REFRESH !== "0";
1871
- return new ClientEntriesBundler({
1872
- app: this.#app,
1873
- entries: bootstrapEntries.buildEntries,
1874
- plugins: [
1875
- await createBarrelImportsPlugin(this.#app, {
1876
- pipeAfter: reactFastRefresh ? RouteClientBuilder.normalizeNamedDefaultFunctionForFastRefresh : undefined,
1877
- external: VENDOR_SPECIFIERS
1878
- })
1879
- ],
1880
- external: VENDOR_SPECIFIERS,
1881
- command: this.#command,
1882
- reactFastRefresh
1883
- }).bundle();
2193
+ static #patternBase(pattern) {
2194
+ return pattern.endsWith("/*") ? pattern.slice(0, -2) : pattern;
1884
2195
  }
1885
- async#buildSsrBundle(bootstrapEntries) {
1886
- return new ClientEntriesBundler({
1887
- app: this.#app,
1888
- entries: bootstrapEntries.buildEntries,
1889
- plugins: [await createBarrelImportsPlugin(this.#app)],
1890
- ...RouteClientBuilder.resolveSsrClientBundleOptions(this.#command),
1891
- outputSubdir: "client-ssr",
1892
- command: this.#command
1893
- }).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;
1894
2203
  }
1895
- async#createBootstrapEntries(entries) {
1896
- if (!await Bun.file(path7.join(this.#app.cwdPath, "lib", "st.ts")).exists()) {
1897
- return { buildEntries: entries, originalByBuildEntry: new Map };
1898
- }
1899
- const outdir = path7.join(this.#app.cwdPath, ".akan", "generated", "client-entry-bootstrap");
1900
- await mkdir2(outdir, { recursive: true });
1901
- const originalByBuildEntry = new Map;
1902
- const buildEntries = await Promise.all(entries.map(async (entry) => {
1903
- const absEntry = path7.resolve(entry);
1904
- const hash = Bun.hash(`${this.#app.name}
1905
- ${absEntry}`).toString(36);
1906
- const base = path7.basename(absEntry).replace(/[^A-Za-z0-9._-]/g, "_");
1907
- const wrapperEntry = path7.join(outdir, `${base}-${hash}.tsx`);
1908
- const exportNames = await this.#scanExportNames(absEntry);
1909
- await Bun.write(wrapperEntry, RouteClientBuilder.createStoreBootstrapEntrySource({
1910
- appName: this.#app.name,
1911
- originalEntry: absEntry,
1912
- exportNames
1913
- }));
1914
- originalByBuildEntry.set(path7.resolve(wrapperEntry), absEntry);
1915
- return wrapperEntry;
1916
- }));
1917
- 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);
1918
2211
  }
1919
- async#scanExportNames(absEntry) {
1920
- 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 });
1921
2225
  }
1922
- static normalizeNamedDefaultFunctionForFastRefresh(source, { path: filePath } = {}) {
1923
- const declared = RouteClientBuilder.#declaredNamedDefaultFunctions(source, filePath);
1924
- if (declared.length === 0)
2226
+ static async create(app, barrels) {
2227
+ if (barrels.length === 0)
1925
2228
  return null;
1926
- let next = "";
1927
- let cursor = 0;
1928
- for (const { index, text, lineStart, indent, asyncKeyword, name } of declared) {
1929
- next += `${source.slice(cursor, index)}${lineStart}${indent}${asyncKeyword}function ${name}`;
1930
- cursor = index + text.length;
1931
- }
1932
- next += source.slice(cursor);
1933
- return `${next}
1934
- ${declared.map(({ name }) => `export default ${name};`).join(`
1935
- `)}
1936
- `;
2229
+ return new DevBarrelImports(barrels, await createTsconfigPackageResolver(app));
1937
2230
  }
1938
- static #declaredNamedDefaultFunctions(source, filePath) {
1939
- const candidates = [
1940
- ...source.matchAll(/(^|\n)([^\S\n]*)export\s+default\s+(async\s+)?function\s+([A-Za-z_$][\w$]*)(?=\s*(?:<|\())/g)
1941
- ].map((match) => ({
1942
- index: match.index,
1943
- text: match[0],
1944
- lineStart: match[1] ?? "",
1945
- indent: match[2] ?? "",
1946
- asyncKeyword: match[3] ?? "",
1947
- name: match[4] ?? ""
1948
- }));
1949
- if (candidates.length === 0)
1950
- return [];
1951
- const probeName = (idx) => `__akanNamedDefault${idx}`;
1952
- let probe = "";
1953
- let cursor = 0;
1954
- candidates.forEach(({ index, text, lineStart, indent, asyncKeyword }, idx) => {
1955
- probe += `${source.slice(cursor, index)}${lineStart}${indent}export ${asyncKeyword}function ${probeName(idx)}`;
1956
- 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]))
1957
2242
  });
1958
- probe += source.slice(cursor);
1959
- const exported = RouteClientBuilder.#scanExports(probe, filePath);
1960
- return candidates.filter((_, idx) => exported.has(probeName(idx)));
1961
- }
1962
- static #scanExports(source, filePath) {
1963
- try {
1964
- return new Set(new Bun.Transpiler({ loader: filePath ? loaderFor(filePath) : "tsx" }).scan(source).exports);
1965
- } catch {
1966
- return new Set;
1967
- }
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) };
1968
2248
  }
1969
- static resolveSsrClientRuntimeAliases() {
1970
- const serverEntry = RouteClientBuilder.resolveAkanServerEntry();
1971
- 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);
1972
2254
  }
1973
- static resolveSsrClientBundleOptions(command) {
1974
- if (command === "start") {
1975
- return {
1976
- target: "bun",
1977
- external: SSR_CLIENT_EXTERNALS,
1978
- externalSubpaths: ["akanjs/fetch"],
1979
- 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)
1980
2262
  };
1981
- }
1982
- return { target: "bun", external: SSR_CLIENT_ALIAS_EXTERNALS };
2263
+ return [barrel, stamp];
2264
+ }));
2265
+ return Object.fromEntries(stamped);
1983
2266
  }
1984
- static resolveAkanServerEntry() {
1985
- try {
1986
- return Bun.resolveSync("akanjs/server", import.meta.dir);
1987
- } catch {
1988
- return path7.resolve(import.meta.dir, "../../../server/index.ts");
1989
- }
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);
1990
2281
  }
1991
- static createStoreBootstrapEntrySource(args) {
1992
- const originalEntry = JSON.stringify(path7.resolve(args.originalEntry));
1993
- const namedExports = args.exportNames.filter((name) => name !== "default");
1994
- const lines = [
1995
- ...StoreBootstrap.importLines(args.appName),
1996
- ...namedExports.length > 0 ? [`export { ${namedExports.join(", ")} } from ${originalEntry};`] : []
1997
- ];
1998
- if (args.exportNames.includes("default"))
1999
- lines.push(`export { default } from ${originalEntry};`);
2000
- return `${lines.join(`
2001
- `)}
2002
- `;
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);
2003
2284
  }
2004
- static resolveOriginalManifestEntry(manifestKey, originalByBuildEntry, clientReferenceIdByBuildEntry = new Map, workspaceRoot = process.cwd()) {
2005
- const hashIdx = manifestKey.lastIndexOf("#");
2006
- 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)
2007
2296
  return null;
2008
- const buildReferenceId = manifestKey.slice(0, hashIdx);
2009
- const name = manifestKey.slice(hashIdx + 1);
2010
- const buildEntry = [...clientReferenceIdByBuildEntry.entries()].find(([, referenceId]) => referenceId === buildReferenceId)?.[0] ?? buildReferenceId;
2011
- const originalEntry = originalByBuildEntry.get(buildEntry) ?? buildEntry;
2012
- const originalReferenceId = toClientReferencePath(originalEntry, workspaceRoot);
2013
- 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}`;
2014
2309
  }
2015
2310
  }
2016
2311
 
@@ -2133,7 +2428,7 @@ class CsrDevModuleCompiler {
2133
2428
  const tangled = [];
2134
2429
  for (const artifact of result.outputs) {
2135
2430
  if (artifact.kind === "asset") {
2136
- const assetPath = path8.join(this.#outDir, artifact.path);
2431
+ const assetPath = path10.join(this.#outDir, artifact.path);
2137
2432
  await Bun.write(assetPath, artifact);
2138
2433
  this.#assets.add(assetPath);
2139
2434
  continue;
@@ -2143,8 +2438,8 @@ class CsrDevModuleCompiler {
2143
2438
  const meta = outputs[artifact.path];
2144
2439
  if (!meta?.entryPoint)
2145
2440
  throw new Error(`[csr-dev] no entry point recorded for ${artifact.path}`);
2146
- const file = CsrDevPaths.realpath(path8.resolve(meta.entryPoint));
2147
- 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)));
2148
2443
  if (inputs.some((input) => input !== file && this.#resolver.isRegistryModule(input))) {
2149
2444
  tangled.push(file);
2150
2445
  continue;
@@ -2179,7 +2474,7 @@ class CsrDevModuleCompiler {
2179
2474
  const reasons = new Map;
2180
2475
  for (const message of error.errors) {
2181
2476
  const file = message.position?.file;
2182
- if (typeof file !== "string" || !path8.isAbsolute(file))
2477
+ if (typeof file !== "string" || !path10.isAbsolute(file))
2183
2478
  continue;
2184
2479
  const real = CsrDevPaths.realpath(file);
2185
2480
  const at = message.position?.line ? `:${message.position.line}` : "";
@@ -2288,7 +2583,7 @@ class CsrDevModuleCompiler {
2288
2583
  }
2289
2584
  #rebaseSourceMap(text) {
2290
2585
  const map = JSON.parse(text);
2291
- const files = map.sources.map((source) => path8.resolve(source));
2586
+ const files = map.sources.map((source) => path10.resolve(source));
2292
2587
  map.sources = files.map((file) => `/${this.#paths.idOf(file)}`);
2293
2588
  map.sourcesContent = files.map((file, index) => CsrDevPaths.isVendorFile(file) ? null : map.sourcesContent?.[index] ?? null);
2294
2589
  return JSON.stringify(map);
@@ -2353,7 +2648,7 @@ ${preamble}return { ${names.join(", ")} };
2353
2648
 
2354
2649
  // pkgs/@akanjs/devkit/frontendBuild/csrDevPatcher.ts
2355
2650
  import fs5 from "fs";
2356
- import path9 from "path";
2651
+ import path11 from "path";
2357
2652
  import { appGenerationOf as appGenerationOf2, CSR_DEV_MANIFEST_FILE as CSR_DEV_MANIFEST_FILE2 } from "akanjs/server/hmr/csrDevManifest";
2358
2653
  class CsrDevPatcher {
2359
2654
  #bundler;
@@ -2388,7 +2683,7 @@ class CsrDevPatcher {
2388
2683
  return this.#handBack("the dev bundle config changed", generation, context);
2389
2684
  const metadataFile = changedFiles.find((file) => this.#bundler.isMetadataFile(file));
2390
2685
  if (metadataFile)
2391
- return this.#handBack(`${path9.basename(metadataFile)} changed`, generation, context);
2686
+ return this.#handBack(`${path11.basename(metadataFile)} changed`, generation, context);
2392
2687
  if (!resident && state.graph.metadata !== await this.#bundler.metadataFingerprint())
2393
2688
  return this.#handBack("signal or dictionary metadata changed since the registry was built", generation, context);
2394
2689
  this.#state = this.#resident ? state : null;
@@ -2490,7 +2785,7 @@ class CsrDevPatcher {
2490
2785
  CsrDevPatcher.#remember(code, compiled);
2491
2786
  const changedIds = compiled.filter((module) => !module.vendor).map((module) => module.id);
2492
2787
  const constantId = changedIds.find((id) => id.endsWith(".constant.ts"));
2493
- 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;
2494
2789
  if (compiled.length === 0 && !reason) {
2495
2790
  await writer.writeJson("graph.json", graph);
2496
2791
  await writer.forgetModules(forgotten);
@@ -2605,9 +2900,9 @@ class CsrDevPatcher {
2605
2900
  const messages = error instanceof AggregateError ? error.errors : [];
2606
2901
  const named = messages.flatMap((message) => {
2607
2902
  const text = String(message.message ?? "");
2608
- const bases = [process.cwd(), ...failing.map((file) => path9.dirname(file))];
2903
+ const bases = [process.cwd(), ...failing.map((file) => path11.dirname(file))];
2609
2904
  return [...text.matchAll(/"([^"\n]+)"/g)].flatMap(([, quoted = ""]) => {
2610
- 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));
2611
2906
  return found ? [CsrDevPaths.realpath(found)] : [];
2612
2907
  });
2613
2908
  });
@@ -2615,7 +2910,7 @@ class CsrDevPatcher {
2615
2910
  }
2616
2911
  static #failingFiles(error) {
2617
2912
  const messages = error instanceof AggregateError ? error.errors : [];
2618
- 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));
2619
2914
  }
2620
2915
  async#carriedRoots(graph, changed, present) {
2621
2916
  const { paths } = this.#bundler;
@@ -2744,16 +3039,16 @@ class CsrDevPatcher {
2744
3039
  #shadowedImporters(graph, changedFiles) {
2745
3040
  const { paths } = this.#bundler;
2746
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) => {
2747
- const stem = file.slice(0, file.length - path9.extname(file).length);
2748
- 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];
2749
3044
  }));
2750
3045
  if (bases.size === 0)
2751
3046
  return [];
2752
3047
  return Object.entries(graph.resolution).filter(([importer, bySpecifier]) => {
2753
3048
  if (!graph.modules[importer] || graph.modules[importer]?.vendor)
2754
3049
  return false;
2755
- const dir = path9.dirname(paths.fileOf(importer));
2756
- 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)));
2757
3052
  }).map(([importer]) => importer);
2758
3053
  }
2759
3054
  #forgetDeletedModules({ graph, code }, present) {
@@ -2769,7 +3064,7 @@ class CsrDevPatcher {
2769
3064
 
2770
3065
  // pkgs/@akanjs/devkit/frontendBuild/registryMetadataFingerprint.ts
2771
3066
  import fs6 from "fs";
2772
- import path10 from "path";
3067
+ import path12 from "path";
2773
3068
 
2774
3069
  class RegistryMetadataFingerprint {
2775
3070
  static #sources = new Bun.Glob("**/*.{signal,dictionary}.ts");
@@ -2777,12 +3072,12 @@ class RegistryMetadataFingerprint {
2777
3072
  static async of(roots, isMetadataFile) {
2778
3073
  const stamps = [];
2779
3074
  for (const root of new Set(roots)) {
2780
- const libDir = path10.join(root, "lib");
3075
+ const libDir = path12.join(root, "lib");
2781
3076
  if (!fs6.existsSync(libDir))
2782
3077
  continue;
2783
- const files = RegistryMetadataFingerprint.#libFiles.map((name) => path10.join(libDir, name));
3078
+ const files = RegistryMetadataFingerprint.#libFiles.map((name) => path12.join(libDir, name));
2784
3079
  for await (const relative of RegistryMetadataFingerprint.#sources.scan({ cwd: libDir, onlyFiles: true }))
2785
- files.push(path10.join(libDir, relative));
3080
+ files.push(path12.join(libDir, relative));
2786
3081
  for (const file of files) {
2787
3082
  if (!isMetadataFile(file))
2788
3083
  continue;
@@ -2808,8 +3103,8 @@ class DevRegistryBundler {
2808
3103
  this.app = app;
2809
3104
  this.routePrefix = routePrefix;
2810
3105
  this.paths = new CsrDevPaths(app.workspace.workspaceRoot);
2811
- this.outDir = path11.join(app.cwdPath, ".akan/artifact", dirName);
2812
- 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);
2813
3108
  this.writer = new CsrDevArtifactWriter(this.outDir, { routePrefix, library });
2814
3109
  }
2815
3110
  async update(changedFiles = [], options = {}) {
@@ -2847,10 +3142,10 @@ class DevRegistryBundler {
2847
3142
  return isAkanRuntimeMetadataFile(file);
2848
3143
  }
2849
3144
  async metadataFingerprint() {
2850
- const libsContainer = path11.resolve(this.app.workspace.workspaceRoot, "libs");
3145
+ const libsContainer = path13.resolve(this.app.workspace.workspaceRoot, "libs");
2851
3146
  const roots = await new WatchRootResolver(this.app).resolve();
2852
- const libRoots = roots.includes(libsContainer) ? fs7.readdirSync(libsContainer).map((name) => path11.join(libsContainer, name)) : roots.filter((root) => path11.dirname(root) === libsContainer);
2853
- 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));
2854
3149
  }
2855
3150
  async fullBuild(context, generation, reason) {
2856
3151
  const metadata = await this.metadataFingerprint();
@@ -2954,11 +3249,11 @@ class CsrDevBundler extends DevRegistryBundler {
2954
3249
  };
2955
3250
  }
2956
3251
  async writeEntries(context) {
2957
- await mkdir3(this.entryDir, { recursive: true });
3252
+ await mkdir4(this.entryDir, { recursive: true });
2958
3253
  const files = {};
2959
3254
  const changed = [];
2960
3255
  for (const basePath of context.htmlBasePaths) {
2961
- const file = path12.join(this.entryDir, CsrEntryFiles.entryFilename(basePath));
3256
+ const file = path14.join(this.entryDir, CsrEntryFiles.entryFilename(basePath));
2962
3257
  const entryPages = CsrEntryFiles.pageEntriesForBasePath(context.pageEntries, basePath, context.basePaths);
2963
3258
  const generator = new PagesEntrySourceGenerator(entryPages, {
2964
3259
  isAsyncDefault: (moduleAbsPath) => this.#isAsyncDefault(moduleAbsPath)
@@ -2997,7 +3292,7 @@ ${hot}`;
2997
3292
  }
2998
3293
  #resolveRefreshRuntime() {
2999
3294
  const akanWebkit = CsrDevPaths.tryResolve("akanjs/webkit", this.app.cwdPath);
3000
- 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))] : []];
3001
3296
  for (const base of bases) {
3002
3297
  const resolved = CsrDevPaths.tryResolve("react-refresh/runtime", base);
3003
3298
  if (resolved)
@@ -3007,326 +3302,6 @@ ${hot}`;
3007
3302
  }
3008
3303
  }
3009
3304
 
3010
- // pkgs/@akanjs/devkit/frontendBuild/devChangePlanner.ts
3011
- import path13 from "path";
3012
- var CONFIG_BASENAMES = new Set(["akan.config.ts", "bunfig.toml", "tsconfig.json", "package.json"]);
3013
- var BARREL_FACETS = new Set(["common", "srvkit", "ui", "webkit", "plugin"]);
3014
- var CLIENT_SUFFIXES = [".Template.tsx", ".Unit.tsx", ".Util.tsx", ".View.tsx", ".Zone.tsx", ".store.ts"];
3015
- var SHARED_SUFFIXES = [".constant.ts", ".dictionary.ts", ".signal.ts"];
3016
- var SERVER_SUFFIXES = [".service.ts", ".document.ts"];
3017
- var RUNTIME_METADATA_BASENAMES = new Set(["dict.ts", "sig.ts", "useClient.ts", "useServer.ts"]);
3018
-
3019
- class DevChangePlanner {
3020
- #workspaceRoot;
3021
- constructor({ workspaceRoot }) {
3022
- this.#workspaceRoot = path13.resolve(workspaceRoot);
3023
- }
3024
- plan({ generation, files, kinds, generatedFiles = [] }) {
3025
- const fileList = uniqueResolved([...files, ...generatedFiles]);
3026
- const generatedSet = new Set(generatedFiles.map((file) => path13.resolve(file)));
3027
- const kindSet = new Set(kinds);
3028
- const roles = new Set;
3029
- const actions = new Set;
3030
- const reasonByFile = {};
3031
- for (const kind of kindSet) {
3032
- if (kind === "css") {
3033
- roles.add("css");
3034
- actions.add("rebuild-css");
3035
- }
3036
- if (kind === "config") {
3037
- roles.add("config");
3038
- actions.add("restart-dev-host");
3039
- }
3040
- }
3041
- for (const file of fileList) {
3042
- const reasons = new Set;
3043
- const fileRoles = this.#rolesForFile(file, { isGenerated: generatedSet.has(path13.resolve(file)), reasons });
3044
- for (const role of fileRoles)
3045
- roles.add(role);
3046
- if (reasons.has("runtime-metadata"))
3047
- actions.add("restart-builder");
3048
- if (reasons.size > 0)
3049
- reasonByFile[path13.resolve(file)] = [...reasons].sort();
3050
- }
3051
- if (roles.has("barrel"))
3052
- actions.add("sync-generated");
3053
- if (roles.has("server") || roles.has("shared"))
3054
- actions.add("restart-backend");
3055
- if (roles.has("client") || roles.has("shared"))
3056
- actions.add("rebuild-client");
3057
- if (roles.has("css"))
3058
- actions.add("rebuild-css");
3059
- return {
3060
- generation,
3061
- files: fileList,
3062
- generatedFiles: uniqueResolved(generatedFiles),
3063
- roles: [...roles].sort(),
3064
- actions: [...actions].sort(),
3065
- reasonByFile
3066
- };
3067
- }
3068
- #rolesForFile(file, { isGenerated, reasons }) {
3069
- const roles = new Set;
3070
- const abs = path13.resolve(file);
3071
- const base = path13.basename(abs);
3072
- const ext = path13.extname(abs).toLowerCase();
3073
- const isSource = SOURCE_EXTS.has(ext);
3074
- const rel = path13.relative(this.#workspaceRoot, abs);
3075
- const parts = rel.split(path13.sep).filter(Boolean);
3076
- if (CONFIG_BASENAMES.has(base)) {
3077
- roles.add("config");
3078
- reasons.add("config-file");
3079
- }
3080
- if (ext === ".css") {
3081
- roles.add("css");
3082
- reasons.add("css-file");
3083
- }
3084
- if (isGenerated || isSource && this.#isBarrelFacetChild(parts)) {
3085
- roles.add("barrel");
3086
- reasons.add(isGenerated ? "generated-index" : "barrel-facet-child");
3087
- }
3088
- if (isSource && this.#isServerBiased(base, parts)) {
3089
- roles.add("server");
3090
- reasons.add("server-path");
3091
- }
3092
- if (isSource && this.#isClientBiased(base, parts)) {
3093
- roles.add("client");
3094
- reasons.add("client-path");
3095
- }
3096
- if (isSource && this.#isSharedBiased(base, parts)) {
3097
- roles.add("shared");
3098
- reasons.add("shared-path");
3099
- }
3100
- if (isSource && this.#isRuntimeMetadataFile(parts, base)) {
3101
- reasons.add("runtime-metadata");
3102
- }
3103
- if (roles.has("server") && roles.has("client")) {
3104
- roles.delete("server");
3105
- roles.delete("client");
3106
- roles.add("shared");
3107
- reasons.add("server-client-overlap");
3108
- }
3109
- if (roles.size === 0 && SOURCE_EXTS.has(ext) && this.#isWorkspaceSource(rel)) {
3110
- roles.add("shared");
3111
- reasons.add("workspace-source-fallback");
3112
- }
3113
- return roles;
3114
- }
3115
- #isServerBiased(base, parts) {
3116
- return parts.includes("srvkit") || SERVER_SUFFIXES.some((suffix) => base.endsWith(suffix)) || base === "main.ts" || base === "server.ts";
3117
- }
3118
- #isClientBiased(base, parts) {
3119
- return parts.includes("ui") || parts.includes("webkit") || parts.includes("page") || CLIENT_SUFFIXES.some((suffix) => base.endsWith(suffix));
3120
- }
3121
- #isSharedBiased(base, parts) {
3122
- return parts.includes("common") || SHARED_SUFFIXES.some((suffix) => base.endsWith(suffix)) || RUNTIME_METADATA_BASENAMES.has(base);
3123
- }
3124
- #isRuntimeMetadataFile(parts, base) {
3125
- const parent = parts.at(-2);
3126
- if (parent === "lib" && RUNTIME_METADATA_BASENAMES.has(base))
3127
- return true;
3128
- const libIndex = parts.lastIndexOf("lib");
3129
- if (libIndex < 0 || parts.length <= libIndex + 1)
3130
- return false;
3131
- return base.endsWith(".dictionary.ts") || base.endsWith(".signal.ts");
3132
- }
3133
- #isBarrelFacetChild(parts) {
3134
- if (parts.length < 4)
3135
- return false;
3136
- const [scope, , facet, child] = parts;
3137
- if (scope !== "apps" && scope !== "libs")
3138
- return false;
3139
- if (!facet || !BARREL_FACETS.has(facet))
3140
- return false;
3141
- if (!child || child.startsWith(".") || child === "index.ts" || child === "index.tsx")
3142
- return false;
3143
- return true;
3144
- }
3145
- #isWorkspaceSource(rel) {
3146
- if (!rel || rel.startsWith("..") || path13.isAbsolute(rel))
3147
- return false;
3148
- const [scope] = rel.split(path13.sep);
3149
- return scope === "apps" || scope === "libs" || scope === "pkgs";
3150
- }
3151
- }
3152
- var uniqueResolved = (files) => [...new Set(files.map((file) => path13.resolve(file)))].sort();
3153
-
3154
- // pkgs/@akanjs/devkit/frontendBuild/devGeneratedIndexSync.ts
3155
- import { mkdir as mkdir4, readdir as readdir3, readFile as readFile2, rm as rm2, stat as stat2 } from "fs/promises";
3156
- import path14 from "path";
3157
- import { capitalize } from "akanjs/common";
3158
- var BARREL_FACETS2 = new Set(["common", "srvkit", "ui", "webkit", "plugin"]);
3159
- var FACET_SOURCE_FILE_RE = /\.(ts|tsx)$/;
3160
- var FACET_EXCLUDED_FILE_RE = /(^index\.tsx?$|\.d\.ts$|\.(test|spec)\.(ts|tsx)$|\.css$|\.scss$|\.sass$)/;
3161
- var FACET_PASCAL_CASE_RE = /^[A-Z][A-Za-z0-9]*$/;
3162
- var FACET_CAMEL_CASE_RE = /^[a-z][A-Za-z0-9]*$/;
3163
- var MODULE_UI_TYPES = ["Template", "Unit", "Util", "View", "Zone"];
3164
- var SERVICE_UI_TYPES = ["Util", "Zone"];
3165
- var SCALAR_UI_TYPES = ["Template", "Unit"];
3166
-
3167
- class DevGeneratedIndexSync {
3168
- #workspaceRoot;
3169
- constructor({ workspaceRoot }) {
3170
- this.#workspaceRoot = path14.resolve(workspaceRoot);
3171
- }
3172
- async syncForBatch(files) {
3173
- const indexPaths = new Set;
3174
- const errors = [];
3175
- for (const file of files) {
3176
- const facetIndex = this.#facetIndexFor(file);
3177
- if (facetIndex)
3178
- indexPaths.add(facetIndex);
3179
- const moduleIndex = await this.#moduleIndexForDirectoryEvent(file).catch((err) => {
3180
- errors.push(`[generated-index] module detection failed for ${file}: ${formatError2(err)}`);
3181
- return null;
3182
- });
3183
- if (moduleIndex)
3184
- indexPaths.add(moduleIndex);
3185
- }
3186
- const changedFiles = [];
3187
- for (const indexPath of [...indexPaths].sort()) {
3188
- try {
3189
- const changed = await this.#syncIndex(indexPath);
3190
- if (changed)
3191
- changedFiles.push(indexPath);
3192
- } catch (err) {
3193
- errors.push(`[generated-index] sync failed for ${indexPath}: ${formatError2(err)}`);
3194
- }
3195
- }
3196
- return { changedFiles, errors };
3197
- }
3198
- #facetIndexFor(file) {
3199
- const abs = path14.resolve(file);
3200
- const rel = path14.relative(this.#workspaceRoot, abs);
3201
- if (rel.startsWith("..") || path14.isAbsolute(rel))
3202
- return null;
3203
- const parts = rel.split(path14.sep).filter(Boolean);
3204
- if (parts.length < 4)
3205
- return null;
3206
- const [scope, project, facet, child] = parts;
3207
- if (scope !== "apps" && scope !== "libs" || !project || !facet || !BARREL_FACETS2.has(facet))
3208
- return null;
3209
- if (!child || child.startsWith(".") || child === "index.ts" || child === "index.tsx")
3210
- return null;
3211
- return path14.join(this.#workspaceRoot, scope, project, facet, "index.ts");
3212
- }
3213
- async#moduleIndexForDirectoryEvent(file) {
3214
- const abs = path14.resolve(file);
3215
- const rel = path14.relative(this.#workspaceRoot, abs);
3216
- if (rel.startsWith("..") || path14.isAbsolute(rel))
3217
- return null;
3218
- const parts = rel.split(path14.sep).filter(Boolean);
3219
- if (parts.length !== 4 && parts.length !== 5)
3220
- return null;
3221
- const [scope, project, libSegment, moduleSegment, scalarSegment] = parts;
3222
- if (scope !== "apps" && scope !== "libs" || !project || libSegment !== "lib")
3223
- return null;
3224
- const isExistingDirectory = await stat2(abs).then((s) => s.isDirectory()).catch(() => false);
3225
- const looksLikeDeletedDirectory = !path14.extname(abs);
3226
- if (!isExistingDirectory && !looksLikeDeletedDirectory)
3227
- return null;
3228
- if (moduleSegment === "__scalar" && scalarSegment) {
3229
- return path14.join(this.#workspaceRoot, scope, project, "lib", "__scalar", scalarSegment, "index.ts");
3230
- }
3231
- if (!moduleSegment || moduleSegment === "__scalar")
3232
- return null;
3233
- return path14.join(this.#workspaceRoot, scope, project, "lib", moduleSegment, "index.ts");
3234
- }
3235
- async#syncIndex(indexPath) {
3236
- const dir = path14.dirname(indexPath);
3237
- const content = await this.#contentForIndex(indexPath);
3238
- if (content === null) {
3239
- if (!await exists(indexPath))
3240
- return false;
3241
- await rm2(indexPath, { force: true });
3242
- return true;
3243
- }
3244
- const current = await readFile2(indexPath, "utf8").catch(() => null);
3245
- if (current === content)
3246
- return false;
3247
- await mkdir4(dir, { recursive: true });
3248
- await FileSys2.writeTextAtomic(indexPath, content);
3249
- return true;
3250
- }
3251
- async#contentForIndex(indexPath) {
3252
- const parts = path14.relative(this.#workspaceRoot, indexPath).split(path14.sep).filter(Boolean);
3253
- const facet = parts.at(-2);
3254
- if (facet && BARREL_FACETS2.has(facet))
3255
- return this.#facetContent(path14.dirname(indexPath));
3256
- return this.#moduleContent(path14.dirname(indexPath));
3257
- }
3258
- async#facetContent(dir) {
3259
- const nameCasePattern = path14.basename(dir) === "ui" ? FACET_PASCAL_CASE_RE : FACET_CAMEL_CASE_RE;
3260
- const entries = await readdir3(dir, { withFileTypes: true }).catch(() => null);
3261
- if (!entries)
3262
- return null;
3263
- const exportNames = entries.flatMap((entry) => {
3264
- const name = entry.name;
3265
- if (name.startsWith("."))
3266
- return [];
3267
- if (entry.isDirectory())
3268
- return nameCasePattern.test(name) ? [name] : [];
3269
- if (!entry.isFile())
3270
- return [];
3271
- if (!FACET_SOURCE_FILE_RE.test(name) || FACET_EXCLUDED_FILE_RE.test(name))
3272
- return [];
3273
- const exportName = name.replace(FACET_SOURCE_FILE_RE, "");
3274
- return nameCasePattern.test(exportName) ? [exportName] : [];
3275
- }).sort(compareExportNames);
3276
- if (exportNames.length === 0)
3277
- return `export {};
3278
- `;
3279
- return `${exportNames.map((name) => `export * from "./${name}";`).join(`
3280
- `)}
3281
- `;
3282
- }
3283
- async#moduleContent(dir) {
3284
- const rel = path14.relative(this.#workspaceRoot, dir);
3285
- const parts = rel.split(path14.sep).filter(Boolean);
3286
- const moduleSegment = parts.at(-1);
3287
- if (!moduleSegment)
3288
- return null;
3289
- const isScalar = parts.at(-2) === "__scalar";
3290
- const rawModel = moduleSegment.startsWith("_") ? moduleSegment.slice(1) : moduleSegment;
3291
- if (!rawModel)
3292
- return null;
3293
- const modelName = capitalize(rawModel);
3294
- const allowedTypes = isScalar ? SCALAR_UI_TYPES : moduleSegment.startsWith("_") ? SERVICE_UI_TYPES : MODULE_UI_TYPES;
3295
- const fileTypes = [];
3296
- for (const type of allowedTypes) {
3297
- if (await exists(path14.join(dir, `${modelName}.${type}.tsx`)))
3298
- fileTypes.push(type);
3299
- }
3300
- if (fileTypes.length === 0)
3301
- return null;
3302
- return `${fileTypes.map((type) => `import * as ${type} from "./${modelName}.${type}";`).join(`
3303
- `)}
3304
-
3305
- export const ${modelName} = { ${fileTypes.join(", ")} };
3306
- `;
3307
- }
3308
- }
3309
- var letterRankOf = (char) => char.toLowerCase().charCodeAt(0) * 2 + (char === char.toLowerCase() ? 1 : 0);
3310
- var digitRunAt = (name, idx) => /^\d+/.exec(name.slice(idx))?.[0] ?? "";
3311
- var compareExportNames = (a, b) => {
3312
- for (let idx = 0;idx < a.length && idx < b.length; ) {
3313
- const [runA, runB] = [digitRunAt(a, idx), digitRunAt(b, idx)];
3314
- if (runA && runB && runA !== runB)
3315
- return runA.length - runB.length || (runA < runB ? -1 : 1);
3316
- if (runA && runB)
3317
- idx += runA.length;
3318
- else if (runA || runB)
3319
- return runA ? -1 : 1;
3320
- else if (a.charAt(idx) !== b.charAt(idx))
3321
- return letterRankOf(a.charAt(idx)) - letterRankOf(b.charAt(idx));
3322
- else
3323
- idx++;
3324
- }
3325
- return a.length - b.length;
3326
- };
3327
- var exists = async (file) => stat2(file).then(() => true).catch(() => false);
3328
- var formatError2 = (err) => err instanceof Error ? err.message : String(err);
3329
-
3330
3305
  // pkgs/@akanjs/devkit/frontendBuild/ssrDevBundler.ts
3331
3306
  import { mkdir as mkdir5 } from "fs/promises";
3332
3307
  import path16 from "path";