faker-schema skill

## When to use

7 stars

Best use case

faker-schema skill is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

## When to use

Teams using faker-schema skill should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/faker-schema/SKILL.md --create-dirs "https://raw.githubusercontent.com/heldernoid/agentic-build-templates/main/projects/developer-tools/db-seed-generator/skills/faker-schema/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/faker-schema/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How faker-schema skill Compares

Feature / Agentfaker-schema skillStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

## When to use

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# faker-schema skill

## When to use

Use this skill when implementing or modifying the faker dispatch table, schema parser, validation logic, or generation engine in db-seed-generator.

## Faker dispatch table

The dispatch table maps a string type key to a function that returns a generated value. It is the single source of truth for supported types.

```typescript
// packages/core/src/faker-map.ts
import { faker } from '@faker-js/faker';

type FakerFn = (options?: Record<string, unknown>) => unknown;

export const FAKER_MAP: Record<string, FakerFn> = {
  'uuid': () => faker.string.uuid(),
  // ... all entries
};
```

Rules:
- Never call faker methods via string eval or dynamic property access on the faker object.
- Always add new types as a new key in `FAKER_MAP`. Do not use `if/switch` chains for dispatch.
- The `options` object from the YAML is passed as-is to the faker call. Validate allowed option keys per type in `validate.ts`, not in `faker-map.ts`.
- `enum` is a special type: the dispatcher returns an empty string as a placeholder. The generator resolves it by calling `faker.helpers.arrayElement(field.values)`.

## Schema structure

```typescript
interface FieldDef {
  name: string;           // must match /^[a-z_][a-z0-9_]*$/i
  type: string;           // key in FAKER_MAP or 'enum'
  options?: Record<string, unknown>;
  nullable?: number;      // 0-100, default 0
  unique?: boolean;       // default false
  values?: string[];      // required for type 'enum'
}

interface SchemaDef {
  table: string;          // must match /^[a-z_][a-z0-9_]*$/i
  count: number;          // 1 to SEED_MAX_COUNT
  seed?: number;          // optional, integer
  format?: OutputFormat | OutputFormat[];
  fields: FieldDef[];     // at least 1 field
}
```

## Validation rules

All rules are enforced in `packages/core/src/validate.ts`. Validation returns `{ ok: boolean; errors: string[] }`.

1. `table` must be a non-empty string matching `/^[a-z_][a-z0-9_]*$/i`.
2. `count` must be a positive integer at or below `maxCount`.
3. `fields` must be a non-empty array.
4. Each `field.name` must match the table name regex. Names must be unique across the schema.
5. Each `field.type` must be a key in `FAKER_MAP` or equal `'enum'`.
6. Fields with `type: 'enum'` must have a non-empty `values` array of strings.
7. `nullable` must be 0-100 if present.
8. `unique` must be boolean if present.
9. Allowed option keys per type are validated against a whitelist map. Unknown options produce a warning (not an error) and are silently dropped before generation.

## Generation loop

```typescript
// Pseudocode for generate()
faker.seed(seed);

const resolvers = schema.fields.map(field => buildResolver(field));

const records: Record<string, unknown>[] = [];
const uniqueSets = new Map<string, Set<unknown>>();

for (let i = 0; i < schema.count; i++) {
  const record: Record<string, unknown> = {};
  for (let j = 0; j < schema.fields.length; j++) {
    const field = schema.fields[j];
    const resolve = resolvers[j];
    let value: unknown;

    if (field.unique) {
      const seen = uniqueSets.get(field.name) ?? new Set();
      let attempts = 0;
      do {
        value = resolve();
        attempts++;
        if (attempts > 10) throw new Error(`Could not generate unique value for field "${field.name}" after 10 attempts`);
      } while (seen.has(value));
      seen.add(value);
      uniqueSets.set(field.name, seen);
    } else if (field.nullable && Math.random() * 100 < field.nullable) {
      value = null;
    } else {
      value = resolve();
    }

    record[field.name] = value;
  }
  records.push(record);
}
```

Key constraints:
- `faker.seed()` is called once before the loop, never inside.
- Nullable and unique are mutually exclusive: `unique` takes precedence if both are set.
- The resolver for `enum` calls `faker.helpers.arrayElement(field.values)`.

## SQL writer value escaping

```typescript
function escapeValue(value: unknown): string {
  if (value === null || value === undefined) return 'NULL';
  if (typeof value === 'boolean') return value ? '1' : '0';
  if (typeof value === 'number') return String(value);
  const str = String(value);
  return `'${str.replace(/'/g, "''")}'`;
}
```

Never use template literal interpolation for SQL values. Always use `escapeValue`.

## Atomic file write pattern

```typescript
import { writeFile, rename } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { randomBytes } from 'node:crypto';
import { mkdir } from 'node:fs/promises';

async function writeAtomic(filePath: string, content: string): Promise<void> {
  await mkdir(dirname(filePath), { recursive: true });
  const tmp = filePath + '.' + randomBytes(6).toString('hex') + '.tmp';
  await writeFile(tmp, content, 'utf8');
  await rename(tmp, filePath);
}
```

Always use this pattern for all output file writes. Never write directly to the final path.

## Path traversal guard

```typescript
import { resolve } from 'node:path';

function guardOutputPath(outputDir: string, filename: string): string {
  const base = resolve(outputDir);
  const full = resolve(outputDir, filename);
  if (!full.startsWith(base + '/') && full !== base) {
    throw new Error(`Output path "${full}" escapes output directory "${base}"`);
  }
  return full;
}
```

Call `guardOutputPath` for every output file path before writing.

## Adding a new faker type

1. Add an entry to `FAKER_MAP` in `packages/core/src/faker-map.ts`.
2. Add the allowed option keys to the whitelist map in `packages/core/src/validate.ts`.
3. Add the type to the category lookup in `packages/web/src/components/FieldTypeTag.tsx`.
4. Add a unit test in `packages/core/src/faker-map.test.ts`.
5. Add an example row to `packages/core/src/types-reference.ts` (used by `db-seed types` CLI command and the dashboard types reference page).

Do not modify any other files to add a type.

## Common pitfalls

- Do not call `faker.fake()` - it uses deprecated template syntax and is removed in faker v9+.
- Do not call `faker.seed()` inside the record loop - this resets the PRNG and produces non-deterministic sequences.
- Do not generate values after calling `faker.seed()` in any setup code before the generation loop - any faker call between `seed()` and the loop will shift the PRNG state and break reproducibility.
- `null` in JavaScript becomes `NULL` in SQL - not the string `'null'` or `'NULL'`.
- Boolean `true`/`false` must become `1`/`0` in SQL output.
- Date fields return ISO 8601 strings from faker - never Date objects.
- `unique: true` on a boolean field will fail after 2 rows if count > 2. Validate this combination in `validate.ts`.

Related Skills

schema-generate

7
from heldernoid/agentic-build-templates

Generate TypeScript types from JSON Schema, OpenAPI specs, and SQLite databases using the s2t CLI

sql-schema-parser skill

7
from heldernoid/agentic-build-templates

## When to use

manage-schemas

7
from heldernoid/agentic-build-templates

Create, update, and delete JSON Schema definitions in config-validator. Use when you need to add a new schema for a config file type, update a schema after adding required fields, list available schemas, or remove an obsolete schema. Triggers include "add schema", "create validation schema", "update schema", "list schemas", "delete schema", "manage validation rules", or any task involving the JSON Schema definitions used by config-validator.

faker-templates

7
from heldernoid/agentic-build-templates

Reference for Faker.js template helpers available in api-mock-server response body definitions. Use when building YAML config files for api-mock-server and you need to know which faker helpers are available, what they produce, or how to use dynamic values from request context.

Skill: Uptime Monitoring

7
from heldernoid/agentic-build-templates

## Overview

Skill: Status Page

7
from heldernoid/agentic-build-templates

## Overview

Skill: unit-conversion

7
from heldernoid/agentic-build-templates

## Overview

Skill: recipe-scaler

7
from heldernoid/agentic-build-templates

## Overview

reading-list

7
from heldernoid/agentic-build-templates

Operate the reading-list API to save, manage, tag, search, and export articles.

email-digest

7
from heldernoid/agentic-build-templates

Configure, test, and troubleshoot the reading-list daily email digest delivered via nodemailer.

websocket-realtime

7
from heldernoid/agentic-build-templates

Use the WebSocket connection in poll-builder to receive live vote updates. Use when you need to stream real-time poll results, monitor a poll for new votes, or build a live dashboard. Triggers include "live results", "real-time updates", "stream votes", "watch poll", or "WebSocket".

poll-builder

7
from heldernoid/agentic-build-templates

Self-hosted poll creation tool with real-time results. Use when you need to create a poll, check vote counts, close a poll, export results, or get the shareable link for a poll. Triggers include "create poll", "vote", "poll results", "survey", "collect votes", "share poll", or any task involving polling or voting.