@dicebear/core 11.0.0-rc.4 → 11.1.0-rc.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.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  <h1><img src="https://www.dicebear.com/logo-readme.svg" width="28" /> DiceBear Core (JavaScript)</h1>
2
2
 
3
3
  [![stars](https://www.dicebear.com/badges/stars.svg)](https://github.com/dicebear/dicebear/stargazers)
4
- [![license](https://www.dicebear.com/badges/license.svg)](https://github.com/dicebear/dicebear/blob/10.x/LICENSE)
4
+ [![license](https://www.dicebear.com/badges/license.svg)](https://github.com/dicebear/dicebear/blob/11.x/LICENSE)
5
5
 
6
6
  JavaScript implementation of the DiceBear avatar library. Generates
7
7
  deterministic SVG avatars from style definitions and a seed string.
@@ -16,9 +16,12 @@ style, and options, regardless of the language used.
16
16
  ## Installation
17
17
 
18
18
  ```sh
19
- npm install @dicebear/core
19
+ npm install @dicebear/core @dicebear/styles
20
20
  ```
21
21
 
22
+ `@dicebear/styles` holds the definitions of the avatar styles. Leave it out when
23
+ you bring your own definitions.
24
+
22
25
  Requires Node.js 22+ or any modern browser.
23
26
 
24
27
  ## Usage
package/lib/Avatar.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Style } from './Style.js';
2
- import type { StyleOptions } from './StyleOptions.js';
2
+ import type { NoInferStyle, StyleOptions } from './StyleOptions.js';
3
3
  interface AvatarJson<D = unknown> {
4
4
  readonly svg: string;
5
5
  readonly options: StyleOptions<D>;
@@ -16,7 +16,7 @@ export declare class Avatar<D = unknown> {
16
16
  * Pass a {@link Style} instance and reuse it across avatars. The parsed
17
17
  * style carries the validation, so nothing is re-checked per render.
18
18
  */
19
- constructor(style: Style<D>, optionsInput?: StyleOptions<D>);
19
+ constructor(style: Style<D>, optionsInput?: StyleOptions<NoInferStyle<D>>);
20
20
  /**
21
21
  * Returns the rendered SVG markup.
22
22
  */
package/lib/Options.js CHANGED
@@ -26,7 +26,8 @@ export class Options {
26
26
  _Options_instances.add(this);
27
27
  _Options_data.set(this, void 0);
28
28
  _Options_tags.set(this, void 0);
29
- __classPrivateFieldSet(this, _Options_data, structuredClone(data), "f");
29
+ // `null` renders the default avatar, as in the other ports.
30
+ __classPrivateFieldSet(this, _Options_data, structuredClone(data ?? {}), "f");
30
31
  }
31
32
  /**
32
33
  * The seed, with every lone surrogate replaced by U+FFFD: ill-formed text
@@ -24,6 +24,7 @@ interface ColorField {
24
24
  readonly list?: true;
25
25
  readonly contrastTo?: string;
26
26
  readonly notEqualTo?: readonly string[];
27
+ readonly minContrast?: Readonly<Record<string, number>>;
27
28
  }
28
29
  interface RangeField {
29
30
  readonly type: 'range';
@@ -73,6 +73,7 @@ _a = OptionsDescriptor, _OptionsDescriptor_descriptor = new WeakMap(), _OptionsD
73
73
  const color = __classPrivateFieldGet(this, _OptionsDescriptor_style, "f").colors().get(name);
74
74
  const contrastTo = color?.contrastTo();
75
75
  const notEqualTo = color?.notEqualTo() ?? [];
76
+ const minContrast = color?.minContrast() ?? {};
76
77
  result[`${name}Color`] = {
77
78
  type: 'color',
78
79
  list: true,
@@ -80,6 +81,9 @@ _a = OptionsDescriptor, _OptionsDescriptor_descriptor = new WeakMap(), _OptionsD
80
81
  ...(notEqualTo.length > 0
81
82
  ? { notEqualTo: Array.from(notEqualTo) }
82
83
  : {}),
84
+ ...(Object.keys(minContrast).length > 0
85
+ ? { minContrast: { ...minContrast } }
86
+ : {}),
83
87
  };
84
88
  result[`${name}ColorFill`] = {
85
89
  type: 'enum',
package/lib/Resolver.js CHANGED
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _Resolver_instances, _Resolver_style, _Resolver_options, _Resolver_prng, _Resolver_colorResolving, _Resolver_result, _Resolver_tagFilterCache, _Resolver_probability, _Resolver_isVisible, _Resolver_variantWeights, _Resolver_tagFilter, _Resolver_tagFilteredNames, _Resolver_resolveColor, _Resolver_order, _Resolver_colorFillStops, _Resolver_memoFloat, _Resolver_memo;
12
+ var _Resolver_instances, _Resolver_style, _Resolver_options, _Resolver_prng, _Resolver_colorResolving, _Resolver_result, _Resolver_tagFilterCache, _Resolver_probability, _Resolver_isVisible, _Resolver_variantWeights, _Resolver_tagFilter, _Resolver_tagFilteredNames, _Resolver_resolveColor, _Resolver_minContrastReferences, _Resolver_order, _Resolver_colorFillStops, _Resolver_memoFloat, _Resolver_memo;
13
13
  import { Prng } from './Prng.js';
14
14
  import { Color } from './Utils/Color.js';
15
15
  import { CircularColorReferenceError } from './Error/CircularColorReferenceError.js';
@@ -311,15 +311,21 @@ _Resolver_style = new WeakMap(), _Resolver_options = new WeakMap(), _Resolver_pr
311
311
  }
312
312
  candidates = Color.filterNotEqualTo(candidates, excluded);
313
313
  }
314
+ // Skip shuffle when sorted by contrast to preserve the ordering
315
+ const ordered = contrastTo
316
+ ? candidates
317
+ : __classPrivateFieldGet(this, _Resolver_instances, "m", _Resolver_order).call(this, name, candidates, fixed);
318
+ // Filtered after the shuffle, so that a color only changes where it
319
+ // broke the rule: a shorter list would be shuffled differently.
320
+ return Color.filterMinContrast(ordered, __classPrivateFieldGet(this, _Resolver_instances, "m", _Resolver_minContrastReferences).call(this, styleColor.minContrast())).slice(0, stops);
314
321
  }
315
322
  finally {
316
323
  __classPrivateFieldGet(this, _Resolver_colorResolving, "f").pop();
317
324
  }
318
- // Skip shuffle when sorted by contrast to preserve the ordering
319
- const ordered = contrastTo
320
- ? candidates
321
- : __classPrivateFieldGet(this, _Resolver_instances, "m", _Resolver_order).call(this, name, candidates, fixed);
322
- return ordered.slice(0, stops);
325
+ }, _Resolver_minContrastReferences = function _Resolver_minContrastReferences(minContrast) {
326
+ return Object.keys(minContrast)
327
+ .sort()
328
+ .flatMap((ref) => this.color(ref).map((color) => ({ color, ratio: minContrast[ref] })));
323
329
  }, _Resolver_order = function _Resolver_order(name, candidates, fixed) {
324
330
  return fixed ? candidates : __classPrivateFieldGet(this, _Resolver_prng, "f").shuffle(`${name}Color`, candidates);
325
331
  }, _Resolver_colorFillStops = function _Resolver_colorFillStops(name, fallback) {
@@ -19,4 +19,9 @@ export declare class Color {
19
19
  * or `undefined` when no contrast constraint is defined.
20
20
  */
21
21
  contrastTo(): string | undefined;
22
+ /**
23
+ * Returns the minimum contrast ratio this color should keep to other colors,
24
+ * keyed by their names, or an empty object when the field is unset.
25
+ */
26
+ minContrast(): Readonly<Record<string, number>>;
22
27
  }
@@ -38,5 +38,12 @@ export class Color {
38
38
  contrastTo() {
39
39
  return __classPrivateFieldGet(this, _Color_data, "f").contrastTo;
40
40
  }
41
+ /**
42
+ * Returns the minimum contrast ratio this color should keep to other colors,
43
+ * keyed by their names, or an empty object when the field is unset.
44
+ */
45
+ minContrast() {
46
+ return __classPrivateFieldGet(this, _Color_data, "f").minContrast ?? {};
47
+ }
41
48
  }
42
49
  _Color_data = new WeakMap();
package/lib/Style.d.ts CHANGED
@@ -4,13 +4,22 @@ import { Canvas } from './Style/Canvas.js';
4
4
  import { Component } from './Style/Component.js';
5
5
  import { Color } from './Style/Color.js';
6
6
  export type { StyleDefinition } from './StyleDefinition.js';
7
+ /** Key of the type-only member that carries the definition type. */
8
+ declare const definitionType: unique symbol;
7
9
  /**
8
- * Validated, lazily-decomposed wrapper around a style definition. Construction
9
- * runs the JSON Schema validator and stores a deep clone of the input so that
10
- * later mutation of the source object cannot leak into the rendered avatar.
10
+ * Lazily-decomposed wrapper around a style definition. Construction stores a
11
+ * deep clone of the input so that later mutation of the source object cannot
12
+ * leak into the rendered avatar. It validates nothing: the package root runs
13
+ * {@link StyleValidator} first, the lite entry trusts its input.
11
14
  */
12
15
  export declare class Style<D = unknown> {
13
16
  #private;
17
+ /**
18
+ * Carries `D` in the shape of the class, so the definition type survives
19
+ * when a style is passed around, and `new Avatar(style, options)` checks the
20
+ * options against it. It exists for the type checker only and is never set.
21
+ */
22
+ readonly [definitionType]?: D;
14
23
  constructor(data: D);
15
24
  /**
16
25
  * Returns the definition's `$id`, or `undefined` when not set.
package/lib/Style.js CHANGED
@@ -9,16 +9,16 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _Style_instances, _a, _Style_data, _Style_meta, _Style_canvas, _Style_components, _Style_colors, _Style_hasAnimations, _Style_animationNames, _Style_validateAliases, _Style_isAlias, _Style_validateAnimations, _Style_visitElements;
13
- import { StyleValidationError } from './Error/StyleValidationError.js';
12
+ var _Style_instances, _a, _Style_data, _Style_meta, _Style_canvas, _Style_components, _Style_colors, _Style_hasAnimations, _Style_animationNames, _Style_isAlias, _Style_visitElements;
14
13
  import { Meta } from './Style/Meta.js';
15
14
  import { Canvas } from './Style/Canvas.js';
16
15
  import { Component } from './Style/Component.js';
17
16
  import { Color } from './Style/Color.js';
18
17
  /**
19
- * Validated, lazily-decomposed wrapper around a style definition. Construction
20
- * runs the JSON Schema validator and stores a deep clone of the input so that
21
- * later mutation of the source object cannot leak into the rendered avatar.
18
+ * Lazily-decomposed wrapper around a style definition. Construction stores a
19
+ * deep clone of the input so that later mutation of the source object cannot
20
+ * leak into the rendered avatar. It validates nothing: the package root runs
21
+ * {@link StyleValidator} first, the lite entry trusts its input.
22
22
  */
23
23
  export class Style {
24
24
  constructor(data) {
@@ -31,8 +31,6 @@ export class Style {
31
31
  _Style_hasAnimations.set(this, void 0);
32
32
  _Style_animationNames.set(this, void 0);
33
33
  __classPrivateFieldSet(this, _Style_data, structuredClone(data), "f");
34
- __classPrivateFieldGet(this, _Style_instances, "m", _Style_validateAliases).call(this);
35
- __classPrivateFieldGet(this, _Style_instances, "m", _Style_validateAnimations).call(this);
36
34
  }
37
35
  /**
38
36
  * Returns the definition's `$id`, or `undefined` when not set.
@@ -153,57 +151,8 @@ export class Style {
153
151
  return __classPrivateFieldGet(this, _Style_colors, "f");
154
152
  }
155
153
  }
156
- _a = Style, _Style_data = new WeakMap(), _Style_meta = new WeakMap(), _Style_canvas = new WeakMap(), _Style_components = new WeakMap(), _Style_colors = new WeakMap(), _Style_hasAnimations = new WeakMap(), _Style_animationNames = new WeakMap(), _Style_instances = new WeakSet(), _Style_validateAliases = function _Style_validateAliases() {
157
- const components = __classPrivateFieldGet(this, _Style_data, "f").components;
158
- if (!components) {
159
- return;
160
- }
161
- const errors = [];
162
- for (const [name, data] of Object.entries(components)) {
163
- if (!__classPrivateFieldGet(_a, _a, "m", _Style_isAlias).call(_a, data)) {
164
- continue;
165
- }
166
- const target = data.extends;
167
- const targetData = components[target];
168
- if (!targetData) {
169
- errors.push({
170
- instancePath: `/components/${name}/extends`,
171
- message: `references unknown component "${target}"`,
172
- });
173
- continue;
174
- }
175
- if (__classPrivateFieldGet(_a, _a, "m", _Style_isAlias).call(_a, targetData)) {
176
- errors.push({
177
- instancePath: `/components/${name}/extends`,
178
- message: `references alias "${target}" — alias chains are not allowed`,
179
- });
180
- }
181
- }
182
- if (errors.length > 0) {
183
- throw new StyleValidationError(errors);
184
- }
185
- }, _Style_isAlias = function _Style_isAlias(data) {
154
+ _a = Style, _Style_data = new WeakMap(), _Style_meta = new WeakMap(), _Style_canvas = new WeakMap(), _Style_components = new WeakMap(), _Style_colors = new WeakMap(), _Style_hasAnimations = new WeakMap(), _Style_animationNames = new WeakMap(), _Style_instances = new WeakSet(), _Style_isAlias = function _Style_isAlias(data) {
186
155
  return 'extends' in data;
187
- }, _Style_validateAnimations = function _Style_validateAnimations() {
188
- const errors = [];
189
- __classPrivateFieldGet(this, _Style_instances, "m", _Style_visitElements).call(this, (element, path) => {
190
- element.animations?.forEach((animation, animationIndex) => {
191
- for (const [trackName, track] of Object.entries(animation.tracks)) {
192
- const keyframes = track.keyframes;
193
- for (let i = 1; i < keyframes.length; i++) {
194
- if (keyframes[i].at <= keyframes[i - 1].at) {
195
- errors.push({
196
- instancePath: `${path}/animations/${animationIndex}/tracks/${trackName}/keyframes/${i}/at`,
197
- message: 'must be greater than the previous keyframe',
198
- });
199
- }
200
- }
201
- }
202
- });
203
- });
204
- if (errors.length > 0) {
205
- throw new StyleValidationError(errors);
206
- }
207
156
  }, _Style_visitElements = function _Style_visitElements(visit) {
208
157
  const walk = (elements, path) => {
209
158
  elements.forEach((element, index) => {
@@ -111,6 +111,7 @@ export interface StyleDefinitionColor {
111
111
  readonly values: readonly string[];
112
112
  readonly notEqualTo?: readonly string[];
113
113
  readonly contrastTo?: string;
114
+ readonly minContrast?: Readonly<Record<string, number>>;
114
115
  }
115
116
  /**
116
117
  * A closed numeric range. `min === max` represents a fixed value. `step`
@@ -13,6 +13,15 @@ export interface TagFilterToken {
13
13
  readonly value?: string;
14
14
  readonly negated: boolean;
15
15
  }
16
+ /**
17
+ * Keeps TypeScript from inferring `T` at this position, so the options of an
18
+ * avatar are checked against the style instead of widening the style's type
19
+ * to fit them. The same as the built-in `NoInfer` of TypeScript 5.4, written
20
+ * out so that the declarations also work with older compilers.
21
+ *
22
+ * @internal
23
+ */
24
+ export type NoInferStyle<T> = [T][T extends unknown ? 0 : never];
16
25
  type ComponentNames<D> = D extends {
17
26
  components: Record<infer K extends string, unknown>;
18
27
  } ? string extends K ? never : K : never;
@@ -71,9 +80,9 @@ type ColorOptions<C extends string> = [C] extends [never] ? unknown : {
71
80
  readonly [K in C as `${K}ColorOrder`]?: StyleOptionsColorOrderValue;
72
81
  };
73
82
  type AnimationOptions = {
74
- readonly [key: `${string}Animation`]: boolean | undefined;
75
- readonly [key: `${string}AnimationSpeed`]: number | readonly [number, number] | undefined;
76
- readonly [key: `${string}AnimationDelay`]: number | readonly [number, number] | undefined;
83
+ readonly [key: `${string}Animation`]: unknown;
84
+ readonly [key: `${string}AnimationSpeed`]: unknown;
85
+ readonly [key: `${string}AnimationDelay`]: unknown;
77
86
  };
78
87
  export type StyleOptions<D = unknown> = StyleOptionsBase & ComponentOptions<D, ComponentNames<D>> & ColorOptions<AllColorNames<D>> & (HasSpecificKeys<D> extends true ? AnimationOptions : {
79
88
  readonly [key: string]: unknown;
@@ -34,4 +34,16 @@ export declare class Color {
34
34
  * original candidates when filtering would empty the list.
35
35
  */
36
36
  static filterNotEqualTo(candidates: readonly string[], excluded: readonly string[]): string[];
37
+ /**
38
+ * Returns a new array with the candidates that reach the minimum contrast
39
+ * ratio to every reference color, in their given order.
40
+ *
41
+ * When no candidate does, each one is rated by the reference it misses by
42
+ * the most (the lowest contrast relative to the required minimum), and the
43
+ * candidates with the best rating are returned.
44
+ */
45
+ static filterMinContrast(candidates: readonly string[], references: readonly {
46
+ readonly color: string;
47
+ readonly ratio: number;
48
+ }[]): string[];
37
49
  }
@@ -3,7 +3,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
3
3
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
4
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
5
  };
6
- var _a, _Color_LINEARIZED, _Color_linearize;
6
+ var _a, _Color_contrastRatio, _Color_LINEARIZED, _Color_linearize;
7
7
  /**
8
8
  * Color helpers used by the renderer and option resolver.
9
9
  */
@@ -61,8 +61,7 @@ export class Color {
61
61
  static sortByContrast(candidates, refColor) {
62
62
  const refLum = this.luminance(refColor);
63
63
  const withRatio = candidates.map((c) => {
64
- const lum = this.luminance(c);
65
- const ratio = (Math.max(lum, refLum) + 0.05) / (Math.min(lum, refLum) + 0.05);
64
+ const ratio = __classPrivateFieldGet(this, _a, "m", _Color_contrastRatio).call(this, this.luminance(c), refLum);
66
65
  return { color: c, ratio };
67
66
  });
68
67
  withRatio.sort((a, b) => b.ratio - a.ratio);
@@ -77,8 +76,43 @@ export class Color {
77
76
  const filtered = candidates.filter((c) => !normalized.has(this.toRgbHex(c)));
78
77
  return filtered.length > 0 ? filtered : Array.from(candidates);
79
78
  }
79
+ /**
80
+ * Returns a new array with the candidates that reach the minimum contrast
81
+ * ratio to every reference color, in their given order.
82
+ *
83
+ * When no candidate does, each one is rated by the reference it misses by
84
+ * the most (the lowest contrast relative to the required minimum), and the
85
+ * candidates with the best rating are returned.
86
+ */
87
+ static filterMinContrast(candidates, references) {
88
+ const refs = references.map(({ color, ratio }) => ({
89
+ luminance: this.luminance(color),
90
+ ratio,
91
+ }));
92
+ const rated = candidates.map((color) => {
93
+ const luminance = this.luminance(color);
94
+ let passes = true;
95
+ let score = Infinity;
96
+ for (const ref of refs) {
97
+ const contrast = __classPrivateFieldGet(this, _a, "m", _Color_contrastRatio).call(this, luminance, ref.luminance);
98
+ passes &&= contrast >= ref.ratio;
99
+ score = Math.min(score, contrast / ref.ratio);
100
+ }
101
+ return { color, passes, score };
102
+ });
103
+ const passing = rated.filter((entry) => entry.passes);
104
+ if (passing.length > 0) {
105
+ return passing.map((entry) => entry.color);
106
+ }
107
+ const best = rated.reduce((max, entry) => Math.max(max, entry.score), 0);
108
+ return rated
109
+ .filter((entry) => entry.score === best)
110
+ .map((entry) => entry.color);
111
+ }
80
112
  }
81
- _a = Color, _Color_linearize = function _Color_linearize(channel) {
113
+ _a = Color, _Color_contrastRatio = function _Color_contrastRatio(a, b) {
114
+ return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
115
+ }, _Color_linearize = function _Color_linearize(channel) {
82
116
  return __classPrivateFieldGet(_a, _a, "f", _Color_LINEARIZED)[channel];
83
117
  };
84
118
  /**
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Finds a number in the options that is not finite.
3
+ *
4
+ * JSON cannot carry Infinity or NaN, so every other port turns such a value
5
+ * down before or during validation. The compiled JS validator lets one
6
+ * through where the schema sets no maximum, a variant weight for example, and
7
+ * the avatar then rendered here but nowhere else.
8
+ */
9
+ export declare class Finite {
10
+ static readonly MESSAGE = "must be a finite number";
11
+ /**
12
+ * Returns the JSON pointer of the first non-finite number in `value`, or
13
+ * `undefined` if there is none. Runs after the depth check, so the value
14
+ * nests at most a few levels.
15
+ */
16
+ static find(value: unknown, path?: string): string | undefined;
17
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Finds a number in the options that is not finite.
3
+ *
4
+ * JSON cannot carry Infinity or NaN, so every other port turns such a value
5
+ * down before or during validation. The compiled JS validator lets one
6
+ * through where the schema sets no maximum, a variant weight for example, and
7
+ * the avatar then rendered here but nowhere else.
8
+ */
9
+ export class Finite {
10
+ /**
11
+ * Returns the JSON pointer of the first non-finite number in `value`, or
12
+ * `undefined` if there is none. Runs after the depth check, so the value
13
+ * nests at most a few levels.
14
+ */
15
+ static find(value, path = '') {
16
+ if (typeof value === 'number') {
17
+ return Number.isFinite(value) ? undefined : path;
18
+ }
19
+ if (value === null || typeof value !== 'object') {
20
+ return undefined;
21
+ }
22
+ for (const [key, inner] of Object.entries(value)) {
23
+ const pointer = `${path}/${key.replace(/~/g, '~0').replace(/\//g, '~1')}`;
24
+ const found = Finite.find(inner, pointer);
25
+ if (found !== undefined) {
26
+ return found;
27
+ }
28
+ }
29
+ return undefined;
30
+ }
31
+ }
32
+ Finite.MESSAGE = 'must be a finite number';
@@ -0,0 +1,3 @@
1
+ export class OptionsSchemaValidator {
2
+ static validate(data: any): void;
3
+ }