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 ¶
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.
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 )
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 ¶
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 ¶
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 ValidMethod ¶
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 ¶
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 ¶
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 ¶
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
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) ErrorClass ¶
ErrorClass implements the interface the conformance harness uses to compare error classes.
type Option ¶
type Option func(*config)
Option configures an Engine or Pool.
func WithClock ¶
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 ¶
WithMaxArgBytes bounds the JSON-encoded argument of a call; larger arguments fail with ErrArgTooLarge before reaching the module.
func WithRefDate ¶
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 ¶
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 ¶
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.
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. |