openapi-ts-mock-generator
Version:
typescript mock data generator based openapi
240 lines (234 loc) • 7.12 kB
JavaScript
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
// src/utils/string-utils.ts
var uuidToB64 = (uuid) => {
const uuidBuffer = Buffer.from(uuid.replace(/-/g, ""), "hex");
const base64Uuid = uuidBuffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
return base64Uuid;
};
var camelToKebab = (str) => {
return str.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
};
var isUrl = (str) => {
return str.startsWith("http://") || str.startsWith("https://");
};
var getFileExtension = (filename) => {
return filename.split(".").pop() || "";
};
// src/utils/code-utils.ts
var toTypeScriptCode = (param, options) => {
const { depth = 0, isStatic } = options;
const prefixSpace = " ".repeat(depth * 2);
if (param === null) {
return "null";
}
if (Array.isArray(param)) {
const results = param.map((elem) => toTypeScriptCode(elem, __spreadProps(__spreadValues({}, options), { depth: depth + 1 }))).join(",\n" + prefixSpace);
return ["[", results, "]"].join("\n" + prefixSpace);
}
if (typeof param === "object") {
const results = Object.entries(param).map(([key, value]) => {
return generateObjectProperty(key, value, options, prefixSpace);
}).join("\n" + prefixSpace);
return ["{", `${results}`, "}"].join("\n" + prefixSpace);
}
if (typeof param === "string") {
if (isStatic === false && (param.startsWith("faker") || param.startsWith("Buffer.from(faker"))) {
return param;
}
if (param.endsWith(" as const")) {
return `"${param.slice(0, -" as const".length)}" as const`;
}
}
return JSON.stringify(param);
};
var shouldApplyNullableExtension = (value, isOptional) => {
if (!isOptional)
return false;
if (value === null)
return true;
if (typeof value === "string" && value.includes(",null")) {
return true;
}
return false;
};
var generateObjectProperty = (key, value, options, prefixSpace) => {
const { isOptional, depth = 0 } = options;
const shouldApplyNullable = shouldApplyNullableExtension(value, isOptional);
const nullableTypeExtensionStart = shouldApplyNullable ? `...(faker.datatype.boolean() ? {
${prefixSpace}` : "";
const nullableTypeExtensionEnd = shouldApplyNullable ? `
${prefixSpace}} : {})` : "";
const propertyValue = toTypeScriptCode(value, __spreadProps(__spreadValues({}, options), {
depth: depth + 1
}));
return `${nullableTypeExtensionStart}${prefixSpace}${key}: ${propertyValue}${nullableTypeExtensionEnd},`;
};
var compressCode = (code) => {
return code.replace(/\n/g, " ").replace(/\s+/g, " ").replace(/\s\./g, ".").trim();
};
var generateInterface = (name, properties) => {
const props = Object.entries(properties).map(([key, type]) => ` ${key}: ${type}`).join("\n");
return `interface ${name} {
${props}
}`;
};
var generateTypeAlias = (name, type) => {
return `type ${name} = ${type}`;
};
// src/core/config.ts
import { Faker, ko } from "@faker-js/faker";
var FAKER_SEED = 1;
var faker = new Faker({
locale: [ko]
});
faker.seed(FAKER_SEED);
// src/utils/array-utils.ts
var getRandomLengthArray = (min = 1, max = 3) => {
const length = faker.number.int({ min, max });
return Array.from({ length }, (_, i) => i);
};
var chunkArray = (array, size) => {
const chunks = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
};
var unique = (array) => {
return [...new Set(array)];
};
var uniqueBy = (array, keyFn) => {
const seen = /* @__PURE__ */ new Set();
return array.filter((item) => {
const key = keyFn(item);
if (seen.has(key)) {
return false;
}
seen.add(key);
return true;
});
};
// src/utils/file-utils.ts
import { existsSync, mkdirSync, writeFileSync, rmSync, readdirSync, readFileSync } from "fs";
import * as path from "path";
var ensureDir = (dirPath) => {
if (!existsSync(dirPath)) {
mkdirSync(dirPath, { recursive: true });
}
};
var clearDirectory = (dirPath) => {
if (existsSync(dirPath)) {
readdirSync(dirPath).forEach((file) => {
rmSync(path.join(dirPath, file));
});
}
};
var safeWriteFile = (filePath, content) => {
const dir = path.dirname(filePath);
ensureDir(dir);
writeFileSync(filePath, content);
};
var readJsonFile = (filePath, defaultValue) => {
if (!existsSync(filePath)) {
return defaultValue;
}
try {
const content = readFileSync(filePath, "utf-8");
return JSON.parse(content);
} catch (error) {
console.warn(`Failed to read JSON file ${filePath}:`, error);
return defaultValue;
}
};
var resolveFilePath = (inputPath, baseDir) => {
if (inputPath.startsWith("http")) {
return inputPath;
}
if (baseDir) {
return path.join(baseDir, inputPath);
}
return inputPath;
};
var createUniqueFileName = (baseName, extension) => {
const timestamp = Date.now();
return `${baseName}-${timestamp}.${extension}`;
};
// src/utils/validation.ts
var isNotEmpty = (value) => {
return value !== null && value !== void 0;
};
var isNonEmptyString = (value) => {
return typeof value === "string" && value.trim().length > 0;
};
var isInRange = (value, min, max) => {
return value >= min && value <= max;
};
var isNonEmptyArray = (value) => {
return Array.isArray(value) && value.length > 0;
};
var isNonEmptyObject = (value) => {
return typeof value === "object" && value !== null && Object.keys(value).length > 0;
};
var isValidStatusCode = (code) => {
return isInRange(code, 100, 599);
};
var hasValidExtension = (filename, allowedExtensions) => {
var _a;
const extension = (_a = filename.split(".").pop()) == null ? void 0 : _a.toLowerCase();
return extension ? allowedExtensions.includes(extension) : false;
};
var isValidUrl = (url) => {
try {
new URL(url);
return true;
} catch (e) {
return false;
}
};
export {
camelToKebab,
chunkArray,
clearDirectory,
compressCode,
createUniqueFileName,
ensureDir,
generateInterface,
generateTypeAlias,
getFileExtension,
getRandomLengthArray,
hasValidExtension,
isInRange,
isNonEmptyArray,
isNonEmptyObject,
isNonEmptyString,
isNotEmpty,
isUrl,
isValidStatusCode,
isValidUrl,
readJsonFile,
resolveFilePath,
safeWriteFile,
toTypeScriptCode,
unique,
uniqueBy,
uuidToB64
};
//# sourceMappingURL=index.mjs.map