forked from apify/crawlee-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransformDocs.js
More file actions
542 lines (458 loc) · 18.9 KB
/
transformDocs.js
File metadata and controls
542 lines (458 loc) · 18.9 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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
/* eslint-disable */
const fs = require('fs');
const { spawnSync } = require('child_process');
const moduleShortcuts = require('./module_shortcuts.json');
const path = require('path');
const REPO_ROOT_PLACEHOLDER = 'REPO_ROOT_PLACEHOLDER';
const APIFY_CLIENT_REPO_URL = 'https://github.com/apify/apify-client-python';
const APIFY_SDK_REPO_URL = 'https://github.com/apify/apify-sdk-python';
const APIFY_SHARED_REPO_URL = 'https://github.com/apify/apify-shared-python';
const CRAWLEE_PYTHON_REPO_URL = 'https://github.com/apify/crawlee-python';
const REPO_URL_PER_PACKAGE = {
'apify': APIFY_SDK_REPO_URL,
'apify_client': APIFY_CLIENT_REPO_URL,
'apify_shared': APIFY_SHARED_REPO_URL,
'crawlee': CRAWLEE_PYTHON_REPO_URL,
};
// For each package, get the installed version, and set the tag to the corresponding version
const TAG_PER_PACKAGE = {};
for (const pkg of ['apify', 'apify_client', 'apify_shared']) {
const spawnResult = spawnSync('python', ['-c', `import ${pkg}; print(${pkg}.__version__)`]);
if (spawnResult.status === 0) {
TAG_PER_PACKAGE[pkg] = `v${spawnResult.stdout.toString().trim()}`;
}
}
// For the current package, set the tag to 'master'
const thisPackagePyprojectToml = fs.readFileSync(path.join(__dirname, '..', '/pyproject.toml'), 'utf8');
const thisPackageName = thisPackagePyprojectToml.match(/^name = "(.+)"$/m)[1];
TAG_PER_PACKAGE[thisPackageName] = 'master';
// Taken from https://github.com/TypeStrong/typedoc/blob/v0.23.24/src/lib/models/reflections/kind.ts, modified
const TYPEDOC_KINDS = {
'class': {
kind: 128,
kindString: 'Class',
},
'function': {
kind: 2048,
kindString: 'Method',
},
'data': {
kind: 1024,
kindString: 'Property',
},
'enum': {
kind: 8,
kindString: 'Enumeration',
},
'enumValue': {
kind: 16,
kindString: 'Enumeration Member',
},
}
const GROUP_ORDER = [
'Classes',
'Abstract classes',
'Data structures',
'Errors',
'Functions',
'Constructors',
'Methods',
'Properties',
'Constants',
'Enumeration Members'
];
const groupSort = (g1, g2) => {
if(GROUP_ORDER.includes(g1) && GROUP_ORDER.includes(g2)){
return GROUP_ORDER.indexOf(g1) - GROUP_ORDER.indexOf(g2)
}
return g1.localeCompare(g2);
};
function getGroupName(object) {
if (object.decorations?.some(d => d.name === 'docs_group')) {
return {
groupName: object.decorations.find(d => d.name === 'docs_group')?.args.slice(2,-2),
source: 'decorator'
}
}
const groupPredicates = {
'Methods': (x) => x.kindString === 'Method',
'Constructors': (x) => x.kindString === 'Constructor',
'Properties': (x) => x.kindString === 'Property',
'Constants': (x) => x.kindString === 'Enumeration',
'Enumeration Members': (x) => x.kindString === 'Enumeration Member',
};
const groupName = Object.entries(groupPredicates).find(
([_, predicate]) => predicate(object)
)?.[0];
return { groupName, source: 'predicate' };
}
// Strips the Optional[] type from the type string, and replaces generic types with just the main type
function getBaseType(type) {
return type?.replace(/Optional\[(.*)\]/g, '$1').split('[')[0];
}
const typedocTypes = [];
function parseTypes(typedocTypes) {
fs.writeFileSync(
path.join(__dirname, 'typedoc-types.raw'),
JSON.stringify(
typedocTypes
.map(x => x.name)
.filter(x=>x)
)
);
spawnSync('python', ['parse_types.py', 'typedoc-types.raw']);
const parsedTypes = JSON.parse(
fs.readFileSync(
path.join(__dirname, 'typedoc-types-parsed.json'),
'utf8'
)
);
for (type of typedocTypes) {
const parsedType = parsedTypes[type.name];
if (parsedType) {
for (const key in parsedType) {
type[key] = parsedType[key];
}
}
}
}
// Infer the Typedoc type from the docspec type
function inferTypedocType(docspecType) {
typedocTypes.push({
name: docspecType?.replaceAll(/#.*/g, '').replaceAll('\n', '').trim() ?? docspecType,
type: 'reference',
})
return typedocTypes[typedocTypes.length - 1];
}
// Sorts the groups of a Typedoc member, and sorts the children of each group
function sortChildren(typedocMember) {
for (let group of typedocMember.groups) {
group.children
.sort((a, b) => {
const firstName = typedocMember.children.find(x => x.id === a || x.inheritedFrom?.target == a).name;
const secondName = typedocMember.children.find(x => x.id === b || x.inheritedFrom?.target == b).name;
return firstName.localeCompare(secondName);
});
}
typedocMember.groups.sort((a, b) => groupSort(a.title, b.title));
}
// Objects with decorators named 'ignore_docs' will be ignored
function isHidden(member) {
return member.decorations?.some(d => d.name === 'ignore_docs') || member.name === 'ignore_docs';
}
// Each object in the Typedoc structure has an unique ID,
// we'll just increment it for each object we convert
let oid = 1;
const symbolIdMap = [];
const contextStack = [];
const getContext = () => contextStack[contextStack.length - 1];
const popContext = () => contextStack.pop();
const newContext = (context) => contextStack.push(context);
const forwardAncestorRefs = new Map();
const backwardAncestorRefs = new Map();
function injectInheritedChildren(ancestor, descendant) {
descendant.children = descendant.children ?? [];
for (const inheritedChild of ancestor.children ?? []) {
let ownChild = descendant.children?.find((x) => x.name === inheritedChild.name);
if (!ownChild) {
const childId = oid++;
const { groupName } = getGroupName(inheritedChild);
if (!groupName) {
throw new Error(`Couldn't resolve the group name for ${inheritedChild.name} (inherited child of ${ancestor.name})`);
}
const group = descendant.groups.find((g) => g.title === groupName);
if (group) {
group.children.push(inheritedChild.id);
} else {
descendant.groups.push({
title: groupName,
children: [inheritedChild.id],
});
}
descendant.children.push({
...inheritedChild,
id: childId,
inheritedFrom: {
type: "reference",
target: inheritedChild.id,
name: `${ancestor.name}.${inheritedChild.name}`,
}
});
} else if (!ownChild.comment.summary[0].text) {
ownChild.inheritedFrom = {
type: "reference",
target: inheritedChild.id,
name: `${ancestor.name}.${inheritedChild.name}`,
}
for (let key in inheritedChild) {
if(key !== 'id' && key !== 'inheritedFrom') {
ownChild[key] = inheritedChild[key];
}
}
}
}
}
// Converts a docspec object to a Typedoc object, including all its children
function convertObject(obj, parent, module) {
const rootModuleName = module.name.split('.')[0];
for (let member of obj.members ?? []) {
let typedocKind = TYPEDOC_KINDS[member.type];
if(member.bases?.includes('Enum')) {
typedocKind = TYPEDOC_KINDS['enum'];
}
let typedocType = inferTypedocType(member.datatype);
if (member.decorations?.some(d => ['property', 'dualproperty'].includes(d.name))) {
typedocKind = TYPEDOC_KINDS['data'];
typedocType = inferTypedocType(member.return_type ?? member.datatype);
}
if(parent.kindString === 'Enumeration') {
typedocKind = TYPEDOC_KINDS['enumValue'];
typedocType = {
type: 'literal',
value: member.value,
}
}
if(member.type in TYPEDOC_KINDS && !isHidden(member)) {
// Get the URL of the member in GitHub
const repoBaseUrl = `${REPO_URL_PER_PACKAGE[rootModuleName]}/blob/${TAG_PER_PACKAGE[rootModuleName]}`;
const filePathInRepo = member.location.filename.replace(REPO_ROOT_PLACEHOLDER, '');
const fileGitHubUrl = member.location.filename.replace(REPO_ROOT_PLACEHOLDER, repoBaseUrl);
const memberGitHubUrl = `${fileGitHubUrl}#L${member.location.lineno}`;
symbolIdMap.push({
qualifiedName: member.name,
sourceFileName: filePathInRepo,
});
// Get the module name of the member, and check if it has a shortcut (reexport from an ancestor module)
const fullName = `${module.name}.${member.name}`;
let moduleName = module.name;
if (fullName in moduleShortcuts) {
moduleName = moduleShortcuts[fullName].replace(`.${member.name}`, '');
}
if (member.name === '_ActorType') {
member.name = 'Actor';
}
let docstring = { text: member.docstring?.content ?? '' };
try {
docstring = JSON.parse(docstring.text);
docstring.args = docstring.sections.find((section) => Object.keys(section)[0] === 'Arguments')['Arguments'] ?? [];
docstring.args = docstring.args.reduce((acc, arg) => {
acc[arg.param] = arg.desc;
return acc;
}, {});
docstring.returns = docstring.sections.find((section) => Object.keys(section)[0] === 'Returns')['Returns'] ?? [];
docstring.returns = docstring.returns.join('\n');
} catch {
// Do nothing
}
if (!docstring.text) {
docstring.text = getContext()?.args?.[member.name] ?? '';
}
// Create the Typedoc member object
let typedocMember = {
id: oid++,
name: member.name,
module: moduleName, // This is an extension to the original Typedoc structure, to support showing where the member is exported from
...typedocKind,
flags: {},
comment: docstring ? {
summary: [{
kind: 'text',
text: docstring.text,
}],
} : undefined,
type: typedocType,
decorations: member.decorations?.map(({ name, args }) => ({ name, args })),
children: [],
groups: [],
sources: [{
filename: filePathInRepo,
line: member.location.lineno,
character: 1,
url: memberGitHubUrl,
}],
};
if(typedocMember.kindString === 'Method') {
typedocMember.signatures = [{
id: oid++,
name: member.name,
modifiers: member.modifiers ?? [],
kind: 4096,
kindString: 'Call signature',
flags: {},
comment: docstring.text ? {
summary: [{
kind: 'text',
text: docstring?.text,
}],
blockTags: docstring?.returns ? [
{ tag: '@returns', content: [{ kind: 'text', text: docstring.returns }] },
] : undefined,
} : undefined,
type: inferTypedocType(member.return_type),
parameters: member.args.filter((arg) => (arg.name !== 'self' && arg.name !== 'cls')).map((arg) => ({
id: oid++,
name: arg.name,
kind: 32768,
kindString: 'Parameter',
flags: {
isOptional: arg.datatype?.includes('Optional') ? 'true' : undefined,
'keyword-only': arg.type === 'KEYWORD_ONLY' ? 'true' : undefined,
},
type: inferTypedocType(arg.datatype),
comment: docstring.args?.[arg.name] ? {
summary: [{
kind: 'text',
text: docstring.args[arg.name]
}]
} : undefined,
defaultValue: arg.default_value,
})),
}];
}
if(typedocMember.name === '__init__') {
typedocMember.kind = 512;
typedocMember.kindString = 'Constructor';
}
convertObject(member, typedocMember, module);
if (typedocMember.kindString === 'Class') {
newContext(docstring);
backwardAncestorRefs.set(member.name, typedocMember);
if (member.bases?.length > 0) {
member.bases.forEach((base) => {
const unwrappedBaseType = getBaseType(base);
const baseTypedocMember = backwardAncestorRefs.get(unwrappedBaseType);
if (baseTypedocMember) {
typedocMember.extendedTypes = [
...typedocMember.extendedTypes ?? [],
{
type: 'reference',
name: baseTypedocMember.name,
target: baseTypedocMember.id,
}
];
baseTypedocMember.extendedBy = [
...baseTypedocMember.extendedBy ?? [],
{
type: 'reference',
name: typedocMember.name,
target: typedocMember.id,
}
];
injectInheritedChildren(baseTypedocMember, typedocMember);
} else {
forwardAncestorRefs.set(
unwrappedBaseType,
[...(forwardAncestorRefs.get(unwrappedBaseType) ?? []), typedocMember],
);
}
});
}
}
if (typedocMember.kindString === 'Class') {
popContext();
}
const { groupName, source: groupSource } = getGroupName(typedocMember);
if (groupName) {
// Use the decorator classes everytime, but don't render the class-level groups for the root project
if (groupSource === 'decorator' || parent.kindString !== 'Project') {
const group = parent.groups.find((g) => g.title === groupName);
if (group) {
group.children.push(typedocMember.id);
} else {
parent.groups.push({
title: groupName,
children: [typedocMember.id],
});
}
}
}
parent.children.push(typedocMember);
sortChildren(typedocMember);
if (typedocMember.kindString === 'Class') {
forwardAncestorRefs.get(typedocMember.name)?.forEach((descendant) => {
descendant.extendedTypes = [
...descendant.extendedTypes ?? [],
{
type: 'reference',
name: typedocMember.name,
target: typedocMember.id,
}
];
typedocMember.extendedBy = [
...typedocMember.extendedBy ?? [],
{
type: 'reference',
name: descendant.name,
target: descendant.id,
}
]
injectInheritedChildren(typedocMember, descendant);
sortChildren(descendant);
});
}
}
}
}
// Recursively traverse a javascript POJO object, if it contains both 'name' and 'type : reference' keys, add the 'target' key
// with the corresponding id of the object with the same name
function fixRefs(obj, namesToIds) {
for (const key in obj) {
if (key === 'name' && obj?.type === 'reference' && namesToIds[obj?.name]) {
obj.target = namesToIds[obj?.name];
}
if (typeof obj[key] === 'object' && obj[key] !== null) {
fixRefs(obj[key], namesToIds);
}
}
}
function main() {
// Root object of the Typedoc structure
const typedocApiReference = {
'id': 0,
'name': 'apify-client',
'kind': 1,
'kindString': 'Project',
'flags': {},
'originalName': '',
'children': [],
'groups': [],
'sources': [
{
'fileName': 'src/index.ts',
'line': 1,
'character': 0,
'url': `http://example.com/blob/123456/src/dummy.py`,
}
]
};
// Load the docspec dump files of this module and of apify-shared
const thisPackageDocspecDump = fs.readFileSync(path.join(__dirname, 'docspec-dump.jsonl'), 'utf8');
const thisPackageModules = JSON.parse(thisPackageDocspecDump)
// Convert all the modules, store them in the root object
for (const module of thisPackageModules) {
convertObject(module, typedocApiReference, module);
};
// Runs the Python AST parser on the collected types to get rich type information
parseTypes(typedocTypes);
// Recursively fix references (collect names->ids of all the named entities and then inject those in the reference objects)
const namesToIds = {};
function collectIds(obj) {
for (const child of obj.children ?? []) {
namesToIds[child.name] = child.id;
collectIds(child);
}
}
collectIds(typedocApiReference);
fixRefs(typedocApiReference, namesToIds);
// Sort the children of the root object
sortChildren(typedocApiReference);
typedocApiReference.symbolIdMap = Object.fromEntries(Object.entries(symbolIdMap));
// Write the Typedoc structure to the output file
fs.writeFileSync(path.join(__dirname, 'api-typedoc-generated.json'), JSON.stringify(typedocApiReference, null, 4));
}
if (require.main === module) {
main();
}
module.exports = {
groupSort,
}