node_modules: upgrade

This commit is contained in:
Dawid Dziurla
2024-01-17 10:08:10 +01:00
parent 9ff0bc8d99
commit 00765f79cf
320 changed files with 31840 additions and 1039 deletions

4
node_modules/yaml/README.md generated vendored
View File

@@ -14,6 +14,10 @@ It has no external dependencies and runs on Node.js as well as modern browsers.
For the purposes of versioning, any changes that break any of the documented endpoints or APIs will be considered semver-major breaking changes.
Undocumented library internals may change between minor versions, and previous APIs may be deprecated (but not removed).
The minimum supported TypeScript version of the included typings is 3.9;
for use in earlier versions you may need to set `skipLibCheck: true` in your config.
This requirement may be updated between minor versions of the library.
For more information, see the project's documentation site: [**eemeli.org/yaml**](https://eemeli.org/yaml/)
To install:

View File

@@ -1,38 +1,50 @@
import { isNode, isMap } from '../nodes/Node.js';
import { isNode } from '../nodes/identity.js';
import { Scalar } from '../nodes/Scalar.js';
import { YAMLMap } from '../nodes/YAMLMap.js';
import { YAMLSeq } from '../nodes/YAMLSeq.js';
import { resolveBlockMap } from './resolve-block-map.js';
import { resolveBlockSeq } from './resolve-block-seq.js';
import { resolveFlowCollection } from './resolve-flow-collection.js';
function composeCollection(CN, ctx, token, tagToken, onError) {
let coll;
switch (token.type) {
case 'block-map': {
coll = resolveBlockMap(CN, ctx, token, onError);
break;
}
case 'block-seq': {
coll = resolveBlockSeq(CN, ctx, token, onError);
break;
}
case 'flow-collection': {
coll = resolveFlowCollection(CN, ctx, token, onError);
break;
}
}
if (!tagToken)
return coll;
const tagName = ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));
if (!tagName)
return coll;
// Cast needed due to: https://github.com/Microsoft/TypeScript/issues/3841
function resolveCollection(CN, ctx, token, onError, tagName, tag) {
const coll = token.type === 'block-map'
? resolveBlockMap(CN, ctx, token, onError, tag)
: token.type === 'block-seq'
? resolveBlockSeq(CN, ctx, token, onError, tag)
: resolveFlowCollection(CN, ctx, token, onError, tag);
const Coll = coll.constructor;
// If we got a tagName matching the class, or the tag name is '!',
// then use the tagName from the node class used to create it.
if (tagName === '!' || tagName === Coll.tagName) {
coll.tag = Coll.tagName;
return coll;
}
const expType = isMap(coll) ? 'map' : 'seq';
let tag = ctx.schema.tags.find(t => t.collection === expType && t.tag === tagName);
if (tagName)
coll.tag = tagName;
return coll;
}
function composeCollection(CN, ctx, token, tagToken, onError) {
const tagName = !tagToken
? null
: ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));
const expType = token.type === 'block-map'
? 'map'
: token.type === 'block-seq'
? 'seq'
: token.start.source === '{'
? 'map'
: 'seq';
// shortcut: check if it's a generic YAMLMap or YAMLSeq
// before jumping into the custom tag logic.
if (!tagToken ||
!tagName ||
tagName === '!' ||
(tagName === YAMLMap.tagName && expType === 'map') ||
(tagName === YAMLSeq.tagName && expType === 'seq') ||
!expType) {
return resolveCollection(CN, ctx, token, onError, tagName);
}
let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);
if (!tag) {
const kt = ctx.schema.knownTags[tagName];
if (kt && kt.collection === expType) {
@@ -40,12 +52,17 @@ function composeCollection(CN, ctx, token, tagToken, onError) {
tag = kt;
}
else {
onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);
coll.tag = tagName;
return coll;
if (kt?.collection) {
onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection}`, true);
}
else {
onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);
}
return resolveCollection(CN, ctx, token, onError, tagName);
}
}
const res = tag.resolve(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options);
const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);
const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll;
const node = isNode(res)
? res
: new Scalar(res);

View File

@@ -26,6 +26,7 @@ function composeDoc(options, directives, { offset, start, value, end }, onError)
!props.hasNewline)
onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');
}
// @ts-expect-error If Contents is set, let's trust the user
doc.contents = value
? composeNode(ctx, value, props, onError)
: composeEmptyNode(ctx, props.end, start, null, props, onError);

View File

@@ -1,4 +1,4 @@
import { SCALAR, isScalar } from '../nodes/Node.js';
import { SCALAR, isScalar } from '../nodes/identity.js';
import { Scalar } from '../nodes/Scalar.js';
import { resolveBlockScalar } from './resolve-block-scalar.js';
import { resolveFlowScalar } from './resolve-flow-scalar.js';

View File

@@ -1,7 +1,7 @@
import { Directives } from '../doc/directives.js';
import { Document } from '../doc/Document.js';
import { YAMLWarning, YAMLParseError } from '../errors.js';
import { isCollection, isPair } from '../nodes/Node.js';
import { isCollection, isPair } from '../nodes/identity.js';
import { composeDoc } from './compose-doc.js';
import { resolveEnd } from './resolve-end.js';

View File

@@ -6,8 +6,9 @@ import { flowIndentCheck } from './util-flow-indent-check.js';
import { mapIncludes } from './util-map-includes.js';
const startColMsg = 'All mapping items must start at the same column';
function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError) {
const map = new YAMLMap(ctx.schema);
function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {
const NodeClass = tag?.nodeClass ?? YAMLMap;
const map = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset = bm.offset;

View File

@@ -2,8 +2,9 @@ import { YAMLSeq } from '../nodes/YAMLSeq.js';
import { resolveProps } from './resolve-props.js';
import { flowIndentCheck } from './util-flow-indent-check.js';
function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError) {
const seq = new YAMLSeq(ctx.schema);
function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {
const NodeClass = tag?.nodeClass ?? YAMLSeq;
const seq = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset = bs.offset;

View File

@@ -1,4 +1,4 @@
import { isPair } from '../nodes/Node.js';
import { isPair } from '../nodes/identity.js';
import { Pair } from '../nodes/Pair.js';
import { YAMLMap } from '../nodes/YAMLMap.js';
import { YAMLSeq } from '../nodes/YAMLSeq.js';
@@ -9,12 +9,11 @@ import { mapIncludes } from './util-map-includes.js';
const blockMsg = 'Block collections are not allowed within flow collections';
const isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');
function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError) {
function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
const isMap = fc.start.source === '{';
const fcName = isMap ? 'flow map' : 'flow sequence';
const coll = isMap
? new YAMLMap(ctx.schema)
: new YAMLSeq(ctx.schema);
const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap : YAMLSeq));
const coll = new NodeClass(ctx.schema);
coll.flow = true;
const atRoot = ctx.atRoot;
if (atRoot)

View File

@@ -1,4 +1,4 @@
import { isScalar } from '../nodes/Node.js';
import { isScalar } from '../nodes/identity.js';
function mapIncludes(ctx, items, search) {
const { uniqueKeys } = ctx.options;

View File

@@ -1,10 +1,9 @@
import { Alias } from '../nodes/Alias.js';
import { isEmptyPath, collectionFromPath } from '../nodes/Collection.js';
import { NODE_TYPE, DOC, isNode, isCollection, isScalar } from '../nodes/Node.js';
import { NODE_TYPE, DOC, isNode, isCollection, isScalar } from '../nodes/identity.js';
import { Pair } from '../nodes/Pair.js';
import { toJS } from '../nodes/toJS.js';
import { Schema } from '../schema/Schema.js';
import { stringify } from '../stringify/stringify.js';
import { stringifyDocument } from '../stringify/stringifyDocument.js';
import { anchorNames, findNewAnchor, createNodeAnchors } from './anchors.js';
import { applyReviver } from './applyReviver.js';
@@ -49,11 +48,9 @@ class Document {
else
this.directives = new Directives({ version });
this.setSchema(version, options);
if (value === undefined)
this.contents = null;
else {
this.contents = this.createNode(value, _replacer, options);
}
// @ts-expect-error We can't really know that this matches Contents.
this.contents =
value === undefined ? null : this.createNode(value, _replacer, options);
}
/**
* Create a deep copy of this Document and its contents.
@@ -72,6 +69,7 @@ class Document {
if (this.directives)
copy.directives = this.directives.clone();
copy.schema = this.schema.clone();
// @ts-expect-error We can't really know that this matches Contents.
copy.contents = isNode(this.contents)
? this.contents.clone(copy.schema)
: this.contents;
@@ -167,6 +165,7 @@ class Document {
if (isEmptyPath(path)) {
if (this.contents == null)
return false;
// @ts-expect-error Presumed impossible if Strict extends false
this.contents = null;
return true;
}
@@ -218,6 +217,7 @@ class Document {
*/
set(key, value) {
if (this.contents == null) {
// @ts-expect-error We can't really know that this matches Contents.
this.contents = collectionFromPath(this.schema, [key], value);
}
else if (assertCollection(this.contents)) {
@@ -229,9 +229,12 @@ class Document {
* boolean to add/remove the item from the set.
*/
setIn(path, value) {
if (isEmptyPath(path))
if (isEmptyPath(path)) {
// @ts-expect-error We can't really know that this matches Contents.
this.contents = value;
}
else if (this.contents == null) {
// @ts-expect-error We can't really know that this matches Contents.
this.contents = collectionFromPath(this.schema, Array.from(path), value);
}
else if (assertCollection(this.contents)) {
@@ -291,8 +294,7 @@ class Document {
keep: !json,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100,
stringify
maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
};
const res = toJS(this.contents, jsonArg ?? '', ctx);
if (typeof onAnchor === 'function')

View File

@@ -1,4 +1,4 @@
import { isScalar, isCollection } from '../nodes/Node.js';
import { isScalar, isCollection } from '../nodes/identity.js';
import { visit } from '../visit.js';
/**

View File

@@ -1,5 +1,5 @@
import { Alias } from '../nodes/Alias.js';
import { isNode, isPair, MAP, SEQ, isDocument } from '../nodes/Node.js';
import { isNode, isPair, MAP, SEQ, isDocument } from '../nodes/identity.js';
import { Scalar } from '../nodes/Scalar.js';
const defaultTagPrefix = 'tag:yaml.org,2002:';
@@ -74,9 +74,13 @@ function createNode(value, tagName, ctx) {
}
const node = tagObj?.createNode
? tagObj.createNode(ctx.schema, value, ctx)
: new Scalar(value);
: typeof tagObj?.nodeClass?.from === 'function'
? tagObj.nodeClass.from(ctx.schema, value, ctx)
: new Scalar(value);
if (tagName)
node.tag = tagName;
else if (!tagObj.default)
node.tag = tagObj.tag;
if (ref)
ref.node = node;
return node;

View File

@@ -1,4 +1,4 @@
import { isNode } from '../nodes/Node.js';
import { isNode } from '../nodes/identity.js';
import { visit } from '../visit.js';
const escapeChars = {
@@ -116,12 +116,19 @@ class Directives {
onError('Verbatim tags must end with a >');
return verbatim;
}
const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/);
const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
if (!suffix)
onError(`The ${source} tag has no suffix`);
const prefix = this.tags[handle];
if (prefix)
return prefix + decodeURIComponent(suffix);
if (prefix) {
try {
return prefix + decodeURIComponent(suffix);
}
catch (error) {
onError(String(error));
return null;
}
}
if (handle === '!')
return source; // local tag
onError(`Could not resolve tag: ${source}`);

View File

@@ -47,7 +47,7 @@ const prettifyError = (src, lc) => (error) => {
let count = 1;
const end = error.linePos[1];
if (end && end.line === line && end.col > col) {
count = Math.min(end.col - col, 80 - ci);
count = Math.max(1, Math.min(end.col - col, 80 - ci));
}
const pointer = ' '.repeat(ci) + '^'.repeat(count);
error.message += `:\n\n${lineStr}\n${pointer}\n`;

View File

@@ -3,7 +3,7 @@ export { Document } from './doc/Document.js';
export { Schema } from './schema/Schema.js';
export { YAMLError, YAMLParseError, YAMLWarning } from './errors.js';
export { Alias } from './nodes/Alias.js';
export { isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq } from './nodes/Node.js';
export { isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq } from './nodes/identity.js';
export { Pair } from './nodes/Pair.js';
export { Scalar } from './nodes/Scalar.js';
export { YAMLMap } from './nodes/YAMLMap.js';

View File

@@ -4,6 +4,8 @@ function debug(logLevel, ...messages) {
}
function warn(logLevel, warning) {
if (logLevel === 'debug' || logLevel === 'warn') {
// https://github.com/typescript-eslint/typescript-eslint/issues/7478
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain
if (typeof process !== 'undefined' && process.emitWarning)
process.emitWarning(warning);
else

View File

@@ -1,4 +1,4 @@
/*! *****************************************************************************
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
@@ -12,153 +12,10 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
};
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __generator(thisArg, body) {
var _ = {
label: 0,
sent: function () {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
return this;
}), g;
function verb(n) {
return function (v) {
return step([n, v]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator,
m = s && o[s],
i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return {
value: o && o[i++],
done: !o
};
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
export { __extends, __generator, __values };
export { __classPrivateFieldGet };

View File

@@ -1,6 +1,8 @@
import { anchorIsValid } from '../doc/anchors.js';
import { visit } from '../visit.js';
import { NodeBase, ALIAS, isAlias, isCollection, isPair } from './Node.js';
import { ALIAS, isAlias, isCollection, isPair } from './identity.js';
import { NodeBase } from './Node.js';
import { toJS } from './toJS.js';
class Alias extends NodeBase {
constructor(source) {
@@ -37,7 +39,12 @@ class Alias extends NodeBase {
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
throw new ReferenceError(msg);
}
const data = anchors.get(source);
let data = anchors.get(source);
if (!data) {
// Resolve anchors for Node.prototype.toJS()
toJS(source, null, ctx);
data = anchors.get(source);
}
/* istanbul ignore if */
if (!data || data.res === undefined) {
const msg = 'This should not happen: Alias anchor was not resolved?';

View File

@@ -1,5 +1,6 @@
import { createNode } from '../doc/createNode.js';
import { NodeBase, isNode, isPair, isCollection, isScalar } from './Node.js';
import { isNode, isPair, isCollection, isScalar } from './identity.js';
import { NodeBase } from './Node.js';
function collectionFromPath(schema, path, value) {
let v = value;

View File

@@ -1,37 +1,7 @@
const ALIAS = Symbol.for('yaml.alias');
const DOC = Symbol.for('yaml.document');
const MAP = Symbol.for('yaml.map');
const PAIR = Symbol.for('yaml.pair');
const SCALAR = Symbol.for('yaml.scalar');
const SEQ = Symbol.for('yaml.seq');
const NODE_TYPE = Symbol.for('yaml.node.type');
const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;
const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;
const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;
const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;
const isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;
const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;
function isCollection(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case MAP:
case SEQ:
return true;
}
return false;
}
function isNode(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case ALIAS:
case MAP:
case SCALAR:
case SEQ:
return true;
}
return false;
}
const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
import { applyReviver } from '../doc/applyReviver.js';
import { NODE_TYPE, isDocument } from './identity.js';
import { toJS } from './toJS.js';
class NodeBase {
constructor(type) {
Object.defineProperty(this, NODE_TYPE, { value: type });
@@ -43,6 +13,26 @@ class NodeBase {
copy.range = this.range.slice();
return copy;
}
/** A plain JavaScript representation of this node. */
toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
if (!isDocument(doc))
throw new TypeError('A document argument is required');
const ctx = {
anchors: new Map(),
doc,
keep: true,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
};
const res = toJS(this, '', ctx);
if (typeof onAnchor === 'function')
for (const { count, res } of ctx.anchors.values())
onAnchor(res, count);
return typeof reviver === 'function'
? applyReviver(reviver, { '': res }, '', res)
: res;
}
}
export { ALIAS, DOC, MAP, NODE_TYPE, NodeBase, PAIR, SCALAR, SEQ, hasAnchor, isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq };
export { NodeBase };

View File

@@ -1,7 +1,7 @@
import { createNode } from '../doc/createNode.js';
import { stringifyPair } from '../stringify/stringifyPair.js';
import { addPairToJSMap } from './addPairToJSMap.js';
import { NODE_TYPE, PAIR, isNode } from './Node.js';
import { NODE_TYPE, PAIR, isNode } from './identity.js';
function createPair(key, value, ctx) {
const k = createNode(key, undefined, ctx);

View File

@@ -1,4 +1,5 @@
import { NodeBase, SCALAR } from './Node.js';
import { SCALAR } from './identity.js';
import { NodeBase } from './Node.js';
import { toJS } from './toJS.js';
const isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');

View File

@@ -1,8 +1,8 @@
import { stringifyCollection } from '../stringify/stringifyCollection.js';
import { addPairToJSMap } from './addPairToJSMap.js';
import { Collection } from './Collection.js';
import { isPair, isScalar, MAP } from './Node.js';
import { Pair } from './Pair.js';
import { isPair, isScalar, MAP } from './identity.js';
import { Pair, createPair } from './Pair.js';
import { isScalarValue } from './Scalar.js';
function findPair(items, key) {
@@ -18,12 +18,40 @@ function findPair(items, key) {
return undefined;
}
class YAMLMap extends Collection {
static get tagName() {
return 'tag:yaml.org,2002:map';
}
constructor(schema) {
super(MAP, schema);
this.items = [];
}
static get tagName() {
return 'tag:yaml.org,2002:map';
/**
* A generic collection parsing method that can be extended
* to other node classes that inherit from YAMLMap
*/
static from(schema, obj, ctx) {
const { keepUndefined, replacer } = ctx;
const map = new this(schema);
const add = (key, value) => {
if (typeof replacer === 'function')
value = replacer.call(obj, key, value);
else if (Array.isArray(replacer) && !replacer.includes(key))
return;
if (value !== undefined || keepUndefined)
map.items.push(createPair(key, value, ctx));
};
if (obj instanceof Map) {
for (const [key, value] of obj)
add(key, value);
}
else if (obj && typeof obj === 'object') {
for (const key of Object.keys(obj))
add(key, obj[key]);
}
if (typeof schema.sortMapEntries === 'function') {
map.items.sort(schema.sortMapEntries);
}
return map;
}
/**
* Adds a value to the collection.

View File

@@ -1,17 +1,18 @@
import { createNode } from '../doc/createNode.js';
import { stringifyCollection } from '../stringify/stringifyCollection.js';
import { Collection } from './Collection.js';
import { SEQ, isScalar } from './Node.js';
import { SEQ, isScalar } from './identity.js';
import { isScalarValue } from './Scalar.js';
import { toJS } from './toJS.js';
class YAMLSeq extends Collection {
static get tagName() {
return 'tag:yaml.org,2002:seq';
}
constructor(schema) {
super(SEQ, schema);
this.items = [];
}
static get tagName() {
return 'tag:yaml.org,2002:seq';
}
add(value) {
this.items.push(value);
}
@@ -84,6 +85,21 @@ class YAMLSeq extends Collection {
onComment
});
}
static from(schema, obj, ctx) {
const { replacer } = ctx;
const seq = new this(schema);
if (obj && Symbol.iterator in Object(obj)) {
let i = 0;
for (let it of obj) {
if (typeof replacer === 'function') {
const key = obj instanceof Set ? it : String(i++);
it = replacer.call(obj, key, it);
}
seq.items.push(createNode(it, undefined, ctx));
}
}
return seq;
}
}
function asItemIndex(key) {
let idx = isScalar(key) ? key.value : key;

View File

@@ -1,6 +1,6 @@
import { warn } from '../log.js';
import { createStringifyContext } from '../stringify/stringify.js';
import { isAlias, isSeq, isScalar, isMap, isNode } from './Node.js';
import { isAlias, isSeq, isScalar, isMap, isNode } from './identity.js';
import { Scalar } from './Scalar.js';
import { toJS } from './toJS.js';
@@ -81,7 +81,7 @@ function stringifyKey(key, jsKey, ctx) {
return '';
if (typeof jsKey !== 'object')
return String(jsKey);
if (isNode(key) && ctx && ctx.doc) {
if (isNode(key) && ctx?.doc) {
const strCtx = createStringifyContext(ctx.doc, {});
strCtx.anchors = new Set();
for (const node of ctx.anchors.keys())

36
node_modules/yaml/browser/dist/nodes/identity.js generated vendored Normal file
View File

@@ -0,0 +1,36 @@
const ALIAS = Symbol.for('yaml.alias');
const DOC = Symbol.for('yaml.document');
const MAP = Symbol.for('yaml.map');
const PAIR = Symbol.for('yaml.pair');
const SCALAR = Symbol.for('yaml.scalar');
const SEQ = Symbol.for('yaml.seq');
const NODE_TYPE = Symbol.for('yaml.node.type');
const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;
const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;
const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;
const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;
const isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;
const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;
function isCollection(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case MAP:
case SEQ:
return true;
}
return false;
}
function isNode(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case ALIAS:
case MAP:
case SCALAR:
case SEQ:
return true;
}
return false;
}
const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
export { ALIAS, DOC, MAP, NODE_TYPE, PAIR, SCALAR, SEQ, hasAnchor, isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq };

View File

@@ -1,4 +1,4 @@
import { hasAnchor } from './Node.js';
import { hasAnchor } from './identity.js';
/**
* Recursively convert any node or its contents to native JavaScript

View File

@@ -1,4 +1,4 @@
import { MAP, SCALAR, SEQ } from '../nodes/Node.js';
import { MAP, SCALAR, SEQ } from '../nodes/identity.js';
import { map } from './common/map.js';
import { seq } from './common/seq.js';
import { string } from './common/string.js';

View File

@@ -1,34 +1,8 @@
import { isMap } from '../../nodes/Node.js';
import { createPair } from '../../nodes/Pair.js';
import { isMap } from '../../nodes/identity.js';
import { YAMLMap } from '../../nodes/YAMLMap.js';
function createMap(schema, obj, ctx) {
const { keepUndefined, replacer } = ctx;
const map = new YAMLMap(schema);
const add = (key, value) => {
if (typeof replacer === 'function')
value = replacer.call(obj, key, value);
else if (Array.isArray(replacer) && !replacer.includes(key))
return;
if (value !== undefined || keepUndefined)
map.items.push(createPair(key, value, ctx));
};
if (obj instanceof Map) {
for (const [key, value] of obj)
add(key, value);
}
else if (obj && typeof obj === 'object') {
for (const key of Object.keys(obj))
add(key, obj[key]);
}
if (typeof schema.sortMapEntries === 'function') {
map.items.sort(schema.sortMapEntries);
}
return map;
}
const map = {
collection: 'map',
createNode: createMap,
default: true,
nodeClass: YAMLMap,
tag: 'tag:yaml.org,2002:map',
@@ -36,7 +10,8 @@ const map = {
if (!isMap(map))
onError('Expected a mapping for this tag');
return map;
}
},
createNode: (schema, obj, ctx) => YAMLMap.from(schema, obj, ctx)
};
export { map };

View File

@@ -1,25 +1,8 @@
import { createNode } from '../../doc/createNode.js';
import { isSeq } from '../../nodes/Node.js';
import { isSeq } from '../../nodes/identity.js';
import { YAMLSeq } from '../../nodes/YAMLSeq.js';
function createSeq(schema, obj, ctx) {
const { replacer } = ctx;
const seq = new YAMLSeq(schema);
if (obj && Symbol.iterator in Object(obj)) {
let i = 0;
for (let it of obj) {
if (typeof replacer === 'function') {
const key = obj instanceof Set ? it : String(i++);
it = replacer.call(obj, key, it);
}
seq.items.push(createNode(it, undefined, ctx));
}
}
return seq;
}
const seq = {
collection: 'seq',
createNode: createSeq,
default: true,
nodeClass: YAMLSeq,
tag: 'tag:yaml.org,2002:seq',
@@ -27,7 +10,8 @@ const seq = {
if (!isSeq(seq))
onError('Expected a sequence for this tag');
return seq;
}
},
createNode: (schema, obj, ctx) => YAMLSeq.from(schema, obj, ctx)
};
export { seq };

View File

@@ -12,7 +12,7 @@ import { omap } from './yaml-1.1/omap.js';
import { pairs } from './yaml-1.1/pairs.js';
import { schema as schema$2 } from './yaml-1.1/schema.js';
import { set } from './yaml-1.1/set.js';
import { floatTime, intTime, timestamp } from './yaml-1.1/timestamp.js';
import { timestamp, floatTime, intTime } from './yaml-1.1/timestamp.js';
const schemas = new Map([
['core', schema],

View File

@@ -1,7 +1,7 @@
import { YAMLSeq } from '../../nodes/YAMLSeq.js';
import { isScalar, isPair } from '../../nodes/identity.js';
import { toJS } from '../../nodes/toJS.js';
import { isScalar, isPair } from '../../nodes/Node.js';
import { YAMLMap } from '../../nodes/YAMLMap.js';
import { YAMLSeq } from '../../nodes/YAMLSeq.js';
import { resolvePairs, createPairs } from './pairs.js';
class YAMLOMap extends YAMLSeq {
@@ -39,6 +39,12 @@ class YAMLOMap extends YAMLSeq {
}
return map;
}
static from(schema, iterable, ctx) {
const pairs = createPairs(schema, iterable, ctx);
const omap = new this();
omap.items = pairs.items;
return omap;
}
}
YAMLOMap.tag = 'tag:yaml.org,2002:omap';
const omap = {
@@ -62,12 +68,7 @@ const omap = {
}
return Object.assign(new YAMLOMap(), pairs);
},
createNode(schema, iterable, ctx) {
const pairs = createPairs(schema, iterable, ctx);
const omap = new YAMLOMap();
omap.items = pairs.items;
return omap;
}
createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)
};
export { YAMLOMap, omap };

View File

@@ -1,4 +1,4 @@
import { isSeq, isPair, isMap } from '../../nodes/Node.js';
import { isSeq, isPair, isMap } from '../../nodes/identity.js';
import { Pair, createPair } from '../../nodes/Pair.js';
import { Scalar } from '../../nodes/Scalar.js';
import { YAMLSeq } from '../../nodes/YAMLSeq.js';
@@ -56,8 +56,9 @@ function createPairs(schema, iterable, ctx) {
key = keys[0];
value = it[key];
}
else
throw new TypeError(`Expected { key: value } tuple: ${it}`);
else {
throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
}
}
else {
key = it;

View File

@@ -1,5 +1,5 @@
import { isMap, isPair, isScalar } from '../../nodes/Node.js';
import { createPair, Pair } from '../../nodes/Pair.js';
import { isMap, isPair, isScalar } from '../../nodes/identity.js';
import { Pair, createPair } from '../../nodes/Pair.js';
import { YAMLMap, findPair } from '../../nodes/YAMLMap.js';
class YAMLSet extends YAMLMap {
@@ -57,6 +57,17 @@ class YAMLSet extends YAMLMap {
else
throw new Error('Set items must all have null values');
}
static from(schema, iterable, ctx) {
const { replacer } = ctx;
const set = new this(schema);
if (iterable && Symbol.iterator in Object(iterable))
for (let value of iterable) {
if (typeof replacer === 'function')
value = replacer.call(iterable, value, value);
set.items.push(createPair(value, null, ctx));
}
return set;
}
}
YAMLSet.tag = 'tag:yaml.org,2002:set';
const set = {
@@ -65,6 +76,7 @@ const set = {
nodeClass: YAMLSet,
default: false,
tag: 'tag:yaml.org,2002:set',
createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),
resolve(map, onError) {
if (isMap(map)) {
if (map.hasAllNullValues(true))
@@ -75,17 +87,6 @@ const set = {
else
onError('Expected a mapping for this tag');
return map;
},
createNode(schema, iterable, ctx) {
const { replacer } = ctx;
const set = new YAMLSet(schema);
if (iterable && Symbol.iterator in Object(iterable))
for (let value of iterable) {
if (typeof replacer === 'function')
value = replacer.call(iterable, value, value);
set.items.push(createPair(value, null, ctx));
}
return set;
}
};

View File

@@ -43,7 +43,7 @@ function stringifySexagesimal(node) {
}
return (sign +
parts
.map(n => (n < 10 ? '0' + String(n) : String(n)))
.map(n => String(n).padStart(2, '0'))
.join(':')
.replace(/000000\d*$/, '') // % 60 may introduce error
);

View File

@@ -1,5 +1,5 @@
import { anchorIsValid } from '../doc/anchors.js';
import { isPair, isAlias, isNode, isScalar, isCollection } from '../nodes/Node.js';
import { isPair, isAlias, isNode, isScalar, isCollection } from '../nodes/identity.js';
import { stringifyComment } from './stringifyComment.js';
import { stringifyString } from './stringifyString.js';
@@ -13,6 +13,7 @@ function createStringifyContext(doc, options) {
doubleQuotedAsJSON: false,
doubleQuotedMinMultiLineLength: 40,
falseStr: 'false',
flowCollectionPadding: true,
indentSeq: true,
lineWidth: 80,
minContentWidth: 20,
@@ -36,6 +37,7 @@ function createStringifyContext(doc, options) {
return {
anchors: new Set(),
doc,
flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',
indent: '',
indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ',
inFlow,

View File

@@ -1,5 +1,5 @@
import { Collection } from '../nodes/Collection.js';
import { isNode, isPair } from '../nodes/Node.js';
import { isNode, isPair } from '../nodes/identity.js';
import { stringify } from './stringify.js';
import { lineComment, indentComment } from './stringifyComment.js';
@@ -60,7 +60,7 @@ function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, fl
return str;
}
function stringifyFlowCollection({ comment, items }, ctx, { flowChars, itemIndent, onComment }) {
const { indent, indentStep, options: { commentString } } = ctx;
const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
itemIndent += indentStep;
const itemCtx = Object.assign({}, ctx, {
indent: itemIndent,
@@ -96,7 +96,7 @@ function stringifyFlowCollection({ comment, items }, ctx, { flowChars, itemInden
if (iv.commentBefore)
reqNewline = true;
}
else if (item.value == null && ik && ik.comment) {
else if (item.value == null && ik?.comment) {
comment = ik.comment;
}
}
@@ -129,11 +129,11 @@ function stringifyFlowCollection({ comment, items }, ctx, { flowChars, itemInden
str += `\n${indent}${end}`;
}
else {
str = `${start} ${lines.join(' ')} ${end}`;
str = `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;
}
}
if (comment) {
str += lineComment(str, commentString(comment), indent);
str += lineComment(str, indent, commentString(comment));
if (onComment)
onComment();
}

View File

@@ -1,4 +1,4 @@
import { isNode } from '../nodes/Node.js';
import { isNode } from '../nodes/identity.js';
import { createStringifyContext, stringify } from './stringify.js';
import { indentComment, lineComment } from './stringifyComment.js';

View File

@@ -1,4 +1,4 @@
import { isCollection, isNode, isScalar, isSeq } from '../nodes/Node.js';
import { isCollection, isNode, isScalar, isSeq } from '../nodes/identity.js';
import { Scalar } from '../nodes/Scalar.js';
import { stringify } from './stringify.js';
import { lineComment, indentComment } from './stringifyComment.js';
@@ -63,19 +63,18 @@ function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
if (keyComment)
str += lineComment(str, ctx.indent, commentString(keyComment));
}
let vcb = '';
let valueComment = null;
let vsb, vcb, valueComment;
if (isNode(value)) {
if (value.spaceBefore)
vcb = '\n';
if (value.commentBefore) {
const cs = commentString(value.commentBefore);
vcb += `\n${indentComment(cs, ctx.indent)}`;
}
vsb = !!value.spaceBefore;
vcb = value.commentBefore;
valueComment = value.comment;
}
else if (value && typeof value === 'object') {
value = doc.createNode(value);
else {
vsb = false;
vcb = null;
valueComment = null;
if (value && typeof value === 'object')
value = doc.createNode(value);
}
ctx.implicitKey = false;
if (!explicitKey && !keyComment && isScalar(value))
@@ -90,24 +89,50 @@ function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
!value.tag &&
!value.anchor) {
// If indentSeq === false, consider '- ' as part of indentation where possible
ctx.indent = ctx.indent.substr(2);
ctx.indent = ctx.indent.substring(2);
}
let valueCommentDone = false;
const valueStr = stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));
let ws = ' ';
if (vcb || keyComment) {
if (valueStr === '' && !ctx.inFlow)
ws = vcb === '\n' ? '\n\n' : vcb;
else
ws = `${vcb}\n${ctx.indent}`;
if (keyComment || vsb || vcb) {
ws = vsb ? '\n' : '';
if (vcb) {
const cs = commentString(vcb);
ws += `\n${indentComment(cs, ctx.indent)}`;
}
if (valueStr === '' && !ctx.inFlow) {
if (ws === '\n')
ws = '\n\n';
}
else {
ws += `\n${ctx.indent}`;
}
}
else if (!explicitKey && isCollection(value)) {
const flow = valueStr[0] === '[' || valueStr[0] === '{';
if (!flow || valueStr.includes('\n'))
ws = `\n${ctx.indent}`;
const vs0 = valueStr[0];
const nl0 = valueStr.indexOf('\n');
const hasNewline = nl0 !== -1;
const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
if (hasNewline || !flow) {
let hasPropsLine = false;
if (hasNewline && (vs0 === '&' || vs0 === '!')) {
let sp0 = valueStr.indexOf(' ');
if (vs0 === '&' &&
sp0 !== -1 &&
sp0 < nl0 &&
valueStr[sp0 + 1] === '!') {
sp0 = valueStr.indexOf(' ', sp0 + 1);
}
if (sp0 === -1 || nl0 < sp0)
hasPropsLine = true;
}
if (!hasPropsLine)
ws = `\n${ctx.indent}`;
}
}
else if (valueStr === '' || valueStr[0] === '\n')
else if (valueStr === '' || valueStr[0] === '\n') {
ws = '';
}
str += ws + valueStr;
if (ctx.inFlow) {
if (valueCommentDone && onComment)

View File

@@ -1,8 +1,8 @@
import { Scalar } from '../nodes/Scalar.js';
import { foldFlowLines, FOLD_QUOTED, FOLD_FLOW, FOLD_BLOCK } from './foldFlowLines.js';
const getFoldOptions = (ctx) => ({
indentAtStart: ctx.indentAtStart,
const getFoldOptions = (ctx, isBlock) => ({
indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
lineWidth: ctx.options.lineWidth,
minContentWidth: ctx.options.minContentWidth
});
@@ -115,7 +115,7 @@ function doubleQuotedString(value, ctx) {
str = start ? str + json.slice(start) : json;
return implicitKey
? str
: foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx));
: foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false));
}
function singleQuotedString(value, ctx) {
if (ctx.options.singleQuote === false ||
@@ -127,7 +127,7 @@ function singleQuotedString(value, ctx) {
const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
return ctx.implicitKey
? res
: foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx));
: foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false));
}
function quotedString(value, ctx) {
const { singleQuote } = ctx.options;
@@ -146,6 +146,15 @@ function quotedString(value, ctx) {
}
return qs(value, ctx);
}
// The negative lookbehind avoids a polynomial search,
// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind
let blockEndNewlines;
try {
blockEndNewlines = new RegExp('(^|(?<!\n))\n+(?!\n|$)', 'g');
}
catch {
blockEndNewlines = /\n+(?!\n|$)/g;
}
function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
const { blockQuote, commentString, lineWidth } = ctx.options;
// 1. Block can't end in whitespace unless the last line is non-empty.
@@ -189,7 +198,7 @@ function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
value = value.slice(0, -end.length);
if (end[end.length - 1] === '\n')
end = end.slice(0, -1);
end = end.replace(/\n+(?!\n|$)/g, `$&${indent}`);
end = end.replace(blockEndNewlines, `$&${indent}`);
}
// determine indent indicator from whitespace at value start
let startWithSpace = false;
@@ -225,13 +234,13 @@ function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
.replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
// ^ more-ind. ^ empty ^ capture next empty lines only at end of indent
.replace(/\n+/g, `$&${indent}`);
const body = foldFlowLines(`${start}${value}${end}`, indent, FOLD_BLOCK, getFoldOptions(ctx));
const body = foldFlowLines(`${start}${value}${end}`, indent, FOLD_BLOCK, getFoldOptions(ctx, true));
return `${header}\n${indent}${body}`;
}
function plainString(item, ctx, onComment, onChompKeep) {
const { type, value } = item;
const { actualString, implicitKey, indent, inFlow } = ctx;
if ((implicitKey && /[\n[\]{},]/.test(value)) ||
const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
if ((implicitKey && value.includes('\n')) ||
(inFlow && /[[\]{},]/.test(value))) {
return quotedString(value, ctx);
}
@@ -254,9 +263,14 @@ function plainString(item, ctx, onComment, onChompKeep) {
// Where allowed & type not set explicitly, prefer block style for multiline strings
return blockString(item, ctx, onComment, onChompKeep);
}
if (indent === '' && containsDocumentMarker(value)) {
ctx.forceBlockIndent = true;
return blockString(item, ctx, onComment, onChompKeep);
if (containsDocumentMarker(value)) {
if (indent === '') {
ctx.forceBlockIndent = true;
return blockString(item, ctx, onComment, onChompKeep);
}
else if (implicitKey && indent === indentStep) {
return quotedString(value, ctx);
}
}
const str = value.replace(/\n+/g, `$&\n${indent}`);
// Verify that output will be parsed as a string, as e.g. plain numbers and
@@ -270,7 +284,7 @@ function plainString(item, ctx, onComment, onChompKeep) {
}
return implicitKey
? str
: foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx));
: foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false));
}
function stringifyString(item, ctx, onComment, onChompKeep) {
const { implicitKey, inFlow } = ctx;

View File

@@ -1,4 +1,6 @@
export { createNode } from './doc/createNode.js';
export { debug, warn } from './log.js';
export { createPair } from './nodes/Pair.js';
export { findPair } from './nodes/YAMLMap.js';
export { toJS } from './nodes/toJS.js';
export { map as mapTag } from './schema/common/map.js';

View File

@@ -1,4 +1,4 @@
import { isDocument, isNode, isPair, isCollection, isMap, isSeq, isScalar, isAlias } from './nodes/Node.js';
import { isDocument, isNode, isPair, isCollection, isMap, isSeq, isScalar, isAlias } from './nodes/identity.js';
const BREAK = Symbol('break visit');
const SKIP = Symbol('skip children');

View File

@@ -1,4 +1,4 @@
import { ParsedNode } from '../nodes/Node.js';
import type { ParsedNode } from '../nodes/Node.js';
import type { BlockMap, BlockSequence, FlowCollection, SourceToken } from '../parse/cst.js';
import type { ComposeContext, ComposeNode } from './compose-node.js';
import type { ComposeErrorHandler } from './composer.js';

View File

@@ -1,40 +1,52 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var Scalar = require('../nodes/Scalar.js');
var YAMLMap = require('../nodes/YAMLMap.js');
var YAMLSeq = require('../nodes/YAMLSeq.js');
var resolveBlockMap = require('./resolve-block-map.js');
var resolveBlockSeq = require('./resolve-block-seq.js');
var resolveFlowCollection = require('./resolve-flow-collection.js');
function composeCollection(CN, ctx, token, tagToken, onError) {
let coll;
switch (token.type) {
case 'block-map': {
coll = resolveBlockMap.resolveBlockMap(CN, ctx, token, onError);
break;
}
case 'block-seq': {
coll = resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError);
break;
}
case 'flow-collection': {
coll = resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError);
break;
}
}
if (!tagToken)
return coll;
const tagName = ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));
if (!tagName)
return coll;
// Cast needed due to: https://github.com/Microsoft/TypeScript/issues/3841
function resolveCollection(CN, ctx, token, onError, tagName, tag) {
const coll = token.type === 'block-map'
? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag)
: token.type === 'block-seq'
? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag)
: resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);
const Coll = coll.constructor;
// If we got a tagName matching the class, or the tag name is '!',
// then use the tagName from the node class used to create it.
if (tagName === '!' || tagName === Coll.tagName) {
coll.tag = Coll.tagName;
return coll;
}
const expType = Node.isMap(coll) ? 'map' : 'seq';
let tag = ctx.schema.tags.find(t => t.collection === expType && t.tag === tagName);
if (tagName)
coll.tag = tagName;
return coll;
}
function composeCollection(CN, ctx, token, tagToken, onError) {
const tagName = !tagToken
? null
: ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));
const expType = token.type === 'block-map'
? 'map'
: token.type === 'block-seq'
? 'seq'
: token.start.source === '{'
? 'map'
: 'seq';
// shortcut: check if it's a generic YAMLMap or YAMLSeq
// before jumping into the custom tag logic.
if (!tagToken ||
!tagName ||
tagName === '!' ||
(tagName === YAMLMap.YAMLMap.tagName && expType === 'map') ||
(tagName === YAMLSeq.YAMLSeq.tagName && expType === 'seq') ||
!expType) {
return resolveCollection(CN, ctx, token, onError, tagName);
}
let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);
if (!tag) {
const kt = ctx.schema.knownTags[tagName];
if (kt && kt.collection === expType) {
@@ -42,13 +54,18 @@ function composeCollection(CN, ctx, token, tagToken, onError) {
tag = kt;
}
else {
onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);
coll.tag = tagName;
return coll;
if (kt?.collection) {
onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection}`, true);
}
else {
onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);
}
return resolveCollection(CN, ctx, token, onError, tagName);
}
}
const res = tag.resolve(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options);
const node = Node.isNode(res)
const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);
const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll;
const node = identity.isNode(res)
? res
: new Scalar.Scalar(res);
node.range = coll.range;

View File

@@ -1,6 +1,7 @@
import type { Directives } from '../doc/directives.js';
import { Document } from '../doc/Document.js';
import type { ParsedNode } from '../nodes/Node.js';
import type { DocumentOptions, ParseOptions, SchemaOptions } from '../options.js';
import type * as CST from '../parse/cst.js';
import type { ComposeErrorHandler } from './composer.js';
export declare function composeDoc(options: ParseOptions & DocumentOptions & SchemaOptions, directives: Directives, { offset, start, value, end }: CST.Document, onError: ComposeErrorHandler): Document.Parsed<import("../index.js").ParsedNode>;
export declare function composeDoc<Contents extends ParsedNode = ParsedNode, Strict extends boolean = true>(options: ParseOptions & DocumentOptions & SchemaOptions, directives: Directives, { offset, start, value, end }: CST.Document, onError: ComposeErrorHandler): Document.Parsed<Contents, Strict>;

View File

@@ -28,6 +28,7 @@ function composeDoc(options, directives, { offset, start, value, end }, onError)
!props.hasNewline)
onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');
}
// @ts-expect-error If Contents is set, let's trust the user
doc.contents = value
? composeNode.composeNode(ctx, value, props, onError)
: composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);

View File

@@ -21,7 +21,7 @@ declare const CN: {
composeNode: typeof composeNode;
composeEmptyNode: typeof composeEmptyNode;
};
export declare type ComposeNode = typeof CN;
export type ComposeNode = typeof CN;
export declare function composeNode(ctx: ComposeContext, token: Token, props: Props, onError: ComposeErrorHandler): ParsedNode;
export declare function composeEmptyNode(ctx: ComposeContext, offset: number, before: Token[] | undefined, pos: number | null, { spaceBefore, comment, anchor, tag, end }: Props, onError: ComposeErrorHandler): import("../index.js").Scalar.Parsed;
export {};

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var Scalar = require('../nodes/Scalar.js');
var resolveBlockScalar = require('./resolve-block-scalar.js');
var resolveFlowScalar = require('./resolve-flow-scalar.js');
@@ -16,11 +16,11 @@ function composeScalar(ctx, token, tagToken, onError) {
? findScalarTagByName(ctx.schema, value, tagName, tagToken, onError)
: token.type === 'scalar'
? findScalarTagByTest(ctx, value, token, onError)
: ctx.schema[Node.SCALAR];
: ctx.schema[identity.SCALAR];
let scalar;
try {
const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);
scalar = Node.isScalar(res) ? res : new Scalar.Scalar(res);
scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);
}
catch (error) {
const msg = error instanceof Error ? error.message : String(error);
@@ -41,7 +41,7 @@ function composeScalar(ctx, token, tagToken, onError) {
}
function findScalarTagByName(schema, value, tagName, tagToken, onError) {
if (tagName === '!')
return schema[Node.SCALAR]; // non-specific tag
return schema[identity.SCALAR]; // non-specific tag
const matchWithTest = [];
for (const tag of schema.tags) {
if (!tag.collection && tag.tag === tagName) {
@@ -62,13 +62,13 @@ function findScalarTagByName(schema, value, tagName, tagToken, onError) {
return kt;
}
onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');
return schema[Node.SCALAR];
return schema[identity.SCALAR];
}
function findScalarTagByTest({ directives, schema }, value, token, onError) {
const tag = schema.tags.find(tag => tag.default && tag.test?.test(value)) || schema[Node.SCALAR];
const tag = schema.tags.find(tag => tag.default && tag.test?.test(value)) || schema[identity.SCALAR];
if (schema.compat) {
const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??
schema[Node.SCALAR];
schema[identity.SCALAR];
if (tag.tag !== compat.tag) {
const ts = directives.tagString(tag.tag);
const cs = directives.tagString(compat.tag);

View File

@@ -1,14 +1,14 @@
import { Directives } from '../doc/directives.js';
import { Document } from '../doc/Document.js';
import { ErrorCode, YAMLParseError, YAMLWarning } from '../errors.js';
import { Range } from '../nodes/Node.js';
import type { ParsedNode, Range } from '../nodes/Node.js';
import type { DocumentOptions, ParseOptions, SchemaOptions } from '../options.js';
import type { Token } from '../parse/cst.js';
declare type ErrorSource = number | [number, number] | Range | {
type ErrorSource = number | [number, number] | Range | {
offset: number;
source?: string;
};
export declare type ComposeErrorHandler = (source: ErrorSource, code: ErrorCode, message: string, warning?: boolean) => void;
export type ComposeErrorHandler = (source: ErrorSource, code: ErrorCode, message: string, warning?: boolean) => void;
/**
* Compose a stream of CST nodes into a stream of YAML Documents.
*
@@ -20,7 +20,7 @@ export declare type ComposeErrorHandler = (source: ErrorSource, code: ErrorCode,
* const docs = new Composer().compose(tokens)
* ```
*/
export declare class Composer {
export declare class Composer<Contents extends ParsedNode = ParsedNode, Strict extends boolean = true> {
private directives;
private doc;
private options;
@@ -48,15 +48,15 @@ export declare class Composer {
* @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
* @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
*/
compose(tokens: Iterable<Token>, forceDoc?: boolean, endOffset?: number): Generator<Document.Parsed<import("../nodes/Node.js").ParsedNode>, void, unknown>;
compose(tokens: Iterable<Token>, forceDoc?: boolean, endOffset?: number): Generator<Document.Parsed<Contents, Strict>, void, unknown>;
/** Advance the composer by one CST token. */
next(token: Token): Generator<Document.Parsed<import("../nodes/Node.js").ParsedNode>, void, unknown>;
next(token: Token): Generator<Document.Parsed<Contents, Strict>, void, unknown>;
/**
* Call at end of input to yield any remaining document.
*
* @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
* @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
*/
end(forceDoc?: boolean, endOffset?: number): Generator<Document.Parsed<import("../nodes/Node.js").ParsedNode>, void, unknown>;
end(forceDoc?: boolean, endOffset?: number): Generator<Document.Parsed<Contents, Strict>, void, unknown>;
}
export {};

View File

@@ -3,7 +3,7 @@
var directives = require('../doc/directives.js');
var Document = require('../doc/Document.js');
var errors = require('../errors.js');
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var composeDoc = require('./compose-doc.js');
var resolveEnd = require('./resolve-end.js');
@@ -83,9 +83,9 @@ class Composer {
else if (afterEmptyLine || doc.directives.docStart || !dc) {
doc.commentBefore = comment;
}
else if (Node.isCollection(dc) && !dc.flow && dc.items.length > 0) {
else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {
let it = dc.items[0];
if (Node.isPair(it))
if (identity.isPair(it))
it = it.key;
const cb = it.commentBefore;
it.commentBefore = cb ? `${comment}\n${cb}` : comment;

View File

@@ -1,6 +1,7 @@
import type { ParsedNode } from '../nodes/Node.js';
import { YAMLMap } from '../nodes/YAMLMap.js';
import type { BlockMap } from '../parse/cst.js';
import { CollectionTag } from '../schema/types.js';
import type { ComposeContext, ComposeNode } from './compose-node.js';
import type { ComposeErrorHandler } from './composer.js';
export declare function resolveBlockMap({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, bm: BlockMap, onError: ComposeErrorHandler): YAMLMap.Parsed<ParsedNode, ParsedNode | null>;
export declare function resolveBlockMap({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, bm: BlockMap, onError: ComposeErrorHandler, tag?: CollectionTag): YAMLMap.Parsed<ParsedNode, ParsedNode | null>;

View File

@@ -8,8 +8,9 @@ var utilFlowIndentCheck = require('./util-flow-indent-check.js');
var utilMapIncludes = require('./util-map-includes.js');
const startColMsg = 'All mapping items must start at the same column';
function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError) {
const map = new YAMLMap.YAMLMap(ctx.schema);
function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {
const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;
const map = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset = bm.offset;

View File

@@ -1,5 +1,6 @@
import { YAMLSeq } from '../nodes/YAMLSeq.js';
import type { BlockSequence } from '../parse/cst.js';
import { CollectionTag } from '../schema/types.js';
import type { ComposeContext, ComposeNode } from './compose-node.js';
import type { ComposeErrorHandler } from './composer.js';
export declare function resolveBlockSeq({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, bs: BlockSequence, onError: ComposeErrorHandler): YAMLSeq.Parsed<import("../index.js").ParsedNode>;
export declare function resolveBlockSeq({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, bs: BlockSequence, onError: ComposeErrorHandler, tag?: CollectionTag): YAMLSeq.Parsed<import("../index.js").ParsedNode>;

View File

@@ -4,8 +4,9 @@ var YAMLSeq = require('../nodes/YAMLSeq.js');
var resolveProps = require('./resolve-props.js');
var utilFlowIndentCheck = require('./util-flow-indent-check.js');
function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError) {
const seq = new YAMLSeq.YAMLSeq(ctx.schema);
function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {
const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;
const seq = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset = bs.offset;

View File

@@ -1,6 +1,7 @@
import { YAMLMap } from '../nodes/YAMLMap.js';
import { YAMLSeq } from '../nodes/YAMLSeq.js';
import type { FlowCollection } from '../parse/cst.js';
import { CollectionTag } from '../schema/types.js';
import type { ComposeContext, ComposeNode } from './compose-node.js';
import type { ComposeErrorHandler } from './composer.js';
export declare function resolveFlowCollection({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, fc: FlowCollection, onError: ComposeErrorHandler): YAMLMap.Parsed<import("../nodes/Node.js").ParsedNode, import("../nodes/Node.js").ParsedNode | null> | YAMLSeq.Parsed<import("../nodes/Node.js").ParsedNode>;
export declare function resolveFlowCollection({ composeNode, composeEmptyNode }: ComposeNode, ctx: ComposeContext, fc: FlowCollection, onError: ComposeErrorHandler, tag?: CollectionTag): YAMLMap.Parsed<import("../index.js").ParsedNode, import("../index.js").ParsedNode | null> | YAMLSeq.Parsed<import("../index.js").ParsedNode>;

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var Pair = require('../nodes/Pair.js');
var YAMLMap = require('../nodes/YAMLMap.js');
var YAMLSeq = require('../nodes/YAMLSeq.js');
@@ -11,12 +11,11 @@ var utilMapIncludes = require('./util-map-includes.js');
const blockMsg = 'Block collections are not allowed within flow collections';
const isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');
function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError) {
function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
const isMap = fc.start.source === '{';
const fcName = isMap ? 'flow map' : 'flow sequence';
const coll = isMap
? new YAMLMap.YAMLMap(ctx.schema)
: new YAMLSeq.YAMLSeq(ctx.schema);
const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq));
const coll = new NodeClass(ctx.schema);
coll.flow = true;
const atRoot = ctx.atRoot;
if (atRoot)
@@ -75,7 +74,7 @@ function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onErr
}
if (prevItemComment) {
let prev = coll.items[coll.items.length - 1];
if (Node.isPair(prev))
if (identity.isPair(prev))
prev = prev.value ?? prev.key;
if (prev.comment)
prev.comment += '\n' + prevItemComment;

View File

@@ -1,4 +1,4 @@
import { ParsedNode } from '../nodes/Node';
import { Pair } from '../nodes/Pair';
import { ComposeContext } from './compose-node';
import type { ParsedNode } from '../nodes/Node.js';
import type { Pair } from '../nodes/Pair.js';
import type { ComposeContext } from './compose-node.js';
export declare function mapIncludes(ctx: ComposeContext, items: Pair<ParsedNode>[], search: ParsedNode): boolean;

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
function mapIncludes(ctx, items, search) {
const { uniqueKeys } = ctx.options;
@@ -9,8 +9,8 @@ function mapIncludes(ctx, items, search) {
const isEqual = typeof uniqueKeys === 'function'
? uniqueKeys
: (a, b) => a === b ||
(Node.isScalar(a) &&
Node.isScalar(b) &&
(identity.isScalar(a) &&
identity.isScalar(b) &&
a.value === b.value &&
!(a.value === '<<' && ctx.schema.merge));
return items.some(pair => isEqual(pair.key, search));

View File

@@ -1,6 +1,7 @@
import type { YAMLError, YAMLWarning } from '../errors.js';
import { Alias } from '../nodes/Alias.js';
import { Node, NodeType, NODE_TYPE, ParsedNode, Range } from '../nodes/Node.js';
import { NODE_TYPE } from '../nodes/identity.js';
import type { Node, NodeType, ParsedNode, Range } from '../nodes/Node.js';
import { Pair } from '../nodes/Pair.js';
import type { Scalar } from '../nodes/Scalar.js';
import type { YAMLMap } from '../nodes/YAMLMap.js';
@@ -8,22 +9,23 @@ import type { YAMLSeq } from '../nodes/YAMLSeq.js';
import type { CreateNodeOptions, DocumentOptions, ParseOptions, SchemaOptions, ToJSOptions, ToStringOptions } from '../options.js';
import { Schema } from '../schema/Schema.js';
import { Directives } from './directives.js';
export declare type Replacer = any[] | ((key: any, value: any) => unknown);
export type Replacer = any[] | ((key: any, value: any) => unknown);
export declare namespace Document {
interface Parsed<T extends ParsedNode = ParsedNode> extends Document<T> {
/** @ts-ignore The typing of directives fails in TS <= 4.2 */
interface Parsed<Contents extends ParsedNode = ParsedNode, Strict extends boolean = true> extends Document<Contents, Strict> {
directives: Directives;
range: Range;
}
}
export declare class Document<T extends Node = Node> {
export declare class Document<Contents extends Node = Node, Strict extends boolean = true> {
readonly [NODE_TYPE]: symbol;
/** A comment before this Document */
commentBefore: string | null;
/** A comment immediately after this Document */
comment: string | null;
/** The document contents. */
contents: T | null;
directives?: Directives;
contents: Strict extends true ? Contents | null : Contents;
directives: Strict extends true ? Directives | undefined : Directives;
/** Errors encountered during parsing. */
errors: YAMLError[];
options: Required<Omit<ParseOptions & DocumentOptions, '_directives' | 'lineCounter' | 'version'>>;
@@ -49,7 +51,7 @@ export declare class Document<T extends Node = Node> {
*
* Custom Node values that inherit from `Object` still refer to their original instances.
*/
clone(): Document<T>;
clone(): Document<Contents, Strict>;
/** Adds a value to the document. */
add(value: any): void;
/** Adds a value to the document. */
@@ -63,7 +65,7 @@ export declare class Document<T extends Node = Node> {
* `name` will be used as a prefix for a new unique anchor.
* If `name` is undefined, the generated anchor will use 'a' as a prefix.
*/
createAlias(node: Scalar | YAMLMap | YAMLSeq, name?: string): Alias;
createAlias(node: Strict extends true ? Scalar | YAMLMap | YAMLSeq : Node, name?: string): Alias;
/**
* Convert any value into a `Node` using the current schema, recursively
* turning objects into collections.
@@ -90,13 +92,13 @@ export declare class Document<T extends Node = Node> {
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
get(key: unknown, keepScalar?: boolean): unknown;
get(key: unknown, keepScalar?: boolean): Strict extends true ? unknown : any;
/**
* Returns item at `path`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
getIn(path: Iterable<unknown> | null, keepScalar?: boolean): unknown;
getIn(path: Iterable<unknown> | null, keepScalar?: boolean): Strict extends true ? unknown : any;
/**
* Checks if the document includes a value with the key `key`.
*/

View File

@@ -2,11 +2,10 @@
var Alias = require('../nodes/Alias.js');
var Collection = require('../nodes/Collection.js');
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var Pair = require('../nodes/Pair.js');
var toJS = require('../nodes/toJS.js');
var Schema = require('../schema/Schema.js');
var stringify = require('../stringify/stringify.js');
var stringifyDocument = require('../stringify/stringifyDocument.js');
var anchors = require('./anchors.js');
var applyReviver = require('./applyReviver.js');
@@ -23,7 +22,7 @@ class Document {
this.errors = [];
/** Warnings encountered during parsing. */
this.warnings = [];
Object.defineProperty(this, Node.NODE_TYPE, { value: Node.DOC });
Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });
let _replacer = null;
if (typeof replacer === 'function' || Array.isArray(replacer)) {
_replacer = replacer;
@@ -51,11 +50,9 @@ class Document {
else
this.directives = new directives.Directives({ version });
this.setSchema(version, options);
if (value === undefined)
this.contents = null;
else {
this.contents = this.createNode(value, _replacer, options);
}
// @ts-expect-error We can't really know that this matches Contents.
this.contents =
value === undefined ? null : this.createNode(value, _replacer, options);
}
/**
* Create a deep copy of this Document and its contents.
@@ -64,7 +61,7 @@ class Document {
*/
clone() {
const copy = Object.create(Document.prototype, {
[Node.NODE_TYPE]: { value: Node.DOC }
[identity.NODE_TYPE]: { value: identity.DOC }
});
copy.commentBefore = this.commentBefore;
copy.comment = this.comment;
@@ -74,7 +71,8 @@ class Document {
if (this.directives)
copy.directives = this.directives.clone();
copy.schema = this.schema.clone();
copy.contents = Node.isNode(this.contents)
// @ts-expect-error We can't really know that this matches Contents.
copy.contents = identity.isNode(this.contents)
? this.contents.clone(copy.schema)
: this.contents;
if (this.range)
@@ -140,7 +138,7 @@ class Document {
sourceObjects
};
const node = createNode.createNode(value, tag, ctx);
if (flow && Node.isCollection(node))
if (flow && identity.isCollection(node))
node.flow = true;
setAnchors();
return node;
@@ -169,6 +167,7 @@ class Document {
if (Collection.isEmptyPath(path)) {
if (this.contents == null)
return false;
// @ts-expect-error Presumed impossible if Strict extends false
this.contents = null;
return true;
}
@@ -182,7 +181,7 @@ class Document {
* `true` (collections are always returned intact).
*/
get(key, keepScalar) {
return Node.isCollection(this.contents)
return identity.isCollection(this.contents)
? this.contents.get(key, keepScalar)
: undefined;
}
@@ -193,10 +192,10 @@ class Document {
*/
getIn(path, keepScalar) {
if (Collection.isEmptyPath(path))
return !keepScalar && Node.isScalar(this.contents)
return !keepScalar && identity.isScalar(this.contents)
? this.contents.value
: this.contents;
return Node.isCollection(this.contents)
return identity.isCollection(this.contents)
? this.contents.getIn(path, keepScalar)
: undefined;
}
@@ -204,7 +203,7 @@ class Document {
* Checks if the document includes a value with the key `key`.
*/
has(key) {
return Node.isCollection(this.contents) ? this.contents.has(key) : false;
return identity.isCollection(this.contents) ? this.contents.has(key) : false;
}
/**
* Checks if the document includes a value at `path`.
@@ -212,7 +211,7 @@ class Document {
hasIn(path) {
if (Collection.isEmptyPath(path))
return this.contents !== undefined;
return Node.isCollection(this.contents) ? this.contents.hasIn(path) : false;
return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false;
}
/**
* Sets a value in this document. For `!!set`, `value` needs to be a
@@ -220,6 +219,7 @@ class Document {
*/
set(key, value) {
if (this.contents == null) {
// @ts-expect-error We can't really know that this matches Contents.
this.contents = Collection.collectionFromPath(this.schema, [key], value);
}
else if (assertCollection(this.contents)) {
@@ -231,9 +231,12 @@ class Document {
* boolean to add/remove the item from the set.
*/
setIn(path, value) {
if (Collection.isEmptyPath(path))
if (Collection.isEmptyPath(path)) {
// @ts-expect-error We can't really know that this matches Contents.
this.contents = value;
}
else if (this.contents == null) {
// @ts-expect-error We can't really know that this matches Contents.
this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value);
}
else if (assertCollection(this.contents)) {
@@ -293,8 +296,7 @@ class Document {
keep: !json,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100,
stringify: stringify.stringify
maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
};
const res = toJS.toJS(this.contents, jsonArg ?? '', ctx);
if (typeof onAnchor === 'function')
@@ -326,7 +328,7 @@ class Document {
}
}
function assertCollection(contents) {
if (Node.isCollection(contents))
if (identity.isCollection(contents))
return true;
throw new Error('Expected a YAML collection as document contents');
}

View File

@@ -1,4 +1,4 @@
import { Node } from '../nodes/Node.js';
import type { Node } from '../nodes/Node.js';
import type { Document } from './Document.js';
/**
* Verify that the input string is a valid anchor.
@@ -6,10 +6,10 @@ import type { Document } from './Document.js';
* Will throw on errors.
*/
export declare function anchorIsValid(anchor: string): true;
export declare function anchorNames(root: Document | Node): Set<string>;
export declare function anchorNames(root: Document<Node, boolean> | Node): Set<string>;
/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */
export declare function findNewAnchor(prefix: string, exclude: Set<string>): string;
export declare function createNodeAnchors(doc: Document, prefix: string): {
export declare function createNodeAnchors(doc: Document<Node, boolean>, prefix: string): {
onAnchor: (source: unknown) => string;
/**
* With circular references, the source node is only resolved after all
@@ -19,6 +19,6 @@ export declare function createNodeAnchors(doc: Document, prefix: string): {
setAnchors: () => void;
sourceObjects: Map<unknown, {
anchor: string | null;
node: Node<unknown> | null;
node: Node | null;
}>;
};

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var visit = require('../visit.js');
/**
@@ -57,7 +57,7 @@ function createNodeAnchors(doc, prefix) {
const ref = sourceObjects.get(source);
if (typeof ref === 'object' &&
ref.anchor &&
(Node.isScalar(ref.node) || Node.isCollection(ref.node))) {
(identity.isScalar(ref.node) || identity.isCollection(ref.node))) {
ref.node.anchor = ref.anchor;
}
else {

View File

@@ -1,4 +1,4 @@
export declare type Reviver = (key: unknown, value: unknown) => unknown;
export type Reviver = (key: unknown, value: unknown) => unknown;
/**
* Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,
* in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the

View File

@@ -1,4 +1,4 @@
import { Node } from '../nodes/Node.js';
import type { Node } from '../nodes/Node.js';
import type { Schema } from '../schema/Schema.js';
import type { CollectionTag, ScalarTag } from '../schema/types.js';
import type { Replacer } from './Document.js';

View File

@@ -1,7 +1,7 @@
'use strict';
var Alias = require('../nodes/Alias.js');
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var Scalar = require('../nodes/Scalar.js');
const defaultTagPrefix = 'tag:yaml.org,2002:';
@@ -16,12 +16,12 @@ function findTagObject(value, tagName, tags) {
return tags.find(t => t.identify?.(value) && !t.format);
}
function createNode(value, tagName, ctx) {
if (Node.isDocument(value))
if (identity.isDocument(value))
value = value.contents;
if (Node.isNode(value))
if (identity.isNode(value))
return value;
if (Node.isPair(value)) {
const map = ctx.schema[Node.MAP].createNode?.(ctx.schema, null, ctx);
if (identity.isPair(value)) {
const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);
map.items.push(value);
return map;
}
@@ -65,10 +65,10 @@ function createNode(value, tagName, ctx) {
}
tagObj =
value instanceof Map
? schema[Node.MAP]
? schema[identity.MAP]
: Symbol.iterator in Object(value)
? schema[Node.SEQ]
: schema[Node.MAP];
? schema[identity.SEQ]
: schema[identity.MAP];
}
if (onTagObj) {
onTagObj(tagObj);
@@ -76,9 +76,13 @@ function createNode(value, tagName, ctx) {
}
const node = tagObj?.createNode
? tagObj.createNode(ctx.schema, value, ctx)
: new Scalar.Scalar(value);
: typeof tagObj?.nodeClass?.from === 'function'
? tagObj.nodeClass.from(ctx.schema, value, ctx)
: new Scalar.Scalar(value);
if (tagName)
node.tag = tagName;
else if (!tagObj.default)
node.tag = tagObj.tag;
if (ref)
ref.node = node;
return node;

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var visit = require('../visit.js');
const escapeChars = {
@@ -118,12 +118,19 @@ class Directives {
onError('Verbatim tags must end with a >');
return verbatim;
}
const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/);
const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
if (!suffix)
onError(`The ${source} tag has no suffix`);
const prefix = this.tags[handle];
if (prefix)
return prefix + decodeURIComponent(suffix);
if (prefix) {
try {
return prefix + decodeURIComponent(suffix);
}
catch (error) {
onError(String(error));
return null;
}
}
if (handle === '!')
return source; // local tag
onError(`Could not resolve tag: ${source}`);
@@ -146,10 +153,10 @@ class Directives {
: [];
const tagEntries = Object.entries(this.tags);
let tagNames;
if (doc && tagEntries.length > 0 && Node.isNode(doc.contents)) {
if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {
const tags = {};
visit.visit(doc.contents, (_key, node) => {
if (Node.isNode(node) && node.tag)
if (identity.isNode(node) && node.tag)
tags[node.tag] = true;
});
tagNames = Object.keys(tags);

4
node_modules/yaml/dist/errors.d.ts generated vendored
View File

@@ -1,6 +1,6 @@
import type { LineCounter } from './parse/line-counter';
export declare type ErrorCode = 'ALIAS_PROPS' | 'BAD_ALIAS' | 'BAD_DIRECTIVE' | 'BAD_DQ_ESCAPE' | 'BAD_INDENT' | 'BAD_PROP_ORDER' | 'BAD_SCALAR_START' | 'BLOCK_AS_IMPLICIT_KEY' | 'BLOCK_IN_FLOW' | 'DUPLICATE_KEY' | 'IMPOSSIBLE' | 'KEY_OVER_1024_CHARS' | 'MISSING_CHAR' | 'MULTILINE_IMPLICIT_KEY' | 'MULTIPLE_ANCHORS' | 'MULTIPLE_DOCS' | 'MULTIPLE_TAGS' | 'TAB_AS_INDENT' | 'TAG_RESOLVE_FAILED' | 'UNEXPECTED_TOKEN';
export declare type LinePos = {
export type ErrorCode = 'ALIAS_PROPS' | 'BAD_ALIAS' | 'BAD_DIRECTIVE' | 'BAD_DQ_ESCAPE' | 'BAD_INDENT' | 'BAD_PROP_ORDER' | 'BAD_SCALAR_START' | 'BLOCK_AS_IMPLICIT_KEY' | 'BLOCK_IN_FLOW' | 'DUPLICATE_KEY' | 'IMPOSSIBLE' | 'KEY_OVER_1024_CHARS' | 'MISSING_CHAR' | 'MULTILINE_IMPLICIT_KEY' | 'MULTIPLE_ANCHORS' | 'MULTIPLE_DOCS' | 'MULTIPLE_TAGS' | 'TAB_AS_INDENT' | 'TAG_RESOLVE_FAILED' | 'UNEXPECTED_TOKEN' | 'BAD_COLLECTION_TYPE';
export type LinePos = {
line: number;
col: number;
};

2
node_modules/yaml/dist/errors.js generated vendored
View File

@@ -49,7 +49,7 @@ const prettifyError = (src, lc) => (error) => {
let count = 1;
const end = error.linePos[1];
if (end && end.line === line && end.col > col) {
count = Math.min(end.col - col, 80 - ci);
count = Math.max(1, Math.min(end.col - col, 80 - ci));
}
const pointer = ' '.repeat(ci) + '^'.repeat(count);
error.message += `:\n\n${lineStr}\n${pointer}\n`;

3
node_modules/yaml/dist/index.d.ts generated vendored
View File

@@ -3,7 +3,8 @@ export { Document } from './doc/Document.js';
export { Schema } from './schema/Schema.js';
export { ErrorCode, YAMLError, YAMLParseError, YAMLWarning } from './errors.js';
export { Alias } from './nodes/Alias.js';
export { isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq, Node, ParsedNode, Range } from './nodes/Node.js';
export { isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq } from './nodes/identity.js';
export { Node, ParsedNode, Range } from './nodes/Node.js';
export { Pair } from './nodes/Pair.js';
export { Scalar } from './nodes/Scalar.js';
export { YAMLMap } from './nodes/YAMLMap.js';

18
node_modules/yaml/dist/index.js generated vendored
View File

@@ -5,7 +5,7 @@ var Document = require('./doc/Document.js');
var Schema = require('./schema/Schema.js');
var errors = require('./errors.js');
var Alias = require('./nodes/Alias.js');
var Node = require('./nodes/Node.js');
var identity = require('./nodes/identity.js');
var Pair = require('./nodes/Pair.js');
var Scalar = require('./nodes/Scalar.js');
var YAMLMap = require('./nodes/YAMLMap.js');
@@ -26,14 +26,14 @@ exports.YAMLError = errors.YAMLError;
exports.YAMLParseError = errors.YAMLParseError;
exports.YAMLWarning = errors.YAMLWarning;
exports.Alias = Alias.Alias;
exports.isAlias = Node.isAlias;
exports.isCollection = Node.isCollection;
exports.isDocument = Node.isDocument;
exports.isMap = Node.isMap;
exports.isNode = Node.isNode;
exports.isPair = Node.isPair;
exports.isScalar = Node.isScalar;
exports.isSeq = Node.isSeq;
exports.isAlias = identity.isAlias;
exports.isCollection = identity.isCollection;
exports.isDocument = identity.isDocument;
exports.isMap = identity.isMap;
exports.isNode = identity.isNode;
exports.isPair = identity.isPair;
exports.isScalar = identity.isScalar;
exports.isSeq = identity.isSeq;
exports.Pair = Pair.Pair;
exports.Scalar = Scalar.Scalar;
exports.YAMLMap = YAMLMap.YAMLMap;

2
node_modules/yaml/dist/log.d.ts generated vendored
View File

@@ -1,3 +1,3 @@
export declare type LogLevelId = 'silent' | 'error' | 'warn' | 'debug';
export type LogLevelId = 'silent' | 'error' | 'warn' | 'debug';
export declare function debug(logLevel: LogLevelId, ...messages: any[]): void;
export declare function warn(logLevel: LogLevelId, warning: string | Error): void;

2
node_modules/yaml/dist/log.js generated vendored
View File

@@ -6,6 +6,8 @@ function debug(logLevel, ...messages) {
}
function warn(logLevel, warning) {
if (logLevel === 'debug' || logLevel === 'warn') {
// https://github.com/typescript-eslint/typescript-eslint/issues/7478
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain
if (typeof process !== 'undefined' && process.emitWarning)
process.emitWarning(warning);
else

View File

@@ -3,7 +3,7 @@ import type { FlowScalar } from '../parse/cst.js';
import type { StringifyContext } from '../stringify/stringify.js';
import { NodeBase, Range } from './Node.js';
import type { Scalar } from './Scalar';
import type { ToJSContext } from './toJS.js';
import { ToJSContext } from './toJS.js';
import type { YAMLMap } from './YAMLMap.js';
import type { YAMLSeq } from './YAMLSeq.js';
export declare namespace Alias {

View File

@@ -2,11 +2,13 @@
var anchors = require('../doc/anchors.js');
var visit = require('../visit.js');
var identity = require('./identity.js');
var Node = require('./Node.js');
var toJS = require('./toJS.js');
class Alias extends Node.NodeBase {
constructor(source) {
super(Node.ALIAS);
super(identity.ALIAS);
this.source = source;
Object.defineProperty(this, 'tag', {
set() {
@@ -39,7 +41,12 @@ class Alias extends Node.NodeBase {
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
throw new ReferenceError(msg);
}
const data = anchors.get(source);
let data = anchors.get(source);
if (!data) {
// Resolve anchors for Node.prototype.toJS()
toJS.toJS(source, null, ctx);
data = anchors.get(source);
}
/* istanbul ignore if */
if (!data || data.res === undefined) {
const msg = 'This should not happen: Alias anchor was not resolved?';
@@ -71,12 +78,12 @@ class Alias extends Node.NodeBase {
}
}
function getAliasCount(doc, node, anchors) {
if (Node.isAlias(node)) {
if (identity.isAlias(node)) {
const source = node.resolve(doc);
const anchor = anchors && source && anchors.get(source);
return anchor ? anchor.count * anchor.aliasCount : 0;
}
else if (Node.isCollection(node)) {
else if (identity.isCollection(node)) {
let count = 0;
for (const item of node.items) {
const c = getAliasCount(doc, item, anchors);
@@ -85,7 +92,7 @@ function getAliasCount(doc, node, anchors) {
}
return count;
}
else if (Node.isPair(node)) {
else if (identity.isPair(node)) {
const kc = getAliasCount(doc, node.key, anchors);
const vc = getAliasCount(doc, node.value, anchors);
return Math.max(kc, vc);

View File

@@ -1,6 +1,7 @@
import type { Schema } from '../schema/Schema.js';
import { NodeBase, NODE_TYPE } from './Node.js';
export declare function collectionFromPath(schema: Schema, path: unknown[], value: unknown): import("./Node.js").Node<unknown>;
import { NODE_TYPE } from './identity.js';
import { NodeBase } from './Node.js';
export declare function collectionFromPath(schema: Schema, path: unknown[], value: unknown): import("./Node.js").Node;
export declare const isEmptyPath: (path: Iterable<unknown> | null | undefined) => path is null | undefined;
export declare abstract class Collection extends NodeBase {
static maxFlowStringSingleLineLength: number;

View File

@@ -1,6 +1,7 @@
'use strict';
var createNode = require('../doc/createNode.js');
var identity = require('./identity.js');
var Node = require('./Node.js');
function collectionFromPath(schema, path, value) {
@@ -49,7 +50,7 @@ class Collection extends Node.NodeBase {
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
if (schema)
copy.schema = schema;
copy.items = copy.items.map(it => Node.isNode(it) || Node.isPair(it) ? it.clone(schema) : it);
copy.items = copy.items.map(it => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it);
if (this.range)
copy.range = this.range.slice();
return copy;
@@ -65,7 +66,7 @@ class Collection extends Node.NodeBase {
else {
const [key, ...rest] = path;
const node = this.get(key, true);
if (Node.isCollection(node))
if (identity.isCollection(node))
node.addIn(rest, value);
else if (node === undefined && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value));
@@ -82,7 +83,7 @@ class Collection extends Node.NodeBase {
if (rest.length === 0)
return this.delete(key);
const node = this.get(key, true);
if (Node.isCollection(node))
if (identity.isCollection(node))
return node.deleteIn(rest);
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
@@ -96,18 +97,18 @@ class Collection extends Node.NodeBase {
const [key, ...rest] = path;
const node = this.get(key, true);
if (rest.length === 0)
return !keepScalar && Node.isScalar(node) ? node.value : node;
return !keepScalar && identity.isScalar(node) ? node.value : node;
else
return Node.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;
return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;
}
hasAllNullValues(allowScalar) {
return this.items.every(node => {
if (!Node.isPair(node))
if (!identity.isPair(node))
return false;
const n = node.value;
return (n == null ||
(allowScalar &&
Node.isScalar(n) &&
identity.isScalar(n) &&
n.value == null &&
!n.commentBefore &&
!n.comment &&
@@ -122,7 +123,7 @@ class Collection extends Node.NodeBase {
if (rest.length === 0)
return this.has(key);
const node = this.get(key, true);
return Node.isCollection(node) ? node.hasIn(rest) : false;
return identity.isCollection(node) ? node.hasIn(rest) : false;
}
/**
* Sets a value in this collection. For `!!set`, `value` needs to be a
@@ -135,7 +136,7 @@ class Collection extends Node.NodeBase {
}
else {
const node = this.get(key, true);
if (Node.isCollection(node))
if (identity.isCollection(node))
node.setIn(rest, value);
else if (node === undefined && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value));

View File

@@ -1,36 +1,21 @@
import type { Document } from '../doc/Document.js';
import type { ToJSOptions } from '../options.js';
import { Token } from '../parse/cst.js';
import type { StringifyContext } from '../stringify/stringify.js';
import type { Alias } from './Alias.js';
import type { Pair } from './Pair.js';
import { NODE_TYPE } from './identity.js';
import type { Scalar } from './Scalar.js';
import type { YAMLMap } from './YAMLMap.js';
import type { YAMLSeq } from './YAMLSeq.js';
export declare type Node<T = unknown> = Alias | Scalar<T> | YAMLMap<unknown, T> | YAMLSeq<T>;
export type Node<T = unknown> = Alias | Scalar<T> | YAMLMap<unknown, T> | YAMLSeq<T>;
/** Utility type mapper */
export declare type NodeType<T> = T extends string | number | bigint | boolean | null ? Scalar<T> : T extends Array<any> ? YAMLSeq<NodeType<T[number]>> : T extends {
export type NodeType<T> = T extends string | number | bigint | boolean | null | undefined ? Scalar<T> : T extends Date ? Scalar<string | Date> : T extends Array<any> ? YAMLSeq<NodeType<T[number]>> : T extends {
[key: string]: any;
} ? YAMLMap<NodeType<keyof T>, NodeType<T[keyof T]>> : T extends {
[key: number]: any;
} ? YAMLMap<NodeType<keyof T>, NodeType<T[keyof T]>> : Node;
export declare type ParsedNode = Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed;
export declare type Range = [number, number, number];
export declare const ALIAS: unique symbol;
export declare const DOC: unique symbol;
export declare const MAP: unique symbol;
export declare const PAIR: unique symbol;
export declare const SCALAR: unique symbol;
export declare const SEQ: unique symbol;
export declare const NODE_TYPE: unique symbol;
export declare const isAlias: (node: any) => node is Alias;
export declare const isDocument: <T extends Node<unknown> = Node<unknown>>(node: any) => node is Document<T>;
export declare const isMap: <K = unknown, V = unknown>(node: any) => node is YAMLMap<K, V>;
export declare const isPair: <K = unknown, V = unknown>(node: any) => node is Pair<K, V>;
export declare const isScalar: <T = unknown>(node: any) => node is Scalar<T>;
export declare const isSeq: <T = unknown>(node: any) => node is YAMLSeq<T>;
export declare function isCollection<K = unknown, V = unknown>(node: any): node is YAMLMap<K, V> | YAMLSeq<V>;
export declare function isNode<T = unknown>(node: any): node is Node<T>;
export declare const hasAnchor: <K = unknown, V = unknown>(node: unknown) => node is Scalar<V> | YAMLMap<K, V> | YAMLSeq<V>;
export type ParsedNode = Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed;
export type Range = [number, number, number];
export declare abstract class NodeBase {
readonly [NODE_TYPE]: symbol;
/** A comment on or immediately after this */
@@ -56,4 +41,6 @@ export declare abstract class NodeBase {
constructor(type: symbol);
/** Create a copy of this node. */
clone(): NodeBase;
/** A plain JavaScript representation of this node. */
toJS(doc: Document<Node, boolean>, { mapAsMap, maxAliasCount, onAnchor, reviver }?: ToJSOptions): any;
}

76
node_modules/yaml/dist/nodes/Node.js generated vendored
View File

@@ -1,42 +1,12 @@
'use strict';
const ALIAS = Symbol.for('yaml.alias');
const DOC = Symbol.for('yaml.document');
const MAP = Symbol.for('yaml.map');
const PAIR = Symbol.for('yaml.pair');
const SCALAR = Symbol.for('yaml.scalar');
const SEQ = Symbol.for('yaml.seq');
const NODE_TYPE = Symbol.for('yaml.node.type');
const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;
const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;
const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;
const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;
const isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;
const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;
function isCollection(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case MAP:
case SEQ:
return true;
}
return false;
}
function isNode(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case ALIAS:
case MAP:
case SCALAR:
case SEQ:
return true;
}
return false;
}
const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
var applyReviver = require('../doc/applyReviver.js');
var identity = require('./identity.js');
var toJS = require('./toJS.js');
class NodeBase {
constructor(type) {
Object.defineProperty(this, NODE_TYPE, { value: type });
Object.defineProperty(this, identity.NODE_TYPE, { value: type });
}
/** Create a copy of this node. */
clone() {
@@ -45,22 +15,26 @@ class NodeBase {
copy.range = this.range.slice();
return copy;
}
/** A plain JavaScript representation of this node. */
toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
if (!identity.isDocument(doc))
throw new TypeError('A document argument is required');
const ctx = {
anchors: new Map(),
doc,
keep: true,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
};
const res = toJS.toJS(this, '', ctx);
if (typeof onAnchor === 'function')
for (const { count, res } of ctx.anchors.values())
onAnchor(res, count);
return typeof reviver === 'function'
? applyReviver.applyReviver(reviver, { '': res }, '', res)
: res;
}
}
exports.ALIAS = ALIAS;
exports.DOC = DOC;
exports.MAP = MAP;
exports.NODE_TYPE = NODE_TYPE;
exports.NodeBase = NodeBase;
exports.PAIR = PAIR;
exports.SCALAR = SCALAR;
exports.SEQ = SEQ;
exports.hasAnchor = hasAnchor;
exports.isAlias = isAlias;
exports.isCollection = isCollection;
exports.isDocument = isDocument;
exports.isMap = isMap;
exports.isNode = isNode;
exports.isPair = isPair;
exports.isScalar = isScalar;
exports.isSeq = isSeq;

View File

@@ -3,9 +3,9 @@ import type { CollectionItem } from '../parse/cst.js';
import type { Schema } from '../schema/Schema.js';
import type { StringifyContext } from '../stringify/stringify.js';
import { addPairToJSMap } from './addPairToJSMap.js';
import { NODE_TYPE } from './Node.js';
import { NODE_TYPE } from './identity.js';
import type { ToJSContext } from './toJS.js';
export declare function createPair(key: unknown, value: unknown, ctx: CreateNodeContext): Pair<import("./Node.js").Node<unknown>, import("./Alias.js").Alias | import("./Scalar.js").Scalar<unknown> | import("./YAMLMap.js").YAMLMap<unknown, unknown> | import("./YAMLSeq.js").YAMLSeq<unknown>>;
export declare function createPair(key: unknown, value: unknown, ctx: CreateNodeContext): Pair<import("./Node.js").Node, import("./YAMLMap.js").YAMLMap<unknown, unknown> | import("./Scalar.js").Scalar<unknown> | import("./Alias.js").Alias | import("./YAMLSeq.js").YAMLSeq<unknown>>;
export declare class Pair<K = unknown, V = unknown> {
readonly [NODE_TYPE]: symbol;
/** Always Node or null when parsed, but can be set to anything. */

View File

@@ -3,7 +3,7 @@
var createNode = require('../doc/createNode.js');
var stringifyPair = require('../stringify/stringifyPair.js');
var addPairToJSMap = require('./addPairToJSMap.js');
var Node = require('./Node.js');
var identity = require('./identity.js');
function createPair(key, value, ctx) {
const k = createNode.createNode(key, undefined, ctx);
@@ -12,15 +12,15 @@ function createPair(key, value, ctx) {
}
class Pair {
constructor(key, value = null) {
Object.defineProperty(this, Node.NODE_TYPE, { value: Node.PAIR });
Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });
this.key = key;
this.value = value;
}
clone(schema) {
let { key, value } = this;
if (Node.isNode(key))
if (identity.isNode(key))
key = key.clone(schema);
if (Node.isNode(value))
if (identity.isNode(value))
value = value.clone(schema);
return new Pair(key, value);
}

View File

@@ -1,12 +1,13 @@
'use strict';
var identity = require('./identity.js');
var Node = require('./Node.js');
var toJS = require('./toJS.js');
const isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');
class Scalar extends Node.NodeBase {
constructor(value) {
super(Node.SCALAR);
super(identity.SCALAR);
this.value = value;
}
toJSON(arg, ctx) {

View File

@@ -1,12 +1,13 @@
import type { BlockMap, FlowCollection } from '../parse/cst.js';
import type { Schema } from '../schema/Schema.js';
import type { StringifyContext } from '../stringify/stringify.js';
import { CreateNodeContext } from '../util.js';
import { Collection } from './Collection.js';
import { ParsedNode, Range } from './Node.js';
import type { ParsedNode, Range } from './Node.js';
import { Pair } from './Pair.js';
import { Scalar } from './Scalar.js';
import type { ToJSContext } from './toJS.js';
export declare type MapLike = Map<unknown, unknown> | Set<unknown> | Record<string | number | symbol, unknown>;
export type MapLike = Map<unknown, unknown> | Set<unknown> | Record<string | number | symbol, unknown>;
export declare function findPair<K = unknown, V = unknown>(items: Iterable<Pair<K, V>>, key: unknown): Pair<K, V> | undefined;
export declare namespace YAMLMap {
interface Parsed<K extends ParsedNode = ParsedNode, V extends ParsedNode | null = ParsedNode | null> extends YAMLMap<K, V> {
@@ -19,6 +20,11 @@ export declare class YAMLMap<K = unknown, V = unknown> extends Collection {
static get tagName(): 'tag:yaml.org,2002:map';
items: Pair<K, V>[];
constructor(schema?: Schema);
/**
* A generic collection parsing method that can be extended
* to other node classes that inherit from YAMLMap
*/
static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLMap<unknown, unknown>;
/**
* Adds a value to the collection.
*

View File

@@ -3,30 +3,58 @@
var stringifyCollection = require('../stringify/stringifyCollection.js');
var addPairToJSMap = require('./addPairToJSMap.js');
var Collection = require('./Collection.js');
var Node = require('./Node.js');
var identity = require('./identity.js');
var Pair = require('./Pair.js');
var Scalar = require('./Scalar.js');
function findPair(items, key) {
const k = Node.isScalar(key) ? key.value : key;
const k = identity.isScalar(key) ? key.value : key;
for (const it of items) {
if (Node.isPair(it)) {
if (identity.isPair(it)) {
if (it.key === key || it.key === k)
return it;
if (Node.isScalar(it.key) && it.key.value === k)
if (identity.isScalar(it.key) && it.key.value === k)
return it;
}
}
return undefined;
}
class YAMLMap extends Collection.Collection {
constructor(schema) {
super(Node.MAP, schema);
this.items = [];
}
static get tagName() {
return 'tag:yaml.org,2002:map';
}
constructor(schema) {
super(identity.MAP, schema);
this.items = [];
}
/**
* A generic collection parsing method that can be extended
* to other node classes that inherit from YAMLMap
*/
static from(schema, obj, ctx) {
const { keepUndefined, replacer } = ctx;
const map = new this(schema);
const add = (key, value) => {
if (typeof replacer === 'function')
value = replacer.call(obj, key, value);
else if (Array.isArray(replacer) && !replacer.includes(key))
return;
if (value !== undefined || keepUndefined)
map.items.push(Pair.createPair(key, value, ctx));
};
if (obj instanceof Map) {
for (const [key, value] of obj)
add(key, value);
}
else if (obj && typeof obj === 'object') {
for (const key of Object.keys(obj))
add(key, obj[key]);
}
if (typeof schema.sortMapEntries === 'function') {
map.items.sort(schema.sortMapEntries);
}
return map;
}
/**
* Adds a value to the collection.
*
@@ -35,7 +63,7 @@ class YAMLMap extends Collection.Collection {
*/
add(pair, overwrite) {
let _pair;
if (Node.isPair(pair))
if (identity.isPair(pair))
_pair = pair;
else if (!pair || typeof pair !== 'object' || !('key' in pair)) {
// In TypeScript, this never happens.
@@ -49,7 +77,7 @@ class YAMLMap extends Collection.Collection {
if (!overwrite)
throw new Error(`Key ${_pair.key} already set`);
// For scalars, keep the old node & its comments and anchors
if (Node.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
prev.value.value = _pair.value;
else
prev.value = _pair.value;
@@ -75,7 +103,7 @@ class YAMLMap extends Collection.Collection {
get(key, keepScalar) {
const it = findPair(this.items, key);
const node = it?.value;
return (!keepScalar && Node.isScalar(node) ? node.value : node) ?? undefined;
return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined;
}
has(key) {
return !!findPair(this.items, key);
@@ -100,7 +128,7 @@ class YAMLMap extends Collection.Collection {
if (!ctx)
return JSON.stringify(this);
for (const item of this.items) {
if (!Node.isPair(item))
if (!identity.isPair(item))
throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
}
if (!ctx.allNullValues && this.hasAllNullValues(false))

View File

@@ -1,8 +1,9 @@
import { CreateNodeContext } from '../doc/createNode.js';
import type { BlockSequence, FlowCollection } from '../parse/cst.js';
import type { Schema } from '../schema/Schema.js';
import type { StringifyContext } from '../stringify/stringify.js';
import { Collection } from './Collection.js';
import { ParsedNode, Range } from './Node.js';
import type { ParsedNode, Range } from './Node.js';
import type { Pair } from './Pair.js';
import { Scalar } from './Scalar.js';
import { ToJSContext } from './toJS.js';
@@ -55,4 +56,5 @@ export declare class YAMLSeq<T = unknown> extends Collection {
set(key: unknown, value: T): void;
toJSON(_?: unknown, ctx?: ToJSContext): unknown[];
toString(ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void): string;
static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLSeq<unknown>;
}

View File

@@ -1,19 +1,20 @@
'use strict';
var createNode = require('../doc/createNode.js');
var stringifyCollection = require('../stringify/stringifyCollection.js');
var Collection = require('./Collection.js');
var Node = require('./Node.js');
var identity = require('./identity.js');
var Scalar = require('./Scalar.js');
var toJS = require('./toJS.js');
class YAMLSeq extends Collection.Collection {
constructor(schema) {
super(Node.SEQ, schema);
this.items = [];
}
static get tagName() {
return 'tag:yaml.org,2002:seq';
}
constructor(schema) {
super(identity.SEQ, schema);
this.items = [];
}
add(value) {
this.items.push(value);
}
@@ -37,7 +38,7 @@ class YAMLSeq extends Collection.Collection {
if (typeof idx !== 'number')
return undefined;
const it = this.items[idx];
return !keepScalar && Node.isScalar(it) ? it.value : it;
return !keepScalar && identity.isScalar(it) ? it.value : it;
}
/**
* Checks if the collection includes a value with the key `key`.
@@ -61,7 +62,7 @@ class YAMLSeq extends Collection.Collection {
if (typeof idx !== 'number')
throw new Error(`Expected a valid index, not ${key}.`);
const prev = this.items[idx];
if (Node.isScalar(prev) && Scalar.isScalarValue(value))
if (identity.isScalar(prev) && Scalar.isScalarValue(value))
prev.value = value;
else
this.items[idx] = value;
@@ -86,9 +87,24 @@ class YAMLSeq extends Collection.Collection {
onComment
});
}
static from(schema, obj, ctx) {
const { replacer } = ctx;
const seq = new this(schema);
if (obj && Symbol.iterator in Object(obj)) {
let i = 0;
for (let it of obj) {
if (typeof replacer === 'function') {
const key = obj instanceof Set ? it : String(i++);
it = replacer.call(obj, key, it);
}
seq.items.push(createNode.createNode(it, undefined, ctx));
}
}
return seq;
}
}
function asItemIndex(key) {
let idx = Node.isScalar(key) ? key.value : key;
let idx = identity.isScalar(key) ? key.value : key;
if (idx && typeof idx === 'string')
idx = Number(idx);
return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0

View File

@@ -2,15 +2,15 @@
var log = require('../log.js');
var stringify = require('../stringify/stringify.js');
var Node = require('./Node.js');
var identity = require('./identity.js');
var Scalar = require('./Scalar.js');
var toJS = require('./toJS.js');
const MERGE_KEY = '<<';
function addPairToJSMap(ctx, map, { key, value }) {
if (ctx?.doc.schema.merge && isMergeKey(key)) {
value = Node.isAlias(value) ? value.resolve(ctx.doc) : value;
if (Node.isSeq(value))
value = identity.isAlias(value) ? value.resolve(ctx.doc) : value;
if (identity.isSeq(value))
for (const it of value.items)
mergeToJSMap(ctx, map, it);
else if (Array.isArray(value))
@@ -44,7 +44,7 @@ function addPairToJSMap(ctx, map, { key, value }) {
return map;
}
const isMergeKey = (key) => key === MERGE_KEY ||
(Node.isScalar(key) &&
(identity.isScalar(key) &&
key.value === MERGE_KEY &&
(!key.type || key.type === Scalar.Scalar.PLAIN));
// If the value associated with a merge key is a single mapping node, each of
@@ -55,8 +55,8 @@ const isMergeKey = (key) => key === MERGE_KEY ||
// Keys in mapping nodes earlier in the sequence override keys specified in
// later mapping nodes. -- http://yaml.org/type/merge.html
function mergeToJSMap(ctx, map, value) {
const source = ctx && Node.isAlias(value) ? value.resolve(ctx.doc) : value;
if (!Node.isMap(source))
const source = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value;
if (!identity.isMap(source))
throw new Error('Merge sources must be maps or map aliases');
const srcMap = source.toJSON(null, ctx, Map);
for (const [key, value] of srcMap) {
@@ -83,7 +83,7 @@ function stringifyKey(key, jsKey, ctx) {
return '';
if (typeof jsKey !== 'object')
return String(jsKey);
if (Node.isNode(key) && ctx && ctx.doc) {
if (identity.isNode(key) && ctx?.doc) {
const strCtx = stringify.createStringifyContext(ctx.doc, {});
strCtx.anchors = new Set();
for (const node of ctx.anchors.keys())

23
node_modules/yaml/dist/nodes/identity.d.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import type { Document } from '../doc/Document.js';
import type { Alias } from './Alias.js';
import type { Node } from './Node.js';
import type { Pair } from './Pair.js';
import type { Scalar } from './Scalar.js';
import type { YAMLMap } from './YAMLMap.js';
import type { YAMLSeq } from './YAMLSeq.js';
export declare const ALIAS: unique symbol;
export declare const DOC: unique symbol;
export declare const MAP: unique symbol;
export declare const PAIR: unique symbol;
export declare const SCALAR: unique symbol;
export declare const SEQ: unique symbol;
export declare const NODE_TYPE: unique symbol;
export declare const isAlias: (node: any) => node is Alias;
export declare const isDocument: <T extends Node = Node>(node: any) => node is Document<T, true>;
export declare const isMap: <K = unknown, V = unknown>(node: any) => node is YAMLMap<K, V>;
export declare const isPair: <K = unknown, V = unknown>(node: any) => node is Pair<K, V>;
export declare const isScalar: <T = unknown>(node: any) => node is Scalar<T>;
export declare const isSeq: <T = unknown>(node: any) => node is YAMLSeq<T>;
export declare function isCollection<K = unknown, V = unknown>(node: any): node is YAMLMap<K, V> | YAMLSeq<V>;
export declare function isNode<T = unknown>(node: any): node is Node<T>;
export declare const hasAnchor: <K = unknown, V = unknown>(node: unknown) => node is Scalar<V> | YAMLMap<K, V> | YAMLSeq<V>;

53
node_modules/yaml/dist/nodes/identity.js generated vendored Normal file
View File

@@ -0,0 +1,53 @@
'use strict';
const ALIAS = Symbol.for('yaml.alias');
const DOC = Symbol.for('yaml.document');
const MAP = Symbol.for('yaml.map');
const PAIR = Symbol.for('yaml.pair');
const SCALAR = Symbol.for('yaml.scalar');
const SEQ = Symbol.for('yaml.seq');
const NODE_TYPE = Symbol.for('yaml.node.type');
const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;
const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;
const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;
const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;
const isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;
const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;
function isCollection(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case MAP:
case SEQ:
return true;
}
return false;
}
function isNode(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case ALIAS:
case MAP:
case SCALAR:
case SEQ:
return true;
}
return false;
}
const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
exports.ALIAS = ALIAS;
exports.DOC = DOC;
exports.MAP = MAP;
exports.NODE_TYPE = NODE_TYPE;
exports.PAIR = PAIR;
exports.SCALAR = SCALAR;
exports.SEQ = SEQ;
exports.hasAnchor = hasAnchor;
exports.isAlias = isAlias;
exports.isCollection = isCollection;
exports.isDocument = isDocument;
exports.isMap = isMap;
exports.isNode = isNode;
exports.isPair = isPair;
exports.isScalar = isScalar;
exports.isSeq = isSeq;

View File

@@ -1,6 +1,5 @@
import type { Document } from '../doc/Document.js';
import type { stringify } from '../stringify/stringify.js';
import { Node } from './Node.js';
import type { Node } from './Node.js';
export interface AnchorData {
aliasCount: number;
count: number;
@@ -8,14 +7,12 @@ export interface AnchorData {
}
export interface ToJSContext {
anchors: Map<Node, AnchorData>;
doc: Document;
doc: Document<Node, boolean>;
keep: boolean;
mapAsMap: boolean;
mapKeyWarned: boolean;
maxAliasCount: number;
onCreate?: (res: unknown) => void;
/** Requiring this directly in Pair would create circular dependencies */
stringify: typeof stringify;
}
/**
* Recursively convert any node or its contents to native JavaScript

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('./Node.js');
var identity = require('./identity.js');
/**
* Recursively convert any node or its contents to native JavaScript
@@ -18,7 +18,7 @@ function toJS(value, arg, ctx) {
return value.map((v, i) => toJS(v, String(i), ctx));
if (value && typeof value.toJSON === 'function') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
if (!ctx || !Node.hasAnchor(value))
if (!ctx || !identity.hasAnchor(value))
return value.toJSON(arg, ctx);
const data = { aliasCount: 0, count: 1, res: undefined };
ctx.anchors.set(value, data);

19
node_modules/yaml/dist/options.d.ts generated vendored
View File

@@ -8,7 +8,7 @@ import type { LineCounter } from './parse/line-counter.js';
import type { Schema } from './schema/Schema.js';
import type { Tags } from './schema/tags.js';
import type { CollectionTag, ScalarTag } from './schema/types.js';
export declare type ParseOptions = {
export type ParseOptions = {
/**
* Whether integers should be parsed into BigInt rather than number values.
*
@@ -56,7 +56,7 @@ export declare type ParseOptions = {
*/
uniqueKeys?: boolean | ((a: ParsedNode, b: ParsedNode) => boolean);
};
export declare type DocumentOptions = {
export type DocumentOptions = {
/**
* @internal
* Used internally by Composer. If set and includes an explicit version,
@@ -76,7 +76,7 @@ export declare type DocumentOptions = {
*/
version?: '1.1' | '1.2' | 'next';
};
export declare type SchemaOptions = {
export type SchemaOptions = {
/**
* When parsing, warn about compatibility issues with the given schema.
* When stringifying, use scalar styles that are parsed correctly
@@ -133,7 +133,7 @@ export declare type SchemaOptions = {
*/
toStringDefaults?: ToStringOptions;
};
export declare type CreateNodeOptions = {
export type CreateNodeOptions = {
/**
* During node construction, use anchors and aliases to keep strictly equal
* non-null objects as equivalent in YAML.
@@ -163,7 +163,7 @@ export declare type CreateNodeOptions = {
*/
tag?: string;
};
export declare type ToJSOptions = {
export type ToJSOptions = {
/**
* Use Map rather than Object to represent mappings.
*
@@ -189,7 +189,7 @@ export declare type ToJSOptions = {
*/
reviver?: Reviver;
};
export declare type ToStringOptions = {
export type ToStringOptions = {
/**
* Use block quote styles for scalar values where applicable.
* Set to `false` to disable block quotes completely.
@@ -264,6 +264,13 @@ export declare type ToStringOptions = {
* Default: `'false'`
*/
falseStr?: string;
/**
* When true, a single space of padding will be added inside the delimiters
* of non-empty single-line flow collections.
*
* Default: `true`
*/
flowCollectionPadding?: boolean;
/**
* The number of spaces to use when indenting code.
*

View File

@@ -1,6 +1,6 @@
import type { CollectionItem, Document } from './cst.js';
export declare type VisitPath = readonly ['key' | 'value', number][];
export declare type Visitor = (item: CollectionItem, path: VisitPath) => number | symbol | Visitor | void;
export type VisitPath = readonly ['key' | 'value', number][];
export type Visitor = (item: CollectionItem, path: VisitPath) => number | symbol | Visitor | void;
/**
* Apply a visitor to a CST document or item.
*

View File

@@ -72,7 +72,7 @@ export interface BlockSequence {
value?: Token;
}>;
}
export declare type CollectionItem = {
export type CollectionItem = {
start: SourceToken[];
key?: Token | null;
sep?: SourceToken[];
@@ -86,8 +86,8 @@ export interface FlowCollection {
items: CollectionItem[];
end: SourceToken[];
}
export declare type Token = SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection;
export declare type TokenType = SourceToken['type'] | DocumentEnd['type'] | FlowScalar['type'];
export type Token = SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection;
export type TokenType = SourceToken['type'] | DocumentEnd['type'] | FlowScalar['type'];
/** The byte order mark */
export declare const BOM = "\uFEFF";
/** Start of doc-mode */

View File

@@ -1,7 +1,7 @@
import { Composer } from './compose/composer.js';
import type { Reviver } from './doc/applyReviver.js';
import { Document, Replacer } from './doc/Document.js';
import type { ParsedNode } from './nodes/Node.js';
import type { Node, ParsedNode } from './nodes/Node.js';
import type { CreateNodeOptions, DocumentOptions, ParseOptions, SchemaOptions, ToJSOptions, ToStringOptions } from './options.js';
export interface EmptyStream extends Array<Document.Parsed>, ReturnType<Composer['streamInfo']> {
empty: true;
@@ -15,9 +15,9 @@ export interface EmptyStream extends Array<Document.Parsed>, ReturnType<Composer
* EmptyStream and contain additional stream information. In
* TypeScript, you should use `'empty' in docs` as a type guard for it.
*/
export declare function parseAllDocuments<T extends ParsedNode = ParsedNode>(source: string, options?: ParseOptions & DocumentOptions & SchemaOptions): Document.Parsed<T>[] | EmptyStream;
export declare function parseAllDocuments<Contents extends Node = ParsedNode, Strict extends boolean = true>(source: string, options?: ParseOptions & DocumentOptions & SchemaOptions): Array<Contents extends ParsedNode ? Document.Parsed<Contents, Strict> : Document<Contents, Strict>> | EmptyStream;
/** Parse an input string into a single YAML.Document */
export declare function parseDocument<T extends ParsedNode = ParsedNode>(source: string, options?: ParseOptions & DocumentOptions & SchemaOptions): Document.Parsed<T>;
export declare function parseDocument<Contents extends Node = ParsedNode, Strict extends boolean = true>(source: string, options?: ParseOptions & DocumentOptions & SchemaOptions): Contents extends ParsedNode ? Document.Parsed<Contents, Strict> : Document<Contents, Strict>;
/**
* Parse an input string into JavaScript.
*

View File

@@ -1,4 +1,4 @@
import { MAP, SCALAR, SEQ } from '../nodes/Node.js';
import { MAP, SCALAR, SEQ } from '../nodes/identity.js';
import type { Pair } from '../nodes/Pair.js';
import type { SchemaOptions, ToStringOptions } from '../options.js';
import type { CollectionTag, ScalarTag } from './types.js';

View File

@@ -1,6 +1,6 @@
'use strict';
var Node = require('../nodes/Node.js');
var identity = require('../nodes/identity.js');
var map = require('./common/map.js');
var seq = require('./common/seq.js');
var string = require('./common/string.js');
@@ -19,9 +19,9 @@ class Schema {
this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
this.tags = tags.getTags(customTags, this.name);
this.toStringOptions = toStringDefaults ?? null;
Object.defineProperty(this, Node.MAP, { value: map.map });
Object.defineProperty(this, Node.SCALAR, { value: string.string });
Object.defineProperty(this, Node.SEQ, { value: seq.seq });
Object.defineProperty(this, identity.MAP, { value: map.map });
Object.defineProperty(this, identity.SCALAR, { value: string.string });
Object.defineProperty(this, identity.SEQ, { value: seq.seq });
// Used by createMap()
this.sortMapEntries =
typeof sortMapEntries === 'function'

View File

@@ -1,44 +1,19 @@
'use strict';
var Node = require('../../nodes/Node.js');
var Pair = require('../../nodes/Pair.js');
var identity = require('../../nodes/identity.js');
var YAMLMap = require('../../nodes/YAMLMap.js');
function createMap(schema, obj, ctx) {
const { keepUndefined, replacer } = ctx;
const map = new YAMLMap.YAMLMap(schema);
const add = (key, value) => {
if (typeof replacer === 'function')
value = replacer.call(obj, key, value);
else if (Array.isArray(replacer) && !replacer.includes(key))
return;
if (value !== undefined || keepUndefined)
map.items.push(Pair.createPair(key, value, ctx));
};
if (obj instanceof Map) {
for (const [key, value] of obj)
add(key, value);
}
else if (obj && typeof obj === 'object') {
for (const key of Object.keys(obj))
add(key, obj[key]);
}
if (typeof schema.sortMapEntries === 'function') {
map.items.sort(schema.sortMapEntries);
}
return map;
}
const map = {
collection: 'map',
createNode: createMap,
default: true,
nodeClass: YAMLMap.YAMLMap,
tag: 'tag:yaml.org,2002:map',
resolve(map, onError) {
if (!Node.isMap(map))
if (!identity.isMap(map))
onError('Expected a mapping for this tag');
return map;
}
},
createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)
};
exports.map = map;

View File

@@ -1,35 +1,19 @@
'use strict';
var createNode = require('../../doc/createNode.js');
var Node = require('../../nodes/Node.js');
var identity = require('../../nodes/identity.js');
var YAMLSeq = require('../../nodes/YAMLSeq.js');
function createSeq(schema, obj, ctx) {
const { replacer } = ctx;
const seq = new YAMLSeq.YAMLSeq(schema);
if (obj && Symbol.iterator in Object(obj)) {
let i = 0;
for (let it of obj) {
if (typeof replacer === 'function') {
const key = obj instanceof Set ? it : String(i++);
it = replacer.call(obj, key, it);
}
seq.items.push(createNode.createNode(it, undefined, ctx));
}
}
return seq;
}
const seq = {
collection: 'seq',
createNode: createSeq,
default: true,
nodeClass: YAMLSeq.YAMLSeq,
tag: 'tag:yaml.org,2002:seq',
resolve(seq, onError) {
if (!Node.isSeq(seq))
if (!identity.isSeq(seq))
onError('Expected a sequence for this tag');
return seq;
}
},
createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)
};
exports.seq = seq;

View File

@@ -1 +1 @@
export declare const schema: (import("../types.js").ScalarTag | import("../types.js").CollectionTag)[];
export declare const schema: (import("../types.js").CollectionTag | import("../types.js").ScalarTag)[];

View File

@@ -1,5 +1,5 @@
declare type JsonSchema = boolean | ArraySchema | ObjectSchema | NumberSchema | StringSchema;
declare type JsonType = 'array' | 'object' | 'string' | 'number' | 'integer' | 'boolean' | 'null';
type JsonSchema = boolean | ArraySchema | ObjectSchema | NumberSchema | StringSchema;
type JsonType = 'array' | 'object' | 'string' | 'number' | 'integer' | 'boolean' | 'null';
interface CommonSchema {
type?: JsonType | JsonType[];
const?: unknown;

Some files were not shown because too many files have changed in this diff Show More