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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const stringify = require('./stringify');
const Types = require('./types');

const DEFAULT_OPTIONS = {
    language: 'en',
    resources: {
        en: JSON.parse(fs.readFileSync(path.join(__dirname, '../res/en.json'), 'utf8'))
    }
};

// order matters for these!
const FUNCTION_DETAILS = ['new', 'this'];
const FUNCTION_DETAILS_VARIABLES = ['functionNew', 'functionThis'];
const MODIFIERS = ['optional', 'nullable', 'repeatable'];

const TEMPLATE_VARIABLES = [
    'application',
    'codeTagClose',
    'codeTagOpen',
    'element',
    'field',
    'functionNew',
    'functionParams',
    'functionReturns',
    'functionThis',
    'keyApplication',
    'name',
    'nullable',
    'optional',
    'param',
    'prefix',
    'repeatable',
    'suffix',
    'type'
];

const FORMATS = {
    EXTENDED: 'extended',
    SIMPLE: 'simple'
};

function makeTagOpen(codeTag, codeClass) {
    let tagOpen = '';
    const tags = codeTag ? codeTag.split(' ') : [];

    tags.forEach(tag => {
        const tagClass = codeClass ? ` class="${codeClass}"` : '';

        tagOpen += `<${tag}${tagClass}>`;
    });

    return tagOpen;
}

function makeTagClose(codeTag) {
    let tagClose = '';
    const tags = codeTag ? codeTag.split(' ') : [];

    tags.reverse();
    tags.forEach(tag => {
        tagClose += `</${tag}>`;
    });

    return tagClose;
}

function reduceMultiple(context, keyName, contextName, translate, previous, current, index, items) {
    let key;

    switch (index) {
        case 0:
            key = '.first.many';
            break;

        case (items.length - 1):
            key = '.last.many';
            break;

        default:
            key = '.middle.many';
    }

    key = keyName + key;
    context[contextName] = items[index];

    return previous + translate(key, context);
}

function modifierKind(useLongFormat) {
    return useLongFormat ? FORMATS.EXTENDED : FORMATS.SIMPLE;
}

function buildModifierStrings(describer, modifiers, type, useLongFormat) {
    const result = {};

    modifiers.forEach(modifier => {
        const key = modifierKind(useLongFormat);
        const modifierStrings = describer[modifier](type[modifier]);

        result[modifier] = modifierStrings[key];
    });

    return result;
}

function addModifiers(describer, context, result, type, useLongFormat) {
    const keyPrefix = `modifiers.${modifierKind(useLongFormat)}`;
    const modifiers = buildModifierStrings(describer, MODIFIERS, type, useLongFormat);

    MODIFIERS.forEach(modifier => {
        const modifierText = modifiers[modifier] || '';

        result.modifiers[modifier] = modifierText;
        if (!useLongFormat) {
            context[modifier] = modifierText;
        }
    });

    context.prefix = describer._translate(`${keyPrefix}.prefix`, context);
    context.suffix = describer._translate(`${keyPrefix}.suffix`, context);
}

function addFunctionModifiers(describer, context, {modifiers}, type, useLongFormat) {
    const functionDetails = buildModifierStrings(describer, FUNCTION_DETAILS, type, useLongFormat);

    FUNCTION_DETAILS.forEach((functionDetail, i) => {
        const functionExtraInfo = functionDetails[functionDetail] || '';
        const functionDetailsVariable = FUNCTION_DETAILS_VARIABLES[i];

        modifiers[functionDetailsVariable] = functionExtraInfo;
        if (!useLongFormat) {
            context[functionDetailsVariable] += functionExtraInfo;
        }
    });
}

// Replace 2+ whitespace characters with a single whitespace character.
function collapseSpaces(string) {
    return string.replace(/(\s)+/g, '$1');
}

function getApplicationKey({expression}, applications) {
    if (applications.length === 1) {
        if (/[Aa]rray/.test(expression.name)) {
            return 'array';
        } else {
            return 'other';
        }
    } else if (/[Ss]tring/.test(applications[0].name)) {
        // object with string keys
        return 'object';
    } else {
        // object with non-string keys
        return 'objectNonString';
    }
}

class Result {
    constructor() {
        this.description = '';
        this.modifiers = {
            functionNew: '',
            functionThis: '',
            optional: '',
            nullable: '',
            repeatable: ''
        };
        this.returns = '';
    }
}

class Context {
    constructor(props) {
        props = props || {};

        TEMPLATE_VARIABLES.forEach(variable => {
            this[variable] = props[variable] || '';
        });
    }
}

class Describer {
    constructor(opts) {
        let options;

        this._useLongFormat = true;
        options = this._options = _.defaults(opts || {}, DEFAULT_OPTIONS);
        this._stringifyOptions = _.defaults(options, { _ignoreModifiers: true });

        // use a dictionary, not a Context object, so we can more easily merge this into Context objects
        this._i18nContext = {
            codeTagClose: makeTagClose(options.codeTag),
            codeTagOpen: makeTagOpen(options.codeTag, options.codeClass)
        };

        // templates start out as strings; we lazily replace them with template functions
        this._templates = options.resources[options.language];
        if (!this._templates) {
            throw new Error(`I18N resources are not available for the language ${options.language}`);
        }
    }

    _stringify(type, typeString, useLongFormat) {
        const context = new Context({
            type: typeString || stringify(type, this._stringifyOptions)
        });
        const result = new Result();

        addModifiers(this, context, result, type, useLongFormat);
        result.description = this._translate('type', context).trim();

        return result;
    }

    _translate(key, context) {
        let result;
        let templateFunction = _.get(this._templates, key);

        context = context || new Context();

        if (templateFunction === undefined) {
            throw new Error(`The template ${key} does not exist for the ` +
                `language ${this._options.language}`);
        }

        // compile and cache the template function if necessary
        if (typeof templateFunction === 'string') {
            // force the templates to use the `context` object
            templateFunction = templateFunction.replace(/<%= /g, '<%= context.');
            templateFunction = _.template(templateFunction, {variable: 'context'});
            _.set(this._templates, key, templateFunction);
        }

        result = (templateFunction(_.extend(context, this._i18nContext)) || '')
            // strip leading spaces
            .replace(/^\s+/, '');
        result = collapseSpaces(result);

        return result;
    }

    _modifierHelper(key, modifierPrefix = '', context) {
        return {
            extended: key ?
                this._translate(`${modifierPrefix}.${FORMATS.EXTENDED}.${key}`, context) :
                '',
            simple: key ?
                this._translate(`${modifierPrefix}.${FORMATS.SIMPLE}.${key}`, context) :
                ''
        };
    }

    _translateModifier(key, context) {
        return this._modifierHelper(key, 'modifiers', context);
    }

    _translateFunctionModifier(key, context) {
        return this._modifierHelper(key, 'function', context);
    }

    application(type, useLongFormat) {
        const applications = type.applications.slice(0);
        const context = new Context();
        const key = `application.${getApplicationKey(type, applications)}`;
        const result = new Result();

        addModifiers(this, context, result, type, useLongFormat);

        context.type = this.type(type.expression).description;
        context.application = this.type(applications.pop()).description;
        context.keyApplication = applications.length ? this.type(applications.pop()).description : '';

        result.description = this._translate(key, context).trim();

        return result;
    }

    elements(type, useLongFormat) {
        const context = new Context();
        const items = type.elements.slice(0);
        const result = new Result();

        addModifiers(this, context, result, type, useLongFormat);
        result.description = this._combineMultiple(items, context, 'union', 'element');

        return result;
    }

    new(funcNew) {
        const context = new Context({'functionNew': this.type(funcNew).description});
        const key = funcNew ? 'new' : '';

        return this._translateFunctionModifier(key, context);
    }

    nullable(nullable) {
        let key;

        switch (nullable) {
            case true:
                key = 'nullable';
                break;

            case false:
                key = 'nonNullable';
                break;

            default:
                key = '';
        }

        return this._translateModifier(key);
    }

    optional(optional) {
        const key = (optional === true) ? 'optional' : '';

        return this._translateModifier(key);
    }

    repeatable(repeatable) {
        const key = (repeatable === true) ? 'repeatable' : '';

        return this._translateModifier(key);
    }

    _combineMultiple(items, context, keyName, contextName) {
        const result = new Result();
        const self = this;
        let strings;

        strings = typeof items[0] === 'string' ?
            items.slice(0) :
            items.map(item => self.type(item).description);

        switch (strings.length) {
            case 0:
                // falls through
            case 1:
                context[contextName] = strings[0] || '';
                result.description = this._translate(`${keyName}.first.one`, context);
                break;
            case 2:
                strings.forEach((item, idx) => {
                    const key = `${keyName + (idx === 0 ? '.first' : '.last' )}.two`;

                    context[contextName] = item;
                    result.description += self._translate(key, context);
                });
                break;
            default:
                result.description = strings.reduce(reduceMultiple.bind(null, context, keyName,
                    contextName, this._translate.bind(this)), '');
        }

        return result.description.trim();
    }

    /* eslint-enable no-unused-vars */

    params(params, functionContext) {
        const context = new Context();
        const result = new Result();
        const self = this;
        let strings;

        // TODO: this hardcodes the order and placement of functionNew and functionThis; need to move
        // this to the template (and also track whether to put a comma after the last modifier)
        functionContext = functionContext || {};
        params = params || [];
        strings = params.map(param => self.type(param).description);

        if (functionContext.functionThis) {
            strings.unshift(functionContext.functionThis);
        }
        if (functionContext.functionNew) {
            strings.unshift(functionContext.functionNew);
        }
        result.description = this._combineMultiple(strings, context, 'params', 'param');

        return result;
    }

    this(funcThis) {
        const context = new Context({'functionThis': this.type(funcThis).description});
        const key = funcThis ? 'this' : '';

        return this._translateFunctionModifier(key, context);
    }

    type(type, useLongFormat) {
        let result = new Result();

        if (useLongFormat === undefined) {
            useLongFormat = this._useLongFormat;
        }
        // ensure we don't use the long format for inner types
        this._useLongFormat = false;

        if (!type) {
            return result;
        }

        switch (type.type) {
            case Types.AllLiteral:
                result = this._stringify(type, this._translate('all'), useLongFormat);
                break;
            case Types.FunctionType:
                result = this._signature(type, useLongFormat);
                break;
            case Types.NameExpression:
                result = this._stringify(type, null, useLongFormat);
                break;
            case Types.NullLiteral:
                result = this._stringify(type, this._translate('null'), useLongFormat);
                break;
            case Types.RecordType:
                result = this._record(type, useLongFormat);
                break;
            case Types.TypeApplication:
                result = this.application(type, useLongFormat);
                break;
            case Types.TypeUnion:
                result = this.elements(type, useLongFormat);
                break;
            case Types.UndefinedLiteral:
                result = this._stringify(type, this._translate('undefined'), useLongFormat);
                break;
            case Types.UnknownLiteral:
                result = this._stringify(type, this._translate('unknown'), useLongFormat);
                break;
            default:
                throw new Error(`Unknown type: ${JSON.stringify(type)}`);
        }

        return result;
    }

    _record(type, useLongFormat) {
        const context = new Context();
        let items;
        const result = new Result();

        items = this._recordFields(type.fields);

        addModifiers(this, context, result, type, useLongFormat);
        result.description = this._combineMultiple(items, context, 'record', 'field');

        return result;
    }

    _recordFields(fields) {
        const context = new Context();
        let result = [];
        const self = this;

        if (!fields.length) {
            return result;
        }

        result = fields.map(field => {
            const key = `field.${field.value ? 'typed' : 'untyped'}`;

            context.name = self.type(field.key).description;
            if (field.value) {
                context.type = self.type(field.value).description;
            }

            return self._translate(key, context);
        });

        return result;
    }

    _getHrefForString(nameString) {
        let href = '';
        const links = this._options.links;

        if (!links) {
            return href;
        }

        // accept a map or an object
        if (links instanceof Map) {
            href = links.get(nameString);
        } else if ({}.hasOwnProperty.call(links, nameString)) {
            href = links[nameString];
        }

        return href;
    }

    _addLinks(nameString) {
        const href = this._getHrefForString(nameString);
        let link = nameString;
        let linkClass = this._options.linkClass || '';

        if (href) {
            if (linkClass) {
                linkClass = ` class="${linkClass}"`;
            }

            link = `<a href="${href}"${linkClass}>${nameString}</a>`;
        }

        return link;
    }

    result(type, useLongFormat) {
        const context = new Context();
        const key = `function.${modifierKind(useLongFormat)}.returns`;
        const result = new Result();

        context.type = this.type(type).description;

        addModifiers(this, context, result, type, useLongFormat);
        result.description = this._translate(key, context);

        return result;
    }

    _signature(type, useLongFormat) {
        const context = new Context();
        const kind = modifierKind(useLongFormat);
        const result = new Result();
        let returns;

        addModifiers(this, context, result, type, useLongFormat);
        addFunctionModifiers(this, context, result, type, useLongFormat);

        context.functionParams = this.params(type.params || [], context).description;

        if (type.result) {
            returns = this.result(type.result, useLongFormat);
            if (useLongFormat) {
                result.returns = returns.description;
            } else {
                context.functionReturns = returns.description;
            }
        }

        result.description += this._translate(`function.${kind}.signature`, context).trim();

        return result;
    }
}

module.exports = (type, options) => {
    const simple = new Describer(options).type(type, false);
    const extended = new Describer(options).type(type);

    [simple, extended].forEach(result => {
        result.description = collapseSpaces(result.description.trim());
    });

    return {
        simple: simple.description,
        extended
    };
};