summaryrefslogtreecommitdiff
path: root/lib/Inline.js
blob: b3995fa5f62d459148de8e3efd3ca4db79615bc5 (plain)
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
// Generated by CoffeeScript 2.4.1
var DumpException, Escaper, Inline, ParseException, ParseMore, Pattern, Unescaper, Utils,
  indexOf = [].indexOf;

Pattern = require('./Pattern');

Unescaper = require('./Unescaper');

Escaper = require('./Escaper');

Utils = require('./Utils');

ParseException = require('./Exception/ParseException');

ParseMore = require('./Exception/ParseMore');

DumpException = require('./Exception/DumpException');

Inline = (function() {
  // Inline YAML parsing and dumping
  class Inline {
    // Configure YAML inline.

    // @param [Boolean]  exceptionOnInvalidType  true if an exception must be thrown on invalid types (a JavaScript resource or object), false otherwise
    // @param [Function] objectDecoder           A function to deserialize custom objects, null otherwise

    static configure(exceptionOnInvalidType = null, objectDecoder = null) {
      // Update settings
      this.settings.exceptionOnInvalidType = exceptionOnInvalidType;
      this.settings.objectDecoder = objectDecoder;
    }

    // Converts a YAML string to a JavaScript object.

    // @param [String]   value                   A YAML string
    // @param [Boolean]  exceptionOnInvalidType  true if an exception must be thrown on invalid types (a JavaScript resource or object), false otherwise
    // @param [Function] objectDecoder           A function to deserialize custom objects, null otherwise

    // @return [Object]  A JavaScript object representing the YAML string

    // @throw [ParseException]

    static parse(value, exceptionOnInvalidType = false, objectDecoder = null) {
      var context, result;
      // Update settings from last call of Inline.parse()
      this.settings.exceptionOnInvalidType = exceptionOnInvalidType;
      this.settings.objectDecoder = objectDecoder;
      if (value == null) {
        return '';
      }
      value = Utils.trim(value);
      if (0 === value.length) {
        return '';
      }
      // Keep a context object to pass through static methods
      context = {
        exceptionOnInvalidType,
        objectDecoder,
        i: 0
      };
      switch (value.charAt(0)) {
        case '[':
          result = this.parseSequence(value, context);
          ++context.i;
          break;
        case '{':
          result = this.parseMapping(value, context);
          ++context.i;
          break;
        default:
          result = this.parseScalar(value, null, ['"', "'"], context);
      }
      // Some comments are allowed at the end
      if (this.PATTERN_TRAILING_COMMENTS.replace(value.slice(context.i), '') !== '') {
        throw new ParseException('Unexpected characters near "' + value.slice(context.i) + '".');
      }
      return result;
    }

    // Dumps a given JavaScript variable to a YAML string.

    // @param [Object]   value                   The JavaScript variable to convert
    // @param [Boolean]  exceptionOnInvalidType  true if an exception must be thrown on invalid types (a JavaScript resource or object), false otherwise
    // @param [Function] objectEncoder           A function to serialize custom objects, null otherwise

    // @return [String]  The YAML string representing the JavaScript object

    // @throw [DumpException]

    static dump(value, exceptionOnInvalidType = false, objectEncoder = null) {
      var ref, result, type;
      if (value == null) {
        return 'null';
      }
      type = typeof value;
      if (type === 'object') {
        if (value instanceof Date) {
          return value.toISOString();
        } else if (objectEncoder != null) {
          result = objectEncoder(value);
          if (typeof result === 'string' || (result != null)) {
            return result;
          }
        }
        return this.dumpObject(value);
      }
      if (type === 'boolean') {
        return (value ? 'true' : 'false');
      }
      if (Utils.isDigits(value)) {
        return (type === 'string' ? "'" + value + "'" : String(parseInt(value)));
      }
      if (Utils.isNumeric(value)) {
        return (type === 'string' ? "'" + value + "'" : String(parseFloat(value)));
      }
      if (type === 'number') {
        return (value === 2e308 ? '.Inf' : (value === -2e308 ? '-.Inf' : (isNaN(value) ? '.NaN' : value)));
      }
      if (Escaper.requiresDoubleQuoting(value)) {
        return Escaper.escapeWithDoubleQuotes(value);
      }
      if (Escaper.requiresSingleQuoting(value)) {
        return Escaper.escapeWithSingleQuotes(value);
      }
      if ('' === value) {
        return '""';
      }
      if (Utils.PATTERN_DATE.test(value)) {
        return "'" + value + "'";
      }
      if ((ref = value.toLowerCase()) === 'null' || ref === '~' || ref === 'true' || ref === 'false') {
        return "'" + value + "'";
      }
      // Default
      return value;
    }

    static dumpObject(value, exceptionOnInvalidType, objectSupport = null) {
      var j, key, len1, output, val;
      // Array
      if (value instanceof Array) {
        output = [];
        for (j = 0, len1 = value.length; j < len1; j++) {
          val = value[j];
          output.push(this.dump(val));
        }
        return '[' + output.join(', ') + ']';
      } else {
        // Mapping
        output = [];
        for (key in value) {
          val = value[key];
          output.push(this.dump(key) + ': ' + this.dump(val));
        }
        return '{' + output.join(', ') + '}';
      }
    }

    // Parses a scalar to a YAML string.

    // @param [Object]   scalar
    // @param [Array]    delimiters
    // @param [Array]    stringDelimiters
    // @param [Object]   context
    // @param [Boolean]  evaluate

    // @return [String]  A YAML string

    // @throw [ParseException] When malformed inline YAML string is parsed

    static parseScalar(scalar, delimiters = null, stringDelimiters = ['"', "'"], context = null, evaluate = true) {
      var i, joinedDelimiters, match, output, pattern, ref, ref1, strpos, tmp;
      if (context == null) {
        context = {
          exceptionOnInvalidType: this.settings.exceptionOnInvalidType,
          objectDecoder: this.settings.objectDecoder,
          i: 0
        };
      }
      ({i} = context);
      if (ref = scalar.charAt(i), indexOf.call(stringDelimiters, ref) >= 0) {
        // Quoted scalar
        output = this.parseQuotedScalar(scalar, context);
        ({i} = context);
        if (delimiters != null) {
          tmp = Utils.ltrim(scalar.slice(i), ' ');
          if (!(ref1 = tmp.charAt(0), indexOf.call(delimiters, ref1) >= 0)) {
            throw new ParseException('Unexpected characters (' + scalar.slice(i) + ').');
          }
        }
      } else {
        // "normal" string
        if (!delimiters) {
          output = scalar.slice(i);
          i += output.length;
          // Remove comments
          strpos = output.indexOf(' #');
          if (strpos !== -1) {
            output = Utils.rtrim(output.slice(0, strpos));
          }
        } else {
          joinedDelimiters = delimiters.join('|');
          pattern = this.PATTERN_SCALAR_BY_DELIMITERS[joinedDelimiters];
          if (pattern == null) {
            pattern = new Pattern('^(.+?)(' + joinedDelimiters + ')');
            this.PATTERN_SCALAR_BY_DELIMITERS[joinedDelimiters] = pattern;
          }
          if (match = pattern.exec(scalar.slice(i))) {
            output = match[1];
            i += output.length;
          } else {
            throw new ParseException('Malformed inline YAML string (' + scalar + ').');
          }
        }
        if (evaluate) {
          output = this.evaluateScalar(output, context);
        }
      }
      context.i = i;
      return output;
    }

    // Parses a quoted scalar to YAML.

    // @param [String]   scalar
    // @param [Object]   context

    // @return [String]  A YAML string

    // @throw [ParseMore] When malformed inline YAML string is parsed

    static parseQuotedScalar(scalar, context) {
      var i, match, output;
      ({i} = context);
      if (!(match = this.PATTERN_QUOTED_SCALAR.exec(scalar.slice(i)))) {
        throw new ParseMore('Malformed inline YAML string (' + scalar.slice(i) + ').');
      }
      output = match[0].substr(1, match[0].length - 2);
      if ('"' === scalar.charAt(i)) {
        output = Unescaper.unescapeDoubleQuotedString(output);
      } else {
        output = Unescaper.unescapeSingleQuotedString(output);
      }
      i += match[0].length;
      context.i = i;
      return output;
    }

    // Parses a sequence to a YAML string.

    // @param [String]   sequence
    // @param [Object]   context

    // @return [String]  A YAML string

    // @throw [ParseMore] When malformed inline YAML string is parsed

    static parseSequence(sequence, context) {
      var e, i, isQuoted, len, output, ref, value;
      output = [];
      len = sequence.length;
      ({i} = context);
      i += 1;
      // [foo, bar, ...]
      while (i < len) {
        context.i = i;
        switch (sequence.charAt(i)) {
          case '[':
            // Nested sequence
            output.push(this.parseSequence(sequence, context));
            ({i} = context);
            break;
          case '{':
            // Nested mapping
            output.push(this.parseMapping(sequence, context));
            ({i} = context);
            break;
          case ']':
            return output;
          case ',':
          case ' ':
          case "\n":
            break;
          default:
            // Do nothing
            isQuoted = ((ref = sequence.charAt(i)) === '"' || ref === "'");
            value = this.parseScalar(sequence, [',', ']'], ['"', "'"], context);
            ({i} = context);
            if (!isQuoted && typeof value === 'string' && (value.indexOf(': ') !== -1 || value.indexOf(":\n") !== -1)) {
              try {
                // Embedded mapping?
                value = this.parseMapping('{' + value + '}');
              } catch (error) {
                e = error;
              }
            }
            // No, it's not
            output.push(value);
            --i;
        }
        ++i;
      }
      throw new ParseMore('Malformed inline YAML string ' + sequence);
    }

    // Parses a mapping to a YAML string.

    // @param [String]   mapping
    // @param [Object]   context

    // @return [String]  A YAML string

    // @throw [ParseMore] When malformed inline YAML string is parsed

    static parseMapping(mapping, context) {
      var done, i, key, len, output, shouldContinueWhileLoop, value;
      output = {};
      len = mapping.length;
      ({i} = context);
      i += 1;
      // {foo: bar, bar:foo, ...}
      shouldContinueWhileLoop = false;
      while (i < len) {
        context.i = i;
        switch (mapping.charAt(i)) {
          case ' ':
          case ',':
          case "\n":
            ++i;
            context.i = i;
            shouldContinueWhileLoop = true;
            break;
          case '}':
            return output;
        }
        if (shouldContinueWhileLoop) {
          shouldContinueWhileLoop = false;
          continue;
        }
        // Key
        key = this.parseScalar(mapping, [':', ' ', "\n"], ['"', "'"], context, false);
        ({i} = context);
        // Value
        done = false;
        while (i < len) {
          context.i = i;
          switch (mapping.charAt(i)) {
            case '[':
              // Nested sequence
              value = this.parseSequence(mapping, context);
              ({i} = context);
              // Spec: Keys MUST be unique; first one wins.
              // Parser cannot abort this mapping earlier, since lines
              // are processed sequentially.
              if (output[key] === void 0) {
                output[key] = value;
              }
              done = true;
              break;
            case '{':
              // Nested mapping
              value = this.parseMapping(mapping, context);
              ({i} = context);
              // Spec: Keys MUST be unique; first one wins.
              // Parser cannot abort this mapping earlier, since lines
              // are processed sequentially.
              if (output[key] === void 0) {
                output[key] = value;
              }
              done = true;
              break;
            case ':':
            case ' ':
            case "\n":
              break;
            default:
              // Do nothing
              value = this.parseScalar(mapping, [',', '}'], ['"', "'"], context);
              ({i} = context);
              // Spec: Keys MUST be unique; first one wins.
              // Parser cannot abort this mapping earlier, since lines
              // are processed sequentially.
              if (output[key] === void 0) {
                output[key] = value;
              }
              done = true;
              --i;
          }
          ++i;
          if (done) {
            break;
          }
        }
      }
      throw new ParseMore('Malformed inline YAML string ' + mapping);
    }

    // Evaluates scalars and replaces magic values.

    // @param [String]   scalar

    // @return [String]  A YAML string

    static evaluateScalar(scalar, context) {
      var cast, date, exceptionOnInvalidType, firstChar, firstSpace, firstWord, objectDecoder, raw, scalarLower, subValue, trimmedScalar;
      scalar = Utils.trim(scalar);
      scalarLower = scalar.toLowerCase();
      switch (scalarLower) {
        case 'null':
        case '':
        case '~':
          return null;
        case 'true':
          return true;
        case 'false':
          return false;
        case '.inf':
          return 2e308;
        case '.nan':
          return 0/0;
        case '-.inf':
          return 2e308;
        default:
          firstChar = scalarLower.charAt(0);
          switch (firstChar) {
            case '!':
              firstSpace = scalar.indexOf(' ');
              if (firstSpace === -1) {
                firstWord = scalarLower;
              } else {
                firstWord = scalarLower.slice(0, firstSpace);
              }
              switch (firstWord) {
                case '!':
                  if (firstSpace !== -1) {
                    return parseInt(this.parseScalar(scalar.slice(2)));
                  }
                  return null;
                case '!str':
                  return Utils.ltrim(scalar.slice(4));
                case '!!str':
                  return Utils.ltrim(scalar.slice(5));
                case '!!int':
                  return parseInt(this.parseScalar(scalar.slice(5)));
                case '!!bool':
                  return Utils.parseBoolean(this.parseScalar(scalar.slice(6)), false);
                case '!!float':
                  return parseFloat(this.parseScalar(scalar.slice(7)));
                case '!!timestamp':
                  return Utils.stringToDate(Utils.ltrim(scalar.slice(11)));
                default:
                  if (context == null) {
                    context = {
                      exceptionOnInvalidType: this.settings.exceptionOnInvalidType,
                      objectDecoder: this.settings.objectDecoder,
                      i: 0
                    };
                  }
                  ({objectDecoder, exceptionOnInvalidType} = context);
                  if (objectDecoder) {
                    // If objectDecoder function is given, we can do custom decoding of custom types
                    trimmedScalar = Utils.rtrim(scalar);
                    firstSpace = trimmedScalar.indexOf(' ');
                    if (firstSpace === -1) {
                      return objectDecoder(trimmedScalar, null);
                    } else {
                      subValue = Utils.ltrim(trimmedScalar.slice(firstSpace + 1));
                      if (!(subValue.length > 0)) {
                        subValue = null;
                      }
                      return objectDecoder(trimmedScalar.slice(0, firstSpace), subValue);
                    }
                  }
                  if (exceptionOnInvalidType) {
                    throw new ParseException('Custom object support when parsing a YAML file has been disabled.');
                  }
                  return null;
              }
              break;
            case '0':
              if ('0x' === scalar.slice(0, 2)) {
                return Utils.hexDec(scalar);
              } else if (Utils.isDigits(scalar)) {
                return Utils.octDec(scalar);
              } else if (Utils.isNumeric(scalar)) {
                return parseFloat(scalar);
              } else {
                return scalar;
              }
              break;
            case '+':
              if (Utils.isDigits(scalar)) {
                raw = scalar;
                cast = parseInt(raw);
                if (raw === String(cast)) {
                  return cast;
                } else {
                  return raw;
                }
              } else if (Utils.isNumeric(scalar)) {
                return parseFloat(scalar);
              } else if (this.PATTERN_THOUSAND_NUMERIC_SCALAR.test(scalar)) {
                return parseFloat(scalar.replace(',', ''));
              }
              return scalar;
            case '-':
              if (Utils.isDigits(scalar.slice(1))) {
                if ('0' === scalar.charAt(1)) {
                  return -Utils.octDec(scalar.slice(1));
                } else {
                  raw = scalar.slice(1);
                  cast = parseInt(raw);
                  if (raw === String(cast)) {
                    return -cast;
                  } else {
                    return -raw;
                  }
                }
              } else if (Utils.isNumeric(scalar)) {
                return parseFloat(scalar);
              } else if (this.PATTERN_THOUSAND_NUMERIC_SCALAR.test(scalar)) {
                return parseFloat(scalar.replace(',', ''));
              }
              return scalar;
            default:
              if (date = Utils.stringToDate(scalar)) {
                return date;
              } else if (Utils.isNumeric(scalar)) {
                return parseFloat(scalar);
              } else if (this.PATTERN_THOUSAND_NUMERIC_SCALAR.test(scalar)) {
                return parseFloat(scalar.replace(',', ''));
              }
              return scalar;
          }
      }
    }

  };

  // Quoted string regular expression
  Inline.REGEX_QUOTED_STRING = '(?:"(?:[^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'(?:[^\']*(?:\'\'[^\']*)*)\')';

  // Pre-compiled patterns

  Inline.PATTERN_TRAILING_COMMENTS = new Pattern('^\\s*#.*$');

  Inline.PATTERN_QUOTED_SCALAR = new Pattern('^' + Inline.REGEX_QUOTED_STRING);

  Inline.PATTERN_THOUSAND_NUMERIC_SCALAR = new Pattern('^(-|\\+)?[0-9,]+(\\.[0-9]+)?$');

  Inline.PATTERN_SCALAR_BY_DELIMITERS = {};

  // Settings
  Inline.settings = {};

  return Inline;

}).call(this);

module.exports = Inline;