schema.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. 'use strict';
  2. var common = require('./common');
  3. var YAMLException = require('./exception');
  4. var Type = require('./type');
  5. function compileList(schema, name, result) {
  6. var exclude = [];
  7. schema.include.forEach(function (includedSchema) {
  8. result = compileList(includedSchema, name, result);
  9. });
  10. schema[name].forEach(function (currentType) {
  11. result.forEach(function (previousType, previousIndex) {
  12. if (previousType.tag === currentType.tag) {
  13. exclude.push(previousIndex);
  14. }
  15. });
  16. result.push(currentType);
  17. });
  18. return result.filter(function (type, index) {
  19. return -1 === exclude.indexOf(index);
  20. });
  21. }
  22. function compileMap(/* lists... */) {
  23. var result = {}, index, length;
  24. function collectType(type) {
  25. result[type.tag] = type;
  26. }
  27. for (index = 0, length = arguments.length; index < length; index += 1) {
  28. arguments[index].forEach(collectType);
  29. }
  30. return result;
  31. }
  32. function Schema(definition) {
  33. this.include = definition.include || [];
  34. this.implicit = definition.implicit || [];
  35. this.explicit = definition.explicit || [];
  36. this.implicit.forEach(function (type) {
  37. if (null !== type.loader && 'string' !== type.loader.kind) {
  38. throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
  39. }
  40. });
  41. this.compiledImplicit = compileList(this, 'implicit', []);
  42. this.compiledExplicit = compileList(this, 'explicit', []);
  43. this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
  44. }
  45. Schema.DEFAULT = null;
  46. Schema.create = function createSchema() {
  47. var schemas, types;
  48. switch (arguments.length) {
  49. case 1:
  50. schemas = Schema.DEFAULT;
  51. types = arguments[0];
  52. break;
  53. case 2:
  54. schemas = arguments[0];
  55. types = arguments[1];
  56. break;
  57. default:
  58. throw new YAMLException('Wrong number of arguments for Schema.create function');
  59. }
  60. schemas = common.toArray(schemas);
  61. types = common.toArray(types);
  62. if (!schemas.every(function (schema) { return schema instanceof Schema; })) {
  63. throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
  64. }
  65. if (!types.every(function (type) { return type instanceof Type; })) {
  66. throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');
  67. }
  68. return new Schema({
  69. include: schemas,
  70. explicit: types
  71. });
  72. };
  73. module.exports = Schema;