@kubb/plugin-faker 5.1.7 → 5.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,304 @@
1
+ import { Exclude, Group, Include, Output, OutputOptions, Override, PluginType, Resolver, ResolverPatch, ast } from "kubb/kit";
2
+ import { KubbReactNode } from "kubb/jsx";
3
+ //#region src/types.d.ts
4
+ /**
5
+ * Resolver for Faker that provides naming methods for mock functions.
6
+ *
7
+ * The top-level `name` and `file` apply the plugin's `create` prefix. Composite
8
+ * operation naming is grouped into the `param` and `response` namespaces.
9
+ */
10
+ type ResolverFaker = Resolver & {
11
+ /**
12
+ * Naming for operation parameters, keyed by their location.
13
+ */
14
+ param: {
15
+ /**
16
+ * Resolves the faker function name for an individual parameter.
17
+ *
18
+ * @example Individual parameter name
19
+ * `resolver.param.name(node, param) // -> 'showPetByIdPathPetId'`
20
+ */
21
+ name(node: ast.OperationNode, param: ast.ParameterNode): string;
22
+ /**
23
+ * Resolves the faker function name for an operation's grouped path parameters.
24
+ *
25
+ * @example Grouped path parameters name
26
+ * `resolver.param.path(node, param) // -> 'createShowPetByIdPath'`
27
+ */
28
+ path(node: ast.OperationNode, param: ast.ParameterNode): string;
29
+ /**
30
+ * Resolves the faker function name for an operation's grouped query parameters.
31
+ *
32
+ * @example Grouped query parameters name
33
+ * `resolver.param.query(node, param) // -> 'createListPetsQuery'`
34
+ */
35
+ query(node: ast.OperationNode, param: ast.ParameterNode): string;
36
+ /**
37
+ * Resolves the faker function name for an operation's grouped header parameters.
38
+ *
39
+ * @example Grouped header parameters name
40
+ * `resolver.param.headers(node, param) // -> 'createDeletePetHeaders'`
41
+ */
42
+ headers(node: ast.OperationNode, param: ast.ParameterNode): string;
43
+ };
44
+ /**
45
+ * Naming for operation request bodies and responses.
46
+ */
47
+ response: {
48
+ /**
49
+ * Resolves the faker function name for a response by status code.
50
+ *
51
+ * @example Response status name
52
+ * `resolver.response.status(node, 200) // -> 'listPetsStatus200'`
53
+ */
54
+ status(node: ast.OperationNode, statusCode: ast.StatusCode): string;
55
+ /**
56
+ * Resolves the faker function name for a request body.
57
+ *
58
+ * @example Request body name
59
+ * `resolver.response.body(node) // -> 'createPetsBody'`
60
+ */
61
+ body(node: ast.OperationNode): string;
62
+ /**
63
+ * Resolves the faker function name for the response union.
64
+ *
65
+ * @example Response union name
66
+ * `resolver.response.response(node) // -> 'listPetsResponse'`
67
+ */
68
+ response(node: ast.OperationNode): string;
69
+ /**
70
+ * Resolves the faker function name for the response collection.
71
+ *
72
+ * @example Responses collection name
73
+ * `resolver.response.responses(node) // -> 'listPetsResponses'`
74
+ */
75
+ responses(node: ast.OperationNode): string;
76
+ };
77
+ };
78
+ /**
79
+ * Where the generated mock factories are written and how they are exported, plus the optional
80
+ * `group` strategy. The `group` option organizes `output.mode: 'directory'` output into per-tag or per-path subdirectories.
81
+ *
82
+ * @default { path: 'mocks', barrel: { type: 'named' } }
83
+ */
84
+ type Options = OutputOptions & {
85
+ /**
86
+ * Skip operations matching at least one entry in the list.
87
+ */
88
+ exclude?: Array<Exclude>;
89
+ /**
90
+ * Restrict generation to operations matching at least one entry in the list.
91
+ */
92
+ include?: Array<Include>;
93
+ /**
94
+ * Apply a different options object to operations matching a pattern.
95
+ */
96
+ override?: Array<Override<ResolvedOptions>>;
97
+ /**
98
+ * Type object factories from generated values and overrides (`'inferred'`) or
99
+ * from the declared API model (`'schema'`).
100
+ *
101
+ * @default 'inferred'
102
+ */
103
+ typeMode?: 'inferred' | 'schema';
104
+ /**
105
+ * Library used to format string-represented date, time, and datetime fields.
106
+ * Any library exporting a default function works; Kubb adds the import for you.
107
+ *
108
+ * @default 'faker'
109
+ */
110
+ dateParser?: 'faker' | 'dayjs' | 'moment' | (string & {});
111
+ /**
112
+ * Library used to generate strings that satisfy a regex `pattern` keyword.
113
+ * - `'faker'` uses `faker.helpers.fromRegExp`. No extra dependency. Faker does not support
114
+ * shorthand classes such as `\d`, `\w`, or `\s`; use `'randexp'` for those patterns.
115
+ * - `'randexp'` uses the `randexp` package. Supports a wider regex grammar.
116
+ *
117
+ * @default 'faker'
118
+ */
119
+ regexGenerator?: 'faker' | 'randexp';
120
+ /**
121
+ * Faker locale code. Switches the named import to `fakerXX` from `@faker-js/faker`
122
+ * so names, addresses, and phone numbers reflect the target region.
123
+ *
124
+ * @default 'en'
125
+ * @example German
126
+ * `locale: 'de'`
127
+ * @example Austrian German
128
+ * `locale: 'de_AT'`
129
+ * @see https://fakerjs.dev/api/localization.html
130
+ */
131
+ locale?: string;
132
+ /**
133
+ * Value passed to `faker.seed(...)`. Set this for deterministic mock output,
134
+ * which is useful for snapshot tests.
135
+ */
136
+ seed?: number | Array<number>;
137
+ /**
138
+ * Override the naming of generated factory helpers. Common use: append `Mock` or
139
+ * `Factory` so helpers do not clash with imported types.
140
+ */
141
+ resolver?: ResolverPatch<ResolverFaker>;
142
+ /**
143
+ * Macros applied to schema and operation nodes before printing.
144
+ */
145
+ macros?: Array<ast.Macro>;
146
+ /**
147
+ * Replace the Faker handler for a specific schema type (`'integer'`, `'date'`, ...).
148
+ * Each handler returns the Faker expression as a string.
149
+ */
150
+ printer?: {
151
+ nodes?: PrinterFakerNodes;
152
+ };
153
+ };
154
+ type ResolvedOptions = {
155
+ output: Output;
156
+ group: Group | null;
157
+ exclude: NonNullable<Options['exclude']>;
158
+ include: Options['include'];
159
+ override: NonNullable<Options['override']>;
160
+ typeMode: NonNullable<Options['typeMode']>;
161
+ dateParser: NonNullable<Options['dateParser']>;
162
+ regexGenerator: NonNullable<Options['regexGenerator']>;
163
+ seed: NonNullable<Options['seed']> | undefined;
164
+ locale: Options['locale'];
165
+ printer: Options['printer'];
166
+ };
167
+ type PluginFaker = PluginType<'plugin-faker', Options, ResolvedOptions, ResolverFaker>;
168
+ declare global {
169
+ namespace Kubb {
170
+ interface PluginRegistry {
171
+ 'plugin-faker': PluginFaker;
172
+ }
173
+ }
174
+ }
175
+ //#endregion
176
+ //#region src/printers/printerFaker.d.ts
177
+ /**
178
+ * Partial map of node-type overrides for the Faker printer. Each key is a
179
+ * `SchemaType` (`'string'`, `'date'`, ...) and each handler returns the
180
+ * Faker expression for that schema as a string. Use `this.transform` to
181
+ * recurse into nested schema nodes, `this.base` to reuse the built-in handler,
182
+ * and `this.options` to read printer options.
183
+ *
184
+ * @example Override the integer handler
185
+ * ```ts
186
+ * pluginFaker({
187
+ * printer: {
188
+ * nodes: {
189
+ * integer() {
190
+ * return 'faker.number.float()'
191
+ * },
192
+ * },
193
+ * },
194
+ * })
195
+ * ```
196
+ */
197
+ type PrinterFakerNodes = ast.PrinterPartial<string, PrinterFakerOptions>;
198
+ /**
199
+ * Options passed to the Faker printer at instantiation: the parser library
200
+ * for date strings, the regex generator, and the resolver used to compute
201
+ * identifiers.
202
+ */
203
+ type PrinterFakerOptions = {
204
+ dateParser?: PluginFaker['resolvedOptions']['dateParser'];
205
+ regexGenerator?: PluginFaker['resolvedOptions']['regexGenerator'];
206
+ resolver: ResolverFaker;
207
+ typeName?: string;
208
+ schemaName?: string;
209
+ nestedInObject?: boolean;
210
+ /**
211
+ * Set while printing the members of a union (`oneOf`). Object properties then index their
212
+ * type as `(NonNullable<T> & Record<K, unknown>)[K]` instead of `NonNullable<T>[K]`, so a key
213
+ * carried by only some branches stays valid (a plain index would be a TS2339).
214
+ */
215
+ nestedInUnion?: boolean;
216
+ nodes?: PrinterFakerNodes;
217
+ /**
218
+ * Names of schemas that participate in a circular dependency chain.
219
+ * Properties whose schema transitively references one of these are emitted
220
+ * as lazy getters so that user overrides via the `data` parameter prevent
221
+ * the recursive faker call from ever executing (avoiding stack overflow).
222
+ */
223
+ cyclicSchemas?: ReadonlySet<string>;
224
+ };
225
+ /**
226
+ * Factory options for the Faker printer, defining input/output types and configuration.
227
+ */
228
+ type PrinterFakerFactory = ast.PrinterFactoryOptions<'faker', PrinterFakerOptions, string, string>;
229
+ /**
230
+ * Creates a Faker printer that generates mock data generation code from schema nodes.
231
+ * Handles circular references gracefully by emitting memoizing getters for cyclic properties.
232
+ */
233
+ export declare const printerFaker: (options: PrinterFakerOptions) => ast.Printer<PrinterFakerFactory>;
234
+ //#endregion
235
+ //#region src/components/Faker.d.ts
236
+ type Props = {
237
+ name: string;
238
+ typeName: string;
239
+ node: ast.SchemaNode;
240
+ printer: ast.Printer<PrinterFakerFactory>;
241
+ description?: string;
242
+ canOverride: boolean;
243
+ typeMode?: PluginFaker['resolvedOptions']['typeMode'];
244
+ };
245
+ export declare function Faker({ node, description, name, typeName, printer, canOverride, typeMode }: Props): KubbReactNode;
246
+ //#endregion
247
+ //#region src/generators/fakerGenerator.d.ts
248
+ /**
249
+ * Built-in generator for `@kubb/plugin-faker`. Emits one `createX` factory
250
+ * per schema in the spec plus per-operation request/response factories. Each
251
+ * factory returns a value matching the corresponding TypeScript type from
252
+ * `@kubb/plugin-ts`.
253
+ */
254
+ export declare const fakerGenerator: import("kubb/kit").Generator<PluginFaker, unknown>;
255
+ //#endregion
256
+ //#region src/plugin.d.ts
257
+ /**
258
+ * Canonical plugin name for `@kubb/plugin-faker`. Used for driver lookups and
259
+ * cross-plugin dependency references.
260
+ */
261
+ export declare const pluginFakerName = "plugin-faker";
262
+ /**
263
+ * Generates one mock-data factory per OpenAPI schema using Faker.js. Call
264
+ * `createPet()` to get a realistic `Pet` object. Useful for tests, Storybook,
265
+ * and local development without a running backend.
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * import { defineConfig } from 'kubb/config'
270
+ * import { pluginTs } from '@kubb/plugin-ts'
271
+ * import { pluginFaker } from '@kubb/plugin-faker'
272
+ *
273
+ * export default defineConfig({
274
+ * input: './petStore.yaml',
275
+ * output: { path: './src/gen' },
276
+ * plugins: [
277
+ * pluginTs(),
278
+ * pluginFaker({
279
+ * output: { path: './mocks' },
280
+ * seed: [100],
281
+ * }),
282
+ * ],
283
+ * })
284
+ * ```
285
+ */
286
+ export declare const pluginFaker: import("kubb/kit").PluginFactory<PluginFaker>;
287
+ //#endregion
288
+ //#region src/resolvers/resolverFaker.d.ts
289
+ /**
290
+ * Default resolver used by `@kubb/plugin-faker`. Decides the names and file
291
+ * paths for every generated mock factory. Functions and files are prefixed
292
+ * with `create` so `Pet` becomes `createPet`.
293
+ *
294
+ * @example Resolve a factory name
295
+ * ```ts
296
+ * import { resolverFaker } from '@kubb/plugin-faker'
297
+ *
298
+ * resolverFaker.name('list pets') // 'createListPets'
299
+ * ```
300
+ */
301
+ export declare const resolverFaker: ResolverFaker;
302
+ //#endregion
303
+ export { type PluginFaker, type PrinterFakerFactory, type PrinterFakerNodes, type PrinterFakerOptions, type ResolverFaker, pluginFaker as default };
304
+ //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { t as __name } from "./rolldown-runtime-C0LytTxp.js";
2
1
  import { Exclude, Group, Include, Output, OutputOptions, Override, PluginType, Resolver, ResolverPatch, ast } from "kubb/kit";
3
2
  import { KubbReactNode } from "kubb/jsx";
4
3
  //#region src/types.d.ts
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import "./rolldown-runtime-C0LytTxp.js";
2
1
  import { posix } from "node:path";
3
2
  import { Diagnostics, Resolver, addGenerator, assertPluginOption, ast, containsCircularRef, createResolver, defineExtension, defineGenerator, setMacros, setResolver } from "kubb/kit";
4
3
  import { File, Function, jsxRenderer } from "kubb/jsx";
5
4
  import { Fragment, jsx, jsxs } from "kubb/jsx/jsx-runtime";
6
5
  import { buildParams, enumTypeName, pluginTsName } from "@kubb/plugin-ts";
6
+ //#endregion
7
7
  //#region ../../internals/utils/src/casing.ts
8
8
  /**
9
9
  * Shared implementation for camelCase and PascalCase conversion.
@@ -12,12 +12,23 @@ import { buildParams, enumTypeName, pluginTsName } from "@kubb/plugin-ts";
12
12
  *
13
13
  * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
14
14
  */
15
- function toCamelOrPascal(text, pascal) {
15
+ function convert(text, pascal) {
16
16
  return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
17
17
  if (word.length > 1 && word === word.toUpperCase()) return word;
18
18
  return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
19
19
  }).join("").replace(/[^a-zA-Z0-9]/g, "");
20
20
  }
21
+ const cache = /* @__PURE__ */ new Map();
22
+ const cacheLimit = 1e4;
23
+ function toCamelOrPascal(text, pascal) {
24
+ const key = `${pascal ? "P" : "c"}${text}`;
25
+ const cached = cache.get(key);
26
+ if (cached !== void 0) return cached;
27
+ const result = convert(text, pascal);
28
+ if (cache.size >= cacheLimit) cache.clear();
29
+ cache.set(key, result);
30
+ return result;
31
+ }
21
32
  /**
22
33
  * Converts `text` to camelCase.
23
34
  *
@@ -220,29 +231,16 @@ function stringify(value) {
220
231
  return `'${JSON.stringify(trimQuotes(value.toString())).slice(1, -1).replace(/\\"/g, "\"").replace(/'/g, "\\'")}'`;
221
232
  }
222
233
  /**
223
- * Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
224
- * and the Unicode line terminators U+2028 and U+2029.
225
- *
226
- * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
234
+ * Escapes an `@` at the start of a line, so a multi-line description can't start a new JSDoc tag.
235
+ * Editors render `\@` as `@` in hovers.
227
236
  *
228
237
  * @example
229
238
  * ```ts
230
- * jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
239
+ * jsDocEscape('intro\n@example value') // 'intro\n\\@example value'
231
240
  * ```
232
241
  */
233
- function jsStringEscape(input) {
234
- return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
235
- switch (character) {
236
- case "\"":
237
- case "'":
238
- case "\\": return `\\${character}`;
239
- case "\n": return "\\n";
240
- case "\r": return "\\r";
241
- case "\u2028": return "\\u2028";
242
- case "\u2029": return "\\u2029";
243
- default: return "";
244
- }
245
- });
242
+ function jsDocEscape(input) {
243
+ return `${input}`.replace(/^(\s*)@/gm, "$1\\@");
246
244
  }
247
245
  /**
248
246
  * Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
@@ -520,7 +518,7 @@ function Faker({ node, description, name, typeName, printer, canOverride, typeMo
520
518
  children: /* @__PURE__ */ jsx(Function, {
521
519
  export: true,
522
520
  name,
523
- JSDoc: { comments: description ? [`@description ${jsStringEscape(description)}`] : [] },
521
+ JSDoc: { comments: description ? [`@description ${jsDocEscape(description)}`] : [] },
524
522
  params: canOverride ? paramsSignature : void 0,
525
523
  returnType: returnType ?? void 0,
526
524
  children: `return ${returnExpression}`
@@ -550,7 +548,7 @@ return {
550
548
  children: /* @__PURE__ */ jsx(Function, {
551
549
  export: true,
552
550
  name,
553
- JSDoc: { comments: description ? [`@description ${jsStringEscape(description)}`] : [] },
551
+ JSDoc: { comments: description ? [`@description ${jsDocEscape(description)}`] : [] },
554
552
  generics: typeMode === "schema" ? void 0 : `TData extends Partial<${typeName}> = object`,
555
553
  params: typeMode === "schema" ? `data?: Partial<${typeName}>` : "data?: TData",
556
554
  returnType: typeMode === "schema" ? typeName : void 0,
@@ -1394,11 +1392,11 @@ const fakerGenerator = defineGenerator({
1394
1392
  //#region kubb-extension.json
1395
1393
  var compatibility = {
1396
1394
  "kubb": ">=5.8.3",
1397
- "node": ">=22"
1395
+ "node": ">=22.12"
1398
1396
  };
1399
1397
  //#endregion
1400
1398
  //#region package.json
1401
- var version = "5.1.7";
1399
+ var version = "5.1.10";
1402
1400
  //#endregion
1403
1401
  //#region src/resolvers/resolverFaker.ts
1404
1402
  /**