diff --git a/dist/Document.js b/dist/Document.js new file mode 100644 index 00000000..008d0731 --- /dev/null +++ b/dist/Document.js @@ -0,0 +1,416 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _addComment = _interopRequireDefault(require("./addComment")); + +var _listTagNames = _interopRequireDefault(require("./listTagNames")); + +var _Node = require("./ast/Node"); + +var _errors = require("./errors"); + +var _resolveValue2 = _interopRequireDefault(require("./resolveValue")); + +var _schema = _interopRequireWildcard(require("./schema")); + +var _Collection = _interopRequireWildcard(require("./schema/Collection")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var isCollectionItem = function isCollectionItem(node) { + return node && [_Node.Type.MAP_KEY, _Node.Type.MAP_VALUE, _Node.Type.SEQ_ITEM].includes(node.type); +}; + +var Document = +/*#__PURE__*/ +function () { + function Document(schema) { + _classCallCheck(this, Document); + + this.anchors = {}; + this.commentBefore = null; + this.comment = null; + this.contents = null; + this.errors = []; + this.tagPrefixes = []; + this.schema = schema instanceof _schema.default ? schema : new _schema.default(schema); + this.version = null; + this.warnings = []; + } + + _createClass(Document, [{ + key: "parse", + value: function parse(_ref) { + var _this = this; + + var _ref$directives = _ref.directives, + directives = _ref$directives === void 0 ? [] : _ref$directives, + _ref$contents = _ref.contents, + contents = _ref$contents === void 0 ? [] : _ref$contents, + error = _ref.error; + + if (error) { + if (!error.source) error.source = this; + this.errors.push(error); + } + + var directiveComments = []; + directives.forEach(function (directive) { + var comment = directive.comment, + name = directive.name; + + switch (name) { + case 'TAG': + _this.resolveTagDirective(directive); + + break; + + case 'YAML': + _this.resolveYamlDirective(directive); + + break; + + default: + if (name) _this.warnings.push(new _errors.YAMLWarning(directive, "YAML 1.2 only supports TAG and YAML directives, and not ".concat(name))); + } + + if (comment) directiveComments.push(comment); + }); + this.commentBefore = directiveComments.join('\n') || null; + var comments = { + before: [], + after: [] + }; + var contentNodes = []; + contents.forEach(function (node) { + if (node.valueRange && !node.valueRange.isEmpty) { + if (contentNodes.length === 1) { + _this.errors.push(new _errors.YAMLSemanticError(node, 'Document is not valid YAML (bad indentation?)')); + } + + contentNodes.push(_this.resolveNode(node)); + } else if (node.comment) { + var cc = contentNodes.length === 0 ? comments.before : comments.after; + cc.push(node.comment); + } + }); + + switch (contentNodes.length) { + case 0: + this.contents = null; + comments.after = comments.before; + break; + + case 1: + this.contents = contentNodes[0]; + + if (this.contents) { + var cb = comments.before.join('\n') || null; + + if (cb) { + var cbNode = this.contents instanceof _Collection.default && this.contents.items[0] ? this.contents.items[0] : this.contents; + cbNode.commentBefore = cbNode.commentBefore ? "".concat(cb, "\n").concat(cbNode.commentBefore) : cb; + } + } else { + comments.after = comments.before.concat(comments.after); + } + + break; + + default: + this.contents = contentNodes; + if (this.contents[0]) this.contents[0].commentBefore = comments.before.join('\n') || null;else comments.after = comments.before.concat(comments.after); + } + + this.comment = comments.after.join('\n') || null; + return this; + } + }, { + key: "resolveTagDirective", + value: function resolveTagDirective(directive) { + var _directive$parameters = _slicedToArray(directive.parameters, 2), + handle = _directive$parameters[0], + prefix = _directive$parameters[1]; + + if (handle && prefix) { + if (this.tagPrefixes.every(function (p) { + return p.handle !== handle; + })) { + this.tagPrefixes.push({ + handle: handle, + prefix: prefix + }); + } else { + this.errors.push(new _errors.YAMLSemanticError(directive, 'The TAG directive must only be given at most once per handle in the same document.')); + } + } else { + this.errors.push(new _errors.YAMLSemanticError(directive, 'Insufficient parameters given for TAG directive')); + } + } + }, { + key: "resolveYamlDirective", + value: function resolveYamlDirective(directive) { + var _directive$parameters2 = _slicedToArray(directive.parameters, 1), + version = _directive$parameters2[0]; + + if (this.version) this.errors.push(new _errors.YAMLSemanticError(directive, 'The YAML directive must only be given at most once per document.')); + if (!version) this.errors.push(new _errors.YAMLSemanticError(directive, 'Insufficient parameters given for YAML directive'));else if (version !== '1.2') this.warnings.push(new _errors.YAMLWarning(directive, "Document will be parsed as YAML 1.2 rather than YAML ".concat(version))); + this.version = version; + } + }, { + key: "resolveTagName", + value: function resolveTagName(node) { + var tag = node.tag, + type = node.type; + var nonSpecific = false; + + if (tag) { + var handle = tag.handle, + suffix = tag.suffix, + verbatim = tag.verbatim; + + if (verbatim) { + if (verbatim !== '!' && verbatim !== '!!') return verbatim; + this.errors.push(new _errors.YAMLSemanticError(node, "Verbatim tags aren't resolved, so ".concat(verbatim, " is invalid."))); + } else if (handle === '!' && !suffix) { + nonSpecific = true; + } else { + var prefix = this.tagPrefixes.find(function (p) { + return p.handle === handle; + }) || _schema.DefaultTagPrefixes.find(function (p) { + return p.handle === handle; + }); + + if (prefix) { + if (suffix) return prefix.prefix + suffix; + this.errors.push(new _errors.YAMLSemanticError(node, "The ".concat(handle, " tag has no suffix."))); + } else { + this.errors.push(new _errors.YAMLSemanticError(node, "The ".concat(handle, " tag handle is non-default and was not declared."))); + } + } + } + + switch (type) { + case _Node.Type.BLOCK_FOLDED: + case _Node.Type.BLOCK_LITERAL: + case _Node.Type.QUOTE_DOUBLE: + case _Node.Type.QUOTE_SINGLE: + return _schema.DefaultTags.STR; + + case _Node.Type.FLOW_MAP: + case _Node.Type.MAP: + return _schema.DefaultTags.MAP; + + case _Node.Type.FLOW_SEQ: + case _Node.Type.SEQ: + return _schema.DefaultTags.SEQ; + + case _Node.Type.PLAIN: + return nonSpecific ? _schema.DefaultTags.STR : null; + + default: + return null; + } + } + }, { + key: "resolveNode", + value: function resolveNode(node) { + if (!node) return null; + var anchors = this.anchors, + errors = this.errors, + schema = this.schema; + var hasAnchor = false; + var hasTag = false; + var comments = { + before: [], + after: [] + }; + var props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props; + props.forEach(function (_ref2, i) { + var start = _ref2.start, + end = _ref2.end; + + switch (node.context.src[start]) { + case _Node.Char.COMMENT: + if (!node.commentHasRequiredWhitespace(start)) errors.push(new _errors.YAMLSemanticError(node, 'Comments must be separated from other tokens by white space characters')); + var c = node.context.src.slice(start + 1, end); + var header = node.header, + valueRange = node.valueRange; + + if (valueRange && (start > valueRange.start || header && start > header.start)) { + comments.after.push(c); + } else { + comments.before.push(c); + } + + break; + + case _Node.Char.ANCHOR: + if (hasAnchor) errors.push(new _errors.YAMLSemanticError(node, 'A node can have at most one anchor')); + hasAnchor = true; + break; + + case _Node.Char.TAG: + if (hasTag) errors.push(new _errors.YAMLSemanticError(node, 'A node can have at most one tag')); + hasTag = true; + break; + } + }); + if (hasAnchor) anchors[node.anchor] = node; + var res; + + if (node.type === _Node.Type.ALIAS) { + if (hasAnchor || hasTag) errors.push(new _errors.YAMLSemanticError(node, 'An alias node must not specify any properties')); + var src = anchors[node.rawValue]; + + if (!src) { + errors.push(new _errors.YAMLReferenceError(node, "Aliased anchor not found: ".concat(node.rawValue))); + return null; + } + + res = src.resolved; + } else { + var tagName = this.resolveTagName(node); + + if (tagName) { + res = schema.resolveNodeWithFallback(this, node, tagName); + } else { + if (node.type !== _Node.Type.PLAIN) { + errors.push(new _errors.YAMLSemanticError(node, "Failed to resolve ".concat(node.type, " node here"))); + return null; + } + + try { + res = schema.resolveScalar(node.strValue || ''); + } catch (error) { + if (!error.source) error.source = node; + errors.push(error); + return null; + } + } + } + + if (res) { + var cb = comments.before.join('\n'); + if (cb) res.commentBefore = res.commentBefore ? "".concat(res.commentBefore, "\n").concat(cb) : cb; + var ca = comments.after.join('\n'); + if (ca) res.comment = res.comment ? "".concat(res.comment, "\n").concat(ca) : ca; + } + + return node.resolved = res; + } + }, { + key: "resolveValue", + value: function resolveValue(value) { + return (0, _resolveValue2.default)(this, value, true); + } + }, { + key: "listNonDefaultTags", + value: function listNonDefaultTags() { + var _DefaultTagPrefixes$f = _schema.DefaultTagPrefixes.find(function (p) { + return p.handle === '!!'; + }), + prefix = _DefaultTagPrefixes$f.prefix; + + return (0, _listTagNames.default)(this.contents).filter(function (t) { + return t.indexOf(prefix) !== 0; + }); + } + }, { + key: "setTagPrefix", + value: function setTagPrefix(handle, prefix) { + if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !'); + + if (prefix) { + var prev = this.tagPrefixes.find(function (p) { + return p.handle === handle; + }); + if (prev) prev.prefix = prefix;else this.tagPrefixes.push({ + handle: handle, + prefix: prefix + }); + } else { + this.tagPrefixes = this.tagPrefixes.filter(function (p) { + return p.handle !== handle; + }); + } + } + }, { + key: "toJSON", + value: function toJSON() { + return (0, _Collection.toJSON)(this.contents); + } + }, { + key: "toString", + value: function toString() { + if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified'); + var lines = []; + if (this.commentBefore) lines.push(this.commentBefore.replace(/^/gm, '#')); + var hasDirectives = false; + + if (this.version) { + lines.push('%YAML 1.2'); + hasDirectives = true; + } + + var tagNames = this.listNonDefaultTags(); + this.tagPrefixes.forEach(function (_ref3) { + var handle = _ref3.handle, + prefix = _ref3.prefix; + + if (tagNames.some(function (t) { + return t.indexOf(prefix) === 0; + })) { + lines.push("%TAG ".concat(handle, " ").concat(prefix)); + hasDirectives = true; + } + }); + if (hasDirectives) lines.push('---'); + + if (this.contents) { + if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); + var options = { + // top-level block scalars need to be indented if followed by a comment + forceBlockIndent: !!this.comment, + indent: '' + }; + var comment = this.contents.comment; + var body = this.schema.stringify(this, this.contents, options, function () { + comment = null; + }); + lines.push((0, _addComment.default)(body, '', comment)); + } else if (this.contents !== undefined) { + lines.push(this.schema.stringify(this, this.contents, { + indent: '' + })); + } + + if (this.comment) lines.push(this.comment.replace(/^/gm, '#')); + return lines.join('\n') + '\n'; + } + }]); + + return Document; +}(); + +exports.default = Document; \ No newline at end of file diff --git a/dist/Tags.js b/dist/Tags.js new file mode 100644 index 00000000..81757d2b --- /dev/null +++ b/dist/Tags.js @@ -0,0 +1,245 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.DefaultTags = exports.DefaultTagPrefixes = void 0; + +var _Node = require("./ast/Node"); + +var _errors = require("./errors"); + +var _schema = _interopRequireDefault(require("./schema")); + +var _Collection = _interopRequireDefault(require("./schema/Collection")); + +var _Pair = _interopRequireDefault(require("./schema/Pair")); + +var _Scalar = _interopRequireDefault(require("./schema/Scalar")); + +var _string = require("./schema/_string"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var defaultPrefix = 'tag:yaml.org,2002:'; +var DefaultTagPrefixes = [{ + handle: '!', + prefix: '!' +}, { + handle: '!!', + prefix: defaultPrefix +}]; +exports.DefaultTagPrefixes = DefaultTagPrefixes; +var DefaultTags = { + MAP: 'tag:yaml.org,2002:map', + SEQ: 'tag:yaml.org,2002:seq', + STR: 'tag:yaml.org,2002:str' +}; +exports.DefaultTags = DefaultTags; + +var isMap = function isMap(_ref) { + var type = _ref.type; + return type === _Node.Type.FLOW_MAP || type === _Node.Type.MAP; +}; + +var isSeq = function isSeq(_ref2) { + var type = _ref2.type; + return type === _Node.Type.FLOW_SEQ || type === _Node.Type.SEQ; +}; + +var Tags = +/*#__PURE__*/ +function () { + _createClass(Tags, null, [{ + key: "defaultStringifier", + value: function defaultStringifier(value) { + return JSON.stringify(value); + } + }]); + + function Tags(_ref3) { + var merge = _ref3.merge, + schema = _ref3.schema, + tags = _ref3.tags; + + _classCallCheck(this, Tags); + + this.merge = !!merge; + this.schema = Array.isArray(schema) ? schema : _schema.default[schema]; + + if (!this.schema) { + var keys = Object.keys(_schema.default).map(function (key) { + return JSON.stringify(key); + }).join(', '); + throw new Error("Unknown schema; use ".concat(keys, ", or { tag, test, resolve }[]")); + } + + if (Array.isArray(tags)) { + this.schema = this.schema.concat(tags); + } else if (typeof tags === 'function') { + this.schema = tags(this.schema.slice()); + } + } // falls back to string on no match + + + _createClass(Tags, [{ + key: "resolveScalar", + value: function resolveScalar(str, tags) { + if (!tags) tags = this.schema; + + for (var i = 0; i < tags.length; ++i) { + var _tags$i = tags[i], + test = _tags$i.test, + resolve = _tags$i.resolve; + + if (test) { + var match = str.match(test); + if (match) return new _Scalar.default(resolve.apply(null, match)); + } + } + + if (this.schema.scalarFallback) str = this.schema.scalarFallback(str); + return new _Scalar.default(str); + } // sets node.resolved on success + + }, { + key: "resolveNode", + value: function resolveNode(doc, node, tagName) { + var tags = this.schema.filter(function (_ref4) { + var tag = _ref4.tag; + return tag === tagName; + }); + var generic = tags.find(function (_ref5) { + var test = _ref5.test; + return !test; + }); + if (node.error) doc.errors.push(node.error); + + try { + if (generic) { + var res = generic.resolve(doc, node); + if (!(res instanceof _Collection.default)) res = new _Scalar.default(res); + node.resolved = res; + } else { + var str = (0, _string.resolve)(doc, node); + + if (typeof str === 'string' && tags.length > 0) { + node.resolved = this.resolveScalar(str, tags); + } + } + } catch (error) { + if (!error.source) error.source = node; + doc.errors.push(error); + node.resolved = null; + } + + if (!node.resolved) return null; + if (node.hasProps) node.resolved.anchor = node.anchor; + if (tagName) node.resolved.tag = tagName; + return node.resolved; + } + }, { + key: "resolveNodeWithFallback", + value: function resolveNodeWithFallback(doc, node, tagName) { + var res = this.resolveNode(doc, node, tagName); + if (node.hasOwnProperty('resolved')) return res; + var fallback = isMap(node) ? DefaultTags.MAP : isSeq(node) ? DefaultTags.SEQ : DefaultTags.STR; + + if (fallback) { + doc.warnings.push(new _errors.YAMLWarning(node, "The tag ".concat(tagName, " is unavailable, falling back to ").concat(fallback))); + + var _res = this.resolveNode(doc, node, fallback); + + _res.origTag = tagName; + return _res; + } else { + doc.errors.push(new _errors.YAMLReferenceError(node, "The tag ".concat(tagName, " is unavailable"))); + } + + return null; + } + }, { + key: "stringify", + value: function stringify(doc, item, options, onComment) { + if (!(item instanceof _Scalar.default || item instanceof _Collection.default || item instanceof _Pair.default)) { + item = doc.resolveValue(item, true); + } + + options.tags = this; + var match; + + if (item instanceof _Pair.default) { + return item.toString(doc, options, onComment); + } else if (item.tag) { + match = this.schema.filter(function (_ref6) { + var format = _ref6.format, + tag = _ref6.tag; + return tag === item.tag && (!item.format || format === item.format); + }); + if (match.length === 0) throw new Error("Tag not available: ".concat(item.tag).concat(item.format ? ', format ' + item.format : '')); + } else if (item.value === null) { + match = this.schema.filter(function (t) { + return t.class === null && !t.format; + }); + if (match.length === 0) throw new Error('Schema is missing a null stringifier'); + } else { + var obj = item; + + if (item.hasOwnProperty('value')) { + switch (_typeof(item.value)) { + case 'boolean': + obj = new Boolean(); + break; + + case 'number': + obj = new Number(); + break; + + case 'string': + obj = new String(); + break; + + default: + obj = item.value; + } + } + + match = this.schema.filter(function (t) { + return t.class && obj instanceof t.class && !t.format; + }); + if (match.length === 0) throw new Error("Tag not resolved for ".concat(obj && obj.constructor ? obj.constructor.name : _typeof(obj))); + } + + var stringify = match[0].stringify || Tags.defaultStringifier; + var str = stringify(item, options, onComment); + var tag = item.origTag || item.tag; + + if (tag && tag.indexOf(defaultPrefix) !== 0) { + var p = doc.tagPrefixes.find(function (p) { + return tag.indexOf(p.prefix) === 0; + }); + var tagProp = p ? p.handle + tag.substr(p.prefix.length) : tag[0] === '!' ? tag : "!<".concat(tag, ">"); + + if (item instanceof _Collection.default && !options.inFlow && item.items.length > 0) { + return "".concat(tagProp, "\n").concat(options.indent).concat(str); + } else { + return "".concat(tagProp, " ").concat(str); + } + } + + return str; + } + }]); + + return Tags; +}(); + +exports.default = Tags; \ No newline at end of file diff --git a/dist/addComment.js b/dist/addComment.js new file mode 100644 index 00000000..3cac0476 --- /dev/null +++ b/dist/addComment.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.addCommentBefore = addCommentBefore; +exports.default = addComment; + +function addCommentBefore(str, indent, comment) { + if (!comment) return str; + var cc = comment.replace(/[\s\S]^/gm, "$&".concat(indent, "#")); + return "#".concat(cc, "\n").concat(indent).concat(str); +} + +function addComment(str, indent, comment) { + return !comment ? str : comment.indexOf('\n') === -1 ? "".concat(str, " #").concat(comment) : "".concat(str, "\n") + comment.replace(/^/gm, "".concat(indent || '', "#")); +} \ No newline at end of file diff --git a/dist/ast/Alias.js b/dist/ast/Alias.js new file mode 100644 index 00000000..9b43f2b9 --- /dev/null +++ b/dist/ast/Alias.js @@ -0,0 +1,69 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _Node2 = _interopRequireDefault(require("./Node")); + +var _Range = _interopRequireDefault(require("./Range")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var Alias = +/*#__PURE__*/ +function (_Node) { + function Alias() { + _classCallCheck(this, Alias); + + return _possibleConstructorReturn(this, _getPrototypeOf(Alias).apply(this, arguments)); + } + + _createClass(Alias, [{ + key: "parse", + + /** + * Parses an *alias from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar + */ + value: function parse(context, start) { + this.context = context; + var src = context.src; + + var offset = _Node2.default.endOfIdentifier(src, start + 1); + + this.valueRange = new _Range.default(start + 1, offset); + offset = _Node2.default.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + return offset; + } + }]); + + _inherits(Alias, _Node); + + return Alias; +}(_Node2.default); + +exports.default = Alias; \ No newline at end of file diff --git a/dist/ast/BlockValue.js b/dist/ast/BlockValue.js new file mode 100644 index 00000000..59c68162 --- /dev/null +++ b/dist/ast/BlockValue.js @@ -0,0 +1,255 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.Chomp = void 0; + +var _Node2 = _interopRequireWildcard(require("./Node")); + +var _Range = _interopRequireDefault(require("./Range")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var Chomp = { + CLIP: 'CLIP', + KEEP: 'KEEP', + STRIP: 'STRIP' +}; +exports.Chomp = Chomp; + +var BlockValue = +/*#__PURE__*/ +function (_Node) { + function BlockValue(type, props) { + var _this; + + _classCallCheck(this, BlockValue); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(BlockValue).call(this, type, props)); + _this.blockIndent = null; + _this.chomping = Chomp.CLIP; + _this.header = null; + return _this; + } + + _createClass(BlockValue, [{ + key: "parseBlockHeader", + value: function parseBlockHeader(start) { + var src = this.context.src; + var offset = start + 1; + var bi = ''; + + while (true) { + var ch = src[offset]; + + switch (ch) { + case '-': + this.chomping = Chomp.STRIP; + break; + + case '+': + this.chomping = Chomp.KEEP; + break; + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + bi += ch; + break; + + default: + this.blockIndent = Number(bi) || null; + this.header = new _Range.default(start, offset); + return offset; + } + + offset += 1; + } + } + }, { + key: "parseBlockValue", + value: function parseBlockValue(start) { + var _this$context = this.context, + indent = _this$context.indent, + inFlow = _this$context.inFlow, + src = _this$context.src; + var offset = start; + var bi = this.blockIndent ? indent + this.blockIndent - 1 : indent; + var minBlockIndent = 1; + + for (var ch = src[offset]; ch === '\n'; ch = src[offset]) { + offset += 1; + if (_Node2.default.atDocumentBoundary(src, offset)) break; + + var end = _Node2.default.endOfBlockIndent(src, bi, offset); // should not include tab? + + + if (end === null) break; + + if (!this.blockIndent) { + // no explicit block indent, none yet detected + var lineIndent = end - (offset + indent); + + if (src[end] !== '\n') { + // first line with non-whitespace content + if (lineIndent < minBlockIndent) { + offset -= 1; + break; + } + + this.blockIndent = lineIndent; + bi = indent + this.blockIndent - 1; + } else if (lineIndent > minBlockIndent) { + // empty line with more whitespace + minBlockIndent = lineIndent; + } + } + + offset = _Node2.default.endOfLine(src, end); + } + + this.valueRange = new _Range.default(start + 1, offset); + return offset; + } + /** + * Parses a block value from the source + * + * Accepted forms are: + * ``` + * BS + * block + * lines + * + * BS #comment + * block + * lines + * ``` + * where the block style BS matches the regexp `[|>][-+1-9]*` and block lines + * are empty or have an indent level greater than `indent`. + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this block + */ + + }, { + key: "parse", + value: function parse(context, start) { + this.context = context; + var src = context.src; + var offset = this.parseBlockHeader(start); + offset = _Node2.default.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + offset = this.parseBlockValue(offset); + return offset; + } + }, { + key: "strValue", + get: function get() { + if (!this.valueRange || !this.context) return null; + var _this$valueRange = this.valueRange, + start = _this$valueRange.start, + end = _this$valueRange.end; + var _this$context2 = this.context, + indent = _this$context2.indent, + src = _this$context2.src; + if (this.valueRange.isEmpty) return ''; + var lastNewLine = null; + var ch = src[end - 1]; + + while (ch === '\n' || ch === '\t' || ch === ' ') { + end -= 1; + + if (end <= start) { + if (this.chomping === Chomp.KEEP) break;else return ''; + } + + if (ch === '\n') lastNewLine = end; + ch = src[end - 1]; + } + + var keepStart = end + 1; + + if (lastNewLine) { + if (this.chomping === Chomp.KEEP) { + keepStart = lastNewLine; + end = this.valueRange.end; + } else { + end = lastNewLine; + } + } + + var bi = indent + this.blockIndent; + var folded = this.type === _Node2.Type.BLOCK_FOLDED; + var str = ''; + var sep = ''; + var prevMoreIndented = false; + + for (var i = start; i < end; ++i) { + for (var j = 0; j < bi; ++j) { + if (src[i] !== ' ') break; + i += 1; + } + + var _ch = src[i]; + + if (_ch === '\n') { + if (sep === '\n') str += '\n';else sep = '\n'; + } else { + var lineEnd = _Node2.default.endOfLine(src, i); + + var line = src.slice(i, lineEnd); + i = lineEnd; + + if (folded && (_ch === ' ' || _ch === '\t') && i < keepStart) { + if (sep === ' ') sep = '\n';else if (!prevMoreIndented && sep === '\n') sep = '\n\n'; + str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '') + + sep = lineEnd < end && src[lineEnd] || ''; + prevMoreIndented = true; + } else { + str += sep + line; + sep = folded && i < keepStart ? ' ' : '\n'; + prevMoreIndented = false; + } + } + } + + return this.chomping === Chomp.STRIP ? str : str + '\n'; + } + }]); + + _inherits(BlockValue, _Node); + + return BlockValue; +}(_Node2.default); + +exports.default = BlockValue; \ No newline at end of file diff --git a/dist/ast/Collection.js b/dist/ast/Collection.js new file mode 100644 index 00000000..bffc510a --- /dev/null +++ b/dist/ast/Collection.js @@ -0,0 +1,192 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _CollectionItem = _interopRequireDefault(require("./CollectionItem")); + +var _Comment = _interopRequireDefault(require("./Comment")); + +var _Node2 = _interopRequireWildcard(require("./Node")); + +var _Range = _interopRequireDefault(require("./Range")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var Collection = +/*#__PURE__*/ +function (_Node) { + function Collection(firstItem) { + var _this; + + _classCallCheck(this, Collection); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Collection).call(this, firstItem.type === _Node2.Type.SEQ_ITEM ? _Node2.Type.SEQ : _Node2.Type.MAP)); + _this.items = [firstItem]; + + for (var i = firstItem.props.length - 1; i >= 0; --i) { + if (firstItem.props[i].start < firstItem.context.lineStart) { + // props on previous line are assumed by the collection + _this.props = firstItem.props.slice(0, i + 1); + firstItem.props = firstItem.props.slice(i + 1); + var itemRange = firstItem.props[0] || firstItem.valueRange; + firstItem.range.start = itemRange.start; + break; + } + } + + return _this; + } + /** + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this + */ + + + _createClass(Collection, [{ + key: "parse", + value: function parse(context, start) { + this.context = context; + var parseNode = context.parseNode, + src = context.src; // It's easier to recalculate lineStart here rather than tracking down the + // last context from which to read it -- eemeli/yaml#2 + + var lineStart = _Node2.default.startOfLine(src, start); + + var firstItem = this.items[0]; + this.valueRange = _Range.default.copy(firstItem.valueRange); + var indent = firstItem.range.start - firstItem.context.lineStart; + var offset = start; + offset = _Node2.default.normalizeOffset(src, offset); + var ch = src[offset]; + var atLineStart = _Node2.default.endOfWhiteSpace(src, lineStart) === offset; + + while (ch) { + while (ch === '\n' || ch === '#') { + if (ch === '#') { + var comment = new _Comment.default(); + offset = comment.parse({ + src: src + }, offset); + this.items.push(comment); + this.valueRange.end = offset; + + if (offset >= src.length) { + ch = null; + break; + } + } + + lineStart = offset + 1; + offset = _Node2.default.endOfIndent(src, lineStart); + + if (_Node2.default.atBlank(src, offset)) { + var wsEnd = _Node2.default.endOfWhiteSpace(src, offset); + + var next = src[wsEnd]; + + if (!next || next === '\n' || next === '#') { + offset = wsEnd; + } + } + + ch = src[offset]; + atLineStart = true; + } + + if (!ch) { + break; + } + + if (offset !== lineStart + indent && (atLineStart || ch !== ':')) { + if (lineStart > start) offset = lineStart; + break; + } + + if (firstItem.type === _Node2.Type.SEQ_ITEM !== (ch === '-')) { + var typeswitch = true; + + if (ch === '-') { + // map key may start with -, as long as it's followed by a non-whitespace char + var _next = src[offset + 1]; + typeswitch = !_next || _next === '\n' || _next === '\t' || _next === ' '; + } + + if (typeswitch) { + if (lineStart > start) offset = lineStart; + break; + } + } + + var node = parseNode({ + atLineStart: atLineStart, + inCollection: true, + indent: indent, + lineStart: lineStart, + parent: this + }, offset); + if (!node) return offset; // at next document start + + this.items.push(node); + this.valueRange.end = node.valueRange.end; + offset = _Node2.default.normalizeOffset(src, node.range.end); + ch = src[offset]; + atLineStart = false; + } + + return offset; + } + }, { + key: "toString", + value: function toString() { + var src = this.context.src, + items = this.items, + range = this.range, + value = this.value; + if (value != null) return value; + var str = src.slice(range.start, items[0].range.start) + String(items[0]); + + for (var i = 1; i < items.length; ++i) { + var item = items[i]; + var _item$context = item.context, + atLineStart = _item$context.atLineStart, + indent = _item$context.indent; + if (atLineStart) for (var _i = 0; _i < indent; ++_i) { + str += ' '; + } + str += String(item); + } + + return _Node2.default.addStringTerminator(src, range.end, str); + } + }]); + + _inherits(Collection, _Node); + + return Collection; +}(_Node2.default); + +exports.default = Collection; \ No newline at end of file diff --git a/dist/ast/CollectionItem.js b/dist/ast/CollectionItem.js new file mode 100644 index 00000000..b5879050 --- /dev/null +++ b/dist/ast/CollectionItem.js @@ -0,0 +1,122 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _errors = require("../errors"); + +var _Node2 = _interopRequireWildcard(require("./Node")); + +var _Range = _interopRequireDefault(require("./Range")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var CollectionItem = +/*#__PURE__*/ +function (_Node) { + function CollectionItem(type, props) { + var _this; + + _classCallCheck(this, CollectionItem); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(CollectionItem).call(this, type, props)); + _this.node = null; + return _this; + } + /** + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this + */ + + + _createClass(CollectionItem, [{ + key: "parse", + value: function parse(context, start) { + this.context = context; + var parseNode = context.parseNode, + src = context.src; + var atLineStart = context.atLineStart, + lineStart = context.lineStart; + if (!atLineStart && this.type === _Node2.Type.SEQ_ITEM) this.error = new _errors.YAMLSyntaxError(this, 'Sequence items are not allowed on the same line with map keys'); + var indent = atLineStart ? start - lineStart : context.indent; + + var offset = _Node2.default.endOfWhiteSpace(src, start + 1); + + var ch = src[offset]; + + while (ch === '\n' || ch === '#') { + var next = offset + 1; + + if (ch === '#') { + var _end = _Node2.default.endOfLine(src, next); + + this.props.push(new _Range.default(offset, _end)); + offset = _end; + } else { + atLineStart = true; + lineStart = next; + offset = _Node2.default.endOfWhiteSpace(src, next); // against spec, to match \t allowed after indicator + } + + ch = src[offset]; + } + + if (_Node2.default.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== _Node2.Type.SEQ_ITEM)) { + this.node = parseNode({ + atLineStart: atLineStart, + inCollection: false, + indent: indent, + lineStart: lineStart, + parent: this + }, offset); + if (this.node) offset = this.node.range.end; + } else if (lineStart > start + 1) { + offset = lineStart - 1; + } + + var end = this.node ? this.node.valueRange.end : offset; + this.valueRange = new _Range.default(start, end); + return offset; + } + }, { + key: "toString", + value: function toString() { + var src = this.context.src, + node = this.node, + range = this.range, + value = this.value; + if (value != null) return value; + var str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end); + return _Node2.default.addStringTerminator(src, range.end, str); + } + }]); + + _inherits(CollectionItem, _Node); + + return CollectionItem; +}(_Node2.default); + +exports.default = CollectionItem; \ No newline at end of file diff --git a/dist/ast/Comment.js b/dist/ast/Comment.js new file mode 100644 index 00000000..2a942ce1 --- /dev/null +++ b/dist/ast/Comment.js @@ -0,0 +1,67 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _Node2 = _interopRequireWildcard(require("./Node")); + +var _Range = _interopRequireDefault(require("./Range")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var Comment = +/*#__PURE__*/ +function (_Node) { + function Comment() { + _classCallCheck(this, Comment); + + return _possibleConstructorReturn(this, _getPrototypeOf(Comment).call(this, _Node2.Type.COMMENT)); + } + /** + * Parses a comment line from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar + */ + + + _createClass(Comment, [{ + key: "parse", + value: function parse(context, start) { + this.context = context; + var src = context.src; + var offset = this.parseComment(start); + this.range = new _Range.default(start, offset); + return offset; + } + }]); + + _inherits(Comment, _Node); + + return Comment; +}(_Node2.default); + +exports.default = Comment; \ No newline at end of file diff --git a/dist/ast/Directive.js b/dist/ast/Directive.js new file mode 100644 index 00000000..9e9ff465 --- /dev/null +++ b/dist/ast/Directive.js @@ -0,0 +1,120 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _Node2 = _interopRequireWildcard(require("./Node")); + +var _Range = _interopRequireDefault(require("./Range")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var Directive = +/*#__PURE__*/ +function (_Node) { + _createClass(Directive, null, [{ + key: "endOfDirective", + value: function endOfDirective(src, offset) { + var ch = src[offset]; + + while (ch && ch !== '\n' && ch !== '#') { + ch = src[offset += 1]; + } // last char can't be whitespace + + + ch = src[offset - 1]; + + while (ch === ' ' || ch === '\t') { + offset -= 1; + ch = src[offset - 1]; + } + + return offset; + } + }]); + + function Directive() { + var _this; + + _classCallCheck(this, Directive); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Directive).call(this, _Node2.Type.DIRECTIVE)); + _this.name = null; + return _this; + } + + _createClass(Directive, [{ + key: "parseName", + value: function parseName(start) { + var src = this.context.src; + var offset = start; + var ch = src[offset]; + + while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') { + ch = src[offset += 1]; + } + + this.name = src.slice(start, offset); + return offset; + } + }, { + key: "parseParameters", + value: function parseParameters(start) { + var src = this.context.src; + var offset = start; + var ch = src[offset]; + + while (ch && ch !== '\n' && ch !== '#') { + ch = src[offset += 1]; + } + + this.valueRange = new _Range.default(start, offset); + return offset; + } + }, { + key: "parse", + value: function parse(context, start) { + this.context = context; + var src = context.src; + var offset = this.parseName(start + 1); + offset = this.parseParameters(offset); + offset = this.parseComment(offset); + this.range = new _Range.default(start, offset); + return offset; + } + }, { + key: "parameters", + get: function get() { + var raw = this.rawValue; + return raw ? raw.trim().split(/[ \t]+/) : []; + } + }]); + + _inherits(Directive, _Node); + + return Directive; +}(_Node2.default); + +exports.default = Directive; \ No newline at end of file diff --git a/dist/ast/Document.js b/dist/ast/Document.js new file mode 100644 index 00000000..6f68ddc4 --- /dev/null +++ b/dist/ast/Document.js @@ -0,0 +1,259 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _errors = require("../errors"); + +var _Comment = _interopRequireDefault(require("./Comment")); + +var _Directive = _interopRequireDefault(require("./Directive")); + +var _Node2 = _interopRequireWildcard(require("./Node")); + +var _Range = _interopRequireDefault(require("./Range")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var Document = +/*#__PURE__*/ +function (_Node) { + _createClass(Document, null, [{ + key: "startCommentOrEndBlankLine", + value: function startCommentOrEndBlankLine(src, start) { + var offset = _Node2.default.endOfWhiteSpace(src, start); + + var ch = src[offset]; + return ch === '#' || ch === '\n' ? offset : start; + } + }]); + + function Document() { + var _this; + + _classCallCheck(this, Document); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Document).call(this, _Node2.Type.DOCUMENT)); + _this.directives = null; + _this.contents = null; + return _this; + } + + _createClass(Document, [{ + key: "parseDirectives", + value: function parseDirectives(start) { + var src = this.context.src; + this.directives = []; + var hasDirectives = false; + var offset = start; + + while (!_Node2.default.atDocumentBoundary(src, offset, _Node2.Char.DIRECTIVES_END)) { + offset = Document.startCommentOrEndBlankLine(src, offset); + + switch (src[offset]) { + case '\n': + offset += 1; + break; + + case '#': + { + var comment = new _Comment.default(); + offset = comment.parse({ + src: src + }, offset); + this.directives.push(comment); + } + break; + + case '%': + { + var directive = new _Directive.default(); + offset = directive.parse({ + parent: this, + src: src + }, offset); + this.directives.push(directive); + hasDirectives = true; + } + break; + + default: + if (hasDirectives) { + this.error = new _errors.YAMLSyntaxError(this, 'Missing directives-end indicator line'); + } else if (this.directives.length > 0) { + this.contents = this.directives; + this.directives = []; + } + + return offset; + } + } + + if (src[offset]) return offset + 3; + + if (hasDirectives) { + this.error = new _errors.YAMLSyntaxError(this, 'Missing directives-end indicator line'); + } else if (this.directives.length > 0) { + this.contents = this.directives; + this.directives = []; + } + + return offset; + } + }, { + key: "parseContents", + value: function parseContents(start) { + var _this$context = this.context, + parseNode = _this$context.parseNode, + src = _this$context.src; + if (!this.contents) this.contents = []; + var lineStart = start; + + while (src[lineStart - 1] === '-') { + lineStart -= 1; + } + + var offset = _Node2.default.endOfWhiteSpace(src, start); + + var atLineStart = lineStart === start; + this.valueRange = new _Range.default(offset); + + while (!_Node2.default.atDocumentBoundary(src, offset, _Node2.Char.DOCUMENT_END)) { + switch (src[offset]) { + case '\n': + offset += 1; + lineStart = offset; + atLineStart = true; + break; + + case '#': + { + var comment = new _Comment.default(); + offset = comment.parse({ + src: src + }, offset); + this.contents.push(comment); + } + break; + + default: + { + var iEnd = _Node2.default.endOfIndent(src, offset); + + var context = { + atLineStart: atLineStart, + indent: -1, + inFlow: false, + inCollection: false, + lineStart: lineStart, + parent: this + }; + var node = parseNode(context, iEnd); + if (!node) return iEnd; // at next document start + + this.contents.push(node); + this.valueRange.end = node.valueRange.end; + offset = node.range.end; + atLineStart = false; + } + } + + offset = Document.startCommentOrEndBlankLine(src, offset); + } + + if (src[offset]) { + offset += 3; + + if (src[offset]) { + offset = _Node2.default.endOfWhiteSpace(src, offset); + + if (src[offset] === '#') { + var _comment = new _Comment.default(); + + offset = _comment.parse({ + src: src + }, offset); + this.contents.push(_comment); + } + + switch (src[offset]) { + case '\n': + offset += 1; + break; + + case undefined: + break; + + default: + this.error = new _errors.YAMLSyntaxError(this, 'Document end marker line should not have a non-comment suffix'); + } + } + } + + return offset; + } + /** + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this + */ + + }, { + key: "parse", + value: function parse(context, start) { + this.context = context; + var src = context.src; + var offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM + + offset = this.parseDirectives(offset); + offset = this.parseContents(offset); + return offset; + } + }, { + key: "toString", + value: function toString() { + var contents = this.contents, + src = this.context.src, + directives = this.directives, + value = this.value; + if (value != null) return value; + var str = directives.join(''); + + if (contents.length > 0) { + if (directives.length > 0 || contents[0].type === _Node2.Type.COMMENT) str += '---\n'; + str += contents.join(''); + } + + if (str[str.length - 1] !== '\n') str += '\n'; + return str; + } + }]); + + _inherits(Document, _Node); + + return Document; +}(_Node2.default); + +exports.default = Document; \ No newline at end of file diff --git a/dist/ast/FlowCollection.js b/dist/ast/FlowCollection.js new file mode 100644 index 00000000..092f3401 --- /dev/null +++ b/dist/ast/FlowCollection.js @@ -0,0 +1,185 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _errors = require("../errors"); + +var _Comment = _interopRequireDefault(require("./Comment")); + +var _Node2 = _interopRequireWildcard(require("./Node")); + +var _Range = _interopRequireDefault(require("./Range")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var FlowCollection = +/*#__PURE__*/ +function (_Node) { + function FlowCollection(type, props) { + var _this; + + _classCallCheck(this, FlowCollection); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(FlowCollection).call(this, type, props)); + _this.items = null; + return _this; + } + + _createClass(FlowCollection, [{ + key: "prevNodeIsJsonLike", + value: function prevNodeIsJsonLike() { + var idx = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.items.length; + var node = this.items[idx - 1]; + return !!node && (node.jsonLike || node.type === _Node2.Type.COMMENT && this.nodeIsJsonLike(idx - 1)); + } + /** + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this + */ + + }, { + key: "parse", + value: function parse(context, start) { + this.context = context; + var parseNode = context.parseNode, + src = context.src; + var indent = context.indent, + lineStart = context.lineStart; + var ch = src[start]; // { or [ + + this.items = [ch]; + + var offset = _Node2.default.endOfWhiteSpace(src, start + 1); + + ch = src[offset]; + + while (ch && ch !== ']' && ch !== '}') { + switch (ch) { + case '\n': + { + lineStart = offset + 1; + offset = _Node2.default.endOfIndent(src, lineStart); + if (offset - lineStart <= indent) this.error = new _errors.YAMLSyntaxError(this, 'Insufficient indentation in flow collection'); + } + break; + + case ',': + { + this.items.push(ch); + offset += 1; + } + break; + + case '#': + { + var comment = new _Comment.default(); + offset = comment.parse({ + src: src + }, offset); + this.items.push(comment); + } + break; + + case '?': + case ':': + { + var next = src[offset + 1]; + + if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace + ch === ':' && this.prevNodeIsJsonLike()) { + this.items.push(ch); + offset += 1; + break; + } // fallthrough + + } + + default: + { + var node = parseNode({ + atLineStart: false, + inCollection: false, + inFlow: true, + indent: -1, + lineStart: lineStart, + parent: this + }, offset); + + if (!node) { + // at next document start + this.valueRange = new _Range.default(start, offset); + return offset; + } + + this.items.push(node); + offset = _Node2.default.normalizeOffset(src, node.range.end); + } + } + + offset = _Node2.default.endOfWhiteSpace(src, offset); + ch = src[offset]; + } + + this.valueRange = new _Range.default(start, offset + 1); + + if (ch) { + this.items.push(ch); + offset = _Node2.default.endOfWhiteSpace(src, offset + 1); + offset = this.parseComment(offset); + } + + return offset; + } + }, { + key: "toString", + value: function toString() { + var src = this.context.src, + items = this.items, + range = this.range, + value = this.value; + if (value != null) return value; + var nodes = items.filter(function (item) { + return item instanceof _Node2.default; + }); + var str = ''; + var prevEnd = range.start; + nodes.forEach(function (node) { + var prefix = src.slice(prevEnd, node.range.start); + prevEnd = node.range.end; + str += prefix + String(node); + }); + str += src.slice(prevEnd, range.end); + return _Node2.default.addStringTerminator(src, range.end, str); + } + }]); + + _inherits(FlowCollection, _Node); + + return FlowCollection; +}(_Node2.default); + +exports.default = FlowCollection; \ No newline at end of file diff --git a/dist/ast/Node.js b/dist/ast/Node.js new file mode 100644 index 00000000..a39cb07d --- /dev/null +++ b/dist/ast/Node.js @@ -0,0 +1,404 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.Char = exports.Type = void 0; + +var _Range = _interopRequireDefault(require("./Range")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var Type = { + ALIAS: 'ALIAS', + BLOCK_FOLDED: 'BLOCK_FOLDED', + BLOCK_LITERAL: 'BLOCK_LITERAL', + COMMENT: 'COMMENT', + DIRECTIVE: 'DIRECTIVE', + DOCUMENT: 'DOCUMENT', + FLOW_MAP: 'FLOW_MAP', + FLOW_SEQ: 'FLOW_SEQ', + MAP: 'MAP', + MAP_KEY: 'MAP_KEY', + MAP_VALUE: 'MAP_VALUE', + PLAIN: 'PLAIN', + QUOTE_DOUBLE: 'QUOTE_DOUBLE', + QUOTE_SINGLE: 'QUOTE_SINGLE', + SEQ: 'SEQ', + SEQ_ITEM: 'SEQ_ITEM' +}; +exports.Type = Type; +var Char = { + ANCHOR: '&', + COMMENT: '#', + TAG: '!', + DIRECTIVES_END: '-', + DOCUMENT_END: '.' + /** Root class of all nodes */ + +}; +exports.Char = Char; + +var Node = +/*#__PURE__*/ +function () { + _createClass(Node, null, [{ + key: "addStringTerminator", + value: function addStringTerminator(src, offset, str) { + if (str[str.length - 1] === '\n') return str; + var next = Node.endOfWhiteSpace(src, offset); + return next >= src.length || src[next] === '\n' ? str + '\n' : str; + } // ^(---|...) + + }, { + key: "atDocumentBoundary", + value: function atDocumentBoundary(src, offset, sep) { + var ch0 = src[offset]; + if (!ch0) return true; + var prev = src[offset - 1]; + if (prev && prev !== '\n') return false; + + if (sep) { + if (ch0 !== sep) return false; + } else { + if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false; + } + + var ch1 = src[offset + 1]; + var ch2 = src[offset + 2]; + if (ch1 !== ch0 || ch2 !== ch0) return false; + var ch3 = src[offset + 3]; + return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' '; + } + }, { + key: "endOfIdentifier", + value: function endOfIdentifier(src, offset) { + var ch = src[offset]; + var isVerbatim = ch === '<'; + var notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ',']; + + while (ch && notOk.indexOf(ch) === -1) { + ch = src[offset += 1]; + } + + if (isVerbatim && ch === '>') offset += 1; + return offset; + } + }, { + key: "endOfIndent", + value: function endOfIndent(src, offset) { + var ch = src[offset]; + + while (ch === ' ') { + ch = src[offset += 1]; + } + + return offset; + } + }, { + key: "endOfLine", + value: function endOfLine(src, offset) { + var ch = src[offset]; + + while (ch && ch !== '\n') { + ch = src[offset += 1]; + } + + return offset; + } + }, { + key: "endOfWhiteSpace", + value: function endOfWhiteSpace(src, offset) { + var ch = src[offset]; + + while (ch === '\t' || ch === ' ') { + ch = src[offset += 1]; + } + + return offset; + } + }, { + key: "startOfLine", + value: function startOfLine(src, offset) { + var ch = src[offset - 1]; + + while (ch && ch !== '\n') { + ch = src[offset -= 1]; + } + + return offset + 1; + } + /** + * End of indentation, or null if the line's indent level is not more + * than `indent` + * + * @param {string} src + * @param {number} indent + * @param {number} lineStart + * @returns {?number} + */ + + }, { + key: "endOfBlockIndent", + value: function endOfBlockIndent(src, indent, lineStart) { + var inEnd = Node.endOfIndent(src, lineStart); + + if (inEnd > lineStart + indent) { + return inEnd; + } else { + var wsEnd = Node.endOfWhiteSpace(src, inEnd); + var ch = src[wsEnd]; + if (!ch || ch === '\n') return wsEnd; + } + + return null; + } + }, { + key: "atBlank", + value: function atBlank(src, offset) { + var ch = src[offset]; + return ch === '\n' || ch === '\t' || ch === ' '; + } + }, { + key: "atCollectionItem", + value: function atCollectionItem(src, offset) { + var ch = src[offset]; + return (ch === '?' || ch === ':' || ch === '-') && Node.atBlank(src, offset + 1); + } + }, { + key: "nextNodeIsIndented", + value: function nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) { + if (!ch || indentDiff < 0) return false; + if (indentDiff > 0) return true; + return indicatorAsIndent && ch === '-'; + } // should be at line or string end, or at next non-whitespace char + + }, { + key: "normalizeOffset", + value: function normalizeOffset(src, offset) { + var ch = src[offset]; + return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node.endOfWhiteSpace(src, offset); + } // fold single newline into space, multiple newlines to N - 1 newlines + // presumes src[offset] === '\n' + + }, { + key: "foldNewline", + value: function foldNewline(src, offset, indent) { + var inCount = 0; + var error = false; + var fold = ''; + var ch = src[offset + 1]; + + while (ch === ' ' || ch === '\t' || ch === '\n') { + switch (ch) { + case '\n': + inCount = 0; + offset += 1; + fold += '\n'; + break; + + case '\t': + if (inCount <= indent) error = true; + offset = Node.endOfWhiteSpace(src, offset + 2) - 1; + break; + + case ' ': + inCount += 1; + offset += 1; + break; + } + + ch = src[offset + 1]; + } + + if (!fold) fold = ' '; + if (ch && inCount <= indent) error = true; + return { + fold: fold, + offset: offset, + error: error + }; + } + }]); + + function Node(type, props, context) { + _classCallCheck(this, Node); + + this.context = context || null; + this.error = null; + this.range = null; + this.valueRange = null; + this.props = props || []; + this.type = type; + this.value = null; + } + + _createClass(Node, [{ + key: "getPropValue", + value: function getPropValue(idx, key, skipKey) { + if (!this.context) return null; + var src = this.context.src; + var prop = this.props[idx]; + return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null; + } + }, { + key: "commentHasRequiredWhitespace", + value: function commentHasRequiredWhitespace(start) { + var src = this.context.src; + if (this.header && start === this.header.end) return false; + + if (this.valueRange) { + var end = this.valueRange.end; + return start !== end || Node.atBlank(src, end - 1); + } + } + }, { + key: "parseComment", + value: function parseComment(start) { + var src = this.context.src; + + if (src[start] === Char.COMMENT) { + var end = Node.endOfLine(src, start + 1); + var commentRange = new _Range.default(start, end); + this.props.push(commentRange); + return end; + } + + return start; + } + }, { + key: "toString", + value: function toString() { + var src = this.context.src, + range = this.range, + value = this.value; + if (value != null) return value; + var str = src.slice(range.start, range.end); + return Node.addStringTerminator(src, range.end, str); + } + }, { + key: "anchor", + get: function get() { + for (var i = 0; i < this.props.length; ++i) { + var anchor = this.getPropValue(i, Char.ANCHOR, true); + if (anchor != null) return anchor; + } + + return null; + } + }, { + key: "comment", + get: function get() { + var comments = []; + + for (var i = 0; i < this.props.length; ++i) { + var comment = this.getPropValue(i, Char.COMMENT, true); + if (comment != null) comments.push(comment); + } + + return comments.length > 0 ? comments.join('\n') : null; + } + }, { + key: "hasComment", + get: function get() { + if (this.context) { + var src = this.context.src; + + for (var i = 0; i < this.props.length; ++i) { + if (src[this.props[i].start] === Char.COMMENT) return true; + } + } + + return false; + } + }, { + key: "hasProps", + get: function get() { + if (this.context) { + var src = this.context.src; + + for (var i = 0; i < this.props.length; ++i) { + if (src[this.props[i].start] !== Char.COMMENT) return true; + } + } + + return false; + } + }, { + key: "jsonLike", + get: function get() { + var jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE]; + return jsonLikeTypes.indexOf(this.type) !== -1; + } + }, { + key: "rawValue", + get: function get() { + if (!this.valueRange || !this.context) return null; + var _this$valueRange = this.valueRange, + start = _this$valueRange.start, + end = _this$valueRange.end; + return this.context.src.slice(start, end); + } + }, { + key: "tag", + get: function get() { + for (var i = 0; i < this.props.length; ++i) { + var tag = this.getPropValue(i, Char.TAG, false); + + if (tag != null) { + if (tag[1] === '<') { + return { + verbatim: tag.slice(2, -1) + }; + } else { + var _tag$match = tag.match(/^(.*!)([^!]*)$/), + _tag$match2 = _slicedToArray(_tag$match, 3), + _ = _tag$match2[0], + handle = _tag$match2[1], + suffix = _tag$match2[2]; + + return { + handle: handle, + suffix: suffix + }; + } + } + } + + return null; + } + }, { + key: "valueRangeContainsNewline", + get: function get() { + if (!this.valueRange || !this.context) return false; + var _this$valueRange2 = this.valueRange, + start = _this$valueRange2.start, + end = _this$valueRange2.end; + var src = this.context.src; + + for (var i = start; i < end; ++i) { + if (src[i] === '\n') return true; + } + + return false; + } + }]); + + return Node; +}(); + +exports.default = Node; \ No newline at end of file diff --git a/dist/ast/ParseContext.js b/dist/ast/ParseContext.js new file mode 100644 index 00000000..0b11d84e --- /dev/null +++ b/dist/ast/ParseContext.js @@ -0,0 +1,282 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _errors = require("../errors"); + +var _Alias = _interopRequireDefault(require("./Alias")); + +var _BlockValue = _interopRequireDefault(require("./BlockValue")); + +var _Collection = _interopRequireDefault(require("./Collection")); + +var _CollectionItem = _interopRequireDefault(require("./CollectionItem")); + +var _FlowCollection = _interopRequireDefault(require("./FlowCollection")); + +var _Node = _interopRequireWildcard(require("./Node")); + +var _PlainValue = _interopRequireDefault(require("./PlainValue")); + +var _QuoteDouble = _interopRequireDefault(require("./QuoteDouble")); + +var _QuoteSingle = _interopRequireDefault(require("./QuoteSingle")); + +var _Range = _interopRequireDefault(require("./Range")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * @param {boolean} atLineStart - Node starts at beginning of line + * @param {boolean} inFlow - true if currently in a flow context + * @param {boolean} inCollection - true if currently in a collection context + * @param {number} indent - Current level of indentation + * @param {number} lineStart - Start of the current line + * @param {Node} parent - The parent of the node + * @param {string} src - Source of the YAML document + */ +var ParseContext = +/*#__PURE__*/ +function () { + _createClass(ParseContext, null, [{ + key: "parseType", + value: function parseType(src, offset, inFlow) { + switch (src[offset]) { + case '*': + return _Node.Type.ALIAS; + + case '>': + return _Node.Type.BLOCK_FOLDED; + + case '|': + return _Node.Type.BLOCK_LITERAL; + + case '{': + return _Node.Type.FLOW_MAP; + + case '[': + return _Node.Type.FLOW_SEQ; + + case '?': + return !inFlow && _Node.default.atBlank(src, offset + 1) ? _Node.Type.MAP_KEY : _Node.Type.PLAIN; + + case ':': + return !inFlow && _Node.default.atBlank(src, offset + 1) ? _Node.Type.MAP_VALUE : _Node.Type.PLAIN; + + case '-': + return !inFlow && _Node.default.atBlank(src, offset + 1) ? _Node.Type.SEQ_ITEM : _Node.Type.PLAIN; + + case '"': + return _Node.Type.QUOTE_DOUBLE; + + case "'": + return _Node.Type.QUOTE_SINGLE; + + default: + return _Node.Type.PLAIN; + } + } + }]); + + function ParseContext() { + var _this = this; + + var orig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + atLineStart = _ref.atLineStart, + inCollection = _ref.inCollection, + inFlow = _ref.inFlow, + indent = _ref.indent, + lineStart = _ref.lineStart, + parent = _ref.parent; + + _classCallCheck(this, ParseContext); + + _defineProperty(this, "parseNode", function (overlay, start) { + if (_Node.default.atDocumentBoundary(_this.src, start)) return null; + var context = new ParseContext(_this, overlay); + + var _context$parseProps = context.parseProps(start), + props = _context$parseProps.props, + type = _context$parseProps.type, + valueStart = _context$parseProps.valueStart; + + var node; + + switch (type) { + case _Node.Type.ALIAS: + node = new _Alias.default(type, props); + break; + + case _Node.Type.BLOCK_FOLDED: + case _Node.Type.BLOCK_LITERAL: + node = new _BlockValue.default(type, props); + break; + + case _Node.Type.FLOW_MAP: + case _Node.Type.FLOW_SEQ: + node = new _FlowCollection.default(type, props); + break; + + case _Node.Type.MAP_KEY: + case _Node.Type.MAP_VALUE: + case _Node.Type.SEQ_ITEM: + node = new _CollectionItem.default(type, props); + break; + + case _Node.Type.COMMENT: + case _Node.Type.PLAIN: + node = new _PlainValue.default(type, props); + break; + + case _Node.Type.QUOTE_DOUBLE: + node = new _QuoteDouble.default(type, props); + break; + + case _Node.Type.QUOTE_SINGLE: + node = new _QuoteSingle.default(type, props); + break; + + default: + node.error = new _errors.YAMLSyntaxError(node, "Unknown node type: ".concat(JSON.stringify(type))); + node.range = new _Range.default(start, start + 1); + return node; + } + + var offset = node.parse(context, valueStart); + var nodeEnd = _this.src[offset] === '\n' ? offset + 1 : offset; + + if (nodeEnd <= start) { + node.error = new Error("Node#parse consumed no characters"); + node.error.parseEnd = nodeEnd; + node.error.source = node; + nodeEnd = start + 1; + } + + node.range = new _Range.default(start, nodeEnd); + + if (context.nodeStartsCollection(node)) { + var collection = new _Collection.default(node); + offset = collection.parse(context, offset); + collection.range = new _Range.default(start, offset); + return collection; + } + + return node; + }); + + this.atLineStart = atLineStart != null ? atLineStart : orig.lineStart || false; + this.inCollection = inCollection != null ? inCollection : orig.inCollection || false; + this.inFlow = inFlow != null ? inFlow : orig.inFlow || false; + this.indent = indent != null ? indent : orig.indent; + this.lineStart = lineStart != null ? lineStart : orig.lineStart; + this.parent = parent != null ? parent : orig.parent || {}; + this.src = orig.src; + } // for logging + + + _createClass(ParseContext, [{ + key: "nodeStartsCollection", + value: function nodeStartsCollection(node) { + var inCollection = this.inCollection, + inFlow = this.inFlow, + src = this.src; + if (inCollection || inFlow) return false; + if (node instanceof _CollectionItem.default) return true; // check for implicit key + + var offset = node.range.end; + if (src[offset] === '\n' || src[offset - 1] === '\n') return false; + offset = _Node.default.endOfWhiteSpace(src, offset); + return src[offset] === ':'; + } // Anchor and tag are before type, which determines the node implementation + // class; hence this intermediate step. + + }, { + key: "parseProps", + value: function parseProps(offset) { + var inFlow = this.inFlow, + parent = this.parent, + src = this.src; + var props = []; + var lineHasProps = false; + offset = _Node.default.endOfWhiteSpace(src, offset); + var ch = src[offset]; + + while (ch === _Node.Char.ANCHOR || ch === _Node.Char.COMMENT || ch === _Node.Char.TAG || ch === '\n') { + if (ch === '\n') { + var lineStart = offset + 1; + + var inEnd = _Node.default.endOfIndent(src, lineStart); + + var indentDiff = inEnd - (lineStart + this.indent); + var noIndicatorAsIndent = parent.type === _Node.Type.SEQ_ITEM && parent.context.atLineStart; + if (!_Node.default.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break; + this.atLineStart = true; + this.lineStart = lineStart; + lineHasProps = false; + offset = inEnd; + } else if (ch === _Node.Char.COMMENT) { + var end = _Node.default.endOfLine(src, offset + 1); + + props.push(new _Range.default(offset, end)); + offset = end; + } else { + var _end = _Node.default.endOfIdentifier(src, offset + 1); + + props.push(new _Range.default(offset, _end)); + lineHasProps = true; + offset = _Node.default.endOfWhiteSpace(src, _end); + } + + ch = src[offset]; + } // '- &a : b' has an anchor on an empty node + + + if (lineHasProps && ch === ':' && _Node.default.atBlank(src, offset + 1)) offset -= 1; + var type = ParseContext.parseType(src, offset, inFlow); + return { + props: props, + type: type, + valueStart: offset + }; + } + /** + * Parses a node from the source + * @param {ParseContext} overlay + * @param {number} start - Index of first non-whitespace character for the node + * @returns {?Node} - null if at a document boundary + */ + + }, { + key: "pretty", + get: function get() { + var obj = { + start: "".concat(this.lineStart, " + ").concat(this.indent), + in: [], + parent: this.parent.type + }; + if (!this.atLineStart) obj.start += ' + N'; + if (this.inCollection) obj.in.push('collection'); + if (this.inFlow) obj.in.push('flow'); + return obj; + } + }]); + + return ParseContext; +}(); + +exports.default = ParseContext; \ No newline at end of file diff --git a/dist/ast/PlainValue.js b/dist/ast/PlainValue.js new file mode 100644 index 00000000..2c3acb52 --- /dev/null +++ b/dist/ast/PlainValue.js @@ -0,0 +1,186 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _Node2 = _interopRequireDefault(require("./Node")); + +var _Range = _interopRequireDefault(require("./Range")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var PlainValue = +/*#__PURE__*/ +function (_Node) { + function PlainValue() { + _classCallCheck(this, PlainValue); + + return _possibleConstructorReturn(this, _getPrototypeOf(PlainValue).apply(this, arguments)); + } + + _createClass(PlainValue, [{ + key: "parseBlockValue", + value: function parseBlockValue(start) { + var _this$context = this.context, + indent = _this$context.indent, + inFlow = _this$context.inFlow, + src = _this$context.src; + var offset = start; + + for (var ch = src[offset]; ch === '\n'; ch = src[offset]) { + if (_Node2.default.atDocumentBoundary(src, offset + 1)) break; + + var end = _Node2.default.endOfBlockIndent(src, indent, offset + 1); + + if (end === null || src[end] === '#') break; + offset = PlainValue.endOfLine(src, end, inFlow); + } + + if (this.valueRange.isEmpty) this.valueRange.start = start; + this.valueRange.end = offset; + return offset; + } + /** + * Parses a plain value from the source + * + * Accepted forms are: + * ``` + * #comment + * + * first line + * + * first line #comment + * + * first line + * block + * lines + * + * #comment + * block + * lines + * ``` + * where block lines are empty or have an indent level greater than `indent`. + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar, may be `\n` + */ + + }, { + key: "parse", + value: function parse(context, start) { + this.context = context; + var inFlow = context.inFlow, + src = context.src; + var offset = start; + var ch = src[offset]; + + if (ch && ch !== '#' && ch !== '\n') { + offset = PlainValue.endOfLine(src, start, inFlow); + } + + this.valueRange = new _Range.default(start, offset); + offset = _Node2.default.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + + if (!this.hasComment || this.valueRange.isEmpty) { + offset = this.parseBlockValue(offset); + } + + return offset; + } + }, { + key: "strValue", + get: function get() { + if (!this.valueRange || !this.context) return null; + var _this$valueRange = this.valueRange, + start = _this$valueRange.start, + end = _this$valueRange.end; + var src = this.context.src; + var ch = src[end - 1]; + + while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) { + ch = src[--end - 1]; + } + + ch = src[start]; + + while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) { + ch = src[++start]; + } + + var str = ''; + + for (var i = start; i < end; ++i) { + var _ch = src[i]; + + if (_ch === '\n') { + var _Node$foldNewline = _Node2.default.foldNewline(src, i, -1), + fold = _Node$foldNewline.fold, + offset = _Node$foldNewline.offset; + + str += fold; + i = offset; + } else if (_ch === ' ' || _ch === '\t') { + // trim trailing whitespace + var wsStart = i; + var next = src[i + 1]; + + while (i < end && (next === ' ' || next === '\t')) { + i += 1; + next = src[i + 1]; + } + + if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : _ch; + } else { + str += _ch; + } + } + + return str; + } + }], [{ + key: "endOfLine", + value: function endOfLine(src, start, inFlow) { + var ch = src[start]; + var offset = start; + + while (ch && ch !== '\n') { + if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break; + var next = src[offset + 1]; + if (ch === ':' && (next === '\n' || next === '\t' || next === ' ' || next === ',')) break; + if ((ch === ' ' || ch === '\t') && next === '#') break; + offset += 1; + ch = next; + } + + return offset; + } + }]); + + _inherits(PlainValue, _Node); + + return PlainValue; +}(_Node2.default); + +exports.default = PlainValue; \ No newline at end of file diff --git a/dist/ast/QuoteDouble.js b/dist/ast/QuoteDouble.js new file mode 100644 index 00000000..5c091532 --- /dev/null +++ b/dist/ast/QuoteDouble.js @@ -0,0 +1,267 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _errors = require("../errors"); + +var _Node2 = _interopRequireDefault(require("./Node")); + +var _Range = _interopRequireDefault(require("./Range")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var QuoteDouble = +/*#__PURE__*/ +function (_Node) { + function QuoteDouble() { + _classCallCheck(this, QuoteDouble); + + return _possibleConstructorReturn(this, _getPrototypeOf(QuoteDouble).apply(this, arguments)); + } + + _createClass(QuoteDouble, [{ + key: "parseCharCode", + value: function parseCharCode(offset, length, errors) { + var src = this.context.src; + var cc = src.substr(offset, length); + var ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + var code = ok ? parseInt(cc, 16) : NaN; + + if (isNaN(code)) { + errors.push(new _errors.YAMLSyntaxError(this, "Invalid escape sequence ".concat(src.substr(offset - 2, length + 2)))); + return src.substr(offset - 2, length + 2); + } + + return String.fromCodePoint(code); + } + /** + * Parses a "double quoted" value from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar + */ + + }, { + key: "parse", + value: function parse(context, start) { + this.context = context; + var src = context.src; + var offset = QuoteDouble.endOfQuote(src, start + 1); + this.valueRange = new _Range.default(start, offset); + offset = _Node2.default.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + return offset; + } + }, { + key: "strValue", + + /** + * @returns {string | { str: string, errors: YAMLSyntaxError[] }} + */ + get: function get() { + if (!this.valueRange || !this.context) return null; + var errors = []; + var _this$valueRange = this.valueRange, + start = _this$valueRange.start, + end = _this$valueRange.end; + var _this$context = this.context, + indent = _this$context.indent, + src = _this$context.src; + if (src[end - 1] !== '"') errors.push(new _errors.YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by + // escaped backslashes; also, this should be faster. + + var str = ''; + + for (var i = start + 1; i < end - 1; ++i) { + var ch = src[i]; + + if (ch === '\n') { + if (_Node2.default.atDocumentBoundary(src, i + 1)) errors.push(new _errors.YAMLSyntaxError(this, 'Document boundary indicators are not allowed within string values')); + + var _Node$foldNewline = _Node2.default.foldNewline(src, i, indent), + fold = _Node$foldNewline.fold, + offset = _Node$foldNewline.offset, + error = _Node$foldNewline.error; + + str += fold; + i = offset; + if (error) errors.push(new _errors.YAMLSyntaxError(this, 'Multi-line double-quoted string needs to be sufficiently indented')); + } else if (ch === '\\') { + i += 1; + + switch (src[i]) { + case '0': + str += '\0'; + break; + // null character + + case 'a': + str += '\x07'; + break; + // bell character + + case 'b': + str += '\b'; + break; + // backspace + + case 'e': + str += '\x1b'; + break; + // escape character + + case 'f': + str += '\f'; + break; + // form feed + + case 'n': + str += '\n'; + break; + // line feed + + case 'r': + str += '\r'; + break; + // carriage return + + case 't': + str += '\t'; + break; + // horizontal tab + + case 'v': + str += '\v'; + break; + // vertical tab + + case 'N': + str += "\x85"; + break; + // Unicode next line + + case '_': + str += "\xA0"; + break; + // Unicode non-breaking space + + case 'L': + str += "\u2028"; + break; + // Unicode line separator + + case 'P': + str += "\u2029"; + break; + // Unicode paragraph separator + + case ' ': + str += ' '; + break; + + case '"': + str += '"'; + break; + + case '/': + str += '/'; + break; + + case '\\': + str += '\\'; + break; + + case '\t': + str += '\t'; + break; + + case 'x': + str += this.parseCharCode(i + 1, 2, errors); + i += 2; + break; + + case 'u': + str += this.parseCharCode(i + 1, 4, errors); + i += 4; + break; + + case 'U': + str += this.parseCharCode(i + 1, 8, errors); + i += 8; + break; + + case '\n': + // skip escaped newlines, but still trim the following line + while (src[i + 1] === ' ' || src[i + 1] === '\t') { + i += 1; + } + + break; + + default: + errors.push(new _errors.YAMLSyntaxError(this, "Invalid escape sequence ".concat(src.substr(i - 1, 2)))); + str += '\\' + src[i]; + } + } else if (ch === ' ' || ch === '\t') { + // trim trailing whitespace + var wsStart = i; + var next = src[i + 1]; + + while (next === ' ' || next === '\t') { + i += 1; + next = src[i + 1]; + } + + if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; + } else { + str += ch; + } + } + + return errors.length > 0 ? { + errors: errors, + str: str + } : str; + } + }], [{ + key: "endOfQuote", + value: function endOfQuote(src, offset) { + var ch = src[offset]; + + while (ch && ch !== '"') { + offset += ch === '\\' ? 2 : 1; + ch = src[offset]; + } + + return offset + 1; + } + }]); + + _inherits(QuoteDouble, _Node); + + return QuoteDouble; +}(_Node2.default); + +exports.default = QuoteDouble; \ No newline at end of file diff --git a/dist/ast/QuoteSingle.js b/dist/ast/QuoteSingle.js new file mode 100644 index 00000000..a31c93e4 --- /dev/null +++ b/dist/ast/QuoteSingle.js @@ -0,0 +1,142 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _errors = require("../errors"); + +var _Node2 = _interopRequireDefault(require("./Node")); + +var _Range = _interopRequireDefault(require("./Range")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var QuoteSingle = +/*#__PURE__*/ +function (_Node) { + function QuoteSingle() { + _classCallCheck(this, QuoteSingle); + + return _possibleConstructorReturn(this, _getPrototypeOf(QuoteSingle).apply(this, arguments)); + } + + _createClass(QuoteSingle, [{ + key: "parse", + + /** + * Parses a 'single quoted' value from the source + * + * @param {ParseContext} context + * @param {number} start - Index of first character + * @returns {number} - Index of the character after this scalar + */ + value: function parse(context, start) { + this.context = context; + var src = context.src; + var offset = QuoteSingle.endOfQuote(src, start + 1); + this.valueRange = new _Range.default(start, offset); + offset = _Node2.default.endOfWhiteSpace(src, offset); + offset = this.parseComment(offset); + return offset; + } + }, { + key: "strValue", + + /** + * @returns {string | { str: string, errors: YAMLSyntaxError[] }} + */ + get: function get() { + if (!this.valueRange || !this.context) return null; + var errors = []; + var _this$valueRange = this.valueRange, + start = _this$valueRange.start, + end = _this$valueRange.end; + var _this$context = this.context, + indent = _this$context.indent, + src = _this$context.src; + if (src[end - 1] !== "'") errors.push(new _errors.YAMLSyntaxError(this, "Missing closing 'quote")); + var str = ''; + + for (var i = start + 1; i < end - 1; ++i) { + var ch = src[i]; + + if (ch === '\n') { + if (_Node2.default.atDocumentBoundary(src, i + 1)) errors.push(new _errors.YAMLSyntaxError(this, 'Document boundary indicators are not allowed within string values')); + + var _Node$foldNewline = _Node2.default.foldNewline(src, i, indent), + fold = _Node$foldNewline.fold, + offset = _Node$foldNewline.offset, + error = _Node$foldNewline.error; + + str += fold; + i = offset; + if (error) errors.push(new _errors.YAMLSyntaxError(this, 'Multi-line single-quoted string needs to be sufficiently indented')); + } else if (ch === "'") { + str += ch; + i += 1; + if (src[i] !== "'") errors.push(new _errors.YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.')); + } else if (ch === ' ' || ch === '\t') { + // trim trailing whitespace + var wsStart = i; + var next = src[i + 1]; + + while (next === ' ' || next === '\t') { + i += 1; + next = src[i + 1]; + } + + if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; + } else { + str += ch; + } + } + + return errors.length > 0 ? { + errors: errors, + str: str + } : str; + } + }], [{ + key: "endOfQuote", + value: function endOfQuote(src, offset) { + var ch = src[offset]; + + while (ch) { + if (ch === "'") { + if (src[offset + 1] !== "'") break; + ch = src[offset += 2]; + } else { + ch = src[offset += 1]; + } + } + + return offset + 1; + } + }]); + + _inherits(QuoteSingle, _Node); + + return QuoteSingle; +}(_Node2.default); + +exports.default = QuoteSingle; \ No newline at end of file diff --git a/dist/ast/Range.js b/dist/ast/Range.js new file mode 100644 index 00000000..d2e1d79d --- /dev/null +++ b/dist/ast/Range.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var Range = +/*#__PURE__*/ +function () { + _createClass(Range, null, [{ + key: "copy", + value: function copy(orig) { + return new Range(orig.start, orig.end); + } + }]); + + function Range(start, end) { + _classCallCheck(this, Range); + + this.start = start; + this.end = end || start; + } + + _createClass(Range, [{ + key: "isEmpty", + get: function get() { + return typeof this.start !== 'number' || !this.end || this.end <= this.start; + } + }, { + key: "length", + get: function get() { + return this.isEmpty ? 0 : this.end - this.start; + } + }]); + + return Range; +}(); + +exports.default = Range; \ No newline at end of file diff --git a/dist/ast/parse.js b/dist/ast/parse.js new file mode 100644 index 00000000..42254294 --- /dev/null +++ b/dist/ast/parse.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parse; + +var _Document = _interopRequireDefault(require("./Document")); + +var _ParseContext = _interopRequireDefault(require("./ParseContext")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(src) { + if (src.indexOf('\r') !== -1) src = src.replace(/\r\n?/g, '\n'); + var context = new _ParseContext.default({ + src: src + }); + var documents = []; + var offset = 0; + + while (offset < src.length) { + var doc = new _Document.default(); + offset = doc.parse(context, offset); + documents.push(doc); + } + + documents.toString = function () { + return documents.join('...\n'); + }; + + return documents; +} \ No newline at end of file diff --git a/dist/errors.js b/dist/errors.js new file mode 100644 index 00000000..aec70ff7 --- /dev/null +++ b/dist/errors.js @@ -0,0 +1,112 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.YAMLWarning = exports.YAMLSyntaxError = exports.YAMLSemanticError = exports.YAMLReferenceError = void 0; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() {} Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, _setPrototypeOf(function Super() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); }, Class)); }; return _wrapNativeSuper(Class); } + +function _construct(Parent, args, Class) { if (typeof Reflect !== "undefined" && Reflect.construct) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Parent.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var YAMLReferenceError = +/*#__PURE__*/ +function (_ReferenceError) { + function YAMLReferenceError(source, message) { + var _this; + + _classCallCheck(this, YAMLReferenceError); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(YAMLReferenceError).call(this)); + _this.name = 'YAMLReferenceError'; + _this.message = message; + _this.source = source; + return _this; + } + + _inherits(YAMLReferenceError, _ReferenceError); + + return YAMLReferenceError; +}(_wrapNativeSuper(ReferenceError)); + +exports.YAMLReferenceError = YAMLReferenceError; + +var YAMLSemanticError = +/*#__PURE__*/ +function (_SyntaxError) { + function YAMLSemanticError(source, message) { + var _this2; + + _classCallCheck(this, YAMLSemanticError); + + _this2 = _possibleConstructorReturn(this, _getPrototypeOf(YAMLSemanticError).call(this)); + _this2.name = 'YAMLSemanticError'; + _this2.message = message; + _this2.source = source; + return _this2; + } + + _inherits(YAMLSemanticError, _SyntaxError); + + return YAMLSemanticError; +}(_wrapNativeSuper(SyntaxError)); + +exports.YAMLSemanticError = YAMLSemanticError; + +var YAMLSyntaxError = +/*#__PURE__*/ +function (_SyntaxError2) { + function YAMLSyntaxError(source, message) { + var _this3; + + _classCallCheck(this, YAMLSyntaxError); + + _this3 = _possibleConstructorReturn(this, _getPrototypeOf(YAMLSyntaxError).call(this)); + _this3.name = 'YAMLSyntaxError'; + _this3.message = message; + _this3.source = source; + return _this3; + } + + _inherits(YAMLSyntaxError, _SyntaxError2); + + return YAMLSyntaxError; +}(_wrapNativeSuper(SyntaxError)); + +exports.YAMLSyntaxError = YAMLSyntaxError; + +var YAMLWarning = +/*#__PURE__*/ +function (_Error) { + function YAMLWarning(source, message) { + var _this4; + + _classCallCheck(this, YAMLWarning); + + _this4 = _possibleConstructorReturn(this, _getPrototypeOf(YAMLWarning).call(this)); + _this4.name = 'YAMLWarning'; + _this4.message = message; + _this4.source = source; + return _this4; + } + + _inherits(YAMLWarning, _Error); + + return YAMLWarning; +}(_wrapNativeSuper(Error)); + +exports.YAMLWarning = YAMLWarning; \ No newline at end of file diff --git a/dist/foldFlowLines.js b/dist/foldFlowLines.js new file mode 100644 index 00000000..c523c471 --- /dev/null +++ b/dist/foldFlowLines.js @@ -0,0 +1,139 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = foldFlowLines; +exports.FOLD_QUOTED = exports.FOLD_BLOCK = exports.FOLD_FLOW = void 0; +var FOLD_FLOW = 'flow'; +exports.FOLD_FLOW = FOLD_FLOW; +var FOLD_BLOCK = 'block'; +exports.FOLD_BLOCK = FOLD_BLOCK; +var FOLD_QUOTED = 'quoted'; +/** + * Tries to keep input at up to `lineWidth` characters, splitting only on spaces + * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are + * terminated with `\n` and started with `indent`. + * + * @param {string} text + * @param {string} indent + * @param {string} [mode='flow'] `'block'` prevents more-indented lines + * from being folded; `'quoted'` allows for `\` escapes, including escaped + * newlines + * @param {Object} options + * @param {number} [options.indentAtStart] Accounts for leading contents on + * the first line, defaulting to `indent.length` + * @param {number} [options.lineWidth=80] + * @param {number} [options.minContentWidth=20] Allow highly indented lines to + * stretch the line width + * @param {function} options.onFold Called once if the text is folded + * @param {function} options.onFold Called once if any line of text exceeds + * lineWidth characters + */ + +exports.FOLD_QUOTED = FOLD_QUOTED; + +function foldFlowLines(text, indent, mode, _ref) { + var indentAtStart = _ref.indentAtStart, + _ref$lineWidth = _ref.lineWidth, + lineWidth = _ref$lineWidth === void 0 ? 80 : _ref$lineWidth, + _ref$minContentWidth = _ref.minContentWidth, + minContentWidth = _ref$minContentWidth === void 0 ? 20 : _ref$minContentWidth, + onFold = _ref.onFold, + onOverflow = _ref.onOverflow; + if (!lineWidth || lineWidth < 0) return text; + var endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) return text; + var folds = []; + var escapedFolds = {}; + var end = lineWidth - (typeof indentAtStart === 'number' ? indentAtStart : indent.length); + var split = undefined; + var prev = undefined; + var overflow = false; + + for (var i = 0, ch = text[0]; ch; ch = text[i += 1]) { + if (mode === FOLD_QUOTED && ch === '\\') { + switch (text[i + 1]) { + case 'x': + ch = text[i += 4]; + break; + + case 'u': + ch = text[i += 6]; + break; + + case 'U': + ch = text[i += 10]; + break; + + default: + ch = text[i += 2]; + } + } + + if (ch === '\n') { + if (mode === FOLD_BLOCK) { + // more-indented lines in blocks can't be folded + var next = text[i + 1]; + + while (next === ' ' || next === '\t') { + do { + ch = text[i += 1]; + } while (ch && ch !== '\n'); + + next = text[i + 1]; + } + } + + end = i + endStep; + split = undefined; + } else { + if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') { + // space surrounded by non-space can be replaced with newline + indent + var _next = text[i + 1]; + if (_next && _next !== ' ' && _next !== '\n' && _next !== '\t') split = i; + } + + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = undefined; + } else if (mode === FOLD_QUOTED) { + // white-space collected at end may stretch past lineWidth + while (prev === ' ' || prev === '\t') { + prev = ch; + ch = text[i += 1]; + overflow = true; + } // i - 2 accounts for not-dropped last char + newline-escaping \ + + + folds.push(i - 2); + escapedFolds[i - 2] = true; + end = i - 2 + endStep; + split = undefined; + } else { + overflow = true; + } + } + } + + prev = ch; + } + + if (overflow && onOverflow) onOverflow(); + if (folds.length === 0) return text; + if (onFold) onFold(); + var res = text.slice(0, folds[0]); + + for (var _i = 0; _i < folds.length; ++_i) { + var fold = folds[_i]; + + var _end = folds[_i + 1] || text.length; + + if (mode === FOLD_QUOTED && escapedFolds[fold]) res += "".concat(text[fold], "\\"); + res += "\n".concat(indent).concat(text.slice(fold + 1, _end)); + } + + return res; +} \ No newline at end of file diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 00000000..c97ec71f --- /dev/null +++ b/dist/index.js @@ -0,0 +1,96 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _parse = _interopRequireDefault(require("./ast/parse")); + +var _Document3 = _interopRequireDefault(require("./Document")); + +var _schema = _interopRequireDefault(require("./schema")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var defaultOptions = { + merge: false, + schema: 'core', + tags: null +}; + +function parseDocuments(src, options) { + var resolvedOptions = options ? Object.assign({}, defaultOptions, options) : defaultOptions; + var schema = new _schema.default(resolvedOptions); + return (0, _parse.default)(src).map(function (astDoc) { + return new _Document3.default(schema).parse(astDoc); + }); +} + +function parse(src, options) { + var docs = parseDocuments(src, options); + docs.forEach(function (doc) { + doc.warnings.forEach(function (warning) { + return console.warn(warning); + }); + doc.errors.forEach(function (error) { + throw error; + }); + }); + + if (docs.length > 1) { + throw new Error('Source contains multiple documents; please use YAML.parseDocuments()'); + } + + return docs[0] && docs[0].toJSON(); +} + +function stringify(value, options) { + var resolvedOptions = options ? Object.assign({}, defaultOptions, options) : defaultOptions; + var doc = new _Document3.default(resolvedOptions); + doc.contents = value; + return String(doc); +} + +var _default = { + defaultOptions: defaultOptions, + Document: + /*#__PURE__*/ + function (_Document2) { + function Document(schema) { + var _this; + + _classCallCheck(this, Document); + + if (schema instanceof _schema.default) { + _this = _possibleConstructorReturn(this, _getPrototypeOf(Document).call(this, schema)); + } else { + _this = _possibleConstructorReturn(this, _getPrototypeOf(Document).call(this, Object.assign({}, defaultOptions, schema))); + } + + return _possibleConstructorReturn(_this); + } + + _inherits(Document, _Document2); + + return Document; + }(_Document3.default), + parse: parse, + parseDocuments: parseDocuments, + stringify: stringify +}; +exports.default = _default; \ No newline at end of file diff --git a/dist/listTagNames.js b/dist/listTagNames.js new file mode 100644 index 00000000..25df8c68 --- /dev/null +++ b/dist/listTagNames.js @@ -0,0 +1,42 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _Collection = _interopRequireDefault(require("./schema/Collection")); + +var _Pair = _interopRequireDefault(require("./schema/Pair")); + +var _Scalar = _interopRequireDefault(require("./schema/Scalar")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +var visit = function visit(node, tags) { + if (node && _typeof(node) === 'object') { + var tag = node.origTag || node.tag; + + if (node instanceof _Collection.default) { + if (tag) tags[tag] = true; + node.items.forEach(function (n) { + return visit(n, tags); + }); + } else if (node instanceof _Pair.default) { + visit(node.key, tags); + visit(node.value, tags); + } else if (node instanceof _Scalar.default) { + if (tag) tags[tag] = true; + } + } + + return tags; +}; + +var _default = function _default(node) { + return Object.keys(visit(node, {})); +}; + +exports.default = _default; \ No newline at end of file diff --git a/dist/resolveValue.js b/dist/resolveValue.js new file mode 100644 index 00000000..e3209599 --- /dev/null +++ b/dist/resolveValue.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = resolveValue; + +var _Map = _interopRequireDefault(require("./schema/Map")); + +var _Pair = _interopRequireDefault(require("./schema/Pair")); + +var _Scalar = _interopRequireDefault(require("./schema/Scalar")); + +var _Seq = _interopRequireDefault(require("./schema/Seq")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function resolveValue(doc, value, wrapScalars) { + if (value == null) return new _Scalar.default(null); + if (_typeof(value) !== 'object') return wrapScalars ? new _Scalar.default(value) : value; + + if (Array.isArray(value)) { + var seq = new _Seq.default(doc); + seq.items = value.map(function (v) { + return resolveValue(doc, v, wrapScalars); + }); + return seq; + } else { + var map = new _Map.default(doc); + map.items = Object.keys(value).map(function (key) { + var k = resolveValue(doc, key, wrapScalars); + var v = resolveValue(doc, value[key], wrapScalars); + return new _Pair.default(k, v); + }); + return map; + } +} \ No newline at end of file diff --git a/dist/schema/Collection.js b/dist/schema/Collection.js new file mode 100644 index 00000000..28be0743 --- /dev/null +++ b/dist/schema/Collection.js @@ -0,0 +1,199 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.toJSON = void 0; + +var _addComment = _interopRequireDefault(require("../addComment")); + +var _errors = require("../errors"); + +var _Node2 = _interopRequireDefault(require("./Node")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +var toJSON = function toJSON(value) { + return Array.isArray(value) ? value.map(toJSON) : value && _typeof(value) === 'object' && 'toJSON' in value ? value.toJSON() : value; +}; + +exports.toJSON = toJSON; + +var Collection = +/*#__PURE__*/ +function (_Node) { + _createClass(Collection, null, [{ + key: "checkKeyLength", + value: function checkKeyLength(doc, node, itemIdx, key, keyStart) { + if (typeof keyStart !== 'number') return; + var item = node.items[itemIdx]; + var keyEnd = item && item.range && item.range.start; + + if (!keyEnd) { + for (var i = itemIdx - 1; i >= 0; --i) { + var it = node.items[i]; + + if (it && it.range) { + keyEnd = it.range.end + 2 * (itemIdx - i); + break; + } + } + } + + if (keyEnd > keyStart + 1024) { + var k = String(key).substr(0, 8) + '...' + String(key).substr(-8); + doc.errors.push(new _errors.YAMLSemanticError(node, "The \"".concat(k, "\" key is too long"))); + } + } + }]); + + function Collection(doc) { + var _this; + + _classCallCheck(this, Collection); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Collection).call(this)); + _this._comments = []; + _this.doc = doc; + _this.items = []; + return _this; + } + + _createClass(Collection, [{ + key: "addComment", + value: function addComment(comment) { + this._comments.push({ + comment: comment, + before: this.items.length + }); + } + }, { + key: "resolveComments", + value: function resolveComments() { + var _this2 = this; + + this._comments.forEach(function (_ref) { + var comment = _ref.comment, + before = _ref.before; + var item = _this2.items[before]; + + if (!item) { + if (_this2.comment) _this2.comment += '\n' + comment;else _this2.comment = comment; + } else { + if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment; + } + }); + + delete this._comments; + } // overridden in implementations + + }, { + key: "toJSON", + value: function toJSON() { + return null; + } + }, { + key: "toString", + value: function toString(options, onComment) { + var _this3 = this; + + var schema = this.doc.schema; + var blockItem = options.blockItem, + flowChars = options.flowChars, + indent = options.indent, + inFlow = options.inFlow, + itemIndent = options.itemIndent; + var opt = { + indent: itemIndent, + inFlow: inFlow, + type: null + }; + var hasItemWithComment = false; + var hasItemWithNewLine = false; + var nodes = this.items.reduce(function (nodes, item, i) { + var commentBefore = item && item.commentBefore; + + if (commentBefore) { + hasItemWithComment = true; + commentBefore.match(/^.*$/gm).forEach(function (line) { + nodes.push({ + type: 'comment', + str: "#".concat(line) + }); + }); + } + + var comment = item && item.comment; + if (comment) hasItemWithComment = true; + var str = schema.stringify(_this3.doc, item, opt, function () { + comment = null; + }); + if (!hasItemWithNewLine && str.indexOf('\n') !== -1) hasItemWithNewLine = true; + if (inFlow && i < _this3.items.length - 1) str += ','; + str = (0, _addComment.default)(str, opt.indent, comment); + nodes.push({ + type: 'item', + str: str + }); + return nodes; + }, []); + var str; + + if (nodes.length === 0) { + str = flowChars.start + flowChars.end; + } else if (inFlow) { + var start = flowChars.start, + end = flowChars.end; + var strings = nodes.map(function (_ref2) { + var str = _ref2.str; + return str; + }); + + if (hasItemWithComment || hasItemWithNewLine || strings.reduce(function (sum, str) { + return sum + str.length + 2; + }, 2) > Collection.maxFlowStringSingleLineLength) { + str = "".concat(start, "\n ").concat(indent).concat(strings.join("\n ".concat(indent)), "\n").concat(indent).concat(end); + } else { + str = "".concat(start, " ").concat(strings.join(' '), " ").concat(end); + } + } else { + str = nodes.map(blockItem).join("\n".concat(indent)); + } + + if (this.comment) { + if (!hasItemWithNewLine && str.indexOf('\n') === -1) str = (0, _addComment.default)(str, indent, this.comment);else str += '\n' + this.comment.replace(/^/gm, "".concat(indent, "#")); + if (onComment) onComment(); + } + + return str; + } + }]); + + _inherits(Collection, _Node); + + return Collection; +}(_Node2.default); + +exports.default = Collection; + +_defineProperty(Collection, "maxFlowStringSingleLineLength", 60); \ No newline at end of file diff --git a/dist/schema/Map.js b/dist/schema/Map.js new file mode 100644 index 00000000..42419439 --- /dev/null +++ b/dist/schema/Map.js @@ -0,0 +1,261 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _Node = require("../ast/Node"); + +var _errors = require("../errors"); + +var _Collection2 = _interopRequireWildcard(require("./Collection")); + +var _Pair = _interopRequireDefault(require("./Pair")); + +var _Seq = _interopRequireDefault(require("./Seq")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var YAMLMap = +/*#__PURE__*/ +function (_Collection) { + function YAMLMap() { + _classCallCheck(this, YAMLMap); + + return _possibleConstructorReturn(this, _getPrototypeOf(YAMLMap).apply(this, arguments)); + } + + _createClass(YAMLMap, [{ + key: "parse", + value: function parse(ast) { + var _this = this; + + ast.resolved = this; + + if (ast.type === _Node.Type.FLOW_MAP) { + this.resolveFlowMapItems(ast); + } else { + this.resolveBlockMapItems(ast); + } + + this.resolveComments(); + + for (var i = 0; i < this.items.length; ++i) { + var iKey = this.items[i].key; + + for (var j = i + 1; j < this.items.length; ++j) { + var jKey = this.items[j].key; + + if (iKey === jKey || iKey && jKey && iKey.hasOwnProperty('value') && iKey.value === jKey.value) { + this.doc.errors.push(new _errors.YAMLSemanticError(ast, "Map keys must be unique; \"".concat(iKey, "\" is repeated"))); + break; + } + } + + if (this.doc.schema.merge && iKey.value === '<<') { + var src = this.items[i].value; + var srcItems = src instanceof _Seq.default ? src.items.reduce(function (acc, _ref) { + var items = _ref.items; + return acc.concat(items); + }, []) : src.items; + var toAdd = srcItems.reduce(function (toAdd, pair) { + var exists = _this.items.some(function (_ref2) { + var key = _ref2.key; + return key.value === pair.key.value; + }) || toAdd.some(function (_ref3) { + var key = _ref3.key; + return key.value === pair.key.value; + }); + return exists ? toAdd : toAdd.concat(pair); + }, []); + Array.prototype.splice.apply(this.items, [i, 1].concat(_toConsumableArray(toAdd))); + i += toAdd.length - 1; + } + } + + return this; + } + }, { + key: "resolveBlockMapItems", + value: function resolveBlockMapItems(map) { + var key = undefined; + var keyStart = null; + + for (var i = 0; i < map.items.length; ++i) { + var item = map.items[i]; + + switch (item.type) { + case _Node.Type.COMMENT: + this.addComment(item.comment); + break; + + case _Node.Type.MAP_KEY: + if (key !== undefined) this.items.push(new _Pair.default(key)); + if (item.error) this.doc.errors.push(item.error); + key = this.doc.resolveNode(item.node); + keyStart = null; + break; + + case _Node.Type.MAP_VALUE: + if (key === undefined) key = null; + if (item.error) this.doc.errors.push(item.error); + + if (!item.context.atLineStart && item.node && item.node.type === _Node.Type.MAP && !item.node.context.atLineStart) { + this.doc.errors.push(new _errors.YAMLSemanticError(item.node, 'Nested mappings are not allowed in compact mappings')); + } + + this.items.push(new _Pair.default(key, this.doc.resolveNode(item.node))); + + _Collection2.default.checkKeyLength(this.doc, map, i, key, keyStart); + + key = undefined; + keyStart = null; + break; + + default: + if (key !== undefined) this.items.push(new _Pair.default(key)); + key = this.doc.resolveNode(item); + keyStart = item.range.start; + var nextItem = map.items[i + 1]; + if (!nextItem || nextItem.type !== _Node.Type.MAP_VALUE) this.doc.errors.push(new _errors.YAMLSemanticError(item.node, 'Implicit map keys need to be followed by map values')); + if (item.valueRangeContainsNewline) this.doc.errors.push(new _errors.YAMLSemanticError(item.node, 'Implicit map keys need to be on a single line')); + } + } + + if (key !== undefined) this.items.push(new _Pair.default(key)); + } + }, { + key: "resolveFlowMapItems", + value: function resolveFlowMapItems(map) { + var key = undefined; + var keyStart = null; + var explicitKey = false; + var next = '{'; + + for (var i = 0; i < map.items.length; ++i) { + _Collection2.default.checkKeyLength(this.doc, map, i, key, keyStart); + + var item = map.items[i]; + + if (typeof item === 'string') { + if (item === '?' && key === undefined && !explicitKey) { + explicitKey = true; + next = ':'; + continue; + } + + if (item === ':') { + if (key === undefined) key = null; + + if (next === ':') { + next = ','; + continue; + } + } else { + if (explicitKey) { + if (key === undefined && item !== ',') key = null; + explicitKey = false; + } + + if (key !== undefined) { + this.items.push(new _Pair.default(key)); + key = undefined; + keyStart = null; + } + } + + if (item === '}') { + if (i === map.items.length - 1) continue; + } else if (item === next || next === ':' && item === ',') { + next = ':'; + continue; + } + + this.doc.errors.push(new _errors.YAMLSemanticError(map, "Flow map contains an unexpected ".concat(item))); + } else if (item.type === _Node.Type.COMMENT) { + this.addComment(item.comment); + } else if (key === undefined) { + if (next === ',') this.doc.errors.push(new _errors.YAMLSemanticError(item, 'Separator , missing in flow map')); + key = this.doc.resolveNode(item); + keyStart = explicitKey ? null : item.range.start; // TODO: add error for non-explicit multiline plain key + } else { + if (next !== ',') this.doc.errors.push(new _errors.YAMLSemanticError(item, 'Indicator : missing in flow map entry')); + this.items.push(new _Pair.default(key, this.doc.resolveNode(item))); + key = undefined; + explicitKey = false; + } + } + + if (key !== undefined) this.items.push(new _Pair.default(key)); + } + }, { + key: "toJSON", + value: function toJSON() { + return this.items.reduce(function (map, _ref4) { + var stringKey = _ref4.stringKey, + value = _ref4.value; + map[stringKey] = (0, _Collection2.toJSON)(value); + return map; + }, {}); + } + }, { + key: "toString", + value: function toString() { + var indent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var inFlow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + var onComment = arguments.length > 2 ? arguments[2] : undefined; + return _get(_getPrototypeOf(YAMLMap.prototype), "toString", this).call(this, { + blockItem: function blockItem(_ref5) { + var str = _ref5.str; + return str; + }, + flowChars: { + start: '{', + end: '}' + }, + indent: indent, + inFlow: inFlow, + itemIndent: indent + (inFlow ? ' ' : '') + }, onComment); + } + }]); + + _inherits(YAMLMap, _Collection); + + return YAMLMap; +}(_Collection2.default); + +exports.default = YAMLMap; \ No newline at end of file diff --git a/dist/schema/Node.js b/dist/schema/Node.js new file mode 100644 index 00000000..c4216d6d --- /dev/null +++ b/dist/schema/Node.js @@ -0,0 +1,18 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var Node = function Node() { + _classCallCheck(this, Node); + + _defineProperty(_defineProperty(_defineProperty(_defineProperty(this, "anchor", null), "comment", null), "commentBefore", null), "tag", null); +}; + +exports.default = Node; \ No newline at end of file diff --git a/dist/schema/Pair.js b/dist/schema/Pair.js new file mode 100644 index 00000000..f1b3dca4 --- /dev/null +++ b/dist/schema/Pair.js @@ -0,0 +1,99 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _addComment = _interopRequireDefault(require("../addComment")); + +var _Collection = _interopRequireWildcard(require("./Collection")); + +var _Scalar = _interopRequireDefault(require("./Scalar")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var Pair = +/*#__PURE__*/ +function () { + function Pair(key) { + var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + + _classCallCheck(this, Pair); + + this.key = key; + this.value = value; + } + + _createClass(Pair, [{ + key: "toJSON", + value: function toJSON() { + var pair = {}; + pair[this.stringKey] = (0, _Collection.toJSON)(this.value); + return pair; + } + }, { + key: "toString", + value: function toString(doc, options, onComment) { + if (!doc) return JSON.stringify(this); + var key = this.key, + value = this.value; + var indent = options.indent; + var explicitKey = !key || key.comment || key instanceof _Collection.default; + var opt = Object.assign({}, options, { + implicitKey: !explicitKey, + indent: options.indent + ' ' + }); + var keyComment = key && key.comment; + var keyStr = doc.schema.stringify(doc, key, opt, function () { + keyComment = null; + }); + if (keyComment) keyStr = (0, _addComment.default)(keyStr, opt.indent, keyComment); + opt.implicitKey = false; + var valueStr = doc.schema.stringify(doc, value, opt, onComment); + + if (explicitKey) { + return "? ".concat(keyStr, "\n").concat(indent, ": ").concat(valueStr); + } else if (value instanceof _Collection.default) { + return "".concat(keyStr, ":\n").concat(opt.indent).concat(valueStr); + } else { + return "".concat(keyStr, ": ").concat(valueStr); + } + } + }, { + key: "comment", + get: function get() { + return this.value && this.value.comment; + }, + set: function set(comment) { + if (this.value == null) this.value = new _Scalar.default(null); + this.value.comment = comment; + } + }, { + key: "stringKey", + get: function get() { + var key = (0, _Collection.toJSON)(this.key); + if (key === null) return ''; + if (_typeof(key) === 'object') try { + return JSON.stringify(key); + } catch (e) { + /* should not happen, but let's ignore in any case */ + } + return String(key); + } + }]); + + return Pair; +}(); + +exports.default = Pair; \ No newline at end of file diff --git a/dist/schema/Scalar.js b/dist/schema/Scalar.js new file mode 100644 index 00000000..453d2665 --- /dev/null +++ b/dist/schema/Scalar.js @@ -0,0 +1,62 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _Collection = require("./Collection"); + +var _Node2 = _interopRequireDefault(require("./Node")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var Scalar = +/*#__PURE__*/ +function (_Node) { + function Scalar(value) { + var _this; + + _classCallCheck(this, Scalar); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(Scalar).call(this)); + _this.value = value; + return _this; + } + + _createClass(Scalar, [{ + key: "toJSON", + value: function toJSON() { + return (0, _Collection.toJSON)(this.value); + } + }, { + key: "toString", + value: function toString() { + return String(this.value); + } + }]); + + _inherits(Scalar, _Node); + + return Scalar; +}(_Node2.default); + +exports.default = Scalar; \ No newline at end of file diff --git a/dist/schema/Seq.js b/dist/schema/Seq.js new file mode 100644 index 00000000..ca4737be --- /dev/null +++ b/dist/schema/Seq.js @@ -0,0 +1,181 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _Node = require("../ast/Node"); + +var _errors = require("../errors"); + +var _Collection2 = _interopRequireWildcard(require("./Collection")); + +var _Pair = _interopRequireDefault(require("./Pair")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } + +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } + +var YAMLSeq = +/*#__PURE__*/ +function (_Collection) { + function YAMLSeq() { + _classCallCheck(this, YAMLSeq); + + return _possibleConstructorReturn(this, _getPrototypeOf(YAMLSeq).apply(this, arguments)); + } + + _createClass(YAMLSeq, [{ + key: "parse", + value: function parse(ast) { + ast.resolved = this; + + if (ast.type === _Node.Type.FLOW_SEQ) { + this.resolveFlowSeqItems(ast); + } else { + this.resolveBlockSeqItems(ast); + } + + this.resolveComments(); + return this; + } + }, { + key: "resolveBlockSeqItems", + value: function resolveBlockSeqItems(seq) { + for (var i = 0; i < seq.items.length; ++i) { + var item = seq.items[i]; + + switch (item.type) { + case _Node.Type.COMMENT: + this.addComment(item.comment); + break; + + case _Node.Type.SEQ_ITEM: + if (item.error) this.doc.errors.push(item.error); + this.items.push(this.doc.resolveNode(item.node)); + if (item.hasProps) this.doc.errors.push(new _errors.YAMLSemanticError(item, 'Sequence items cannot have tags or anchors before the - indicator')); + break; + + default: + this.doc.errors.push(new _errors.YAMLSemanticError(item, "Unexpected ".concat(item.type, " node in sequence"))); + } + } + } + }, { + key: "resolveFlowSeqItems", + value: function resolveFlowSeqItems(seq) { + var explicitKey = false; + var key = undefined; + var keyStart = null; + var next = '['; + + for (var i = 0; i < seq.items.length; ++i) { + var item = seq.items[i]; + + if (typeof item === 'string') { + if (item !== ':' && (explicitKey || key !== undefined)) { + if (explicitKey && key === undefined) key = null; + this.items.push(new _Pair.default(key)); + explicitKey = false; + key = undefined; + keyStart = null; + } + + if (item === next) { + next = null; + } else if (!next && item === '?') { + explicitKey = true; + } else if (next !== '[' && item === ':' && key === undefined) { + if (next === ',') { + key = this.items.pop(); + if (key instanceof _Pair.default) this.doc.errors.push(new _errors.YAMLSemanticError(item, 'Chaining flow sequence pairs is invalid (e.g. [ a : b : c ])')); + if (!explicitKey) _Collection2.default.checkKeyLength(this.doc, seq, i, key, keyStart); + } else { + key = null; + } + + keyStart = null; + explicitKey = false; // TODO: add error for non-explicit multiline plain key + + next = null; + } else if (next === '[' || item !== ']' || i < seq.items.length - 1) { + this.doc.errors.push(new _errors.YAMLSemanticError(seq, "Flow sequence contains an unexpected ".concat(item))); + } + } else if (item.type === _Node.Type.COMMENT) { + this.addComment(item.comment); + } else { + if (next) this.doc.errors.push(new _errors.YAMLSemanticError(item, "Expected a ".concat(next, " here in flow sequence"))); + var value = this.doc.resolveNode(item); + + if (key === undefined) { + this.items.push(value); + } else { + this.items.push(new _Pair.default(key, value)); + key = undefined; + } + + keyStart = item.range.start; + next = ','; + } + } + + if (seq.items[seq.items.length - 1] !== ']') this.doc.errors.push(new _errors.YAMLSemanticError(seq, 'Expected flow sequence to end with ]')); + if (key !== undefined) this.items.push(new _Pair.default(key)); + } + }, { + key: "toJSON", + value: function toJSON() { + return this.items.map(_Collection2.toJSON); + } + }, { + key: "toString", + value: function toString() { + var indent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var inFlow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + var onComment = arguments.length > 2 ? arguments[2] : undefined; + return _get(_getPrototypeOf(YAMLSeq.prototype), "toString", this).call(this, { + blockItem: function blockItem(_ref) { + var type = _ref.type, + str = _ref.str; + return type === 'comment' ? str : "- ".concat(str); + }, + flowChars: { + start: '[', + end: ']' + }, + indent: indent, + inFlow: inFlow, + itemIndent: indent + (inFlow ? ' ' : ' ') + }, onComment); + } + }]); + + _inherits(YAMLSeq, _Collection); + + return YAMLSeq; +}(_Collection2.default); + +exports.default = YAMLSeq; \ No newline at end of file diff --git a/dist/schema/_binary.js b/dist/schema/_binary.js new file mode 100644 index 00000000..66d86c61 --- /dev/null +++ b/dist/schema/_binary.js @@ -0,0 +1,78 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.binary = void 0; + +var _errors = require("../errors"); + +var _string = require("./_string"); + +var binary = { + class: Uint8Array, + // Buffer inherits from Uint8Array + tag: 'tag:yaml.org,2002:binary', + + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve: function resolve(doc, node) { + if (typeof Buffer === 'function') { + var str = (0, _string.resolve)(doc, node); + return Buffer.from(str, 'base64'); + } else if (typeof atob === 'function') { + var _str = atob((0, _string.resolve)(doc, node)); + + var buffer = new Uint8Array(_str.length); + + for (var i = 0; i < _str.length; ++i) { + buffer[i] = _str.charCodeAt(i); + } + + return buffer; + } else { + doc.errors.push(new _errors.YAMLReferenceError(node, 'This environment does not support reading binary tags; either Buffer or atob is required')); + return null; + } + }, + options: { + lineWidth: 76 + }, + stringify: function stringify(_ref) { + var value = _ref.value; + var str; + + if (typeof Buffer === 'function') { + str = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64'); + } else if (typeof btoa === 'function') { + var s = ''; + + for (var i = 0; i < value.length; ++i) { + s += String.fromCharCode(buf[i]); + } + + str = btoa(s); + } else { + throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required'); + } + + var lineWidth = binary.options.lineWidth; + var n = Math.ceil(str.length / lineWidth); + var lines = new Array(n); + + for (var _i = 0, o = 0; _i < n; ++_i, o += lineWidth) { + lines[_i] = str.substr(o, lineWidth); + } + + return lines.join('\n'); + } +}; +exports.binary = binary; +var _default = [binary]; +exports.default = _default; \ No newline at end of file diff --git a/dist/schema/_string.js b/dist/schema/_string.js new file mode 100644 index 00000000..8a00087f --- /dev/null +++ b/dist/schema/_string.js @@ -0,0 +1,302 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.str = exports.resolve = exports.strOptions = void 0; + +var _addComment = require("../addComment"); + +var _Node = require("../ast/Node"); + +var _foldFlowLines = _interopRequireWildcard(require("../foldFlowLines")); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } + +var strOptions = { + defaultType: _Node.Type.PLAIN, + dropCR: false, + doubleQuoted: { + jsonEncoding: false, + minMultiLineLength: 40 + }, + fold: { + lineWidth: 80, + minContentWidth: 20 + } +}; +exports.strOptions = strOptions; + +var resolve = function resolve(doc, node) { + // on error, will return { str: string, errors: Error[] } + var res = node.strValue; + if (!res) return ''; + if (typeof res === 'string') return res; + res.errors.forEach(function (error) { + if (!error.source) error.source = node; + doc.errors.push(error); + }); + return res.str; +}; + +exports.resolve = resolve; + +function doubleQuotedString(value, indent, oneLine) { + var _strOptions$doubleQuo = strOptions.doubleQuoted, + jsonEncoding = _strOptions$doubleQuo.jsonEncoding, + minMultiLineLength = _strOptions$doubleQuo.minMultiLineLength; + var json = JSON.stringify(value); + if (jsonEncoding) return json; + var str = ''; + var start = 0; + + for (var i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') { + // space before newline needs to be escaped to not be folded + str += json.slice(start, i) + '\\ '; + i += 1; + start = i; + ch = '\\'; + } + + if (ch === '\\') switch (json[i + 1]) { + case 'u': + str += json.slice(start, i); + var code = json.substr(i + 2, 4); + + switch (code) { + case '0000': + str += '\\0'; + break; + + case '0007': + str += '\\a'; + break; + + case '000b': + str += '\\v'; + break; + + case '001b': + str += '\\e'; + break; + + case '0085': + str += '\\N'; + break; + + case '00a0': + str += '\\_'; + break; + + case '2028': + str += '\\L'; + break; + + case '2029': + str += '\\P'; + break; + + default: + if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6); + } + + i += 5; + start = i + 1; + break; + + case 'n': + if (oneLine || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + // folding will eat first newline + str += json.slice(start, i) + '\n\n'; + + while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') { + str += '\n'; + i += 2; + } + + str += indent; // space after newline needs to be escaped to not be folded + + if (json[i + 2] === ' ') str += '\\'; + i += 1; + start = i + 1; + } + + break; + + default: + i += 1; + } + } + + str = start ? str + json.slice(start) : json; + return oneLine ? str : (0, _foldFlowLines.default)(str, indent, _foldFlowLines.FOLD_QUOTED, strOptions.fold); +} + +function singleQuotedString(value, indent, oneLine) { + if (oneLine) { + if (/\n/.test(value)) return doubleQuotedString(value, indent, true); + } else { + // single quoted string can't have leading or trailing whitespace around newline + if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, indent, false); + } + + value = "'" + value.replace(/'/g, "''").replace(/\n+/g, "$&\n".concat(indent)) + "'"; + return oneLine ? value : (0, _foldFlowLines.default)(value, indent, _foldFlowLines.FOLD_FLOW, strOptions.fold); +} + +function blockString(value, indent, literal, forceBlockIndent, comment, onComment) { + // block can't end in whitespace unless the last line is non-empty + if (/\n[\t ]+$/.test(value)) return doubleQuotedString(value, indent, false); + if (forceBlockIndent && !indent) indent = ' '; + var indentSize = indent ? '2' : '1'; // root is at -1 + + var header = literal ? '|' : '>'; + if (!value) return header + '\n'; + var wsStart = ''; + var wsEnd = ''; + value = value.replace(/[\n\t ]*$/, function (ws) { + var n = ws.indexOf('\n'); + + if (n === -1) { + header += '-'; // strip + } else if (value === ws || n !== ws.length - 1) { + header += '+'; // keep + } + + wsEnd = ws.replace(/\n$/, ''); + return ''; + }).replace(/^[\n ]*/, function (ws) { + if (ws.indexOf(' ') !== -1) header += indentSize; + var m = ws.match(/ +$/); + + if (m) { + wsStart = ws.slice(0, -m[0].length); + return m[0]; + } else { + wsStart = ws; + return ''; + } + }); + if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, "$&".concat(indent)); + if (wsStart) wsStart = wsStart.replace(/\n+/g, "$&".concat(indent)); + + if (comment) { + header += ' #' + comment.replace(/ ?[\r\n]+/g, ' '); + if (onComment) onComment(); + } + + if (!value) return "".concat(header).concat(indentSize, "\n").concat(indent).concat(wsEnd); + + if (literal) { + value = value.replace(/\n+/g, "$&".concat(indent)); + return "".concat(header, "\n").concat(indent).concat(wsStart).concat(value).concat(wsEnd); + } + + value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded + // ^ ind.line ^ empty ^ capture next empty lines only at end of indent + .replace(/\n+/g, "$&".concat(indent)); + var body = (0, _foldFlowLines.default)("".concat(wsStart).concat(value).concat(wsEnd), indent, _foldFlowLines.FOLD_BLOCK, strOptions.fold); + return "".concat(header, "\n").concat(indent).concat(body); +} + +function plainString(value, indent, implicitKey, inFlow, forceBlockIndent, tags, comment, onComment) { + if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) { + return doubleQuotedString(value, indent, implicitKey); + } + + if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t ]$/.test(value)) { + // not allowed: + // - empty string + // - start with an indicator character (except [?:-]) or /[?-] / + // - '\n ', ': ' or ' \n' anywhere + // - '#' not preceded by a non-space char + // - end with ' ' + return implicitKey || inFlow ? doubleQuotedString(value, indent, implicitKey) : blockString(value, indent, false, forceBlockIndent, comment, onComment); + } // Need to verify that output will be parsed as a string + + + var str = value.replace(/\n+/g, "$&\n".concat(indent)); + + if (typeof tags.resolveScalar(str).value !== 'string') { + return doubleQuotedString(value, indent, implicitKey); + } + + var body = implicitKey ? str : (0, _foldFlowLines.default)(str, indent, _foldFlowLines.FOLD_FLOW, strOptions.fold); + + if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) { + if (onComment) onComment(); + return (0, _addComment.addCommentBefore)(body, indent, comment); + } + + return body; +} + +var str = { + class: String, + tag: 'tag:yaml.org,2002:str', + resolve: resolve, + options: strOptions, + stringify: function stringify(_ref) { + var comment = _ref.comment, + value = _ref.value; + + var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + forceBlockIndent = _ref2.forceBlockIndent, + implicitKey = _ref2.implicitKey, + indent = _ref2.indent, + inFlow = _ref2.inFlow, + tags = _ref2.tags, + type = _ref2.type; + + var onComment = arguments.length > 2 ? arguments[2] : undefined; + var dropCR = strOptions.dropCR, + defaultType = strOptions.defaultType; + if (typeof value !== 'string') value = String(value); + if (dropCR && /\r/.test(value)) value = value.replace(/\r\n?/g, '\n'); + + var _stringify = function _stringify(_type) { + switch (_type) { + case _Node.Type.BLOCK_FOLDED: + return blockString(value, indent, false, forceBlockIndent, comment, onComment); + + case _Node.Type.BLOCK_LITERAL: + return blockString(value, indent, true, forceBlockIndent, comment, onComment); + + case _Node.Type.QUOTE_DOUBLE: + return doubleQuotedString(value, indent, implicitKey, comment); + + case _Node.Type.QUOTE_SINGLE: + return singleQuotedString(value, indent, implicitKey, comment); + + case _Node.Type.PLAIN: + return plainString(value, indent, implicitKey, inFlow, forceBlockIndent, tags, comment, onComment); + + default: + return null; + } + }; + + if (type !== _Node.Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) { + // force double quotes on control characters + type = _Node.Type.QUOTE_DOUBLE; + } else if (inFlow && (type === _Node.Type.BLOCK_FOLDED || type === _Node.Type.BLOCK_LITERAL)) { + // should not happen; blocks are not valid inside flow containers + type = _Node.Type.QUOTE_DOUBLE; + } + + var res = _stringify(type); + + if (res === null) { + res = _stringify(defaultType); + if (res === null) throw new Error("Unsupported default string type ".concat(defaultType)); + } + + return res; + } +}; +exports.str = str; +var _default = [str]; +exports.default = _default; \ No newline at end of file diff --git a/dist/schema/_timestamp.js b/dist/schema/_timestamp.js new file mode 100644 index 00000000..e2d5cd0d --- /dev/null +++ b/dist/schema/_timestamp.js @@ -0,0 +1,99 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.timestamp = exports.floatTime = exports.intTime = void 0; + +var _core = require("./core"); + +var parseSexagesimal = function parseSexagesimal(sign, parts) { + var n = parts.split(':').reduce(function (n, p) { + return n * 60 + Number(p); + }, 0); + return sign === '-' ? -n : n; +}; // hhhh:mm:ss.sss + + +var stringifySexagesimal = function stringifySexagesimal(_ref) { + var value = _ref.value; + if (!isNan(value) || !isFinite(value)) return (0, _core.stringifyNumber)(value); + var sign = ''; + + if (value < 0) { + sign = '-'; + value = Math.abs(value); + } + + var parts = [value % 60]; // seconds, including ms + + if (value < 60) { + parts.unshift(0); // at least one : is required + } else { + value = Math.round((value - parts[0]) / 60); + parts.unshift(value % 60); // minutes + + if (value >= 60) { + value = Math.round((value - parts[0]) / 60); + parts.unshift(value); // hours + } + } + + return sign + parts.map(function (n) { + return n < 10 ? '0' + String(n) : String(n); + }).join(':'); +}; + +var intTime = { + class: Number, + tag: 'tag:yaml.org,2002:int', + format: 'time', + test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/, + resolve: function resolve(str, sign, parts) { + return parseSexagesimal(sign, parts.replace(/_/g, '')); + }, + stringify: stringifySexagesimal +}; +exports.intTime = intTime; +var floatTime = { + class: Number, + tag: 'tag:yaml.org,2002:float', + format: 'time', + test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/, + resolve: function resolve(str, sign, parts) { + return parseSexagesimal(sign, parts.replace(/_/g, '')); + }, + stringify: stringifySexagesimal +}; +exports.floatTime = floatTime; +var timestamp = { + class: Date, + tag: 'tag:yaml.org,2002:timestamp', + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp('^(?:' + '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd + '(?:(?:t|T|[ \\t]+)' + // t | T | whitespace + '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)? + '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30 + ')?' + ')$'), + resolve: function resolve(str, year, month, day, hour, minute, second, millisec, tz) { + if (millisec) millisec = (millisec + '00').substr(1, 3); + var date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0); + + if (tz && tz !== 'Z') { + var d = parseSexagesimal(tz[0], tz.slice(1)); + if (Math.abs(d) < 30) d *= 60; + date -= 60000 * d; + } + + return new Date(date); + }, + stringify: function stringify(_ref2) { + var value = _ref2.value; + return value.toISOString(); + } +}; +exports.timestamp = timestamp; +var _default = [intTime, floatTime, timestamp]; +exports.default = _default; \ No newline at end of file diff --git a/dist/schema/core.js b/dist/schema/core.js new file mode 100644 index 00000000..f26b8e35 --- /dev/null +++ b/dist/schema/core.js @@ -0,0 +1,91 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.nullOptions = exports.stringifyNumber = void 0; + +var _failsafe = _interopRequireDefault(require("./failsafe")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var stringifyNumber = function stringifyNumber(_ref) { + var value = _ref.value; + return isFinite(value) ? JSON.stringify(value) : isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf'; +}; + +exports.stringifyNumber = stringifyNumber; +var nullOptions = { + nullStr: 'null' +}; +exports.nullOptions = nullOptions; + +var _default = _failsafe.default.concat([{ + class: null, + tag: 'tag:yaml.org,2002:null', + test: /^(?:~|null)?$/i, + resolve: function resolve() { + return null; + }, + options: nullOptions, + stringify: function stringify() { + return nullOptions.nullStr; + } +}, { + class: Boolean, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:true|false)$/i, + resolve: function resolve(str) { + return str[0] === 't' || str[0] === 'T'; + } +}, { + class: Number, + tag: 'tag:yaml.org,2002:int', + format: 'oct', + test: /^0o([0-7]+)$/, + resolve: function resolve(str, oct) { + return parseInt(oct, 8); + }, + stringify: function stringify(_ref2) { + var value = _ref2.value; + return '0o' + value.toString(8); + } +}, { + class: Number, + tag: 'tag:yaml.org,2002:int', + test: /^[-+]?[0-9]+$/, + resolve: function resolve(str) { + return parseInt(str, 10); + }, + stringify: stringifyNumber +}, { + class: Number, + tag: 'tag:yaml.org,2002:int', + format: 'hex', + test: /^0x([0-9a-fA-F]+)$/, + resolve: function resolve(str, hex) { + return parseInt(hex, 16); + }, + stringify: function stringify(_ref3) { + var value = _ref3.value; + return '0x' + value.toString(16); + } +}, { + class: Number, + tag: 'tag:yaml.org,2002:float', + test: /^(?:[-+]?\.inf|(\.nan))$/i, + resolve: function resolve(str, nan) { + return nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY; + }, + stringify: stringifyNumber +}, { + class: Number, + tag: 'tag:yaml.org,2002:float', + test: /^[-+]?(0|[1-9][0-9]*)(\.[0-9]*)?([eE][-+]?[0-9]+)?$/, + resolve: function resolve(str) { + return parseFloat(str); + }, + stringify: stringifyNumber +}]); + +exports.default = _default; \ No newline at end of file diff --git a/dist/schema/extended.js b/dist/schema/extended.js new file mode 100644 index 00000000..cc2f7f85 --- /dev/null +++ b/dist/schema/extended.js @@ -0,0 +1,127 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.boolOptions = exports.nullOptions = void 0; + +var _errors = require("../errors"); + +var _binary = _interopRequireDefault(require("./_binary")); + +var _timestamp = _interopRequireDefault(require("./_timestamp")); + +var _core = require("./core"); + +var _failsafe = _interopRequireDefault(require("./failsafe")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nullOptions = { + nullStr: 'null' +}; +exports.nullOptions = nullOptions; +var boolOptions = { + trueStr: 'true', + falseStr: 'false' +}; +exports.boolOptions = boolOptions; + +var _default = _failsafe.default.concat([{ + class: null, + tag: 'tag:yaml.org,2002:null', + test: /^(?:~|null)?$/i, + resolve: function resolve() { + return null; + }, + options: nullOptions, + stringify: function stringify() { + return nullOptions.nullStr; + } +}, { + class: Boolean, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:y|yes|true|on)$/i, + resolve: function resolve() { + return true; + }, + options: boolOptions, + stringify: function stringify(_ref) { + var value = _ref.value; + return value ? boolOptions.trueStr : boolOptions.falseStr; + } +}, { + class: Boolean, + tag: 'tag:yaml.org,2002:bool', + test: /^(?:n|no|false|off)$/i, + resolve: function resolve() { + return false; + }, + options: boolOptions, + stringify: function stringify(_ref2) { + var value = _ref2.value; + return value ? boolOptions.trueStr : boolOptions.falseStr; + } +}, { + class: Number, + tag: 'tag:yaml.org,2002:int', + format: 'bin', + test: /^0b([0-1_]+)$/, + resolve: function resolve(str, bin) { + return parseInt(bin.replace(/_/g, ''), 2); + }, + stringify: function stringify(_ref3) { + var value = _ref3.value; + return '0b' + value.toString(2); + } +}, { + class: Number, + tag: 'tag:yaml.org,2002:int', + format: 'oct', + test: /^[-+]?0([0-7_]+)$/, + resolve: function resolve(str, oct) { + return parseInt(oct.replace(/_/g, ''), 8); + }, + stringify: function stringify(_ref4) { + var value = _ref4.value; + return (value < 0 ? '-0' : '0') + value.toString(8); + } +}, { + class: Number, + tag: 'tag:yaml.org,2002:int', + test: /^[-+]?[0-9][0-9_]*$/, + resolve: function resolve(str) { + return parseInt(str.replace(/_/g, ''), 10); + }, + stringify: _core.stringifyNumber +}, { + class: Number, + tag: 'tag:yaml.org,2002:int', + format: 'hex', + test: /^0x([0-9a-fA-F_]+)$/, + resolve: function resolve(str, hex) { + return parseInt(hex.replace(/_/g, ''), 16); + }, + stringify: function stringify(_ref5) { + var value = _ref5.value; + return (value < 0 ? '-0x' : '0x') + value.toString(16); + } +}, { + class: Number, + tag: 'tag:yaml.org,2002:float', + test: /^(?:[-+]?\.inf|(\.nan))$/i, + resolve: function resolve(str, nan) { + return nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY; + }, + stringify: _core.stringifyNumber +}, { + class: Number, + tag: 'tag:yaml.org,2002:float', + test: /^[-+]?([0-9][0-9_]*)?\.[0-9_]*([eE][-+]?[0-9]+)?$/, + resolve: function resolve(str) { + return parseFloat(str.replace(/_/g, '')); + }, + stringify: _core.stringifyNumber +}], _timestamp.default, _binary.default); + +exports.default = _default; \ No newline at end of file diff --git a/dist/schema/failsafe.js b/dist/schema/failsafe.js new file mode 100644 index 00000000..aaa5e178 --- /dev/null +++ b/dist/schema/failsafe.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.seq = exports.map = void 0; + +var _Node = require("../ast/Node"); + +var _Map = _interopRequireDefault(require("./Map")); + +var _Seq = _interopRequireDefault(require("./Seq")); + +var _string = require("./_string"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var map = { + class: _Map.default, + tag: 'tag:yaml.org,2002:map', + resolve: function resolve(doc, node) { + return new _Map.default(doc).parse(node); + }, + stringify: function stringify(value, _ref, onComment) { + var indent = _ref.indent, + inFlow = _ref.inFlow; + return value.toString(indent, inFlow, onComment); + } +}; +exports.map = map; +var seq = { + class: _Seq.default, + tag: 'tag:yaml.org,2002:seq', + resolve: function resolve(doc, node) { + return new _Seq.default(doc).parse(node); + }, + stringify: function stringify(value, _ref2, onComment) { + var indent = _ref2.indent, + inFlow = _ref2.inFlow; + return value.toString(indent, inFlow, onComment); + } +}; +exports.seq = seq; +var _default = [map, seq, _string.str]; +exports.default = _default; \ No newline at end of file diff --git a/dist/schema/index.js b/dist/schema/index.js new file mode 100644 index 00000000..077d0647 --- /dev/null +++ b/dist/schema/index.js @@ -0,0 +1,258 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.DefaultTags = exports.DefaultTagPrefixes = exports.availableSchema = void 0; + +var _Node = require("../ast/Node"); + +var _errors = require("../errors"); + +var _Collection = _interopRequireDefault(require("./Collection")); + +var _core = _interopRequireDefault(require("./core")); + +var _extended = _interopRequireDefault(require("./extended")); + +var _failsafe = _interopRequireDefault(require("./failsafe")); + +var _json = _interopRequireDefault(require("./json")); + +var _Pair = _interopRequireDefault(require("./Pair")); + +var _Scalar = _interopRequireDefault(require("./Scalar")); + +var _string = require("./_string"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var availableSchema = { + core: _core.default, + extended: _extended.default, + failsafe: _failsafe.default, + json: _json.default +}; +exports.availableSchema = availableSchema; +var defaultPrefix = 'tag:yaml.org,2002:'; +var DefaultTagPrefixes = [{ + handle: '!', + prefix: '!' +}, { + handle: '!!', + prefix: defaultPrefix +}]; +exports.DefaultTagPrefixes = DefaultTagPrefixes; +var DefaultTags = { + MAP: 'tag:yaml.org,2002:map', + SEQ: 'tag:yaml.org,2002:seq', + STR: 'tag:yaml.org,2002:str' +}; +exports.DefaultTags = DefaultTags; + +var isMap = function isMap(_ref) { + var type = _ref.type; + return type === _Node.Type.FLOW_MAP || type === _Node.Type.MAP; +}; + +var isSeq = function isSeq(_ref2) { + var type = _ref2.type; + return type === _Node.Type.FLOW_SEQ || type === _Node.Type.SEQ; +}; + +var Schema = +/*#__PURE__*/ +function () { + _createClass(Schema, null, [{ + key: "defaultStringifier", + value: function defaultStringifier(value) { + return JSON.stringify(value); + } + }]); + + function Schema(_ref3) { + var merge = _ref3.merge, + schema = _ref3.schema, + tags = _ref3.tags; + + _classCallCheck(this, Schema); + + this.merge = !!merge; + this.schema = Array.isArray(schema) ? schema : availableSchema[schema]; + + if (!this.schema) { + var keys = Object.keys(availableSchema).map(function (key) { + return JSON.stringify(key); + }).join(', '); + throw new Error("Unknown schema; use ".concat(keys, ", or { tag, test, resolve }[]")); + } + + if (Array.isArray(tags)) { + this.schema = this.schema.concat(tags); + } else if (typeof tags === 'function') { + this.schema = tags(this.schema.slice()); + } + } // falls back to string on no match + + + _createClass(Schema, [{ + key: "resolveScalar", + value: function resolveScalar(str, tags) { + if (!tags) tags = this.schema; + + for (var i = 0; i < tags.length; ++i) { + var _tags$i = tags[i], + test = _tags$i.test, + resolve = _tags$i.resolve; + + if (test) { + var match = str.match(test); + if (match) return new _Scalar.default(resolve.apply(null, match)); + } + } + + if (this.schema.scalarFallback) str = this.schema.scalarFallback(str); + return new _Scalar.default(str); + } // sets node.resolved on success + + }, { + key: "resolveNode", + value: function resolveNode(doc, node, tagName) { + var tags = this.schema.filter(function (_ref4) { + var tag = _ref4.tag; + return tag === tagName; + }); + var generic = tags.find(function (_ref5) { + var test = _ref5.test; + return !test; + }); + if (node.error) doc.errors.push(node.error); + + try { + if (generic) { + var res = generic.resolve(doc, node); + if (!(res instanceof _Collection.default)) res = new _Scalar.default(res); + node.resolved = res; + } else { + var str = (0, _string.resolve)(doc, node); + + if (typeof str === 'string' && tags.length > 0) { + node.resolved = this.resolveScalar(str, tags); + } + } + } catch (error) { + if (!error.source) error.source = node; + doc.errors.push(error); + node.resolved = null; + } + + if (!node.resolved) return null; + if (node.hasProps) node.resolved.anchor = node.anchor; + if (tagName) node.resolved.tag = tagName; + return node.resolved; + } + }, { + key: "resolveNodeWithFallback", + value: function resolveNodeWithFallback(doc, node, tagName) { + var res = this.resolveNode(doc, node, tagName); + if (node.hasOwnProperty('resolved')) return res; + var fallback = isMap(node) ? DefaultTags.MAP : isSeq(node) ? DefaultTags.SEQ : DefaultTags.STR; + + if (fallback) { + doc.warnings.push(new _errors.YAMLWarning(node, "The tag ".concat(tagName, " is unavailable, falling back to ").concat(fallback))); + + var _res = this.resolveNode(doc, node, fallback); + + _res.origTag = tagName; + return _res; + } else { + doc.errors.push(new _errors.YAMLReferenceError(node, "The tag ".concat(tagName, " is unavailable"))); + } + + return null; + } + }, { + key: "stringify", + value: function stringify(doc, item, options, onComment) { + if (!(item instanceof _Scalar.default || item instanceof _Collection.default || item instanceof _Pair.default)) { + item = doc.resolveValue(item, true); + } + + options.tags = this; + var match; + + if (item instanceof _Pair.default) { + return item.toString(doc, options, onComment); + } else if (item.tag) { + match = this.schema.filter(function (_ref6) { + var format = _ref6.format, + tag = _ref6.tag; + return tag === item.tag && (!item.format || format === item.format); + }); + if (match.length === 0) throw new Error("Tag not available: ".concat(item.tag).concat(item.format ? ', format ' + item.format : '')); + } else if (item.value === null) { + match = this.schema.filter(function (t) { + return t.class === null && !t.format; + }); + if (match.length === 0) throw new Error('Schema is missing a null stringifier'); + } else { + var obj = item; + + if (item.hasOwnProperty('value')) { + switch (_typeof(item.value)) { + case 'boolean': + obj = new Boolean(); + break; + + case 'number': + obj = new Number(); + break; + + case 'string': + obj = new String(); + break; + + default: + obj = item.value; + } + } + + match = this.schema.filter(function (t) { + return t.class && obj instanceof t.class && !t.format; + }); + if (match.length === 0) throw new Error("Tag not resolved for ".concat(obj && obj.constructor ? obj.constructor.name : _typeof(obj))); + } + + var stringify = match[0].stringify || Schema.defaultStringifier; + var str = stringify(item, options, onComment); + var tag = item.origTag || item.tag; + + if (tag && tag.indexOf(defaultPrefix) !== 0) { + var p = doc.tagPrefixes.find(function (p) { + return tag.indexOf(p.prefix) === 0; + }); + var tagProp = p ? p.handle + tag.substr(p.prefix.length) : tag[0] === '!' ? tag : "!<".concat(tag, ">"); + + if (item instanceof _Collection.default && !options.inFlow && item.items.length > 0) { + return "".concat(tagProp, "\n").concat(options.indent).concat(str); + } else { + return "".concat(tagProp, " ").concat(str); + } + } + + return str; + } + }]); + + return Schema; +}(); + +exports.default = Schema; \ No newline at end of file diff --git a/dist/schema/json.js b/dist/schema/json.js new file mode 100644 index 00000000..125c652e --- /dev/null +++ b/dist/schema/json.js @@ -0,0 +1,58 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _failsafe = require("./failsafe"); + +var _string = require("./_string"); + +var schema = [_failsafe.map, _failsafe.seq, { + class: String, + tag: 'tag:yaml.org,2002:str', + resolve: _string.resolve +}, { + class: null, + tag: 'tag:yaml.org,2002:null', + test: /^null$/, + resolve: function resolve() { + return null; + } +}, { + class: Boolean, + tag: 'tag:yaml.org,2002:bool', + test: /^true$/, + resolve: function resolve() { + return true; + } +}, { + class: Boolean, + tag: 'tag:yaml.org,2002:bool', + test: /^false$/, + resolve: function resolve() { + return false; + } +}, { + class: Number, + tag: 'tag:yaml.org,2002:int', + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: function resolve(str) { + return parseInt(str, 10); + } +}, { + class: Number, + tag: 'tag:yaml.org,2002:float', + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: function resolve(str) { + return parseFloat(str); + } +}]; + +schema.scalarFallback = function (str) { + throw new SyntaxError("Unresolved plain scalar ".concat(JSON.stringify(str))); +}; + +var _default = schema; +exports.default = _default; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 6beed2c6..71933912 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "yaml", - "version": "1.0.0-beta.5", + "version": "1.0.0-beta.6", "lockfileVersion": 1, "requires": true, "dependencies": {