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