@akanjs/devkit 3.3.0-rc.38 → 3.3.0-rc.39
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/CHANGELOG.md +10 -0
- package/frontendBuild/allRoutesBuilder.ts +7 -2
- package/frontendBuild/buildRouteClient.test.ts +65 -0
- package/frontendBuild/clientBuildTypes.ts +11 -0
- package/frontendBuild/clientEntriesBundler.ts +21 -11
- package/frontendBuild/clientEntryDiscovery.test.ts +20 -0
- package/frontendBuild/clientEntryDiscovery.ts +10 -2
- package/frontendBuild/renderedEntries.ts +25 -10
- package/frontendBuild/routeClientBuilder.ts +65 -27
- package/frontendBuild/routeModulePreloads.test.ts +32 -0
- package/frontendBuild/routeModulePreloads.ts +20 -11
- package/frontendBuild/routeRuntimeCheck.test.ts +23 -0
- package/frontendBuild/routeRuntimeCheck.ts +10 -3
- package/package.json +3 -3
- package/transforms/barrelImportsPlugin.ts +56 -40
- package/transforms/exportReach.ts +4 -0
- package/transforms/moduleParts.test.ts +225 -0
- package/transforms/moduleParts.ts +418 -0
- package/transforms/partImports.test.ts +76 -0
- package/transforms/partImports.ts +110 -0
- package/transforms/partModules.test.ts +187 -0
- package/transforms/partModules.ts +90 -0
- package/transforms/partPurity.ts +124 -0
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { ExportReach } from "./exportReach";
|
|
3
|
+
import { ObjectModule } from "./objectModule";
|
|
4
|
+
import { PartPurity } from "./partPurity";
|
|
5
|
+
|
|
6
|
+
interface Unit {
|
|
7
|
+
at: number;
|
|
8
|
+
texts: string[];
|
|
9
|
+
declares: string[];
|
|
10
|
+
reads: Set<string>;
|
|
11
|
+
pure: boolean;
|
|
12
|
+
publics: string[];
|
|
13
|
+
listed: string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface ValueImport {
|
|
17
|
+
from: string;
|
|
18
|
+
bare: boolean;
|
|
19
|
+
defaultName?: string;
|
|
20
|
+
namespace?: string;
|
|
21
|
+
named: { local: string; text: string }[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface Part {
|
|
25
|
+
id: string;
|
|
26
|
+
units: Unit[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const REST = "rest";
|
|
30
|
+
const SHARED = "__akanPart_";
|
|
31
|
+
const MACRO_ATTRIBUTE = /with\s*\{\s*type\s*:\s*["']macro["']\s*\}/;
|
|
32
|
+
|
|
33
|
+
//* One source file as several modules, so a bundler placing whole modules can load one export without the others.
|
|
34
|
+
//* A top-level declaration that only builds a value is a part, with the declarations it alone reads and the ones it
|
|
35
|
+
//* is in a cycle with. Every other statement, and what those read, is the `rest` part each part imports, so what the
|
|
36
|
+
//* file does when it loads still happens before any of its exports is used. Names are matched by text, so a part can
|
|
37
|
+
//* import more than it reads, never less.
|
|
38
|
+
export class ModuleParts {
|
|
39
|
+
static readonly query = "?akan-part=";
|
|
40
|
+
static readonly specifier = /\?akan-part=([\w$]+)$/;
|
|
41
|
+
|
|
42
|
+
//? Dropped once the parts are placed: a build keeps the parts of every file it loads, and a syntax tree is large.
|
|
43
|
+
#tree: ts.SourceFile | null;
|
|
44
|
+
readonly #directives: string[] = [];
|
|
45
|
+
readonly #types: string[] = [];
|
|
46
|
+
readonly #typeNames = new Set<string>();
|
|
47
|
+
readonly #declaredTypes = new Set<string>();
|
|
48
|
+
readonly #imports: ValueImport[] = [];
|
|
49
|
+
readonly #importLocals = new Set<string>();
|
|
50
|
+
readonly #units: Unit[] = [];
|
|
51
|
+
readonly #ownerOf = new Map<string, Unit>();
|
|
52
|
+
readonly #lists: { local: string; exported: string }[] = [];
|
|
53
|
+
readonly #purity = new PartPurity();
|
|
54
|
+
#overloads: string[] = [];
|
|
55
|
+
#parts: Part[] = [];
|
|
56
|
+
#partOfLocal = new Map<string, string>();
|
|
57
|
+
#partOfPublic = new Map<string, string>();
|
|
58
|
+
#lent = new Set<string>();
|
|
59
|
+
|
|
60
|
+
private constructor(sourceFile: ts.SourceFile) {
|
|
61
|
+
this.#tree = sourceFile;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
get #sourceFile(): ts.SourceFile {
|
|
65
|
+
if (!this.#tree) throw new Error("[akan] a module's parts are read from its source once");
|
|
66
|
+
return this.#tree;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
//? null: the file stays one module (a shape this cannot place, or nothing to gain from parts).
|
|
70
|
+
static read(source: string, file: string): ModuleParts | null {
|
|
71
|
+
if (MACRO_ATTRIBUTE.test(source) || source.includes(SHARED)) return null;
|
|
72
|
+
const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ObjectModule.scriptKindOf(file));
|
|
73
|
+
const parts = new ModuleParts(sourceFile);
|
|
74
|
+
let prologue = true;
|
|
75
|
+
for (const statement of sourceFile.statements) {
|
|
76
|
+
if (prologue && ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression)) {
|
|
77
|
+
parts.#directives.push(statement.getText(sourceFile));
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
prologue = false;
|
|
81
|
+
if (!parts.#collect(statement)) return null;
|
|
82
|
+
}
|
|
83
|
+
const placed = parts.#place();
|
|
84
|
+
parts.#tree = null;
|
|
85
|
+
return placed ? parts : null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
get ids(): string[] {
|
|
89
|
+
return this.#parts.map(({ id }) => id);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
get exports(): string[] {
|
|
93
|
+
return [...this.#partOfPublic.keys()];
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
partOf(exported: string): string | null {
|
|
97
|
+
return this.#partOfPublic.get(exported) ?? null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
isType(exported: string): boolean {
|
|
101
|
+
return this.#typeNames.has(exported);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
facade(self: string): string {
|
|
105
|
+
const lines = [...this.#directives];
|
|
106
|
+
for (const { id } of this.#parts) {
|
|
107
|
+
const names = [...this.#partOfPublic].filter(([, part]) => part === id).map(([name]) => name);
|
|
108
|
+
if (names.length) lines.push(`export { ${names.join(", ")} } from ${ModuleParts.#from(self, id)};`);
|
|
109
|
+
}
|
|
110
|
+
return `${lines.join("\n")}\n`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
sourceOf(id: string, self: string): string | null {
|
|
114
|
+
const part = this.#parts.find((candidate) => candidate.id === id);
|
|
115
|
+
if (!part) return null;
|
|
116
|
+
const reads = new Set(part.units.flatMap((unit) => [...unit.reads]));
|
|
117
|
+
const own = new Set(part.units.flatMap((unit) => unit.declares));
|
|
118
|
+
const lines = [...this.#directives];
|
|
119
|
+
if (id !== REST && this.#parts.some((candidate) => candidate.id === REST))
|
|
120
|
+
lines.push(`import ${ModuleParts.#from(self, REST)};`);
|
|
121
|
+
for (const imported of this.#imports) {
|
|
122
|
+
const line = ModuleParts.#importOf(imported, reads, id === REST);
|
|
123
|
+
if (line) lines.push(line);
|
|
124
|
+
}
|
|
125
|
+
const borrowed = new Map<string, string[]>();
|
|
126
|
+
for (const name of reads) {
|
|
127
|
+
const from = this.#partOfLocal.get(name);
|
|
128
|
+
if (from && from !== id && !own.has(name)) borrowed.set(from, [...(borrowed.get(from) ?? []), name]);
|
|
129
|
+
}
|
|
130
|
+
for (const [from, names] of borrowed)
|
|
131
|
+
lines.push(
|
|
132
|
+
`import { ${names.map((name) => `${SHARED}${name} as ${name}`).join(", ")} } from ${ModuleParts.#from(self, from)};`,
|
|
133
|
+
);
|
|
134
|
+
lines.push(...this.#types, ...part.units.flatMap((unit) => unit.texts));
|
|
135
|
+
const lent = [...own].filter((name) => this.#lent.has(name)).map((name) => `${name} as ${SHARED}${name}`);
|
|
136
|
+
const listed = part.units.flatMap((unit) => unit.listed);
|
|
137
|
+
if (lent.length + listed.length) lines.push(`export { ${[...lent, ...listed].join(", ")} };`);
|
|
138
|
+
return `${lines.join("\n")}\n`;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
static #from(self: string, id: string): string {
|
|
142
|
+
return JSON.stringify(`${self}${ModuleParts.query}${id}`);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
//? `rest` keeps every import the file makes for its effect alone, in the order written.
|
|
146
|
+
static #importOf(
|
|
147
|
+
{ from, bare, defaultName, namespace, named }: ValueImport,
|
|
148
|
+
reads: Set<string>,
|
|
149
|
+
rest: boolean,
|
|
150
|
+
): string | null {
|
|
151
|
+
if (bare) return rest ? `import ${from};` : null;
|
|
152
|
+
const bound: string[] = [];
|
|
153
|
+
if (defaultName && reads.has(defaultName)) bound.push(defaultName);
|
|
154
|
+
if (namespace && reads.has(namespace)) bound.push(`* as ${namespace}`);
|
|
155
|
+
const read = named.filter(({ local }) => reads.has(local));
|
|
156
|
+
if (read.length) bound.push(`{ ${read.map(({ text }) => text).join(", ")} }`);
|
|
157
|
+
return bound.length ? `import ${bound.join(", ")} from ${from};` : null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
#collect(statement: ts.Statement): boolean {
|
|
161
|
+
const text = statement.getFullText(this.#sourceFile).replace(/^\s*\n/, "");
|
|
162
|
+
if (ts.isImportDeclaration(statement)) return this.#collectImport(statement);
|
|
163
|
+
if (ts.isEmptyStatement(statement)) return true;
|
|
164
|
+
if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) {
|
|
165
|
+
this.#types.push(text);
|
|
166
|
+
this.#declaredTypes.add(statement.name.text);
|
|
167
|
+
if (ModuleParts.#has(statement, ts.SyntaxKind.ExportKeyword)) this.#typeNames.add(statement.name.text);
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
if (ModuleParts.#has(statement, ts.SyntaxKind.DeclareKeyword)) {
|
|
171
|
+
this.#types.push(text);
|
|
172
|
+
return true;
|
|
173
|
+
}
|
|
174
|
+
if (ts.isImportEqualsDeclaration(statement) || ts.isModuleDeclaration(statement)) return false;
|
|
175
|
+
if (ts.isExportDeclaration(statement)) return this.#collectExportList(statement);
|
|
176
|
+
if (ts.isExportAssignment(statement)) {
|
|
177
|
+
if (statement.isExportEquals) return false;
|
|
178
|
+
this.#add(statement, text, { publics: ["default"], pure: this.#purity.of(statement.expression) });
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
if (ts.isVariableStatement(statement)) return this.#collectVariables(statement, text);
|
|
182
|
+
if (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement))
|
|
183
|
+
return this.#collectDeclaration(statement, text);
|
|
184
|
+
const given = ts.isExpressionStatement(statement) ? ModuleParts.#given(statement.expression) : null;
|
|
185
|
+
const owner = given && this.#ownerOf.get(given.to);
|
|
186
|
+
if (!given || !owner) {
|
|
187
|
+
this.#add(statement, text, { pure: false });
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
owner.texts.push(text);
|
|
191
|
+
for (const name of ExportReach.namesReadBy(statement)) owner.reads.add(name);
|
|
192
|
+
owner.pure &&= given.values.every((value) => this.#purity.of(value));
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
#collectImport(statement: ts.ImportDeclaration): boolean {
|
|
197
|
+
if (!ts.isStringLiteral(statement.moduleSpecifier)) return false;
|
|
198
|
+
const clause = statement.importClause;
|
|
199
|
+
if (clause?.phaseModifier === ts.SyntaxKind.TypeKeyword) return true;
|
|
200
|
+
const bindings = clause?.namedBindings;
|
|
201
|
+
const namespace = bindings && ts.isNamespaceImport(bindings) ? bindings.name.text : undefined;
|
|
202
|
+
const named = (bindings && ts.isNamedImports(bindings) ? [...bindings.elements] : [])
|
|
203
|
+
.filter((element) => !element.isTypeOnly)
|
|
204
|
+
.map((element) => ({ local: element.name.text, text: element.getText(this.#sourceFile) }));
|
|
205
|
+
const tail = statement.attributes ? ` ${statement.attributes.getText(this.#sourceFile)}` : "";
|
|
206
|
+
const from = `${statement.moduleSpecifier.getText(this.#sourceFile)}${tail}`;
|
|
207
|
+
const defaultName = clause?.name?.text;
|
|
208
|
+
for (const local of [defaultName, namespace, ...named.map(({ local }) => local)])
|
|
209
|
+
if (local) this.#importLocals.add(local);
|
|
210
|
+
//? `import {} from` binds nothing and still loads the module, as a bare import does.
|
|
211
|
+
const bare = !clause || (!defaultName && !!bindings && ts.isNamedImports(bindings) && !bindings.elements.length);
|
|
212
|
+
this.#imports.push({ from, bare, defaultName, namespace, named });
|
|
213
|
+
this.#purity.note(statement);
|
|
214
|
+
if (bare) this.#add(statement, "", { pure: false });
|
|
215
|
+
return true;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
#collectExportList(statement: ts.ExportDeclaration): boolean {
|
|
219
|
+
const clause = statement.exportClause;
|
|
220
|
+
if (!clause) return statement.isTypeOnly;
|
|
221
|
+
if (ts.isNamespaceExport(clause)) {
|
|
222
|
+
if (statement.isTypeOnly) this.#typeNames.add(clause.name.text);
|
|
223
|
+
else this.#add(statement, statement.getText(this.#sourceFile), { publics: [clause.name.text] });
|
|
224
|
+
return true;
|
|
225
|
+
}
|
|
226
|
+
const values = clause.elements.filter((element) => !statement.isTypeOnly && !element.isTypeOnly);
|
|
227
|
+
for (const element of clause.elements) if (!values.includes(element)) this.#typeNames.add(element.name.text);
|
|
228
|
+
if (!statement.moduleSpecifier) {
|
|
229
|
+
for (const element of values)
|
|
230
|
+
this.#lists.push({ local: (element.propertyName ?? element.name).text, exported: element.name.text });
|
|
231
|
+
return true;
|
|
232
|
+
}
|
|
233
|
+
if (!values.length) return true;
|
|
234
|
+
const from = statement.moduleSpecifier.getText(this.#sourceFile);
|
|
235
|
+
const names = values.map((element) => element.getText(this.#sourceFile));
|
|
236
|
+
const tail = statement.attributes ? ` ${statement.attributes.getText(this.#sourceFile)}` : "";
|
|
237
|
+
this.#add(statement, `export { ${names.join(", ")} } from ${from}${tail};`, {
|
|
238
|
+
publics: values.map((element) => element.name.text),
|
|
239
|
+
});
|
|
240
|
+
return true;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
#collectVariables(statement: ts.VariableStatement, text: string): boolean {
|
|
244
|
+
const { flags, declarations } = statement.declarationList;
|
|
245
|
+
if ((flags & ts.NodeFlags.BlockScoped) !== ts.NodeFlags.Const) return false;
|
|
246
|
+
const declares = declarations.flatMap((declaration) => ModuleParts.#boundNames(declaration.name));
|
|
247
|
+
const pure = declarations.every(
|
|
248
|
+
(declaration) => declaration.initializer && this.#purity.of(declaration.initializer),
|
|
249
|
+
);
|
|
250
|
+
const exported = ModuleParts.#has(statement, ts.SyntaxKind.ExportKeyword);
|
|
251
|
+
this.#add(statement, text, { declares, pure, publics: exported ? declares : [] });
|
|
252
|
+
return true;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
#collectDeclaration(
|
|
256
|
+
statement: ts.FunctionDeclaration | ts.ClassDeclaration | ts.EnumDeclaration,
|
|
257
|
+
text: string,
|
|
258
|
+
): boolean {
|
|
259
|
+
if (ts.isFunctionDeclaration(statement) && !statement.body) {
|
|
260
|
+
this.#overloads.push(text);
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
const declares = statement.name ? [statement.name.text] : [];
|
|
264
|
+
const publics = ModuleParts.#has(statement, ts.SyntaxKind.DefaultKeyword)
|
|
265
|
+
? ["default"]
|
|
266
|
+
: ModuleParts.#has(statement, ts.SyntaxKind.ExportKeyword)
|
|
267
|
+
? declares
|
|
268
|
+
: [];
|
|
269
|
+
const pure = !ts.isClassDeclaration(statement) || this.#purity.ofClass(statement);
|
|
270
|
+
this.#add(statement, [...this.#overloads, text].join("\n"), { declares, pure, publics });
|
|
271
|
+
this.#overloads = [];
|
|
272
|
+
return true;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
#add(
|
|
276
|
+
statement: ts.Statement,
|
|
277
|
+
text: string,
|
|
278
|
+
{ declares = [], pure = true, publics = [] }: { declares?: string[]; pure?: boolean; publics?: string[] },
|
|
279
|
+
) {
|
|
280
|
+
const reads = ts.isImportDeclaration(statement) ? new Set<string>() : ExportReach.namesReadBy(statement);
|
|
281
|
+
const known = declares.map((name) => this.#ownerOf.get(name)).find((unit) => unit !== undefined);
|
|
282
|
+
const unit = known ?? {
|
|
283
|
+
at: statement.pos,
|
|
284
|
+
texts: [],
|
|
285
|
+
declares: [],
|
|
286
|
+
reads: new Set(),
|
|
287
|
+
pure: true,
|
|
288
|
+
publics: [],
|
|
289
|
+
listed: [],
|
|
290
|
+
};
|
|
291
|
+
if (text) unit.texts.push(text);
|
|
292
|
+
unit.declares.push(...declares);
|
|
293
|
+
unit.publics.push(...publics);
|
|
294
|
+
unit.pure &&= pure;
|
|
295
|
+
for (const name of reads) unit.reads.add(name);
|
|
296
|
+
for (const name of declares) this.#ownerOf.set(name, unit);
|
|
297
|
+
if (!known) this.#units.push(unit);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
#place(): boolean {
|
|
301
|
+
for (const { local, exported } of this.#lists) {
|
|
302
|
+
const owner = this.#ownerOf.get(local);
|
|
303
|
+
if (owner) owner.listed.push(local === exported ? local : `${local} as ${exported}`);
|
|
304
|
+
else if (this.#importLocals.has(local))
|
|
305
|
+
this.#units.push({
|
|
306
|
+
at: this.#sourceFile.end,
|
|
307
|
+
texts: [`export { ${local === exported ? local : `${local} as ${exported}`} };`],
|
|
308
|
+
declares: [],
|
|
309
|
+
reads: new Set([local]),
|
|
310
|
+
pure: true,
|
|
311
|
+
publics: [exported],
|
|
312
|
+
listed: [],
|
|
313
|
+
});
|
|
314
|
+
else if (this.#declaredTypes.has(local)) this.#typeNames.add(exported);
|
|
315
|
+
else return false;
|
|
316
|
+
if (owner) owner.publics.push(exported);
|
|
317
|
+
}
|
|
318
|
+
const dependencies = new Map<Unit, Set<Unit>>();
|
|
319
|
+
for (const unit of this.#units) {
|
|
320
|
+
const read = [...unit.reads].map((name) => this.#ownerOf.get(name));
|
|
321
|
+
dependencies.set(unit, new Set(read.filter((owner): owner is Unit => !!owner && owner !== unit)));
|
|
322
|
+
}
|
|
323
|
+
const rest = ModuleParts.#closureOf(
|
|
324
|
+
this.#units.filter((unit) => !unit.pure),
|
|
325
|
+
dependencies,
|
|
326
|
+
);
|
|
327
|
+
const groups = ModuleParts.#grouped(
|
|
328
|
+
this.#units.filter((unit) => !rest.has(unit)),
|
|
329
|
+
dependencies,
|
|
330
|
+
);
|
|
331
|
+
const parts = groups.map((units) => units.sort((a, b) => a.at - b.at)).sort(([a], [b]) => a.at - b.at);
|
|
332
|
+
this.#parts = parts.map((units, index) => ({ id: `p${index}`, units }));
|
|
333
|
+
if (rest.size) this.#parts.push({ id: REST, units: [...rest].sort((a, b) => a.at - b.at) });
|
|
334
|
+
if (this.#parts.length < 2) return false;
|
|
335
|
+
for (const { id, units } of this.#parts)
|
|
336
|
+
for (const unit of units) {
|
|
337
|
+
for (const name of unit.declares) this.#partOfLocal.set(name, id);
|
|
338
|
+
for (const name of unit.publics) this.#partOfPublic.set(name, id);
|
|
339
|
+
}
|
|
340
|
+
for (const { id, units } of this.#parts)
|
|
341
|
+
for (const unit of units)
|
|
342
|
+
for (const name of unit.reads) {
|
|
343
|
+
const from = this.#partOfLocal.get(name);
|
|
344
|
+
if (from && from !== id) this.#lent.add(name);
|
|
345
|
+
}
|
|
346
|
+
return true;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
static #closureOf(starts: Unit[], dependencies: Map<Unit, Set<Unit>>): Set<Unit> {
|
|
350
|
+
const reached = new Set(starts);
|
|
351
|
+
for (const unit of reached) for (const dependency of dependencies.get(unit) ?? []) reached.add(dependency);
|
|
352
|
+
return reached;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
//? Units in a cycle load together. One no export names, read by a single group, joins it; read by none, it is dropped.
|
|
356
|
+
static #grouped(units: Unit[], dependencies: Map<Unit, Set<Unit>>): Unit[][] {
|
|
357
|
+
const groupOf = new Map<Unit, Set<Unit>>();
|
|
358
|
+
for (const unit of units) {
|
|
359
|
+
if (groupOf.has(unit)) continue;
|
|
360
|
+
const down = ModuleParts.#closureOf([unit], dependencies);
|
|
361
|
+
const cycle = new Set(
|
|
362
|
+
units.filter((other) => down.has(other) && ModuleParts.#closureOf([other], dependencies).has(unit)),
|
|
363
|
+
);
|
|
364
|
+
for (const member of cycle) groupOf.set(member, cycle);
|
|
365
|
+
}
|
|
366
|
+
const groups = new Set(groupOf.values());
|
|
367
|
+
const readersOf = (group: Set<Unit>) =>
|
|
368
|
+
[...groups].filter(
|
|
369
|
+
(other) =>
|
|
370
|
+
other !== group && [...other].some((unit) => [...group].some((own) => dependencies.get(unit)?.has(own))),
|
|
371
|
+
);
|
|
372
|
+
for (let settled = false; !settled; ) {
|
|
373
|
+
settled = true;
|
|
374
|
+
for (const group of groups) {
|
|
375
|
+
if ([...group].some((unit) => unit.publics.length)) continue;
|
|
376
|
+
const readers = readersOf(group);
|
|
377
|
+
if (readers.length > 1) continue;
|
|
378
|
+
for (const unit of group) readers[0]?.add(unit);
|
|
379
|
+
groups.delete(group);
|
|
380
|
+
settled = false;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return [...groups].map((group) => [...group]);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
//? `A.b = v` and `Object.assign(A, v)` belong to the part declaring `A`: they only add to a value it built.
|
|
387
|
+
static #given(expression: ts.Expression): { to: string; values: ts.Expression[] } | null {
|
|
388
|
+
let target: ts.Expression | undefined;
|
|
389
|
+
let values: ts.Expression[] = [];
|
|
390
|
+
if (ts.isBinaryExpression(expression) && expression.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
|
|
391
|
+
target = expression.left;
|
|
392
|
+
while (ts.isPropertyAccessExpression(target)) target = target.expression;
|
|
393
|
+
if (target === expression.left) return null;
|
|
394
|
+
values = [expression.right];
|
|
395
|
+
} else if (
|
|
396
|
+
ts.isCallExpression(expression) &&
|
|
397
|
+
ts.isPropertyAccessExpression(expression.expression) &&
|
|
398
|
+
expression.expression.name.text === "assign" &&
|
|
399
|
+
ts.isIdentifier(expression.expression.expression) &&
|
|
400
|
+
expression.expression.expression.text === "Object"
|
|
401
|
+
) {
|
|
402
|
+
[target, ...values] = expression.arguments;
|
|
403
|
+
values = values.map((value) => (ts.isSpreadElement(value) ? value.expression : value));
|
|
404
|
+
}
|
|
405
|
+
return target && ts.isIdentifier(target) ? { to: target.text, values } : null;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
static #boundNames(name: ts.BindingName): string[] {
|
|
409
|
+
if (ts.isIdentifier(name)) return [name.text];
|
|
410
|
+
return name.elements.flatMap((element) =>
|
|
411
|
+
ts.isOmittedExpression(element) ? [] : ModuleParts.#boundNames(element.name),
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
static #has(node: ts.Node, kind: ts.SyntaxKind) {
|
|
416
|
+
return ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((modifier) => modifier.kind === kind);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { ModuleParts } from "./moduleParts";
|
|
4
|
+
import { PartImports } from "./partImports";
|
|
5
|
+
|
|
6
|
+
const dir = "/repo/apps/demo/ui";
|
|
7
|
+
const pair = `${dir}/Pair.tsx`;
|
|
8
|
+
const importer = `${dir}/Page.tsx`;
|
|
9
|
+
const part = (id: string) => `"${pair}?akan-part=${id}"`;
|
|
10
|
+
const pairSource = [
|
|
11
|
+
"export interface Props { a: number }",
|
|
12
|
+
"export const A = () => 1;",
|
|
13
|
+
"export const B = () => 2;",
|
|
14
|
+
"const C = () => 3;",
|
|
15
|
+
"export default C;",
|
|
16
|
+
"",
|
|
17
|
+
].join("\n");
|
|
18
|
+
|
|
19
|
+
const imports = new PartImports({
|
|
20
|
+
resolve: async (specifier, from) => path.resolve(path.dirname(from), `${specifier}.tsx`),
|
|
21
|
+
partsOf: async (file) => (file === pair ? ModuleParts.read(pairSource, pair) : null),
|
|
22
|
+
});
|
|
23
|
+
const rewritten = async (...lines: string[]) => imports.rewrite(`${lines.join("\n")}\n`, importer);
|
|
24
|
+
|
|
25
|
+
describe("PartImports", () => {
|
|
26
|
+
test("each name asked of a file in parts is asked of the part holding it, and a type is asked of none", async () => {
|
|
27
|
+
expect(
|
|
28
|
+
await rewritten(
|
|
29
|
+
'import Pair, { A, B as Bee, type Props } from "./Pair";',
|
|
30
|
+
'import { Other } from "./Other";',
|
|
31
|
+
"export const page = [Pair, A, Bee, Other];",
|
|
32
|
+
),
|
|
33
|
+
).toBe(
|
|
34
|
+
[
|
|
35
|
+
`import { default as Pair } from ${part("p2")};`,
|
|
36
|
+
`import { A } from ${part("p0")};`,
|
|
37
|
+
`import { B as Bee } from ${part("p1")};`,
|
|
38
|
+
'import { Other } from "./Other";',
|
|
39
|
+
"export const page = [Pair, A, Bee, Other];",
|
|
40
|
+
"",
|
|
41
|
+
].join("\n"),
|
|
42
|
+
);
|
|
43
|
+
expect(await rewritten('import { A, Props } from "./Pair";', "export const page = A;")).toBe(
|
|
44
|
+
[`import { A } from ${part("p0")};`, "export const page = A;", ""].join("\n"),
|
|
45
|
+
);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("a re-export follows its names to their parts the same way", async () => {
|
|
49
|
+
expect(await rewritten('export { A as First, B } from "./Pair";')).toBe(
|
|
50
|
+
[`export { A as First } from ${part("p0")};`, `export { B } from ${part("p1")};`, ""].join("\n"),
|
|
51
|
+
);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("a name the parts do not hold stays asked of the file", async () => {
|
|
55
|
+
expect(await rewritten('import { A, Missing } from "./Pair";')).toBe(
|
|
56
|
+
[`import { A } from ${part("p0")};`, 'import { Missing } from "./Pair";', ""].join("\n"),
|
|
57
|
+
);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test.each([
|
|
61
|
+
["a namespace import", 'import * as Pair from "./Pair";'],
|
|
62
|
+
["`export *`", 'export * from "./Pair";'],
|
|
63
|
+
["a bare import", 'import "./Pair";'],
|
|
64
|
+
["a type import", 'import type { Props } from "./Pair";'],
|
|
65
|
+
["an import with attributes", 'import { A } from "./Pair" with { type: "json" };'],
|
|
66
|
+
["`import()`", 'export const later = () => import("./Pair");'],
|
|
67
|
+
["an import of a file left whole", 'import { Other } from "./Other";'],
|
|
68
|
+
["an import already naming a part", `import { A } from ${part("p0")};`],
|
|
69
|
+
])("%s is left as written", async (_, line) => {
|
|
70
|
+
expect(await rewritten(line)).toBeNull();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test("a file's import of itself is left as written", async () => {
|
|
74
|
+
expect(await imports.rewrite('import { A } from "./Pair";\n', pair)).toBeNull();
|
|
75
|
+
});
|
|
76
|
+
});
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { ModuleParts } from "./moduleParts";
|
|
3
|
+
import { ObjectModule } from "./objectModule";
|
|
4
|
+
|
|
5
|
+
export interface PartImportsOptions {
|
|
6
|
+
resolve: (specifier: string, importer: string) => Promise<string | null>;
|
|
7
|
+
//? Null for a file that stays one module.
|
|
8
|
+
partsOf: (file: string) => Promise<ModuleParts | null>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface Asked {
|
|
12
|
+
imported: string;
|
|
13
|
+
local: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface Statement {
|
|
17
|
+
kind: "import" | "export";
|
|
18
|
+
specifier: string;
|
|
19
|
+
written: string;
|
|
20
|
+
names: Asked[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface Edit {
|
|
24
|
+
start: number;
|
|
25
|
+
end: number;
|
|
26
|
+
text: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const FROM = /\bfrom\s*["']/;
|
|
30
|
+
|
|
31
|
+
//* Sends each name an import or re-export asks of a file in parts to the part holding it, so a bundler follows that
|
|
32
|
+
//* part alone. A namespace import, `export *`, a bare import and `import()` keep asking the file, which loads them all.
|
|
33
|
+
export class PartImports {
|
|
34
|
+
readonly #resolve: PartImportsOptions["resolve"];
|
|
35
|
+
readonly #partsOf: PartImportsOptions["partsOf"];
|
|
36
|
+
|
|
37
|
+
constructor({ resolve, partsOf }: PartImportsOptions) {
|
|
38
|
+
this.#resolve = resolve;
|
|
39
|
+
this.#partsOf = partsOf;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async rewrite(source: string, importer: string): Promise<string | null> {
|
|
43
|
+
if (!FROM.test(source)) return null;
|
|
44
|
+
const sourceFile = ts.createSourceFile(
|
|
45
|
+
importer,
|
|
46
|
+
source,
|
|
47
|
+
ts.ScriptTarget.Latest,
|
|
48
|
+
true,
|
|
49
|
+
ObjectModule.scriptKindOf(importer),
|
|
50
|
+
);
|
|
51
|
+
const edits: Edit[] = [];
|
|
52
|
+
for (const statement of sourceFile.statements) {
|
|
53
|
+
const asked = PartImports.#askedBy(statement);
|
|
54
|
+
if (!asked) continue;
|
|
55
|
+
const file = await this.#resolve(asked.specifier, importer);
|
|
56
|
+
const parts = file && file !== importer ? await this.#partsOf(file) : null;
|
|
57
|
+
if (!file || !parts) continue;
|
|
58
|
+
const lines = PartImports.#lines(asked, parts, file);
|
|
59
|
+
edits.push({ start: statement.getStart(sourceFile), end: statement.end, text: lines.join("\n") });
|
|
60
|
+
}
|
|
61
|
+
if (edits.length === 0) return null;
|
|
62
|
+
let next = "";
|
|
63
|
+
let cursor = 0;
|
|
64
|
+
for (const { start, end, text } of edits) {
|
|
65
|
+
next += `${source.slice(cursor, start)}${text}`;
|
|
66
|
+
cursor = end;
|
|
67
|
+
}
|
|
68
|
+
return `${next}${source.slice(cursor)}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
static #askedBy(statement: ts.Statement): Statement | null {
|
|
72
|
+
if (!ts.isImportDeclaration(statement) && !ts.isExportDeclaration(statement)) return null;
|
|
73
|
+
const { moduleSpecifier, attributes } = statement;
|
|
74
|
+
if (!moduleSpecifier || !ts.isStringLiteral(moduleSpecifier) || attributes) return null;
|
|
75
|
+
if (ModuleParts.specifier.test(moduleSpecifier.text)) return null;
|
|
76
|
+
const from = { specifier: moduleSpecifier.text, written: moduleSpecifier.getText() };
|
|
77
|
+
const namesOf = (elements: readonly (ts.ImportSpecifier | ts.ExportSpecifier)[]) =>
|
|
78
|
+
elements
|
|
79
|
+
.filter((element) => !element.isTypeOnly)
|
|
80
|
+
.map((element) => ({ imported: (element.propertyName ?? element.name).text, local: element.name.text }));
|
|
81
|
+
if (ts.isExportDeclaration(statement)) {
|
|
82
|
+
const clause = statement.exportClause;
|
|
83
|
+
if (statement.isTypeOnly || !clause || !ts.isNamedExports(clause)) return null;
|
|
84
|
+
const names = namesOf(clause.elements);
|
|
85
|
+
return names.length ? { kind: "export", ...from, names } : null;
|
|
86
|
+
}
|
|
87
|
+
const clause = statement.importClause;
|
|
88
|
+
if (!clause || clause.phaseModifier === ts.SyntaxKind.TypeKeyword) return null;
|
|
89
|
+
const bindings = clause.namedBindings;
|
|
90
|
+
if (bindings && ts.isNamespaceImport(bindings)) return null;
|
|
91
|
+
const names = namesOf(bindings?.elements ?? []);
|
|
92
|
+
if (clause.name) names.unshift({ imported: "default", local: clause.name.text });
|
|
93
|
+
return names.length ? { kind: "import", ...from, names } : null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
//? A name the file's parts do not hold stays asked of the file, so the bundler reports it as it did before.
|
|
97
|
+
static #lines({ kind, names, written }: Statement, parts: ModuleParts, file: string): string[] {
|
|
98
|
+
const byTarget = new Map<string, Asked[]>();
|
|
99
|
+
for (const asked of names) {
|
|
100
|
+
const part = parts.partOf(asked.imported);
|
|
101
|
+
if (!part && parts.isType(asked.imported)) continue;
|
|
102
|
+
const target = part ? JSON.stringify(`${file}${ModuleParts.query}${part}`) : written;
|
|
103
|
+
byTarget.set(target, [...(byTarget.get(target) ?? []), asked]);
|
|
104
|
+
}
|
|
105
|
+
return [...byTarget].map(([target, held]) => {
|
|
106
|
+
const list = held.map(({ imported, local }) => (imported === local ? local : `${imported} as ${local}`));
|
|
107
|
+
return `${kind} { ${list.join(", ")} } from ${target};`;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
}
|