"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/plugin.ts var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _core = require('@kubb/core'); var _transformers = require('@kubb/core/transformers'); var _transformers2 = _interopRequireDefault(_transformers); var _utils = require('@kubb/core/utils'); var _pluginoas = require('@kubb/plugin-oas'); var _utils3 = require('@kubb/plugin-oas/utils'); var _swaggerts = require('@kubb/swagger-ts'); // src/OperationGenerator.tsx var _components = require('@kubb/plugin-oas/components'); var _react = require('@kubb/react'); // src/components/OperationSchema.tsx var _hooks = require('@kubb/plugin-oas/hooks'); // src/SchemaGenerator.tsx // src/components/Schema.tsx // src/parser/index.ts var fakerKeywordMapper = { any: () => "undefined", unknown: () => "unknown", number: (min, max) => { if (max !== void 0 && min !== void 0) { return `faker.number.float({ min: ${min}, max: ${max} })`; } if (min !== void 0) { return `faker.number.float({ min: ${min} })`; } if (max !== void 0) { return `faker.number.float({ max: ${max} })`; } return "faker.number.float()"; }, integer: (min, max) => { if (max !== void 0 && min !== void 0) { return `faker.number.int({ min: ${min}, max: ${max} })`; } if (min !== void 0) { return `faker.number.int({ min: ${min} })`; } if (max !== void 0) { return `faker.number.int({ max: ${max} })`; } return "faker.number.int()"; }, string: (min, max) => { if (max !== void 0 && min !== void 0) { return `faker.string.alpha({ length: { min: ${min}, max: ${max} } })`; } if (min !== void 0) { return `faker.string.alpha({ length: { min: ${min} } })`; } if (max !== void 0) { return `faker.string.alpha({ length: { max: ${max} } })`; } return "faker.string.alpha()"; }, boolean: () => "faker.datatype.boolean()", undefined: () => "undefined", null: () => "null", array: (items = []) => `faker.helpers.arrayElements([${items.join(", ")}]) as any`, tuple: (items = []) => `faker.helpers.arrayElements([${items.join(", ")}]) as any`, enum: (items = []) => `faker.helpers.arrayElement([${items.join(", ")}])`, union: (items = []) => `faker.helpers.arrayElement([${items.join(", ")}])`, /** * ISO 8601 */ datetime: () => "faker.date.anytime().toISOString()", /** * Type `'date'` Date * Type `'string'` ISO date format (YYYY-MM-DD) * @default ISO date format (YYYY-MM-DD) */ date: (type = "string", parser) => { if (type === "string") { if (parser) { return `${parser}(faker.date.anytime()).format("YYYY-MM-DD")`; } return "faker.date.anytime().toString()"; } return "faker.date.anytime()"; }, /** * Type `'date'` Date * Type `'string'` ISO time format (HH:mm:ss[.SSSSSS]) * @default ISO time format (HH:mm:ss[.SSSSSS]) */ time: (type = "string", parser) => { if (type === "string") { if (parser) { return `${parser}(faker.date.anytime()).format("HH:mm:ss")`; } return "faker.date.anytime().toString()"; } return "faker.date.anytime()"; }, uuid: () => "faker.string.uuid()", url: () => "faker.internet.url()", and: (items = []) => `Object.assign({}, ${items.join(", ")})`, object: () => "object", ref: () => "ref", matches: (value = "", regexGenerator = "faker") => { if (regexGenerator === "randexp") { return `${_transformers2.default.toRegExpString(value, "RandExp")}.gen()`; } return `faker.helpers.fromRegExp(${_transformers2.default.toRegExpString(value)})`; }, email: () => "faker.internet.email()", firstName: () => "faker.person.firstName()", lastName: () => "faker.person.lastName()", password: () => "faker.internet.password()", phone: () => "faker.phone.number()", blob: () => "faker.image.imageUrl() as unknown as Blob", default: void 0, describe: void 0, const: (value) => _nullishCoalesce(value, () => ( "")), max: void 0, min: void 0, nullable: void 0, nullish: void 0, optional: void 0, readOnly: void 0, writeOnly: void 0, strict: void 0, deprecated: void 0, example: void 0, schema: void 0, catchall: void 0, name: void 0 }; function schemaKeywordsorter(a, b) { if (b.keyword === "null") { return -1; } return 0; } function joinItems(items) { switch (items.length) { case 0: return "undefined"; case 1: return items[0]; default: return fakerKeywordMapper.union(items); } } function parse(parent, current, options) { const value = fakerKeywordMapper[current.keyword]; if (!value) { return void 0; } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.union)) { return fakerKeywordMapper.union(current.args.map((schema) => parse(current, schema, { ...options, withData: false })).filter(Boolean)); } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.and)) { return fakerKeywordMapper.and(current.args.map((schema) => parse(current, schema, { ...options, withData: false })).filter(Boolean)); } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.array)) { return fakerKeywordMapper.array(current.args.items.map((schema) => parse(current, schema, { ...options, withData: false })).filter(Boolean)); } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.enum)) { return fakerKeywordMapper.enum( current.args.items.map((schema) => { if (schema.format === "number") { return schema.name; } return _transformers2.default.stringify(schema.name); }) ); } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.ref)) { if (!_optionalChain([current, 'access', _ => _.args, 'optionalAccess', _2 => _2.name])) { throw new Error(`Name not defined for keyword ${current.keyword}`); } if (options.withData) { return `${current.args.name}(data)`; } return `${current.args.name}()`; } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.object)) { const argsObject = Object.entries(_optionalChain([current, 'access', _3 => _3.args, 'optionalAccess', _4 => _4.properties]) || {}).filter((item) => { const schema = item[1]; return schema && typeof schema.map === "function"; }).map(([name, schemas]) => { const nameSchema = schemas.find((schema) => schema.keyword === _pluginoas.schemaKeywords.name); const mappedName = _optionalChain([nameSchema, 'optionalAccess', _5 => _5.args]) || name; if (_optionalChain([options, 'access', _6 => _6.mapper, 'optionalAccess', _7 => _7[mappedName]])) { return `"${name}": ${_optionalChain([options, 'access', _8 => _8.mapper, 'optionalAccess', _9 => _9[mappedName]])}`; } return `"${name}": ${joinItems( schemas.sort(schemaKeywordsorter).map((schema) => parse(current, schema, { ...options, withData: false })).filter(Boolean) )}`; }).join(","); return `{${argsObject}}`; } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.tuple)) { if (Array.isArray(current.args.items)) { return fakerKeywordMapper.tuple(current.args.items.map((schema) => parse(current, schema, { ...options, withData: false })).filter(Boolean)); } return parse(current, current.args.items, { ...options, withData: false }); } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.const)) { if (current.args.format === "number" && current.args.name !== void 0) { return fakerKeywordMapper.const(_optionalChain([current, 'access', _10 => _10.args, 'access', _11 => _11.name, 'optionalAccess', _12 => _12.toString, 'call', _13 => _13()])); } return fakerKeywordMapper.const(_transformers2.default.stringify(current.args.value)); } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.matches) && current.args) { return fakerKeywordMapper.matches(current.args, options.regexGenerator); } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.null) || _pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.undefined) || _pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.any)) { return value() || ""; } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.string)) { if (parent) { const minSchema = _pluginoas.SchemaGenerator.find([parent], _pluginoas.schemaKeywords.min); const maxSchema = _pluginoas.SchemaGenerator.find([parent], _pluginoas.schemaKeywords.max); return fakerKeywordMapper.string(_optionalChain([minSchema, 'optionalAccess', _14 => _14.args]), _optionalChain([maxSchema, 'optionalAccess', _15 => _15.args])); } return fakerKeywordMapper.string(); } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.number)) { if (parent) { const minSchema = _pluginoas.SchemaGenerator.find([parent], _pluginoas.schemaKeywords.min); const maxSchema = _pluginoas.SchemaGenerator.find([parent], _pluginoas.schemaKeywords.max); return fakerKeywordMapper.number(_optionalChain([minSchema, 'optionalAccess', _16 => _16.args]), _optionalChain([maxSchema, 'optionalAccess', _17 => _17.args])); } return fakerKeywordMapper.number(); } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.integer)) { if (parent) { const minSchema = _pluginoas.SchemaGenerator.find([parent], _pluginoas.schemaKeywords.min); const maxSchema = _pluginoas.SchemaGenerator.find([parent], _pluginoas.schemaKeywords.max); return fakerKeywordMapper.integer(_optionalChain([minSchema, 'optionalAccess', _18 => _18.args]), _optionalChain([maxSchema, 'optionalAccess', _19 => _19.args])); } return fakerKeywordMapper.integer(); } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.datetime)) { return fakerKeywordMapper.datetime(); } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.date)) { return fakerKeywordMapper.date(current.args.type, options.dateParser); } if (_pluginoas.isKeyword.call(void 0, current, _pluginoas.schemaKeywords.time)) { return fakerKeywordMapper.time(current.args.type, options.dateParser); } if (current.keyword in fakerKeywordMapper && "args" in current) { const value2 = fakerKeywordMapper[current.keyword]; const options2 = JSON.stringify(current.args); return value2(options2); } if (current.keyword in fakerKeywordMapper) { return value(); } return void 0; } // src/components/Schema.tsx var _jsxruntime = require('@kubb/react/jsx-runtime'); function Schema(props) { const { withData, description } = props; const { tree, name } = _hooks.useSchema.call(void 0, ); const { pluginManager, plugin: { options: { dateParser, regexGenerator, mapper, seed } } } = _react.useApp.call(void 0, ); const resolvedName = pluginManager.resolveName({ name, pluginKey: [pluginFakerName], type: "function" }); const typeName = pluginManager.resolveName({ name, pluginKey: [_swaggerts.pluginTsName], type: "type" }); const fakerText = joinItems( tree.map((schema) => parse(void 0, schema, { name: resolvedName, typeName, seed, regexGenerator, mapper, withData, dateParser })).filter(Boolean) ); let fakerDefaultOverride = void 0; let fakerTextWithOverride = fakerText; if (withData && fakerText.startsWith("{")) { fakerDefaultOverride = "{}"; fakerTextWithOverride = `{ ...${fakerText}, ...data }`; } if (withData && fakerText.startsWith("faker.helpers.arrayElements")) { fakerDefaultOverride = "[]"; fakerTextWithOverride = `[ ...${fakerText}, ...data ]`; } const params = fakerDefaultOverride ? `data: NonNullable> = ${fakerDefaultOverride}` : `data?: NonNullable>`; return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment, { children: [ /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _react.Function, { export: true, name: resolvedName, JSDoc: { comments: [description ? `@description ${_transformers2.default.jsStringEscape(description)}` : void 0].filter(Boolean) }, params: withData ? params : "", returnType: typeName ? `NonNullable<${typeName}>` : "", children: [ seed ? `faker.seed(${JSON.stringify(seed)})` : "", /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "br", {}), /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.Function.Return, { children: fakerTextWithOverride }) ] } ), /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "br", {}) ] }); } Schema.File = function({}) { const { pluginManager } = _react.useApp.call(void 0, ); const { tree, schema } = _hooks.useSchema.call(void 0, ); const withData = tree.some( (schema2) => schema2.keyword === _pluginoas.schemaKeywords.array || schema2.keyword === _pluginoas.schemaKeywords.and || schema2.keyword === _pluginoas.schemaKeywords.object || schema2.keyword === _pluginoas.schemaKeywords.union || schema2.keyword === _pluginoas.schemaKeywords.tuple ); return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _components.Oas.Schema.File, { output: pluginManager.config.output.path, children: [ /* @__PURE__ */ _jsxruntime.jsx.call(void 0, Schema.Imports, {}), /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.File.Source, { children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, Schema, { description: _optionalChain([schema, 'optionalAccess', _20 => _20.description]), withData }) }) ] }); }; Schema.Imports = () => { const { pluginManager, plugin: { options: { extName, dateParser, regexGenerator } } } = _react.useApp.call(void 0, ); const { path: root } = _react.useFile.call(void 0, ); const { name, tree, schema } = _hooks.useSchema.call(void 0, ); const typeName = pluginManager.resolveName({ name, pluginKey: [_swaggerts.pluginTsName], type: "type" }); const typeFileName = pluginManager.resolveName({ name, pluginKey: [_swaggerts.pluginTsName], type: "file" }); const typePath = pluginManager.resolvePath({ baseName: typeFileName, pluginKey: [_swaggerts.pluginTsName] }); return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment, { children: [ /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.File.Import, { name: ["faker"], path: "@faker-js/faker" }), regexGenerator === "randexp" && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.File.Import, { name: "RandExp", path: "randexp" }), dateParser && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.File.Import, { path: dateParser, name: dateParser }), typeName && typePath && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.File.Import, { extName, isTypeOnly: true, root, path: typePath, name: [typeName] }) ] }); }; // src/SchemaGenerator.tsx var SchemaGenerator2 = class extends _pluginoas.SchemaGenerator { async schema(name, schema, options) { const { oas, pluginManager, plugin, mode, output } = this.context; const root = _react.createRoot.call(void 0, { logger: pluginManager.logger }); const tree = this.parse({ schema, name }); root.render( /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.App, { pluginManager, plugin: { ...plugin, options }, mode, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _components.Oas, { oas, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _components.Oas.Schema, { name, value: schema, tree, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, Schema.File, {}) }) }) }) ); return root.files; } }; // src/components/OperationSchema.tsx function OperationSchema({ description }) { return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, Schema, { withData: false, description }); } OperationSchema.File = function({}) { const { plugin, pluginManager, mode } = _react.useApp.call(void 0, ); const oas = _hooks.useOas.call(void 0, ); const { getSchemas, getFile } = _hooks.useOperationManager.call(void 0, ); const operation = _hooks.useOperation.call(void 0, ); const file = getFile(operation); const schemas = getSchemas(operation); const generator = new SchemaGenerator2(plugin.options, { oas, plugin, pluginManager, mode, override: plugin.options.override }); const items = [schemas.pathParams, schemas.queryParams, schemas.headerParams, schemas.statusCodes, schemas.request, schemas.response].flat().filter(Boolean); const mapItem = ({ name, schema, description, ...options }, i) => { const typeName = pluginManager.resolveName({ name, pluginKey: [_swaggerts.pluginTsName], type: "type" }); const typeFileName = pluginManager.resolveName({ name: options.operationName || name, pluginKey: [_swaggerts.pluginTsName], type: "file" }); const typePath = pluginManager.resolvePath({ baseName: typeFileName, pluginKey: [_swaggerts.pluginTsName], options: { tag: _optionalChain([options, 'access', _21 => _21.operation, 'optionalAccess', _22 => _22.getTags, 'call', _23 => _23(), 'access', _24 => _24[0], 'optionalAccess', _25 => _25.name]) } }); const tree = generator.parse({ schema, name }); return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _components.Oas.Schema, { name, value: schema, tree, children: [ typeName && typePath && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.File.Import, { extName: plugin.options.extName, isTypeOnly: true, root: file.path, path: typePath, name: [typeName] }), plugin.options.dateParser && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.File.Import, { path: plugin.options.dateParser, name: plugin.options.dateParser }), mode === "split" && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _components.Oas.Schema.Imports, { extName: plugin.options.extName }), /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.File.Source, { children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, OperationSchema, { description }) }) ] }, i); }; return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.Parser, { language: "typescript", children: /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _react.File, { baseName: file.baseName, path: file.path, meta: file.meta, children: [ /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.File.Import, { name: ["faker"], path: "@faker-js/faker" }), plugin.options.regexGenerator === "randexp" && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.File.Import, { name: "RandExp", path: "randexp" }), items.map(mapItem) ] }) }); }; // src/OperationGenerator.tsx var OperationGenerator = class extends _pluginoas.OperationGenerator { async operation(operation, options) { const { oas, pluginManager, plugin, mode } = this.context; const root = _react.createRoot.call(void 0, { logger: pluginManager.logger }); root.render( /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.App, { pluginManager, plugin: { ...plugin, options }, mode, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _components.Oas, { oas, operations: [operation], generator: this, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _components.Oas.Operation, { operation, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, OperationSchema.File, {}) }) }) }) ); return root.files; } }; // src/plugin.ts var pluginFakerName = "plugin-faker"; var pluginFaker = _core.createPlugin.call(void 0, (options) => { const { output = { path: "mocks" }, seed, group, exclude = [], include, override = [], transformers: transformers3 = {}, mapper = {}, dateType = "string", unknownType = "any", dateParser, regexGenerator = "faker" } = options; const template = _optionalChain([group, 'optionalAccess', _26 => _26.output]) ? group.output : `${output.path}/{{tag}}Controller`; return { name: pluginFakerName, options: { extName: output.extName, transformers: transformers3, dateType, seed, unknownType, dateParser, mapper, override, regexGenerator }, pre: [_pluginoas.pluginOasName, _swaggerts.pluginTsName], resolvePath(baseName, pathMode, options2) { const root = _path2.default.resolve(this.config.root, this.config.output.path); const mode = _nullishCoalesce(pathMode, () => ( _core.FileManager.getMode(_path2.default.resolve(root, output.path)))); if (mode === "single") { return _path2.default.resolve(root, output.path); } if (_optionalChain([options2, 'optionalAccess', _27 => _27.tag]) && _optionalChain([group, 'optionalAccess', _28 => _28.type]) === "tag") { const tag = _transformers.camelCase.call(void 0, options2.tag); return _path2.default.resolve(root, _utils.renderTemplate.call(void 0, template, { tag }), baseName); } return _path2.default.resolve(root, output.path, baseName); }, resolveName(name, type) { const resolvedName = _transformers.camelCase.call(void 0, name, { prefix: type ? "create" : void 0, isFile: type === "file" }); if (type) { return _optionalChain([transformers3, 'optionalAccess', _29 => _29.name, 'optionalCall', _30 => _30(resolvedName, type)]) || resolvedName; } return resolvedName; }, async writeFile(path2, source) { if (!path2.endsWith(".ts") || !source) { return; } return this.fileManager.write(path2, source, { sanity: false }); }, async buildStart() { const [swaggerPlugin] = _core.PluginManager.getDependedPlugins(this.plugins, [_pluginoas.pluginOasName]); const oas = await swaggerPlugin.api.getOas(); const root = _path2.default.resolve(this.config.root, this.config.output.path); const mode = _core.FileManager.getMode(_path2.default.resolve(root, output.path)); const schemaGenerator = new SchemaGenerator2(this.plugin.options, { oas, pluginManager: this.pluginManager, plugin: this.plugin, contentType: swaggerPlugin.api.contentType, include: void 0, override, mode, output: output.path }); const schemaFiles = await schemaGenerator.build(); await this.addFile(...schemaFiles); const operationGenerator = new OperationGenerator(this.plugin.options, { oas, pluginManager: this.pluginManager, plugin: this.plugin, contentType: swaggerPlugin.api.contentType, exclude, include, override, mode }); const operationFiles = await operationGenerator.build(); await this.addFile(...operationFiles); }, async buildEnd() { if (this.config.output.write === false) { return; } const root = _path2.default.resolve(this.config.root, this.config.output.path); if (_optionalChain([group, 'optionalAccess', _31 => _31.type]) === "tag") { const rootFiles = await _utils3.getGroupedByTagFiles.call(void 0, { logger: this.logger, files: this.fileManager.files, plugin: this.plugin, template, exportAs: group.exportAs || "{{tag}}Mocks", root, output }); await this.addFile(...rootFiles); } await this.fileManager.addIndexes({ root, output, meta: { pluginKey: this.plugin.key }, logger: this.logger }); } }; }); // src/index.ts var definePluginDefault = pluginFaker; var definePlugin = pluginFaker; var src_default = definePluginDefault; exports.default = src_default; exports.definePlugin = definePlugin; exports.pluginFaker = pluginFaker; exports.pluginFakerName = pluginFakerName; //# sourceMappingURL=index.cjs.map