Repository navigation
Expand file tree
/
Copy pathinstalledLibrary.ts
More file actions
181 lines (178 loc) · 7.52 KB
/
Copy pathinstalledLibrary.ts
File metadata and controls
181 lines (178 loc) · 7.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import { webLibraryCatalog } from './frozenLibrary';
import { WebStorageError } from './storage';
import { installedLibraryLabels } from './installedLibraryLabels';
import { matchesInstalledLibraryModuleAlias } from './installedLibrarySearch';
import { installedLibraryDeclarations } from './installedLibraryDefinitions';
import { installedLibraryInterfaceSearchText } from './installedLibraryInterfaceSearch';
import { frozenLibraryQuery, matchFrozenLibraryEntry } from '../../src/math/frozenLibraryQuery';
import { installedLibraryMathematics } from './installedLibraryMathematics';
import { readInstalledLibrarySearchData } from '../../src/math/frozenLibrarySearchData';
import type {
InstalledLibraryDetail,
InstalledLibraryDirectory,
InstalledLibraryInfo,
InstalledLibraryModule,
InstalledLibraryModuleSummary,
InstalledLibrarySource,
} from './installedLibraryTypes';
function installedCatalog() {
try {
return webLibraryCatalog();
} catch {
throw new WebStorageError(503, '现有 Lean 库目录读取失败,请检查服务的库版本配置后重试。');
}
}
type Catalog = ReturnType<typeof installedCatalog>;
function libraryInfo(catalog: Catalog): InstalledLibraryInfo {
return {
...catalog.identity,
environment: catalog.environment,
toolchain: catalog.toolchain,
moduleCount: catalog.moduleCount,
declarationCount: catalog.declarationCount,
};
}
function moduleInfo(catalog: Catalog, file: string): InstalledLibraryModule {
if (!catalog.moduleFiles.includes(file)) throw new WebStorageError(404, '现有 Lean 库中没有此模块。');
// The catalog reader validates every required field, including when the root TS build uses non-strict Zod inference.
const module = catalog.moduleMetadata(file) as Omit<InstalledLibraryModule, 'name' | 'area' | 'import'>;
const name = file.slice('Submission/Library/'.length, -'.lean'.length).replaceAll('/', '.');
return {
...module,
name,
area: name.split('.')[1] ?? '',
import: `import ${file.slice(0, -'.lean'.length).replaceAll('/', '.')}`,
};
}
/** The installed solver release is visible even when no researcher has published an asset. */
export function installedLibraryDirectory(
options: {
q?: string;
area?: string;
environment?: string;
offset?: number;
limit?: number;
} = {},
): InstalledLibraryDirectory {
const catalog = installedCatalog(),
all = catalog.moduleFiles.map(file => moduleInfo(catalog, file));
const tokens = (options.q ?? '').toLocaleLowerCase().trim().split(/\s+/u).filter(Boolean);
const searchData = tokens.length ? readInstalledLibrarySearchData() : undefined;
const matches = (text: string) => tokens.every(token => text.toLocaleLowerCase().includes(token));
const matchInterface = frozenLibraryQuery(options.q ?? '');
const interfaceMatches = new Map<string, InstalledLibraryModuleSummary['matchingInterfaces']>();
const rank = new Map<string, { exactInterface: boolean; moduleAlias: boolean }>();
const filtered = all
.filter(module => {
const labels = installedLibraryLabels(module.name);
if (
(options.area && !module.area.toLocaleLowerCase().includes(options.area.toLocaleLowerCase())) ||
(options.environment && options.environment !== catalog.environment)
)
return false;
const indexed =
searchData?.catalogDigest === catalog.identity.catalogDigest &&
searchData.modules[module.file]?.sha256 === module.sha256
? searchData.modules[module.file].entries
: undefined;
const matchesWithScores = tokens.length
? module.entries.flatMap(entry => {
const value = indexed?.[entry.name];
const score = value
? matchFrozenLibraryEntry(matchInterface, value, entry.name)
: matchInterface(installedLibraryInterfaceSearchText(entry, module.import), entry.name);
return score
? [
{
name: entry.name,
score,
summary: value?.summary ?? installedLibraryMathematics(entry, module.import).summary,
},
]
: [];
})
: [];
const exactInterface = matchesWithScores.some(hit => hit.score === 3);
const moduleAlias = matchesInstalledLibraryModuleAlias(module.name, options.q ?? '');
rank.set(module.file, { exactInterface, moduleAlias });
interfaceMatches.set(
module.file,
matchesWithScores
.sort((a, b) => Number(b.score === 3) - Number(a.score === 3))
.map(({ score: _score, ...entry }) => entry),
);
return (
matchesWithScores.length > 0 ||
moduleAlias ||
matches(
[
module.name,
module.file,
labels?.zh.title,
labels?.zh.description,
labels?.en.title,
labels?.en.description,
...module.declarations,
...module.entries.map(entry => `${entry.name} ${entry.type} ${entry.description}`),
]
.filter(Boolean)
.join('\n'),
)
);
})
.sort((left, right) => {
const a = rank.get(left.file)!,
b = rank.get(right.file)!;
return Number(b.exactInterface) - Number(a.exactInterface) || Number(b.moduleAlias) - Number(a.moduleAlias);
});
const offset = options.offset ?? 0,
limit = options.limit ?? 24;
const items: InstalledLibraryModuleSummary[] = filtered.slice(offset, offset + limit).map(module => {
const { entries, declarations, ...metadata } = module;
const matchingEntries = tokens.length
? entries.filter(entry => matches(`${entry.name} ${entry.type} ${entry.description}`))
: [];
const matchingInterfaces = interfaceMatches.get(module.file) ?? [];
return {
...metadata,
entryCount: entries.length,
declarationCount: declarations.length,
preview: (matchingEntries.length ? matchingEntries : entries).slice(0, 3),
matchingInterfaces: matchingInterfaces.slice(0, 3),
matchingInterfaceCount: matchingInterfaces.length,
};
});
return {
library: libraryInfo(catalog),
items,
areas: [...new Set(all.map(module => module.area))].sort(),
total: filtered.length,
offset,
limit,
...(offset + limit < filtered.length ? { nextOffset: offset + limit } : {}),
};
}
function pinnedModule(file: string, digest: string) {
const catalog = installedCatalog();
if (digest !== catalog.identity.catalogDigest)
throw new WebStorageError(409, '库版本已改变,请返回目录重新选择模块。');
return { catalog, module: moduleInfo(catalog, file) };
}
export function installedLibraryDetail(file: string, digest: string): InstalledLibraryDetail {
const { catalog, module } = pinnedModule(file, digest);
try {
const declarations = installedLibraryDeclarations(catalog.readModule(file).source, module.entries);
return { library: libraryInfo(catalog), module, ...declarations };
} catch {
throw new WebStorageError(503, '声明与定义源码读取失败或与固定版本不一致,请检查服务的库文件后重试。');
}
}
export function installedLibrarySource(file: string, digest: string): InstalledLibrarySource {
const { catalog, module } = pinnedModule(file, digest);
try {
const { source } = catalog.readModule(file);
return { library: libraryInfo(catalog), file, sourceDigest: module.sha256, source };
} catch {
throw new WebStorageError(503, '模块源码读取失败或与固定版本不一致,请检查服务的库文件后重试。');
}
}