forked from dtao/autodoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autodoc.js
2157 lines (1906 loc) · 64 KB
/
autodoc.js
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Autodoc helps eliminate a lot of the gruntwork involved in creating a
* JavaScript project. In particular it simplifies **writing and executing
* tests**, **running performance benchmarks**, and **generating API
* documentation**.
*/
(function(context) {
var Lazy = context.Lazy,
Spiderman = context.Spiderman;
// Auto-require dependencies if they aren't already defined and we're in Node.
if (typeof Lazy === 'undefined' && typeof require === 'function') {
Lazy = require('lazy.js');
}
if (typeof Spiderman === 'undefined' && typeof require === 'function') {
Spiderman = require('spiderman');
}
/**
* An object responsible for parsing source code into an AST.
*
* @typedef {Object} Parser
* @property {function(string):*} parse
*/
/**
* @typedef {Object} ExampleHandler
* @property {RegExp} pattern
* @property {function(Array.<string>, *):*} test
*/
/**
* An object responsible for rendering HTML templates. Autodoc currently
* assumes a decidedly Mustache-like engine. Maybe someday this will be more
* abstract, with adapters and whatnot.
*
* @typedef {Object} TemplateEngine
* @property {function(string, Object):string} render
*/
/**
* All of the options Autodoc supports.
*
* @typedef {Object} AutodocOptions
* @property {Parser|function(string):*} codeParser
* @property {Parser|function(string):*} commentParser
* @property {Parser|function(string):*} markdownParser
* @property {Array.<string>} namespaces
* @property {Array.<string>} tags
* @property {string} grep
* @property {Array.<string>} javascripts
* @property {string} template
* @property {TemplateEngine} templateEngine
* @property {Object.<string, string>} templatePartials
* @property {Array.<ExampleHandler>} exampleHandlers
* @property {Object} extraOptions
*/
/**
* @constructor
* @param {AutodocOptions=} options
*/
function Autodoc(options) {
options = Lazy(options || {})
.defaults(Autodoc.options)
.toObject();
this.codeParser = wrapParser(options.codeParser);
this.commentParser = wrapParser(options.commentParser);
this.markdownParser = wrapParser(options.markdownParser, Autodoc.processInternalLinks);
this.highlighter = options.highlighter;
this.language = options.language || 'javascript';
this.compiler = options.compiler[this.language];
this.namespaces = options.namespaces || [];
this.tags = options.tags || [];
this.grep = options.grep;
this.javascripts = options.javascripts || [];
this.exampleHandlers = exampleHandlers(options.exampleHandlers);
this.template = options.template;
this.templateEngine = options.templateEngine;
this.templatePartials = options.templatePartials;
this.extraOptions = options.extraOptions || {};
this.errors = [];
if (this.highlighter) {
this.highlighter.loadMode(this.language);
}
}
Autodoc.VERSION = '0.6.3';
/**
* Default Autodoc options. (See autodoc-node.js)
*/
Autodoc.options = {};
/**
* Represents an error encountered by Autodoc.
*
* @public @typedef {Object} ErrorInfo
* @property {string} stage
* @property {string} message
* @property {number} line
*/
/**
* An object describing a library, including its namespaces and custom types
* as well as private/internal members.
*
* @public @typedef {Object} LibraryInfo
* @property {string} name
* @property {string} referenceName
* @property {string} description
* @property {string} code
* @property {Array.<NamespaceInfo>} namespaces
* @property {boolean} hasTypes
* @property {Array.<TypeInfo>} types
* @property {Array.<FunctionInfo>} privateMembers
* @property {string} exampleHelpers
* @property {Array.<ErrorInfo>} errors
*/
/**
* Creates a Autodoc instance with the specified options and uses it to
* parse the given code.
*
* @public
* @param {string} code The JavaScript code to parse.
* @param {AutodocOptions=} options
* @returns {LibraryInfo}
*/
Autodoc.parse = function(code, options) {
return new Autodoc(options).parse(code);
};
/**
* Creates a Autodoc instance with the specified options and uses it to
* generate HTML documentation from the given code.
*
* @public
* @param {LibraryInfo|string} source Either the already-parsed library data
* (from calling {@link #parse}), or the raw source code.
* @param {AutodocOptions} options
* @returns {string} The HTML for the library's API docs.
*/
Autodoc.generate = function(source, options) {
return new Autodoc(options).generate(source);
};
/**
* Parses an arbitrary blob of JavaScript code and returns an object
* containing all of the data necessary to generate a project website with
* docs, specs, and performance benchmarks.
*
* @param {string} code The JavaScript code to parse.
* @returns {LibraryInfo}
*/
Autodoc.prototype.parse = function(code) {
var autodoc = this;
// Compile the input code into something codeParser can parse. (For
// JavaScript, this should just spit the same code right back out. For
// CoffeeScript, it will compile it to JS then do a bit of post-processing
// on it to ensure our AST-traversal and doclet-grouping stuff all still
// works.)
code = this.compiler.compile(code);
// Generate the abstract syntax tree.
var ast = this.codeParser.parse(code, {
comment: true,
loc: true,
range: true
});
// This is kind of stupid... for now, I'm just assuming the library will
// have a @fileOverview tag and @name tag in the header comments.
var librarySummary = autodoc.getLibrarySummary(ast.comments);
// Extract all of the functions from the AST, and map them to their location
// in the code (this is so that we can associate each function with its
// accompanying doc comments, if any).
var functionsByLine = Lazy(Spiderman(ast).descendents())
.filter(function(node) {
return node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression';
})
.groupBy(function(node) { return node.unwrap().loc.start.line; })
.map(function(list, line) { return [line, list[0]]; })
.toObject();
// Go through all of of the comments in the AST, attempting to associate
// each with a function.
var functions = Lazy(ast.comments)
.map(function(comment) {
// Find the function right after this comment. If none exists, skip it.
var fn = functionsByLine[comment.loc.end.line + 1];
if (typeof fn === 'undefined') {
return null;
}
// Attempt to parse the comment. If it can't be parsed, or it appears to
// be basically empty, then skip it.
var doc = autodoc.parseComment(comment);
if (!doc) {
return null;
}
// This will be useful later.
comment.lines = comment.value.split('\n');
return autodoc.createFunctionInfo(fn, doc, comment, Autodoc.getFunctionSource(fn.unwrap(), code));
})
.compact()
.toArray();
// Also identify all of the comments that define custom types w/ the
// `@typedef` tag.
var typeDefs = Lazy(ast.comments)
.filter(function(comment) {
return (/@typedef\b/).test(comment.value);
})
.map(function(comment) {
var doc = autodoc.parseComment(comment);
if (typeof doc === 'undefined') {
return null;
}
if (!Lazy(doc.tags).any({ title: 'typedef' })) {
return null;
}
return autodoc.createTypeInfo(doc);
})
.compact()
.toArray();
// If no tags have been explicitly provided, but we find any occurrences of
// the @public tag, we'll use that as a hint that only those methods tagged
// @public should be included. Otherwise include everything.
if (this.tags.length === 0) {
if (Lazy(functions).any('isPublic')) {
this.tags.push('public');
}
}
// Only include documentation for functions/types with the specified tag(s),
// if provided.
if (this.tags.length > 0) {
Lazy(functions).concat(typeDefs).each(function(functionOrType) {
var hasTag = Lazy(autodoc.tags).any(function(tag) {
return Lazy(functionOrType.tags).contains(tag);
});
if (!hasTag) {
functionOrType.excludeFromDocs = true;
}
});
}
// Group by namespace so that we can keep the functions organized.
var functionsByNamespace = Lazy(functions)
.groupBy(function(fn) {
return fn.isPrivate ? '[private]' : (fn.namespace || fn.shortName);
})
.toObject();
// Only include specified namespaces, if the option has been provided.
// Otherwise use all namespaces.
if (this.namespaces.length === 0) {
this.namespaces = Object.keys(functionsByNamespace).sort();
}
var namespaces = Lazy(this.namespaces)
.map(function(namespace) {
return Autodoc.createNamespaceInfo(functionsByNamespace, namespace);
})
.toArray();
var privateMembers = Lazy(namespaces)
.map('privateMembers')
.flatten()
.reject(function(member) {
return !member.shortName;
})
.toArray();
Lazy(privateMembers).each(function(member, i) {
member.methods = Lazy(functions)
.where({ namespace: member.shortName })
.toArray();
});
// If there's a line that looks like:
//
// module.exports = Foo;
//
// ...then we'll assume 'Foo' is the "reference name" of the library; i.e.,
// the name conventionally used to refer to it within other libraries or
// applications (like _ for Underscore, $ for jQuery, and so on).
var nameFromModuleExports = Lazy(Spiderman(ast).descendents())
.map(Autodoc.getModuleExportsIdentifier)
.compact()
.first();
var referenceName = nameFromModuleExports;
// If not, we'll guess that the first "namespace" that actually has members
// is probably the conventional name.
if (!referenceName) {
var firstNonEmptyNamespace = Lazy(namespaces)
.find(function(namespace) {
return namespace.members.length > 0;
});
referenceName = firstNonEmptyNamespace ?
firstNonEmptyNamespace.namespace.split('.').shift() :
null;
}
// See if there's a comment somewhere w/ the @exampleHelpers tag; if so,
// we'll supply that code to all examples.
var exampleHelpers = Lazy(ast.comments)
.filter(function(comment) {
return (/@exampleHelpers\b/).test(comment.value);
})
.map(function(comment) {
var doc = autodoc.parseComment(comment);
if (typeof doc === 'undefined') {
return null;
}
return Autodoc.getTagDescriptions(doc, 'exampleHelpers');
})
.flatten()
.compact()
.first() || '';
// TODO: Make this code a little more agnostic about the whole namespace
// thing. I'm pretty sure there are plenty of libraries that don't use
// this pattern at all.
return {
name: librarySummary.name || referenceName,
referenceName: referenceName,
description: librarySummary.description,
code: code,
namespaces: namespaces,
docs: functions,
privateMembers: privateMembers,
hasTypes: !Lazy(typeDefs).all('excludeFromDocs'),
types: typeDefs,
exampleHelpers: exampleHelpers,
errors: this.errors
};
};
/**
* Generates HTML for the API docs for the given library (as raw source code)
* using the specified options, including templating library.
*
* @param {LibraryInfo|string} source Either the already-parsed library data
* (from calling {@link #parse}), or the raw source code.
* @returns {string} The HTML for the library's API docs.
*/
Autodoc.prototype.generate = function(source) {
var libraryInfo = typeof source === 'string' ?
this.parse(source) :
source;
// Decorate examples w/ custom handlers so that the template can be
// populated differently for them.
this.updateExamples(libraryInfo);
// Additional stuff we want to tack on.
libraryInfo.javascripts = this.javascripts;
// If the grep option was provided, filter out all methods not matching the
// specified pattern.
var grep = this.grep;
if (grep) {
grep = new RegExp(grep);
Lazy(libraryInfo.namespaces).each(function(namespace) {
namespace.allMembers = Lazy(namespace.allMembers)
.filter(function(member) {
return grep.test(member.name);
})
.toArray();
namespace.hasExamples = Lazy(namespace.allMembers).any('hasExamples');
});
libraryInfo.docs = Lazy(libraryInfo.docs)
.filter(function(member) {
return grep.test(member.name)
})
.toArray();
}
// Allow for arbitrary additional options, e.g. if the user wants to use
// a custom template.
var templateData = Lazy(libraryInfo)
.extend(this.extraOptions)
.toObject();
// Finally pass our awesomely-finessed data to the template engine,
// e.g., Mustache.
return this.templateEngine.render(this.template, templateData, this.templatePartials);
};
/**
* Iterates over all of the examples in the library and applies a callback to
* each, along with its associated function name.
*
* @param {LibraryInfo} libraryInfo
* @param {function(ExampleInfo, string):*} callback
*/
Autodoc.prototype.eachExample = function(libraryInfo, callback) {
Lazy(libraryInfo.docs)
.each(function(doc) {
Lazy(doc.examples).pluck('list').flatten().each(function(example) {
callback(example, doc.name);
});
});
};
/**
* Iterates over all of the examples in the library and tests whether each
* should be handled by a custom handler. If so, marks it as such for
* consumption by e.g. a template or a test runner.
*
* @param {LibraryInfo} libraryInfo
*/
Autodoc.prototype.updateExamples = function(libraryInfo) {
// Allow a library to provide a config.js file, which should define an array
// of handlers like:
//
// [
// { pattern: /regex/, test: function(match, actual) },
// { pattern: /regex/, test: function(match, actual) },
// ...
// ]
//
var exampleHandlers = this.exampleHandlers;
if (exampleHandlers.length === 0) {
return;
}
var templateEngine = this.templateEngine,
templatePartials = this.templatePartials,
codeParser = this.codeParser;
var brokenExamples = [];
this.eachExample(libraryInfo, function(example) {
// Look at all of our examples. Those that are matched by some handler, we
// will leave to be verified by handler.test, which will obviously need to
// be available in the output HTML (bin/autodoc ensures this).
var matchingHandler = Lazy(exampleHandlers).any(function(handler, i) {
var match = example.expected.match(handler.pattern),
data;
if (match) {
if (typeof handler.template === 'string') {
if (!(handler.template in templatePartials)) {
throw 'Template "' + handler.template + '" not defined.';
}
data = { match: match };
if (typeof handler.data === 'function') {
data = handler.data(match);
// Yes, this could potentially override a property like
// 'whateverEscaped'... I don't care about that right now. Easy to
// fix later.
Lazy(Object.keys(data)).each(function(key) {
data[key + 'Escaped'] = Autodoc.escapeJsString(data[key]);
});
}
example.exampleSource = templateEngine.render(
templatePartials[handler.template],
Lazy(example).extend(data).toObject()
) || '// pending';
} else {
throw 'Custom example handlers must provide a template name.';
}
// Exit early -- we found our handler!
return true;
}
});
if (!matchingHandler) {
// In case there's no custom handler defined for this example, let's
// ensure that it's at least valid JavaScript. If not, that's a good
// indicator there SHOULD be a custom handler defined for it!
try {
codeParser.parse(
example.statement + '\n' +
'var expected = ' + example.expected
);
} catch (e) {
brokenExamples.push({
example: example,
error: e
});
}
}
});
if (brokenExamples.length > 0) {
console.error("\n\x1B[33mThe following examples don't match any custom handlers, " +
"and they aren't valid JavaScript:\x1B[39m\n");
Lazy(brokenExamples).each(function(data) {
var example = data.example,
error = data.error;
var offendingLine = error.lineNumber;
console.error(withLineNumbers(example.actual + '\n' + example.expected,
example.absoluteLine, offendingLine));
error = String(error).replace(/Line (\d+)/, function(match, number) {
return 'Line ' + (Number(number) + example.absoluteLine - 1);
});
console.error('\x1B[31m' + error + '\x1B[39m');
// Mark the example as broken so we don't run it.
example.broken = true;
});
console.error("\nYou can define custom handlers in a 'handlers.js' file " +
"(or specify with the --handlers option), like this:\n");
console.error([
'this.exampleHandlers = [',
' {',
' pattern: /pattern to match/',
' template: "name of template"',
' }',
' ...',
'];'
].join('\n'));
console.error('\nSee the README at ' +
'\x1B[36mhttps://github.com/dtao/autodoc/blob/master/README.md\x1B[39m ' +
'for more details.\n');
}
};
/**
* @public
* @typedef {Object} FunctionInfo
* @property {string} name
* @property {string} description
* @property {boolean} isConstructor
* @property {boolean} isStatic
* @property {boolean} isPublic
* @property {boolean} isPrivate
* @property {boolean} hasSignature
* @property {string} signature
* @property {string} highlightedSignature
* @property {boolean} hasExamples
* @property {boolean} hasBenchmarks
* @property {Array.<ParameterInfo>} params
* @property {Array.<ReturnInfo>} returns
* @property {ExampleCollection} examples
* @property {BenchmarkCollection} benchmarks
* @property {Array.<string>} tags
* @property {string} source
* @property {string} highlightedSource
*/
/**
* Takes a function node from the AST along with its associated doclet (from
* parsing its comments) and generates an object with boatloads of data on it,
* useful for passing to a templating system such as Mustache.
*
* @param {Object} fn
* @param {Object} doc
* @param {Object} comment
* @param {string} source
* @returns {FunctionInfo}
*/
Autodoc.prototype.createFunctionInfo = function(fn, doc, comment, source) {
var nameInfo = Autodoc.parseName(fn.inferName() || '', doc),
description = this.parseMarkdown(doc.description),
params = this.getParams(doc),
returns = this.getReturns(doc),
aliases = this.getAliases(doc),
isCtor = Autodoc.hasTag(doc, 'constructor'),
isStatic = nameInfo.name.indexOf('#') === -1, // That's right, hacky smacky
isPublic = Autodoc.hasTag(doc, 'public'),
isGlobal = fn.parent.type === 'Program',
isPrivate = Autodoc.hasTag(doc, 'private'),
signature = Autodoc.getSignature(nameInfo, params),
examples = this.getExamples(doc, comment),
benchmarks = this.getBenchmarks(doc, comment),
tags = Lazy(doc.tags).pluck('title').toArray();
// Do you guys know what I'm talking about? I don't. -Mitch Hedberg
if (nameInfo.name !== nameInfo.shortName) {
source = nameInfo.namespace + '.' + nameInfo.shortName + ' = ' + source;
}
return {
name: nameInfo.name,
shortName: nameInfo.shortName,
longName: nameInfo.longName,
lowerCaseName: nameInfo.shortName.toLowerCase(),
searchName: hyphenate(nameInfo.shortName),
acronym: acronym(nameInfo.name),
identifier: nameInfo.identifier,
namespace: nameInfo.namespace,
description: description,
params: params,
returns: returns,
aliases: aliases,
isConstructor: isCtor,
isGlobal: isGlobal,
isStatic: isStatic,
isPublic: isPublic,
isPrivate: isPrivate,
hasSignature: params.length > 0 || !!returns,
signature: signature,
highlightedSignature: insertSignatureLink(this.highlightCode(signature), nameInfo.identifier),
examples: examples,
hasExamples: examples.length > 0,
benchmarks: benchmarks,
hasBenchmarks: benchmarks.length > 0,
tags: tags,
source: source,
highlightedSource: this.highlightCode(source)
};
};
/**
* @typedef {Object} ParameterInfo
* @public
* @property {string} name
* @property {string} type
* @property {string} description
*/
/**
* Gets an array of { name, type, description } objects representing the
* parameters of a function definition.
*
* @param {Object} doc The doclet for the function.
* @param {string=} tagName The name of the tag to find (default: 'param').
* @returns {Array.<ParameterInfo>} An array of { name, type, description }
* objects.
*/
Autodoc.prototype.getParams = function(doc, tagName) {
var self = this;
return Lazy(doc.tags)
.where({ title: tagName || 'param' })
.map(function(tag) {
return {
name: tag.name,
type: Autodoc.formatType(tag.type),
description: self.parseMarkdown(tag.description || '')
};
})
.toArray();
};
/**
* @typedef {Object} ReturnInfo
* @property {string} type
* @property {string} description
*/
/**
* Get a { type, description } object representing the return value of a
* function definition.
*
* @param {Object} doc The doclet for the function.
* @returns {ReturnInfo} A { type, description } object.
*/
Autodoc.prototype.getReturns = function(doc) {
var returnTag = Lazy(doc.tags).findWhere({ title: 'returns' });
if (typeof returnTag === 'undefined') {
return null;
}
return {
type: Autodoc.formatType(returnTag.type),
description: this.parseMarkdown(returnTag.description || '')
};
};
/**
* Gets an array of strings providing the aliases for the function definition.
*
* @param {Object} doc The doclet for the function.
* @returns {Array.<string>} An array of strings representing the function's
* aliases.
*/
Autodoc.prototype.getAliases = function(doc, tagName) {
var akaTag = Lazy(doc.tags).findWhere({ title: 'aka' });
if (typeof akaTag === 'undefined' || !akaTag.description) {
return [];
}
return akaTag.description.split(/\s*,\s*/);
};
/**
* A custom type defined by a library.
*
* @typedef {object} TypeInfo
* @public
* @property {string} name
* @property {string} description
* @property {Array.<PropertyInfo>} properties
* @property {Array.<string>} tags
*/
/**
* A property of a type defined by a {@link TypeInfo} object.
*
* @typedef {Object} PropertyInfo
* @public
* @property {string} name
* @property {string} type
* @property {string} description
*/
/**
* Get a { name, properties } object representing a type defined w/ the
* `@typedef` tag.
*/
Autodoc.prototype.createTypeInfo = function(doc) {
var description = doc.description,
names = Autodoc.getTagDescriptions(doc, 'typedef')
properties = this.getParams(doc, 'property'),
tags = Lazy(doc.tags).pluck('title').toArray();
var name = names[0] || '';
return {
name: name,
identifier: 'type-' + name,
lowerCaseName: name.toLowerCase(),
searchName: hyphenate(name),
acronym: acronym(name),
description: this.parseMarkdown(description),
properties: properties,
tags: tags
};
};
/**
* High-level info about a library, namely its name and a brief description.
*
* @typedef {Object} LibrarySummary
* @property {string} name
* @property {string} description
*/
/**
* Returns a { name, description } object describing an entire library.
*
* @param {Array.<string>} comments
* @returns {LibrarySummary}
*/
Autodoc.prototype.getLibrarySummary = function(comments) {
var autodoc = this;
var docs = Lazy(comments)
.map(function(comment) {
return autodoc.parseComment(comment);
})
.compact()
.toArray();
var docWithFileOverview = Lazy(docs)
.filter(function(doc) {
return Lazy(doc.tags).where({ title: 'fileOverview' }).any();
})
.first();
var libraryNameTag,
libraryName = '',
libraryDesc = '';
if (docWithFileOverview) {
libraryDesc = Lazy(docWithFileOverview.tags).findWhere({ title: 'fileOverview' }).description;
libraryNameTag = Lazy(docWithFileOverview.tags).findWhere({ title: 'name' });
if (libraryNameTag) {
libraryName = libraryNameTag.description;
}
} else if (docs.length > 0) {
libraryNameTag = Lazy(docs[0].tags).findWhere({ title: 'name' });
if (libraryNameTag) {
libraryName = libraryNameTag.description;
}
libraryDesc = docs[0].description;
}
return {
name: libraryName,
description: this.parseMarkdown(libraryDesc)
};
};
/**
* Parses a comment.
*
* @param {Object} comment The comment to parse.
* @returns {Object?}
*/
Autodoc.prototype.parseComment = function(comment) {
var value = comment.value;
// I think I'm going crazy? For some reason I was originally wrapping
// comments in /* and */ before parsing them with doctrine. Now it seems
// that was never necessary and, in fact, just introduced ugliness with
// CoffeeScript. So I'm completely reversing course, and REMOVING these
// strings instead of introducing them. Seems to fix the issue.
value = value.replace(/^\s*\/\*|\*\/\s*$/g, '');
try {
return this.commentParser.parse(value, { unwrap: true, lineNumbers: true });
} catch (e) {
this.errors.push({
stage: 'parsing comment',
line: comment.loc.start.line,
message: String(e.message || e)
});
return null;
}
};
/**
* Represents a single code example illustrating how a function works,
* including an expectation as well as an actual (relative) source location.
*
* @typedef {Object} ExampleInfo
* @public
* @property {number} id
* @property {number} relativeLine
* @property {number} absoluteLine
* @property {string} actual
* @property {string} actualEscaped
* @property {string} expected
* @property {string} expectedEscaped
*/
/**
* A collection of {@link ExampleInfo} objects, with an optional block of
* setup code and some additional properties.
*
* @typedef {Object} ExampleCollection
* @public
* @property {string} code
* @property {string} highlightedCode
* @property {string} setup
* @property {Array.<ExampleInfo>} list
*/
/**
* Produces a { setup, examples } object providing some examples of a function.
*
* @param {Object} doc
* @returns {ExampleCollection}
*/
Autodoc.prototype.getExamples = function(doc, comment) {
var self = this,
exampleIdCounter = 1;
return this.parseCommentLines(doc, comment.lines, ['examples', 'example'], function(data) {
return {
code: data.content,
highlightedCode: self.highlightCode(data.content),
setup: self.compileSnippet(data.preamble),
list: Lazy(data.pairs).map(function(pair) {
// Snip out any leading 'var x = ' before the actual expression.
// Why? Because this is going to get injected into a template, and
// we don't want to have 'var result = var x = '.
//
// To be fair, there's probably a better approach. I'll leave figuring
// that out as an exercise to my future self.
var actual = pair.left,
expected = pair.right,
variable = extractVar(pair.left) || 'actual',
statement = 'var ' + variable + ' = ' + removeVar(actual);
return {
id: exampleIdCounter++,
relativeLine: pair.lineNumber,
absoluteLine: comment.loc.start.line + data.lineNumber + pair.lineNumber,
actual: self.compileSnippet(actual),
actualEscaped: Autodoc.escapeJsString(actual),
expected: expected,
expectedEscaped: Autodoc.escapeJsString(expected),
variable: variable,
statement: statement
};
}).toArray()
};
});
};
/**
* Represents a single benchmark case.
*
* @typedef {Object} BenchmarkCase
* @public
* @property {number} caseId
* @property {string} impl
* @property {string} name
* @property {string} label
*/
/**
* Represents a performance benchmark, which should illustrate a single piece
* of functionality with one or more *cases* to compare different
* implementations.
*
* @typedef {Object} BenchmarkInfo
* @public
* @property {number} id
* @property {string} name
* @property {Array.<BenchmarkCase>} cases
*/
/**
* A collection of {@link BenchmarkInfo} objects, each of which illustrates a
* single piece of functionality with one or more cases each.
*
* @typedef {Object} BenchmarkCollection
* @public
* @property {string} code
* @property {string} highlightedCode
* @property {string} setup
* @property {Array.<BenchmarkInfo>} list
*/
/**
* Produces a { setup, benchmarks } object providing some benchmarks for a function.
*
* @param {Object} doc
* @param {Object} comment
* @returns {BenchmarkCollection}
*/
Autodoc.prototype.getBenchmarks = function(doc, comment) {
var self = this,
benchmarkCaseIdCounter = 1,
benchmarkIdCounter = 1;
return this.parseCommentLines(doc, comment.lines, 'benchmarks', function(data) {
var benchmarks = Lazy(data.pairs)
.map(function(pair) {
var parts = divide(pair.right, ' - ');
return {
caseId: benchmarkCaseIdCounter++,
impl: self.compileSnippet(pair.left),
name: parts[0],
label: parts[1] || 'Ops/second'
};
})
.groupBy('name')
.map(function(cases, name) {
return {
id: benchmarkIdCounter++,
name: name,
cases: cases
}
})
.toArray();
return {
code: data.content,
highlightedCode: self.highlightCode(data.content),
setup: self.compileSnippet(data.preamble),
list: benchmarks,
cases: benchmarks.length > 0 ? benchmarks[0].cases : []
};
});
};
/**
* Does syntax highlighting on a bit of code.
*/
Autodoc.prototype.highlightCode = function(code) {