@akanjs/devkit 3.3.0-rc.37 → 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 +65 -0
- package/app/applicationBuildRunner.ts +7 -1
- package/app/dictionarySizes.ts +2 -5
- package/app/routeFilesReport.test.ts +59 -0
- package/app/routeFilesReport.ts +46 -0
- package/app/routeJsBudget.ts +18 -4
- package/artifact/storeBootstrap.ts +5 -1
- package/biome.base.json +1 -3
- package/codeAgent/skills/akan-page/SKILL.md +28 -7
- package/executors/clientRuntimeKeys.test.ts +72 -1
- package/executors/sysExecutor.ts +10 -8
- package/frontendBuild/allRoutesBuilder.ts +20 -8
- package/frontendBuild/buildRouteClient.test.ts +65 -0
- package/frontendBuild/clientBuildTypes.ts +11 -0
- package/frontendBuild/clientEntriesBundler.ts +21 -11
- package/frontendBuild/clientEntryDiscovery.test.ts +213 -0
- package/frontendBuild/clientEntryDiscovery.ts +49 -8
- package/frontendBuild/devBarrelImports.test.ts +54 -0
- package/frontendBuild/devBarrelImports.ts +1 -0
- package/frontendBuild/dictionaryAssetBuilder.test.ts +12 -4
- package/frontendBuild/dictionaryAssetBuilder.ts +20 -7
- package/frontendBuild/dictionaryConstants.ts +55 -1
- package/frontendBuild/dictionaryPacking.test.ts +58 -0
- package/frontendBuild/dictionaryPacking.ts +43 -0
- package/frontendBuild/dictionaryRoutes.test.ts +65 -0
- package/frontendBuild/dictionaryRoutes.ts +3 -1
- package/frontendBuild/precompressArtifacts.test.ts +22 -0
- package/frontendBuild/precompressArtifacts.ts +18 -11
- package/frontendBuild/renderedEntries.ts +144 -0
- package/frontendBuild/routeClientBuilder.ts +65 -27
- package/frontendBuild/routeHandoffs.test.ts +10 -0
- package/frontendBuild/routeHandoffs.ts +3 -1
- 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/frontendBuild/routeRuntimePays.test.ts +7 -1
- package/lint/biomeBase.test.ts +23 -3
- package/package.json +3 -3
- package/quality/dictionaryKeys.test.ts +185 -2
- package/quality/dictionaryKeys.ts +82 -9
- package/quality/objectImportReport.ts +6 -3
- package/quality/translatorBindings.ts +187 -0
- package/transforms/barrelImportsPlugin.ts +56 -35
- package/transforms/exportReach.test.ts +162 -0
- package/transforms/exportReach.ts +308 -0
- package/transforms/moduleParts.test.ts +225 -0
- package/transforms/moduleParts.ts +418 -0
- package/transforms/objectMemberImports.test.ts +289 -7
- package/transforms/objectMemberImports.ts +92 -58
- package/transforms/objectMemberLookup.ts +150 -0
- package/transforms/objectModule.test.ts +72 -2
- package/transforms/objectModule.ts +31 -7
- 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
- package/workspace/scanInfo.ts +24 -0
|
@@ -4,8 +4,10 @@ import ts from "typescript";
|
|
|
4
4
|
import { StoreBootstrap } from "../artifact/storeBootstrap";
|
|
5
5
|
import type { App } from "../commandDecorators";
|
|
6
6
|
import { BarrelAnalyzer, type BarrelExportMap, type PackageEntry } from "./barrelAnalyzer";
|
|
7
|
+
import { ModuleParts } from "./moduleParts";
|
|
7
8
|
import { loaderFor, type NamedItem } from "./moduleSyntax";
|
|
8
9
|
import { ObjectMemberImports } from "./objectMemberImports";
|
|
10
|
+
import { PartModules, type PartSource } from "./partModules";
|
|
9
11
|
import type { RouteRuntime } from "./routeRuntime";
|
|
10
12
|
|
|
11
13
|
export interface BarrelImportsPluginOptions {
|
|
@@ -21,6 +23,8 @@ export interface BarrelImportsPluginOptions {
|
|
|
21
23
|
modelRuntime?: string;
|
|
22
24
|
/** Gives each client module the runtime pieces of the modules it names, in a build loading only the page runtime. */
|
|
23
25
|
routeRuntime?: RouteRuntime | null;
|
|
26
|
+
/** Takes each workspace file apart by export, so a chunk holds the exports asked for; holds the parts read so far. */
|
|
27
|
+
parts?: Map<string, ModuleParts | null>;
|
|
24
28
|
}
|
|
25
29
|
|
|
26
30
|
export const createBarrelImportsPlugin = async (
|
|
@@ -32,6 +36,7 @@ export const createBarrelImportsPlugin = async (
|
|
|
32
36
|
barrels: only,
|
|
33
37
|
modelRuntime,
|
|
34
38
|
routeRuntime,
|
|
39
|
+
parts,
|
|
35
40
|
}: BarrelImportsPluginOptions = {},
|
|
36
41
|
): Promise<BunPlugin> => {
|
|
37
42
|
const barrels = [...new Set(only ?? (await app.getConfig()).barrelImports)].filter(
|
|
@@ -43,54 +48,70 @@ export const createBarrelImportsPlugin = async (
|
|
|
43
48
|
resolvePackage,
|
|
44
49
|
...(route ? { packageRoot: app.workspace.workspaceRoot } : {}),
|
|
45
50
|
});
|
|
46
|
-
const
|
|
51
|
+
const resolve = ObjectMemberImports.resolverOf(resolvePackage);
|
|
52
|
+
const objects = route ? new ObjectMemberImports({ resolve, barrels: { names: barrels, analyzer } }) : null;
|
|
53
|
+
|
|
54
|
+
const read = async (realPath: string): Promise<PartSource | null> => {
|
|
55
|
+
const file = Bun.file(realPath);
|
|
56
|
+
//? A build's `files` entry has no copy on disk: Bun loads it itself.
|
|
57
|
+
if (!(await file.exists())) return null;
|
|
58
|
+
if (modelRuntime !== undefined && StoreBootstrap.modelRuntimeFilter.test(realPath))
|
|
59
|
+
return { source: modelRuntime, settled: true };
|
|
60
|
+
const whole = routeRuntime?.redirectOf(realPath);
|
|
61
|
+
if (whole) return { source: whole, settled: true };
|
|
62
|
+
let source = await file.text();
|
|
63
|
+
if (skipPath(realPath)) return { source, settled: true };
|
|
64
|
+
|
|
65
|
+
// Bun's macro evaluator races when a rewritten module holds `with { type: "macro" }` imports while another
|
|
66
|
+
// macro host evaluates (a macro identifier ends up undefined), so macro hosts keep their barrel imports.
|
|
67
|
+
const macroHost = MACRO_ATTR_RE.test(source);
|
|
68
|
+
if (!macroHost) {
|
|
69
|
+
const routed = routeRuntime?.transform(source, realPath);
|
|
70
|
+
if (routed) source = routed.source;
|
|
71
|
+
const rewritten =
|
|
72
|
+
barrels.length > 0
|
|
73
|
+
? await rewriteBarrelImports(source, barrels, analyzer, {
|
|
74
|
+
perModule: routed?.perModule,
|
|
75
|
+
reexports: route,
|
|
76
|
+
})
|
|
77
|
+
: null;
|
|
78
|
+
if (rewritten !== null) source = rewritten;
|
|
79
|
+
const narrowed = await objects?.rewrite(source, realPath);
|
|
80
|
+
if (narrowed?.contents) source = narrowed.contents;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (pipeAfter) {
|
|
84
|
+
const piped = await pipeAfter(source, { path: realPath });
|
|
85
|
+
if (piped !== null) source = piped;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return { source, settled: macroHost };
|
|
89
|
+
};
|
|
90
|
+
const partModules =
|
|
91
|
+
parts && route
|
|
92
|
+
? new PartModules({ workspaceRoot: app.workspace.workspaceRoot, resolve, read, cache: parts })
|
|
93
|
+
: null;
|
|
47
94
|
|
|
48
95
|
return {
|
|
49
96
|
name: "barrel-imports",
|
|
50
97
|
setup(build) {
|
|
98
|
+
if (partModules) build.onResolve({ filter: ModuleParts.specifier }, ({ path: asked }) => ({ path: asked }));
|
|
51
99
|
// node_modules/akanjs stays in: framework `"use client"` modules still need RSC stubbing in generated workspaces.
|
|
52
100
|
// The optional `?v=N` tail matches HMR cache-busted paths; it is stripped before reading.
|
|
53
101
|
build.onLoad(
|
|
54
102
|
{
|
|
55
103
|
filter:
|
|
56
|
-
/^(?:(?!.*[\\/]node_modules[\\/]).*|.*[\\/]node_modules[\\/]akanjs[\\/].*)\.(tsx|ts|jsx|js)(\?v=\d+)?$/,
|
|
104
|
+
/^(?:(?!.*[\\/]node_modules[\\/]).*|.*[\\/]node_modules[\\/]akanjs[\\/].*)\.(tsx|ts|jsx|js)(\?v=\d+|\?akan-part=[\w$]+)?$/,
|
|
57
105
|
},
|
|
58
106
|
async (args) => {
|
|
59
107
|
const realPath = args.path.replace(/\?v=\d+$/, "");
|
|
60
|
-
const loader = loaderFor(realPath);
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
if (modelRuntime !== undefined && StoreBootstrap.modelRuntimeFilter.test(realPath))
|
|
65
|
-
return { contents: modelRuntime, loader };
|
|
66
|
-
const whole = routeRuntime?.redirectOf(realPath);
|
|
67
|
-
if (whole) return { contents: whole, loader };
|
|
68
|
-
let source = await file.text();
|
|
69
|
-
if (skipPath(realPath)) return { contents: source, loader };
|
|
70
|
-
|
|
71
|
-
// Bun's macro evaluator races when a rewritten module holds `with { type: "macro" }` imports while another
|
|
72
|
-
// macro host evaluates (a macro identifier ends up undefined), so macro hosts keep their barrel imports.
|
|
73
|
-
if (!MACRO_ATTR_RE.test(source)) {
|
|
74
|
-
const routed = routeRuntime?.transform(source, realPath);
|
|
75
|
-
if (routed) source = routed.source;
|
|
76
|
-
const rewritten =
|
|
77
|
-
barrels.length > 0
|
|
78
|
-
? await rewriteBarrelImports(source, barrels, analyzer, {
|
|
79
|
-
perModule: routed?.perModule,
|
|
80
|
-
reexports: route,
|
|
81
|
-
})
|
|
82
|
-
: null;
|
|
83
|
-
if (rewritten !== null) source = rewritten;
|
|
84
|
-
const narrowed = await objects?.rewrite(source, realPath);
|
|
85
|
-
if (narrowed?.contents) source = narrowed.contents;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
if (pipeAfter) {
|
|
89
|
-
const piped = await pipeAfter(source, { path: realPath });
|
|
90
|
-
if (piped !== null) source = piped;
|
|
108
|
+
const loader = loaderFor(PartModules.fileOf(realPath));
|
|
109
|
+
if (partModules) {
|
|
110
|
+
const contents = await partModules.load(realPath);
|
|
111
|
+
return contents === null ? undefined : { contents, loader };
|
|
91
112
|
}
|
|
92
|
-
|
|
93
|
-
return { contents: source, loader };
|
|
113
|
+
const loaded = await read(realPath);
|
|
114
|
+
return loaded ? { contents: loaded.source, loader } : undefined;
|
|
94
115
|
},
|
|
95
116
|
);
|
|
96
117
|
},
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { ExportReach } from "./exportReach";
|
|
3
|
+
|
|
4
|
+
const read = (source: string, file = "View.tsx") => ExportReach.read(source, file) as ExportReach;
|
|
5
|
+
const importsOf = (source: string, name: string) => {
|
|
6
|
+
const reached = read(source).of(name);
|
|
7
|
+
return reached.known ? reached.imports : null;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
const view = `
|
|
11
|
+
import { Remove, Edit } from "./Memo.Util";
|
|
12
|
+
import { Chart } from "./Chart";
|
|
13
|
+
import type { Memo } from "./memo.constant";
|
|
14
|
+
import * as Unit from "./Memo.Unit";
|
|
15
|
+
import { format } from "./format";
|
|
16
|
+
|
|
17
|
+
const Title = ({ memo }: { memo: Memo }) => <h1>{format(memo.title)}</h1>;
|
|
18
|
+
|
|
19
|
+
export const General = ({ memo }: { memo: Memo }) => (
|
|
20
|
+
<div>
|
|
21
|
+
<Title memo={memo} />
|
|
22
|
+
<Remove id={memo.id} />
|
|
23
|
+
</div>
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
export function Stats({ memo }: { memo: Memo }) {
|
|
27
|
+
return <Chart value={memo.count} />;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const Card = ({ memo }: { memo: Memo }) => <Unit.Card memo={memo} />;
|
|
31
|
+
export const All = () => Object.values(Unit);
|
|
32
|
+
export interface Props { memo: Memo }
|
|
33
|
+
`;
|
|
34
|
+
|
|
35
|
+
describe("ExportReach", () => {
|
|
36
|
+
test("reaches, from one export, the imports its declaration reads and those of the declarations it reads", () => {
|
|
37
|
+
expect(importsOf(view, "General")).toEqual([
|
|
38
|
+
{ specifier: "./Memo.Util", names: ["Remove"] },
|
|
39
|
+
{ specifier: "./format", names: ["format"] },
|
|
40
|
+
]);
|
|
41
|
+
expect(importsOf(view, "Stats")).toEqual([{ specifier: "./Chart", names: ["Chart"] }]);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test("asks a namespace import for the members read from it, and for the whole module once it is handed on", () => {
|
|
45
|
+
expect(importsOf(view, "Card")).toEqual([{ specifier: "./Memo.Unit", names: ["Card"] }]);
|
|
46
|
+
expect(importsOf(view, "All")).toEqual([{ specifier: "./Memo.Unit", names: null }]);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("reaches nothing for a type, and does not follow a name read only in a type", () => {
|
|
50
|
+
expect(importsOf(view, "Props")).toEqual([]);
|
|
51
|
+
expect(
|
|
52
|
+
read(view)
|
|
53
|
+
.whole()
|
|
54
|
+
.map(({ specifier }) => specifier),
|
|
55
|
+
).not.toContain("./memo.constant");
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test("answers a name the file does not hold as unknown, with the `export *` targets that may hold it", () => {
|
|
59
|
+
expect(read(view).of("Missing")).toEqual({ known: false, stars: [] });
|
|
60
|
+
expect(read('export * from "./a";\nexport * from "./b";\nexport const X = 1;\n').of("Y")).toEqual({
|
|
61
|
+
known: false,
|
|
62
|
+
stars: ["./a", "./b"],
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("follows an export list, a re-export, a namespace re-export and a default export", () => {
|
|
67
|
+
const source = `
|
|
68
|
+
import Base from "./Base";
|
|
69
|
+
import { Row } from "./Row";
|
|
70
|
+
const List = () => <Row />;
|
|
71
|
+
export { List as Rows };
|
|
72
|
+
export { Cell as GridCell, default as Grid } from "./Grid";
|
|
73
|
+
export * as Icons from "./icons";
|
|
74
|
+
export default function Page() { return <Base />; }
|
|
75
|
+
`;
|
|
76
|
+
expect(importsOf(source, "Rows")).toEqual([{ specifier: "./Row", names: ["Row"] }]);
|
|
77
|
+
expect(importsOf(source, "GridCell")).toEqual([{ specifier: "./Grid", names: ["Cell"] }]);
|
|
78
|
+
expect(importsOf(source, "Grid")).toEqual([{ specifier: "./Grid", names: ["default"] }]);
|
|
79
|
+
expect(importsOf(source, "Icons")).toEqual([{ specifier: "./icons", names: null }]);
|
|
80
|
+
expect(importsOf(source, "default")).toEqual([{ specifier: "./Base", names: ["default"] }]);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("reads a member put on a declaration with the declaration, not with every importer", () => {
|
|
84
|
+
const source = `
|
|
85
|
+
import { Header } from "./Header";
|
|
86
|
+
import { Footer } from "./Footer";
|
|
87
|
+
import { Plain } from "./Plain";
|
|
88
|
+
export const Card = () => null;
|
|
89
|
+
Card.Header = Header;
|
|
90
|
+
Object.assign(Card, { Footer });
|
|
91
|
+
export const Other = () => <Plain />;
|
|
92
|
+
`;
|
|
93
|
+
expect(importsOf(source, "Card")).toEqual([
|
|
94
|
+
{ specifier: "./Header", names: ["Header"] },
|
|
95
|
+
{ specifier: "./Footer", names: ["Footer"] },
|
|
96
|
+
]);
|
|
97
|
+
expect(importsOf(source, "Other")).toEqual([{ specifier: "./Plain", names: ["Plain"] }]);
|
|
98
|
+
expect(read(source).always()).toEqual([]);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
test("reaches, for every importer, a bare import and what a statement that is no declaration reads", () => {
|
|
102
|
+
const source = `
|
|
103
|
+
import "./polyfill";
|
|
104
|
+
import { register } from "./registry";
|
|
105
|
+
import { Panel } from "./Panel";
|
|
106
|
+
import { Plain } from "./Plain";
|
|
107
|
+
register("panel", Panel);
|
|
108
|
+
export const Other = () => <Plain />;
|
|
109
|
+
`;
|
|
110
|
+
expect(read(source).always()).toEqual([
|
|
111
|
+
{ specifier: "./polyfill", names: null },
|
|
112
|
+
{ specifier: "./registry", names: ["register"] },
|
|
113
|
+
{ specifier: "./Panel", names: ["Panel"] },
|
|
114
|
+
]);
|
|
115
|
+
expect(importsOf(source, "Other")).toEqual([{ specifier: "./Plain", names: ["Plain"] }]);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test("reaches a module loaded on demand as a whole, from the export whose declaration loads it", () => {
|
|
119
|
+
const source = `
|
|
120
|
+
import { lazy } from "react";
|
|
121
|
+
const Editor = lazy(() => import("./Editor"));
|
|
122
|
+
export const Rich = () => <Editor />;
|
|
123
|
+
export const Plain = () => null;
|
|
124
|
+
`;
|
|
125
|
+
expect(importsOf(source, "Rich")).toEqual([
|
|
126
|
+
{ specifier: "./Editor", names: null },
|
|
127
|
+
{ specifier: "react", names: ["lazy"] },
|
|
128
|
+
]);
|
|
129
|
+
expect(importsOf(source, "Plain")).toEqual([]);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test("counts a property name as no read of an import of that name, and a shadowed name as one", () => {
|
|
133
|
+
const source = `
|
|
134
|
+
import { Card } from "./Card";
|
|
135
|
+
import { Row } from "./Row";
|
|
136
|
+
export const A = (props: { Card: string }) => [props.Card, { Card: 1 }];
|
|
137
|
+
export const B = (Row: string) => Row;
|
|
138
|
+
`;
|
|
139
|
+
expect(importsOf(source, "A")).toEqual([]);
|
|
140
|
+
expect(importsOf(source, "B")).toEqual([{ specifier: "./Row", names: ["Row"] }]);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test("the whole module reaches every import a value of it reads, re-exports and `export *` included", () => {
|
|
144
|
+
const source = `
|
|
145
|
+
import { A } from "./a";
|
|
146
|
+
import type { T } from "./t";
|
|
147
|
+
export { B } from "./b";
|
|
148
|
+
export * from "./c";
|
|
149
|
+
export const X = () => <A />;
|
|
150
|
+
`;
|
|
151
|
+
expect(read(source).whole()).toEqual([
|
|
152
|
+
{ specifier: "./a", names: ["A"] },
|
|
153
|
+
{ specifier: "./b", names: ["B"] },
|
|
154
|
+
{ specifier: "./c", names: null },
|
|
155
|
+
]);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
test("does not read a CommonJS module, whose exports are assigned at run time", () => {
|
|
159
|
+
expect(ExportReach.read('const a = require("./a");\nmodule.exports = { a };\n', "legacy.js")).toBeNull();
|
|
160
|
+
expect(ExportReach.read("export const a = 1;\n", "modern.js")).not.toBeNull();
|
|
161
|
+
});
|
|
162
|
+
});
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { ObjectModule } from "./objectModule";
|
|
3
|
+
|
|
4
|
+
export interface ReachedImport {
|
|
5
|
+
specifier: string;
|
|
6
|
+
/** null: the whole module (a namespace handed on, a bare or dynamic import, a name the file re-exports as `*`). */
|
|
7
|
+
names: string[] | null;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export type ExportReached =
|
|
11
|
+
| { known: true; imports: ReachedImport[] }
|
|
12
|
+
/** The file neither declares nor names it: one of its `export *` targets may. */
|
|
13
|
+
| { known: false; stars: string[] };
|
|
14
|
+
|
|
15
|
+
interface ImportedName {
|
|
16
|
+
specifier: string;
|
|
17
|
+
/** `*` for a namespace import, `default` for a default import. */
|
|
18
|
+
imported: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
//? null: the name is read as a value of its own. A set: only these members of it are read (`View.General`).
|
|
22
|
+
type Reads = Map<string, Set<string> | null>;
|
|
23
|
+
|
|
24
|
+
interface Unit {
|
|
25
|
+
reads: Reads;
|
|
26
|
+
dynamic: string[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const CJS_EXPORT_RE = /\b(?:module\.exports|exports\.[A-Za-z_$])/;
|
|
30
|
+
|
|
31
|
+
//* What an importer of one export of a server module can reach: the imports read by that export's declaration and by
|
|
32
|
+
//* the top-level declarations it reads in turn. A type reaches nothing. A statement that is not a declaration runs for
|
|
33
|
+
//* every importer, so what it reads is reached always. Names are matched by text, so a shadowed name counts as read:
|
|
34
|
+
//* the answer can hold more than the export uses, never less.
|
|
35
|
+
export class ExportReach {
|
|
36
|
+
readonly stars: string[] = [];
|
|
37
|
+
readonly #imports = new Map<string, ImportedName>();
|
|
38
|
+
readonly #bare: string[] = [];
|
|
39
|
+
readonly #units = new Map<string, Unit[]>();
|
|
40
|
+
readonly #effects: Unit[] = [];
|
|
41
|
+
readonly #exported = new Map<string, string>();
|
|
42
|
+
readonly #reexports = new Map<string, ImportedName>();
|
|
43
|
+
readonly #types = new Set<string>();
|
|
44
|
+
|
|
45
|
+
//? null for a CommonJS module: what it exports is assigned at run time.
|
|
46
|
+
static read(source: string, file: string): ExportReach | null {
|
|
47
|
+
const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ObjectModule.scriptKindOf(file));
|
|
48
|
+
const esm = sourceFile.statements.some(
|
|
49
|
+
(statement) =>
|
|
50
|
+
ts.isImportDeclaration(statement) ||
|
|
51
|
+
ts.isExportDeclaration(statement) ||
|
|
52
|
+
ts.isExportAssignment(statement) ||
|
|
53
|
+
ExportReach.#has(statement, ts.SyntaxKind.ExportKeyword),
|
|
54
|
+
);
|
|
55
|
+
if (!esm && CJS_EXPORT_RE.test(source)) return null;
|
|
56
|
+
const reach = new ExportReach();
|
|
57
|
+
for (const statement of sourceFile.statements) reach.#collect(statement);
|
|
58
|
+
return reach;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
of(name: string): ExportReached {
|
|
62
|
+
const reexport = this.#reexports.get(name);
|
|
63
|
+
if (reexport) return { known: true, imports: [ExportReach.#whole(reexport)] };
|
|
64
|
+
const local = this.#exported.get(name);
|
|
65
|
+
if (local !== undefined) return { known: true, imports: this.#reached([ExportReach.#reading(local)], []) };
|
|
66
|
+
if (this.#types.has(name)) return { known: true, imports: [] };
|
|
67
|
+
return { known: false, stars: this.stars };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
always(): ReachedImport[] {
|
|
71
|
+
return this.#reached(this.#effects, this.#bare);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
whole(): ReachedImport[] {
|
|
75
|
+
const reexports = [...this.#reexports.values(), ...this.stars.map((specifier) => ({ specifier, imported: "*" }))];
|
|
76
|
+
return ExportReach.#merged([
|
|
77
|
+
...this.#reached([...this.#effects, ...[...this.#units.values()].flat()], this.#bare),
|
|
78
|
+
...reexports.map(ExportReach.#whole),
|
|
79
|
+
]);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
static #whole({ specifier, imported }: ImportedName): ReachedImport {
|
|
83
|
+
return { specifier, names: imported === "*" ? null : [imported] };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
static #reading(name: string): Unit {
|
|
87
|
+
return { reads: new Map([[name, null]]), dynamic: [] };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
#reached(starts: Unit[], bare: string[]): ReachedImport[] {
|
|
91
|
+
const used = new Map<string, Set<string> | null>();
|
|
92
|
+
const dynamic = new Set(bare);
|
|
93
|
+
const seen = new Set<Unit>();
|
|
94
|
+
const queue = [...starts];
|
|
95
|
+
for (const unit of queue) {
|
|
96
|
+
if (seen.has(unit)) continue;
|
|
97
|
+
seen.add(unit);
|
|
98
|
+
for (const specifier of unit.dynamic) dynamic.add(specifier);
|
|
99
|
+
for (const [name, members] of unit.reads) {
|
|
100
|
+
if (this.#imports.has(name)) {
|
|
101
|
+
const known = used.get(name);
|
|
102
|
+
if (members === null || known === null) used.set(name, null);
|
|
103
|
+
else used.set(name, new Set([...(known ?? []), ...members]));
|
|
104
|
+
}
|
|
105
|
+
queue.push(...(this.#units.get(name) ?? []));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const reached: ReachedImport[] = [...dynamic].map((specifier) => ({ specifier, names: null }));
|
|
109
|
+
for (const [local, members] of used) {
|
|
110
|
+
const { specifier, imported } = this.#imports.get(local) as ImportedName;
|
|
111
|
+
if (imported !== "*") reached.push({ specifier, names: [imported] });
|
|
112
|
+
else reached.push({ specifier, names: members ? [...members] : null });
|
|
113
|
+
}
|
|
114
|
+
return ExportReach.#merged(reached);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
static #merged(reached: ReachedImport[]): ReachedImport[] {
|
|
118
|
+
const bySpecifier = new Map<string, Set<string> | null>();
|
|
119
|
+
for (const { specifier, names } of reached) {
|
|
120
|
+
const known = bySpecifier.get(specifier);
|
|
121
|
+
if (names === null || known === null) bySpecifier.set(specifier, null);
|
|
122
|
+
else bySpecifier.set(specifier, new Set([...(known ?? []), ...names]));
|
|
123
|
+
}
|
|
124
|
+
return [...bySpecifier].map(([specifier, names]) => ({ specifier, names: names ? [...names].sort() : null }));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
#collect(statement: ts.Statement) {
|
|
128
|
+
if (ts.isImportDeclaration(statement)) return this.#collectImport(statement);
|
|
129
|
+
if (ts.isExportDeclaration(statement)) return this.#collectExportList(statement);
|
|
130
|
+
if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) {
|
|
131
|
+
if (ExportReach.#has(statement, ts.SyntaxKind.ExportKeyword)) this.#types.add(statement.name.text);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (ExportReach.#has(statement, ts.SyntaxKind.DeclareKeyword) || ts.isEmptyStatement(statement)) return;
|
|
135
|
+
if (ts.isImportEqualsDeclaration(statement)) return this.#collectImportEquals(statement);
|
|
136
|
+
if (ts.isExportAssignment(statement)) {
|
|
137
|
+
if (statement.isExportEquals) return this.#effects.push(ExportReach.#unitOf(statement));
|
|
138
|
+
this.#exported.set("default", "default");
|
|
139
|
+
return this.#declare("default", ExportReach.#unitOf(statement.expression));
|
|
140
|
+
}
|
|
141
|
+
if (ts.isVariableStatement(statement)) return this.#collectVariables(statement);
|
|
142
|
+
if (
|
|
143
|
+
ts.isFunctionDeclaration(statement) ||
|
|
144
|
+
ts.isClassDeclaration(statement) ||
|
|
145
|
+
ts.isEnumDeclaration(statement) ||
|
|
146
|
+
ts.isModuleDeclaration(statement)
|
|
147
|
+
) {
|
|
148
|
+
if (ts.isFunctionDeclaration(statement) && !statement.body) return;
|
|
149
|
+
const name = statement.name && !ts.isStringLiteral(statement.name) ? statement.name.getText() : "default";
|
|
150
|
+
this.#declare(name, ExportReach.#unitOf(statement));
|
|
151
|
+
if (ExportReach.#has(statement, ts.SyntaxKind.DefaultKeyword)) this.#exported.set("default", name);
|
|
152
|
+
else if (ExportReach.#has(statement, ts.SyntaxKind.ExportKeyword)) this.#exported.set(name, name);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
const unit = ExportReach.#unitOf(statement);
|
|
156
|
+
const owner = ts.isExpressionStatement(statement) ? this.#ownerOf(statement.expression) : null;
|
|
157
|
+
if (owner) this.#declare(owner, unit);
|
|
158
|
+
else this.#effects.push(unit);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
//? `Card.Header = Header` and `Object.assign(Card, { Header })` change only `Card`, so they are read with it.
|
|
162
|
+
#ownerOf(expression: ts.Expression): string | null {
|
|
163
|
+
let target: ts.Expression | undefined;
|
|
164
|
+
if (ts.isBinaryExpression(expression) && expression.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
|
|
165
|
+
target = expression.left;
|
|
166
|
+
while (ts.isPropertyAccessExpression(target)) target = target.expression;
|
|
167
|
+
if (target === expression.left) return null;
|
|
168
|
+
} else if (
|
|
169
|
+
ts.isCallExpression(expression) &&
|
|
170
|
+
ts.isPropertyAccessExpression(expression.expression) &&
|
|
171
|
+
expression.expression.name.text === "assign" &&
|
|
172
|
+
ts.isIdentifier(expression.expression.expression) &&
|
|
173
|
+
expression.expression.expression.text === "Object"
|
|
174
|
+
)
|
|
175
|
+
[target] = expression.arguments;
|
|
176
|
+
return target && ts.isIdentifier(target) && this.#units.has(target.text) ? target.text : null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
#declare(name: string, unit: Unit) {
|
|
180
|
+
this.#units.set(name, [...(this.#units.get(name) ?? []), unit]);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
#collectImport(statement: ts.ImportDeclaration) {
|
|
184
|
+
if (!ts.isStringLiteral(statement.moduleSpecifier)) return;
|
|
185
|
+
const specifier = statement.moduleSpecifier.text;
|
|
186
|
+
const clause = statement.importClause;
|
|
187
|
+
if (!clause) return this.#bare.push(specifier);
|
|
188
|
+
if (clause.phaseModifier === ts.SyntaxKind.TypeKeyword) return;
|
|
189
|
+
if (clause.name) this.#imports.set(clause.name.text, { specifier, imported: "default" });
|
|
190
|
+
const bindings = clause.namedBindings;
|
|
191
|
+
if (!bindings) return;
|
|
192
|
+
if (ts.isNamespaceImport(bindings)) return this.#imports.set(bindings.name.text, { specifier, imported: "*" });
|
|
193
|
+
for (const element of bindings.elements)
|
|
194
|
+
if (!element.isTypeOnly)
|
|
195
|
+
this.#imports.set(element.name.text, { specifier, imported: (element.propertyName ?? element.name).text });
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
#collectImportEquals(statement: ts.ImportEqualsDeclaration) {
|
|
199
|
+
if (statement.isTypeOnly) return;
|
|
200
|
+
const reference = statement.moduleReference;
|
|
201
|
+
if (ts.isExternalModuleReference(reference) && ts.isStringLiteral(reference.expression))
|
|
202
|
+
this.#imports.set(statement.name.text, { specifier: reference.expression.text, imported: "*" });
|
|
203
|
+
else this.#declare(statement.name.text, ExportReach.#unitOf(statement));
|
|
204
|
+
if (ExportReach.#has(statement, ts.SyntaxKind.ExportKeyword))
|
|
205
|
+
this.#exported.set(statement.name.text, statement.name.text);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
#collectExportList(statement: ts.ExportDeclaration) {
|
|
209
|
+
const from = statement.moduleSpecifier;
|
|
210
|
+
const specifier = from && ts.isStringLiteral(from) ? from.text : null;
|
|
211
|
+
const clause = statement.exportClause;
|
|
212
|
+
if (!clause) {
|
|
213
|
+
if (specifier && !statement.isTypeOnly) this.stars.push(specifier);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
if (ts.isNamespaceExport(clause)) {
|
|
217
|
+
if (statement.isTypeOnly) this.#types.add(clause.name.text);
|
|
218
|
+
else if (specifier) this.#reexports.set(clause.name.text, { specifier, imported: "*" });
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
for (const element of clause.elements) {
|
|
222
|
+
const exported = element.name.text;
|
|
223
|
+
const local = (element.propertyName ?? element.name).text;
|
|
224
|
+
if (statement.isTypeOnly || element.isTypeOnly) this.#types.add(exported);
|
|
225
|
+
else if (specifier) this.#reexports.set(exported, { specifier, imported: local });
|
|
226
|
+
else this.#exported.set(exported, local);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
#collectVariables(statement: ts.VariableStatement) {
|
|
231
|
+
const exported = ExportReach.#has(statement, ts.SyntaxKind.ExportKeyword);
|
|
232
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
233
|
+
const unit = ExportReach.#unitOf(declaration);
|
|
234
|
+
for (const name of ExportReach.#boundNames(declaration.name)) {
|
|
235
|
+
this.#declare(name, unit);
|
|
236
|
+
if (exported) this.#exported.set(name, name);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
static #boundNames(name: ts.BindingName): string[] {
|
|
242
|
+
if (ts.isIdentifier(name)) return [name.text];
|
|
243
|
+
return name.elements.flatMap((element) =>
|
|
244
|
+
ts.isOmittedExpression(element) ? [] : ExportReach.#boundNames(element.name),
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
static namesReadBy(root: ts.Node): Set<string> {
|
|
249
|
+
return new Set(ExportReach.#unitOf(root).reads.keys());
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
static #unitOf(root: ts.Node): Unit {
|
|
253
|
+
const unit: Unit = { reads: new Map(), dynamic: [] };
|
|
254
|
+
const read = (name: string, member: string | null) => {
|
|
255
|
+
const known = unit.reads.get(name);
|
|
256
|
+
if (member === null || known === null) unit.reads.set(name, null);
|
|
257
|
+
else unit.reads.set(name, (known ?? new Set<string>()).add(member));
|
|
258
|
+
};
|
|
259
|
+
const visit = (node: ts.Node): void => {
|
|
260
|
+
if (ts.isExpressionWithTypeArguments(node)) {
|
|
261
|
+
visit(node.expression);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (ts.isTypeNode(node) || ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) return;
|
|
265
|
+
if (ts.isIdentifier(node)) {
|
|
266
|
+
read(node.text, null);
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (ts.isPropertyAccessExpression(node)) {
|
|
270
|
+
if (ts.isIdentifier(node.expression)) read(node.expression.text, node.name.text);
|
|
271
|
+
else visit(node.expression);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (ts.isCallExpression(node)) {
|
|
275
|
+
const [first] = node.arguments;
|
|
276
|
+
const loads =
|
|
277
|
+
node.expression.kind === ts.SyntaxKind.ImportKeyword ||
|
|
278
|
+
(ts.isIdentifier(node.expression) && node.expression.text === "require");
|
|
279
|
+
if (loads && first && ts.isStringLiteralLike(first)) unit.dynamic.push(first.text);
|
|
280
|
+
}
|
|
281
|
+
if (ts.isPropertyAssignment(node) || ts.isJsxAttribute(node)) {
|
|
282
|
+
if (ts.isComputedPropertyName(node.name)) visit(node.name);
|
|
283
|
+
if (node.initializer) visit(node.initializer);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
if (ts.isBindingElement(node)) {
|
|
287
|
+
if (node.propertyName && ts.isComputedPropertyName(node.propertyName)) visit(node.propertyName);
|
|
288
|
+
visit(node.name);
|
|
289
|
+
if (node.initializer) visit(node.initializer);
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
if (
|
|
293
|
+
(ts.isMethodDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isAccessor(node)) &&
|
|
294
|
+
!ts.isComputedPropertyName(node.name)
|
|
295
|
+
) {
|
|
296
|
+
node.forEachChild((child) => (child === node.name ? undefined : visit(child)));
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
node.forEachChild(visit);
|
|
300
|
+
};
|
|
301
|
+
visit(root);
|
|
302
|
+
return unit;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
static #has(node: ts.Node, kind: ts.SyntaxKind) {
|
|
306
|
+
return ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((modifier) => modifier.kind === kind);
|
|
307
|
+
}
|
|
308
|
+
}
|