UNPKG

json-schema-faker

Version:
1,333 lines (1,332 loc) 237 kB
var JSONSchemaFaker = (() => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/shared.js var shared_exports = {}; __export(shared_exports, { JSONSchemaFaker: () => JSONSchemaFaker, default: () => lib_default, setDependencies: () => setDependencies }); function optionAPI(nameOrOptionMap, optionalValue) { if (typeof nameOrOptionMap === "string") { if (typeof optionalValue !== "undefined") { return registry.register(nameOrOptionMap, optionalValue); } return registry.get(nameOrOptionMap); } return registry.registerMany(nameOrOptionMap); } function getRandomInteger(min, max) { min = typeof min === "undefined" ? constants_default.MIN_INTEGER : min; max = typeof max === "undefined" ? constants_default.MAX_INTEGER : max; return Math.floor(option_default("random")() * (max - min + 1)) + min; } function _randexp(value) { import_randexp.default.prototype.max = option_default("defaultRandExpMax"); import_randexp.default.prototype.randInt = (a, b) => a + Math.floor(option_default("random")() * (1 + (b - a))); const re = new import_randexp.default(value); return re.gen(); } function pick(collection) { return collection[Math.floor(option_default("random")() * collection.length)]; } function shuffle(collection) { let tmp; let key; let length = collection.length; const copy = collection.slice(); for (; length > 0; ) { key = Math.floor(option_default("random")() * length); length -= 1; tmp = copy[length]; copy[length] = copy[key]; copy[key] = tmp; } return copy; } function getRandom(min, max) { return option_default("random")() * (max - min) + min; } function number(min, max, defMin, defMax, hasPrecision = false) { defMin = typeof defMin === "undefined" ? constants_default.MIN_NUMBER : defMin; defMax = typeof defMax === "undefined" ? constants_default.MAX_NUMBER : defMax; min = typeof min === "undefined" ? defMin : min; max = typeof max === "undefined" ? defMax : max; if (max < min) { max += min; } if (hasPrecision) { return getRandom(min, max); } return getRandomInteger(min, max); } function by(type) { switch (type) { case "seconds": return number(0, 60) * 60; case "minutes": return number(15, 50) * 612; case "hours": return number(12, 72) * 36123; case "days": return number(7, 30) * 86412345; case "weeks": return number(4, 52) * 604812345; case "months": return number(2, 13) * 2592012345; case "years": return number(1, 20) * 31104012345; default: break; } } function date(step) { if (step) { return by(step); } let earliest = option_default("minDateTime"); let latest = option_default("maxDateTime"); if (typeof earliest === "string") { earliest = new Date(earliest); } if (typeof latest === "string") { latest = new Date(latest); } const now = (/* @__PURE__ */ new Date()).getTime(); if (typeof earliest === "number") { earliest = new Date(now + earliest); } if (typeof latest === "number") { latest = new Date(now + latest); } return new Date(getRandom(earliest.getTime(), latest.getTime())); } function getLocalRef(obj, path, refs) { path = decodeURIComponent(path); if (refs && refs[path]) return clone(refs[path]); const keyElements = path.replace("#/", "/").split("/"); let schema = obj.$ref && refs && refs[obj.$ref] || obj; if (!schema && !keyElements[0]) { keyElements[0] = obj.$ref.split("#/")[0]; } if (refs && path.includes("#/") && refs[keyElements[0]]) { schema = refs[keyElements.shift()]; } if (!keyElements[0]) keyElements.shift(); while (schema && keyElements.length > 0) { const prop = keyElements.shift(); if (!schema[prop]) { throw new Error(`Prop not found: ${prop} (${path})`); } schema = schema[prop]; } return schema; } function isNumeric(value) { return typeof value === "string" && RE_NUMERIC.test(value); } function isScalar(value) { return ["number", "boolean"].includes(typeof value); } function hasProperties(obj, ...properties) { return properties.filter((key) => { return typeof obj[key] !== "undefined"; }).length > 0; } function clampDate(value) { if (value.includes(" ")) { return new Date(value).toISOString().substr(0, 10); } let [year, month, day] = value.split("T")[0].split("-"); month = `0${Math.max(1, Math.min(12, month))}`.slice(-2); day = `0${Math.max(1, Math.min(31, day))}`.slice(-2); return `${year}-${month}-${day}`; } function clampDateTime(value) { if (value.includes(" ")) { return new Date(value).toISOString().substr(0, 10); } const [datePart, timePart] = value.split("T"); let [year, month, day] = datePart.split("-"); let [hour, minute, second] = timePart.substr(0, 8).split(":"); month = `0${Math.max(1, Math.min(12, month))}`.slice(-2); day = `0${Math.max(1, Math.min(31, day))}`.slice(-2); hour = `0${Math.max(1, Math.min(23, hour))}`.slice(-2); minute = `0${Math.max(1, Math.min(59, minute))}`.slice(-2); second = `0${Math.max(1, Math.min(59, second))}`.slice(-2); return `${year}-${month}-${day}T${hour}:${minute}:${second}.000Z`; } function typecast(type, schema, callback) { const params = {}; switch (type || schema.type) { case "integer": case "number": if (typeof schema.minimum !== "undefined") { params.minimum = schema.minimum; } if (typeof schema.maximum !== "undefined") { params.maximum = schema.maximum; } if (schema.enum) { let min = Math.max(params.minimum || 0, 0); let max = Math.min(params.maximum || Infinity, Infinity); if (schema.exclusiveMinimum && min === schema.minimum) { min += schema.multipleOf || 1; } if (schema.exclusiveMaximum && max === schema.maximum) { max -= schema.multipleOf || 1; } if (min || max !== Infinity) { schema.enum = schema.enum.filter((x) => { if (x >= min && x <= max) { return true; } return false; }); } } break; case "string": { params.minLength = option_default("minLength") || 0; params.maxLength = option_default("maxLength") || Number.MAX_SAFE_INTEGER; if (typeof schema.minLength !== "undefined") { params.minLength = Math.max(params.minLength, schema.minLength); } if (typeof schema.maxLength !== "undefined") { params.maxLength = Math.min(params.maxLength, schema.maxLength); } break; } default: break; } let value = callback(params); if (value === null || value === void 0) { return null; } switch (type || schema.type) { case "number": value = isNumeric(value) ? parseFloat(value) : value; break; case "integer": value = isNumeric(value) ? parseInt(value, 10) : value; break; case "boolean": value = !!value; break; case "string": { if (isScalar(value)) { return value; } value = String(value); const min = Math.max(params.minLength || 0, 0); const max = Math.min(params.maxLength || Infinity, Infinity); let prev; let noChangeCount = 0; while (value.length < min) { prev = value; if (!schema.pattern) { value += `${random_default.pick([" ", "/", "_", "-", "+", "=", "@", "^"])}${value}`; } else { value += random_default.randexp(schema.pattern); } if (value === prev) { noChangeCount += 1; if (noChangeCount === 3) { break; } } else { noChangeCount = 0; } } if (value.length > max) { value = value.substr(0, max); const pattern = schema.pattern ? new RegExp(schema.pattern) : null; if (pattern && !pattern.test(value)) { let temp = value; const maxRetries = option_default("maxRegexRetry"); const minLength = Math.max(value.length - maxRetries, min); while (temp.length > minLength && !pattern.test(temp)) { temp = temp.slice(0, -1); if (pattern.test(temp)) { value = temp; } } } } switch (schema.format) { case "date-time": case "datetime": value = new Date(clampDateTime(value)).toISOString().replace(/([0-9])0+Z$/, "$1Z"); break; case "full-date": case "date": value = new Date(clampDate(value)).toISOString().substr(0, 10); break; case "time": value = (/* @__PURE__ */ new Date(`1969-01-01 ${value}`)).toISOString().substr(11); break; default: break; } break; } default: break; } return value; } function merge(a, b) { Object.keys(b).forEach((key) => { if (typeof b[key] !== "object" || b[key] === null) { a[key] = b[key]; } else if (Array.isArray(b[key])) { a[key] = a[key] || []; b[key].forEach((value, i) => { if (a.type === "array" && b.type === "array") { a[key][i] = merge(a[key][i] || {}, value, true); } else if (Array.isArray(a[key]) && a[key].indexOf(value) === -1) { a[key].push(value); } }); } else if (typeof a[key] !== "object" || a[key] === null || Array.isArray(a[key])) { a[key] = merge({}, b[key]); } else { a[key] = merge(a[key], b[key]); } }); return a; } function clone(obj, cache = /* @__PURE__ */ new Map()) { if (!obj || typeof obj !== "object") { return obj; } if (cache.has(obj)) { return cache.get(obj); } if (Array.isArray(obj)) { const arr = []; cache.set(obj, arr); arr.push(...obj.map((x) => clone(x, cache))); return arr; } const clonedObj = {}; cache.set(obj, clonedObj); return Object.keys(obj).reduce((prev, cur) => { prev[cur] = clone(obj[cur], cache); return prev; }, clonedObj); } function short(schema) { const s = JSON.stringify(schema); const l = JSON.stringify(schema, null, 2); return s.length > 400 ? `${l.substr(0, 400)}...` : l; } function anyValue() { return random_default.pick([ false, true, null, -1, NaN, Math.PI, Infinity, void 0, [], {}, // FIXME: use built-in random? Math.random(), Math.random().toString(36).substr(2) ]); } function hasValue(schema, value) { if (schema.enum) return schema.enum.includes(value); if (schema.const) return schema.const === value; } function notValue(schema, parent) { const copy = merge({}, parent); if (typeof schema.minimum !== "undefined") { copy.maximum = schema.minimum; copy.exclusiveMaximum = true; } if (typeof schema.maximum !== "undefined") { copy.minimum = schema.maximum > copy.maximum ? 0 : schema.maximum; copy.exclusiveMinimum = true; } if (typeof schema.minLength !== "undefined") { copy.maxLength = schema.minLength; } if (typeof schema.maxLength !== "undefined") { copy.minLength = schema.maxLength > copy.maxLength ? 0 : schema.maxLength; } if (schema.type) { copy.type = random_default.pick(constants_default.SCALAR_TYPES.filter((x) => { const types2 = Array.isArray(schema.type) ? schema.type : [schema.type]; return types2.every((type) => { if (x === "number" || x === "integer") { return type !== "number" && type !== "integer"; } return x !== type; }); })); } else if (schema.enum) { let value; do { value = anyValue(); } while (schema.enum.indexOf(value) !== -1); copy.enum = [value]; } if (schema.required && copy.properties) { schema.required.forEach((prop) => { delete copy.properties[prop]; }); } return copy; } function validateValueForSchema(value, schema) { const schemaHasMin = schema.minimum !== void 0; const schemaHasMax = schema.maximum !== void 0; return (schemaHasMin || schemaHasMax) && (!schemaHasMin || value >= schema.minimum) && (!schemaHasMax || value <= schema.maximum); } function validate(value, schemas) { return !schemas.every((schema) => validateValueForSchema(value, schema)); } function validateValueForOneOf(value, oneOf) { const validCount = oneOf.reduce((count, schema) => count + (validateValueForSchema(value, schema) ? 1 : 0), 0); return validCount === 1; } function isKey(prop) { return ["enum", "const", "default", "examples", "required", "definitions", "items", "properties"].includes(prop); } function omitProps(obj, props) { return Object.keys(obj).filter((key) => !props.includes(key)).reduce((copy, k) => { if (Array.isArray(obj[k])) { copy[k] = obj[k].slice(); } else { copy[k] = obj[k] instanceof Object ? merge({}, obj[k]) : obj[k]; } return copy; }, {}); } function template(value, schema) { if (Array.isArray(value)) { return value.map((x) => template(x, schema)); } if (typeof value === "string") { value = value.replace(/#\{([\w.-]+)\}/g, (_, $1) => schema[$1]); } return value; } function isEmpty(value) { return Object.prototype.toString.call(value) === "[object Object]" && !Object.keys(value).length; } function shouldClean(key, schema) { schema = schema.items || schema; const alwaysFakeOptionals = option_default("alwaysFakeOptionals"); const isRequired = Array.isArray(schema.required) && schema.required.includes(key) || alwaysFakeOptionals; const wasCleaned = typeof schema.thunk === "function" || schema.additionalProperties && typeof schema.additionalProperties.thunk === "function"; return !isRequired && !wasCleaned; } function clean(obj, schema, isArray = false) { if (!obj || typeof obj !== "object") { return obj; } if (Array.isArray(obj)) { return obj.map((value) => clean(value, schema == null ? void 0 : schema.items, true)).filter((value) => typeof value !== "undefined"); } Object.keys(obj).forEach((k) => { if (isEmpty(obj[k])) { if (shouldClean(k, schema)) { delete obj[k]; } } else { let subSchema = schema; if (schema && schema.properties && schema.properties[k]) { subSchema = schema.properties[k]; } const value = clean(obj[k], subSchema); if (!isEmpty(value)) { obj[k] = value; } } if (typeof obj[k] === "undefined") { delete obj[k]; } }); if (!Object.keys(obj).length && isArray) { return void 0; } return obj; } function proxy(gen) { return (value, schema, property, rootSchema) => { let fn = value; let args = []; if (typeof value === "object") { fn = Object.keys(value)[0]; if (Array.isArray(value[fn])) { args = value[fn]; } else { args.push(value[fn]); } } const props = fn.split("."); let ctx = gen(); while (props.length > 1) { ctx = ctx[props.shift()]; } value = typeof ctx === "object" ? ctx[props[0]] : ctx; if (typeof value === "function") { value = value.apply(ctx, args.map((x) => utils_default.template(x, rootSchema))); } if (Object.prototype.toString.call(value) === "[object Object]") { Object.keys(value).forEach((key) => { if (typeof value[key] === "function") { throw new Error(`Cannot resolve value for '${property}: ${fn}', given: ${value}`); } }); } return value; }; } function formatAPI(nameOrFormatMap, callback) { if (typeof nameOrFormatMap === "undefined") { return registry2.list(); } if (typeof nameOrFormatMap === "string") { if (typeof callback === "function") { registry2.register(nameOrFormatMap, callback); } else if (callback === null || callback === false) { registry2.unregister(nameOrFormatMap); } else { return registry2.get(nameOrFormatMap); } } else { registry2.registerMany(nameOrFormatMap); } } function matchesType(obj, lastElementInPath, inferredTypeProperties) { return Object.keys(obj).filter((prop) => { const isSubschema = subschemaProperties.indexOf(lastElementInPath) > -1; const inferredPropertyFound = inferredTypeProperties.indexOf(prop) > -1; if (inferredPropertyFound && !isSubschema) { return true; } return false; }).length > 0; } function inferType(obj, schemaPath) { const keys = Object.keys(inferredProperties); for (let i = 0; i < keys.length; i += 1) { const typeName = keys[i]; const lastElementInPath = schemaPath[schemaPath.length - 1]; if (matchesType(obj, lastElementInPath, inferredProperties[typeName])) { return typeName; } } } function booleanGenerator() { return option_default("random")() > 0.5; } function nullGenerator() { return null; } function unique(path, items, value, sample, resolve2, traverseCallback) { const tmp = []; const seen = []; function walk(obj) { const json = JSON.stringify(obj.value); if (seen.indexOf(json) === -1) { seen.push(json); tmp.push(obj); return true; } return false; } items.forEach(walk); let limit = 100; while (tmp.length !== items.length) { if (!walk(traverseCallback(value.items || sample, path, resolve2))) { limit -= 1; } if (!limit) { break; } } return tmp; } function arrayType(value, path, resolve2, traverseCallback) { const items = []; if (!(value.items || value.additionalItems)) { if (utils_default.hasProperties(value, "minItems", "maxItems", "uniqueItems")) { if (value.minItems !== 0 || value.maxItems !== 0) { throw new error_default(`missing items for ${utils_default.short(value)}`, path); } } return items; } if (Array.isArray(value.items)) { return value.items.map((item, key) => { const itemSubpath = path.concat(["items", key]); return traverseCallback(item, itemSubpath, resolve2); }); } let minItems = value.minItems; let maxItems = value.maxItems; const defaultMinItems = option_default("minItems"); const defaultMaxItems = option_default("maxItems"); if (defaultMinItems) { minItems = typeof minItems === "undefined" ? defaultMinItems : Math.min(defaultMinItems, minItems); } if (defaultMaxItems) { maxItems = typeof maxItems === "undefined" ? defaultMaxItems : Math.min(defaultMaxItems, maxItems); if (maxItems && maxItems > defaultMaxItems) { maxItems = defaultMaxItems; } if (minItems && minItems > defaultMaxItems) { minItems = maxItems; } } const optionalsProbability = option_default("alwaysFakeOptionals") === true ? 1 : option_default("optionalsProbability"); const fixedProbabilities = option_default("alwaysFakeOptionals") || option_default("fixedProbabilities") || false; let length = random_default.number(minItems, maxItems, 0, 5); if (optionalsProbability !== null) { length = Math.max(fixedProbabilities ? Math.round((maxItems || length) * optionalsProbability) : Math.abs(random_default.number(minItems, maxItems) * optionalsProbability), minItems || 0); } const sample = typeof value.additionalItems === "object" ? value.additionalItems : {}; for (let current = items.length; current < length; current += 1) { const itemSubpath = path.concat(["items", current]); const element = traverseCallback(value.items || sample, itemSubpath, resolve2); items.push(element); } if (value.contains && length > 0) { const idx = random_default.number(0, length - 1); items[idx] = traverseCallback(value.contains, path.concat(["items", idx]), resolve2); } if (value.uniqueItems) { return unique(path.concat(["items"]), items, value, sample, resolve2, traverseCallback); } return items; } function numberType(value) { let min = typeof value.minimum === "undefined" || value.minimum === -Number.MAX_VALUE ? constants_default.MIN_INTEGER : value.minimum; let max = typeof value.maximum === "undefined" || value.maximum === Number.MAX_VALUE ? constants_default.MAX_INTEGER : value.maximum; if (min > max) { max = Number.MAX_SAFE_INTEGER; } const multipleOf = value.multipleOf; const decimals = multipleOf && String(multipleOf).match(/e-(\d)|\.(\d+)$/); if (decimals) { const number2 = (Math.random() * random_default.number(0, 10) + 1) * multipleOf; const truncate = decimals[1] || decimals[2].length; const result = parseFloat(number2.toFixed(truncate)); const base = random_default.number(min, max - 1); if (!String(result).includes(".")) { return (base + result).toExponential(); } return base + result; } if (multipleOf) { max = Math.floor(max / multipleOf) * multipleOf; min = Math.ceil(min / multipleOf) * multipleOf; } if (value.exclusiveMinimum && min === value.minimum) { min += multipleOf || 1; } if (value.exclusiveMaximum && max === value.maximum) { max -= multipleOf || 1; } if (min > max) { return NaN; } if (multipleOf) { let base = random_default.number(Math.floor(min / multipleOf), Math.floor(max / multipleOf)) * multipleOf; while (base < min) { base += multipleOf; } return base; } return random_default.number(min, max, void 0, void 0, value.type !== "integer"); } function integerType(value) { return Math.floor(number_default({ ...value })); } function wordsGenerator(length) { const words = random_default.shuffle(LIPSUM_WORDS); return words.slice(0, length); } function objectType(value, path, resolve2, traverseCallback) { const props = {}; const properties = value.properties || {}; const patternProperties = value.patternProperties || {}; const requiredProperties = typeof value.required === "boolean" ? [] : (value.required || []).slice(); const allowsAdditional = value.additionalProperties !== false; const propertyKeys = Object.keys(properties); const patternPropertyKeys = Object.keys(patternProperties); const optionalProperties = propertyKeys.concat(patternPropertyKeys).reduce((_response, _key) => { if (requiredProperties.indexOf(_key) === -1) _response.push(_key); return _response; }, []); const allProperties = requiredProperties.concat(optionalProperties); const additionalProperties = allowsAdditional ? value.additionalProperties === true ? anyType : value.additionalProperties : value.additionalProperties; if (!allowsAdditional && propertyKeys.length === 0 && patternPropertyKeys.length === 0 && utils_default.hasProperties(value, "minProperties", "maxProperties", "dependencies", "required")) { return null; } if (option_default("requiredOnly") === true) { requiredProperties.forEach((key) => { if (properties[key]) { props[key] = properties[key]; } }); return traverseCallback(props, path.concat(["properties"]), resolve2, value); } const optionalsProbability = option_default("alwaysFakeOptionals") === true ? 1 : option_default("optionalsProbability"); const fixedProbabilities = option_default("alwaysFakeOptionals") || option_default("fixedProbabilities") || false; const ignoreProperties = option_default("ignoreProperties") || []; const reuseProps = option_default("reuseProperties"); const fillProps = option_default("fillProperties"); const max = value.maxProperties || allProperties.length + (allowsAdditional ? random_default.number(1, 5) : 0); let min = Math.max(value.minProperties || 0, requiredProperties.length); let neededExtras = Math.max(0, allProperties.length - min); if (allProperties.length === 1 && !requiredProperties.length) { min = Math.max(random_default.number(fillProps ? 1 : 0, max), min); } if (optionalsProbability !== null) { if (fixedProbabilities === true) { neededExtras = Math.round(min - requiredProperties.length + optionalsProbability * (allProperties.length - min)); } else { neededExtras = random_default.number(min - requiredProperties.length, optionalsProbability * (allProperties.length - min)); } } const extraPropertiesRandomOrder = random_default.shuffle(optionalProperties).slice(0, neededExtras); const extraProperties = optionalProperties.filter((_item) => { return extraPropertiesRandomOrder.indexOf(_item) !== -1; }); const _limit = optionalsProbability !== null || requiredProperties.length === max ? max : random_default.number(0, max); const _props = requiredProperties.concat(random_default.shuffle(extraProperties).slice(0, _limit)).slice(0, max); const _defns = []; const _deps = []; if (value.dependencies) { Object.keys(value.dependencies).forEach((prop) => { const _required = value.dependencies[prop]; if (_props.indexOf(prop) !== -1) { if (Array.isArray(_required)) { _required.forEach((sub) => { if (_props.indexOf(sub) === -1) { _props.push(sub); } }); } else if (Array.isArray(_required.oneOf || _required.anyOf)) { const values = _required.oneOf || _required.anyOf; _deps.push({ prop, values }); } else { _defns.push(_required); } } }); if (_defns.length) { delete value.dependencies; return traverseCallback({ allOf: _defns.concat(value) }, path.concat(["properties"]), resolve2, value); } } const skipped = []; const missing = []; _props.forEach((key) => { if (properties[key] && ["{}", "true"].includes(JSON.stringify(properties[key].not))) { return; } for (let i = 0; i < ignoreProperties.length; i += 1) { if (ignoreProperties[i] instanceof RegExp && ignoreProperties[i].test(key) || typeof ignoreProperties[i] === "string" && ignoreProperties[i] === key || typeof ignoreProperties[i] === "function" && ignoreProperties[i](properties[key], key)) { skipped.push(key); return; } } if (additionalProperties === false) { if (requiredProperties.indexOf(key) !== -1) { props[key] = properties[key]; } } if (properties[key]) { props[key] = properties[key]; } let found; patternPropertyKeys.forEach((_key) => { if (key.match(new RegExp(_key))) { found = true; if (props[key]) { utils_default.merge(props[key], patternProperties[_key]); } else { props[random_default.randexp(key)] = patternProperties[_key]; } } }); if (!found) { const subschema = patternProperties[key] || additionalProperties; if (subschema && additionalProperties !== false) { props[patternProperties[key] ? random_default.randexp(key) : key] = properties[key] || subschema; } else { missing.push(key); } } }); let current = Object.keys(props).length + (fillProps ? 0 : skipped.length); const hash = (suffix) => random_default.randexp(`_?[_a-f\\d]{1,3}${suffix ? "\\$?" : ""}`); function get(from) { let one; do { if (!from.length) break; one = from.shift(); } while (props[one]); return one; } let minProps = min; if (allowsAdditional && !requiredProperties.length) { minProps = Math.max(optionalsProbability === null || additionalProperties ? random_default.number(fillProps ? 1 : 0, max) : 0, min); } if (!extraProperties.length && !neededExtras && allowsAdditional && fixedProbabilities === true && fillProps) { const limit = random_default.number(0, max); for (let i = 0; i < limit; i += 1) { props[words_default(1) + hash(limit[i])] = additionalProperties || anyType; } } while (fillProps) { if (!(patternPropertyKeys.length || allowsAdditional)) { break; } if (current >= minProps) { break; } if (allowsAdditional) { if (reuseProps && propertyKeys.length - current > minProps) { let count = 0; let key; do { count += 1; if (count > 1e3) { break; } key = get(requiredProperties) || random_default.pick(propertyKeys); } while (typeof props[key] !== "undefined"); if (typeof props[key] === "undefined") { props[key] = properties[key]; current += 1; } } else if (patternPropertyKeys.length && !additionalProperties) { const prop = random_default.pick(patternPropertyKeys); const word = random_default.randexp(prop); if (!props[word]) { props[word] = patternProperties[prop]; current += 1; } } else { const word = get(requiredProperties) || words_default(1) + hash(); if (!props[word]) { props[word] = additionalProperties || anyType; current += 1; } } } for (let i = 0; current < min && i < patternPropertyKeys.length; i += 1) { const _key = patternPropertyKeys[i]; const word = random_default.randexp(_key); if (!props[word]) { props[word] = patternProperties[_key]; current += 1; } } } if (requiredProperties.length === 0 && (!allowsAdditional || optionalsProbability === false)) { const maximum = random_default.number(min, max); for (; current < maximum; ) { const word = get(propertyKeys); if (word) { props[word] = properties[word]; } current += 1; } } let sortedObj = props; if (option_default("sortProperties") !== null) { const originalKeys = Object.keys(properties); const sortedKeys = Object.keys(props).sort((a, b) => { return option_default("sortProperties") ? a.localeCompare(b) : originalKeys.indexOf(a) - originalKeys.indexOf(b); }); sortedObj = sortedKeys.reduce((memo, key) => { memo[key] = props[key]; return memo; }, {}); } const result = traverseCallback(sortedObj, path.concat(["properties"]), resolve2, value); _deps.forEach((dep) => { for (const sub of dep.values) { if (utils_default.hasValue(sub.properties[dep.prop], result.value[dep.prop])) { Object.keys(sub.properties).forEach((next) => { if (next !== dep.prop) { utils_default.merge(result.value, traverseCallback(sub.properties, path.concat(["properties"]), resolve2, value).value); } }); break; } } }); return result; } function produce() { const length = random_default.number(1, 5); return words_default(length).join(" "); } function thunkGenerator(min = 0, max = 140) { const _min = Math.max(0, min); const _max = random_default.number(_min, max); let result = produce(); while (result.length < _min) { result += produce(); } if (result.length > _max) { result = result.substr(0, _max); } return result; } function ipv4Generator() { return [0, 0, 0, 0].map(() => { return random_default.number(0, 255); }).join("."); } function dateTimeGenerator() { return random_default.date().toISOString(); } function dateGenerator() { return dateTime_default().slice(0, 10); } function timeGenerator() { return dateTime_default().slice(11); } function coreFormatGenerator(coreFormat) { return random_default.randexp(regexps[coreFormat]).replace(ALLOWED_FORMATS, (match, key) => { return random_default.randexp(regexps[key]); }); } function generateFormat(value, invalid) { const callback = format_default(value.format); if (typeof callback === "function") { return callback(value); } switch (value.format) { case "date-time": case "datetime": return dateTime_default(); case "date": return date_default(); case "time": return time_default(); case "ipv4": return ipv4_default(); case "regex": return ".+?"; case "email": case "hostname": case "ipv6": case "uri": case "uri-reference": case "iri": case "iri-reference": case "idn-email": case "idn-hostname": case "json-pointer": case "slug": case "uri-template": case "uuid": case "duration": return coreFormat_default(value.format); default: if (typeof callback === "undefined") { if (option_default("failOnInvalidFormat")) { throw new Error(`unknown registry key ${utils_default.short(value.format)}`); } else { return invalid(); } } throw new Error(`unsupported format '${value.format}'`); } } function stringType(value) { const output = utils_default.typecast("string", value, (opts) => { if (value.format) { return generateFormat(value, () => thunk_default(opts.minLength, opts.maxLength)); } if (value.pattern) { return random_default.randexp(value.pattern); } return thunk_default(opts.minLength, opts.maxLength); }); return output; } function getMeta({ $comment: comment, title, description }) { return Object.entries({ comment, title, description }).filter(([, value]) => value).reduce((memo, [k, v]) => { memo[k] = v; return memo; }, {}); } function traverse(schema, path, resolve2, rootSchema) { schema = resolve2(schema, null, path); if (schema && (schema.oneOf || schema.anyOf || schema.allOf)) { schema = resolve2(schema, null, path); } if (!schema) { throw new Error(`Cannot traverse at '${path.join(".")}', given '${JSON.stringify(rootSchema)}'`); } const context = { ...getMeta(schema), schemaPath: path }; if (path[path.length - 1] !== "properties") { if (option_default("useExamplesValue") && Array.isArray(schema.examples)) { const fixedExamples = schema.examples.concat("default" in schema ? [schema.default] : []); return { value: utils_default.typecast(null, schema, () => random_default.pick(fixedExamples)), context }; } if (option_default("useExamplesValue") && typeof schema.example !== "undefined") { return { value: utils_default.typecast(null, schema, () => schema.example), context }; } if (option_default("useDefaultValue") && "default" in schema) { if (schema.default !== "" || !option_default("replaceEmptyByRandomValue")) { return { value: schema.default, context }; } } if ("template" in schema) { return { value: utils_default.template(schema.template, rootSchema), context }; } if ("const" in schema) { return { value: schema.const, context }; } } if (schema.not && typeof schema.not === "object") { schema = utils_default.notValue(schema.not, utils_default.omitProps(schema, ["not"])); if (schema.type && schema.type === "object") { const { value, context: innerContext } = traverse(schema, path.concat(["not"]), resolve2, rootSchema); return { value: utils_default.clean(value, schema, false), context: { ...context, items: innerContext } }; } } if (typeof schema.thunk === "function") { const { value, context: innerContext } = traverse(schema.thunk(rootSchema), path, resolve2); return { value, context: { ...context, items: innerContext } }; } if (schema.jsonPath) { return { value: schema, context }; } let type = schema.type; if (Array.isArray(type)) { type = random_default.pick(type); } else if (typeof type === "undefined") { type = infer_default(schema, path) || type; if (type) { schema.type = type; } } if (typeof schema.generate === "function") { const retVal = utils_default.typecast(null, schema, () => schema.generate(rootSchema, path)); const retType = retVal === null ? "null" : typeof retVal; if (retType === type || retType === "number" && type === "integer" || Array.isArray(retVal) && type === "array") { return { value: retVal, context }; } } if (typeof schema.pattern === "string") { return { value: utils_default.typecast("string", schema, () => random_default.randexp(schema.pattern)), context }; } if (Array.isArray(schema.enum)) { return { value: utils_default.typecast(null, schema, () => random_default.pick(schema.enum)), context }; } if (typeof type === "string") { if (!types_default[type]) { if (option_default("failOnInvalidTypes")) { throw new error_default(`unknown primitive ${utils_default.short(type)}`, path.concat(["type"])); } else { const value = option_default("defaultInvalidTypeProduct"); if (typeof value === "string" && types_default[value]) { return { value: types_default[value](schema, path, resolve2, traverse), context }; } return { value, context }; } } else { try { const innerResult = types_default[type](schema, path, resolve2, traverse); if (type === "array") { return { value: innerResult.map(({ value }) => value), context: { ...context, items: innerResult.map( Array.isArray(schema.items) ? ({ context: c }) => c : ({ context: c }) => ({ ...c, // we have to remove the index from the path to get the real schema path schemaPath: c.schemaPath.slice(0, -1) }) ) } }; } if (type === "object") { return innerResult !== null ? { value: innerResult.value, context: { ...context, items: innerResult.context } } : { value: {}, context }; } return { value: innerResult, context }; } catch (e) { if (typeof e.path === "undefined") { throw new error_default(e.stack, path); } throw e; } } } let valueCopy = {}; let contextCopy = { ...context }; if (Array.isArray(schema)) { valueCopy = []; } const pruneProperties = option_default("pruneProperties") || []; Object.keys(schema).forEach((prop) => { if (pruneProperties.includes(prop)) return; if (schema[prop] === null) return; if (typeof schema[prop] === "object" && prop !== "definitions") { const { value, context: innerContext } = traverse(schema[prop], path.concat([prop]), resolve2, valueCopy); valueCopy[prop] = utils_default.clean(value, schema[prop], false); contextCopy[prop] = innerContext; if (valueCopy[prop] === null && option_default("omitNulls")) { delete valueCopy[prop]; delete contextCopy[prop]; } } else { valueCopy[prop] = schema[prop]; } }); return { value: valueCopy, context: contextCopy }; } function pick2(data) { return Array.isArray(data) ? random_default.pick(data) : data; } function cycle(data, reverse) { if (!Array.isArray(data)) { return data; } const value = reverse ? data.pop() : data.shift(); if (reverse) { data.unshift(value); } else { data.push(value); } return value; } function resolve(obj, data, values, property) { if (!obj || typeof obj !== "object") { return obj; } if (!values) { values = {}; } if (!data) { data = obj; } if (Array.isArray(obj)) { return obj.map((x) => resolve(x, data, values, property)); } if (obj.jsonPath) { const { JSONPath: JSONPath2 } = getDependencies(); const params = typeof obj.jsonPath !== "object" ? { path: obj.jsonPath } : obj.jsonPath; params.group = obj.group || params.group || property; params.cycle = obj.cycle || params.cycle || false; params.reverse = obj.reverse || params.reverse || false; params.count = obj.count || params.count || 1; const key = `${params.group}__${params.path}`; if (!values[key]) { if (params.count > 1) { values[key] = JSONPath2(params.path, data).slice(0, params.count); } else { values[key] = JSONPath2(params.path, data); } } if (params.cycle || params.reverse) { return cycle(values[key], params.reverse); } return pick2(values[key]); } Object.keys(obj).forEach((k) => { obj[k] = resolve(obj[k], data, values, k); }); return obj; } function run(refs, schema, container2, synchronous) { if (Object.prototype.toString.call(schema) !== "[object Object]") { throw new Error(`Invalid input, expecting object but given ${typeof schema}`); } const refDepthMin = option_default("refDepthMin") || 0; const refDepthMax = option_default("refDepthMax") || 3; try { const { resolveSchema } = buildResolveSchema_default({ refs, schema, container: container2, synchronous, refDepthMin, refDepthMax }); const result = traverse_default(utils_default.clone(schema), [], resolveSchema); if (option_default("resolveJsonPath")) { return { value: resolve(result.value), context: result.context }; } return result; } catch (e) { if (e.path) { throw new Error(`${e.message} in /${e.path.join("/")}`); } else { throw e; } } } function renderJS(res) { return res.value; } function getIn(obj, path) { return path.reduce((v, k) => k in v ? v[k] : {}, obj); } function addComments(context, path, commentNode, iterNode = commentNode) { const { title, description, comment } = getIn(context, path); const lines = []; if (option_default("renderTitle") && title) { lines.push(` ${title}`, ""); } if (option_default("renderDescription") && description) { lines.push(` ${description}`); } if (option_default("renderComment") && comment) { lines.push(` ${comment}`); } commentNode.commentBefore = lines.join("\n"); if (iterNode instanceof YAMLMap) { iterNode.items.forEach((n) => { addComments(context, [...path, "items", n.key.value], n.key, n.value); }); } else if (iterNode instanceof YAMLSeq) { iterNode.items.forEach((n, i) => { addComments(context, [...path, "items", i], n); }); } } function renderYAML({ value, context }) { const nodes = yaml_default.createNode(value); addComments(context, [], nodes); const doc = new yaml_default.Document(); doc.contents = nodes; return doc.toString(); } function setupKeywords() { container.define("autoIncrement", function autoIncrement(value, schema) { if (!this.offset) { const min = schema.minimum || 1; const max = min + constants_default.MAX_NUMBER; const offset = value.initialOffset || schema.initialOffset; this.offset = offset || random_default.number(min, max); } if (value) { return this.offset++; } return schema; }); container.define("sequentialDate", function sequentialDate(value, schema) { if (!this.now) { this.now = random_default.date(); } if (value) { schema = this.now.toISOString(); value = value === true ? "days" : value; if (["seconds", "minutes", "hours", "days", "weeks", "months", "years"].indexOf(value) === -1) { throw new Error(`Unsupported increment by ${utils_default.short(value)}`); } this.now.setTime(this.now.getTime() + random_default.date(value)); } return schema; }); } function getRefs(refs, schema) { let $refs = {}; if (Array.isArray(refs)) { refs.forEach((_schema) => { $refs[_schema.$id || _schema.id] = _schema; }); } else { $refs = refs || {}; } function walk(obj) { if (!obj || typeof obj !== "object") return; if (Array.isArray(obj)) return obj.forEach(walk); const _id = obj.$id || obj.id; if (typeof _id === "string" && !$refs[_id]) { $refs[_id] = obj; } Object.keys(obj).forEach((key) => { walk(obj[key]); }); } walk(refs); walk(schema); return $refs; } var __create, __defProp2, __getOwnPropDesc2, __getOwnPropNames2, __getProtoOf, __hasOwnProp2, __commonJS2, __copyProps2, __toESM, require_types, require_sets, require_util, require_positions, require_lib, require_lib2, require_randexp, require_PlainValue_ec8e588e, require_resolveSeq_d03cb037, require_warnings_1000a372, require_Schema_88e323a7, require_types2, DEPENDENCIES, getDependencies, setDependencies, Registry, Registry_default, defaults, defaults_default, OptionRegistry, OptionRegistry_default, registry, option_default, ALLOWED_TYPES, SCALAR_TYPES, ALL_TYPES, MOST_NEAR_DATETIME, MIN_INTEGER, MAX_INTEGER, MIN_NUMBER, MAX_NUMBER, constants_default, import_randexp, random_default, RE_NUMERIC, utils_default, Container, Container_default, registry2, format_default, ParseError, error_default, inferredProperties, subschemaProperties, infer_default, boolean_default, booleanType, boolean_default2, null_default, nullType, null_default2, array_default, number_default, integer_default, LIPSUM_WORDS, words_default, anyType, object_default, thunk_default, ipv4_default, dateTime_default, date_default, time_default, FRAGMENT, URI_PATTERN, PARAM_PATTERN, regexps, ALLOWED_FORMATS, coreFormat_default, string_default, typeMap, types_default, traverse_default, buildResolveSchema, buildResolveSchema_default, run_default, js_default, import_types2, binaryOptions, boolOptions, intOptions, nullOptions, strOptions, Schema, Alias, Collection, Merge, Node, Pair, Scalar, YAMLMap, YAMLSeq, yaml_default, container, jsf, JSONSchemaFaker, lib_default; var init_shared = __esm({ "src/shared.js"() { __create = Object.create; __defProp2 = Object.defineProperty; __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; __getOwnPropNames2 = Object.getOwnPropertyNames; __getProtoOf = Object.getPrototypeOf; __hasOwnProp2 = Object.prototype.hasOwnProperty; __commonJS2 = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; __copyProps2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }; __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps2( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set //