@schmock/faker 2.2.3 → 2.3.1

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.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +45 -0
  3. package/dist/constants.d.ts +82 -1
  4. package/dist/constants.d.ts.map +1 -1
  5. package/dist/field-mappings.d.ts.map +1 -1
  6. package/dist/field-name-matcher.d.ts +19 -0
  7. package/dist/field-name-matcher.d.ts.map +1 -1
  8. package/dist/index.d.ts +3 -0
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +4 -1
  11. package/dist/jsf-config.d.ts +27 -2
  12. package/dist/jsf-config.d.ts.map +1 -1
  13. package/dist/output-limits.d.ts +3 -0
  14. package/dist/output-limits.d.ts.map +1 -0
  15. package/dist/overrides.d.ts +2 -1
  16. package/dist/overrides.d.ts.map +1 -1
  17. package/dist/schema-children.d.ts +14 -0
  18. package/dist/schema-children.d.ts.map +1 -0
  19. package/dist/schema-enhancement.d.ts +1 -0
  20. package/dist/schema-enhancement.d.ts.map +1 -1
  21. package/dist/validation.d.ts +24 -5
  22. package/dist/validation.d.ts.map +1 -1
  23. package/package.json +19 -9
  24. package/dist/constants.js +0 -8
  25. package/dist/field-mappings.js +0 -1107
  26. package/dist/field-name-matcher.js +0 -149
  27. package/dist/jsf-config.js +0 -35
  28. package/dist/overrides.js +0 -131
  29. package/dist/schema-enhancement.js +0 -89
  30. package/dist/test-utils.d.ts +0 -57
  31. package/dist/test-utils.d.ts.map +0 -1
  32. package/dist/test-utils.js +0 -271
  33. package/dist/validation.js +0 -300
  34. package/src/advanced-features.test.ts +0 -912
  35. package/src/audit-faker-args.test.ts +0 -97
  36. package/src/constants.d.ts.map +0 -1
  37. package/src/constants.ts +0 -9
  38. package/src/data-quality.test.ts +0 -415
  39. package/src/error-handling.test.ts +0 -504
  40. package/src/field-mappings.test.ts +0 -351
  41. package/src/field-mappings.ts +0 -1141
  42. package/src/field-name-matcher.test.ts +0 -292
  43. package/src/field-name-matcher.ts +0 -188
  44. package/src/index.d.ts.map +0 -1
  45. package/src/index.test.ts +0 -1218
  46. package/src/index.ts +0 -168
  47. package/src/integration.test.ts +0 -634
  48. package/src/jsf-config.d.ts.map +0 -1
  49. package/src/jsf-config.ts +0 -48
  50. package/src/overrides.d.ts.map +0 -1
  51. package/src/overrides.property.test.ts +0 -172
  52. package/src/overrides.test.ts +0 -38
  53. package/src/overrides.ts +0 -176
  54. package/src/performance.test.ts +0 -494
  55. package/src/plugin-integration.test.ts +0 -575
  56. package/src/post-process.test.ts +0 -151
  57. package/src/real-world.test.ts +0 -636
  58. package/src/schema-enhancement.d.ts.map +0 -1
  59. package/src/schema-enhancement.test.ts +0 -216
  60. package/src/schema-enhancement.ts +0 -128
  61. package/src/steps/deterministic-seeds.steps.ts +0 -35
  62. package/src/steps/faker-plugin.steps.ts +0 -109
  63. package/src/test-utils.ts +0 -365
  64. package/src/validation.d.ts.map +0 -1
  65. package/src/validation.ts +0 -417
@@ -1,271 +0,0 @@
1
- import { expect } from "vitest";
2
- import { generateFromSchema } from "./index";
3
- // Schema Factory Functions
4
- export const schemas = {
5
- simple: {
6
- string: () => ({
7
- type: "string",
8
- }),
9
- number: () => ({
10
- type: "number",
11
- }),
12
- object: (properties = {}) => ({
13
- type: "object",
14
- properties,
15
- }),
16
- array: (items, constraints) => ({
17
- type: "array",
18
- items,
19
- ...constraints,
20
- }),
21
- },
22
- withFaker: (type, fakerMethod) => ({
23
- type,
24
- faker: fakerMethod,
25
- }),
26
- nested: {
27
- deep: (depth, leafSchema = schemas.simple.string()) => {
28
- if (depth <= 0)
29
- return leafSchema;
30
- return {
31
- type: "object",
32
- properties: {
33
- nested: schemas.nested.deep(depth - 1, leafSchema),
34
- },
35
- };
36
- },
37
- wide: (width, propertySchema = schemas.simple.string()) => ({
38
- type: "object",
39
- properties: Object.fromEntries(Array.from({ length: width }, (_, i) => [`prop${i}`, propertySchema])),
40
- }),
41
- },
42
- complex: {
43
- user: () => ({
44
- type: "object",
45
- properties: {
46
- id: { type: "string", format: "uuid" },
47
- email: { type: "string" },
48
- firstName: { type: "string" },
49
- lastName: { type: "string" },
50
- createdAt: { type: "string" },
51
- },
52
- required: ["id", "email"],
53
- }),
54
- apiResponse: () => ({
55
- type: "object",
56
- properties: {
57
- success: { type: "boolean" },
58
- data: {
59
- type: "array",
60
- items: schemas.complex.user(),
61
- },
62
- meta: {
63
- type: "object",
64
- properties: {
65
- page: { type: "number" },
66
- total: { type: "number" },
67
- },
68
- },
69
- },
70
- }),
71
- },
72
- };
73
- // Validation Helpers
74
- export const validators = {
75
- // Check if a field was mapped to a faker method by comparing with unmapped behavior
76
- isFieldMapped: async (fieldName, fieldType = "string") => {
77
- const mappedSchema = {
78
- type: "object",
79
- properties: {
80
- [fieldName]: { type: fieldType },
81
- },
82
- };
83
- const unmappedSchema = {
84
- type: "object",
85
- properties: {
86
- unmappedRandomField12345: { type: fieldType },
87
- },
88
- };
89
- // Generate multiple samples to check for patterns
90
- const mappedSamples = [];
91
- for (let i = 0; i < 10; i++) {
92
- const result = (await generateFromSchema({
93
- schema: mappedSchema,
94
- }));
95
- mappedSamples.push(result[fieldName]);
96
- }
97
- const unmappedSamples = [];
98
- for (let i = 0; i < 10; i++) {
99
- const result = (await generateFromSchema({
100
- schema: unmappedSchema,
101
- }));
102
- unmappedSamples.push(result.unmappedRandomField12345);
103
- }
104
- // If field is mapped to a specific faker method, it should have different characteristics
105
- // than the generic unmapped field
106
- return (analyzeDataCharacteristics(mappedSamples) !==
107
- analyzeDataCharacteristics(unmappedSamples));
108
- },
109
- // Analyze uniqueness of generated data
110
- uniquenessRatio: (samples) => {
111
- const unique = new Set(samples);
112
- return unique.size / samples.length;
113
- },
114
- // Check if all samples match a basic pattern without being too specific
115
- allMatch: (samples, validator) => {
116
- return samples.every(validator);
117
- },
118
- // Check if data appears to be from a specific faker category
119
- appearsToBeFromCategory: (samples, category) => {
120
- switch (category) {
121
- case "email":
122
- return validators.allMatch(samples, (s) => typeof s === "string" && s.includes("@") && s.includes("."));
123
- case "name":
124
- return validators.allMatch(samples, (s) => typeof s === "string" &&
125
- s.length > 1 &&
126
- s.length < 50 &&
127
- /^[A-Z]/.test(s));
128
- case "phone":
129
- return validators.allMatch(samples, (s) => typeof s === "string" && /\d/.test(s) && s.length > 10);
130
- case "address":
131
- return validators.allMatch(samples, (s) => typeof s === "string" &&
132
- s.length > 10 &&
133
- /\d/.test(s) &&
134
- /[A-Z]/.test(s));
135
- case "uuid":
136
- return validators.allMatch(samples, (s) => typeof s === "string" &&
137
- /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s));
138
- case "date":
139
- return validators.allMatch(samples, (s) => typeof s === "string" && !Number.isNaN(Date.parse(s)));
140
- default:
141
- return false;
142
- }
143
- },
144
- };
145
- // Performance Testing Utilities
146
- export const performance = {
147
- measure: async (fn) => {
148
- const start = Date.now();
149
- const result = await fn();
150
- const duration = Date.now() - start;
151
- return { result, duration };
152
- },
153
- measureMemory: (fn) => {
154
- if (globalThis.gc) {
155
- globalThis.gc();
156
- }
157
- const before = process.memoryUsage().heapUsed;
158
- fn();
159
- const after = process.memoryUsage().heapUsed;
160
- return after - before;
161
- },
162
- benchmark: async (_name, fn, iterations = 100) => {
163
- const times = [];
164
- for (let i = 0; i < iterations; i++) {
165
- const start = Date.now();
166
- await fn();
167
- const duration = Date.now() - start;
168
- times.push(duration);
169
- }
170
- return {
171
- mean: times.reduce((a, b) => a + b, 0) / times.length,
172
- min: Math.min(...times),
173
- max: Math.max(...times),
174
- };
175
- },
176
- };
177
- // Test Data Generators
178
- export const generate = {
179
- samples: async (schema, count = 10, options) => {
180
- const results = [];
181
- for (let i = 0; i < count; i++) {
182
- results.push((await generateFromSchema({ schema, ...options })));
183
- }
184
- return results;
185
- },
186
- withSeed: async (schema, _seed) => {
187
- // Note: faker.js doesn't support seeding in the same way,
188
- // but we can at least ensure consistent test behavior
189
- return await generateFromSchema({ schema });
190
- },
191
- };
192
- // Statistical Analysis
193
- export const stats = {
194
- distribution: (samples) => {
195
- const dist = new Map();
196
- for (const sample of samples) {
197
- const key = JSON.stringify(sample);
198
- dist.set(key, (dist.get(key) || 0) + 1);
199
- }
200
- return dist;
201
- },
202
- entropy: (samples) => {
203
- const dist = stats.distribution(samples);
204
- const total = samples.length;
205
- let entropy = 0;
206
- for (const count of dist.values()) {
207
- const p = count / total;
208
- if (p > 0) {
209
- entropy -= p * Math.log2(p);
210
- }
211
- }
212
- return entropy;
213
- },
214
- };
215
- // Schema Validation Test Helpers
216
- export const schemaTests = {
217
- expectValid: async (schema) => {
218
- await expect(generateFromSchema({ schema })).resolves.not.toThrow();
219
- },
220
- expectInvalid: async (schema, errorMessage) => {
221
- if (errorMessage) {
222
- await expect(generateFromSchema({ schema })).rejects.toThrow(errorMessage);
223
- }
224
- else {
225
- await expect(generateFromSchema({ schema })).rejects.toThrow();
226
- }
227
- },
228
- expectSchemaError: async (schema, path, issue) => {
229
- try {
230
- await generateFromSchema({ schema });
231
- throw new Error("Expected schema validation to fail");
232
- }
233
- catch (error) {
234
- expect(error.name).toBe("SchemaValidationError");
235
- // The schemaPath is in the context
236
- if (error.context?.schemaPath) {
237
- expect(error.context.schemaPath).toBe(path);
238
- }
239
- if (issue) {
240
- expect(error.message).toContain(issue);
241
- }
242
- }
243
- },
244
- };
245
- // Helper to analyze data characteristics without hardcoding patterns
246
- function analyzeDataCharacteristics(samples) {
247
- if (samples.length === 0)
248
- return "empty";
249
- const first = samples[0];
250
- const type = typeof first;
251
- if (type !== "string")
252
- return type;
253
- // Analyze string characteristics
254
- const characteristics = [type];
255
- // Check common patterns without being too specific
256
- if (samples.every((s) => s.includes("@")))
257
- characteristics.push("has-at");
258
- if (samples.every((s) => /^\d+$/.test(s)))
259
- characteristics.push("numeric");
260
- if (samples.every((s) => /^[0-9a-f-]+$/i.test(s)))
261
- characteristics.push("hex-like");
262
- if (samples.every((s) => s.length > 50))
263
- characteristics.push("long");
264
- if (samples.every((s) => s.length < 10))
265
- characteristics.push("short");
266
- if (validators.uniquenessRatio(samples) > 0.8)
267
- characteristics.push("high-entropy");
268
- if (validators.uniquenessRatio(samples) < 0.2)
269
- characteristics.push("low-entropy");
270
- return characteristics.join("-");
271
- }
@@ -1,300 +0,0 @@
1
- import { ResourceLimitError, SchemaValidationError } from "@schmock/core";
2
- import { DEEP_NESTING_THRESHOLD, DEFAULT_ARRAY_COUNT, LARGE_ARRAY_THRESHOLD, MAX_ARRAY_SIZE, MAX_NESTING_DEPTH, } from "./constants.js";
3
- import { createFakerInstance } from "./jsf-config.js";
4
- let validationFaker;
5
- export function isJSONSchema7(value) {
6
- return typeof value === "object" && value !== null && !Array.isArray(value);
7
- }
8
- /**
9
- * Validate JSON Schema structure and enforce resource limits
10
- * Checks for malformed schemas, circular references, excessive nesting,
11
- * and dangerous patterns that could cause memory issues
12
- * @param schema - JSON Schema to validate
13
- * @param path - Current path in schema tree (for error messages)
14
- * @throws {SchemaValidationError} When schema structure is invalid
15
- * @throws {ResourceLimitError} When schema exceeds safety limits
16
- */
17
- export function validateSchema(schema, path = "$") {
18
- if (!schema || typeof schema !== "object") {
19
- throw new SchemaValidationError(path, "Schema must be a valid JSON Schema object");
20
- }
21
- if (Object.keys(schema).length === 0) {
22
- throw new SchemaValidationError(path, "Schema cannot be empty");
23
- }
24
- // Check for invalid schema types
25
- const validTypes = [
26
- "object",
27
- "array",
28
- "string",
29
- "number",
30
- "integer",
31
- "boolean",
32
- "null",
33
- ];
34
- if (schema.type &&
35
- typeof schema.type === "string" &&
36
- !validTypes.includes(schema.type)) {
37
- throw new SchemaValidationError(path, `Invalid schema type: "${schema.type}"`, "Supported types are: object, array, string, number, integer, boolean, null");
38
- }
39
- // Check for malformed properties (must be object, not string)
40
- if (schema.type === "object" && schema.properties) {
41
- if (typeof schema.properties !== "object" ||
42
- Array.isArray(schema.properties)) {
43
- throw new SchemaValidationError(`${path}.properties`, "Properties must be an object mapping property names to schemas", 'Use { "propertyName": { "type": "string" } } format');
44
- }
45
- // Validate each property recursively
46
- for (const [propName, propSchema] of Object.entries(schema.properties)) {
47
- if (typeof propSchema === "object" && propSchema !== null) {
48
- // Check for invalid faker methods in property schemas
49
- const fakerProp = "faker" in propSchema ? String(propSchema.faker) : undefined;
50
- if (fakerProp) {
51
- try {
52
- validateFakerMethod(fakerProp);
53
- }
54
- catch (error) {
55
- // Re-throw with proper path context
56
- if (error instanceof SchemaValidationError) {
57
- const ctx = error.context;
58
- let issue = "Invalid faker method";
59
- let suggestion;
60
- if (ctx && typeof ctx === "object") {
61
- if ("issue" in ctx && typeof ctx.issue === "string")
62
- issue = ctx.issue;
63
- if ("suggestion" in ctx && typeof ctx.suggestion === "string")
64
- suggestion = ctx.suggestion;
65
- }
66
- throw new SchemaValidationError(`${path}.properties.${propName}.faker`, issue, suggestion);
67
- }
68
- if (error instanceof Error)
69
- throw error;
70
- throw new Error(String(error));
71
- }
72
- }
73
- validateSchema(propSchema, `${path}.properties.${propName}`);
74
- }
75
- }
76
- }
77
- // Check for invalid array items
78
- if (schema.type === "array") {
79
- // Array must have items defined and non-null
80
- if (schema.items === null || schema.items === undefined) {
81
- throw new SchemaValidationError(`${path}.items`, "Array schema must have valid items definition", "Define items as a schema object or array of schemas");
82
- }
83
- if (Array.isArray(schema.items)) {
84
- if (schema.items.length === 0) {
85
- throw new SchemaValidationError(`${path}.items`, "Array items cannot be empty array", "Provide at least one item schema");
86
- }
87
- schema.items.forEach((item, index) => {
88
- if (typeof item === "object" && item !== null) {
89
- validateSchema(item, `${path}.items[${index}]`);
90
- }
91
- });
92
- }
93
- else if (typeof schema.items === "object" && schema.items !== null) {
94
- validateSchema(schema.items, `${path}.items`);
95
- }
96
- }
97
- // Full-tree integrity checks are O(n) each, so only run them once at the
98
- // top of the recursion. Running them at every node turns validation into
99
- // O(n²) on deep schemas without finding anything the top-level pass misses.
100
- // The self-ref/$ref="#" check is part of this group so that an inner $ref
101
- // is reported as "circular references" (caught by hasCircularReference at
102
- // the root), matching the legacy error message.
103
- if (path === "$") {
104
- if (hasCircularReference(schema)) {
105
- throw new SchemaValidationError(path, "Schema contains circular references which are not supported");
106
- }
107
- if (schema.$ref === "#") {
108
- throw new SchemaValidationError(path, "Self-referencing schemas are not supported");
109
- }
110
- const depth = calculateNestingDepth(schema);
111
- if (depth > MAX_NESTING_DEPTH) {
112
- throw new ResourceLimitError("schema_nesting_depth", MAX_NESTING_DEPTH, depth);
113
- }
114
- if (depth >= DEEP_NESTING_THRESHOLD) {
115
- checkForDeepNestingWithArrays(schema, path);
116
- }
117
- checkArraySizeLimits(schema, path);
118
- }
119
- }
120
- /**
121
- * Detect circular references in JSON Schema using path-based traversal
122
- * Uses backtracking to distinguish between cycles and legitimate schema reuse
123
- * @param schema - Schema to check for cycles
124
- * @param currentPath - Set of schemas currently in traversal path
125
- * @returns true if circular reference detected, false otherwise
126
- * @example
127
- * // Detects: schema A -> B -> A (cycle)
128
- * // Allows: schema A -> B, A -> C (reuse of A)
129
- */
130
- function hasCircularReference(schema, currentPath = new Set()) {
131
- // Check if this schema is currently being traversed (cycle detected)
132
- if (currentPath.has(schema)) {
133
- return true;
134
- }
135
- if (schema.$ref === "#") {
136
- return true;
137
- }
138
- // Add to current path for this traversal branch
139
- currentPath.add(schema);
140
- if (schema.type === "object" && schema.properties) {
141
- for (const prop of Object.values(schema.properties)) {
142
- if (isJSONSchema7(prop)) {
143
- if (hasCircularReference(prop, currentPath)) {
144
- return true;
145
- }
146
- }
147
- }
148
- }
149
- if (schema.type === "array" && schema.items) {
150
- const items = Array.isArray(schema.items) ? schema.items : [schema.items];
151
- for (const item of items) {
152
- if (isJSONSchema7(item)) {
153
- if (hasCircularReference(item, currentPath)) {
154
- return true;
155
- }
156
- }
157
- }
158
- }
159
- // Remove from current path after checking all children (backtrack)
160
- currentPath.delete(schema);
161
- return false;
162
- }
163
- /**
164
- * Calculate maximum nesting depth of a JSON Schema
165
- * Recursively traverses object properties and array items
166
- * @param schema - Schema to measure
167
- * @param depth - Current depth (internal recursion parameter)
168
- * @returns Maximum nesting depth found
169
- */
170
- function calculateNestingDepth(schema, depth = 0) {
171
- if (depth > MAX_NESTING_DEPTH) {
172
- return depth;
173
- }
174
- let maxDepth = depth;
175
- if (schema.type === "object" && schema.properties) {
176
- for (const prop of Object.values(schema.properties)) {
177
- if (isJSONSchema7(prop)) {
178
- maxDepth = Math.max(maxDepth, calculateNestingDepth(prop, depth + 1));
179
- }
180
- }
181
- }
182
- if (schema.type === "array" && schema.items) {
183
- const items = Array.isArray(schema.items) ? schema.items : [schema.items];
184
- for (const item of items) {
185
- if (isJSONSchema7(item)) {
186
- maxDepth = Math.max(maxDepth, calculateNestingDepth(item, depth + 1));
187
- }
188
- }
189
- }
190
- return maxDepth;
191
- }
192
- /**
193
- * Check for dangerous patterns of deep nesting combined with large arrays
194
- * Prevents memory issues from schemas like: depth 3+ with 100+ item arrays
195
- * @param schema - Schema to check
196
- * @param _path - Path in schema (unused but kept for signature consistency)
197
- * @throws {ResourceLimitError} When dangerous nesting pattern detected
198
- */
199
- function checkForDeepNestingWithArrays(schema, _path) {
200
- // Look for arrays in deeply nested structures that could cause memory issues
201
- function findArraysInDeepNesting(node, currentDepth) {
202
- const schemaType = node.type;
203
- const isArray = Array.isArray(schemaType)
204
- ? schemaType.includes("array")
205
- : schemaType === "array";
206
- if (isArray) {
207
- const maxItems = node.maxItems || DEFAULT_ARRAY_COUNT;
208
- // Be more aggressive about deep nesting detection
209
- if (currentDepth >= DEEP_NESTING_THRESHOLD &&
210
- maxItems >= LARGE_ARRAY_THRESHOLD) {
211
- throw new ResourceLimitError("deep_nesting_memory_risk", DEEP_NESTING_THRESHOLD * LARGE_ARRAY_THRESHOLD, currentDepth * maxItems);
212
- }
213
- // Check items if they exist
214
- if (node.items) {
215
- const items = Array.isArray(node.items) ? node.items : [node.items];
216
- for (const item of items) {
217
- if (isJSONSchema7(item)) {
218
- findArraysInDeepNesting(item, currentDepth + 1);
219
- }
220
- }
221
- }
222
- return;
223
- }
224
- if (schemaType === "object" && node.properties) {
225
- for (const prop of Object.values(node.properties)) {
226
- if (isJSONSchema7(prop)) {
227
- findArraysInDeepNesting(prop, currentDepth + 1);
228
- }
229
- }
230
- }
231
- }
232
- findArraysInDeepNesting(schema, 0);
233
- }
234
- function checkArraySizeLimits(schema, path) {
235
- // Recursively check all array constraints in the schema
236
- if (schema.type === "array") {
237
- // Check for dangerously large maxItems
238
- if (schema.maxItems && schema.maxItems > MAX_ARRAY_SIZE) {
239
- throw new ResourceLimitError("array_max_items", MAX_ARRAY_SIZE, schema.maxItems);
240
- }
241
- // Check for combination of deep nesting and large arrays
242
- const depth = calculateNestingDepth(schema);
243
- const estimatedSize = schema.maxItems || schema.minItems || DEFAULT_ARRAY_COUNT;
244
- // If we have deep nesting and large arrays, it could cause memory issues
245
- if (depth > DEEP_NESTING_THRESHOLD &&
246
- estimatedSize > LARGE_ARRAY_THRESHOLD) {
247
- throw new ResourceLimitError("memory_estimation", DEEP_NESTING_THRESHOLD * LARGE_ARRAY_THRESHOLD, depth * estimatedSize);
248
- }
249
- }
250
- // Recursively check nested schemas
251
- if (schema.type === "object" && schema.properties) {
252
- for (const [propName, propSchema] of Object.entries(schema.properties)) {
253
- if (isJSONSchema7(propSchema)) {
254
- checkArraySizeLimits(propSchema, `${path}.properties.${propName}`);
255
- }
256
- }
257
- }
258
- if (schema.type === "array" && schema.items) {
259
- if (Array.isArray(schema.items)) {
260
- schema.items.forEach((item, index) => {
261
- if (isJSONSchema7(item)) {
262
- checkArraySizeLimits(item, `${path}.items[${index}]`);
263
- }
264
- });
265
- }
266
- else if (isJSONSchema7(schema.items)) {
267
- checkArraySizeLimits(schema.items, `${path}.items`);
268
- }
269
- }
270
- }
271
- /**
272
- * Validate that faker method string references a valid Faker.js API
273
- * Checks format (namespace.method) and validates against known namespaces
274
- * @param fakerMethod - Faker method string (e.g., "person.fullName")
275
- * @throws {SchemaValidationError} When faker method format or namespace is invalid
276
- */
277
- export function validateFakerMethod(fakerMethod) {
278
- // Check if faker method follows valid format (namespace.method)
279
- const parts = fakerMethod.split(".");
280
- if (parts.length < 2) {
281
- throw new SchemaValidationError("$.faker", `Invalid faker method format: "${fakerMethod}"`, "Use format like 'person.firstName' or 'internet.email'");
282
- }
283
- // Validate by resolving the method path on a cached faker instance
284
- if (!validationFaker) {
285
- validationFaker = createFakerInstance();
286
- }
287
- const faker = validationFaker;
288
- let current = faker;
289
- for (const part of parts) {
290
- if (current && typeof current === "object" && part in current) {
291
- current = current[part];
292
- }
293
- else {
294
- throw new SchemaValidationError("$.faker", `Invalid faker method: "${fakerMethod}"`, "Check faker.js documentation for valid methods");
295
- }
296
- }
297
- if (typeof current !== "function") {
298
- throw new SchemaValidationError("$.faker", `Invalid faker method: "${fakerMethod}" is not a function`, "Check faker.js documentation for valid methods");
299
- }
300
- }