UNPKG

@ng-openapi/http-resource

Version:

HTTP Resource plugin for ng-openapi - Angular HTTP utilities with caching and state management

1,519 lines (1,510 loc) 120 kB
var __defProp = Object.defineProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); // src/lib/http-resource.generator.ts import { Scope } from "ts-morph"; // ../../shared/src/utils/string.utils.ts function camelCase(str2) { return str2.replace(/[-_\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "").replace(/^./, (char) => char.toLowerCase()); } __name(camelCase, "camelCase"); function pascalCase(str2) { return str2.replace(/[-_\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "").replace(/^./, (char) => char.toUpperCase()); } __name(pascalCase, "pascalCase"); // ../../shared/src/utils/type.utils.ts function getTypeScriptType(schemaOrType, config, formatOrNullable, isNullable, context = "type") { let schema2; let nullable; if (typeof schemaOrType === "string" || schemaOrType === void 0) { schema2 = { type: schemaOrType, format: typeof formatOrNullable === "string" ? formatOrNullable : void 0 }; nullable = typeof formatOrNullable === "boolean" ? formatOrNullable : isNullable; } else { schema2 = schemaOrType; nullable = typeof formatOrNullable === "boolean" ? formatOrNullable : schema2.nullable; } if (!schema2) { return "any"; } if (schema2.$ref) { const refName = schema2.$ref.split("/").pop(); return nullableType(pascalCase(refName), nullable); } if (schema2.type === "array") { const itemType = schema2.items ? getTypeScriptType(schema2.items, config, void 0, void 0, context) : "unknown"; return nullable ? `(${itemType}[] | null)` : `${itemType}[]`; } switch (schema2.type) { case "string": if (schema2.enum) { return schema2.enum.map((value) => typeof value === "string" ? `'${escapeString(value)}'` : String(value)).join(" | "); } if (schema2.format === "date" || schema2.format === "date-time") { const dateType = config.options.dateType === "Date" ? "Date" : "string"; return nullableType(dateType, nullable); } if (schema2.format === "binary") { const binaryType = context === "type" ? "Blob" : "File"; return nullableType(binaryType, nullable); } if (schema2.format === "uuid" || schema2.format === "email" || schema2.format === "uri" || schema2.format === "hostname" || schema2.format === "ipv4" || schema2.format === "ipv6") { return nullableType("string", nullable); } return nullableType("string", nullable); case "number": case "integer": return nullableType("number", nullable); case "boolean": return nullableType("boolean", nullable); case "object": return nullableType(context === "type" ? "Record<string, any>" : "any", nullable); case "null": return "null"; default: return nullableType("any", nullable); } } __name(getTypeScriptType, "getTypeScriptType"); function nullableType(type2, isNullable) { return type2 + (isNullable ? " | null" : ""); } __name(nullableType, "nullableType"); function escapeString(str2) { return str2.replace(/\\/g, "\\\\").replace(/'/g, "\\'"); } __name(escapeString, "escapeString"); // ../../shared/src/utils/functions/token-names.ts function getClientContextTokenName(clientName = "default") { const clientSuffix = clientName.toUpperCase().replace(/[^A-Z0-9]/g, "_"); return `CLIENT_CONTEXT_TOKEN_${clientSuffix}`; } __name(getClientContextTokenName, "getClientContextTokenName"); function getBasePathTokenName(clientName = "default") { const clientSuffix = clientName.toUpperCase().replace(/[^A-Z0-9]/g, "_"); return `BASE_PATH_${clientSuffix}`; } __name(getBasePathTokenName, "getBasePathTokenName"); // ../../shared/src/utils/functions/duplicate-function-name.ts function hasDuplicateFunctionNames(arr) { return new Set(arr.map((fn) => fn.getName())).size !== arr.length; } __name(hasDuplicateFunctionNames, "hasDuplicateFunctionNames"); // ../../shared/src/utils/functions/extract-paths.ts function extractPaths(swaggerPaths = {}, methods = [ "get", "post", "put", "patch", "delete", "options", "head" ]) { const paths = []; Object.entries(swaggerPaths).forEach(([path3, pathItem]) => { methods.forEach((method) => { if (pathItem[method]) { const operation = pathItem[method]; paths.push({ path: path3, method: method.toUpperCase(), operationId: operation.operationId, summary: operation.summary, description: operation.description, tags: operation.tags || [], parameters: parseParameters(operation.parameters || [], pathItem.parameters || []), requestBody: operation.requestBody, responses: operation.responses || {} }); } }); }); return paths; } __name(extractPaths, "extractPaths"); function parseParameters(operationParams, pathParams) { const allParams = [ ...pathParams, ...operationParams ]; return allParams.map((param) => ({ name: param.name, in: param.in, required: param.required || param.in === "path", schema: param.schema, type: param.type, format: param.format, description: param.description })); } __name(parseParameters, "parseParameters"); // ../../shared/src/utils/functions/extract-swagger-response-type.ts function getResponseTypeFromResponse(response, responseTypeMapping) { const content = response.content || {}; if (Object.keys(content).length === 0) { return "json"; } const responseTypes = []; for (const [contentType, mediaType] of Object.entries(content)) { const schema2 = mediaType?.schema; const mapping = responseTypeMapping || {}; if (mapping[contentType]) { responseTypes.push({ type: mapping[contentType], priority: 1, contentType }); continue; } if (schema2?.format === "binary" || schema2?.format === "byte") { responseTypes.push({ type: "blob", priority: 2, contentType }); continue; } if (schema2?.type === "string" && (schema2?.format === "binary" || schema2?.format === "byte")) { responseTypes.push({ type: "blob", priority: 2, contentType }); continue; } const isPrimitive = isPrimitiveType(schema2); const inferredType = inferResponseTypeFromContentType(contentType); let priority = 3; let finalType = inferredType; if (inferredType === "json" && isPrimitive) { finalType = "text"; priority = 2; } else if (inferredType === "json") { priority = 2; } responseTypes.push({ type: finalType, priority, contentType, isPrimitive }); } responseTypes.sort((a, b) => a.priority - b.priority); return responseTypes[0]?.type || "json"; } __name(getResponseTypeFromResponse, "getResponseTypeFromResponse"); function isPrimitiveType(schema2) { if (!schema2) return false; const primitiveTypes = [ "string", "number", "integer", "boolean" ]; if (primitiveTypes.includes(schema2.type)) { return true; } if (schema2.type === "array") { return false; } if (schema2.type === "object" || schema2.properties) { return false; } if (schema2.$ref) { return false; } if (schema2.allOf || schema2.oneOf || schema2.anyOf) { return false; } return false; } __name(isPrimitiveType, "isPrimitiveType"); function inferResponseTypeFromContentType(contentType) { const normalizedType = contentType.split(";")[0].trim().toLowerCase(); if (normalizedType.includes("json") || normalizedType === "application/ld+json" || normalizedType === "application/hal+json" || normalizedType === "application/vnd.api+json") { return "json"; } if (normalizedType.includes("xml") || normalizedType === "application/soap+xml" || normalizedType === "application/atom+xml" || normalizedType === "application/rss+xml") { return "text"; } if (normalizedType.startsWith("text/")) { const binaryTextTypes = [ "text/rtf", "text/cache-manifest", "text/vcard", "text/calendar" ]; if (binaryTextTypes.includes(normalizedType)) { return "blob"; } return "text"; } if (normalizedType === "application/x-www-form-urlencoded" || normalizedType === "multipart/form-data") { return "text"; } if (normalizedType === "application/javascript" || normalizedType === "application/typescript" || normalizedType === "application/css" || normalizedType === "application/yaml" || normalizedType === "application/x-yaml" || normalizedType === "application/toml") { return "text"; } if (normalizedType.startsWith("image/") || normalizedType.startsWith("audio/") || normalizedType.startsWith("video/") || normalizedType === "application/pdf" || normalizedType === "application/zip" || normalizedType.includes("octet-stream")) { return "arraybuffer"; } return "blob"; } __name(inferResponseTypeFromContentType, "inferResponseTypeFromContentType"); function getResponseType(response, config) { const responseType = getResponseTypeFromResponse(response); const content = response.content || {}; for (const [contentType, mediaType] of Object.entries(content)) { if (mediaType?.schema) { return getTypeScriptType(mediaType.schema, config, mediaType.schema.nullable); } } switch (responseType) { case "blob": return "Blob"; case "arraybuffer": return "ArrayBuffer"; case "text": return "string"; default: return "any"; } } __name(getResponseType, "getResponseType"); // ../../shared/src/config/constants.ts var disableLinting = `/* @ts-nocheck */ /* eslint-disable */ /* @noformat */ /* @formatter:off */ `; var authorComment = `/** * Generated by ng-openapi `; var defaultHeaderComment = disableLinting + authorComment; var TYPE_GENERATOR_HEADER_COMMENT = defaultHeaderComment + `* Generated TypeScript interfaces from Swagger specification * Do not edit this file manually */ `; var SERVICE_INDEX_GENERATOR_HEADER_COMMENT = defaultHeaderComment + `* Generated service exports * Do not edit this file manually */ `; var MAIN_INDEX_GENERATOR_HEADER_COMMENT = defaultHeaderComment + `* Entrypoint for the client * Do not edit this file manually */ `; var PROVIDER_GENERATOR_HEADER_COMMENT = defaultHeaderComment + `* Generated provider functions for easy setup * Do not edit this file manually */ `; var HTTP_RESOURCE_GENERATOR_HEADER_COMMENT = /* @__PURE__ */ __name((resourceName) => defaultHeaderComment + `* \`httpResource\` is still an experimental feature - NOT PRODUCTION READY * Generated Angular service for ${resourceName} * Do not edit this file manually */ `, "HTTP_RESOURCE_GENERATOR_HEADER_COMMENT"); var ZOD_PLUGIN_INDEX_GENERATOR_HEADER_COMMENT = defaultHeaderComment + `* Generated Zod Schemas exports * Do not edit this file manually */ `; // ../../../node_modules/js-yaml/dist/js-yaml.mjs function isNothing(subject) { return typeof subject === "undefined" || subject === null; } __name(isNothing, "isNothing"); function isObject(subject) { return typeof subject === "object" && subject !== null; } __name(isObject, "isObject"); function toArray(sequence) { if (Array.isArray(sequence)) return sequence; else if (isNothing(sequence)) return []; return [sequence]; } __name(toArray, "toArray"); function extend(target, source) { var index, length, key, sourceKeys; if (source) { sourceKeys = Object.keys(source); for (index = 0, length = sourceKeys.length; index < length; index += 1) { key = sourceKeys[index]; target[key] = source[key]; } } return target; } __name(extend, "extend"); function repeat(string, count) { var result = "", cycle; for (cycle = 0; cycle < count; cycle += 1) { result += string; } return result; } __name(repeat, "repeat"); function isNegativeZero(number) { return number === 0 && Number.NEGATIVE_INFINITY === 1 / number; } __name(isNegativeZero, "isNegativeZero"); var isNothing_1 = isNothing; var isObject_1 = isObject; var toArray_1 = toArray; var repeat_1 = repeat; var isNegativeZero_1 = isNegativeZero; var extend_1 = extend; var common = { isNothing: isNothing_1, isObject: isObject_1, toArray: toArray_1, repeat: repeat_1, isNegativeZero: isNegativeZero_1, extend: extend_1 }; function formatError(exception2, compact) { var where = "", message = exception2.reason || "(unknown reason)"; if (!exception2.mark) return message; if (exception2.mark.name) { where += 'in "' + exception2.mark.name + '" '; } where += "(" + (exception2.mark.line + 1) + ":" + (exception2.mark.column + 1) + ")"; if (!compact && exception2.mark.snippet) { where += "\n\n" + exception2.mark.snippet; } return message + " " + where; } __name(formatError, "formatError"); function YAMLException$1(reason, mark) { Error.call(this); this.name = "YAMLException"; this.reason = reason; this.mark = mark; this.message = formatError(this, false); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { this.stack = new Error().stack || ""; } } __name(YAMLException$1, "YAMLException$1"); YAMLException$1.prototype = Object.create(Error.prototype); YAMLException$1.prototype.constructor = YAMLException$1; YAMLException$1.prototype.toString = /* @__PURE__ */ __name(function toString(compact) { return this.name + ": " + formatError(this, compact); }, "toString"); var exception = YAMLException$1; function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { var head = ""; var tail = ""; var maxHalfLength = Math.floor(maxLineLength / 2) - 1; if (position - lineStart > maxHalfLength) { head = " ... "; lineStart = position - maxHalfLength + head.length; } if (lineEnd - position > maxHalfLength) { tail = " ..."; lineEnd = position + maxHalfLength - tail.length; } return { str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail, pos: position - lineStart + head.length // relative position }; } __name(getLine, "getLine"); function padStart(string, max) { return common.repeat(" ", max - string.length) + string; } __name(padStart, "padStart"); function makeSnippet(mark, options) { options = Object.create(options || null); if (!mark.buffer) return null; if (!options.maxLength) options.maxLength = 79; if (typeof options.indent !== "number") options.indent = 1; if (typeof options.linesBefore !== "number") options.linesBefore = 3; if (typeof options.linesAfter !== "number") options.linesAfter = 2; var re = /\r?\n|\r|\0/g; var lineStarts = [0]; var lineEnds = []; var match; var foundLineNo = -1; while (match = re.exec(mark.buffer)) { lineEnds.push(match.index); lineStarts.push(match.index + match[0].length); if (mark.position <= match.index && foundLineNo < 0) { foundLineNo = lineStarts.length - 2; } } if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; var result = "", i, line; var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); for (i = 1; i <= options.linesBefore; i++) { if (foundLineNo - i < 0) break; line = getLine( mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength ); result = common.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result; } line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n"; result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n"; for (i = 1; i <= options.linesAfter; i++) { if (foundLineNo + i >= lineEnds.length) break; line = getLine( mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength ); result += common.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line.str + "\n"; } return result.replace(/\n$/, ""); } __name(makeSnippet, "makeSnippet"); var snippet = makeSnippet; var TYPE_CONSTRUCTOR_OPTIONS = [ "kind", "multi", "resolve", "construct", "instanceOf", "predicate", "represent", "representName", "defaultStyle", "styleAliases" ]; var YAML_NODE_KINDS = [ "scalar", "sequence", "mapping" ]; function compileStyleAliases(map2) { var result = {}; if (map2 !== null) { Object.keys(map2).forEach(function(style) { map2[style].forEach(function(alias) { result[String(alias)] = style; }); }); } return result; } __name(compileStyleAliases, "compileStyleAliases"); function Type$1(tag, options) { options = options || {}; Object.keys(options).forEach(function(name) { if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); } }); this.options = options; this.tag = tag; this.kind = options["kind"] || null; this.resolve = options["resolve"] || function() { return true; }; this.construct = options["construct"] || function(data) { return data; }; this.instanceOf = options["instanceOf"] || null; this.predicate = options["predicate"] || null; this.represent = options["represent"] || null; this.representName = options["representName"] || null; this.defaultStyle = options["defaultStyle"] || null; this.multi = options["multi"] || false; this.styleAliases = compileStyleAliases(options["styleAliases"] || null); if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); } } __name(Type$1, "Type$1"); var type = Type$1; function compileList(schema2, name) { var result = []; schema2[name].forEach(function(currentType) { var newIndex = result.length; result.forEach(function(previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { newIndex = previousIndex; } }); result[newIndex] = currentType; }); return result; } __name(compileList, "compileList"); function compileMap() { var result = { scalar: {}, sequence: {}, mapping: {}, fallback: {}, multi: { scalar: [], sequence: [], mapping: [], fallback: [] } }, index, length; function collectType(type2) { if (type2.multi) { result.multi[type2.kind].push(type2); result.multi["fallback"].push(type2); } else { result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2; } } __name(collectType, "collectType"); for (index = 0, length = arguments.length; index < length; index += 1) { arguments[index].forEach(collectType); } return result; } __name(compileMap, "compileMap"); function Schema$1(definition) { return this.extend(definition); } __name(Schema$1, "Schema$1"); Schema$1.prototype.extend = /* @__PURE__ */ __name(function extend2(definition) { var implicit = []; var explicit = []; if (definition instanceof type) { explicit.push(definition); } else if (Array.isArray(definition)) { explicit = explicit.concat(definition); } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { if (definition.implicit) implicit = implicit.concat(definition.implicit); if (definition.explicit) explicit = explicit.concat(definition.explicit); } else { throw new exception("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })"); } implicit.forEach(function(type$1) { if (!(type$1 instanceof type)) { throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); } if (type$1.loadKind && type$1.loadKind !== "scalar") { throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported."); } if (type$1.multi) { throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit."); } }); explicit.forEach(function(type$1) { if (!(type$1 instanceof type)) { throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); } }); var result = Object.create(Schema$1.prototype); result.implicit = (this.implicit || []).concat(implicit); result.explicit = (this.explicit || []).concat(explicit); result.compiledImplicit = compileList(result, "implicit"); result.compiledExplicit = compileList(result, "explicit"); result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); return result; }, "extend"); var schema = Schema$1; var str = new type("tag:yaml.org,2002:str", { kind: "scalar", construct: /* @__PURE__ */ __name(function(data) { return data !== null ? data : ""; }, "construct") }); var seq = new type("tag:yaml.org,2002:seq", { kind: "sequence", construct: /* @__PURE__ */ __name(function(data) { return data !== null ? data : []; }, "construct") }); var map = new type("tag:yaml.org,2002:map", { kind: "mapping", construct: /* @__PURE__ */ __name(function(data) { return data !== null ? data : {}; }, "construct") }); var failsafe = new schema({ explicit: [ str, seq, map ] }); function resolveYamlNull(data) { if (data === null) return true; var max = data.length; return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL"); } __name(resolveYamlNull, "resolveYamlNull"); function constructYamlNull() { return null; } __name(constructYamlNull, "constructYamlNull"); function isNull(object) { return object === null; } __name(isNull, "isNull"); var _null = new type("tag:yaml.org,2002:null", { kind: "scalar", resolve: resolveYamlNull, construct: constructYamlNull, predicate: isNull, represent: { canonical: /* @__PURE__ */ __name(function() { return "~"; }, "canonical"), lowercase: /* @__PURE__ */ __name(function() { return "null"; }, "lowercase"), uppercase: /* @__PURE__ */ __name(function() { return "NULL"; }, "uppercase"), camelcase: /* @__PURE__ */ __name(function() { return "Null"; }, "camelcase"), empty: /* @__PURE__ */ __name(function() { return ""; }, "empty") }, defaultStyle: "lowercase" }); function resolveYamlBoolean(data) { if (data === null) return false; var max = data.length; return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE"); } __name(resolveYamlBoolean, "resolveYamlBoolean"); function constructYamlBoolean(data) { return data === "true" || data === "True" || data === "TRUE"; } __name(constructYamlBoolean, "constructYamlBoolean"); function isBoolean(object) { return Object.prototype.toString.call(object) === "[object Boolean]"; } __name(isBoolean, "isBoolean"); var bool = new type("tag:yaml.org,2002:bool", { kind: "scalar", resolve: resolveYamlBoolean, construct: constructYamlBoolean, predicate: isBoolean, represent: { lowercase: /* @__PURE__ */ __name(function(object) { return object ? "true" : "false"; }, "lowercase"), uppercase: /* @__PURE__ */ __name(function(object) { return object ? "TRUE" : "FALSE"; }, "uppercase"), camelcase: /* @__PURE__ */ __name(function(object) { return object ? "True" : "False"; }, "camelcase") }, defaultStyle: "lowercase" }); function isHexCode(c) { return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102; } __name(isHexCode, "isHexCode"); function isOctCode(c) { return 48 <= c && c <= 55; } __name(isOctCode, "isOctCode"); function isDecCode(c) { return 48 <= c && c <= 57; } __name(isDecCode, "isDecCode"); function resolveYamlInteger(data) { if (data === null) return false; var max = data.length, index = 0, hasDigits = false, ch; if (!max) return false; ch = data[index]; if (ch === "-" || ch === "+") { ch = data[++index]; } if (ch === "0") { if (index + 1 === max) return true; ch = data[++index]; if (ch === "b") { index++; for (; index < max; index++) { ch = data[index]; if (ch === "_") continue; if (ch !== "0" && ch !== "1") return false; hasDigits = true; } return hasDigits && ch !== "_"; } if (ch === "x") { index++; for (; index < max; index++) { ch = data[index]; if (ch === "_") continue; if (!isHexCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== "_"; } if (ch === "o") { index++; for (; index < max; index++) { ch = data[index]; if (ch === "_") continue; if (!isOctCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== "_"; } } if (ch === "_") return false; for (; index < max; index++) { ch = data[index]; if (ch === "_") continue; if (!isDecCode(data.charCodeAt(index))) { return false; } hasDigits = true; } if (!hasDigits || ch === "_") return false; return true; } __name(resolveYamlInteger, "resolveYamlInteger"); function constructYamlInteger(data) { var value = data, sign = 1, ch; if (value.indexOf("_") !== -1) { value = value.replace(/_/g, ""); } ch = value[0]; if (ch === "-" || ch === "+") { if (ch === "-") sign = -1; value = value.slice(1); ch = value[0]; } if (value === "0") return 0; if (ch === "0") { if (value[1] === "b") return sign * parseInt(value.slice(2), 2); if (value[1] === "x") return sign * parseInt(value.slice(2), 16); if (value[1] === "o") return sign * parseInt(value.slice(2), 8); } return sign * parseInt(value, 10); } __name(constructYamlInteger, "constructYamlInteger"); function isInteger(object) { return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common.isNegativeZero(object)); } __name(isInteger, "isInteger"); var int = new type("tag:yaml.org,2002:int", { kind: "scalar", resolve: resolveYamlInteger, construct: constructYamlInteger, predicate: isInteger, represent: { binary: /* @__PURE__ */ __name(function(obj) { return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1); }, "binary"), octal: /* @__PURE__ */ __name(function(obj) { return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1); }, "octal"), decimal: /* @__PURE__ */ __name(function(obj) { return obj.toString(10); }, "decimal"), /* eslint-disable max-len */ hexadecimal: /* @__PURE__ */ __name(function(obj) { return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1); }, "hexadecimal") }, defaultStyle: "decimal", styleAliases: { binary: [2, "bin"], octal: [8, "oct"], decimal: [10, "dec"], hexadecimal: [16, "hex"] } }); var YAML_FLOAT_PATTERN = new RegExp( // 2.5e4, 2.5 and integers "^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$" ); function resolveYamlFloat(data) { if (data === null) return false; if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_` // Probably should update regexp & check speed data[data.length - 1] === "_") { return false; } return true; } __name(resolveYamlFloat, "resolveYamlFloat"); function constructYamlFloat(data) { var value, sign; value = data.replace(/_/g, "").toLowerCase(); sign = value[0] === "-" ? -1 : 1; if ("+-".indexOf(value[0]) >= 0) { value = value.slice(1); } if (value === ".inf") { return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; } else if (value === ".nan") { return NaN; } return sign * parseFloat(value, 10); } __name(constructYamlFloat, "constructYamlFloat"); var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; function representYamlFloat(object, style) { var res; if (isNaN(object)) { switch (style) { case "lowercase": return ".nan"; case "uppercase": return ".NAN"; case "camelcase": return ".NaN"; } } else if (Number.POSITIVE_INFINITY === object) { switch (style) { case "lowercase": return ".inf"; case "uppercase": return ".INF"; case "camelcase": return ".Inf"; } } else if (Number.NEGATIVE_INFINITY === object) { switch (style) { case "lowercase": return "-.inf"; case "uppercase": return "-.INF"; case "camelcase": return "-.Inf"; } } else if (common.isNegativeZero(object)) { return "-0.0"; } res = object.toString(10); return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res; } __name(representYamlFloat, "representYamlFloat"); function isFloat(object) { return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object)); } __name(isFloat, "isFloat"); var float = new type("tag:yaml.org,2002:float", { kind: "scalar", resolve: resolveYamlFloat, construct: constructYamlFloat, predicate: isFloat, represent: representYamlFloat, defaultStyle: "lowercase" }); var json = failsafe.extend({ implicit: [ _null, bool, int, float ] }); var core = json; var YAML_DATE_REGEXP = new RegExp( "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$" ); var YAML_TIMESTAMP_REGEXP = new RegExp( "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$" ); function resolveYamlTimestamp(data) { if (data === null) return false; if (YAML_DATE_REGEXP.exec(data) !== null) return true; if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; return false; } __name(resolveYamlTimestamp, "resolveYamlTimestamp"); function constructYamlTimestamp(data) { var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date; match = YAML_DATE_REGEXP.exec(data); if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); if (match === null) throw new Error("Date resolve error"); year = +match[1]; month = +match[2] - 1; day = +match[3]; if (!match[4]) { return new Date(Date.UTC(year, month, day)); } hour = +match[4]; minute = +match[5]; second = +match[6]; if (match[7]) { fraction = match[7].slice(0, 3); while (fraction.length < 3) { fraction += "0"; } fraction = +fraction; } if (match[9]) { tz_hour = +match[10]; tz_minute = +(match[11] || 0); delta = (tz_hour * 60 + tz_minute) * 6e4; if (match[9] === "-") delta = -delta; } date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); if (delta) date.setTime(date.getTime() - delta); return date; } __name(constructYamlTimestamp, "constructYamlTimestamp"); function representYamlTimestamp(object) { return object.toISOString(); } __name(representYamlTimestamp, "representYamlTimestamp"); var timestamp = new type("tag:yaml.org,2002:timestamp", { kind: "scalar", resolve: resolveYamlTimestamp, construct: constructYamlTimestamp, instanceOf: Date, represent: representYamlTimestamp }); function resolveYamlMerge(data) { return data === "<<" || data === null; } __name(resolveYamlMerge, "resolveYamlMerge"); var merge = new type("tag:yaml.org,2002:merge", { kind: "scalar", resolve: resolveYamlMerge }); var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r"; function resolveYamlBinary(data) { if (data === null) return false; var code, idx, bitlen = 0, max = data.length, map2 = BASE64_MAP; for (idx = 0; idx < max; idx++) { code = map2.indexOf(data.charAt(idx)); if (code > 64) continue; if (code < 0) return false; bitlen += 6; } return bitlen % 8 === 0; } __name(resolveYamlBinary, "resolveYamlBinary"); function constructYamlBinary(data) { var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max = input.length, map2 = BASE64_MAP, bits = 0, result = []; for (idx = 0; idx < max; idx++) { if (idx % 4 === 0 && idx) { result.push(bits >> 16 & 255); result.push(bits >> 8 & 255); result.push(bits & 255); } bits = bits << 6 | map2.indexOf(input.charAt(idx)); } tailbits = max % 4 * 6; if (tailbits === 0) { result.push(bits >> 16 & 255); result.push(bits >> 8 & 255); result.push(bits & 255); } else if (tailbits === 18) { result.push(bits >> 10 & 255); result.push(bits >> 2 & 255); } else if (tailbits === 12) { result.push(bits >> 4 & 255); } return new Uint8Array(result); } __name(constructYamlBinary, "constructYamlBinary"); function representYamlBinary(object) { var result = "", bits = 0, idx, tail, max = object.length, map2 = BASE64_MAP; for (idx = 0; idx < max; idx++) { if (idx % 3 === 0 && idx) { result += map2[bits >> 18 & 63]; result += map2[bits >> 12 & 63]; result += map2[bits >> 6 & 63]; result += map2[bits & 63]; } bits = (bits << 8) + object[idx]; } tail = max % 3; if (tail === 0) { result += map2[bits >> 18 & 63]; result += map2[bits >> 12 & 63]; result += map2[bits >> 6 & 63]; result += map2[bits & 63]; } else if (tail === 2) { result += map2[bits >> 10 & 63]; result += map2[bits >> 4 & 63]; result += map2[bits << 2 & 63]; result += map2[64]; } else if (tail === 1) { result += map2[bits >> 2 & 63]; result += map2[bits << 4 & 63]; result += map2[64]; result += map2[64]; } return result; } __name(representYamlBinary, "representYamlBinary"); function isBinary(obj) { return Object.prototype.toString.call(obj) === "[object Uint8Array]"; } __name(isBinary, "isBinary"); var binary = new type("tag:yaml.org,2002:binary", { kind: "scalar", resolve: resolveYamlBinary, construct: constructYamlBinary, predicate: isBinary, represent: representYamlBinary }); var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; var _toString$2 = Object.prototype.toString; function resolveYamlOmap(data) { if (data === null) return true; var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data; for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; pairHasKey = false; if (_toString$2.call(pair) !== "[object Object]") return false; for (pairKey in pair) { if (_hasOwnProperty$3.call(pair, pairKey)) { if (!pairHasKey) pairHasKey = true; else return false; } } if (!pairHasKey) return false; if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); else return false; } return true; } __name(resolveYamlOmap, "resolveYamlOmap"); function constructYamlOmap(data) { return data !== null ? data : []; } __name(constructYamlOmap, "constructYamlOmap"); var omap = new type("tag:yaml.org,2002:omap", { kind: "sequence", resolve: resolveYamlOmap, construct: constructYamlOmap }); var _toString$1 = Object.prototype.toString; function resolveYamlPairs(data) { if (data === null) return true; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; if (_toString$1.call(pair) !== "[object Object]") return false; keys = Object.keys(pair); if (keys.length !== 1) return false; result[index] = [keys[0], pair[keys[0]]]; } return true; } __name(resolveYamlPairs, "resolveYamlPairs"); function constructYamlPairs(data) { if (data === null) return []; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; keys = Object.keys(pair); result[index] = [keys[0], pair[keys[0]]]; } return result; } __name(constructYamlPairs, "constructYamlPairs"); var pairs = new type("tag:yaml.org,2002:pairs", { kind: "sequence", resolve: resolveYamlPairs, construct: constructYamlPairs }); var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; function resolveYamlSet(data) { if (data === null) return true; var key, object = data; for (key in object) { if (_hasOwnProperty$2.call(object, key)) { if (object[key] !== null) return false; } } return true; } __name(resolveYamlSet, "resolveYamlSet"); function constructYamlSet(data) { return data !== null ? data : {}; } __name(constructYamlSet, "constructYamlSet"); var set = new type("tag:yaml.org,2002:set", { kind: "mapping", resolve: resolveYamlSet, construct: constructYamlSet }); var _default = core.extend({ implicit: [ timestamp, merge ], explicit: [ binary, omap, pairs, set ] }); var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; var CONTEXT_FLOW_IN = 1; var CONTEXT_FLOW_OUT = 2; var CONTEXT_BLOCK_IN = 3; var CONTEXT_BLOCK_OUT = 4; var CHOMPING_CLIP = 1; var CHOMPING_STRIP = 2; var CHOMPING_KEEP = 3; var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; function _class(obj) { return Object.prototype.toString.call(obj); } __name(_class, "_class"); function is_EOL(c) { return c === 10 || c === 13; } __name(is_EOL, "is_EOL"); function is_WHITE_SPACE(c) { return c === 9 || c === 32; } __name(is_WHITE_SPACE, "is_WHITE_SPACE"); function is_WS_OR_EOL(c) { return c === 9 || c === 32 || c === 10 || c === 13; } __name(is_WS_OR_EOL, "is_WS_OR_EOL"); function is_FLOW_INDICATOR(c) { return c === 44 || c === 91 || c === 93 || c === 123 || c === 125; } __name(is_FLOW_INDICATOR, "is_FLOW_INDICATOR"); function fromHexCode(c) { var lc; if (48 <= c && c <= 57) { return c - 48; } lc = c | 32; if (97 <= lc && lc <= 102) { return lc - 97 + 10; } return -1; } __name(fromHexCode, "fromHexCode"); function escapedHexLen(c) { if (c === 120) { return 2; } if (c === 117) { return 4; } if (c === 85) { return 8; } return 0; } __name(escapedHexLen, "escapedHexLen"); function fromDecimalCode(c) { if (48 <= c && c <= 57) { return c - 48; } return -1; } __name(fromDecimalCode, "fromDecimalCode"); function simpleEscapeSequence(c) { return c === 48 ? "\0" : c === 97 ? "\x07" : c === 98 ? "\b" : c === 116 ? " " : c === 9 ? " " : c === 110 ? "\n" : c === 118 ? "\v" : c === 102 ? "\f" : c === 114 ? "\r" : c === 101 ? "\x1B" : c === 32 ? " " : c === 34 ? '"' : c === 47 ? "/" : c === 92 ? "\\" : c === 78 ? "\x85" : c === 95 ? "\xA0" : c === 76 ? "\u2028" : c === 80 ? "\u2029" : ""; } __name(simpleEscapeSequence, "simpleEscapeSequence"); function charFromCodepoint(c) { if (c <= 65535) { return String.fromCharCode(c); } return String.fromCharCode( (c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320 ); } __name(charFromCodepoint, "charFromCodepoint"); var simpleEscapeCheck = new Array(256); var simpleEscapeMap = new Array(256); for (i = 0; i < 256; i++) { simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; simpleEscapeMap[i] = simpleEscapeSequence(i); } var i; function State$1(input, options) { this.input = input; this.filename = options["filename"] || null; this.schema = options["schema"] || _default; this.onWarning = options["onWarning"] || null; this.legacy = options["legacy"] || false; this.json = options["json"] || false; this.listener = options["listener"] || null; this.implicitTypes = this.schema.compiledImplicit; this.typeMap = this.schema.compiledTypeMap; this.length = input.length; this.position = 0; this.line = 0; this.lineStart = 0; this.lineIndent = 0; this.firstTabInLine = -1; this.documents = []; } __name(State$1, "State$1"); function generateError(state, message) { var mark = { name: state.filename, buffer: state.input.slice(0, -1), // omit trailing \0 position: state.position, line: state.line, column: state.position - state.lineStart }; mark.snippet = snippet(mark); return new exception(message, mark); } __name(generateError, "generateError"); function throwError(state, message) { throw generateError(state, message); } __name(throwError, "throwError"); function throwWarning(state, message) { if (state.onWarning) { state.onWarning.call(null, generateError(state, message)); } } __name(throwWarning, "throwWarning"); var directiveHandlers = { YAML: /* @__PURE__ */ __name(function handleYamlDirective(state, name, args) { var match, major, minor; if (state.version !== null) { throwError(state, "duplication of %YAML directive"); } if (args.length !== 1) { throwError(state, "YAML directive accepts exactly one argument"); } match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); if (match === null) { throwError(state, "ill-formed argument of the YAML directive"); } major = parseInt(match[1], 10); minor = parseInt(match[2], 10); if (major !== 1) { throwError(state, "unacceptable YAML version of the document"); } state.version = args[0]; state.checkLineBreaks = minor < 2; if (minor !== 1 && minor !== 2) { throwWarning(state, "unsupported YAML version of the document"); } }, "handleYamlDirective"), TAG: /* @__PURE__ */ __name(function handleTagDirective(state, name, args) { var handle, prefix; if (args.length !== 2) { throwError(state, "TAG directive accepts exactly two arguments"); } handle = args[0]; prefix = args[1]; if (!PATTERN_TAG_HANDLE.test(handle)) { throwError(state, "ill-formed tag handle (first argument) of the TAG directive"); } if (_hasOwnProperty$1.call(state.tagMap, handle)) { throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); } if (!PATTERN_TAG_URI.test(prefix)) { throwError(state, "ill-formed tag prefix (second argument) of the TAG directive"); } try { prefix = decodeURIComponent(prefix); } catch (err) { throwError(state, "tag prefix is malformed: " + prefix); } state.tagMap[handle] = prefix; }, "handleTagDirective") }; function captureSegment(state, start, end, checkJson) { var _position, _length, _character, _result; if (start < end) { _result = state.input.slice(start, end); if (checkJson) { for (_position = 0, _length = _result.length; _position < _length; _position += 1) { _character = _result.charCodeAt(_position); if (!(_character === 9 || 32 <= _character && _character <= 1114111)) { throwError(state, "expected valid JSON character"); } } } else if (PATTERN_NON_PRINTABLE.test(_result)) { throwError(state, "the stream contains non-printable characters"); } state.result += _result; } } __name(captureSegment, "captureSegment"); function mergeMappings(state, destination, source, overridableKeys) { var sourceKeys, key, index, quantity; if (!common.isObject(source)) { throwError(state, "cannot merge mappings; the provided source object is unacceptable"); } sourceKeys = Object.keys(source); for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { key = sourceKeys[index]; if (!_hasOwnProperty$1.call(destination, key)) { destination[key] = source[key]; overridableKeys[key] = true; } } } __name(mergeMappings, "mergeMappings"); function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) { var index, quantity; if (Array.isArray(keyNode)) { keyNode = Array.prototype.slice.call(keyNode); for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { if (Array.isArray(keyNode[index])) { throwError(state, "nested arrays are not supported inside keys"); } if (typeof keyNode === "object" && _class(keyNode[index]) === "[object Object]") { keyNode[index] = "[object Object]"; } } } if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") { keyNode = "[object Object]"; } keyNode = String(keyNode); if (_result === null) { _result = {}; } if (keyTag === "tag:yaml.org,2002:merge") { if (Array.isArray(valueNode)) { for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { mergeMappings(state, _result, valueNode[index], overridableKeys); } } else { mergeMappings(state, _result, valueNode, overridableKeys); } } else { if (!state.json && !_hasOwnProperty$1.call(overridableKeys, keyNode) && _hasOwnProperty$1.call(_result, keyNode)) { state.line = startLine || state.line; state.lineStart = startLineStart || state.lineStart; state.position = startPos || state.position; throwError(state, "duplicated mapping key"); } if (keyNode === "__proto__") { Object.defineProperty(_result, keyNode, { configurable: true, enumerable: true, writable: true, value: valueNode }); } else { _result[keyNode] = valueNode; } delete overridableKeys[keyNode]; } return _result; } __name(storeMappingPair, "storeMappingPair"); function readLineBreak(state) { var ch; ch = state.input.charCodeAt(state.position); if (ch === 10) { state.position++; } else if (ch === 13) { state.position++; if (state.input.charCodeAt(state.position) === 10) { state.position++; } } else { throwError(state, "a line break is expected"); } state.line += 1; state.lineStart = state.position; state.firstTabInLine = -1; } __name(readLineBreak, "readLineBreak"); function skipSeparationSpace(state, allowComments, checkIndent) { var lineBreaks = 0, ch = state.input.charCodeAt(state.position); while (ch !== 0) { while (is_WHITE_SPACE(ch)) { if (ch === 9 && state.firstTabInLine === -1) { state.firstTabInLine = state.position; } ch = state.input.charCodeAt(++state.position); } if (allowComments && ch === 35) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 10 && ch !== 13 && ch !== 0); } if (is_EOL(ch)) { readLineBreak(state); ch = state.input.charCodeAt(state.position); lineBreaks++; state.lineIndent = 0; while (ch === 32) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } } else { break; } } if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { throwWarning(state, "deficient indentation"); } return lineBreaks; } __name(skipSeparationSpace, "skipSeparationSpace"); function testDocumentSeparator(state) { var _position = state.position, ch; ch = state.input.charCodeAt(_position); if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { _position += 3; ch = state.input.charCodeAt(_position); if (ch === 0 || is_WS_OR_EOL(ch)) { return true; } } return false; } __name(testDocumentSeparator, "testDocumentSeparator"); function writeFoldedLines(state, count) { if (count === 1) { state.result += " "; } else if (count > 1) { state.result += common.repeat("\n", count - 1); } } __name(writeFoldedLines, "writeFoldedLines"); function readPlainScalar(state, nodeIndent, withinFlowCollection) { var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch; ch = state.input.charCodeAt(state.position); if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) { return false; } if (ch === 63 || ch === 45) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { return false; } } state.kind = "scalar"; state.result = ""; captureStart = captureEnd = state.position; hasPendingContent = false; while (ch !== 0) { if (ch === 58) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { break; } } else if (ch === 35) { preceding = state.input.charCodeAt(state.position - 1); if (is_WS_OR_EOL(preceding)) { break; } } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection &&