-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdocs.ts
346 lines (323 loc) · 9.16 KB
/
docs.ts
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
/** Functions related to documenting modules.
*
* @module
*/
import type { LoadResponse } from "deno_graph";
import {
Datastore,
entityToObject,
objectSetKey,
objectToEntity,
} from "google_datastore";
import type { Mutation } from "google_datastore/types";
import * as JSONC from "jsonc-parser";
import { getAnalysis } from "./analysis.ts";
import { getDatastore } from "./auth.ts";
import { cacheInfoPage, lookup } from "./cache.ts";
import { kinds } from "./consts.ts";
import { loadModule } from "./modules.ts";
import { enqueue } from "./process.ts";
import type {
InfoPage,
ModInfoPage,
Module,
ModuleEntry,
ModuleVersion,
PageInvalidVersion,
} from "./types.d.ts";
import { assert } from "./util.ts";
/** Used only in APIland to represent a module without any exported symbols in
* the datastore.
*/
export interface DocNodeNull {
kind: "null";
}
export interface LegacyIndex {
name: string;
description: string;
version: string;
uploaded_at: string;
upload_options: {
type: string;
repository: string;
ref: string;
};
files: ModuleEntry[];
}
interface ConfigFileJson {
importMap?: string;
imports?: Record<string, string>;
}
const MAX_CACHE_SIZE = parseInt(Deno.env.get("MAX_CACHE_SIZE") ?? "", 10) ||
25_000_000;
const cachedSpecifiers = new Set<string>();
const cachedResources = new Map<string, LoadResponse | undefined>();
let cacheCheckQueued = false;
let cacheSize = 0;
const DENO_LAND_X = new URLPattern(
"https://deno.land/x/:mod@:ver/:path*",
);
const DENO_LAND_STD = new URLPattern("https://deno.land/std@:ver/:path*");
export async function load(
specifier: string,
): Promise<LoadResponse | undefined> {
if (cachedResources.has(specifier)) {
cachedSpecifiers.delete(specifier);
cachedSpecifiers.add(specifier);
return cachedResources.get(specifier);
}
try {
let cdnSpecifier: string | undefined;
const matchStd = DENO_LAND_STD.exec(specifier);
if (matchStd) {
const { ver, path } = matchStd.pathname.groups;
cdnSpecifier = `https://cdn.deno.land/std/versions/${ver}/raw/${path}`;
} else {
const matchX = DENO_LAND_X.exec(specifier);
if (matchX) {
const { mod, ver, path } = matchX.pathname.groups;
cdnSpecifier =
`https://cdn.deno.land/${mod}/versions/${ver}/raw/${path}`;
}
}
const url = new URL(cdnSpecifier ?? specifier);
if (url.protocol === "http:" || url.protocol === "https:") {
const response = await fetch(url, { redirect: "follow" });
if (response.status !== 200) {
cachedResources.set(specifier, undefined);
cachedSpecifiers.add(specifier);
await response.arrayBuffer();
return undefined;
}
const content = await response.text();
const headers: Record<string, string> = {};
for (const [key, value] of response.headers) {
headers[key.toLowerCase()] = value;
}
const loadResponse: LoadResponse = {
kind: "module",
specifier: cdnSpecifier ? specifier : response.url,
headers,
content,
};
cachedResources.set(specifier, loadResponse);
cachedSpecifiers.add(specifier);
cacheSize += content.length;
enqueueCheck();
return loadResponse;
} else if (url.protocol === "node:" || url.protocol === "npm:") {
return {
kind: "external",
specifier,
};
}
} catch {
cachedResources.set(specifier, undefined);
cachedSpecifiers.add(specifier);
}
}
function checkCache() {
if (cacheSize > MAX_CACHE_SIZE) {
const toEvict: string[] = [];
for (const specifier of cachedSpecifiers) {
const loadResponse = cachedResources.get(specifier);
toEvict.push(specifier);
if (loadResponse && loadResponse.kind === "module") {
cacheSize -= loadResponse.content.length;
if (cacheSize <= MAX_CACHE_SIZE) {
break;
}
}
}
console.log(
`%cEvicting %c${toEvict.length}%c responses from cache.`,
"color:green",
"color:yellow",
"color:none",
);
for (const evict of toEvict) {
cachedResources.delete(evict);
cachedSpecifiers.delete(evict);
}
}
cacheCheckQueued = false;
}
function enqueueCheck() {
if (!cacheCheckQueued) {
cacheCheckQueued = true;
queueMicrotask(checkCache);
}
}
const CONFIG_FILES = ["deno.jsonc", "deno.json"] as const;
/** Given a module and version, attempt to resolve an import map specifier from
* a Deno configuration file. If none can be resolved, `undefined` is
* resolved. */
export async function getImportMapSpecifier(
module: string,
version: string,
): Promise<string | undefined> {
let result;
for (const configFile of CONFIG_FILES) {
result = await load(
`https://deno.land/x/${module}@${version}/${configFile}`,
);
if (result) {
break;
}
}
if (result?.kind === "module") {
const { specifier, content } = result;
const configFileJson: ConfigFileJson | undefined = JSONC.parse(content);
if (configFileJson) {
if (configFileJson.imports) {
return new URL(specifier).toString();
} else if (configFileJson.importMap) {
return new URL(configFileJson.importMap, specifier).toString();
}
}
return undefined;
}
}
function getPageInvalidVersion(
{ name: module, description, versions, latest_version }: Module,
): PageInvalidVersion {
assert(
latest_version,
"Assertion failed for " + JSON.stringify({ module, versions }),
);
return {
kind: "invalid-version",
module,
description,
versions,
latest_version,
};
}
let datastore: Datastore | undefined;
export async function getModuleEntries(
module: string,
version: string,
): Promise<ModuleEntry[]> {
datastore = datastore || await getDatastore();
const query = datastore
.createQuery(kinds.MODULE_ENTRY_KIND)
.hasAncestor(datastore.key(
[kinds.MODULE_KIND, module],
[kinds.MODULE_VERSION_KIND, version],
));
const entries: ModuleEntry[] = [];
for await (const entity of datastore.streamQuery(query)) {
entries.push(entityToObject(entity));
}
return entries;
}
function getDefaultModule(entries: ModuleEntry[]): ModuleEntry | undefined {
const root = entries.find(({ path, type }) => path === "/" && type === "dir");
const defModule = root?.default;
if (defModule) {
return entries.find(({ path, type }) =>
path === defModule && type === "file"
);
}
}
function getConfig(entries: ModuleEntry[]): ModuleEntry | undefined {
return entries.find(({ type, path }) =>
type === "file" && /^\/deno\.jsonc?$/i.test(path)
);
}
function getReadme(entries: ModuleEntry[]): ModuleEntry | undefined {
return entries.find(({ type, path }) =>
type === "file" && /^\/README(\.(md|txt|markdown))?$/i.test(path)
);
}
async function getModInfoPage(
moduleItem: Module,
moduleVersion: ModuleVersion,
entries: ModuleEntry[],
): Promise<ModInfoPage> {
const {
name: module,
description,
latest_version,
tags,
versions,
} = moduleItem;
assert(latest_version);
const { uploaded_at, upload_options, version } = moduleVersion;
const defaultModule = getDefaultModule(entries);
const config = getConfig(entries);
const readme = getReadme(entries);
const [dependencies, dependency_errors] = await getAnalysis(
moduleItem,
moduleVersion,
);
return {
kind: "modinfo",
module,
description,
dependencies,
dependency_errors,
version,
versions,
latest_version,
defaultModule,
readme,
config,
uploaded_at: uploaded_at.toISOString(),
upload_options,
tags,
};
}
export async function generateInfoPage(
module: string,
version: string,
): Promise<InfoPage | undefined> {
let [moduleItem, moduleVersion] = await lookup(module, version);
let moduleEntries: ModuleEntry[] | undefined;
if (
!moduleItem || (!moduleVersion && moduleItem.versions.includes(version))
) {
let mutations: Mutation[];
try {
[
mutations,
moduleItem,
moduleVersion,
,
,
moduleEntries,
] = await loadModule(module, version);
enqueue({ kind: "commitMutations", mutations });
} catch (e) {
console.log("error loading module", e);
return undefined;
}
}
if (!moduleVersion) {
assert(moduleItem);
return getPageInvalidVersion(moduleItem);
}
if (!moduleItem.latest_version) {
return { kind: "no-versions", module: moduleItem.name };
}
moduleEntries = moduleEntries || await getModuleEntries(module, version);
const infoPage = await getModInfoPage(
moduleItem,
moduleVersion,
moduleEntries,
);
datastore = datastore || await getDatastore();
objectSetKey(
infoPage,
datastore.key([kinds.MODULE_KIND, module], ["info_page", version]),
);
const mutations: Mutation[] = [{ upsert: objectToEntity(infoPage) }];
enqueue({ kind: "commitMutations", mutations });
cacheInfoPage(module, version, infoPage);
return infoPage;
}
/** Determines if a file path can be doc'ed or not. */
export function isDocable(path: string): boolean {
return /\.(ts|tsx|js|jsx|mjs|cjs|mts|cts)$/i.test(path);
}