fakerjs

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 11 Imported by: 0

README

go-fakerjs

go-fakerjs runs the Faker.js package inside a JavaScript interpreter that is compiled into your Go binary, so you can generate seed-reproducible fake data in Go. It doesn't need cgo, a Wasm runtime, or any third-party dependency, and its output is byte-identical to Faker.js on V8 across the tested surface.

CI Go Reference

Why it exists

I wanted seed-reproducible fake data in Go that matches Faker.js exactly, without cgo. Reimplementing Faker in Go wouldn't match its output byte for byte, and embedding V8 needs cgo and a prebuilt library for each platform, so go-fakerjs runs Faker.js itself, translated to Go.

Install

go get github.com/iamramtin/go-fakerjs

Requires Go 1.27.1 or later (go.mod). The generated code is committed, so no build step or toolchain is needed.

Quickstart

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/iamramtin/go-fakerjs"
)

func main() {
	// A fixed seed and reference date make the output reproducible, including date methods.
	e := fakerjs.NewEngine(42, fakerjs.WithRefDate(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)))
	defer e.Close()

	name, err := e.Generate("person.firstName", nil) // nil calls the method with no argument
	if err != nil {
		log.Fatal(err)
	}

	codes, err := e.GenerateN("string.alpha", map[string]any{"length": 8}, 3) // the argument is JSON-encoded
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(name, codes)
}
  • NewEngine(seed, opts...) starts lazily on the first call. Seed 0 leaves Faker on its own random seed.
  • GenerateN returns the same values as n calls to Generate, in one call into the engine.
  • NewPool(size, seed, opts...) runs engines in parallel; engine i is seeded with DeriveSeed(seed, i).
  • WithTimeout (default 30 s) and WithMaxArgBytes (default 4 MiB) bound each call. Unknown methods fail with ClassUnknownMethod.

More: usage examples and the package documentation.

Compatibility

go-fakerjs Faker.js Oracle
v0.1.0 10.6.0 (en locale) Node 22.23.3 (V8 12.4), TZ=UTC

The Faker.js version has one source of truth, and make check-versions fails if any other statement of it disagrees.

  • Identical output to Faker.js on V8 for the tested surface when run with TZ=UTC: 262 methods, with 2,235 of 2,240 per-method cases exact, and all 220 workload cases and all 3 interleaved sequences exact.
  • Known divergences: one method, finance.amount with autoFormat, which needs Intl. Every divergence and its root cause is listed in the divergence catalogue.
  • Time zone: dates print the UTC zone name. Under any other TZ, V8's text differs.
  • Locales: en only. Locale selection isn't built.

Performance

The trade-off is throughput. QuickJS interprets Faker's JavaScript, whereas V8 compiles it, so each call is slower than on V8.

v8go go-fakerjs wazero + QuickJS
How the JavaScript runs V8 with its JIT, through cgo QuickJS-NG bytecode interpreter, compiled to Wasm and translated to Go QuickJS-NG compiled to Wasm, run by the wazero runtime
Engine startup (first value included) 4.75 ms 0.31 ms 23.4 ms
Average time per fake value (20-column row, one call per value) 1.97 µs 23.8 µs 73.8 µs
Rows/s, 20 fake columns, 1 engine 25,339 2,100 677
Rows/s, 20 fake columns, 10 engines 111,128 9,652 727
Output identical to Faker.js V8 itself; not run through the golden suite here yes on the tested surface, 5 Intl divergences 2,135 of 2,240 per-method cases exact; dates differ
cgo / platform limits cgo; prebuilt V8 for linux and darwin (amd64, arm64) and android none: pure Go none: pure Go

Apple M5, darwin/arm64, medians of 10 runs; v8go builds a script per call. These figures come from the final build, measured on 2026-10-20 with the same pinned Faker.js and toolchain as v0.1.0. Per call, go-fakerjs is 1.3× to 55× slower than v8go depending on the method, the 20-column row is 12.1× slower, and startup is 15.2× faster. Baseline conformance was measured on a Linux VM.

Use it for tests, fixtures, and tools that need exact, reproducible Faker.js output, a cgo-free build, or many short-lived engines. Do not use it for bulk generation where throughput per core matters; use V8 there.

How it works

The snapshot is built once per Faker.js release with make snapshot, and the generated files are committed:

  • Bundle. esbuild packs the pinned @faker-js/faker and an entry file into one IIFE, targeting ES2020, with _-prefixed properties mangled.
  • Module. QuickJS-NG and a C harness are compiled with wasi-sdk to a wasm32-wasip1 reactor, which wasm-opt -O2 then optimises. Wizer runs the module's initialisation once, evaluating the bundle, and saves the resulting memory as a snapshot.
  • Translation. wasm2go converts the snapshot into Go source, internal/wasm/snapshot_en.go, with the data segments in snapshot_en.dat. The package builds with CGO_ENABLED=0 and needs no separate Wasm runtime.
  • Engine. A fakerjs.Engine calls into its own copy of the snapshot for each method call, and a fakerjs.Pool hands out engines for concurrent use.
  • Verification. Golden outputs come from three oracles: the npm package, the bundle under Node's vm, and one evaluation per call. Every method and seed must match, unless the difference is listed in the divergence catalogue with its root cause.
flowchart LR
  npm["@faker-js/faker<br/>pinned npm release"] -->|esbuild| bundle["faker.en.min.js"]
  subgraph snapshot ["make snapshot"]
    direction LR
    clang["wasi-sdk clang<br/>QuickJS-NG + harness.c"] --> opt["wasm-opt -O2"]
    opt --> wizer["Wizer<br/>evaluates the bundle once"]
    wizer --> w2g["wasm2go"]
  end
  bundle --> clang
  w2g --> gen["internal/wasm/snapshot_en.go<br/>+ snapshot_en.dat"]

At run time each call crosses from Go into the translated module once:

sequenceDiagram
  participant App as Your code
  participant E as fakerjs.Engine
  participant G as Translated module (QuickJS-NG)
  App->>E: Generate("person.firstName", nil)
  E->>E: check the method name, encode the argument as JSON
  E->>E: lock, start the module on first use, set the deadline
  E->>G: call(method, argument, n)
  G->>G: reject names outside the allowlist
  G->>G: parse the argument, run the Faker method, String() the result
  G-->>E: n strings, or a status and message
  E-->>App: string, or *fakerjs.Error

The findings explain why each stage exists.

Updating Faker.js

Upgrade to the latest minor or patch release, or rehearse an upgrade to a given version without committing anything:

make faker-upgrade
make faker-upgrade FAKER=10.5.0

The upgrade works in a temporary git worktree. It pins the new version, rebuilds the bundle, the golden data, and the snapshot, runs the test suites, and requires two clean builds to be byte-identical. It stops at the first failure. A normal run commits the result on a faker-upgrade/<version> branch and pushes nothing, and a dry run prints the commit message it would use, with the API diff and the conformance counts.

  • Major versions are refused. Upgrade them by hand.
  • New divergences from Faker.js fail the tests unless they are listed in the divergence catalogue with a reason.
  • No newer version exits with a message and changes nothing.

The upgrade guide lists every step and the weekly workflow that runs it.

Documentation

AI assistance

Designed and tested with the help of Claude Opus 5.5.

Credits

Faker.js (MIT), QuickJS-NG (MIT; QuickJS by Fabrice Bellard and Charlie Gordon), wasm2go, Wizer, Binaryen, wasi-sdk, and esbuild. Versions and licences are listed in full.

Licence

Released under the MIT licence. The generated snapshot also contains code under the licences listed in third-party notices.

Documentation

Overview

Package fakerjs runs the real Faker.js (version FakerVersion) from pure Go, with no cgo and no Wasm runtime.

Faker.js and QuickJS-NG are compiled to WebAssembly, pre-initialised with Wizer so the Faker data is already loaded, and translated to Go source by wasm2go. An Engine is one private instance of that translated program.

Status: experimental. The API may change before v1.0.0; see FINDINGS.md for the evidence behind it.

Index

Examples

Constants

View Source
const (
	// ClassInvalidMethod marks a method string that is not a "module.method" reference.
	ClassInvalidMethod = "invalid-method"
	// ClassUnknownMethod marks a well-formed method that is not on the allowlist.
	ClassUnknownMethod = "unknown-method"
	// ClassJSException marks an exception thrown by Faker.js (or by the engine while running it).
	ClassJSException = "js-exception"
	// ClassInvalidArgument marks an argument that is not valid JSON or is too large.
	ClassInvalidArgument = "invalid-argument"
	// ClassResource marks a call stopped by a resource limit: deadline, module memory or result size.
	ClassResource = "resource-limit"
	// ClassEngine marks a failure of the engine itself: closed, poisoned or unable to start.
	ClassEngine = "engine"
)

Error classes reported by Error.Class and by the conformance harness.

View Source
const (
	// DefaultTimeout bounds a single Generate or GenerateN call.
	DefaultTimeout = 30 * time.Second
	// DefaultMaxArgBytes bounds the JSON-encoded argument of a call.
	DefaultMaxArgBytes = 4 << 20
)
View Source
const FakerVersion = "10.6.0"

FakerVersion is the Faker.js release embedded in the snapshot. tools.versions is its source of truth; `make check-versions` fails if the two differ.

Variables

View Source
var (
	// ErrClosed is returned by every call on an engine after Close. A closed engine never restarts.
	ErrClosed = errors.New("engine is closed")
	// ErrPoisoned is returned when a previous call left the module in an unknown state (a trap or a panic
	// in a host import). The engine cannot be repaired without losing its sequence; use a [Pool] or make a
	// new engine.
	ErrPoisoned = errors.New("engine poisoned")
	// ErrDeadline is returned when a call ran past its timeout and was interrupted.
	ErrDeadline = errors.New("faker call exceeded its deadline")
	// ErrOutOfMemory is returned when a call exceeded the module's memory limit.
	ErrOutOfMemory = errors.New("faker call exceeded the Wasm memory limit")
	// ErrResultTooLarge is returned when a call's results exceed the result size limit.
	ErrResultTooLarge = errors.New("faker call result exceeds the size limit")
	// ErrArgTooLarge is returned when a method or argument exceeds the size limit.
	ErrArgTooLarge = errors.New("faker call argument exceeds the size limit")
	// ErrUnknownMethod is returned for a "module.method" that is not an allowlisted Faker method.
	ErrUnknownMethod = errors.New("unknown faker method")
)

Functions

func DeriveSeed

func DeriveSeed(base int64, index int) int64

DeriveSeed returns the seed of engine index in a pool seeded with base: index 0 uses base itself and index i>0 uses base + i*0x9E3779B97F4A7C15 (wrapping int64 arithmetic), skipping 0 so that a derived engine never falls back to Faker's non-deterministic seed. A base of 0 stays 0 for every index.

func IsClass

func IsClass(err error, class string) bool

IsClass reports whether err is an *Error of the given class.

func ValidMethod

func ValidMethod(method string) bool

ValidMethod reports whether method is a "module.method" reference Generate accepts, such as "person.firstName". It checks the format only; whether the module and method exist is decided by the engine's allowlist.

The grammar is ^[a-zA-Z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]*$ . It is implemented without regexp so that "$" cannot match before a trailing newline in any future edit.

Types

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine runs Faker.js methods in a private pre-initialised Wasm instance.

A non-zero seed makes the generated sequence reproducible; a zero seed leaves Faker.js on its own non-deterministic default. The instance is built lazily on the first call and released by Close, which is terminal. An Engine is safe for concurrent use; calls are serialised by an internal mutex.

func NewEngine

func NewEngine(seed int64, opts ...Option) *Engine

NewEngine returns an Engine that seeds Faker.js with seed on its first call. It does no work until then.

Example
package main

import (
	"fmt"
	"time"

	"github.com/iamramtin/go-fakerjs"
)

// refDate is pinned so that date output does not depend on the wall clock.
var refDate = time.Date(2026, 1, 15, 0, 0, 0, 0, time.UTC)

func main() {
	a := fakerjs.NewEngine(42, fakerjs.WithRefDate(refDate))
	defer a.Close()

	b := fakerjs.NewEngine(42, fakerjs.WithRefDate(refDate))
	defer b.Close()

	// The same seed and reference date give the same sequence.
	x, err := a.Generate("person.firstName", nil)
	if err != nil {
		panic(err)
	}

	y, err := b.Generate("person.firstName", nil)
	if err != nil {
		panic(err)
	}

	fmt.Println(x == y)
}
Output:
true

func (*Engine) Close

func (e *Engine) Close()

Close releases the instance. It is safe to call more than once and on an engine that never started.

A closed engine stays closed: every later call fails with ErrClosed instead of building a fresh instance whose sequence would restart from the seed.

func (*Engine) Generate

func (e *Engine) Generate(method string, arg any) (string, error)

Generate runs method and returns its result coerced like JavaScript's String(result).

A nil arg calls the method bare, e.g. Generate("person.fullName", nil). Anything else is marshalled to JSON and passed as the single argument, e.g. Generate("string.alpha", map[string]any{"length": 5}).

Example
package main

import (
	"fmt"

	"github.com/iamramtin/go-fakerjs"
)

func main() {
	e := fakerjs.NewEngine(42)
	defer e.Close()

	// Arguments are JSON-encoded, so a Go map or struct with the same keys works.
	code, err := e.Generate("string.alpha", map[string]any{"length": 8})
	if err != nil {
		panic(err)
	}

	fmt.Println(len(code))
}
Output:
8
Example (Errors)
package main

import (
	"errors"
	"fmt"

	"github.com/iamramtin/go-fakerjs"
)

func main() {
	e := fakerjs.NewEngine(1)
	defer e.Close()

	_, err := e.Generate("person.notAMethod", nil)

	fmt.Println(fakerjs.IsClass(err, fakerjs.ClassUnknownMethod), errors.Is(err, fakerjs.ErrUnknownMethod))
}
Output:
true true

func (*Engine) GenerateN

func (e *Engine) GenerateN(method string, arg any, n int) ([]string, error)

GenerateN returns n consecutive results of method in one boundary crossing. The results equal those of n successive Generate calls with the same arguments.

Example
package main

import (
	"fmt"
	"time"

	"github.com/iamramtin/go-fakerjs"
)

// refDate is pinned so that date output does not depend on the wall clock.
var refDate = time.Date(2026, 1, 15, 0, 0, 0, 0, time.UTC)

func main() {
	e := fakerjs.NewEngine(7, fakerjs.WithRefDate(refDate))
	defer e.Close()

	// One boundary crossing for three values; the result equals three successive Generate calls.
	names, err := e.GenerateN("person.firstName", nil, 3)
	if err != nil {
		panic(err)
	}

	fmt.Println(len(names))
}
Output:
3

func (*Engine) Poisoned

func (e *Engine) Poisoned() bool

Poisoned reports whether a trap or panic has left the engine unusable.

type Error

type Error struct {
	// Class is one of the Class constants.
	Class string
	// Method is the module.method that failed, when known.
	Method string
	// Msg is the engine's description; for ClassJSException it is the JavaScript exception text.
	Msg string
	// Err is the sentinel the failure matches with errors.Is, when there is one.
	Err error
}

Error describes a failed call.

func (*Error) Error

func (e *Error) Error() string

func (*Error) ErrorClass

func (e *Error) ErrorClass() string

ErrorClass implements the interface the conformance harness uses to compare error classes.

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Option

type Option func(*config)

Option configures an Engine or Pool.

func WithClock

func WithClock(now func() time.Time) Option

WithClock replaces the wall clock the module sees through WASI. It exists so tests can prove that output does not depend on the host clock; production code should not need it.

func WithMaxArgBytes

func WithMaxArgBytes(n int) Option

WithMaxArgBytes bounds the JSON-encoded argument of a call; larger arguments fail with ErrArgTooLarge before reaching the module.

func WithRefDate

func WithRefDate(t time.Time) Option

WithRefDate pins Faker's default reference date (faker.setDefaultRefDate). Without it, date.recent, date.past, date.future and friends are relative to the wall clock and are not reproducible across days even with a fixed seed.

Example
package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/iamramtin/go-fakerjs"
)

// refDate is pinned so that date output does not depend on the wall clock.
var refDate = time.Date(2026, 1, 15, 0, 0, 0, 0, time.UTC)

func main() {
	// Without WithRefDate, date.recent is relative to the wall clock and changes from day to day.
	// With it, a seeded engine prints the same date on every run.
	e := fakerjs.NewEngine(42, fakerjs.WithRefDate(refDate))
	defer e.Close()

	when, err := e.Generate("date.recent", map[string]any{"days": 10})
	if err != nil {
		panic(err)
	}

	// The ten days before 15 January 2026 all fall in January 2026.
	fmt.Println(strings.Contains(when, "Jan") && strings.Contains(when, "2026"))
}
Output:
true

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout bounds each Generate and GenerateN call. A call that runs longer is interrupted and fails with ErrDeadline. Zero or negative disables the bound.

type Pool

type Pool struct {
	// contains filtered or unexported fields
}

Pool is a fixed set of engines for parallel generation. Engine i is seeded with DeriveSeed(base, i), so a pool is reproducible as long as each engine is used by one logical stream. An engine that gets poisoned is replaced on Put with a fresh one; the replacement's sequence restarts, so determinism is only guaranteed while no engine is poisoned.

func NewPool

func NewPool(size int, base int64, opts ...Option) *Pool

NewPool returns a pool of size engines (at least 1).

Example
package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/iamramtin/go-fakerjs"
)

// refDate is pinned so that date output does not depend on the wall clock.
var refDate = time.Date(2026, 1, 15, 0, 0, 0, 0, time.UTC)

func main() {
	p := fakerjs.NewPool(4, 42, fakerjs.WithRefDate(refDate))
	defer p.Close()

	// Engine i is seeded with DeriveSeed(42, i). Do borrows an engine for the duration of the function.
	err := p.Do(func(e *fakerjs.Engine) error {
		email, err := e.Generate("internet.email", nil)
		if err != nil {
			return err
		}

		fmt.Println(strings.Contains(email, "@"))

		return nil
	})
	if err != nil {
		panic(err)
	}
}
Output:
true

func (*Pool) Close

func (p *Pool) Close()

Close closes every engine returned to the pool. Engines still borrowed are closed on release.

func (*Pool) Do

func (p *Pool) Do(fn func(*Engine) error) error

Do borrows an engine for the duration of fn.

func (*Pool) Get

func (p *Pool) Get() (*Engine, func())

Get borrows an engine, blocking until one is free. The returned release function must be called once.

func (*Pool) Size

func (p *Pool) Size() int

Size is the number of engines in the pool.

Directories

Path Synopsis
Package conformance is the engine-agnostic golden-data test harness.
Package conformance is the engine-agnostic golden-data test harness.
internal
wasi
Package wasi is the minimal WASI preview1 host the Faker module still imports after pre-initialisation: clocks and writes to stdout/stderr.
Package wasi is the minimal WASI preview1 host the Faker module still imports after pre-initialisation: clocks and writes to stdout/stderr.
scripts
dylibs command
Command dylibs lists the dynamic libraries a Go binary links against (ELF, Mach-O or PE), which is the check `ldd` / `otool -L` performs, but usable for any target from any host.
Command dylibs lists the dynamic libraries a Go binary links against (ELF, Mach-O or PE), which is the check `ldd` / `otool -L` performs, but usable for any target from any host.
Package stress holds the robustness tests: GC pressure, leaks, isolation, resource bombs, deadlines, fuzzing.
Package stress holds the robustness tests: GC pressure, leaks, isolation, resource bombs, deadlines, fuzzing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL