Skip to main content
Auric Artisan · Documentation

Palette Gen Developer Reference

Back to Documentation Auric Artisan Home

A source-level map of @auric-artisan/palette-gen: package exports, API contracts, palette schema, algorithms, color science, accessibility, dataset engine, GPU fallback, exporters, research utilities, Palette Library integration and maintenance notes.

Published: May 26, 2026 Updated: May 26, 2026 Reading time: 22 min read Author: Chirag Bansal

Overview

A source-level map of @auric-artisan/palette-gen : package exports, API contracts, palette schema, algorithms, color science, accessibility, dataset engine, GPU fallback, exporters, research utilities, Palette Library integration and maintenance notes.

Table of contents

  1. 1. Package contract
  2. 2. Public API
  3. 3. Palette object schema
  4. 4. Color-space layer
  5. 5. Generation algorithms
  6. 6. Metrics and mood
  7. 7. Accessibility module
  8. 8. Dataset Engine
  9. 9. Streaming and worker utilities
  10. 10. GPU and CPU pipeline
  11. 11. Export system
  12. 12. Visualization and research
  13. 13. Palette Library integration
  14. 14. API integration
  15. 15. Tests, examples and benchmarks
  16. 16. Maintenance checklist

1. Package contract

+

tool/palette-gen/package.json defines @auric-artisan/palette-gen, an ESM package that requires Node 20 or newer. The package exposes the root entry and subpath exports for every major subsystem.

Subpath Module Purpose
. src/index.js Top-level re-exports and public named helpers.
./api src/api/index.js High-level generation, dataset, evaluation and metadata API.
./core src/core/index.js Palette object creation, binary helpers and color-space conversions.
./palette_algorithms src/palette_algorithms/index.js Harmony, mathematical, scientific and evolutionary algorithms.
./color_science src/color_science/index.js Delta E, contrast, entropy, diversity and distribution metrics.
./accessibility src/accessibility/index.js WCAG checks, color blindness simulation and palette accessibility reports.
./dataset_engine src/dataset_engine/index.js Dataset generator, streaming writer, worker pool and binary generation.
./gpu src/gpu/index.js GPU.js kernels, WebGPU shader strings and CPU fallback pipeline.
./export src/export/index.js JSON, NDJSON, CSV, binary, Arrow and Parquet file exporters.
./research src/research/index.js Distribution analysis, clustering, entropy studies and mood classification.
./utils src/utils/index.js PRNG, timers, chunking, formatting and concurrency helpers.

Top-level named exports include generatePalette, generateDataset, evaluatePalette, simulateColorBlindness, getAvailableMethods and getSupportedFormats. The package also re-exports subsystem modules for advanced workflows.

2. Public API

+

The public API lives in src/api/api.js. It wraps lower-level modules and normalizes the output into palette objects with metrics.

Function Signature Behavior
generatePalette (options = {}) Generates one palette and attaches Delta E, entropy, contrast matrix and mood metadata.
generateDataset (options = {}) Streams palette datasets through DatasetGenerator and destroys resources in finally.
evaluatePaletteAPI (palette) Returns metrics, accessibility, mood and score for an existing palette.
simulateColorBlindnessAPI (palette) Returns original, protanopia, deuteranopia and tritanopia RGB arrays.
getAvailableMethods () Returns method groups for harmony, mathematical, scientific, evolutionary and other methods.
getSupportedFormats () Returns package export formats from SUPPORTED_FORMATS.
const palette = generatePalette({
  method: "deltaE_spaced",
  count: 6,
  seed: 90210
});

const evaluation = evaluatePaletteAPI(palette);
const simulations = simulateColorBlindnessAPI(palette);

src/index.js aliases evaluatePaletteAPI to the public top-level name evaluatePalette, and aliases simulateColorBlindnessAPI to simulateColorBlindness.

3. Palette object schema

+

createPalette(rgbColors, meta) in src/core/palette.js is the central object factory. It creates a unique palette_id, maps RGB colors to HEX, OKLCH and Lab, and merges method metadata.

{
  palette_id: "pal_lx0a9abc_1",
  colors: [
    {
      hex: "#2f8ed8",
      rgb: [47, 142, 216],
      oklch: [0.61, 0.14, 248.7],
      lab: [56.8, 2.9, -45.2]
    }
  ],
  metadata: {
    method: "triadic",
    color_count: 5,
    timestamp: 1779753600000,
    deltaE_avg: 61.2,
    entropy: 0.8,
    contrast_matrix: [[1, 2.14], [2.14, 1]],
    mood: "balanced"
  }
}

Binary helpers in the same module provide compact RGB transport: createBinaryPalette(), decodeBinaryPalette(), createPaletteBatchBuffer(), writePaletteToBatch() and readPaletteFromBatch(). The single-palette binary shape stores a 4-byte color count followed by 3 RGB bytes per color.

4. Color-space layer

+

src/core/color-spaces.js is a pure conversion module. It uses D65 white point constants and routes arbitrary conversion requests through RGB when needed.

Space Support
Display and web rgb, rgba, hex, hsl, hsv, cmyk
CIE and perceptual xyz, lab, lch, oklab, oklch, hcl
Video yuv, ycbcr

The key helpers are convert(value, from, to), rgbToAll(r, g, b), rgbToHex(), rgbToLab() and rgbToOklch(). All exported palette colors are derived from this layer, so changes here affect datasets, API responses and the Palette Library.

5. Generation algorithms

+

Algorithm modules return arrays of RGB triplets. The high-level API then normalizes length, creates a palette object and adds metrics.

File Exports Notes
harmony.js complementary, splitComplementary, triadic, tetradic, square, analogous, monochromatic HSL hue rotations from a starting hue, saturation and lightness.
mathematical.js goldenRatioHues, fibonacciDistribution, fractalSampling, polarTraversal, sinusoidalWaves Procedural sampling for ordered, cyclic and varied palettes.
scientific.js uniformPerceptualSpacing, deltaESpacing, kMeansClustering, spectralSampling OKLCH, Lab and wavelength-inspired sampling. Seeded functions use xorshift-style PRNGs.
evolutionary.js scorePalette, evolutionaryGeneration, simulatedAnnealing, geneticMutation Search-based optimization over diversity, uniformity, contrast and entropy.

generatePalette() pads or truncates algorithm output so the returned palette has exactly count colors. That is useful for API stability, but algorithm authors should still return meaningful output lengths to avoid repeated colors.

6. Metrics and mood

+

src/color_science/metrics.js owns the numeric measurements used by generation, evaluation, datasets and the library viewer.

  • deltaE76, deltaE94 and deltaE2000 for perceptual difference.
  • relativeLuminance, contrastRatio and contrastMatrix for WCAG-style contrast data.
  • paletteAvgDeltaE and paletteMinDeltaE for pair-distance summaries.
  • paletteEntropy, colorDiversityIndex and perceptualUniformity for palette quality signals.
  • chromaStats, luminanceStats and hueDistribution for analysis and filtering.
  • evaluatePalette(rgbColors) returns the consolidated metrics object.

Mood classification lives in src/research/research.js. classifyMood() combines warmth, chroma, lightness, entropy and saturation into a primary mood and attribute list. The high-level palette metadata stores classifyMood(rgbColors).primary.

7. Accessibility module

+

src/accessibility/accessibility.js provides WCAG contrast and CVD helpers. It is used by evaluatePaletteAPI() and can be imported directly for focused reports.

Function Returns
wcagCompliance(rgb1, rgb2) Contrast ratio and AA/AAA booleans for normal and large text.
evaluatePaletteAccessibility(rgbColors) On-white, on-black and pairwise contrast reports with summary fields.
simulateCVD(rgb, type) Single-color protanopia, deuteranopia or tritanopia matrix result.
simulateColorBlindness(rgbColors) Original plus three simulated RGB arrays.
colorBlindnessSafeScore(rgbColors) Normalized minimum-distance score after CVD simulations.
fullAccessibilityReport(rgbColors) WCAG, CVD simulation and CVD safety score in one object.

Maintenance note: the current pairwise allPairsPassAA summary uses the AA_large boolean. Keep docs, UI labels and tests clear if that field is renamed or split into normal-text and large-text summaries.

8. Dataset Engine

+

src/dataset_engine/generator.js contains DatasetGenerator, the main streaming dataset factory. Constructor options include colorsPerPalette, useGPU, workerCount, batchSize, includeMetrics and seed.

const generator = new DatasetGenerator({
  colorsPerPalette: 5,
  useGPU: false,
  batchSize: 50000,
  includeMetrics: true,
  seed: 42
});

await generator.init();
const result = await generator.generateDataset({
  paletteCount: 5000000,
  outputPath: "./output",
  format: "ndjson",
  method: "mixed",
  compress: false
});
await generator.destroy();
Path Purpose
generateDataset() Streams JSON, NDJSON, CSV or binary palette objects through StreamingPaletteWriter.
generateRawDataset() Writes optimized raw RGB binary with a 16-byte header.
generatePaletteBatch() Creates an in-memory batch of palette objects from deterministic raw bytes.
_pickMethod(seed) Cycles mixed dataset method labels across complementary, triadic, analogous, tetradic, golden_ratio, random and monochromatic.

Current implementation detail: DatasetGenerator.init() can initialize both the GPU pipeline and WorkerPool, but generateDataset() currently uses the CPU byte generator path for batch production. Treat the worker and GPU modules as available lower-level infrastructure unless a future dataset path explicitly routes through them.

9. Streaming and worker utilities

+

src/dataset_engine/streaming.js provides StreamingPaletteWriter, PaletteTransform and ChunkedProcessor. The writer supports JSON, NDJSON, CSV and binary output, plus gzip compression through compress: true.

  • JSON output writes an array stream with comma-safe item boundaries.
  • NDJSON output writes one palette object per line.
  • CSV output writes palette_id, method, color_count, colors_hex, deltaE_avg and entropy.
  • Binary output writes a 4-byte color count plus RGB bytes for each palette object.

src/dataset_engine/worker-pool.js exposes a worker-thread pool with generateDistributed() and evaluateDistributed(). The worker supports generation methods named random, harmony and golden. Keep that naming distinct from the high-level public method list.

10. GPU and CPU pipeline

+

src/gpu/gpu-pipeline.js provides optional GPU.js acceleration and stable CPU fallback. initGPU() tries gpu.js in GPU mode, then CPU mode, then disables acceleration if the import fails.

Export Purpose
createGeneratePaletteKernel() GPU.js kernel that returns packed RGB integers.
createContrastKernel() GPU.js contrast ratio matrix kernel.
createDeltaEKernel() GPU.js Delta E 1976 matrix kernel for Lab arrays.
createPaletteEntropyKernel() GPU.js hue-bin entropy kernel for batches.
generatePalettesCPU() Deterministic xorshift CPU byte generator used by datasets and fallback paths.
GPUPipeline High-level batched generation and contrast matrix wrapper with fallback behavior.
WGSL_PALETTE_GENERATOR, WGSL_CONTRAST_RATIO WebGPU shader source for future browser or Deno compute paths.

Always call destroy() on a GPUPipeline instance or DatasetGenerator after long-running work so GPU.js resources and worker threads do not remain active.

11. Export system

+

src/export/exporters.js provides file-writing exporters. These are package-level exporters for local Node workflows; the HTTP API uses a separate in-memory mirror in api/lib/exporters/palette.js.

Function Dependency Output
exportJSON Node fs Complete array as JSON, optionally pretty-printed.
exportNDJSON Node streams One palette per line.
exportCSV Node streams Palette metadata and configurable color columns.
exportBinary Node streams 16-byte header followed by raw RGB rows.
exportArrow apache-arrow Arrow IPC table with id, method, colors, Delta E and entropy.
exportParquet parquetjs-lite Parquet rows with the same compact analytical fields.

exportDataset(palettes, outputPath, format, options) dispatches to the appropriate exporter and validates the format against json, ndjson, csv, binary, arrow and parquet.

12. Visualization and research

+

src/visualization/visualization.js provides direct SVG and terminal-oriented views for generated palettes:

  • paletteSwatchSVG() creates a labeled horizontal color strip.
  • colorWheelSVG() plots palette colors on a hue wheel.
  • contrastMatrixSVG() renders WCAG contrast as a heatmap.
  • perceptualMapSVG() plots OKLCH lightness and chroma.
  • paletteASCII() and contrastMatrixASCII() support terminal examples.

src/research/research.js analyzes palette datasets with distribution summaries, Lab clustering, entropy histograms, mood distribution and fullResearchReport(). Use these helpers for generated data QA before publishing new manifest or library data.

13. Palette Library integration

+

library/palette/index.html is the public UI and library/palette/palette-library.js is the browser runtime. The UI preloads /data/palette-db/palettes.json, uses Auric Artisan cursor, scroll and loader layers, and exposes Library, Inspect, Harmony, Accessibility, Stats, Export and Saved panels.

The data file is intentionally compact:

{
  "schema": "aa.palette-db.compact.v1",
  "format": "deterministic-palette-gen-manifest",
  "source": "@auric-artisan/palette-gen",
  "count": 5000000,
  "colors_per_palette": 5,
  "seed": 42,
  "batch_size": 50000,
  "batch_seed_stride": 2654435761,
  "methods": [
    "complementary",
    "triadic",
    "analogous",
    "tetradic",
    "golden_ratio",
    "random",
    "monochromatic"
  ]
}

The browser derives the palette id as pal_${index.toString(36)}, regenerates RGB values from the same xorshift batch seed, enriches each visible palette with HEX, OKLCH, Lab, Delta E, entropy and contrast, and caches a bounded number of materialized palettes. This keeps the public page fast while representing a 5,000,000-palette corpus.

14. API integration

+

Server-side handlers import the package directly:

  • api/lib/handlers/palette.js imports generatePalette and evaluatePaletteAPI for /v1/palette/generate and /v1/palette/evaluate.
  • api/lib/handlers/meta.js imports getAvailableMethods for /v1/methods/palette.
  • api/lib/handlers/graphql.js exposes palette generation through GraphQL.
  • api/lib/exporters/palette.js mirrors browser-friendly formats for stateless HTTP export.

The HTTP generator validates count (1 through 64), hue, saturation and lightness, then passes the options object to the package API. Keep route docs and request validation synchronized whenever new high-level options are added.

15. Tests, examples and benchmarks

+

The package declares the following scripts:

cd tool/palette-gen
npm run example:basic
npm run example:gpu
npm run example:large
npm run generate:dataset
npm run benchmark
npm test

examples/basic-generation.js covers public methods, metrics, ASCII visualization, full evaluation and CVD simulation. benchmarks/benchmark.js is for local throughput comparisons after engine changes.

Current maintenance caveat: package.json defines npm test as node --test tests/, but the package does not currently include a tests directory. Until package tests are added, use smoke imports, example runs, root tests, API contract checks and documentation generation as the release gate.

16. Maintenance checklist

+
  • Update getAvailableMethods() when adding, renaming or removing generation methods.
  • Keep user docs, developer docs, API metadata and Palette Library filter labels aligned with method names.
  • Add Node tests before changing color-space conversion, Delta E, contrast, entropy or scoring behavior.
  • Check deterministic output when changing generatePalettesCPU(), seed stride, batch size or manifest shape.
  • Regenerate or migrate data/palette-db/palettes.json when public dataset parameters change.
  • Validate optional Arrow and Parquet exporters when dependency versions move.
  • Keep the API in-memory exporter synchronized with browser exports and package file exporters where names overlap.
  • Destroy dataset, GPU and worker resources after long-running scripts.
  • Run root site tests, docs discovery generation, RSS, sitemap, PWA cache and search-index generation before publishing docs.

For workflow-level usage, see the Palette Gen User Guide.