Debian Codegraph @

node/colorjs.io/dist/color-fn.legacy.js

raw
1 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2
3 var es_error_cause = {};
4
5 var globalThis_1;
6 var hasRequiredGlobalThis;
7
8 function requireGlobalThis () {
9 if (hasRequiredGlobalThis) return globalThis_1;
10 hasRequiredGlobalThis = 1;
11 var check = function (it) {
12 return it && it.Math === Math && it;
13 };
14
15 // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
16 globalThis_1 =
17 // eslint-disable-next-line es/no-global-this -- safe
18 check(typeof globalThis == 'object' && globalThis) ||
19 check(typeof window == 'object' && window) ||
20 // eslint-disable-next-line no-restricted-globals -- safe
21 check(typeof self == 'object' && self) ||
22 check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
23 check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
24 // eslint-disable-next-line no-new-func -- fallback
25 (function () { return this; })() || Function('return this')();
26 return globalThis_1;
27 }
28
29 var objectGetOwnPropertyDescriptor = {};
30
31 var fails;
32 var hasRequiredFails;
33
34 function requireFails () {
35 if (hasRequiredFails) return fails;
36 hasRequiredFails = 1;
37 fails = function (exec) {
38 try {
39 return !!exec();
40 } catch (error) {
41 return true;
42 }
43 };
44 return fails;
45 }
46
47 var descriptors;
48 var hasRequiredDescriptors;
49
50 function requireDescriptors () {
51 if (hasRequiredDescriptors) return descriptors;
52 hasRequiredDescriptors = 1;
53 var fails = requireFails();
54
55 // Detect IE8's incomplete defineProperty implementation
56 descriptors = !fails(function () {
57 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
58 return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7;
59 });
60 return descriptors;
61 }
62
63 var functionBindNative;
64 var hasRequiredFunctionBindNative;
65
66 function requireFunctionBindNative () {
67 if (hasRequiredFunctionBindNative) return functionBindNative;
68 hasRequiredFunctionBindNative = 1;
69 var fails = requireFails();
70
71 functionBindNative = !fails(function () {
72 // eslint-disable-next-line es/no-function-prototype-bind -- safe
73 var test = (function () { /* empty */ }).bind();
74 // eslint-disable-next-line no-prototype-builtins -- safe
75 return typeof test != 'function' || test.hasOwnProperty('prototype');
76 });
77 return functionBindNative;
78 }
79
80 var functionCall;
81 var hasRequiredFunctionCall;
82
83 function requireFunctionCall () {
84 if (hasRequiredFunctionCall) return functionCall;
85 hasRequiredFunctionCall = 1;
86 var NATIVE_BIND = requireFunctionBindNative();
87
88 var call = Function.prototype.call;
89
90 functionCall = NATIVE_BIND ? call.bind(call) : function () {
91 return call.apply(call, arguments);
92 };
93 return functionCall;
94 }
95
96 var objectPropertyIsEnumerable = {};
97
98 var hasRequiredObjectPropertyIsEnumerable;
99
100 function requireObjectPropertyIsEnumerable () {
101 if (hasRequiredObjectPropertyIsEnumerable) return objectPropertyIsEnumerable;
102 hasRequiredObjectPropertyIsEnumerable = 1;
103 var $propertyIsEnumerable = {}.propertyIsEnumerable;
104 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
105 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
106
107 // Nashorn ~ JDK8 bug
108 var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);
109
110 // `Object.prototype.propertyIsEnumerable` method implementation
111 // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
112 objectPropertyIsEnumerable.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
113 var descriptor = getOwnPropertyDescriptor(this, V);
114 return !!descriptor && descriptor.enumerable;
115 } : $propertyIsEnumerable;
116 return objectPropertyIsEnumerable;
117 }
118
119 var createPropertyDescriptor;
120 var hasRequiredCreatePropertyDescriptor;
121
122 function requireCreatePropertyDescriptor () {
123 if (hasRequiredCreatePropertyDescriptor) return createPropertyDescriptor;
124 hasRequiredCreatePropertyDescriptor = 1;
125 createPropertyDescriptor = function (bitmap, value) {
126 return {
127 enumerable: !(bitmap & 1),
128 configurable: !(bitmap & 2),
129 writable: !(bitmap & 4),
130 value: value
131 };
132 };
133 return createPropertyDescriptor;
134 }
135
136 var functionUncurryThis;
137 var hasRequiredFunctionUncurryThis;
138
139 function requireFunctionUncurryThis () {
140 if (hasRequiredFunctionUncurryThis) return functionUncurryThis;
141 hasRequiredFunctionUncurryThis = 1;
142 var NATIVE_BIND = requireFunctionBindNative();
143
144 var FunctionPrototype = Function.prototype;
145 var call = FunctionPrototype.call;
146 var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call);
147
148 functionUncurryThis = NATIVE_BIND ? uncurryThisWithBind : function (fn) {
149 return function () {
150 return call.apply(fn, arguments);
151 };
152 };
153 return functionUncurryThis;
154 }
155
156 var classofRaw;
157 var hasRequiredClassofRaw;
158
159 function requireClassofRaw () {
160 if (hasRequiredClassofRaw) return classofRaw;
161 hasRequiredClassofRaw = 1;
162 var uncurryThis = requireFunctionUncurryThis();
163
164 var toString = uncurryThis({}.toString);
165 var stringSlice = uncurryThis(''.slice);
166
167 classofRaw = function (it) {
168 return stringSlice(toString(it), 8, -1);
169 };
170 return classofRaw;
171 }
172
173 var indexedObject;
174 var hasRequiredIndexedObject;
175
176 function requireIndexedObject () {
177 if (hasRequiredIndexedObject) return indexedObject;
178 hasRequiredIndexedObject = 1;
179 var uncurryThis = requireFunctionUncurryThis();
180 var fails = requireFails();
181 var classof = requireClassofRaw();
182
183 var $Object = Object;
184 var split = uncurryThis(''.split);
185
186 // fallback for non-array-like ES3 and non-enumerable old V8 strings
187 indexedObject = fails(function () {
188 // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
189 // eslint-disable-next-line no-prototype-builtins -- safe
190 return !$Object('z').propertyIsEnumerable(0);
191 }) ? function (it) {
192 return classof(it) === 'String' ? split(it, '') : $Object(it);
193 } : $Object;
194 return indexedObject;
195 }
196
197 var isNullOrUndefined;
198 var hasRequiredIsNullOrUndefined;
199
200 function requireIsNullOrUndefined () {
201 if (hasRequiredIsNullOrUndefined) return isNullOrUndefined;
202 hasRequiredIsNullOrUndefined = 1;
203 // we can't use just `it == null` since of `document.all` special case
204 // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
205 isNullOrUndefined = function (it) {
206 return it === null || it === undefined;
207 };
208 return isNullOrUndefined;
209 }
210
211 var requireObjectCoercible;
212 var hasRequiredRequireObjectCoercible;
213
214 function requireRequireObjectCoercible () {
215 if (hasRequiredRequireObjectCoercible) return requireObjectCoercible;
216 hasRequiredRequireObjectCoercible = 1;
217 var isNullOrUndefined = requireIsNullOrUndefined();
218
219 var $TypeError = TypeError;
220
221 // `RequireObjectCoercible` abstract operation
222 // https://tc39.es/ecma262/#sec-requireobjectcoercible
223 requireObjectCoercible = function (it) {
224 if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it);
225 return it;
226 };
227 return requireObjectCoercible;
228 }
229
230 var toIndexedObject;
231 var hasRequiredToIndexedObject;
232
233 function requireToIndexedObject () {
234 if (hasRequiredToIndexedObject) return toIndexedObject;
235 hasRequiredToIndexedObject = 1;
236 // toObject with fallback for non-array-like ES3 strings
237 var IndexedObject = requireIndexedObject();
238 var requireObjectCoercible = requireRequireObjectCoercible();
239
240 toIndexedObject = function (it) {
241 return IndexedObject(requireObjectCoercible(it));
242 };
243 return toIndexedObject;
244 }
245
246 var isCallable;
247 var hasRequiredIsCallable;
248
249 function requireIsCallable () {
250 if (hasRequiredIsCallable) return isCallable;
251 hasRequiredIsCallable = 1;
252 // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
253 var documentAll = typeof document == 'object' && document.all;
254
255 // `IsCallable` abstract operation
256 // https://tc39.es/ecma262/#sec-iscallable
257 // eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing
258 isCallable = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) {
259 return typeof argument == 'function' || argument === documentAll;
260 } : function (argument) {
261 return typeof argument == 'function';
262 };
263 return isCallable;
264 }
265
266 var isObject;
267 var hasRequiredIsObject;
268
269 function requireIsObject () {
270 if (hasRequiredIsObject) return isObject;
271 hasRequiredIsObject = 1;
272 var isCallable = requireIsCallable();
273
274 isObject = function (it) {
275 return typeof it == 'object' ? it !== null : isCallable(it);
276 };
277 return isObject;
278 }
279
280 var getBuiltIn;
281 var hasRequiredGetBuiltIn;
282
283 function requireGetBuiltIn () {
284 if (hasRequiredGetBuiltIn) return getBuiltIn;
285 hasRequiredGetBuiltIn = 1;
286 var globalThis = requireGlobalThis();
287 var isCallable = requireIsCallable();
288
289 var aFunction = function (argument) {
290 return isCallable(argument) ? argument : undefined;
291 };
292
293 getBuiltIn = function (namespace, method) {
294 return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method];
295 };
296 return getBuiltIn;
297 }
298
299 var objectIsPrototypeOf;
300 var hasRequiredObjectIsPrototypeOf;
301
302 function requireObjectIsPrototypeOf () {
303 if (hasRequiredObjectIsPrototypeOf) return objectIsPrototypeOf;
304 hasRequiredObjectIsPrototypeOf = 1;
305 var uncurryThis = requireFunctionUncurryThis();
306
307 objectIsPrototypeOf = uncurryThis({}.isPrototypeOf);
308 return objectIsPrototypeOf;
309 }
310
311 var environmentUserAgent;
312 var hasRequiredEnvironmentUserAgent;
313
314 function requireEnvironmentUserAgent () {
315 if (hasRequiredEnvironmentUserAgent) return environmentUserAgent;
316 hasRequiredEnvironmentUserAgent = 1;
317 var globalThis = requireGlobalThis();
318
319 var navigator = globalThis.navigator;
320 var userAgent = navigator && navigator.userAgent;
321
322 environmentUserAgent = userAgent ? String(userAgent) : '';
323 return environmentUserAgent;
324 }
325
326 var environmentV8Version;
327 var hasRequiredEnvironmentV8Version;
328
329 function requireEnvironmentV8Version () {
330 if (hasRequiredEnvironmentV8Version) return environmentV8Version;
331 hasRequiredEnvironmentV8Version = 1;
332 var globalThis = requireGlobalThis();
333 var userAgent = requireEnvironmentUserAgent();
334
335 var process = globalThis.process;
336 var Deno = globalThis.Deno;
337 var versions = process && process.versions || Deno && Deno.version;
338 var v8 = versions && versions.v8;
339 var match, version;
340
341 if (v8) {
342 match = v8.split('.');
343 // in old Chrome, versions of V8 isn't V8 = Chrome / 10
344 // but their correct versions are not interesting for us
345 version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
346 }
347
348 // BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
349 // so check `userAgent` even if `.v8` exists, but 0
350 if (!version && userAgent) {
351 match = userAgent.match(/Edge\/(\d+)/);
352 if (!match || match[1] >= 74) {
353 match = userAgent.match(/Chrome\/(\d+)/);
354 if (match) version = +match[1];
355 }
356 }
357
358 environmentV8Version = version;
359 return environmentV8Version;
360 }
361
362 var symbolConstructorDetection;
363 var hasRequiredSymbolConstructorDetection;
364
365 function requireSymbolConstructorDetection () {
366 if (hasRequiredSymbolConstructorDetection) return symbolConstructorDetection;
367 hasRequiredSymbolConstructorDetection = 1;
368 /* eslint-disable es/no-symbol -- required for testing */
369 var V8_VERSION = requireEnvironmentV8Version();
370 var fails = requireFails();
371 var globalThis = requireGlobalThis();
372
373 var $String = globalThis.String;
374
375 // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
376 symbolConstructorDetection = !!Object.getOwnPropertySymbols && !fails(function () {
377 var symbol = Symbol('symbol detection');
378 // Chrome 38 Symbol has incorrect toString conversion
379 // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
380 // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will,
381 // of course, fail.
382 return !$String(symbol) || !(Object(symbol) instanceof Symbol) ||
383 // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
384 !Symbol.sham && V8_VERSION && V8_VERSION < 41;
385 });
386 return symbolConstructorDetection;
387 }
388
389 var useSymbolAsUid;
390 var hasRequiredUseSymbolAsUid;
391
392 function requireUseSymbolAsUid () {
393 if (hasRequiredUseSymbolAsUid) return useSymbolAsUid;
394 hasRequiredUseSymbolAsUid = 1;
395 /* eslint-disable es/no-symbol -- required for testing */
396 var NATIVE_SYMBOL = requireSymbolConstructorDetection();
397
398 useSymbolAsUid = NATIVE_SYMBOL &&
399 !Symbol.sham &&
400 typeof Symbol.iterator == 'symbol';
401 return useSymbolAsUid;
402 }
403
404 var isSymbol;
405 var hasRequiredIsSymbol;
406
407 function requireIsSymbol () {
408 if (hasRequiredIsSymbol) return isSymbol;
409 hasRequiredIsSymbol = 1;
410 var getBuiltIn = requireGetBuiltIn();
411 var isCallable = requireIsCallable();
412 var isPrototypeOf = requireObjectIsPrototypeOf();
413 var USE_SYMBOL_AS_UID = requireUseSymbolAsUid();
414
415 var $Object = Object;
416
417 isSymbol = USE_SYMBOL_AS_UID ? function (it) {
418 return typeof it == 'symbol';
419 } : function (it) {
420 var $Symbol = getBuiltIn('Symbol');
421 return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it));
422 };
423 return isSymbol;
424 }
425
426 var tryToString;
427 var hasRequiredTryToString;
428
429 function requireTryToString () {
430 if (hasRequiredTryToString) return tryToString;
431 hasRequiredTryToString = 1;
432 var $String = String;
433
434 tryToString = function (argument) {
435 try {
436 return $String(argument);
437 } catch (error) {
438 return 'Object';
439 }
440 };
441 return tryToString;
442 }
443
444 var aCallable;
445 var hasRequiredACallable;
446
447 function requireACallable () {
448 if (hasRequiredACallable) return aCallable;
449 hasRequiredACallable = 1;
450 var isCallable = requireIsCallable();
451 var tryToString = requireTryToString();
452
453 var $TypeError = TypeError;
454
455 // `Assert: IsCallable(argument) is true`
456 aCallable = function (argument) {
457 if (isCallable(argument)) return argument;
458 throw new $TypeError(tryToString(argument) + ' is not a function');
459 };
460 return aCallable;
461 }
462
463 var getMethod;
464 var hasRequiredGetMethod;
465
466 function requireGetMethod () {
467 if (hasRequiredGetMethod) return getMethod;
468 hasRequiredGetMethod = 1;
469 var aCallable = requireACallable();
470 var isNullOrUndefined = requireIsNullOrUndefined();
471
472 // `GetMethod` abstract operation
473 // https://tc39.es/ecma262/#sec-getmethod
474 getMethod = function (V, P) {
475 var func = V[P];
476 return isNullOrUndefined(func) ? undefined : aCallable(func);
477 };
478 return getMethod;
479 }
480
481 var ordinaryToPrimitive;
482 var hasRequiredOrdinaryToPrimitive;
483
484 function requireOrdinaryToPrimitive () {
485 if (hasRequiredOrdinaryToPrimitive) return ordinaryToPrimitive;
486 hasRequiredOrdinaryToPrimitive = 1;
487 var call = requireFunctionCall();
488 var isCallable = requireIsCallable();
489 var isObject = requireIsObject();
490
491 var $TypeError = TypeError;
492
493 // `OrdinaryToPrimitive` abstract operation
494 // https://tc39.es/ecma262/#sec-ordinarytoprimitive
495 ordinaryToPrimitive = function (input, pref) {
496 var fn, val;
497 if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
498 if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
499 if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
500 throw new $TypeError("Can't convert object to primitive value");
501 };
502 return ordinaryToPrimitive;
503 }
504
505 var sharedStore = {exports: {}};
506
507 var isPure;
508 var hasRequiredIsPure;
509
510 function requireIsPure () {
511 if (hasRequiredIsPure) return isPure;
512 hasRequiredIsPure = 1;
513 isPure = false;
514 return isPure;
515 }
516
517 var defineGlobalProperty;
518 var hasRequiredDefineGlobalProperty;
519
520 function requireDefineGlobalProperty () {
521 if (hasRequiredDefineGlobalProperty) return defineGlobalProperty;
522 hasRequiredDefineGlobalProperty = 1;
523 var globalThis = requireGlobalThis();
524
525 // eslint-disable-next-line es/no-object-defineproperty -- safe
526 var defineProperty = Object.defineProperty;
527
528 defineGlobalProperty = function (key, value) {
529 try {
530 defineProperty(globalThis, key, { value: value, configurable: true, writable: true });
531 } catch (error) {
532 globalThis[key] = value;
533 } return value;
534 };
535 return defineGlobalProperty;
536 }
537
538 var hasRequiredSharedStore;
539
540 function requireSharedStore () {
541 if (hasRequiredSharedStore) return sharedStore.exports;
542 hasRequiredSharedStore = 1;
543 var IS_PURE = requireIsPure();
544 var globalThis = requireGlobalThis();
545 var defineGlobalProperty = requireDefineGlobalProperty();
546
547 var SHARED = '__core-js_shared__';
548 var store = sharedStore.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {});
549
550 (store.versions || (store.versions = [])).push({
551 version: '3.39.0',
552 mode: IS_PURE ? 'pure' : 'global',
553 copyright: '© 2014-2024 Denis Pushkarev (zloirock.ru)',
554 license: 'https://github.com/zloirock/core-js/blob/v3.39.0/LICENSE',
555 source: 'https://github.com/zloirock/core-js'
556 });
557 return sharedStore.exports;
558 }
559
560 var shared;
561 var hasRequiredShared;
562
563 function requireShared () {
564 if (hasRequiredShared) return shared;
565 hasRequiredShared = 1;
566 var store = requireSharedStore();
567
568 shared = function (key, value) {
569 return store[key] || (store[key] = value || {});
570 };
571 return shared;
572 }
573
574 var toObject;
575 var hasRequiredToObject;
576
577 function requireToObject () {
578 if (hasRequiredToObject) return toObject;
579 hasRequiredToObject = 1;
580 var requireObjectCoercible = requireRequireObjectCoercible();
581
582 var $Object = Object;
583
584 // `ToObject` abstract operation
585 // https://tc39.es/ecma262/#sec-toobject
586 toObject = function (argument) {
587 return $Object(requireObjectCoercible(argument));
588 };
589 return toObject;
590 }
591
592 var hasOwnProperty_1;
593 var hasRequiredHasOwnProperty;
594
595 function requireHasOwnProperty () {
596 if (hasRequiredHasOwnProperty) return hasOwnProperty_1;
597 hasRequiredHasOwnProperty = 1;
598 var uncurryThis = requireFunctionUncurryThis();
599 var toObject = requireToObject();
600
601 var hasOwnProperty = uncurryThis({}.hasOwnProperty);
602
603 // `HasOwnProperty` abstract operation
604 // https://tc39.es/ecma262/#sec-hasownproperty
605 // eslint-disable-next-line es/no-object-hasown -- safe
606 hasOwnProperty_1 = Object.hasOwn || function hasOwn(it, key) {
607 return hasOwnProperty(toObject(it), key);
608 };
609 return hasOwnProperty_1;
610 }
611
612 var uid;
613 var hasRequiredUid;
614
615 function requireUid () {
616 if (hasRequiredUid) return uid;
617 hasRequiredUid = 1;
618 var uncurryThis = requireFunctionUncurryThis();
619
620 var id = 0;
621 var postfix = Math.random();
622 var toString = uncurryThis(1.0.toString);
623
624 uid = function (key) {
625 return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36);
626 };
627 return uid;
628 }
629
630 var wellKnownSymbol;
631 var hasRequiredWellKnownSymbol;
632
633 function requireWellKnownSymbol () {
634 if (hasRequiredWellKnownSymbol) return wellKnownSymbol;
635 hasRequiredWellKnownSymbol = 1;
636 var globalThis = requireGlobalThis();
637 var shared = requireShared();
638 var hasOwn = requireHasOwnProperty();
639 var uid = requireUid();
640 var NATIVE_SYMBOL = requireSymbolConstructorDetection();
641 var USE_SYMBOL_AS_UID = requireUseSymbolAsUid();
642
643 var Symbol = globalThis.Symbol;
644 var WellKnownSymbolsStore = shared('wks');
645 var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid;
646
647 wellKnownSymbol = function (name) {
648 if (!hasOwn(WellKnownSymbolsStore, name)) {
649 WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name)
650 ? Symbol[name]
651 : createWellKnownSymbol('Symbol.' + name);
652 } return WellKnownSymbolsStore[name];
653 };
654 return wellKnownSymbol;
655 }
656
657 var toPrimitive;
658 var hasRequiredToPrimitive;
659
660 function requireToPrimitive () {
661 if (hasRequiredToPrimitive) return toPrimitive;
662 hasRequiredToPrimitive = 1;
663 var call = requireFunctionCall();
664 var isObject = requireIsObject();
665 var isSymbol = requireIsSymbol();
666 var getMethod = requireGetMethod();
667 var ordinaryToPrimitive = requireOrdinaryToPrimitive();
668 var wellKnownSymbol = requireWellKnownSymbol();
669
670 var $TypeError = TypeError;
671 var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
672
673 // `ToPrimitive` abstract operation
674 // https://tc39.es/ecma262/#sec-toprimitive
675 toPrimitive = function (input, pref) {
676 if (!isObject(input) || isSymbol(input)) return input;
677 var exoticToPrim = getMethod(input, TO_PRIMITIVE);
678 var result;
679 if (exoticToPrim) {
680 if (pref === undefined) pref = 'default';
681 result = call(exoticToPrim, input, pref);
682 if (!isObject(result) || isSymbol(result)) return result;
683 throw new $TypeError("Can't convert object to primitive value");
684 }
685 if (pref === undefined) pref = 'number';
686 return ordinaryToPrimitive(input, pref);
687 };
688 return toPrimitive;
689 }
690
691 var toPropertyKey;
692 var hasRequiredToPropertyKey;
693
694 function requireToPropertyKey () {
695 if (hasRequiredToPropertyKey) return toPropertyKey;
696 hasRequiredToPropertyKey = 1;
697 var toPrimitive = requireToPrimitive();
698 var isSymbol = requireIsSymbol();
699
700 // `ToPropertyKey` abstract operation
701 // https://tc39.es/ecma262/#sec-topropertykey
702 toPropertyKey = function (argument) {
703 var key = toPrimitive(argument, 'string');
704 return isSymbol(key) ? key : key + '';
705 };
706 return toPropertyKey;
707 }
708
709 var documentCreateElement;
710 var hasRequiredDocumentCreateElement;
711
712 function requireDocumentCreateElement () {
713 if (hasRequiredDocumentCreateElement) return documentCreateElement;
714 hasRequiredDocumentCreateElement = 1;
715 var globalThis = requireGlobalThis();
716 var isObject = requireIsObject();
717
718 var document = globalThis.document;
719 // typeof document.createElement is 'object' in old IE
720 var EXISTS = isObject(document) && isObject(document.createElement);
721
722 documentCreateElement = function (it) {
723 return EXISTS ? document.createElement(it) : {};
724 };
725 return documentCreateElement;
726 }
727
728 var ie8DomDefine;
729 var hasRequiredIe8DomDefine;
730
731 function requireIe8DomDefine () {
732 if (hasRequiredIe8DomDefine) return ie8DomDefine;
733 hasRequiredIe8DomDefine = 1;
734 var DESCRIPTORS = requireDescriptors();
735 var fails = requireFails();
736 var createElement = requireDocumentCreateElement();
737
738 // Thanks to IE8 for its funny defineProperty
739 ie8DomDefine = !DESCRIPTORS && !fails(function () {
740 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
741 return Object.defineProperty(createElement('div'), 'a', {
742 get: function () { return 7; }
743 }).a !== 7;
744 });
745 return ie8DomDefine;
746 }
747
748 var hasRequiredObjectGetOwnPropertyDescriptor;
749
750 function requireObjectGetOwnPropertyDescriptor () {
751 if (hasRequiredObjectGetOwnPropertyDescriptor) return objectGetOwnPropertyDescriptor;
752 hasRequiredObjectGetOwnPropertyDescriptor = 1;
753 var DESCRIPTORS = requireDescriptors();
754 var call = requireFunctionCall();
755 var propertyIsEnumerableModule = requireObjectPropertyIsEnumerable();
756 var createPropertyDescriptor = requireCreatePropertyDescriptor();
757 var toIndexedObject = requireToIndexedObject();
758 var toPropertyKey = requireToPropertyKey();
759 var hasOwn = requireHasOwnProperty();
760 var IE8_DOM_DEFINE = requireIe8DomDefine();
761
762 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
763 var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
764
765 // `Object.getOwnPropertyDescriptor` method
766 // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
767 objectGetOwnPropertyDescriptor.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
768 O = toIndexedObject(O);
769 P = toPropertyKey(P);
770 if (IE8_DOM_DEFINE) try {
771 return $getOwnPropertyDescriptor(O, P);
772 } catch (error) { /* empty */ }
773 if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);
774 };
775 return objectGetOwnPropertyDescriptor;
776 }
777
778 var objectDefineProperty = {};
779
780 var v8PrototypeDefineBug;
781 var hasRequiredV8PrototypeDefineBug;
782
783 function requireV8PrototypeDefineBug () {
784 if (hasRequiredV8PrototypeDefineBug) return v8PrototypeDefineBug;
785 hasRequiredV8PrototypeDefineBug = 1;
786 var DESCRIPTORS = requireDescriptors();
787 var fails = requireFails();
788
789 // V8 ~ Chrome 36-
790 // https://bugs.chromium.org/p/v8/issues/detail?id=3334
791 v8PrototypeDefineBug = DESCRIPTORS && fails(function () {
792 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
793 return Object.defineProperty(function () { /* empty */ }, 'prototype', {
794 value: 42,
795 writable: false
796 }).prototype !== 42;
797 });
798 return v8PrototypeDefineBug;
799 }
800
801 var anObject;
802 var hasRequiredAnObject;
803
804 function requireAnObject () {
805 if (hasRequiredAnObject) return anObject;
806 hasRequiredAnObject = 1;
807 var isObject = requireIsObject();
808
809 var $String = String;
810 var $TypeError = TypeError;
811
812 // `Assert: Type(argument) is Object`
813 anObject = function (argument) {
814 if (isObject(argument)) return argument;
815 throw new $TypeError($String(argument) + ' is not an object');
816 };
817 return anObject;
818 }
819
820 var hasRequiredObjectDefineProperty;
821
822 function requireObjectDefineProperty () {
823 if (hasRequiredObjectDefineProperty) return objectDefineProperty;
824 hasRequiredObjectDefineProperty = 1;
825 var DESCRIPTORS = requireDescriptors();
826 var IE8_DOM_DEFINE = requireIe8DomDefine();
827 var V8_PROTOTYPE_DEFINE_BUG = requireV8PrototypeDefineBug();
828 var anObject = requireAnObject();
829 var toPropertyKey = requireToPropertyKey();
830
831 var $TypeError = TypeError;
832 // eslint-disable-next-line es/no-object-defineproperty -- safe
833 var $defineProperty = Object.defineProperty;
834 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
835 var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
836 var ENUMERABLE = 'enumerable';
837 var CONFIGURABLE = 'configurable';
838 var WRITABLE = 'writable';
839
840 // `Object.defineProperty` method
841 // https://tc39.es/ecma262/#sec-object.defineproperty
842 objectDefineProperty.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) {
843 anObject(O);
844 P = toPropertyKey(P);
845 anObject(Attributes);
846 if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
847 var current = $getOwnPropertyDescriptor(O, P);
848 if (current && current[WRITABLE]) {
849 O[P] = Attributes.value;
850 Attributes = {
851 configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
852 enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
853 writable: false
854 };
855 }
856 } return $defineProperty(O, P, Attributes);
857 } : $defineProperty : function defineProperty(O, P, Attributes) {
858 anObject(O);
859 P = toPropertyKey(P);
860 anObject(Attributes);
861 if (IE8_DOM_DEFINE) try {
862 return $defineProperty(O, P, Attributes);
863 } catch (error) { /* empty */ }
864 if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported');
865 if ('value' in Attributes) O[P] = Attributes.value;
866 return O;
867 };
868 return objectDefineProperty;
869 }
870
871 var createNonEnumerableProperty;
872 var hasRequiredCreateNonEnumerableProperty;
873
874 function requireCreateNonEnumerableProperty () {
875 if (hasRequiredCreateNonEnumerableProperty) return createNonEnumerableProperty;
876 hasRequiredCreateNonEnumerableProperty = 1;
877 var DESCRIPTORS = requireDescriptors();
878 var definePropertyModule = requireObjectDefineProperty();
879 var createPropertyDescriptor = requireCreatePropertyDescriptor();
880
881 createNonEnumerableProperty = DESCRIPTORS ? function (object, key, value) {
882 return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
883 } : function (object, key, value) {
884 object[key] = value;
885 return object;
886 };
887 return createNonEnumerableProperty;
888 }
889
890 var makeBuiltIn = {exports: {}};
891
892 var functionName;
893 var hasRequiredFunctionName;
894
895 function requireFunctionName () {
896 if (hasRequiredFunctionName) return functionName;
897 hasRequiredFunctionName = 1;
898 var DESCRIPTORS = requireDescriptors();
899 var hasOwn = requireHasOwnProperty();
900
901 var FunctionPrototype = Function.prototype;
902 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
903 var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;
904
905 var EXISTS = hasOwn(FunctionPrototype, 'name');
906 // additional protection from minified / mangled / dropped function names
907 var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
908 var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable));
909
910 functionName = {
911 EXISTS: EXISTS,
912 PROPER: PROPER,
913 CONFIGURABLE: CONFIGURABLE
914 };
915 return functionName;
916 }
917
918 var inspectSource;
919 var hasRequiredInspectSource;
920
921 function requireInspectSource () {
922 if (hasRequiredInspectSource) return inspectSource;
923 hasRequiredInspectSource = 1;
924 var uncurryThis = requireFunctionUncurryThis();
925 var isCallable = requireIsCallable();
926 var store = requireSharedStore();
927
928 var functionToString = uncurryThis(Function.toString);
929
930 // this helper broken in `[email protected]`, so we can't use `shared` helper
931 if (!isCallable(store.inspectSource)) {
932 store.inspectSource = function (it) {
933 return functionToString(it);
934 };
935 }
936
937 inspectSource = store.inspectSource;
938 return inspectSource;
939 }
940
941 var weakMapBasicDetection;
942 var hasRequiredWeakMapBasicDetection;
943
944 function requireWeakMapBasicDetection () {
945 if (hasRequiredWeakMapBasicDetection) return weakMapBasicDetection;
946 hasRequiredWeakMapBasicDetection = 1;
947 var globalThis = requireGlobalThis();
948 var isCallable = requireIsCallable();
949
950 var WeakMap = globalThis.WeakMap;
951
952 weakMapBasicDetection = isCallable(WeakMap) && /native code/.test(String(WeakMap));
953 return weakMapBasicDetection;
954 }
955
956 var sharedKey;
957 var hasRequiredSharedKey;
958
959 function requireSharedKey () {
960 if (hasRequiredSharedKey) return sharedKey;
961 hasRequiredSharedKey = 1;
962 var shared = requireShared();
963 var uid = requireUid();
964
965 var keys = shared('keys');
966
967 sharedKey = function (key) {
968 return keys[key] || (keys[key] = uid(key));
969 };
970 return sharedKey;
971 }
972
973 var hiddenKeys;
974 var hasRequiredHiddenKeys;
975
976 function requireHiddenKeys () {
977 if (hasRequiredHiddenKeys) return hiddenKeys;
978 hasRequiredHiddenKeys = 1;
979 hiddenKeys = {};
980 return hiddenKeys;
981 }
982
983 var internalState;
984 var hasRequiredInternalState;
985
986 function requireInternalState () {
987 if (hasRequiredInternalState) return internalState;
988 hasRequiredInternalState = 1;
989 var NATIVE_WEAK_MAP = requireWeakMapBasicDetection();
990 var globalThis = requireGlobalThis();
991 var isObject = requireIsObject();
992 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
993 var hasOwn = requireHasOwnProperty();
994 var shared = requireSharedStore();
995 var sharedKey = requireSharedKey();
996 var hiddenKeys = requireHiddenKeys();
997
998 var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
999 var TypeError = globalThis.TypeError;
1000 var WeakMap = globalThis.WeakMap;
1001 var set, get, has;
1002
1003 var enforce = function (it) {
1004 return has(it) ? get(it) : set(it, {});
1005 };
1006
1007 var getterFor = function (TYPE) {
1008 return function (it) {
1009 var state;
1010 if (!isObject(it) || (state = get(it)).type !== TYPE) {
1011 throw new TypeError('Incompatible receiver, ' + TYPE + ' required');
1012 } return state;
1013 };
1014 };
1015
1016 if (NATIVE_WEAK_MAP || shared.state) {
1017 var store = shared.state || (shared.state = new WeakMap());
1018 /* eslint-disable no-self-assign -- prototype methods protection */
1019 store.get = store.get;
1020 store.has = store.has;
1021 store.set = store.set;
1022 /* eslint-enable no-self-assign -- prototype methods protection */
1023 set = function (it, metadata) {
1024 if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
1025 metadata.facade = it;
1026 store.set(it, metadata);
1027 return metadata;
1028 };
1029 get = function (it) {
1030 return store.get(it) || {};
1031 };
1032 has = function (it) {
1033 return store.has(it);
1034 };
1035 } else {
1036 var STATE = sharedKey('state');
1037 hiddenKeys[STATE] = true;
1038 set = function (it, metadata) {
1039 if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
1040 metadata.facade = it;
1041 createNonEnumerableProperty(it, STATE, metadata);
1042 return metadata;
1043 };
1044 get = function (it) {
1045 return hasOwn(it, STATE) ? it[STATE] : {};
1046 };
1047 has = function (it) {
1048 return hasOwn(it, STATE);
1049 };
1050 }
1051
1052 internalState = {
1053 set: set,
1054 get: get,
1055 has: has,
1056 enforce: enforce,
1057 getterFor: getterFor
1058 };
1059 return internalState;
1060 }
1061
1062 var hasRequiredMakeBuiltIn;
1063
1064 function requireMakeBuiltIn () {
1065 if (hasRequiredMakeBuiltIn) return makeBuiltIn.exports;
1066 hasRequiredMakeBuiltIn = 1;
1067 var uncurryThis = requireFunctionUncurryThis();
1068 var fails = requireFails();
1069 var isCallable = requireIsCallable();
1070 var hasOwn = requireHasOwnProperty();
1071 var DESCRIPTORS = requireDescriptors();
1072 var CONFIGURABLE_FUNCTION_NAME = requireFunctionName().CONFIGURABLE;
1073 var inspectSource = requireInspectSource();
1074 var InternalStateModule = requireInternalState();
1075
1076 var enforceInternalState = InternalStateModule.enforce;
1077 var getInternalState = InternalStateModule.get;
1078 var $String = String;
1079 // eslint-disable-next-line es/no-object-defineproperty -- safe
1080 var defineProperty = Object.defineProperty;
1081 var stringSlice = uncurryThis(''.slice);
1082 var replace = uncurryThis(''.replace);
1083 var join = uncurryThis([].join);
1084
1085 var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () {
1086 return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8;
1087 });
1088
1089 var TEMPLATE = String(String).split('String');
1090
1091 var makeBuiltIn$1 = makeBuiltIn.exports = function (value, name, options) {
1092 if (stringSlice($String(name), 0, 7) === 'Symbol(') {
1093 name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']';
1094 }
1095 if (options && options.getter) name = 'get ' + name;
1096 if (options && options.setter) name = 'set ' + name;
1097 if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
1098 if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true });
1099 else value.name = name;
1100 }
1101 if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) {
1102 defineProperty(value, 'length', { value: options.arity });
1103 }
1104 try {
1105 if (options && hasOwn(options, 'constructor') && options.constructor) {
1106 if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false });
1107 // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable
1108 } else if (value.prototype) value.prototype = undefined;
1109 } catch (error) { /* empty */ }
1110 var state = enforceInternalState(value);
1111 if (!hasOwn(state, 'source')) {
1112 state.source = join(TEMPLATE, typeof name == 'string' ? name : '');
1113 } return value;
1114 };
1115
1116 // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
1117 // eslint-disable-next-line no-extend-native -- required
1118 Function.prototype.toString = makeBuiltIn$1(function toString() {
1119 return isCallable(this) && getInternalState(this).source || inspectSource(this);
1120 }, 'toString');
1121 return makeBuiltIn.exports;
1122 }
1123
1124 var defineBuiltIn;
1125 var hasRequiredDefineBuiltIn;
1126
1127 function requireDefineBuiltIn () {
1128 if (hasRequiredDefineBuiltIn) return defineBuiltIn;
1129 hasRequiredDefineBuiltIn = 1;
1130 var isCallable = requireIsCallable();
1131 var definePropertyModule = requireObjectDefineProperty();
1132 var makeBuiltIn = requireMakeBuiltIn();
1133 var defineGlobalProperty = requireDefineGlobalProperty();
1134
1135 defineBuiltIn = function (O, key, value, options) {
1136 if (!options) options = {};
1137 var simple = options.enumerable;
1138 var name = options.name !== undefined ? options.name : key;
1139 if (isCallable(value)) makeBuiltIn(value, name, options);
1140 if (options.global) {
1141 if (simple) O[key] = value;
1142 else defineGlobalProperty(key, value);
1143 } else {
1144 try {
1145 if (!options.unsafe) delete O[key];
1146 else if (O[key]) simple = true;
1147 } catch (error) { /* empty */ }
1148 if (simple) O[key] = value;
1149 else definePropertyModule.f(O, key, {
1150 value: value,
1151 enumerable: false,
1152 configurable: !options.nonConfigurable,
1153 writable: !options.nonWritable
1154 });
1155 } return O;
1156 };
1157 return defineBuiltIn;
1158 }
1159
1160 var objectGetOwnPropertyNames = {};
1161
1162 var mathTrunc;
1163 var hasRequiredMathTrunc;
1164
1165 function requireMathTrunc () {
1166 if (hasRequiredMathTrunc) return mathTrunc;
1167 hasRequiredMathTrunc = 1;
1168 var ceil = Math.ceil;
1169 var floor = Math.floor;
1170
1171 // `Math.trunc` method
1172 // https://tc39.es/ecma262/#sec-math.trunc
1173 // eslint-disable-next-line es/no-math-trunc -- safe
1174 mathTrunc = Math.trunc || function trunc(x) {
1175 var n = +x;
1176 return (n > 0 ? floor : ceil)(n);
1177 };
1178 return mathTrunc;
1179 }
1180
1181 var toIntegerOrInfinity;
1182 var hasRequiredToIntegerOrInfinity;
1183
1184 function requireToIntegerOrInfinity () {
1185 if (hasRequiredToIntegerOrInfinity) return toIntegerOrInfinity;
1186 hasRequiredToIntegerOrInfinity = 1;
1187 var trunc = requireMathTrunc();
1188
1189 // `ToIntegerOrInfinity` abstract operation
1190 // https://tc39.es/ecma262/#sec-tointegerorinfinity
1191 toIntegerOrInfinity = function (argument) {
1192 var number = +argument;
1193 // eslint-disable-next-line no-self-compare -- NaN check
1194 return number !== number || number === 0 ? 0 : trunc(number);
1195 };
1196 return toIntegerOrInfinity;
1197 }
1198
1199 var toAbsoluteIndex;
1200 var hasRequiredToAbsoluteIndex;
1201
1202 function requireToAbsoluteIndex () {
1203 if (hasRequiredToAbsoluteIndex) return toAbsoluteIndex;
1204 hasRequiredToAbsoluteIndex = 1;
1205 var toIntegerOrInfinity = requireToIntegerOrInfinity();
1206
1207 var max = Math.max;
1208 var min = Math.min;
1209
1210 // Helper for a popular repeating case of the spec:
1211 // Let integer be ? ToInteger(index).
1212 // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
1213 toAbsoluteIndex = function (index, length) {
1214 var integer = toIntegerOrInfinity(index);
1215 return integer < 0 ? max(integer + length, 0) : min(integer, length);
1216 };
1217 return toAbsoluteIndex;
1218 }
1219
1220 var toLength;
1221 var hasRequiredToLength;
1222
1223 function requireToLength () {
1224 if (hasRequiredToLength) return toLength;
1225 hasRequiredToLength = 1;
1226 var toIntegerOrInfinity = requireToIntegerOrInfinity();
1227
1228 var min = Math.min;
1229
1230 // `ToLength` abstract operation
1231 // https://tc39.es/ecma262/#sec-tolength
1232 toLength = function (argument) {
1233 var len = toIntegerOrInfinity(argument);
1234 return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
1235 };
1236 return toLength;
1237 }
1238
1239 var lengthOfArrayLike;
1240 var hasRequiredLengthOfArrayLike;
1241
1242 function requireLengthOfArrayLike () {
1243 if (hasRequiredLengthOfArrayLike) return lengthOfArrayLike;
1244 hasRequiredLengthOfArrayLike = 1;
1245 var toLength = requireToLength();
1246
1247 // `LengthOfArrayLike` abstract operation
1248 // https://tc39.es/ecma262/#sec-lengthofarraylike
1249 lengthOfArrayLike = function (obj) {
1250 return toLength(obj.length);
1251 };
1252 return lengthOfArrayLike;
1253 }
1254
1255 var arrayIncludes;
1256 var hasRequiredArrayIncludes;
1257
1258 function requireArrayIncludes () {
1259 if (hasRequiredArrayIncludes) return arrayIncludes;
1260 hasRequiredArrayIncludes = 1;
1261 var toIndexedObject = requireToIndexedObject();
1262 var toAbsoluteIndex = requireToAbsoluteIndex();
1263 var lengthOfArrayLike = requireLengthOfArrayLike();
1264
1265 // `Array.prototype.{ indexOf, includes }` methods implementation
1266 var createMethod = function (IS_INCLUDES) {
1267 return function ($this, el, fromIndex) {
1268 var O = toIndexedObject($this);
1269 var length = lengthOfArrayLike(O);
1270 if (length === 0) return !IS_INCLUDES && -1;
1271 var index = toAbsoluteIndex(fromIndex, length);
1272 var value;
1273 // Array#includes uses SameValueZero equality algorithm
1274 // eslint-disable-next-line no-self-compare -- NaN check
1275 if (IS_INCLUDES && el !== el) while (length > index) {
1276 value = O[index++];
1277 // eslint-disable-next-line no-self-compare -- NaN check
1278 if (value !== value) return true;
1279 // Array#indexOf ignores holes, Array#includes - not
1280 } else for (;length > index; index++) {
1281 if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
1282 } return !IS_INCLUDES && -1;
1283 };
1284 };
1285
1286 arrayIncludes = {
1287 // `Array.prototype.includes` method
1288 // https://tc39.es/ecma262/#sec-array.prototype.includes
1289 includes: createMethod(true),
1290 // `Array.prototype.indexOf` method
1291 // https://tc39.es/ecma262/#sec-array.prototype.indexof
1292 indexOf: createMethod(false)
1293 };
1294 return arrayIncludes;
1295 }
1296
1297 var objectKeysInternal;
1298 var hasRequiredObjectKeysInternal;
1299
1300 function requireObjectKeysInternal () {
1301 if (hasRequiredObjectKeysInternal) return objectKeysInternal;
1302 hasRequiredObjectKeysInternal = 1;
1303 var uncurryThis = requireFunctionUncurryThis();
1304 var hasOwn = requireHasOwnProperty();
1305 var toIndexedObject = requireToIndexedObject();
1306 var indexOf = requireArrayIncludes().indexOf;
1307 var hiddenKeys = requireHiddenKeys();
1308
1309 var push = uncurryThis([].push);
1310
1311 objectKeysInternal = function (object, names) {
1312 var O = toIndexedObject(object);
1313 var i = 0;
1314 var result = [];
1315 var key;
1316 for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);
1317 // Don't enum bug & hidden keys
1318 while (names.length > i) if (hasOwn(O, key = names[i++])) {
1319 ~indexOf(result, key) || push(result, key);
1320 }
1321 return result;
1322 };
1323 return objectKeysInternal;
1324 }
1325
1326 var enumBugKeys;
1327 var hasRequiredEnumBugKeys;
1328
1329 function requireEnumBugKeys () {
1330 if (hasRequiredEnumBugKeys) return enumBugKeys;
1331 hasRequiredEnumBugKeys = 1;
1332 // IE8- don't enum bug keys
1333 enumBugKeys = [
1334 'constructor',
1335 'hasOwnProperty',
1336 'isPrototypeOf',
1337 'propertyIsEnumerable',
1338 'toLocaleString',
1339 'toString',
1340 'valueOf'
1341 ];
1342 return enumBugKeys;
1343 }
1344
1345 var hasRequiredObjectGetOwnPropertyNames;
1346
1347 function requireObjectGetOwnPropertyNames () {
1348 if (hasRequiredObjectGetOwnPropertyNames) return objectGetOwnPropertyNames;
1349 hasRequiredObjectGetOwnPropertyNames = 1;
1350 var internalObjectKeys = requireObjectKeysInternal();
1351 var enumBugKeys = requireEnumBugKeys();
1352
1353 var hiddenKeys = enumBugKeys.concat('length', 'prototype');
1354
1355 // `Object.getOwnPropertyNames` method
1356 // https://tc39.es/ecma262/#sec-object.getownpropertynames
1357 // eslint-disable-next-line es/no-object-getownpropertynames -- safe
1358 objectGetOwnPropertyNames.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
1359 return internalObjectKeys(O, hiddenKeys);
1360 };
1361 return objectGetOwnPropertyNames;
1362 }
1363
1364 var objectGetOwnPropertySymbols = {};
1365
1366 var hasRequiredObjectGetOwnPropertySymbols;
1367
1368 function requireObjectGetOwnPropertySymbols () {
1369 if (hasRequiredObjectGetOwnPropertySymbols) return objectGetOwnPropertySymbols;
1370 hasRequiredObjectGetOwnPropertySymbols = 1;
1371 // eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
1372 objectGetOwnPropertySymbols.f = Object.getOwnPropertySymbols;
1373 return objectGetOwnPropertySymbols;
1374 }
1375
1376 var ownKeys;
1377 var hasRequiredOwnKeys;
1378
1379 function requireOwnKeys () {
1380 if (hasRequiredOwnKeys) return ownKeys;
1381 hasRequiredOwnKeys = 1;
1382 var getBuiltIn = requireGetBuiltIn();
1383 var uncurryThis = requireFunctionUncurryThis();
1384 var getOwnPropertyNamesModule = requireObjectGetOwnPropertyNames();
1385 var getOwnPropertySymbolsModule = requireObjectGetOwnPropertySymbols();
1386 var anObject = requireAnObject();
1387
1388 var concat = uncurryThis([].concat);
1389
1390 // all object keys, includes non-enumerable and symbols
1391 ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
1392 var keys = getOwnPropertyNamesModule.f(anObject(it));
1393 var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
1394 return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
1395 };
1396 return ownKeys;
1397 }
1398
1399 var copyConstructorProperties;
1400 var hasRequiredCopyConstructorProperties;
1401
1402 function requireCopyConstructorProperties () {
1403 if (hasRequiredCopyConstructorProperties) return copyConstructorProperties;
1404 hasRequiredCopyConstructorProperties = 1;
1405 var hasOwn = requireHasOwnProperty();
1406 var ownKeys = requireOwnKeys();
1407 var getOwnPropertyDescriptorModule = requireObjectGetOwnPropertyDescriptor();
1408 var definePropertyModule = requireObjectDefineProperty();
1409
1410 copyConstructorProperties = function (target, source, exceptions) {
1411 var keys = ownKeys(source);
1412 var defineProperty = definePropertyModule.f;
1413 var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
1414 for (var i = 0; i < keys.length; i++) {
1415 var key = keys[i];
1416 if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) {
1417 defineProperty(target, key, getOwnPropertyDescriptor(source, key));
1418 }
1419 }
1420 };
1421 return copyConstructorProperties;
1422 }
1423
1424 var isForced_1;
1425 var hasRequiredIsForced;
1426
1427 function requireIsForced () {
1428 if (hasRequiredIsForced) return isForced_1;
1429 hasRequiredIsForced = 1;
1430 var fails = requireFails();
1431 var isCallable = requireIsCallable();
1432
1433 var replacement = /#|\.prototype\./;
1434
1435 var isForced = function (feature, detection) {
1436 var value = data[normalize(feature)];
1437 return value === POLYFILL ? true
1438 : value === NATIVE ? false
1439 : isCallable(detection) ? fails(detection)
1440 : !!detection;
1441 };
1442
1443 var normalize = isForced.normalize = function (string) {
1444 return String(string).replace(replacement, '.').toLowerCase();
1445 };
1446
1447 var data = isForced.data = {};
1448 var NATIVE = isForced.NATIVE = 'N';
1449 var POLYFILL = isForced.POLYFILL = 'P';
1450
1451 isForced_1 = isForced;
1452 return isForced_1;
1453 }
1454
1455 var _export;
1456 var hasRequired_export;
1457
1458 function require_export () {
1459 if (hasRequired_export) return _export;
1460 hasRequired_export = 1;
1461 var globalThis = requireGlobalThis();
1462 var getOwnPropertyDescriptor = requireObjectGetOwnPropertyDescriptor().f;
1463 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1464 var defineBuiltIn = requireDefineBuiltIn();
1465 var defineGlobalProperty = requireDefineGlobalProperty();
1466 var copyConstructorProperties = requireCopyConstructorProperties();
1467 var isForced = requireIsForced();
1468
1469 /*
1470 options.target - name of the target object
1471 options.global - target is the global object
1472 options.stat - export as static methods of target
1473 options.proto - export as prototype methods of target
1474 options.real - real prototype method for the `pure` version
1475 options.forced - export even if the native feature is available
1476 options.bind - bind methods to the target, required for the `pure` version
1477 options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
1478 options.unsafe - use the simple assignment of property instead of delete + defineProperty
1479 options.sham - add a flag to not completely full polyfills
1480 options.enumerable - export as enumerable property
1481 options.dontCallGetSet - prevent calling a getter on target
1482 options.name - the .name of the function if it does not match the key
1483 */
1484 _export = function (options, source) {
1485 var TARGET = options.target;
1486 var GLOBAL = options.global;
1487 var STATIC = options.stat;
1488 var FORCED, target, key, targetProperty, sourceProperty, descriptor;
1489 if (GLOBAL) {
1490 target = globalThis;
1491 } else if (STATIC) {
1492 target = globalThis[TARGET] || defineGlobalProperty(TARGET, {});
1493 } else {
1494 target = globalThis[TARGET] && globalThis[TARGET].prototype;
1495 }
1496 if (target) for (key in source) {
1497 sourceProperty = source[key];
1498 if (options.dontCallGetSet) {
1499 descriptor = getOwnPropertyDescriptor(target, key);
1500 targetProperty = descriptor && descriptor.value;
1501 } else targetProperty = target[key];
1502 FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
1503 // contained in target
1504 if (!FORCED && targetProperty !== undefined) {
1505 if (typeof sourceProperty == typeof targetProperty) continue;
1506 copyConstructorProperties(sourceProperty, targetProperty);
1507 }
1508 // add a flag to not completely full polyfills
1509 if (options.sham || (targetProperty && targetProperty.sham)) {
1510 createNonEnumerableProperty(sourceProperty, 'sham', true);
1511 }
1512 defineBuiltIn(target, key, sourceProperty, options);
1513 }
1514 };
1515 return _export;
1516 }
1517
1518 var functionApply;
1519 var hasRequiredFunctionApply;
1520
1521 function requireFunctionApply () {
1522 if (hasRequiredFunctionApply) return functionApply;
1523 hasRequiredFunctionApply = 1;
1524 var NATIVE_BIND = requireFunctionBindNative();
1525
1526 var FunctionPrototype = Function.prototype;
1527 var apply = FunctionPrototype.apply;
1528 var call = FunctionPrototype.call;
1529
1530 // eslint-disable-next-line es/no-reflect -- safe
1531 functionApply = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () {
1532 return call.apply(apply, arguments);
1533 });
1534 return functionApply;
1535 }
1536
1537 var functionUncurryThisAccessor;
1538 var hasRequiredFunctionUncurryThisAccessor;
1539
1540 function requireFunctionUncurryThisAccessor () {
1541 if (hasRequiredFunctionUncurryThisAccessor) return functionUncurryThisAccessor;
1542 hasRequiredFunctionUncurryThisAccessor = 1;
1543 var uncurryThis = requireFunctionUncurryThis();
1544 var aCallable = requireACallable();
1545
1546 functionUncurryThisAccessor = function (object, key, method) {
1547 try {
1548 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
1549 return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method]));
1550 } catch (error) { /* empty */ }
1551 };
1552 return functionUncurryThisAccessor;
1553 }
1554
1555 var isPossiblePrototype;
1556 var hasRequiredIsPossiblePrototype;
1557
1558 function requireIsPossiblePrototype () {
1559 if (hasRequiredIsPossiblePrototype) return isPossiblePrototype;
1560 hasRequiredIsPossiblePrototype = 1;
1561 var isObject = requireIsObject();
1562
1563 isPossiblePrototype = function (argument) {
1564 return isObject(argument) || argument === null;
1565 };
1566 return isPossiblePrototype;
1567 }
1568
1569 var aPossiblePrototype;
1570 var hasRequiredAPossiblePrototype;
1571
1572 function requireAPossiblePrototype () {
1573 if (hasRequiredAPossiblePrototype) return aPossiblePrototype;
1574 hasRequiredAPossiblePrototype = 1;
1575 var isPossiblePrototype = requireIsPossiblePrototype();
1576
1577 var $String = String;
1578 var $TypeError = TypeError;
1579
1580 aPossiblePrototype = function (argument) {
1581 if (isPossiblePrototype(argument)) return argument;
1582 throw new $TypeError("Can't set " + $String(argument) + ' as a prototype');
1583 };
1584 return aPossiblePrototype;
1585 }
1586
1587 var objectSetPrototypeOf;
1588 var hasRequiredObjectSetPrototypeOf;
1589
1590 function requireObjectSetPrototypeOf () {
1591 if (hasRequiredObjectSetPrototypeOf) return objectSetPrototypeOf;
1592 hasRequiredObjectSetPrototypeOf = 1;
1593 /* eslint-disable no-proto -- safe */
1594 var uncurryThisAccessor = requireFunctionUncurryThisAccessor();
1595 var isObject = requireIsObject();
1596 var requireObjectCoercible = requireRequireObjectCoercible();
1597 var aPossiblePrototype = requireAPossiblePrototype();
1598
1599 // `Object.setPrototypeOf` method
1600 // https://tc39.es/ecma262/#sec-object.setprototypeof
1601 // Works with __proto__ only. Old v8 can't work with null proto objects.
1602 // eslint-disable-next-line es/no-object-setprototypeof -- safe
1603 objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
1604 var CORRECT_SETTER = false;
1605 var test = {};
1606 var setter;
1607 try {
1608 setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set');
1609 setter(test, []);
1610 CORRECT_SETTER = test instanceof Array;
1611 } catch (error) { /* empty */ }
1612 return function setPrototypeOf(O, proto) {
1613 requireObjectCoercible(O);
1614 aPossiblePrototype(proto);
1615 if (!isObject(O)) return O;
1616 if (CORRECT_SETTER) setter(O, proto);
1617 else O.__proto__ = proto;
1618 return O;
1619 };
1620 }() : undefined);
1621 return objectSetPrototypeOf;
1622 }
1623
1624 var proxyAccessor;
1625 var hasRequiredProxyAccessor;
1626
1627 function requireProxyAccessor () {
1628 if (hasRequiredProxyAccessor) return proxyAccessor;
1629 hasRequiredProxyAccessor = 1;
1630 var defineProperty = requireObjectDefineProperty().f;
1631
1632 proxyAccessor = function (Target, Source, key) {
1633 key in Target || defineProperty(Target, key, {
1634 configurable: true,
1635 get: function () { return Source[key]; },
1636 set: function (it) { Source[key] = it; }
1637 });
1638 };
1639 return proxyAccessor;
1640 }
1641
1642 var inheritIfRequired;
1643 var hasRequiredInheritIfRequired;
1644
1645 function requireInheritIfRequired () {
1646 if (hasRequiredInheritIfRequired) return inheritIfRequired;
1647 hasRequiredInheritIfRequired = 1;
1648 var isCallable = requireIsCallable();
1649 var isObject = requireIsObject();
1650 var setPrototypeOf = requireObjectSetPrototypeOf();
1651
1652 // makes subclassing work correct for wrapped built-ins
1653 inheritIfRequired = function ($this, dummy, Wrapper) {
1654 var NewTarget, NewTargetPrototype;
1655 if (
1656 // it can work only with native `setPrototypeOf`
1657 setPrototypeOf &&
1658 // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
1659 isCallable(NewTarget = dummy.constructor) &&
1660 NewTarget !== Wrapper &&
1661 isObject(NewTargetPrototype = NewTarget.prototype) &&
1662 NewTargetPrototype !== Wrapper.prototype
1663 ) setPrototypeOf($this, NewTargetPrototype);
1664 return $this;
1665 };
1666 return inheritIfRequired;
1667 }
1668
1669 var toStringTagSupport;
1670 var hasRequiredToStringTagSupport;
1671
1672 function requireToStringTagSupport () {
1673 if (hasRequiredToStringTagSupport) return toStringTagSupport;
1674 hasRequiredToStringTagSupport = 1;
1675 var wellKnownSymbol = requireWellKnownSymbol();
1676
1677 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
1678 var test = {};
1679
1680 test[TO_STRING_TAG] = 'z';
1681
1682 toStringTagSupport = String(test) === '[object z]';
1683 return toStringTagSupport;
1684 }
1685
1686 var classof;
1687 var hasRequiredClassof;
1688
1689 function requireClassof () {
1690 if (hasRequiredClassof) return classof;
1691 hasRequiredClassof = 1;
1692 var TO_STRING_TAG_SUPPORT = requireToStringTagSupport();
1693 var isCallable = requireIsCallable();
1694 var classofRaw = requireClassofRaw();
1695 var wellKnownSymbol = requireWellKnownSymbol();
1696
1697 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
1698 var $Object = Object;
1699
1700 // ES3 wrong here
1701 var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments';
1702
1703 // fallback for IE11 Script Access Denied error
1704 var tryGet = function (it, key) {
1705 try {
1706 return it[key];
1707 } catch (error) { /* empty */ }
1708 };
1709
1710 // getting tag from ES6+ `Object.prototype.toString`
1711 classof = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
1712 var O, tag, result;
1713 return it === undefined ? 'Undefined' : it === null ? 'Null'
1714 // @@toStringTag case
1715 : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag
1716 // builtinTag case
1717 : CORRECT_ARGUMENTS ? classofRaw(O)
1718 // ES3 arguments fallback
1719 : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result;
1720 };
1721 return classof;
1722 }
1723
1724 var toString;
1725 var hasRequiredToString;
1726
1727 function requireToString () {
1728 if (hasRequiredToString) return toString;
1729 hasRequiredToString = 1;
1730 var classof = requireClassof();
1731
1732 var $String = String;
1733
1734 toString = function (argument) {
1735 if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string');
1736 return $String(argument);
1737 };
1738 return toString;
1739 }
1740
1741 var normalizeStringArgument;
1742 var hasRequiredNormalizeStringArgument;
1743
1744 function requireNormalizeStringArgument () {
1745 if (hasRequiredNormalizeStringArgument) return normalizeStringArgument;
1746 hasRequiredNormalizeStringArgument = 1;
1747 var toString = requireToString();
1748
1749 normalizeStringArgument = function (argument, $default) {
1750 return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument);
1751 };
1752 return normalizeStringArgument;
1753 }
1754
1755 var installErrorCause;
1756 var hasRequiredInstallErrorCause;
1757
1758 function requireInstallErrorCause () {
1759 if (hasRequiredInstallErrorCause) return installErrorCause;
1760 hasRequiredInstallErrorCause = 1;
1761 var isObject = requireIsObject();
1762 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1763
1764 // `InstallErrorCause` abstract operation
1765 // https://tc39.es/proposal-error-cause/#sec-errorobjects-install-error-cause
1766 installErrorCause = function (O, options) {
1767 if (isObject(options) && 'cause' in options) {
1768 createNonEnumerableProperty(O, 'cause', options.cause);
1769 }
1770 };
1771 return installErrorCause;
1772 }
1773
1774 var errorStackClear;
1775 var hasRequiredErrorStackClear;
1776
1777 function requireErrorStackClear () {
1778 if (hasRequiredErrorStackClear) return errorStackClear;
1779 hasRequiredErrorStackClear = 1;
1780 var uncurryThis = requireFunctionUncurryThis();
1781
1782 var $Error = Error;
1783 var replace = uncurryThis(''.replace);
1784
1785 var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd');
1786 // eslint-disable-next-line redos/no-vulnerable, sonarjs/slow-regex -- safe
1787 var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/;
1788 var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);
1789
1790 errorStackClear = function (stack, dropEntries) {
1791 if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) {
1792 while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, '');
1793 } return stack;
1794 };
1795 return errorStackClear;
1796 }
1797
1798 var errorStackInstallable;
1799 var hasRequiredErrorStackInstallable;
1800
1801 function requireErrorStackInstallable () {
1802 if (hasRequiredErrorStackInstallable) return errorStackInstallable;
1803 hasRequiredErrorStackInstallable = 1;
1804 var fails = requireFails();
1805 var createPropertyDescriptor = requireCreatePropertyDescriptor();
1806
1807 errorStackInstallable = !fails(function () {
1808 var error = new Error('a');
1809 if (!('stack' in error)) return true;
1810 // eslint-disable-next-line es/no-object-defineproperty -- safe
1811 Object.defineProperty(error, 'stack', createPropertyDescriptor(1, 7));
1812 return error.stack !== 7;
1813 });
1814 return errorStackInstallable;
1815 }
1816
1817 var errorStackInstall;
1818 var hasRequiredErrorStackInstall;
1819
1820 function requireErrorStackInstall () {
1821 if (hasRequiredErrorStackInstall) return errorStackInstall;
1822 hasRequiredErrorStackInstall = 1;
1823 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1824 var clearErrorStack = requireErrorStackClear();
1825 var ERROR_STACK_INSTALLABLE = requireErrorStackInstallable();
1826
1827 // non-standard V8
1828 var captureStackTrace = Error.captureStackTrace;
1829
1830 errorStackInstall = function (error, C, stack, dropEntries) {
1831 if (ERROR_STACK_INSTALLABLE) {
1832 if (captureStackTrace) captureStackTrace(error, C);
1833 else createNonEnumerableProperty(error, 'stack', clearErrorStack(stack, dropEntries));
1834 }
1835 };
1836 return errorStackInstall;
1837 }
1838
1839 var wrapErrorConstructorWithCause;
1840 var hasRequiredWrapErrorConstructorWithCause;
1841
1842 function requireWrapErrorConstructorWithCause () {
1843 if (hasRequiredWrapErrorConstructorWithCause) return wrapErrorConstructorWithCause;
1844 hasRequiredWrapErrorConstructorWithCause = 1;
1845 var getBuiltIn = requireGetBuiltIn();
1846 var hasOwn = requireHasOwnProperty();
1847 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1848 var isPrototypeOf = requireObjectIsPrototypeOf();
1849 var setPrototypeOf = requireObjectSetPrototypeOf();
1850 var copyConstructorProperties = requireCopyConstructorProperties();
1851 var proxyAccessor = requireProxyAccessor();
1852 var inheritIfRequired = requireInheritIfRequired();
1853 var normalizeStringArgument = requireNormalizeStringArgument();
1854 var installErrorCause = requireInstallErrorCause();
1855 var installErrorStack = requireErrorStackInstall();
1856 var DESCRIPTORS = requireDescriptors();
1857 var IS_PURE = requireIsPure();
1858
1859 wrapErrorConstructorWithCause = function (FULL_NAME, wrapper, FORCED, IS_AGGREGATE_ERROR) {
1860 var STACK_TRACE_LIMIT = 'stackTraceLimit';
1861 var OPTIONS_POSITION = IS_AGGREGATE_ERROR ? 2 : 1;
1862 var path = FULL_NAME.split('.');
1863 var ERROR_NAME = path[path.length - 1];
1864 var OriginalError = getBuiltIn.apply(null, path);
1865
1866 if (!OriginalError) return;
1867
1868 var OriginalErrorPrototype = OriginalError.prototype;
1869
1870 // V8 9.3- bug https://bugs.chromium.org/p/v8/issues/detail?id=12006
1871 if (!IS_PURE && hasOwn(OriginalErrorPrototype, 'cause')) delete OriginalErrorPrototype.cause;
1872
1873 if (!FORCED) return OriginalError;
1874
1875 var BaseError = getBuiltIn('Error');
1876
1877 var WrappedError = wrapper(function (a, b) {
1878 var message = normalizeStringArgument(IS_AGGREGATE_ERROR ? b : a, undefined);
1879 var result = IS_AGGREGATE_ERROR ? new OriginalError(a) : new OriginalError();
1880 if (message !== undefined) createNonEnumerableProperty(result, 'message', message);
1881 installErrorStack(result, WrappedError, result.stack, 2);
1882 if (this && isPrototypeOf(OriginalErrorPrototype, this)) inheritIfRequired(result, this, WrappedError);
1883 if (arguments.length > OPTIONS_POSITION) installErrorCause(result, arguments[OPTIONS_POSITION]);
1884 return result;
1885 });
1886
1887 WrappedError.prototype = OriginalErrorPrototype;
1888
1889 if (ERROR_NAME !== 'Error') {
1890 if (setPrototypeOf) setPrototypeOf(WrappedError, BaseError);
1891 else copyConstructorProperties(WrappedError, BaseError, { name: true });
1892 } else if (DESCRIPTORS && STACK_TRACE_LIMIT in OriginalError) {
1893 proxyAccessor(WrappedError, OriginalError, STACK_TRACE_LIMIT);
1894 proxyAccessor(WrappedError, OriginalError, 'prepareStackTrace');
1895 }
1896
1897 copyConstructorProperties(WrappedError, OriginalError);
1898
1899 if (!IS_PURE) try {
1900 // Safari 13- bug: WebAssembly errors does not have a proper `.name`
1901 if (OriginalErrorPrototype.name !== ERROR_NAME) {
1902 createNonEnumerableProperty(OriginalErrorPrototype, 'name', ERROR_NAME);
1903 }
1904 OriginalErrorPrototype.constructor = WrappedError;
1905 } catch (error) { /* empty */ }
1906
1907 return WrappedError;
1908 };
1909 return wrapErrorConstructorWithCause;
1910 }
1911
1912 var hasRequiredEs_error_cause;
1913
1914 function requireEs_error_cause () {
1915 if (hasRequiredEs_error_cause) return es_error_cause;
1916 hasRequiredEs_error_cause = 1;
1917 /* eslint-disable no-unused-vars -- required for functions `.length` */
1918 var $ = require_export();
1919 var globalThis = requireGlobalThis();
1920 var apply = requireFunctionApply();
1921 var wrapErrorConstructorWithCause = requireWrapErrorConstructorWithCause();
1922
1923 var WEB_ASSEMBLY = 'WebAssembly';
1924 var WebAssembly = globalThis[WEB_ASSEMBLY];
1925
1926 // eslint-disable-next-line es/no-error-cause -- feature detection
1927 var FORCED = new Error('e', { cause: 7 }).cause !== 7;
1928
1929 var exportGlobalErrorCauseWrapper = function (ERROR_NAME, wrapper) {
1930 var O = {};
1931 O[ERROR_NAME] = wrapErrorConstructorWithCause(ERROR_NAME, wrapper, FORCED);
1932 $({ global: true, constructor: true, arity: 1, forced: FORCED }, O);
1933 };
1934
1935 var exportWebAssemblyErrorCauseWrapper = function (ERROR_NAME, wrapper) {
1936 if (WebAssembly && WebAssembly[ERROR_NAME]) {
1937 var O = {};
1938 O[ERROR_NAME] = wrapErrorConstructorWithCause(WEB_ASSEMBLY + '.' + ERROR_NAME, wrapper, FORCED);
1939 $({ target: WEB_ASSEMBLY, stat: true, constructor: true, arity: 1, forced: FORCED }, O);
1940 }
1941 };
1942
1943 // https://tc39.es/ecma262/#sec-nativeerror
1944 exportGlobalErrorCauseWrapper('Error', function (init) {
1945 return function Error(message) { return apply(init, this, arguments); };
1946 });
1947 exportGlobalErrorCauseWrapper('EvalError', function (init) {
1948 return function EvalError(message) { return apply(init, this, arguments); };
1949 });
1950 exportGlobalErrorCauseWrapper('RangeError', function (init) {
1951 return function RangeError(message) { return apply(init, this, arguments); };
1952 });
1953 exportGlobalErrorCauseWrapper('ReferenceError', function (init) {
1954 return function ReferenceError(message) { return apply(init, this, arguments); };
1955 });
1956 exportGlobalErrorCauseWrapper('SyntaxError', function (init) {
1957 return function SyntaxError(message) { return apply(init, this, arguments); };
1958 });
1959 exportGlobalErrorCauseWrapper('TypeError', function (init) {
1960 return function TypeError(message) { return apply(init, this, arguments); };
1961 });
1962 exportGlobalErrorCauseWrapper('URIError', function (init) {
1963 return function URIError(message) { return apply(init, this, arguments); };
1964 });
1965 exportWebAssemblyErrorCauseWrapper('CompileError', function (init) {
1966 return function CompileError(message) { return apply(init, this, arguments); };
1967 });
1968 exportWebAssemblyErrorCauseWrapper('LinkError', function (init) {
1969 return function LinkError(message) { return apply(init, this, arguments); };
1970 });
1971 exportWebAssemblyErrorCauseWrapper('RuntimeError', function (init) {
1972 return function RuntimeError(message) { return apply(init, this, arguments); };
1973 });
1974 return es_error_cause;
1975 }
1976
1977 requireEs_error_cause();
1978
1979 var es_array_push = {};
1980
1981 var isArray;
1982 var hasRequiredIsArray;
1983
1984 function requireIsArray () {
1985 if (hasRequiredIsArray) return isArray;
1986 hasRequiredIsArray = 1;
1987 var classof = requireClassofRaw();
1988
1989 // `IsArray` abstract operation
1990 // https://tc39.es/ecma262/#sec-isarray
1991 // eslint-disable-next-line es/no-array-isarray -- safe
1992 isArray = Array.isArray || function isArray(argument) {
1993 return classof(argument) === 'Array';
1994 };
1995 return isArray;
1996 }
1997
1998 var arraySetLength;
1999 var hasRequiredArraySetLength;
2000
2001 function requireArraySetLength () {
2002 if (hasRequiredArraySetLength) return arraySetLength;
2003 hasRequiredArraySetLength = 1;
2004 var DESCRIPTORS = requireDescriptors();
2005 var isArray = requireIsArray();
2006
2007 var $TypeError = TypeError;
2008 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
2009 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
2010
2011 // Safari < 13 does not throw an error in this case
2012 var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () {
2013 // makes no sense without proper strict mode support
2014 if (this !== undefined) return true;
2015 try {
2016 // eslint-disable-next-line es/no-object-defineproperty -- safe
2017 Object.defineProperty([], 'length', { writable: false }).length = 1;
2018 } catch (error) {
2019 return error instanceof TypeError;
2020 }
2021 }();
2022
2023 arraySetLength = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
2024 if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) {
2025 throw new $TypeError('Cannot set read only .length');
2026 } return O.length = length;
2027 } : function (O, length) {
2028 return O.length = length;
2029 };
2030 return arraySetLength;
2031 }
2032
2033 var doesNotExceedSafeInteger;
2034 var hasRequiredDoesNotExceedSafeInteger;
2035
2036 function requireDoesNotExceedSafeInteger () {
2037 if (hasRequiredDoesNotExceedSafeInteger) return doesNotExceedSafeInteger;
2038 hasRequiredDoesNotExceedSafeInteger = 1;
2039 var $TypeError = TypeError;
2040 var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991
2041
2042 doesNotExceedSafeInteger = function (it) {
2043 if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded');
2044 return it;
2045 };
2046 return doesNotExceedSafeInteger;
2047 }
2048
2049 var hasRequiredEs_array_push;
2050
2051 function requireEs_array_push () {
2052 if (hasRequiredEs_array_push) return es_array_push;
2053 hasRequiredEs_array_push = 1;
2054 var $ = require_export();
2055 var toObject = requireToObject();
2056 var lengthOfArrayLike = requireLengthOfArrayLike();
2057 var setArrayLength = requireArraySetLength();
2058 var doesNotExceedSafeInteger = requireDoesNotExceedSafeInteger();
2059 var fails = requireFails();
2060
2061 var INCORRECT_TO_LENGTH = fails(function () {
2062 return [].push.call({ length: 0x100000000 }, 1) !== 4294967297;
2063 });
2064
2065 // V8 <= 121 and Safari <= 15.4; FF < 23 throws InternalError
2066 // https://bugs.chromium.org/p/v8/issues/detail?id=12681
2067 var properErrorOnNonWritableLength = function () {
2068 try {
2069 // eslint-disable-next-line es/no-object-defineproperty -- safe
2070 Object.defineProperty([], 'length', { writable: false }).push();
2071 } catch (error) {
2072 return error instanceof TypeError;
2073 }
2074 };
2075
2076 var FORCED = INCORRECT_TO_LENGTH || !properErrorOnNonWritableLength();
2077
2078 // `Array.prototype.push` method
2079 // https://tc39.es/ecma262/#sec-array.prototype.push
2080 $({ target: 'Array', proto: true, arity: 1, forced: FORCED }, {
2081 // eslint-disable-next-line no-unused-vars -- required for `.length`
2082 push: function push(item) {
2083 var O = toObject(this);
2084 var len = lengthOfArrayLike(O);
2085 var argCount = arguments.length;
2086 doesNotExceedSafeInteger(len + argCount);
2087 for (var i = 0; i < argCount; i++) {
2088 O[len] = arguments[i];
2089 len++;
2090 }
2091 setArrayLength(O, len);
2092 return len;
2093 }
2094 });
2095 return es_array_push;
2096 }
2097
2098 requireEs_array_push();
2099
2100 var esnext_iterator_constructor = {};
2101
2102 var es_iterator_constructor = {};
2103
2104 var anInstance;
2105 var hasRequiredAnInstance;
2106
2107 function requireAnInstance () {
2108 if (hasRequiredAnInstance) return anInstance;
2109 hasRequiredAnInstance = 1;
2110 var isPrototypeOf = requireObjectIsPrototypeOf();
2111
2112 var $TypeError = TypeError;
2113
2114 anInstance = function (it, Prototype) {
2115 if (isPrototypeOf(Prototype, it)) return it;
2116 throw new $TypeError('Incorrect invocation');
2117 };
2118 return anInstance;
2119 }
2120
2121 var correctPrototypeGetter;
2122 var hasRequiredCorrectPrototypeGetter;
2123
2124 function requireCorrectPrototypeGetter () {
2125 if (hasRequiredCorrectPrototypeGetter) return correctPrototypeGetter;
2126 hasRequiredCorrectPrototypeGetter = 1;
2127 var fails = requireFails();
2128
2129 correctPrototypeGetter = !fails(function () {
2130 function F() { /* empty */ }
2131 F.prototype.constructor = null;
2132 // eslint-disable-next-line es/no-object-getprototypeof -- required for testing
2133 return Object.getPrototypeOf(new F()) !== F.prototype;
2134 });
2135 return correctPrototypeGetter;
2136 }
2137
2138 var objectGetPrototypeOf;
2139 var hasRequiredObjectGetPrototypeOf;
2140
2141 function requireObjectGetPrototypeOf () {
2142 if (hasRequiredObjectGetPrototypeOf) return objectGetPrototypeOf;
2143 hasRequiredObjectGetPrototypeOf = 1;
2144 var hasOwn = requireHasOwnProperty();
2145 var isCallable = requireIsCallable();
2146 var toObject = requireToObject();
2147 var sharedKey = requireSharedKey();
2148 var CORRECT_PROTOTYPE_GETTER = requireCorrectPrototypeGetter();
2149
2150 var IE_PROTO = sharedKey('IE_PROTO');
2151 var $Object = Object;
2152 var ObjectPrototype = $Object.prototype;
2153
2154 // `Object.getPrototypeOf` method
2155 // https://tc39.es/ecma262/#sec-object.getprototypeof
2156 // eslint-disable-next-line es/no-object-getprototypeof -- safe
2157 objectGetPrototypeOf = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) {
2158 var object = toObject(O);
2159 if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];
2160 var constructor = object.constructor;
2161 if (isCallable(constructor) && object instanceof constructor) {
2162 return constructor.prototype;
2163 } return object instanceof $Object ? ObjectPrototype : null;
2164 };
2165 return objectGetPrototypeOf;
2166 }
2167
2168 var defineBuiltInAccessor;
2169 var hasRequiredDefineBuiltInAccessor;
2170
2171 function requireDefineBuiltInAccessor () {
2172 if (hasRequiredDefineBuiltInAccessor) return defineBuiltInAccessor;
2173 hasRequiredDefineBuiltInAccessor = 1;
2174 var makeBuiltIn = requireMakeBuiltIn();
2175 var defineProperty = requireObjectDefineProperty();
2176
2177 defineBuiltInAccessor = function (target, name, descriptor) {
2178 if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true });
2179 if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true });
2180 return defineProperty.f(target, name, descriptor);
2181 };
2182 return defineBuiltInAccessor;
2183 }
2184
2185 var createProperty;
2186 var hasRequiredCreateProperty;
2187
2188 function requireCreateProperty () {
2189 if (hasRequiredCreateProperty) return createProperty;
2190 hasRequiredCreateProperty = 1;
2191 var DESCRIPTORS = requireDescriptors();
2192 var definePropertyModule = requireObjectDefineProperty();
2193 var createPropertyDescriptor = requireCreatePropertyDescriptor();
2194
2195 createProperty = function (object, key, value) {
2196 if (DESCRIPTORS) definePropertyModule.f(object, key, createPropertyDescriptor(0, value));
2197 else object[key] = value;
2198 };
2199 return createProperty;
2200 }
2201
2202 var objectDefineProperties = {};
2203
2204 var objectKeys;
2205 var hasRequiredObjectKeys;
2206
2207 function requireObjectKeys () {
2208 if (hasRequiredObjectKeys) return objectKeys;
2209 hasRequiredObjectKeys = 1;
2210 var internalObjectKeys = requireObjectKeysInternal();
2211 var enumBugKeys = requireEnumBugKeys();
2212
2213 // `Object.keys` method
2214 // https://tc39.es/ecma262/#sec-object.keys
2215 // eslint-disable-next-line es/no-object-keys -- safe
2216 objectKeys = Object.keys || function keys(O) {
2217 return internalObjectKeys(O, enumBugKeys);
2218 };
2219 return objectKeys;
2220 }
2221
2222 var hasRequiredObjectDefineProperties;
2223
2224 function requireObjectDefineProperties () {
2225 if (hasRequiredObjectDefineProperties) return objectDefineProperties;
2226 hasRequiredObjectDefineProperties = 1;
2227 var DESCRIPTORS = requireDescriptors();
2228 var V8_PROTOTYPE_DEFINE_BUG = requireV8PrototypeDefineBug();
2229 var definePropertyModule = requireObjectDefineProperty();
2230 var anObject = requireAnObject();
2231 var toIndexedObject = requireToIndexedObject();
2232 var objectKeys = requireObjectKeys();
2233
2234 // `Object.defineProperties` method
2235 // https://tc39.es/ecma262/#sec-object.defineproperties
2236 // eslint-disable-next-line es/no-object-defineproperties -- safe
2237 objectDefineProperties.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
2238 anObject(O);
2239 var props = toIndexedObject(Properties);
2240 var keys = objectKeys(Properties);
2241 var length = keys.length;
2242 var index = 0;
2243 var key;
2244 while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);
2245 return O;
2246 };
2247 return objectDefineProperties;
2248 }
2249
2250 var html;
2251 var hasRequiredHtml;
2252
2253 function requireHtml () {
2254 if (hasRequiredHtml) return html;
2255 hasRequiredHtml = 1;
2256 var getBuiltIn = requireGetBuiltIn();
2257
2258 html = getBuiltIn('document', 'documentElement');
2259 return html;
2260 }
2261
2262 var objectCreate;
2263 var hasRequiredObjectCreate;
2264
2265 function requireObjectCreate () {
2266 if (hasRequiredObjectCreate) return objectCreate;
2267 hasRequiredObjectCreate = 1;
2268 /* global ActiveXObject -- old IE, WSH */
2269 var anObject = requireAnObject();
2270 var definePropertiesModule = requireObjectDefineProperties();
2271 var enumBugKeys = requireEnumBugKeys();
2272 var hiddenKeys = requireHiddenKeys();
2273 var html = requireHtml();
2274 var documentCreateElement = requireDocumentCreateElement();
2275 var sharedKey = requireSharedKey();
2276
2277 var GT = '>';
2278 var LT = '<';
2279 var PROTOTYPE = 'prototype';
2280 var SCRIPT = 'script';
2281 var IE_PROTO = sharedKey('IE_PROTO');
2282
2283 var EmptyConstructor = function () { /* empty */ };
2284
2285 var scriptTag = function (content) {
2286 return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
2287 };
2288
2289 // Create object with fake `null` prototype: use ActiveX Object with cleared prototype
2290 var NullProtoObjectViaActiveX = function (activeXDocument) {
2291 activeXDocument.write(scriptTag(''));
2292 activeXDocument.close();
2293 var temp = activeXDocument.parentWindow.Object;
2294 // eslint-disable-next-line no-useless-assignment -- avoid memory leak
2295 activeXDocument = null;
2296 return temp;
2297 };
2298
2299 // Create object with fake `null` prototype: use iframe Object with cleared prototype
2300 var NullProtoObjectViaIFrame = function () {
2301 // Thrash, waste and sodomy: IE GC bug
2302 var iframe = documentCreateElement('iframe');
2303 var JS = 'java' + SCRIPT + ':';
2304 var iframeDocument;
2305 iframe.style.display = 'none';
2306 html.appendChild(iframe);
2307 // https://github.com/zloirock/core-js/issues/475
2308 iframe.src = String(JS);
2309 iframeDocument = iframe.contentWindow.document;
2310 iframeDocument.open();
2311 iframeDocument.write(scriptTag('document.F=Object'));
2312 iframeDocument.close();
2313 return iframeDocument.F;
2314 };
2315
2316 // Check for document.domain and active x support
2317 // No need to use active x approach when document.domain is not set
2318 // see https://github.com/es-shims/es5-shim/issues/150
2319 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
2320 // avoid IE GC bug
2321 var activeXDocument;
2322 var NullProtoObject = function () {
2323 try {
2324 activeXDocument = new ActiveXObject('htmlfile');
2325 } catch (error) { /* ignore */ }
2326 NullProtoObject = typeof document != 'undefined'
2327 ? document.domain && activeXDocument
2328 ? NullProtoObjectViaActiveX(activeXDocument) // old IE
2329 : NullProtoObjectViaIFrame()
2330 : NullProtoObjectViaActiveX(activeXDocument); // WSH
2331 var length = enumBugKeys.length;
2332 while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
2333 return NullProtoObject();
2334 };
2335
2336 hiddenKeys[IE_PROTO] = true;
2337
2338 // `Object.create` method
2339 // https://tc39.es/ecma262/#sec-object.create
2340 // eslint-disable-next-line es/no-object-create -- safe
2341 objectCreate = Object.create || function create(O, Properties) {
2342 var result;
2343 if (O !== null) {
2344 EmptyConstructor[PROTOTYPE] = anObject(O);
2345 result = new EmptyConstructor();
2346 EmptyConstructor[PROTOTYPE] = null;
2347 // add "__proto__" for Object.getPrototypeOf polyfill
2348 result[IE_PROTO] = O;
2349 } else result = NullProtoObject();
2350 return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
2351 };
2352 return objectCreate;
2353 }
2354
2355 var iteratorsCore;
2356 var hasRequiredIteratorsCore;
2357
2358 function requireIteratorsCore () {
2359 if (hasRequiredIteratorsCore) return iteratorsCore;
2360 hasRequiredIteratorsCore = 1;
2361 var fails = requireFails();
2362 var isCallable = requireIsCallable();
2363 var isObject = requireIsObject();
2364 var create = requireObjectCreate();
2365 var getPrototypeOf = requireObjectGetPrototypeOf();
2366 var defineBuiltIn = requireDefineBuiltIn();
2367 var wellKnownSymbol = requireWellKnownSymbol();
2368 var IS_PURE = requireIsPure();
2369
2370 var ITERATOR = wellKnownSymbol('iterator');
2371 var BUGGY_SAFARI_ITERATORS = false;
2372
2373 // `%IteratorPrototype%` object
2374 // https://tc39.es/ecma262/#sec-%iteratorprototype%-object
2375 var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
2376
2377 /* eslint-disable es/no-array-prototype-keys -- safe */
2378 if ([].keys) {
2379 arrayIterator = [].keys();
2380 // Safari 8 has buggy iterators w/o `next`
2381 if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
2382 else {
2383 PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
2384 if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
2385 }
2386 }
2387
2388 var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () {
2389 var test = {};
2390 // FF44- legacy iterators case
2391 return IteratorPrototype[ITERATOR].call(test) !== test;
2392 });
2393
2394 if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};
2395 else if (IS_PURE) IteratorPrototype = create(IteratorPrototype);
2396
2397 // `%IteratorPrototype%[@@iterator]()` method
2398 // https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
2399 if (!isCallable(IteratorPrototype[ITERATOR])) {
2400 defineBuiltIn(IteratorPrototype, ITERATOR, function () {
2401 return this;
2402 });
2403 }
2404
2405 iteratorsCore = {
2406 IteratorPrototype: IteratorPrototype,
2407 BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
2408 };
2409 return iteratorsCore;
2410 }
2411
2412 var hasRequiredEs_iterator_constructor;
2413
2414 function requireEs_iterator_constructor () {
2415 if (hasRequiredEs_iterator_constructor) return es_iterator_constructor;
2416 hasRequiredEs_iterator_constructor = 1;
2417 var $ = require_export();
2418 var globalThis = requireGlobalThis();
2419 var anInstance = requireAnInstance();
2420 var anObject = requireAnObject();
2421 var isCallable = requireIsCallable();
2422 var getPrototypeOf = requireObjectGetPrototypeOf();
2423 var defineBuiltInAccessor = requireDefineBuiltInAccessor();
2424 var createProperty = requireCreateProperty();
2425 var fails = requireFails();
2426 var hasOwn = requireHasOwnProperty();
2427 var wellKnownSymbol = requireWellKnownSymbol();
2428 var IteratorPrototype = requireIteratorsCore().IteratorPrototype;
2429 var DESCRIPTORS = requireDescriptors();
2430 var IS_PURE = requireIsPure();
2431
2432 var CONSTRUCTOR = 'constructor';
2433 var ITERATOR = 'Iterator';
2434 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2435
2436 var $TypeError = TypeError;
2437 var NativeIterator = globalThis[ITERATOR];
2438
2439 // FF56- have non-standard global helper `Iterator`
2440 var FORCED = IS_PURE
2441 || !isCallable(NativeIterator)
2442 || NativeIterator.prototype !== IteratorPrototype
2443 // FF44- non-standard `Iterator` passes previous tests
2444 || !fails(function () { NativeIterator({}); });
2445
2446 var IteratorConstructor = function Iterator() {
2447 anInstance(this, IteratorPrototype);
2448 if (getPrototypeOf(this) === IteratorPrototype) throw new $TypeError('Abstract class Iterator not directly constructable');
2449 };
2450
2451 var defineIteratorPrototypeAccessor = function (key, value) {
2452 if (DESCRIPTORS) {
2453 defineBuiltInAccessor(IteratorPrototype, key, {
2454 configurable: true,
2455 get: function () {
2456 return value;
2457 },
2458 set: function (replacement) {
2459 anObject(this);
2460 if (this === IteratorPrototype) throw new $TypeError("You can't redefine this property");
2461 if (hasOwn(this, key)) this[key] = replacement;
2462 else createProperty(this, key, replacement);
2463 }
2464 });
2465 } else IteratorPrototype[key] = value;
2466 };
2467
2468 if (!hasOwn(IteratorPrototype, TO_STRING_TAG)) defineIteratorPrototypeAccessor(TO_STRING_TAG, ITERATOR);
2469
2470 if (FORCED || !hasOwn(IteratorPrototype, CONSTRUCTOR) || IteratorPrototype[CONSTRUCTOR] === Object) {
2471 defineIteratorPrototypeAccessor(CONSTRUCTOR, IteratorConstructor);
2472 }
2473
2474 IteratorConstructor.prototype = IteratorPrototype;
2475
2476 // `Iterator` constructor
2477 // https://tc39.es/ecma262/#sec-iterator
2478 $({ global: true, constructor: true, forced: FORCED }, {
2479 Iterator: IteratorConstructor
2480 });
2481 return es_iterator_constructor;
2482 }
2483
2484 var hasRequiredEsnext_iterator_constructor;
2485
2486 function requireEsnext_iterator_constructor () {
2487 if (hasRequiredEsnext_iterator_constructor) return esnext_iterator_constructor;
2488 hasRequiredEsnext_iterator_constructor = 1;
2489 // TODO: Remove from `core-js@4`
2490 requireEs_iterator_constructor();
2491 return esnext_iterator_constructor;
2492 }
2493
2494 requireEsnext_iterator_constructor();
2495
2496 var esnext_iterator_every = {};
2497
2498 var es_iterator_every = {};
2499
2500 var functionUncurryThisClause;
2501 var hasRequiredFunctionUncurryThisClause;
2502
2503 function requireFunctionUncurryThisClause () {
2504 if (hasRequiredFunctionUncurryThisClause) return functionUncurryThisClause;
2505 hasRequiredFunctionUncurryThisClause = 1;
2506 var classofRaw = requireClassofRaw();
2507 var uncurryThis = requireFunctionUncurryThis();
2508
2509 functionUncurryThisClause = function (fn) {
2510 // Nashorn bug:
2511 // https://github.com/zloirock/core-js/issues/1128
2512 // https://github.com/zloirock/core-js/issues/1130
2513 if (classofRaw(fn) === 'Function') return uncurryThis(fn);
2514 };
2515 return functionUncurryThisClause;
2516 }
2517
2518 var functionBindContext;
2519 var hasRequiredFunctionBindContext;
2520
2521 function requireFunctionBindContext () {
2522 if (hasRequiredFunctionBindContext) return functionBindContext;
2523 hasRequiredFunctionBindContext = 1;
2524 var uncurryThis = requireFunctionUncurryThisClause();
2525 var aCallable = requireACallable();
2526 var NATIVE_BIND = requireFunctionBindNative();
2527
2528 var bind = uncurryThis(uncurryThis.bind);
2529
2530 // optional / simple context binding
2531 functionBindContext = function (fn, that) {
2532 aCallable(fn);
2533 return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) {
2534 return fn.apply(that, arguments);
2535 };
2536 };
2537 return functionBindContext;
2538 }
2539
2540 var iterators;
2541 var hasRequiredIterators;
2542
2543 function requireIterators () {
2544 if (hasRequiredIterators) return iterators;
2545 hasRequiredIterators = 1;
2546 iterators = {};
2547 return iterators;
2548 }
2549
2550 var isArrayIteratorMethod;
2551 var hasRequiredIsArrayIteratorMethod;
2552
2553 function requireIsArrayIteratorMethod () {
2554 if (hasRequiredIsArrayIteratorMethod) return isArrayIteratorMethod;
2555 hasRequiredIsArrayIteratorMethod = 1;
2556 var wellKnownSymbol = requireWellKnownSymbol();
2557 var Iterators = requireIterators();
2558
2559 var ITERATOR = wellKnownSymbol('iterator');
2560 var ArrayPrototype = Array.prototype;
2561
2562 // check on default Array iterator
2563 isArrayIteratorMethod = function (it) {
2564 return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
2565 };
2566 return isArrayIteratorMethod;
2567 }
2568
2569 var getIteratorMethod;
2570 var hasRequiredGetIteratorMethod;
2571
2572 function requireGetIteratorMethod () {
2573 if (hasRequiredGetIteratorMethod) return getIteratorMethod;
2574 hasRequiredGetIteratorMethod = 1;
2575 var classof = requireClassof();
2576 var getMethod = requireGetMethod();
2577 var isNullOrUndefined = requireIsNullOrUndefined();
2578 var Iterators = requireIterators();
2579 var wellKnownSymbol = requireWellKnownSymbol();
2580
2581 var ITERATOR = wellKnownSymbol('iterator');
2582
2583 getIteratorMethod = function (it) {
2584 if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR)
2585 || getMethod(it, '@@iterator')
2586 || Iterators[classof(it)];
2587 };
2588 return getIteratorMethod;
2589 }
2590
2591 var getIterator;
2592 var hasRequiredGetIterator;
2593
2594 function requireGetIterator () {
2595 if (hasRequiredGetIterator) return getIterator;
2596 hasRequiredGetIterator = 1;
2597 var call = requireFunctionCall();
2598 var aCallable = requireACallable();
2599 var anObject = requireAnObject();
2600 var tryToString = requireTryToString();
2601 var getIteratorMethod = requireGetIteratorMethod();
2602
2603 var $TypeError = TypeError;
2604
2605 getIterator = function (argument, usingIterator) {
2606 var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
2607 if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument));
2608 throw new $TypeError(tryToString(argument) + ' is not iterable');
2609 };
2610 return getIterator;
2611 }
2612
2613 var iteratorClose;
2614 var hasRequiredIteratorClose;
2615
2616 function requireIteratorClose () {
2617 if (hasRequiredIteratorClose) return iteratorClose;
2618 hasRequiredIteratorClose = 1;
2619 var call = requireFunctionCall();
2620 var anObject = requireAnObject();
2621 var getMethod = requireGetMethod();
2622
2623 iteratorClose = function (iterator, kind, value) {
2624 var innerResult, innerError;
2625 anObject(iterator);
2626 try {
2627 innerResult = getMethod(iterator, 'return');
2628 if (!innerResult) {
2629 if (kind === 'throw') throw value;
2630 return value;
2631 }
2632 innerResult = call(innerResult, iterator);
2633 } catch (error) {
2634 innerError = true;
2635 innerResult = error;
2636 }
2637 if (kind === 'throw') throw value;
2638 if (innerError) throw innerResult;
2639 anObject(innerResult);
2640 return value;
2641 };
2642 return iteratorClose;
2643 }
2644
2645 var iterate;
2646 var hasRequiredIterate;
2647
2648 function requireIterate () {
2649 if (hasRequiredIterate) return iterate;
2650 hasRequiredIterate = 1;
2651 var bind = requireFunctionBindContext();
2652 var call = requireFunctionCall();
2653 var anObject = requireAnObject();
2654 var tryToString = requireTryToString();
2655 var isArrayIteratorMethod = requireIsArrayIteratorMethod();
2656 var lengthOfArrayLike = requireLengthOfArrayLike();
2657 var isPrototypeOf = requireObjectIsPrototypeOf();
2658 var getIterator = requireGetIterator();
2659 var getIteratorMethod = requireGetIteratorMethod();
2660 var iteratorClose = requireIteratorClose();
2661
2662 var $TypeError = TypeError;
2663
2664 var Result = function (stopped, result) {
2665 this.stopped = stopped;
2666 this.result = result;
2667 };
2668
2669 var ResultPrototype = Result.prototype;
2670
2671 iterate = function (iterable, unboundFunction, options) {
2672 var that = options && options.that;
2673 var AS_ENTRIES = !!(options && options.AS_ENTRIES);
2674 var IS_RECORD = !!(options && options.IS_RECORD);
2675 var IS_ITERATOR = !!(options && options.IS_ITERATOR);
2676 var INTERRUPTED = !!(options && options.INTERRUPTED);
2677 var fn = bind(unboundFunction, that);
2678 var iterator, iterFn, index, length, result, next, step;
2679
2680 var stop = function (condition) {
2681 if (iterator) iteratorClose(iterator, 'normal', condition);
2682 return new Result(true, condition);
2683 };
2684
2685 var callFn = function (value) {
2686 if (AS_ENTRIES) {
2687 anObject(value);
2688 return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
2689 } return INTERRUPTED ? fn(value, stop) : fn(value);
2690 };
2691
2692 if (IS_RECORD) {
2693 iterator = iterable.iterator;
2694 } else if (IS_ITERATOR) {
2695 iterator = iterable;
2696 } else {
2697 iterFn = getIteratorMethod(iterable);
2698 if (!iterFn) throw new $TypeError(tryToString(iterable) + ' is not iterable');
2699 // optimisation for array iterators
2700 if (isArrayIteratorMethod(iterFn)) {
2701 for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
2702 result = callFn(iterable[index]);
2703 if (result && isPrototypeOf(ResultPrototype, result)) return result;
2704 } return new Result(false);
2705 }
2706 iterator = getIterator(iterable, iterFn);
2707 }
2708
2709 next = IS_RECORD ? iterable.next : iterator.next;
2710 while (!(step = call(next, iterator)).done) {
2711 try {
2712 result = callFn(step.value);
2713 } catch (error) {
2714 iteratorClose(iterator, 'throw', error);
2715 }
2716 if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
2717 } return new Result(false);
2718 };
2719 return iterate;
2720 }
2721
2722 var getIteratorDirect;
2723 var hasRequiredGetIteratorDirect;
2724
2725 function requireGetIteratorDirect () {
2726 if (hasRequiredGetIteratorDirect) return getIteratorDirect;
2727 hasRequiredGetIteratorDirect = 1;
2728 // `GetIteratorDirect(obj)` abstract operation
2729 // https://tc39.es/proposal-iterator-helpers/#sec-getiteratordirect
2730 getIteratorDirect = function (obj) {
2731 return {
2732 iterator: obj,
2733 next: obj.next,
2734 done: false
2735 };
2736 };
2737 return getIteratorDirect;
2738 }
2739
2740 var hasRequiredEs_iterator_every;
2741
2742 function requireEs_iterator_every () {
2743 if (hasRequiredEs_iterator_every) return es_iterator_every;
2744 hasRequiredEs_iterator_every = 1;
2745 var $ = require_export();
2746 var iterate = requireIterate();
2747 var aCallable = requireACallable();
2748 var anObject = requireAnObject();
2749 var getIteratorDirect = requireGetIteratorDirect();
2750
2751 // `Iterator.prototype.every` method
2752 // https://tc39.es/ecma262/#sec-iterator.prototype.every
2753 $({ target: 'Iterator', proto: true, real: true }, {
2754 every: function every(predicate) {
2755 anObject(this);
2756 aCallable(predicate);
2757 var record = getIteratorDirect(this);
2758 var counter = 0;
2759 return !iterate(record, function (value, stop) {
2760 if (!predicate(value, counter++)) return stop();
2761 }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
2762 }
2763 });
2764 return es_iterator_every;
2765 }
2766
2767 var hasRequiredEsnext_iterator_every;
2768
2769 function requireEsnext_iterator_every () {
2770 if (hasRequiredEsnext_iterator_every) return esnext_iterator_every;
2771 hasRequiredEsnext_iterator_every = 1;
2772 // TODO: Remove from `core-js@4`
2773 requireEs_iterator_every();
2774 return esnext_iterator_every;
2775 }
2776
2777 requireEsnext_iterator_every();
2778
2779 var esnext_iterator_map = {};
2780
2781 var es_iterator_map = {};
2782
2783 var defineBuiltIns;
2784 var hasRequiredDefineBuiltIns;
2785
2786 function requireDefineBuiltIns () {
2787 if (hasRequiredDefineBuiltIns) return defineBuiltIns;
2788 hasRequiredDefineBuiltIns = 1;
2789 var defineBuiltIn = requireDefineBuiltIn();
2790
2791 defineBuiltIns = function (target, src, options) {
2792 for (var key in src) defineBuiltIn(target, key, src[key], options);
2793 return target;
2794 };
2795 return defineBuiltIns;
2796 }
2797
2798 var createIterResultObject;
2799 var hasRequiredCreateIterResultObject;
2800
2801 function requireCreateIterResultObject () {
2802 if (hasRequiredCreateIterResultObject) return createIterResultObject;
2803 hasRequiredCreateIterResultObject = 1;
2804 // `CreateIterResultObject` abstract operation
2805 // https://tc39.es/ecma262/#sec-createiterresultobject
2806 createIterResultObject = function (value, done) {
2807 return { value: value, done: done };
2808 };
2809 return createIterResultObject;
2810 }
2811
2812 var iteratorCreateProxy;
2813 var hasRequiredIteratorCreateProxy;
2814
2815 function requireIteratorCreateProxy () {
2816 if (hasRequiredIteratorCreateProxy) return iteratorCreateProxy;
2817 hasRequiredIteratorCreateProxy = 1;
2818 var call = requireFunctionCall();
2819 var create = requireObjectCreate();
2820 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
2821 var defineBuiltIns = requireDefineBuiltIns();
2822 var wellKnownSymbol = requireWellKnownSymbol();
2823 var InternalStateModule = requireInternalState();
2824 var getMethod = requireGetMethod();
2825 var IteratorPrototype = requireIteratorsCore().IteratorPrototype;
2826 var createIterResultObject = requireCreateIterResultObject();
2827 var iteratorClose = requireIteratorClose();
2828
2829 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2830 var ITERATOR_HELPER = 'IteratorHelper';
2831 var WRAP_FOR_VALID_ITERATOR = 'WrapForValidIterator';
2832 var setInternalState = InternalStateModule.set;
2833
2834 var createIteratorProxyPrototype = function (IS_ITERATOR) {
2835 var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER);
2836
2837 return defineBuiltIns(create(IteratorPrototype), {
2838 next: function next() {
2839 var state = getInternalState(this);
2840 // for simplification:
2841 // for `%WrapForValidIteratorPrototype%.next` our `nextHandler` returns `IterResultObject`
2842 // for `%IteratorHelperPrototype%.next` - just a value
2843 if (IS_ITERATOR) return state.nextHandler();
2844 try {
2845 var result = state.done ? undefined : state.nextHandler();
2846 return createIterResultObject(result, state.done);
2847 } catch (error) {
2848 state.done = true;
2849 throw error;
2850 }
2851 },
2852 'return': function () {
2853 var state = getInternalState(this);
2854 var iterator = state.iterator;
2855 state.done = true;
2856 if (IS_ITERATOR) {
2857 var returnMethod = getMethod(iterator, 'return');
2858 return returnMethod ? call(returnMethod, iterator) : createIterResultObject(undefined, true);
2859 }
2860 if (state.inner) try {
2861 iteratorClose(state.inner.iterator, 'normal');
2862 } catch (error) {
2863 return iteratorClose(iterator, 'throw', error);
2864 }
2865 if (iterator) iteratorClose(iterator, 'normal');
2866 return createIterResultObject(undefined, true);
2867 }
2868 });
2869 };
2870
2871 var WrapForValidIteratorPrototype = createIteratorProxyPrototype(true);
2872 var IteratorHelperPrototype = createIteratorProxyPrototype(false);
2873
2874 createNonEnumerableProperty(IteratorHelperPrototype, TO_STRING_TAG, 'Iterator Helper');
2875
2876 iteratorCreateProxy = function (nextHandler, IS_ITERATOR) {
2877 var IteratorProxy = function Iterator(record, state) {
2878 if (state) {
2879 state.iterator = record.iterator;
2880 state.next = record.next;
2881 } else state = record;
2882 state.type = IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER;
2883 state.nextHandler = nextHandler;
2884 state.counter = 0;
2885 state.done = false;
2886 setInternalState(this, state);
2887 };
2888
2889 IteratorProxy.prototype = IS_ITERATOR ? WrapForValidIteratorPrototype : IteratorHelperPrototype;
2890
2891 return IteratorProxy;
2892 };
2893 return iteratorCreateProxy;
2894 }
2895
2896 var callWithSafeIterationClosing;
2897 var hasRequiredCallWithSafeIterationClosing;
2898
2899 function requireCallWithSafeIterationClosing () {
2900 if (hasRequiredCallWithSafeIterationClosing) return callWithSafeIterationClosing;
2901 hasRequiredCallWithSafeIterationClosing = 1;
2902 var anObject = requireAnObject();
2903 var iteratorClose = requireIteratorClose();
2904
2905 // call something on iterator step with safe closing on error
2906 callWithSafeIterationClosing = function (iterator, fn, value, ENTRIES) {
2907 try {
2908 return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
2909 } catch (error) {
2910 iteratorClose(iterator, 'throw', error);
2911 }
2912 };
2913 return callWithSafeIterationClosing;
2914 }
2915
2916 var iteratorMap;
2917 var hasRequiredIteratorMap;
2918
2919 function requireIteratorMap () {
2920 if (hasRequiredIteratorMap) return iteratorMap;
2921 hasRequiredIteratorMap = 1;
2922 var call = requireFunctionCall();
2923 var aCallable = requireACallable();
2924 var anObject = requireAnObject();
2925 var getIteratorDirect = requireGetIteratorDirect();
2926 var createIteratorProxy = requireIteratorCreateProxy();
2927 var callWithSafeIterationClosing = requireCallWithSafeIterationClosing();
2928
2929 var IteratorProxy = createIteratorProxy(function () {
2930 var iterator = this.iterator;
2931 var result = anObject(call(this.next, iterator));
2932 var done = this.done = !!result.done;
2933 if (!done) return callWithSafeIterationClosing(iterator, this.mapper, [result.value, this.counter++], true);
2934 });
2935
2936 // `Iterator.prototype.map` method
2937 // https://github.com/tc39/proposal-iterator-helpers
2938 iteratorMap = function map(mapper) {
2939 anObject(this);
2940 aCallable(mapper);
2941 return new IteratorProxy(getIteratorDirect(this), {
2942 mapper: mapper
2943 });
2944 };
2945 return iteratorMap;
2946 }
2947
2948 var hasRequiredEs_iterator_map;
2949
2950 function requireEs_iterator_map () {
2951 if (hasRequiredEs_iterator_map) return es_iterator_map;
2952 hasRequiredEs_iterator_map = 1;
2953 var $ = require_export();
2954 var map = requireIteratorMap();
2955 var IS_PURE = requireIsPure();
2956
2957 // `Iterator.prototype.map` method
2958 // https://tc39.es/ecma262/#sec-iterator.prototype.map
2959 $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
2960 map: map
2961 });
2962 return es_iterator_map;
2963 }
2964
2965 var hasRequiredEsnext_iterator_map;
2966
2967 function requireEsnext_iterator_map () {
2968 if (hasRequiredEsnext_iterator_map) return esnext_iterator_map;
2969 hasRequiredEsnext_iterator_map = 1;
2970 // TODO: Remove from `core-js@4`
2971 requireEs_iterator_map();
2972 return esnext_iterator_map;
2973 }
2974
2975 requireEsnext_iterator_map();
2976
2977 var esnext_iterator_some = {};
2978
2979 var es_iterator_some = {};
2980
2981 var hasRequiredEs_iterator_some;
2982
2983 function requireEs_iterator_some () {
2984 if (hasRequiredEs_iterator_some) return es_iterator_some;
2985 hasRequiredEs_iterator_some = 1;
2986 var $ = require_export();
2987 var iterate = requireIterate();
2988 var aCallable = requireACallable();
2989 var anObject = requireAnObject();
2990 var getIteratorDirect = requireGetIteratorDirect();
2991
2992 // `Iterator.prototype.some` method
2993 // https://tc39.es/ecma262/#sec-iterator.prototype.some
2994 $({ target: 'Iterator', proto: true, real: true }, {
2995 some: function some(predicate) {
2996 anObject(this);
2997 aCallable(predicate);
2998 var record = getIteratorDirect(this);
2999 var counter = 0;
3000 return iterate(record, function (value, stop) {
3001 if (predicate(value, counter++)) return stop();
3002 }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
3003 }
3004 });
3005 return es_iterator_some;
3006 }
3007
3008 var hasRequiredEsnext_iterator_some;
3009
3010 function requireEsnext_iterator_some () {
3011 if (hasRequiredEsnext_iterator_some) return esnext_iterator_some;
3012 hasRequiredEsnext_iterator_some = 1;
3013 // TODO: Remove from `core-js@4`
3014 requireEs_iterator_some();
3015 return esnext_iterator_some;
3016 }
3017
3018 requireEsnext_iterator_some();
3019
3020 var esnext_set_difference_v2 = {};
3021
3022 var es_set_difference_v2 = {};
3023
3024 var setHelpers;
3025 var hasRequiredSetHelpers;
3026
3027 function requireSetHelpers () {
3028 if (hasRequiredSetHelpers) return setHelpers;
3029 hasRequiredSetHelpers = 1;
3030 var uncurryThis = requireFunctionUncurryThis();
3031
3032 // eslint-disable-next-line es/no-set -- safe
3033 var SetPrototype = Set.prototype;
3034
3035 setHelpers = {
3036 // eslint-disable-next-line es/no-set -- safe
3037 Set: Set,
3038 add: uncurryThis(SetPrototype.add),
3039 has: uncurryThis(SetPrototype.has),
3040 remove: uncurryThis(SetPrototype['delete']),
3041 proto: SetPrototype
3042 };
3043 return setHelpers;
3044 }
3045
3046 var aSet;
3047 var hasRequiredASet;
3048
3049 function requireASet () {
3050 if (hasRequiredASet) return aSet;
3051 hasRequiredASet = 1;
3052 var has = requireSetHelpers().has;
3053
3054 // Perform ? RequireInternalSlot(M, [[SetData]])
3055 aSet = function (it) {
3056 has(it);
3057 return it;
3058 };
3059 return aSet;
3060 }
3061
3062 var iterateSimple;
3063 var hasRequiredIterateSimple;
3064
3065 function requireIterateSimple () {
3066 if (hasRequiredIterateSimple) return iterateSimple;
3067 hasRequiredIterateSimple = 1;
3068 var call = requireFunctionCall();
3069
3070 iterateSimple = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) {
3071 var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator;
3072 var next = record.next;
3073 var step, result;
3074 while (!(step = call(next, iterator)).done) {
3075 result = fn(step.value);
3076 if (result !== undefined) return result;
3077 }
3078 };
3079 return iterateSimple;
3080 }
3081
3082 var setIterate;
3083 var hasRequiredSetIterate;
3084
3085 function requireSetIterate () {
3086 if (hasRequiredSetIterate) return setIterate;
3087 hasRequiredSetIterate = 1;
3088 var uncurryThis = requireFunctionUncurryThis();
3089 var iterateSimple = requireIterateSimple();
3090 var SetHelpers = requireSetHelpers();
3091
3092 var Set = SetHelpers.Set;
3093 var SetPrototype = SetHelpers.proto;
3094 var forEach = uncurryThis(SetPrototype.forEach);
3095 var keys = uncurryThis(SetPrototype.keys);
3096 var next = keys(new Set()).next;
3097
3098 setIterate = function (set, fn, interruptible) {
3099 return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn);
3100 };
3101 return setIterate;
3102 }
3103
3104 var setClone;
3105 var hasRequiredSetClone;
3106
3107 function requireSetClone () {
3108 if (hasRequiredSetClone) return setClone;
3109 hasRequiredSetClone = 1;
3110 var SetHelpers = requireSetHelpers();
3111 var iterate = requireSetIterate();
3112
3113 var Set = SetHelpers.Set;
3114 var add = SetHelpers.add;
3115
3116 setClone = function (set) {
3117 var result = new Set();
3118 iterate(set, function (it) {
3119 add(result, it);
3120 });
3121 return result;
3122 };
3123 return setClone;
3124 }
3125
3126 var setSize;
3127 var hasRequiredSetSize;
3128
3129 function requireSetSize () {
3130 if (hasRequiredSetSize) return setSize;
3131 hasRequiredSetSize = 1;
3132 var uncurryThisAccessor = requireFunctionUncurryThisAccessor();
3133 var SetHelpers = requireSetHelpers();
3134
3135 setSize = uncurryThisAccessor(SetHelpers.proto, 'size', 'get') || function (set) {
3136 return set.size;
3137 };
3138 return setSize;
3139 }
3140
3141 var getSetRecord;
3142 var hasRequiredGetSetRecord;
3143
3144 function requireGetSetRecord () {
3145 if (hasRequiredGetSetRecord) return getSetRecord;
3146 hasRequiredGetSetRecord = 1;
3147 var aCallable = requireACallable();
3148 var anObject = requireAnObject();
3149 var call = requireFunctionCall();
3150 var toIntegerOrInfinity = requireToIntegerOrInfinity();
3151 var getIteratorDirect = requireGetIteratorDirect();
3152
3153 var INVALID_SIZE = 'Invalid size';
3154 var $RangeError = RangeError;
3155 var $TypeError = TypeError;
3156 var max = Math.max;
3157
3158 var SetRecord = function (set, intSize) {
3159 this.set = set;
3160 this.size = max(intSize, 0);
3161 this.has = aCallable(set.has);
3162 this.keys = aCallable(set.keys);
3163 };
3164
3165 SetRecord.prototype = {
3166 getIterator: function () {
3167 return getIteratorDirect(anObject(call(this.keys, this.set)));
3168 },
3169 includes: function (it) {
3170 return call(this.has, this.set, it);
3171 }
3172 };
3173
3174 // `GetSetRecord` abstract operation
3175 // https://tc39.es/proposal-set-methods/#sec-getsetrecord
3176 getSetRecord = function (obj) {
3177 anObject(obj);
3178 var numSize = +obj.size;
3179 // NOTE: If size is undefined, then numSize will be NaN
3180 // eslint-disable-next-line no-self-compare -- NaN check
3181 if (numSize !== numSize) throw new $TypeError(INVALID_SIZE);
3182 var intSize = toIntegerOrInfinity(numSize);
3183 if (intSize < 0) throw new $RangeError(INVALID_SIZE);
3184 return new SetRecord(obj, intSize);
3185 };
3186 return getSetRecord;
3187 }
3188
3189 var setDifference;
3190 var hasRequiredSetDifference;
3191
3192 function requireSetDifference () {
3193 if (hasRequiredSetDifference) return setDifference;
3194 hasRequiredSetDifference = 1;
3195 var aSet = requireASet();
3196 var SetHelpers = requireSetHelpers();
3197 var clone = requireSetClone();
3198 var size = requireSetSize();
3199 var getSetRecord = requireGetSetRecord();
3200 var iterateSet = requireSetIterate();
3201 var iterateSimple = requireIterateSimple();
3202
3203 var has = SetHelpers.has;
3204 var remove = SetHelpers.remove;
3205
3206 // `Set.prototype.difference` method
3207 // https://github.com/tc39/proposal-set-methods
3208 setDifference = function difference(other) {
3209 var O = aSet(this);
3210 var otherRec = getSetRecord(other);
3211 var result = clone(O);
3212 if (size(O) <= otherRec.size) iterateSet(O, function (e) {
3213 if (otherRec.includes(e)) remove(result, e);
3214 });
3215 else iterateSimple(otherRec.getIterator(), function (e) {
3216 if (has(O, e)) remove(result, e);
3217 });
3218 return result;
3219 };
3220 return setDifference;
3221 }
3222
3223 var setMethodAcceptSetLike;
3224 var hasRequiredSetMethodAcceptSetLike;
3225
3226 function requireSetMethodAcceptSetLike () {
3227 if (hasRequiredSetMethodAcceptSetLike) return setMethodAcceptSetLike;
3228 hasRequiredSetMethodAcceptSetLike = 1;
3229 var getBuiltIn = requireGetBuiltIn();
3230
3231 var createSetLike = function (size) {
3232 return {
3233 size: size,
3234 has: function () {
3235 return false;
3236 },
3237 keys: function () {
3238 return {
3239 next: function () {
3240 return { done: true };
3241 }
3242 };
3243 }
3244 };
3245 };
3246
3247 setMethodAcceptSetLike = function (name) {
3248 var Set = getBuiltIn('Set');
3249 try {
3250 new Set()[name](createSetLike(0));
3251 try {
3252 // late spec change, early WebKit ~ Safari 17.0 beta implementation does not pass it
3253 // https://github.com/tc39/proposal-set-methods/pull/88
3254 new Set()[name](createSetLike(-1));
3255 return false;
3256 } catch (error2) {
3257 return true;
3258 }
3259 } catch (error) {
3260 return false;
3261 }
3262 };
3263 return setMethodAcceptSetLike;
3264 }
3265
3266 var hasRequiredEs_set_difference_v2;
3267
3268 function requireEs_set_difference_v2 () {
3269 if (hasRequiredEs_set_difference_v2) return es_set_difference_v2;
3270 hasRequiredEs_set_difference_v2 = 1;
3271 var $ = require_export();
3272 var difference = requireSetDifference();
3273 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3274
3275 // `Set.prototype.difference` method
3276 // https://tc39.es/ecma262/#sec-set.prototype.difference
3277 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('difference') }, {
3278 difference: difference
3279 });
3280 return es_set_difference_v2;
3281 }
3282
3283 var hasRequiredEsnext_set_difference_v2;
3284
3285 function requireEsnext_set_difference_v2 () {
3286 if (hasRequiredEsnext_set_difference_v2) return esnext_set_difference_v2;
3287 hasRequiredEsnext_set_difference_v2 = 1;
3288 // TODO: Remove from `core-js@4`
3289 requireEs_set_difference_v2();
3290 return esnext_set_difference_v2;
3291 }
3292
3293 requireEsnext_set_difference_v2();
3294
3295 var esnext_set_intersection_v2 = {};
3296
3297 var es_set_intersection_v2 = {};
3298
3299 var setIntersection;
3300 var hasRequiredSetIntersection;
3301
3302 function requireSetIntersection () {
3303 if (hasRequiredSetIntersection) return setIntersection;
3304 hasRequiredSetIntersection = 1;
3305 var aSet = requireASet();
3306 var SetHelpers = requireSetHelpers();
3307 var size = requireSetSize();
3308 var getSetRecord = requireGetSetRecord();
3309 var iterateSet = requireSetIterate();
3310 var iterateSimple = requireIterateSimple();
3311
3312 var Set = SetHelpers.Set;
3313 var add = SetHelpers.add;
3314 var has = SetHelpers.has;
3315
3316 // `Set.prototype.intersection` method
3317 // https://github.com/tc39/proposal-set-methods
3318 setIntersection = function intersection(other) {
3319 var O = aSet(this);
3320 var otherRec = getSetRecord(other);
3321 var result = new Set();
3322
3323 if (size(O) > otherRec.size) {
3324 iterateSimple(otherRec.getIterator(), function (e) {
3325 if (has(O, e)) add(result, e);
3326 });
3327 } else {
3328 iterateSet(O, function (e) {
3329 if (otherRec.includes(e)) add(result, e);
3330 });
3331 }
3332
3333 return result;
3334 };
3335 return setIntersection;
3336 }
3337
3338 var hasRequiredEs_set_intersection_v2;
3339
3340 function requireEs_set_intersection_v2 () {
3341 if (hasRequiredEs_set_intersection_v2) return es_set_intersection_v2;
3342 hasRequiredEs_set_intersection_v2 = 1;
3343 var $ = require_export();
3344 var fails = requireFails();
3345 var intersection = requireSetIntersection();
3346 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3347
3348 var INCORRECT = !setMethodAcceptSetLike('intersection') || fails(function () {
3349 // eslint-disable-next-line es/no-array-from, es/no-set -- testing
3350 return String(Array.from(new Set([1, 2, 3]).intersection(new Set([3, 2])))) !== '3,2';
3351 });
3352
3353 // `Set.prototype.intersection` method
3354 // https://tc39.es/ecma262/#sec-set.prototype.intersection
3355 $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, {
3356 intersection: intersection
3357 });
3358 return es_set_intersection_v2;
3359 }
3360
3361 var hasRequiredEsnext_set_intersection_v2;
3362
3363 function requireEsnext_set_intersection_v2 () {
3364 if (hasRequiredEsnext_set_intersection_v2) return esnext_set_intersection_v2;
3365 hasRequiredEsnext_set_intersection_v2 = 1;
3366 // TODO: Remove from `core-js@4`
3367 requireEs_set_intersection_v2();
3368 return esnext_set_intersection_v2;
3369 }
3370
3371 requireEsnext_set_intersection_v2();
3372
3373 var esnext_set_isDisjointFrom_v2 = {};
3374
3375 var es_set_isDisjointFrom_v2 = {};
3376
3377 var setIsDisjointFrom;
3378 var hasRequiredSetIsDisjointFrom;
3379
3380 function requireSetIsDisjointFrom () {
3381 if (hasRequiredSetIsDisjointFrom) return setIsDisjointFrom;
3382 hasRequiredSetIsDisjointFrom = 1;
3383 var aSet = requireASet();
3384 var has = requireSetHelpers().has;
3385 var size = requireSetSize();
3386 var getSetRecord = requireGetSetRecord();
3387 var iterateSet = requireSetIterate();
3388 var iterateSimple = requireIterateSimple();
3389 var iteratorClose = requireIteratorClose();
3390
3391 // `Set.prototype.isDisjointFrom` method
3392 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isDisjointFrom
3393 setIsDisjointFrom = function isDisjointFrom(other) {
3394 var O = aSet(this);
3395 var otherRec = getSetRecord(other);
3396 if (size(O) <= otherRec.size) return iterateSet(O, function (e) {
3397 if (otherRec.includes(e)) return false;
3398 }, true) !== false;
3399 var iterator = otherRec.getIterator();
3400 return iterateSimple(iterator, function (e) {
3401 if (has(O, e)) return iteratorClose(iterator, 'normal', false);
3402 }) !== false;
3403 };
3404 return setIsDisjointFrom;
3405 }
3406
3407 var hasRequiredEs_set_isDisjointFrom_v2;
3408
3409 function requireEs_set_isDisjointFrom_v2 () {
3410 if (hasRequiredEs_set_isDisjointFrom_v2) return es_set_isDisjointFrom_v2;
3411 hasRequiredEs_set_isDisjointFrom_v2 = 1;
3412 var $ = require_export();
3413 var isDisjointFrom = requireSetIsDisjointFrom();
3414 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3415
3416 // `Set.prototype.isDisjointFrom` method
3417 // https://tc39.es/ecma262/#sec-set.prototype.isdisjointfrom
3418 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isDisjointFrom') }, {
3419 isDisjointFrom: isDisjointFrom
3420 });
3421 return es_set_isDisjointFrom_v2;
3422 }
3423
3424 var hasRequiredEsnext_set_isDisjointFrom_v2;
3425
3426 function requireEsnext_set_isDisjointFrom_v2 () {
3427 if (hasRequiredEsnext_set_isDisjointFrom_v2) return esnext_set_isDisjointFrom_v2;
3428 hasRequiredEsnext_set_isDisjointFrom_v2 = 1;
3429 // TODO: Remove from `core-js@4`
3430 requireEs_set_isDisjointFrom_v2();
3431 return esnext_set_isDisjointFrom_v2;
3432 }
3433
3434 requireEsnext_set_isDisjointFrom_v2();
3435
3436 var esnext_set_isSubsetOf_v2 = {};
3437
3438 var es_set_isSubsetOf_v2 = {};
3439
3440 var setIsSubsetOf;
3441 var hasRequiredSetIsSubsetOf;
3442
3443 function requireSetIsSubsetOf () {
3444 if (hasRequiredSetIsSubsetOf) return setIsSubsetOf;
3445 hasRequiredSetIsSubsetOf = 1;
3446 var aSet = requireASet();
3447 var size = requireSetSize();
3448 var iterate = requireSetIterate();
3449 var getSetRecord = requireGetSetRecord();
3450
3451 // `Set.prototype.isSubsetOf` method
3452 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSubsetOf
3453 setIsSubsetOf = function isSubsetOf(other) {
3454 var O = aSet(this);
3455 var otherRec = getSetRecord(other);
3456 if (size(O) > otherRec.size) return false;
3457 return iterate(O, function (e) {
3458 if (!otherRec.includes(e)) return false;
3459 }, true) !== false;
3460 };
3461 return setIsSubsetOf;
3462 }
3463
3464 var hasRequiredEs_set_isSubsetOf_v2;
3465
3466 function requireEs_set_isSubsetOf_v2 () {
3467 if (hasRequiredEs_set_isSubsetOf_v2) return es_set_isSubsetOf_v2;
3468 hasRequiredEs_set_isSubsetOf_v2 = 1;
3469 var $ = require_export();
3470 var isSubsetOf = requireSetIsSubsetOf();
3471 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3472
3473 // `Set.prototype.isSubsetOf` method
3474 // https://tc39.es/ecma262/#sec-set.prototype.issubsetof
3475 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSubsetOf') }, {
3476 isSubsetOf: isSubsetOf
3477 });
3478 return es_set_isSubsetOf_v2;
3479 }
3480
3481 var hasRequiredEsnext_set_isSubsetOf_v2;
3482
3483 function requireEsnext_set_isSubsetOf_v2 () {
3484 if (hasRequiredEsnext_set_isSubsetOf_v2) return esnext_set_isSubsetOf_v2;
3485 hasRequiredEsnext_set_isSubsetOf_v2 = 1;
3486 // TODO: Remove from `core-js@4`
3487 requireEs_set_isSubsetOf_v2();
3488 return esnext_set_isSubsetOf_v2;
3489 }
3490
3491 requireEsnext_set_isSubsetOf_v2();
3492
3493 var esnext_set_isSupersetOf_v2 = {};
3494
3495 var es_set_isSupersetOf_v2 = {};
3496
3497 var setIsSupersetOf;
3498 var hasRequiredSetIsSupersetOf;
3499
3500 function requireSetIsSupersetOf () {
3501 if (hasRequiredSetIsSupersetOf) return setIsSupersetOf;
3502 hasRequiredSetIsSupersetOf = 1;
3503 var aSet = requireASet();
3504 var has = requireSetHelpers().has;
3505 var size = requireSetSize();
3506 var getSetRecord = requireGetSetRecord();
3507 var iterateSimple = requireIterateSimple();
3508 var iteratorClose = requireIteratorClose();
3509
3510 // `Set.prototype.isSupersetOf` method
3511 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSupersetOf
3512 setIsSupersetOf = function isSupersetOf(other) {
3513 var O = aSet(this);
3514 var otherRec = getSetRecord(other);
3515 if (size(O) < otherRec.size) return false;
3516 var iterator = otherRec.getIterator();
3517 return iterateSimple(iterator, function (e) {
3518 if (!has(O, e)) return iteratorClose(iterator, 'normal', false);
3519 }) !== false;
3520 };
3521 return setIsSupersetOf;
3522 }
3523
3524 var hasRequiredEs_set_isSupersetOf_v2;
3525
3526 function requireEs_set_isSupersetOf_v2 () {
3527 if (hasRequiredEs_set_isSupersetOf_v2) return es_set_isSupersetOf_v2;
3528 hasRequiredEs_set_isSupersetOf_v2 = 1;
3529 var $ = require_export();
3530 var isSupersetOf = requireSetIsSupersetOf();
3531 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3532
3533 // `Set.prototype.isSupersetOf` method
3534 // https://tc39.es/ecma262/#sec-set.prototype.issupersetof
3535 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSupersetOf') }, {
3536 isSupersetOf: isSupersetOf
3537 });
3538 return es_set_isSupersetOf_v2;
3539 }
3540
3541 var hasRequiredEsnext_set_isSupersetOf_v2;
3542
3543 function requireEsnext_set_isSupersetOf_v2 () {
3544 if (hasRequiredEsnext_set_isSupersetOf_v2) return esnext_set_isSupersetOf_v2;
3545 hasRequiredEsnext_set_isSupersetOf_v2 = 1;
3546 // TODO: Remove from `core-js@4`
3547 requireEs_set_isSupersetOf_v2();
3548 return esnext_set_isSupersetOf_v2;
3549 }
3550
3551 requireEsnext_set_isSupersetOf_v2();
3552
3553 var esnext_set_symmetricDifference_v2 = {};
3554
3555 var es_set_symmetricDifference_v2 = {};
3556
3557 var setSymmetricDifference;
3558 var hasRequiredSetSymmetricDifference;
3559
3560 function requireSetSymmetricDifference () {
3561 if (hasRequiredSetSymmetricDifference) return setSymmetricDifference;
3562 hasRequiredSetSymmetricDifference = 1;
3563 var aSet = requireASet();
3564 var SetHelpers = requireSetHelpers();
3565 var clone = requireSetClone();
3566 var getSetRecord = requireGetSetRecord();
3567 var iterateSimple = requireIterateSimple();
3568
3569 var add = SetHelpers.add;
3570 var has = SetHelpers.has;
3571 var remove = SetHelpers.remove;
3572
3573 // `Set.prototype.symmetricDifference` method
3574 // https://github.com/tc39/proposal-set-methods
3575 setSymmetricDifference = function symmetricDifference(other) {
3576 var O = aSet(this);
3577 var keysIter = getSetRecord(other).getIterator();
3578 var result = clone(O);
3579 iterateSimple(keysIter, function (e) {
3580 if (has(O, e)) remove(result, e);
3581 else add(result, e);
3582 });
3583 return result;
3584 };
3585 return setSymmetricDifference;
3586 }
3587
3588 var hasRequiredEs_set_symmetricDifference_v2;
3589
3590 function requireEs_set_symmetricDifference_v2 () {
3591 if (hasRequiredEs_set_symmetricDifference_v2) return es_set_symmetricDifference_v2;
3592 hasRequiredEs_set_symmetricDifference_v2 = 1;
3593 var $ = require_export();
3594 var symmetricDifference = requireSetSymmetricDifference();
3595 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3596
3597 // `Set.prototype.symmetricDifference` method
3598 // https://tc39.es/ecma262/#sec-set.prototype.symmetricdifference
3599 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('symmetricDifference') }, {
3600 symmetricDifference: symmetricDifference
3601 });
3602 return es_set_symmetricDifference_v2;
3603 }
3604
3605 var hasRequiredEsnext_set_symmetricDifference_v2;
3606
3607 function requireEsnext_set_symmetricDifference_v2 () {
3608 if (hasRequiredEsnext_set_symmetricDifference_v2) return esnext_set_symmetricDifference_v2;
3609 hasRequiredEsnext_set_symmetricDifference_v2 = 1;
3610 // TODO: Remove from `core-js@4`
3611 requireEs_set_symmetricDifference_v2();
3612 return esnext_set_symmetricDifference_v2;
3613 }
3614
3615 requireEsnext_set_symmetricDifference_v2();
3616
3617 var esnext_set_union_v2 = {};
3618
3619 var es_set_union_v2 = {};
3620
3621 var setUnion;
3622 var hasRequiredSetUnion;
3623
3624 function requireSetUnion () {
3625 if (hasRequiredSetUnion) return setUnion;
3626 hasRequiredSetUnion = 1;
3627 var aSet = requireASet();
3628 var add = requireSetHelpers().add;
3629 var clone = requireSetClone();
3630 var getSetRecord = requireGetSetRecord();
3631 var iterateSimple = requireIterateSimple();
3632
3633 // `Set.prototype.union` method
3634 // https://github.com/tc39/proposal-set-methods
3635 setUnion = function union(other) {
3636 var O = aSet(this);
3637 var keysIter = getSetRecord(other).getIterator();
3638 var result = clone(O);
3639 iterateSimple(keysIter, function (it) {
3640 add(result, it);
3641 });
3642 return result;
3643 };
3644 return setUnion;
3645 }
3646
3647 var hasRequiredEs_set_union_v2;
3648
3649 function requireEs_set_union_v2 () {
3650 if (hasRequiredEs_set_union_v2) return es_set_union_v2;
3651 hasRequiredEs_set_union_v2 = 1;
3652 var $ = require_export();
3653 var union = requireSetUnion();
3654 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3655
3656 // `Set.prototype.union` method
3657 // https://tc39.es/ecma262/#sec-set.prototype.union
3658 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('union') }, {
3659 union: union
3660 });
3661 return es_set_union_v2;
3662 }
3663
3664 var hasRequiredEsnext_set_union_v2;
3665
3666 function requireEsnext_set_union_v2 () {
3667 if (hasRequiredEsnext_set_union_v2) return esnext_set_union_v2;
3668 hasRequiredEsnext_set_union_v2 = 1;
3669 // TODO: Remove from `core-js@4`
3670 requireEs_set_union_v2();
3671 return esnext_set_union_v2;
3672 }
3673
3674 requireEsnext_set_union_v2();
3675
3676 /** @import { Matrix3x3, Vector3 } from "./types.js" */
3677
3678 /**
3679 * A is m x n. B is n x p. product is m x p.
3680 *
3681 * Array arguments are treated like vectors:
3682 * - A becomes 1 x n
3683 * - B becomes n x 1
3684 *
3685 * Returns Matrix m x p or equivalent array or number
3686 *
3687 * @overload
3688 * @param {number[]} A Vector 1 x n
3689 * @param {number[]} B Vector n x 1
3690 * @returns {number} Scalar number
3691 *
3692 * @overload
3693 * @param {number[][]} A Matrix m x n
3694 * @param {number[]} B Vector n x 1
3695 * @returns {number[]} Array with length m
3696 *
3697 * @overload
3698 * @param {number[]} A Vector 1 x n
3699 * @param {number[][]} B Matrix n x p
3700 * @returns {number[]} Array with length p
3701 *
3702 * @overload
3703 * @param {number[][]} A Matrix m x n
3704 * @param {number[][]} B Matrix n x p
3705 * @returns {number[][]} Matrix m x p
3706 *
3707 * @param {number[] | number[][]} A Matrix m x n or a vector
3708 * @param {number[] | number[][]} B Matrix n x p or a vector
3709 * @returns {number | number[] | number[][]} Matrix m x p or equivalent array or number
3710 */
3711 function multiplyMatrices(A, B) {
3712 let m = A.length;
3713 /** @type {number[][]} */
3714 let AM;
3715 /** @type {number[][]} */
3716 let BM;
3717 let aVec = false;
3718 let bVec = false;
3719 if (!Array.isArray(A[0])) {
3720 // A is vector, convert to [[a, b, c, ...]]
3721 AM = [(/** @type {number[]} */A)];
3722 m = AM.length;
3723 aVec = true;
3724 } else {
3725 AM = /** @type {number[][]} */A;
3726 }
3727 if (!Array.isArray(B[0])) {
3728 // B is vector, convert to [[a], [b], [c], ...]]
3729 BM = B.length > 0 ? B.map(x => [x]) : [[]]; // Avoid mapping empty array
3730 bVec = true;
3731 } else {
3732 BM = /** @type {number[][]} */B;
3733 }
3734 let p = BM[0].length;
3735 let BM_cols = BM[0].map((_, i) => BM.map(x => x[i])); // transpose B
3736 /** @type {number[] | number[][]} */
3737 let product = AM.map(row => BM_cols.map(col => {
3738 let ret = 0;
3739 if (!Array.isArray(row)) {
3740 for (let c of col) {
3741 ret += row * c;
3742 }
3743 return ret;
3744 }
3745 for (let i = 0; i < row.length; i++) {
3746 ret += row[i] * (col[i] || 0);
3747 }
3748 return ret;
3749 }));
3750 if (m === 1 && aVec) {
3751 product = product[0]; // Avoid [[a, b, c, ...]]
3752 }
3753 if (p === 1 && bVec) {
3754 if (m === 1 && aVec) {
3755 return product[0]; // Avoid [[a]], return a number
3756 } else {
3757 return product.map(x => x[0]); // Avoid [[a], [b], [c], ...]]
3758 }
3759 }
3760 return product;
3761 }
3762
3763 // dot3 and transform functions adapted from https://github.com/texel-org/color/blob/9793c7d4d02b51f068e0f3fd37131129a4270396/src/core.js
3764 //
3765 // The MIT License (MIT)
3766 // Copyright (c) 2024 Matt DesLauriers
3767
3768 // Permission is hereby granted, free of charge, to any person obtaining a copy
3769 // of this software and associated documentation files (the "Software"), to deal
3770 // in the Software without restriction, including without limitation the rights
3771 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3772 // copies of the Software, and to permit persons to whom the Software is
3773 // furnished to do so, subject to the following conditions:
3774
3775 // The above copyright notice and this permission notice shall be included in all
3776 // copies or substantial portions of the Software.
3777
3778 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
3779 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3780 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
3781 // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3782 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3783 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
3784 // OR OTHER DEALINGS IN THE SOFTWARE.
3785
3786 /**
3787 * Returns the dot product of two vectors each with a length of 3.
3788 *
3789 * @param {Vector3} a
3790 * @param {Vector3} b
3791 * @returns {number}
3792 */
3793 function dot3(a, b) {
3794 return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
3795 }
3796
3797 /**
3798 * Transforms a vector of length 3 by a 3x3 matrix. Specify the same input and output
3799 * vector to transform in place.
3800 *
3801 * @param {Vector3} input
3802 * @param {Matrix3x3} matrix
3803 * @param {Vector3} [out]
3804 * @returns {Vector3}
3805 */
3806 function multiply_v3_m3x3(input, matrix, out = [0, 0, 0]) {
3807 const x = dot3(input, matrix[0]);
3808 const y = dot3(input, matrix[1]);
3809 const z = dot3(input, matrix[2]);
3810 out[0] = x;
3811 out[1] = y;
3812 out[2] = z;
3813 return out;
3814 }
3815
3816 /**
3817 * Various utility functions
3818 */
3819
3820
3821 /**
3822 * Check if a value is a string (including a String object)
3823 * @param {any} str - Value to check
3824 * @returns {str is string}
3825 */
3826 function isString(str) {
3827 return type(str) === "string";
3828 }
3829
3830 /**
3831 * Determine the internal JavaScript [[Class]] of an object.
3832 * @param {any} o - Value to check
3833 * @returns {string}
3834 */
3835 function type(o) {
3836 let str = Object.prototype.toString.call(o);
3837 return (str.match(/^\[object\s+(.*?)\]$/)[1] || "").toLowerCase();
3838 }
3839
3840 /**
3841 * @param {number} n
3842 * @param {{ precision?: number | undefined, unit?: string | undefined }} options
3843 * @returns {string}
3844 */
3845 function serializeNumber(n, {
3846 precision = 16,
3847 unit
3848 }) {
3849 if (isNone(n)) {
3850 return "none";
3851 }
3852 n = +toPrecision(n, precision);
3853 return n + (unit !== null && unit !== void 0 ? unit : "");
3854 }
3855
3856 /**
3857 * Check if a value corresponds to a none argument
3858 * @param {any} n - Value to check
3859 * @returns {n is null}
3860 */
3861 function isNone(n) {
3862 return n === null;
3863 }
3864
3865 /**
3866 * Replace none values with 0
3867 * @param {number | null} n
3868 * @returns {number}
3869 */
3870 function skipNone(n) {
3871 return isNone(n) ? 0 : n;
3872 }
3873
3874 /**
3875 * Round a number to a certain number of significant digits
3876 * @param {number} n - The number to round
3877 * @param {number} precision - Number of significant digits
3878 */
3879 function toPrecision(n, precision) {
3880 if (n === 0) {
3881 return 0;
3882 }
3883 let integer = ~~n;
3884 let digits = 0;
3885 if (integer && precision) {
3886 digits = ~~Math.log10(Math.abs(integer)) + 1;
3887 }
3888 const multiplier = 10.0 ** (precision - digits);
3889 return Math.floor(n * multiplier + 0.5) / multiplier;
3890 }
3891
3892 /**
3893 * @param {number} start
3894 * @param {number} end
3895 * @param {number} p
3896 */
3897 function interpolate(start, end, p) {
3898 if (isNaN(start)) {
3899 return end;
3900 }
3901 if (isNaN(end)) {
3902 return start;
3903 }
3904 return start + (end - start) * p;
3905 }
3906
3907 /**
3908 * @param {number} start
3909 * @param {number} end
3910 * @param {number} value
3911 */
3912 function interpolateInv(start, end, value) {
3913 return (value - start) / (end - start);
3914 }
3915
3916 /**
3917 * @param {[number, number]} from
3918 * @param {[number, number]} to
3919 * @param {number} value
3920 */
3921 function mapRange(from, to, value) {
3922 if (!from || !to || from === to || from[0] === to[0] && from[1] === to[1] || isNaN(value) || value === null) {
3923 // Ranges missing or the same
3924 return value;
3925 }
3926 return interpolate(to[0], to[1], interpolateInv(from[0], from[1], value));
3927 }
3928
3929 /**
3930 * Clamp value between the minimum and maximum
3931 * @param {number} min minimum value to return
3932 * @param {number} val the value to return if it is between min and max
3933 * @param {number} max maximum value to return
3934 */
3935 function clamp(min, val, max) {
3936 return Math.max(Math.min(max, val), min);
3937 }
3938
3939 /**
3940 * Copy sign of one value to another.
3941 * @param {number} to - Number to copy sign to
3942 * @param {number} from - Number to copy sign from
3943 */
3944 function copySign(to, from) {
3945 return Math.sign(to) === Math.sign(from) ? to : -to;
3946 }
3947
3948 /**
3949 * Perform pow on a signed number and copy sign to result
3950 * @param {number} base The base number
3951 * @param {number} exp The exponent
3952 */
3953 function spow(base, exp) {
3954 return copySign(Math.abs(base) ** exp, base);
3955 }
3956
3957 /**
3958 * Perform a divide, but return zero if the denominator is zero
3959 * @param {number} n The numerator
3960 * @param {number} d The denominator
3961 */
3962 function zdiv(n, d) {
3963 return d === 0 ? 0 : n / d;
3964 }
3965
3966 /**
3967 * Perform a bisect on a sorted list and locate the insertion point for
3968 * a value in arr to maintain sorted order.
3969 * @param {number[]} arr - array of sorted numbers
3970 * @param {number} value - value to find insertion point for
3971 * @param {number} lo - used to specify a the low end of a subset of the list
3972 * @param {number} hi - used to specify a the high end of a subset of the list
3973 */
3974 function bisectLeft(arr, value, lo = 0, hi = arr.length) {
3975 while (lo < hi) {
3976 const mid = lo + hi >> 1;
3977 if (arr[mid] < value) {
3978 lo = mid + 1;
3979 } else {
3980 hi = mid;
3981 }
3982 }
3983 return lo;
3984 }
3985
3986 /**
3987 * Determines whether an argument is an instance of a constructor, including subclasses.
3988 * This is done by first just checking `instanceof`,
3989 * and then comparing the string names of the constructors if that fails.
3990 * @param {any} arg
3991 * @param {C} constructor
3992 * @template {new (...args: any) => any} C
3993 * @returns {arg is InstanceType<C>}
3994 */
3995 function isInstance(arg, constructor) {
3996 if (arg instanceof constructor) {
3997 return true;
3998 }
3999 const targetName = constructor.name;
4000 while (arg) {
4001 var _proto$constructor;
4002 const proto = Object.getPrototypeOf(arg);
4003 const constructorName = proto === null || proto === void 0 || (_proto$constructor = proto.constructor) === null || _proto$constructor === void 0 ? void 0 : _proto$constructor.name;
4004 if (constructorName === targetName) {
4005 return true;
4006 }
4007 if (!constructorName || constructorName === "Object") {
4008 return false;
4009 }
4010 arg = proto;
4011 }
4012 return false;
4013 }
4014
4015 var esnext_iterator_find = {};
4016
4017 var es_iterator_find = {};
4018
4019 var hasRequiredEs_iterator_find;
4020
4021 function requireEs_iterator_find () {
4022 if (hasRequiredEs_iterator_find) return es_iterator_find;
4023 hasRequiredEs_iterator_find = 1;
4024 var $ = require_export();
4025 var iterate = requireIterate();
4026 var aCallable = requireACallable();
4027 var anObject = requireAnObject();
4028 var getIteratorDirect = requireGetIteratorDirect();
4029
4030 // `Iterator.prototype.find` method
4031 // https://tc39.es/ecma262/#sec-iterator.prototype.find
4032 $({ target: 'Iterator', proto: true, real: true }, {
4033 find: function find(predicate) {
4034 anObject(this);
4035 aCallable(predicate);
4036 var record = getIteratorDirect(this);
4037 var counter = 0;
4038 return iterate(record, function (value, stop) {
4039 if (predicate(value, counter++)) return stop(value);
4040 }, { IS_RECORD: true, INTERRUPTED: true }).result;
4041 }
4042 });
4043 return es_iterator_find;
4044 }
4045
4046 var hasRequiredEsnext_iterator_find;
4047
4048 function requireEsnext_iterator_find () {
4049 if (hasRequiredEsnext_iterator_find) return esnext_iterator_find;
4050 hasRequiredEsnext_iterator_find = 1;
4051 // TODO: Remove from `core-js@4`
4052 requireEs_iterator_find();
4053 return esnext_iterator_find;
4054 }
4055
4056 requireEsnext_iterator_find();
4057
4058 class Type {
4059 // Class properties - declared here so that type inference works
4060 type;
4061 coordMeta;
4062 coordRange;
4063 /** @type {[number, number]} */
4064 range;
4065
4066 /**
4067 * @param {any} type
4068 * @param {import("./types.js").CoordMeta} coordMeta
4069 */
4070 constructor(type, coordMeta) {
4071 if (typeof type === "object") {
4072 this.coordMeta = type;
4073 }
4074 if (coordMeta) {
4075 var _coordMeta$range;
4076 this.coordMeta = coordMeta;
4077 this.coordRange = (_coordMeta$range = coordMeta.range) !== null && _coordMeta$range !== void 0 ? _coordMeta$range : coordMeta.refRange;
4078 }
4079 if (typeof type === "string") {
4080 let params = type.trim().match(/^(?<type><[a-z]+>)(\[(?<min>-?[.\d]+),\s*(?<max>-?[.\d]+)\])?$/);
4081 if (!params) {
4082 throw new TypeError(`Cannot parse ${type} as a type definition.`);
4083 }
4084 this.type = params.groups.type;
4085 let {
4086 min,
4087 max
4088 } = params.groups;
4089 if (min || max) {
4090 this.range = [+min, +max];
4091 }
4092 }
4093 }
4094
4095 /** @returns {[number, number]} */
4096 get computedRange() {
4097 if (this.range) {
4098 return this.range;
4099 }
4100 if (this.type === "<percentage>") {
4101 return this.percentageRange();
4102 } else if (this.type === "<angle>") {
4103 return [0, 360];
4104 }
4105 return null;
4106 }
4107 get unit() {
4108 if (this.type === "<percentage>") {
4109 return "%";
4110 } else if (this.type === "<angle>") {
4111 return "deg";
4112 }
4113 return "";
4114 }
4115
4116 /**
4117 * Map a number to the internal representation
4118 * @param {number} number
4119 */
4120 resolve(number) {
4121 if (this.type === "<angle>") {
4122 return number;
4123 }
4124 let fromRange = this.computedRange;
4125 let toRange = this.coordRange;
4126 if (this.type === "<percentage>") {
4127 var _toRange;
4128 (_toRange = toRange) !== null && _toRange !== void 0 ? _toRange : toRange = this.percentageRange();
4129 }
4130 return mapRange(fromRange, toRange, number);
4131 }
4132
4133 /**
4134 * Serialize a number from the internal representation to a string
4135 * @param {number} number
4136 * @param {number} [precision]
4137 */
4138 serialize(number, precision) {
4139 let toRange = this.type === "<percentage>" ? this.percentageRange(100) : this.computedRange;
4140 let unit = this.unit;
4141 number = mapRange(this.coordRange, toRange, number);
4142 return serializeNumber(number, {
4143 unit,
4144 precision
4145 });
4146 }
4147 toString() {
4148 let ret = this.type;
4149 if (this.range) {
4150 let [min = "", max = ""] = this.range;
4151 ret += `[${min},${max}]`;
4152 }
4153 return ret;
4154 }
4155
4156 /**
4157 * Returns a percentage range for values of this type
4158 * @param {number} scale
4159 * @returns {[number, number]}
4160 */
4161 percentageRange(scale = 1) {
4162 let range;
4163 if (this.coordMeta && this.coordMeta.range || this.coordRange && this.coordRange[0] >= 0) {
4164 range = [0, 1];
4165 } else {
4166 range = [-1, 1];
4167 }
4168 return [range[0] * scale, range[1] * scale];
4169 }
4170 static get(type, coordMeta) {
4171 if (isInstance(type, this)) {
4172 return type;
4173 }
4174 return new this(type, coordMeta);
4175 }
4176 }
4177
4178 /** @import { ColorSpace, Coords } from "./types.js" */
4179
4180 // Type re-exports
4181 /** @typedef {import("./types.js").Format} FormatInterface */
4182
4183 /**
4184 * @internal
4185 * Used to index {@link FormatInterface Format} objects and store an instance.
4186 * Not meant for external use
4187 */
4188 const instance = Symbol("instance");
4189
4190 /**
4191 * Remove the first element of an array type
4192 * @template {any[]} T
4193 * @typedef {T extends [any, ...infer R] ? R : T[number][]} RemoveFirstElement
4194 */
4195
4196 /**
4197 * @class Format
4198 * @implements {Omit<FormatInterface, "coords" | "serializeCoords">}
4199 * Class to hold a color serialization format
4200 */
4201 class Format {
4202 // Class properties - declared here so that type inference works
4203 type;
4204 name;
4205 spaceCoords;
4206 /** @type {Type[][]} */
4207 coords;
4208 /** @type {string | undefined} */
4209 id;
4210 /** @type {boolean | undefined} */
4211 alpha;
4212
4213 /**
4214 * @param {FormatInterface} format
4215 * @param {ColorSpace} space
4216 */
4217 constructor(format, space = format.space) {
4218 format[instance] = this;
4219 this.type = "function";
4220 this.name = "color";
4221 Object.assign(this, format);
4222 this.space = space;
4223 if (this.type === "custom") {
4224 // Nothing else to do here
4225 return;
4226 }
4227 this.spaceCoords = Object.values(space.coords);
4228 if (!this.coords) {
4229 // @ts-expect-error Strings are converted to the correct type later
4230 this.coords = this.spaceCoords.map(coordMeta => {
4231 let ret = ["<number>", "<percentage>"];
4232 if (coordMeta.type === "angle") {
4233 ret.push("<angle>");
4234 }
4235 return ret;
4236 });
4237 }
4238 this.coords = this.coords.map(/** @param {string | string[] | Type[]} types */(types, i) => {
4239 let coordMeta = this.spaceCoords[i];
4240 if (typeof types === "string") {
4241 types = types.trim().split(/\s*\|\s*/);
4242 }
4243 return types.map(type => Type.get(type, coordMeta));
4244 });
4245 }
4246
4247 /**
4248 * @param {Coords} coords
4249 * @param {number} precision
4250 * @param {Type[]} types
4251 */
4252 serializeCoords(coords, precision, types) {
4253 types = coords.map((_, i) => {
4254 var _types$i, _types;
4255 return Type.get((_types$i = (_types = types) === null || _types === void 0 ? void 0 : _types[i]) !== null && _types$i !== void 0 ? _types$i : this.coords[i][0], this.spaceCoords[i]);
4256 });
4257 return coords.map((c, i) => types[i].serialize(c, precision));
4258 }
4259
4260 /**
4261 * Validates the coordinates of a color against a format's coord grammar and
4262 * maps the coordinates to the range or refRange of the coordinates.
4263 * @param {Coords} coords
4264 * @param {[string, string, string]} types
4265 */
4266 coerceCoords(coords, types) {
4267 return Object.entries(this.space.coords).map(([id, coordMeta], i) => {
4268 let arg = coords[i];
4269 if (isNone(arg) || isNaN(arg)) {
4270 // Nothing to do here
4271 return arg;
4272 }
4273
4274 // Find grammar alternative that matches the provided type
4275 // Non-strict equals is intentional because we are comparing w/ string objects
4276 let providedType = types[i];
4277 let type = this.coords[i].find(c => c.type == providedType);
4278
4279 // Check that each coord conforms to its grammar
4280 if (!type) {
4281 var _ref, _arg;
4282 // Type does not exist in the grammar, throw
4283 let coordName = coordMeta.name || id;
4284 throw new TypeError(`${(_ref = providedType !== null && providedType !== void 0 ? providedType : /** @type {any} */(_arg = arg) === null || _arg === void 0 ? void 0 : _arg.raw) !== null && _ref !== void 0 ? _ref : arg} not allowed for ${coordName} in ${this.name}()`);
4285 }
4286 arg = type.resolve(arg);
4287 if (type.range) {
4288 // Adjust type to include range
4289 types[i] = type.toString();
4290 }
4291 return arg;
4292 });
4293 }
4294
4295 /**
4296 * @returns {boolean | Required<FormatInterface>["serialize"]}
4297 */
4298 canSerialize() {
4299 return this.type === "function" || /** @type {any} */this.serialize;
4300 }
4301
4302 /**
4303 * @param {string} str
4304 * @returns {(import("./types.js").ColorConstructor) | undefined | null}
4305 */
4306 parse(str) {
4307 return null;
4308 }
4309
4310 /**
4311 * @param {Format | FormatInterface} format
4312 * @param {RemoveFirstElement<ConstructorParameters<typeof Format>>} args
4313 * @returns {Format}
4314 */
4315 static get(format, ...args) {
4316 if (!format || isInstance(format, this)) {
4317 return /** @type {Format} */format;
4318 }
4319 if (format[instance]) {
4320 return format[instance];
4321 }
4322 return new Format(format, ...args);
4323 }
4324 }
4325
4326 var esnext_iterator_forEach = {};
4327
4328 var es_iterator_forEach = {};
4329
4330 var hasRequiredEs_iterator_forEach;
4331
4332 function requireEs_iterator_forEach () {
4333 if (hasRequiredEs_iterator_forEach) return es_iterator_forEach;
4334 hasRequiredEs_iterator_forEach = 1;
4335 var $ = require_export();
4336 var iterate = requireIterate();
4337 var aCallable = requireACallable();
4338 var anObject = requireAnObject();
4339 var getIteratorDirect = requireGetIteratorDirect();
4340
4341 // `Iterator.prototype.forEach` method
4342 // https://tc39.es/ecma262/#sec-iterator.prototype.foreach
4343 $({ target: 'Iterator', proto: true, real: true }, {
4344 forEach: function forEach(fn) {
4345 anObject(this);
4346 aCallable(fn);
4347 var record = getIteratorDirect(this);
4348 var counter = 0;
4349 iterate(record, function (value) {
4350 fn(value, counter++);
4351 }, { IS_RECORD: true });
4352 }
4353 });
4354 return es_iterator_forEach;
4355 }
4356
4357 var hasRequiredEsnext_iterator_forEach;
4358
4359 function requireEsnext_iterator_forEach () {
4360 if (hasRequiredEsnext_iterator_forEach) return esnext_iterator_forEach;
4361 hasRequiredEsnext_iterator_forEach = 1;
4362 // TODO: Remove from `core-js@4`
4363 requireEs_iterator_forEach();
4364 return esnext_iterator_forEach;
4365 }
4366
4367 requireEsnext_iterator_forEach();
4368
4369 /**
4370 * A class for adding deep extensibility to any piece of JS code
4371 */
4372 class Hooks {
4373 add(name, callback, first) {
4374 if (typeof arguments[0] != "string") {
4375 // Multiple hooks
4376 for (var name in arguments[0]) {
4377 this.add(name, arguments[0][name], arguments[1]);
4378 }
4379 return;
4380 }
4381 (Array.isArray(name) ? name : [name]).forEach(function (name) {
4382 this[name] = this[name] || [];
4383 if (callback) {
4384 this[name][first ? "unshift" : "push"](callback);
4385 }
4386 }, this);
4387 }
4388 run(name, env) {
4389 this[name] = this[name] || [];
4390 this[name].forEach(function (callback) {
4391 callback.call(env && env.context ? env.context : env, env);
4392 });
4393 }
4394 }
4395
4396 /**
4397 * The instance of {@link Hooks} used throughout Color.js
4398 */
4399 const hooks = new Hooks();
4400
4401 // Type re-exports
4402 /** @typedef {import("./types.js").White} White */
4403
4404 /** @type {Record<string, White>} */
4405 // prettier-ignore
4406 const WHITES = {
4407 // for compatibility, the four-digit chromaticity-derived ones everyone else uses
4408 D50: [0.3457 / 0.3585, 1.00000, (1.0 - 0.3457 - 0.3585) / 0.3585],
4409 D65: [0.3127 / 0.3290, 1.00000, (1.0 - 0.3127 - 0.3290) / 0.3290]
4410 };
4411
4412 /**
4413 *
4414 * @param {string | White} name
4415 * @returns {White}
4416 */
4417 function getWhite(name) {
4418 if (Array.isArray(name)) {
4419 return name;
4420 }
4421 return WHITES[name];
4422 }
4423
4424 /**
4425 * Adapt XYZ from white point W1 to W2
4426 * @param {White | string} W1
4427 * @param {White | string} W2
4428 * @param {[number, number, number]} XYZ
4429 * @param {{ method?: string | undefined }} options
4430 * @returns {[number, number, number]}
4431 */
4432 function adapt$2(W1, W2, XYZ, options = {}) {
4433 W1 = getWhite(W1);
4434 W2 = getWhite(W2);
4435 if (!W1 || !W2) {
4436 throw new TypeError(`Missing white point to convert ${!W1 ? "from" : ""}${!W1 && !W2 ? "/" : ""}${!W2 ? "to" : ""}`);
4437 }
4438 if (W1 === W2) {
4439 // Same whitepoints, no conversion needed
4440 return XYZ;
4441 }
4442 let env = {
4443 W1,
4444 W2,
4445 XYZ,
4446 options
4447 };
4448 hooks.run("chromatic-adaptation-start", env);
4449 if (!env.M) {
4450 if (env.W1 === WHITES.D65 && env.W2 === WHITES.D50) {
4451 // prettier-ignore
4452 env.M = [[1.0479297925449969, 0.022946870601609652, -0.05019226628920524], [0.02962780877005599, 0.9904344267538799, -0.017073799063418826], [-0.009243040646204504, 0.015055191490298152, 0.7518742814281371]];
4453 } else if (env.W1 === WHITES.D50 && env.W2 === WHITES.D65) {
4454 // prettier-ignore
4455 env.M = [[0.955473421488075, -0.02309845494876471, 0.06325924320057072], [-0.0283697093338637, 1.0099953980813041, 0.021041441191917323], [0.012314014864481998, -0.020507649298898964, 1.330365926242124]];
4456 }
4457 }
4458 hooks.run("chromatic-adaptation-end", env);
4459 if (env.M) {
4460 return multiply_v3_m3x3(env.XYZ, env.M);
4461 } else {
4462 throw new TypeError("Only Bradford CAT with white points D50 and D65 supported for now.");
4463 }
4464 }
4465
4466 var _globalThis$process;
4467 // Global defaults one may want to configure
4468 var defaults = {
4469 gamut_mapping: "css",
4470 precision: 5,
4471 deltaE: "76",
4472 // Default deltaE method
4473 verbose: (globalThis === null || globalThis === void 0 || (_globalThis$process = globalThis.process) === null || _globalThis$process === void 0 || (_globalThis$process = _globalThis$process.env) === null || _globalThis$process === void 0 || (_globalThis$process = _globalThis$process.NODE_ENV) === null || _globalThis$process === void 0 ? void 0 : _globalThis$process.toLowerCase()) !== "test",
4474 warn: function warn(msg) {
4475 if (this.verbose) {
4476 var _globalThis$console, _globalThis$console$w;
4477 globalThis === null || globalThis === void 0 || (_globalThis$console = globalThis.console) === null || _globalThis$console === void 0 || (_globalThis$console$w = _globalThis$console.warn) === null || _globalThis$console$w === void 0 || _globalThis$console$w.call(_globalThis$console, msg);
4478 }
4479 }
4480 };
4481
4482 /** @import { ColorConstructor } from "./types.js" */
4483
4484 // Type re-exports
4485 /** @typedef {import("./types.js").ArgumentMeta} ArgumentMeta */
4486 /** @typedef {import("./types.js").ParseFunctionReturn} ParseFunctionReturn */
4487 /** @typedef {import("./types.js").ParseOptions} ParseOptions */
4488
4489 /**
4490 * Convert a CSS Color string to a color object
4491 * @param {string} str
4492 * @param {ParseOptions} [options]
4493 * @returns {ColorConstructor}
4494 */
4495 function parse(str, options) {
4496 var _String, _env$options$parseMet;
4497 let env = {
4498 str: (_String = String(str)) === null || _String === void 0 ? void 0 : _String.trim(),
4499 options
4500 };
4501 hooks.run("parse-start", env);
4502 if (env.color) {
4503 return env.color;
4504 }
4505 env.parsed = parseFunction(env.str);
4506 let ret;
4507 let meta = env.options ? (_env$options$parseMet = env.options.parseMeta) !== null && _env$options$parseMet !== void 0 ? _env$options$parseMet : env.options.meta : null;
4508 if (env.parsed) {
4509 // Is a functional syntax
4510 let name = env.parsed.name;
4511 let format;
4512 let space;
4513 let coords = env.parsed.args;
4514 let types = coords.map((c, i) => {
4515 var _env$parsed$argMeta$i;
4516 return (_env$parsed$argMeta$i = env.parsed.argMeta[i]) === null || _env$parsed$argMeta$i === void 0 ? void 0 : _env$parsed$argMeta$i.type;
4517 });
4518 if (name === "color") {
4519 // color() function
4520 let id = coords.shift();
4521 types.shift();
4522 // Check against both <dashed-ident> and <ident> versions
4523 let alternateId = id.startsWith("--") ? id.substring(2) : `--${id}`;
4524 let ids = [id, alternateId];
4525 format = ColorSpace.findFormat({
4526 name,
4527 id: ids,
4528 type: "function"
4529 });
4530 if (!format) {
4531 var _didYouMean;
4532 // Not found
4533 let didYouMean;
4534 let registryId = id in ColorSpace.registry ? id : alternateId;
4535 if (registryId in ColorSpace.registry) {
4536 var _ColorSpace$registry$;
4537 // Used color space id instead of color() id, these are often different
4538 let cssId = (_ColorSpace$registry$ = ColorSpace.registry[registryId].formats) === null || _ColorSpace$registry$ === void 0 || (_ColorSpace$registry$ = _ColorSpace$registry$.color) === null || _ColorSpace$registry$ === void 0 ? void 0 : _ColorSpace$registry$.id;
4539 if (cssId) {
4540 let altColor = str.replace("color(" + id, "color(" + cssId);
4541 didYouMean = `Did you mean ${altColor}?`;
4542 }
4543 }
4544 throw new TypeError(`Cannot parse ${env.str}. ` + ((_didYouMean = didYouMean) !== null && _didYouMean !== void 0 ? _didYouMean : "Missing a plugin?"));
4545 }
4546 space = format.space;
4547 if (format.id.startsWith("--") && !id.startsWith("--")) {
4548 defaults.warn(`${space.name} is a non-standard space and not currently supported in the CSS spec. ` + `Use prefixed color(${format.id}) instead of color(${id}).`);
4549 }
4550 if (id.startsWith("--") && !format.id.startsWith("--")) {
4551 defaults.warn(`${space.name} is a standard space and supported in the CSS spec. ` + `Use color(${format.id}) instead of prefixed color(${id}).`);
4552 }
4553 } else {
4554 format = ColorSpace.findFormat({
4555 name,
4556 type: "function"
4557 });
4558 space = format.space;
4559 }
4560 if (meta) {
4561 Object.assign(meta, {
4562 format,
4563 formatId: format.name,
4564 types,
4565 commas: env.parsed.commas
4566 });
4567 }
4568 let alpha = 1;
4569 if (env.parsed.lastAlpha) {
4570 alpha = env.parsed.args.pop();
4571 if (meta) {
4572 meta.alphaType = types.pop();
4573 }
4574 }
4575 let coordCount = format.coords.length;
4576 if (coords.length !== coordCount) {
4577 throw new TypeError(`Expected ${coordCount} coordinates for ${space.id} in ${env.str}), got ${coords.length}`);
4578 }
4579 coords = format.coerceCoords(coords, types);
4580 ret = {
4581 spaceId: space.id,
4582 coords,
4583 alpha
4584 };
4585 } else {
4586 // Custom, colorspace-specific format
4587 spaceloop: for (let space of ColorSpace.all) {
4588 for (let formatId in space.formats) {
4589 let format = space.formats[formatId];
4590 if (format.type !== "custom") {
4591 continue;
4592 }
4593 if (format.test && !format.test(env.str)) {
4594 continue;
4595 }
4596
4597 // Convert to Format object
4598 let formatObject = space.getFormat(format);
4599 let color = formatObject.parse(env.str);
4600 if (color) {
4601 if (meta) {
4602 Object.assign(meta, {
4603 format: formatObject,
4604 formatId
4605 });
4606 }
4607 ret = color;
4608 break spaceloop;
4609 }
4610 }
4611 }
4612 }
4613 if (!ret) {
4614 // If we're here, we couldn't parse
4615 throw new TypeError(`Could not parse ${str} as a color. Missing a plugin?`);
4616 }
4617
4618 // Clamp alpha to [0, 1]
4619 ret.alpha = isNone(ret.alpha) ? ret.alpha : ret.alpha === undefined ? 1 : clamp(0, ret.alpha, 1);
4620 return ret;
4621 }
4622
4623 /**
4624 * Units and multiplication factors for the internally stored numbers
4625 */
4626 const units = {
4627 "%": 0.01,
4628 deg: 1,
4629 grad: 0.9,
4630 rad: 180 / Math.PI,
4631 turn: 360
4632 };
4633 const regex = {
4634 // Need to list calc(NaN) explicitly as otherwise its ending paren would terminate the function call
4635 function: /^([a-z]+)\(((?:calc\(NaN\)|.)+?)\)$/i,
4636 number: /^([-+]?(?:[0-9]*\.)?[0-9]+(e[-+]?[0-9]+)?)$/i,
4637 unitValue: RegExp(`(${Object.keys(units).join("|")})$`),
4638 // NOTE The -+ are not just for prefix, but also for idents, and e+N notation!
4639 singleArgument: /\/?\s*(none|NaN|calc\(NaN\)|[-+\w.]+(?:%|deg|g?rad|turn)?)/g
4640 };
4641
4642 /**
4643 * Parse a single function argument
4644 * @param {string} rawArg
4645 * @returns {{value: number, meta: ArgumentMeta}}
4646 */
4647 function parseArgument(rawArg) {
4648 var _rawArg$match;
4649 /** @type {Partial<ArgumentMeta>} */
4650 let meta = {};
4651 let unit = (_rawArg$match = rawArg.match(regex.unitValue)) === null || _rawArg$match === void 0 ? void 0 : _rawArg$match[0];
4652 /** @type {string | number} */
4653 let value = meta.raw = rawArg;
4654 if (unit) {
4655 // It’s a dimension token
4656 meta.type = unit === "%" ? "<percentage>" : "<angle>";
4657 meta.unit = unit;
4658 meta.unitless = Number(value.slice(0, -unit.length)); // unitless number
4659
4660 value = meta.unitless * units[unit];
4661 } else if (regex.number.test(value)) {
4662 // It's a number
4663 // Convert numerical args to numbers
4664 value = Number(value);
4665 meta.type = "<number>";
4666 } else if (value === "none") {
4667 value = null;
4668 } else if (value === "NaN" || value === "calc(NaN)") {
4669 value = NaN;
4670 meta.type = "<number>";
4671 } else {
4672 meta.type = "<ident>";
4673 }
4674 return {
4675 value: (/** @type {number} */value),
4676 meta: (/** @type {ArgumentMeta} */meta)
4677 };
4678 }
4679
4680 /**
4681 * Parse a CSS function, regardless of its name and arguments
4682 * @param {string} str String to parse
4683 * @return {ParseFunctionReturn | void}
4684 */
4685 function parseFunction(str) {
4686 if (!str) {
4687 return;
4688 }
4689 str = str.trim();
4690 let parts = str.match(regex.function);
4691 if (parts) {
4692 // It is a function, parse args
4693 let args = [];
4694 let argMeta = [];
4695 let lastAlpha = false;
4696 let name = parts[1].toLowerCase();
4697 let separators = parts[2].replace(regex.singleArgument, ($0, rawArg) => {
4698 let {
4699 value,
4700 meta
4701 } = parseArgument(rawArg);
4702 if (
4703 // If there's a slash here, it's modern syntax
4704 $0.startsWith("/") ||
4705 // If there's still elements to process after there's already 3 in `args` (and the we're not dealing with "color()"), it's likely to be a legacy color like "hsl(0, 0%, 0%, 0.5)"
4706 name !== "color" && args.length === 3) {
4707 // It's alpha
4708 lastAlpha = true;
4709 }
4710 args.push(value);
4711 argMeta.push(meta);
4712 return "";
4713 });
4714 return {
4715 name,
4716 args,
4717 argMeta,
4718 lastAlpha,
4719 commas: separators.includes(","),
4720 rawName: parts[1],
4721 rawArgs: parts[2]
4722 };
4723 }
4724 }
4725
4726 /** @import { ColorTypes, ParseOptions as GetColorOptions, PlainColorObject } from "./types.js" */
4727
4728 /**
4729 * Resolves a color reference (object or string) to a plain color object
4730 * @overload
4731 * @param {ColorTypes} color
4732 * @param {GetColorOptions} [options]
4733 * @returns {PlainColorObject}
4734 */
4735 /**
4736 * @overload
4737 * @param {ColorTypes[]} color
4738 * @param {GetColorOptions} [options]
4739 * @returns {PlainColorObject[]}
4740 */
4741 function getColor(color, options) {
4742 if (Array.isArray(color)) {
4743 return color.map(c => getColor(c, options));
4744 }
4745 if (!color) {
4746 throw new TypeError("Empty color reference");
4747 }
4748 if (isString(color)) {
4749 color = parse(color, options);
4750 }
4751
4752 // Object fixup
4753 let space = color.space || color.spaceId;
4754 if (typeof space === "string") {
4755 // Convert string id to color space object
4756 color.space = ColorSpace.get(space);
4757 }
4758 if (color.alpha === undefined) {
4759 color.alpha = 1;
4760 }
4761 return color;
4762 }
4763
4764 const ε$7 = 0.000075;
4765
4766 /**
4767 * Class to represent a color space
4768 */
4769 class ColorSpace {
4770 constructor(options) {
4771 var _options$displaySpace, _options$coords, _ref, _options$white, _options$formats, _this$formats$color;
4772 this.id = options.id;
4773 this.name = options.name;
4774 this.base = options.base ? ColorSpace.get(options.base) : null;
4775 this.aliases = options.aliases;
4776 this.displaySpaces = (_options$displaySpace = options.displaySpaces) === null || _options$displaySpace === void 0 ? void 0 : _options$displaySpace.map(space => ColorSpace.get(space));
4777
4778 // This space's ancestors, closest first (immediate base → root), excluding the space itself.
4779 this.bases = [];
4780 for (let base = this.base; base; base = base.base) {
4781 this.bases.push(base);
4782 }
4783 if (options.rgbGamut) {
4784 this.rgbGamut = options.rgbGamut;
4785 }
4786 if (options.linearGamut) {
4787 this.linearGamut = options.linearGamut;
4788 }
4789 if (this.base) {
4790 this.fromBase = options.fromBase;
4791 this.toBase = options.toBase;
4792 }
4793
4794 // Coordinate metadata
4795
4796 let coords = (_options$coords = options.coords) !== null && _options$coords !== void 0 ? _options$coords : this.base.coords;
4797 for (let name in coords) {
4798 if (!("name" in coords[name])) {
4799 coords[name].name = name;
4800 }
4801 }
4802 this.coords = coords;
4803
4804 // White point
4805
4806 let white = (_ref = (_options$white = options.white) !== null && _options$white !== void 0 ? _options$white : this.base.white) !== null && _ref !== void 0 ? _ref : "D65";
4807 this.white = getWhite(white);
4808
4809 // Sort out formats
4810
4811 this.formats = (_options$formats = options.formats) !== null && _options$formats !== void 0 ? _options$formats : {};
4812 for (let name in this.formats) {
4813 let format = this.formats[name];
4814 format.type || (format.type = "function");
4815 format.name || (format.name = name);
4816 }
4817 if (!((_this$formats$color = this.formats.color) !== null && _this$formats$color !== void 0 && _this$formats$color.id)) {
4818 var _this$formats$color2;
4819 this.formats.color = {
4820 ...((_this$formats$color2 = this.formats.color) !== null && _this$formats$color2 !== void 0 ? _this$formats$color2 : {}),
4821 id: options.cssId || this.id
4822 };
4823 }
4824
4825 // Gamut space
4826
4827 if (options.gamutSpace) {
4828 // Gamut space explicitly specified
4829 this.gamutSpace = options.gamutSpace === "self" ? this : ColorSpace.get(options.gamutSpace);
4830 } else {
4831 // No gamut space specified, calculate a sensible default
4832 if (this.isPolar) {
4833 // Do not check gamut through polar coordinates
4834 this.gamutSpace = this.base;
4835 } else {
4836 this.gamutSpace = this;
4837 }
4838 }
4839
4840 // Optimize inGamut for unbounded spaces
4841 if (this.gamutSpace.isUnbounded) {
4842 this.inGamut = (coords, options) => {
4843 return true;
4844 };
4845 }
4846
4847 // Other stuff
4848 this.referred = options.referred;
4849
4850 // Compute ancestors and store them, since they will never change
4851 Object.defineProperty(this, "path", {
4852 value: getPath(this).reverse(),
4853 writable: false,
4854 enumerable: true,
4855 configurable: true
4856 });
4857 hooks.run("colorspace-init-end", this);
4858 }
4859 inGamut(coords, {
4860 epsilon = ε$7
4861 } = {}) {
4862 if (!this.equals(this.gamutSpace)) {
4863 coords = this.to(this.gamutSpace, coords);
4864 return this.gamutSpace.inGamut(coords, {
4865 epsilon
4866 });
4867 }
4868 let coordMeta = Object.values(this.coords);
4869 return coords.every((c, i) => {
4870 let meta = coordMeta[i];
4871 if (meta.type !== "angle" && meta.range) {
4872 if (isNone(c)) {
4873 // NaN is always in gamut
4874 return true;
4875 }
4876 let [min, max] = meta.range;
4877 return (min === undefined || c >= min - epsilon) && (max === undefined || c <= max + epsilon);
4878 }
4879 return true;
4880 });
4881 }
4882 get isUnbounded() {
4883 return Object.values(this.coords).every(coord => !("range" in coord));
4884 }
4885 get cssId() {
4886 var _this$formats;
4887 return ((_this$formats = this.formats) === null || _this$formats === void 0 || (_this$formats = _this$formats.color) === null || _this$formats === void 0 ? void 0 : _this$formats.id) || this.id;
4888 }
4889 get isPolar() {
4890 for (let id in this.coords) {
4891 if (this.coords[id].type === "angle") {
4892 return true;
4893 }
4894 }
4895 return false;
4896 }
4897
4898 /**
4899 * Lookup a format in this color space
4900 * @param {string | object | Format} format - Format id if string. If object, it's converted to a `Format` object and returned.
4901 * @returns {Format}
4902 */
4903 getFormat(format) {
4904 if (!format) {
4905 return null;
4906 }
4907 if (format === "default") {
4908 format = Object.values(this.formats)[0];
4909 } else if (typeof format === "string") {
4910 format = this.formats[format];
4911 }
4912 let ret = Format.get(format, this);
4913 if (ret !== format && format.name in this.formats) {
4914 // Update the format we have on file so we can find it more quickly next time
4915 this.formats[format.name] = ret;
4916 }
4917 return ret;
4918 }
4919
4920 /**
4921 * Check if this color space is the same as another color space reference.
4922 * Allows proxying color space objects and comparing color spaces with ids.
4923 * @param {string | ColorSpace} space ColorSpace object or id to compare to
4924 * @returns {boolean}
4925 */
4926 equals(space) {
4927 if (!space) {
4928 return false;
4929 }
4930 return this === space || this.id === space || this.id === space.id;
4931 }
4932 to(space, coords) {
4933 if (arguments.length === 1) {
4934 const color = getColor(space);
4935 [space, coords] = [color.space, color.coords];
4936 }
4937 space = ColorSpace.get(space);
4938 if (this.equals(space)) {
4939 // Same space, no change needed
4940 return coords;
4941 }
4942
4943 // Convert NaN to 0, which seems to be valid in every coordinate of every color space
4944 coords = coords.map(c => isNone(c) ? 0 : c);
4945
4946 // Find connection space = lowest common ancestor in the base tree
4947 let myPath = this.path;
4948 let otherPath = space.path;
4949 let connectionSpace, connectionSpaceIndex;
4950 for (let i = 0; i < myPath.length; i++) {
4951 if (myPath[i].equals(otherPath[i])) {
4952 connectionSpace = myPath[i];
4953 connectionSpaceIndex = i;
4954 } else {
4955 break;
4956 }
4957 }
4958 if (!connectionSpace) {
4959 // This should never happen
4960 throw new Error(`Cannot convert between color spaces ${this} and ${space}: no connection space was found`);
4961 }
4962
4963 // Go up from current space to connection space
4964 for (let i = myPath.length - 1; i > connectionSpaceIndex; i--) {
4965 coords = myPath[i].toBase(coords);
4966 }
4967
4968 // Go down from connection space to target space
4969 for (let i = connectionSpaceIndex + 1; i < otherPath.length; i++) {
4970 coords = otherPath[i].fromBase(coords);
4971 }
4972 return coords;
4973 }
4974 from(space, coords) {
4975 if (arguments.length === 1) {
4976 const color = getColor(space);
4977 [space, coords] = [color.space, color.coords];
4978 }
4979 space = ColorSpace.get(space);
4980 return space.to(this, coords);
4981 }
4982 toString() {
4983 return `${this.name} (${this.id})`;
4984 }
4985 getMinCoords() {
4986 let ret = [];
4987 for (let id in this.coords) {
4988 var _range$min;
4989 let meta = this.coords[id];
4990 let range = meta.range || meta.refRange;
4991 ret.push((_range$min = range === null || range === void 0 ? void 0 : range.min) !== null && _range$min !== void 0 ? _range$min : 0);
4992 }
4993 return ret;
4994 }
4995 static registry = {};
4996
4997 // Returns array of unique color spaces
4998 static get all() {
4999 return [...new Set(Object.values(ColorSpace.registry))];
5000 }
5001 static register(id, space) {
5002 if (arguments.length === 1) {
5003 space = arguments[0];
5004 id = space.id;
5005 }
5006 space = this.get(space);
5007 if (this.registry[id] && this.registry[id] !== space) {
5008 throw new Error(`Duplicate color space registration: '${id}'`);
5009 }
5010 this.registry[id] = space;
5011
5012 // Register aliases when called without an explicit ID.
5013 if (arguments.length === 1 && space.aliases) {
5014 for (let alias of space.aliases) {
5015 this.register(alias, space);
5016 }
5017 }
5018 return space;
5019 }
5020
5021 /**
5022 * Lookup ColorSpace object by name
5023 * @param {ColorSpace | string} name
5024 */
5025 static get(space, ...alternatives) {
5026 if (!space || isInstance(space, this)) {
5027 return space;
5028 }
5029 let argType = type(space);
5030 if (argType === "string") {
5031 // It's a color space id
5032 let ret = ColorSpace.registry[space.toLowerCase()];
5033 if (!ret) {
5034 throw new TypeError(`No color space found with id = "${space}"`);
5035 }
5036 return ret;
5037 }
5038 if (alternatives.length) {
5039 return ColorSpace.get(...alternatives);
5040 }
5041 throw new TypeError(`${space} is not a valid color space`);
5042 }
5043
5044 /**
5045 * Look up all color spaces for a format that matches certain criteria
5046 * @param {object | string} filters
5047 * @param {Array<ColorSpace>} [spaces=ColorSpace.all]
5048 * @returns {Format | null}
5049 */
5050 static findFormat(filters, spaces = ColorSpace.all) {
5051 if (!filters) {
5052 return null;
5053 }
5054 if (typeof filters === "string") {
5055 filters = {
5056 name: filters
5057 };
5058 }
5059 for (let space of spaces) {
5060 for (let [name, format] of Object.entries(space.formats)) {
5061 var _format$name, _format$type;
5062 (_format$name = format.name) !== null && _format$name !== void 0 ? _format$name : format.name = name;
5063 (_format$type = format.type) !== null && _format$type !== void 0 ? _format$type : format.type = "function";
5064 let matches = (!filters.name || format.name === filters.name) && (!filters.type || format.type === filters.type);
5065 if (filters.id) {
5066 let ids = format.ids || [format.id];
5067 let filterIds = Array.isArray(filters.id) ? filters.id : [filters.id];
5068 matches && (matches = filterIds.some(id => ids.includes(id)));
5069 }
5070 if (matches) {
5071 let ret = Format.get(format, space);
5072 if (ret !== format) {
5073 space.formats[format.name] = ret;
5074 }
5075 return ret;
5076 }
5077 }
5078 }
5079 return null;
5080 }
5081
5082 /**
5083 * Get metadata about a coordinate of a color space
5084 *
5085 * @static
5086 * @param {Array | string} ref
5087 * @param {ColorSpace | string} [workingSpace]
5088 * @return {Object}
5089 */
5090 static resolveCoord(ref, workingSpace) {
5091 let coordType = type(ref);
5092 let space, coord;
5093 if (coordType === "string") {
5094 if (ref.includes(".")) {
5095 // Absolute coordinate
5096 [space, coord] = ref.split(".");
5097 } else {
5098 // Relative coordinate
5099 [space, coord] = [, ref];
5100 }
5101 } else if (Array.isArray(ref)) {
5102 [space, coord] = ref;
5103 } else {
5104 // Object
5105 space = ref.space;
5106 coord = ref.coordId;
5107 }
5108 space = ColorSpace.get(space);
5109 if (!space) {
5110 space = workingSpace;
5111 }
5112 if (!space) {
5113 throw new TypeError(`Cannot resolve coordinate reference ${ref}: No color space specified and relative references are not allowed here`);
5114 }
5115 coordType = type(coord);
5116 if (coordType === "number" || coordType === "string" && coord >= 0) {
5117 // Resolve numerical coord
5118 let meta = Object.entries(space.coords)[coord];
5119 if (meta) {
5120 return {
5121 space,
5122 id: meta[0],
5123 index: coord,
5124 ...meta[1]
5125 };
5126 }
5127 }
5128 space = ColorSpace.get(space);
5129 let normalizedCoord = coord.toLowerCase();
5130 let i = 0;
5131 for (let id in space.coords) {
5132 var _meta$name;
5133 let meta = space.coords[id];
5134 if (id.toLowerCase() === normalizedCoord || ((_meta$name = meta.name) === null || _meta$name === void 0 ? void 0 : _meta$name.toLowerCase()) === normalizedCoord) {
5135 return {
5136 space,
5137 id,
5138 index: i,
5139 ...meta
5140 };
5141 }
5142 i++;
5143 }
5144 throw new TypeError(`No "${coord}" coordinate found in ${space.name}. Its coordinates are: ${Object.keys(space.coords).join(", ")}`);
5145 }
5146 static DEFAULT_FORMAT = {
5147 type: "functions",
5148 name: "color"
5149 };
5150 }
5151 function getPath(space) {
5152 let ret = [space];
5153 for (let s = space; s = s.base;) {
5154 ret.push(s);
5155 }
5156 return ret;
5157 }
5158
5159 var XYZ_D65 = new ColorSpace({
5160 id: "xyz-d65",
5161 name: "XYZ D65",
5162 coords: {
5163 x: {
5164 refRange: [0, 1],
5165 name: "X"
5166 },
5167 y: {
5168 refRange: [0, 1],
5169 name: "Y"
5170 },
5171 z: {
5172 refRange: [0, 1],
5173 name: "Z"
5174 }
5175 },
5176 white: "D65",
5177 formats: {
5178 color: {
5179 ids: ["xyz-d65", "xyz"]
5180 }
5181 },
5182 aliases: ["xyz"]
5183 });
5184
5185 // Type re-exports
5186 /** @typedef {import("./types.js").RGBOptions} RGBOptions */
5187
5188 /** Convenience class for RGB color spaces */
5189 class RGBColorSpace extends ColorSpace {
5190 /**
5191 * Creates a new RGB ColorSpace.
5192 * If coords are not specified, they will use the default RGB coords.
5193 * Instead of `fromBase()` and `toBase()` functions,
5194 * you can specify to/from XYZ matrices and have `toBase()` and `fromBase()` automatically generated.
5195 * @param {RGBOptions} options
5196 */
5197 constructor(options) {
5198 var _options$referred;
5199 if (!options.coords) {
5200 options.coords = {
5201 r: {
5202 range: [0, 1],
5203 name: "Red"
5204 },
5205 g: {
5206 range: [0, 1],
5207 name: "Green"
5208 },
5209 b: {
5210 range: [0, 1],
5211 name: "Blue"
5212 }
5213 };
5214 }
5215 if (!options.base) {
5216 options.base = XYZ_D65;
5217 }
5218 if (options.toXYZ_M && options.fromXYZ_M) {
5219 var _options$toBase, _options$fromBase;
5220 (_options$toBase = options.toBase) !== null && _options$toBase !== void 0 ? _options$toBase : options.toBase = rgb => {
5221 let xyz = multiply_v3_m3x3(rgb, options.toXYZ_M);
5222 if (this.white !== this.base.white) {
5223 // Perform chromatic adaptation
5224 xyz = adapt$2(this.white, this.base.white, xyz);
5225 }
5226 return xyz;
5227 };
5228 (_options$fromBase = options.fromBase) !== null && _options$fromBase !== void 0 ? _options$fromBase : options.fromBase = xyz => {
5229 xyz = adapt$2(this.base.white, this.white, xyz);
5230 return multiply_v3_m3x3(xyz, options.fromXYZ_M);
5231 };
5232 }
5233 (_options$referred = options.referred) !== null && _options$referred !== void 0 ? _options$referred : options.referred = "display";
5234 super(options);
5235 }
5236 }
5237
5238 /** @import { ColorTypes, PlainColorObject } from "./types.js" */
5239
5240 // Type re-exports
5241 /** @typedef {import("./types.js").TryColorOptions} TryColorOptions */
5242
5243 /**
5244 * Resolves a color reference (object or string) to a plain color object, or `null` if resolution fails.
5245 * Can resolve more complex CSS colors (e.g. relative colors, `calc()`, CSS variables, `color-mix()`, etc.) through the DOM.
5246 *
5247 * @overload
5248 * @param {ColorTypes} color
5249 * @param {TryColorOptions} [options]
5250 * @returns {PlainColorObject | null}
5251 */
5252 /**
5253 * @overload
5254 * @param {ColorTypes[]} color
5255 * @param {TryColorOptions} [options]
5256 * @returns {(PlainColorObject | null)[]}
5257 */
5258 function tryColor(color, options = {}) {
5259 if (Array.isArray(color)) {
5260 return color.map(c => tryColor(c, options));
5261 }
5262 let {
5263 cssProperty = "background-color",
5264 element,
5265 ...getColorOptions
5266 } = options;
5267 let error = null;
5268 try {
5269 return getColor(color, getColorOptions);
5270 } catch (e) {
5271 error = e;
5272 }
5273 let {
5274 CSS,
5275 getComputedStyle
5276 } = globalThis;
5277 if (isString(color) && element && CSS && getComputedStyle) {
5278 // Try resolving the color using the DOM, if supported in CSS
5279 if (CSS.supports(cssProperty, color)) {
5280 let previousValue = element.style[cssProperty];
5281 if (color !== previousValue) {
5282 element.style[cssProperty] = color;
5283 }
5284 let computedColor = getComputedStyle(element).getPropertyValue(cssProperty);
5285 if (color !== previousValue) {
5286 element.style[cssProperty] = previousValue;
5287 }
5288 if (computedColor !== color) {
5289 // getComputedStyle() changed the color, try again
5290 try {
5291 return getColor(computedColor, getColorOptions);
5292 } catch (e) {
5293 error = e;
5294 }
5295 } else {
5296 // Still not resolved
5297 error = {
5298 message: "Color value is a valid CSS color, but it could not be resolved :("
5299 };
5300 }
5301 }
5302 }
5303
5304 // If we're here, we failed to resolve the color
5305 if (options.errorMeta) {
5306 options.errorMeta.error = error;
5307 }
5308 return null;
5309 }
5310
5311 /** @import { ColorTypes, Coords } from "./types.js" */
5312
5313 /**
5314 * Options for {@link getAll}
5315 * @typedef GetAllOptions
5316 * @property {string | ColorSpace | undefined} [space]
5317 * The color space to convert to. Defaults to the color's current space
5318 * @property {number | undefined} [precision]
5319 * The number of significant digits to round the coordinates to
5320 */
5321
5322 /**
5323 * Get the coordinates of a color in any color space
5324 * @overload
5325 * @param {ColorTypes} color
5326 * @param {string | ColorSpace} [options=color.space] The color space to convert to. Defaults to the color's current space
5327 * @returns {Coords} The color coordinates in the given color space
5328 */
5329 /**
5330 * @overload
5331 * @param {ColorTypes} color
5332 * @param {GetAllOptions} [options]
5333 * @returns {Coords} The color coordinates in the given color space
5334 */
5335 function getAll(color, options) {
5336 color = getColor(color);
5337 let space = ColorSpace.get(options, options === null || options === void 0 ? void 0 : options.space);
5338 let precision = options === null || options === void 0 ? void 0 : options.precision;
5339 let coords;
5340 if (!space || color.space.equals(space)) {
5341 // No conversion needed
5342 coords = color.coords.slice();
5343 } else {
5344 coords = space.from(color);
5345 }
5346 return precision === undefined ? coords : coords.map(coord => toPrecision(coord, precision));
5347 }
5348
5349 /** @import { ColorTypes, Ref } from "./types.js" */
5350
5351 /**
5352 * @param {ColorTypes} color
5353 * @param {Ref} prop
5354 * @returns {number}
5355 */
5356 function get(color, prop) {
5357 color = getColor(color);
5358 if (prop === "alpha") {
5359 var _color$alpha;
5360 return (_color$alpha = color.alpha) !== null && _color$alpha !== void 0 ? _color$alpha : 1;
5361 }
5362 let {
5363 space,
5364 index
5365 } = ColorSpace.resolveCoord(prop, color.space);
5366 let coords = getAll(color, space);
5367 return coords[index];
5368 }
5369
5370 /** @import { ColorTypes, Coords, PlainColorObject } from "./types.js" */
5371
5372 /**
5373 * Set all coordinates of a color at once, in its own color space or another.
5374 * Modifies the color in place.
5375 * @overload
5376 * @param {ColorTypes} color
5377 * @param {Coords} coords Array of coordinates
5378 * @param {number} [alpha]
5379 * @returns {PlainColorObject}
5380 */
5381 /**
5382 * @overload
5383 * @param {ColorTypes} color
5384 * @param {string | ColorSpace} space The color space of the provided coordinates.
5385 * @param {Coords} coords Array of coordinates
5386 * @param {number} [alpha]
5387 * @returns {PlainColorObject}
5388 */
5389 function setAll(color, space, coords, alpha) {
5390 color = getColor(color);
5391 if (Array.isArray(space)) {
5392 // Space is omitted
5393 [space, coords, alpha] = [color.space, space, coords];
5394 }
5395 space = ColorSpace.get(space); // Make sure we have a ColorSpace object
5396 color.coords = space === color.space ? coords.slice() : space.to(color.space, coords);
5397 if (alpha !== undefined) {
5398 color.alpha = alpha;
5399 }
5400 return color;
5401 }
5402
5403 /** @type {"color"} */
5404 setAll.returns = "color";
5405
5406 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
5407
5408 /**
5409 * Set properties and return current instance
5410 * @overload
5411 * @param {ColorTypes} color
5412 * @param {Ref} prop
5413 * @param {number | ((coord: number) => number)} value
5414 * @returns {PlainColorObject}
5415 */
5416 /**
5417 * @overload
5418 * @param {ColorTypes} color
5419 * @param {Record<string, number | ((coord: number) => number)>} props
5420 * @returns {PlainColorObject}
5421 */
5422 function set(color, prop, value) {
5423 color = getColor(color);
5424 if (arguments.length === 2 && type(arguments[1]) === "object") {
5425 // Argument is an object literal
5426 let object = arguments[1];
5427 for (let p in object) {
5428 set(color, p, object[p]);
5429 }
5430 } else {
5431 if (typeof value === "function") {
5432 value = value(get(color, prop));
5433 }
5434 if (prop === "alpha") {
5435 color.alpha = value;
5436 } else {
5437 let {
5438 space,
5439 index
5440 } = ColorSpace.resolveCoord(prop, color.space);
5441 let coords = getAll(color, space);
5442 coords[index] = value;
5443 setAll(color, space, coords);
5444 }
5445 }
5446 return color;
5447 }
5448
5449 /** @type {"color"} */
5450 set.returns = "color";
5451
5452 var XYZ_D50 = new ColorSpace({
5453 id: "xyz-d50",
5454 name: "XYZ D50",
5455 white: "D50",
5456 base: XYZ_D65,
5457 fromBase: coords => adapt$2(XYZ_D65.white, "D50", coords),
5458 toBase: coords => adapt$2("D50", XYZ_D65.white, coords)
5459 });
5460
5461 // κ * ε = 2^3 = 8
5462 const ε$6 = 216 / 24389; // 6^3/29^3 == (24/116)^3
5463 const ε3$1 = 24 / 116;
5464 const κ$4 = 24389 / 27; // 29^3/3^3
5465
5466 let white$4 = WHITES.D50;
5467 var lab = new ColorSpace({
5468 id: "lab",
5469 name: "Lab",
5470 coords: {
5471 l: {
5472 refRange: [0, 100],
5473 name: "Lightness"
5474 },
5475 a: {
5476 refRange: [-125, 125]
5477 },
5478 b: {
5479 refRange: [-125, 125]
5480 }
5481 },
5482 // Assuming XYZ is relative to D50, convert to CIE Lab
5483 // from CIE standard, which now defines these as a rational fraction
5484 white: white$4,
5485 base: XYZ_D50,
5486 // Convert D50-adapted XYX to Lab
5487 // CIE 15.3:2004 section 8.2.1.1
5488 fromBase(XYZ) {
5489 // XYZ scaled relative to reference white
5490 let xyz = XYZ.map((value, i) => value / white$4[i]);
5491 let f = xyz.map(value => value > ε$6 ? Math.cbrt(value) : (κ$4 * value + 16) / 116);
5492 let L = 116 * f[1] - 16;
5493 let a = 500 * (f[0] - f[1]);
5494 let b = 200 * (f[1] - f[2]);
5495 return [L, a, b];
5496 },
5497 // Convert Lab to D50-adapted XYZ
5498 // Same result as CIE 15.3:2004 Appendix D although the derivation is different
5499 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
5500 toBase(Lab) {
5501 // compute f, starting with the luminance-related term
5502 let [L, a, b] = Lab;
5503 let f = [];
5504 f[1] = (L + 16) / 116;
5505 f[0] = a / 500 + f[1];
5506 f[2] = f[1] - b / 200;
5507
5508 // compute xyz
5509 // prettier-ignore
5510 let xyz = [f[0] > ε3$1 ? Math.pow(f[0], 3) : (116 * f[0] - 16) / κ$4, Lab[0] > 8 ? Math.pow((Lab[0] + 16) / 116, 3) : Lab[0] / κ$4, f[2] > ε3$1 ? Math.pow(f[2], 3) : (116 * f[2] - 16) / κ$4];
5511
5512 // Compute XYZ by scaling xyz by reference white
5513 return xyz.map((value, i) => value * white$4[i]);
5514 },
5515 formats: {
5516 lab: {
5517 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
5518 }
5519 }
5520 });
5521
5522 /**
5523 * Constrain an angle to 360 degrees
5524 * @param {number} angle
5525 * @returns {number}
5526 */
5527 function constrain(angle) {
5528 if (typeof angle !== "number") {
5529 return angle;
5530 }
5531 return (angle % 360 + 360) % 360;
5532 }
5533
5534 /**
5535 * @param {"raw" | "increasing" | "decreasing" | "longer" | "shorter"} arc
5536 * @param {[number, number]} angles
5537 * @returns {[number, number]}
5538 */
5539 function adjust(arc, angles) {
5540 let [a1, a2] = angles;
5541 let none1 = isNone(a1);
5542 let none2 = isNone(a2);
5543 if (none1 && none2) {
5544 return [a1, a2];
5545 } else if (none1) {
5546 a1 = a2;
5547 } else if (none2) {
5548 a2 = a1;
5549 }
5550 if (arc === "raw") {
5551 return angles;
5552 }
5553 a1 = constrain(a1);
5554 a2 = constrain(a2);
5555 let angleDiff = a2 - a1;
5556 if (arc === "increasing") {
5557 if (angleDiff < 0) {
5558 a2 += 360;
5559 }
5560 } else if (arc === "decreasing") {
5561 if (angleDiff > 0) {
5562 a1 += 360;
5563 }
5564 } else if (arc === "longer") {
5565 if (-180 < angleDiff && angleDiff < 180) {
5566 if (angleDiff > 0) {
5567 a1 += 360;
5568 } else {
5569 a2 += 360;
5570 }
5571 }
5572 } else if (arc === "shorter") {
5573 if (angleDiff > 180) {
5574 a1 += 360;
5575 } else if (angleDiff < -180) {
5576 a2 += 360;
5577 }
5578 }
5579 return [a1, a2];
5580 }
5581
5582 var lch = new ColorSpace({
5583 id: "lch",
5584 name: "LCH",
5585 coords: {
5586 l: {
5587 refRange: [0, 100],
5588 name: "Lightness"
5589 },
5590 c: {
5591 refRange: [0, 150],
5592 name: "Chroma"
5593 },
5594 h: {
5595 refRange: [0, 360],
5596 type: "angle",
5597 name: "Hue"
5598 }
5599 },
5600 base: lab,
5601 fromBase(Lab) {
5602 // These methods are used for other polar forms as well, so we can't hardcode the ε
5603 if (this.ε === undefined) {
5604 // @ts-expect-error Property 'coords' does not exist on type 'string | ColorSpace'
5605 let range = Object.values(this.base.coords)[1].refRange;
5606 let extent = range[1] - range[0];
5607 this.ε = extent / 100000;
5608 }
5609
5610 // Convert to polar form
5611 let [L, a, b] = Lab;
5612 let isAchromatic = Math.abs(a) < this.ε && Math.abs(b) < this.ε;
5613 let h = isAchromatic ? null : constrain(Math.atan2(b, a) * 180 / Math.PI);
5614 let C = isAchromatic ? 0 : Math.sqrt(a ** 2 + b ** 2);
5615 return [L, C, h];
5616 },
5617 toBase(lch) {
5618 // Convert from polar form
5619 let [L, C, h] = lch;
5620 let a = null,
5621 b = null;
5622 if (!isNone(h)) {
5623 C = C < 0 ? 0 : C; // Clamp negative Chroma
5624 a = C * Math.cos(h * Math.PI / 180);
5625 b = C * Math.sin(h * Math.PI / 180);
5626 }
5627 return [L, a, b];
5628 },
5629 formats: {
5630 lch: {
5631 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
5632 }
5633 }
5634 });
5635
5636 // deltaE2000 is a statistically significant improvement
5637 // and is recommended by the CIE and Idealliance
5638 // especially for color differences less than 10 deltaE76
5639 // but is wicked complicated
5640 // and many implementations have small errors!
5641 // DeltaE2000 is also discontinuous; in case this
5642 // matters to you, use deltaECMC instead.
5643
5644 const Gfactor = 25 ** 7;
5645 const π$1 = Math.PI;
5646 const r2d = 180 / π$1;
5647 const d2r$1 = π$1 / 180;
5648 function pow7(x) {
5649 // Faster than x ** 7 or Math.pow(x, 7)
5650
5651 const x2 = x * x;
5652 const x7 = x2 * x2 * x2 * x;
5653 return x7;
5654 }
5655
5656 /**
5657 * @param {import("../types.js").ColorTypes} color
5658 * @param {import("../types.js").ColorTypes} sample
5659 * @param {{ kL?: number | undefined; kC?: number | undefined; kH?: number | undefined }} options
5660 * @returns {number}
5661 */
5662 function deltaE2000 (color, sample, {
5663 kL = 1,
5664 kC = 1,
5665 kH = 1
5666 } = {}) {
5667 [color, sample] = getColor([color, sample]);
5668
5669 // Given this color as the reference
5670 // and the function parameter as the sample,
5671 // calculate deltaE 2000.
5672
5673 // This implementation assumes the parametric
5674 // weighting factors kL, kC and kH
5675 // for the influence of viewing conditions
5676 // are all 1, as sadly seems typical.
5677 // kL should be increased for lightness texture or noise
5678 // and kC increased for chroma noise
5679
5680 let [L1, a1, b1] = lab.from(color);
5681 let C1 = lch.from(lab, [L1, a1, b1])[1];
5682 let [L2, a2, b2] = lab.from(sample);
5683 let C2 = lch.from(lab, [L2, a2, b2])[1];
5684
5685 // Check for negative Chroma,
5686 // which might happen through
5687 // direct user input of LCH values
5688
5689 if (C1 < 0) {
5690 C1 = 0;
5691 }
5692 if (C2 < 0) {
5693 C2 = 0;
5694 }
5695 let Cbar = (C1 + C2) / 2; // mean Chroma
5696
5697 // calculate a-axis asymmetry factor from mean Chroma
5698 // this turns JND ellipses for near-neutral colors back into circles
5699 let C7 = pow7(Cbar);
5700 let G = 0.5 * (1 - Math.sqrt(C7 / (C7 + Gfactor)));
5701
5702 // scale a axes by asymmetry factor
5703 // this by the way is why there is no Lab2000 colorspace
5704 let adash1 = (1 + G) * a1;
5705 let adash2 = (1 + G) * a2;
5706
5707 // calculate new Chroma from scaled a and original b axes
5708 let Cdash1 = Math.sqrt(adash1 ** 2 + b1 ** 2);
5709 let Cdash2 = Math.sqrt(adash2 ** 2 + b2 ** 2);
5710
5711 // calculate new hues, with zero hue for true neutrals
5712 // and in degrees, not radians
5713
5714 let h1 = adash1 === 0 && b1 === 0 ? 0 : Math.atan2(b1, adash1);
5715 let h2 = adash2 === 0 && b2 === 0 ? 0 : Math.atan2(b2, adash2);
5716 if (h1 < 0) {
5717 h1 += 2 * π$1;
5718 }
5719 if (h2 < 0) {
5720 h2 += 2 * π$1;
5721 }
5722 h1 *= r2d;
5723 h2 *= r2d;
5724
5725 // Lightness and Chroma differences; sign matters
5726 let ΔL = L2 - L1;
5727 let ΔC = Cdash2 - Cdash1;
5728
5729 // Hue difference, getting the sign correct
5730 let hdiff = h2 - h1;
5731 let hsum = h1 + h2;
5732 let habs = Math.abs(hdiff);
5733 let Δh;
5734 if (Cdash1 * Cdash2 === 0) {
5735 Δh = 0;
5736 } else if (habs <= 180) {
5737 Δh = hdiff;
5738 } else if (hdiff > 180) {
5739 Δh = hdiff - 360;
5740 } else if (hdiff < -180) {
5741 Δh = hdiff + 360;
5742 } else {
5743 defaults.warn("the unthinkable has happened");
5744 }
5745
5746 // weighted Hue difference, more for larger Chroma
5747 let ΔH = 2 * Math.sqrt(Cdash2 * Cdash1) * Math.sin(Δh * d2r$1 / 2);
5748
5749 // calculate mean Lightness and Chroma
5750 let Ldash = (L1 + L2) / 2;
5751 let Cdash = (Cdash1 + Cdash2) / 2;
5752 let Cdash7 = pow7(Cdash);
5753
5754 // Compensate for non-linearity in the blue region of Lab.
5755 // Four possibilities for hue weighting factor,
5756 // depending on the angles, to get the correct sign
5757 let hdash;
5758 if (Cdash1 * Cdash2 === 0) {
5759 hdash = hsum; // which should be zero
5760 } else if (habs <= 180) {
5761 hdash = hsum / 2;
5762 } else if (hsum < 360) {
5763 hdash = (hsum + 360) / 2;
5764 } else {
5765 hdash = (hsum - 360) / 2;
5766 }
5767
5768 // positional corrections to the lack of uniformity of CIELAB
5769 // These are all trying to make JND ellipsoids more like spheres
5770
5771 // SL Lightness crispening factor
5772 // a background with L=50 is assumed
5773 let lsq = (Ldash - 50) ** 2;
5774 let SL = 1 + 0.015 * lsq / Math.sqrt(20 + lsq);
5775
5776 // SC Chroma factor, similar to those in CMC and deltaE 94 formulae
5777 let SC = 1 + 0.045 * Cdash;
5778
5779 // Cross term T for blue non-linearity
5780 let T = 1;
5781 T -= 0.17 * Math.cos((hdash - 30) * d2r$1);
5782 T += 0.24 * Math.cos(2 * hdash * d2r$1);
5783 T += 0.32 * Math.cos((3 * hdash + 6) * d2r$1);
5784 T -= 0.2 * Math.cos((4 * hdash - 63) * d2r$1);
5785
5786 // SH Hue factor depends on Chroma,
5787 // as well as adjusted hue angle like deltaE94.
5788 let SH = 1 + 0.015 * Cdash * T;
5789
5790 // RT Hue rotation term compensates for rotation of JND ellipses
5791 // and Munsell constant hue lines
5792 // in the medium-high Chroma blue region
5793 // (Hue 225 to 315)
5794 let Δθ = 30 * Math.exp(-1 * ((hdash - 275) / 25) ** 2);
5795 let RC = 2 * Math.sqrt(Cdash7 / (Cdash7 + Gfactor));
5796 let RT = -1 * Math.sin(2 * Δθ * d2r$1) * RC;
5797
5798 // Finally calculate the deltaE, term by term as root sume of squares
5799 let dE = (ΔL / (kL * SL)) ** 2;
5800 dE += (ΔC / (kC * SC)) ** 2;
5801 dE += (ΔH / (kH * SH)) ** 2;
5802 dE += RT * (ΔC / (kC * SC)) * (ΔH / (kH * SH));
5803 return Math.sqrt(dE);
5804 // Yay!!!
5805 }
5806
5807 /** @import { Matrix3x3 } from "../types.js" */
5808
5809 // Recalculated for consistent reference white
5810 // see https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-943521484
5811 /** @type {Matrix3x3} */
5812 // prettier-ignore
5813 const XYZtoLMS_M$1 = [[0.8190224379967030, 0.3619062600528904, -0.1288737815209879], [0.0329836539323885, 0.9292868615863434, 0.0361446663506424], [0.0481771893596242, 0.2642395317527308, 0.6335478284694309]];
5814 // inverse of XYZtoLMS_M
5815 /** @type {Matrix3x3} */
5816 // prettier-ignore
5817 const LMStoXYZ_M$1 = [[1.2268798758459243, -0.5578149944602171, 0.2813910456659647], [-0.0405757452148008, 1.1122868032803170, -0.0717110580655164], [-0.0763729366746601, -0.4214933324022432, 1.5869240198367816]];
5818 /** @type {Matrix3x3} */
5819 // prettier-ignore
5820 const LMStoLab_M = [[0.2104542683093140, 0.7936177747023054, -0.0040720430116193], [1.9779985324311684, -2.4285922420485799, 0.4505937096174110], [0.0259040424655478, 0.7827717124575296, -0.8086757549230774]];
5821 // LMStoIab_M inverted
5822 /** @type {Matrix3x3} */
5823 // prettier-ignore
5824 const LabtoLMS_M = [[1.0000000000000000, 0.3963377773761749, 0.2158037573099136], [1.0000000000000000, -0.1055613458156586, -0.0638541728258133], [1.0000000000000000, -0.0894841775298119, -1.2914855480194092]];
5825 var Oklab = new ColorSpace({
5826 id: "oklab",
5827 name: "Oklab",
5828 coords: {
5829 l: {
5830 refRange: [0, 1],
5831 name: "Lightness"
5832 },
5833 a: {
5834 refRange: [-0.4, 0.4]
5835 },
5836 b: {
5837 refRange: [-0.4, 0.4]
5838 }
5839 },
5840 // Note that XYZ is relative to D65
5841 white: "D65",
5842 base: XYZ_D65,
5843 fromBase(XYZ) {
5844 // move to LMS cone domain
5845 let LMS = multiply_v3_m3x3(XYZ, XYZtoLMS_M$1);
5846
5847 // non-linearity
5848 LMS[0] = Math.cbrt(LMS[0]);
5849 LMS[1] = Math.cbrt(LMS[1]);
5850 LMS[2] = Math.cbrt(LMS[2]);
5851 return multiply_v3_m3x3(LMS, LMStoLab_M, LMS);
5852 },
5853 toBase(OKLab) {
5854 // move to LMS cone domain
5855 let LMSg = multiply_v3_m3x3(OKLab, LabtoLMS_M);
5856
5857 // restore linearity
5858 LMSg[0] = LMSg[0] ** 3;
5859 LMSg[1] = LMSg[1] ** 3;
5860 LMSg[2] = LMSg[2] ** 3;
5861 return multiply_v3_m3x3(LMSg, LMStoXYZ_M$1, LMSg);
5862 },
5863 formats: {
5864 oklab: {
5865 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
5866 }
5867 }
5868 });
5869
5870 /**
5871 * More accurate color-difference formulae
5872 * than the simple 1976 Euclidean distance in CIE Lab
5873 * @param {import("../types.js").ColorTypes} color
5874 * @param {import("../types.js").ColorTypes} sample
5875 * @returns {number}
5876 */
5877 function deltaEOK (color, sample) {
5878 [color, sample] = getColor([color, sample]);
5879
5880 // Given this color as the reference
5881 // and a sample,
5882 // calculate deltaEOK, term by term as root sum of squares
5883 let [L1, a1, b1] = Oklab.from(color);
5884 let [L2, a2, b2] = Oklab.from(sample);
5885 let ΔL = L1 - L2;
5886 let Δa = a1 - a2;
5887 let Δb = b1 - b2;
5888 return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2);
5889 }
5890
5891 /** @import { ColorTypes } from "./types.js" */
5892
5893 const ε$5 = 0.000075;
5894
5895 /**
5896 * Check if a color is in gamut of either its own or another color space
5897 * @param {ColorTypes} color
5898 * @param {string | ColorSpace} [space]
5899 * @param {{ epsilon?: number | undefined }} [param2]
5900 * @returns {boolean}
5901 */
5902 function inGamut(color, space, {
5903 epsilon = ε$5
5904 } = {}) {
5905 color = getColor(color);
5906 if (!space) {
5907 space = color.space;
5908 }
5909 space = ColorSpace.get(space);
5910 let coords = color.coords;
5911 if (space !== color.space) {
5912 coords = space.from(color);
5913 }
5914 return space.inGamut(coords, {
5915 epsilon
5916 });
5917 }
5918
5919 var OKLCH = new ColorSpace({
5920 id: "oklch",
5921 name: "OkLCh",
5922 coords: {
5923 l: {
5924 refRange: [0, 1],
5925 name: "Lightness"
5926 },
5927 c: {
5928 refRange: [0, 0.4],
5929 name: "Chroma"
5930 },
5931 h: {
5932 refRange: [0, 360],
5933 type: "angle",
5934 name: "Hue"
5935 }
5936 },
5937 white: "D65",
5938 base: Oklab,
5939 fromBase: lch.fromBase,
5940 toBase: lch.toBase,
5941 formats: {
5942 oklch: {
5943 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
5944 }
5945 }
5946 });
5947
5948 /** @import { Coords, PlainColorObject } from "./types.js" */
5949
5950 /**
5951 * @param {PlainColorObject} color
5952 * @returns {PlainColorObject}
5953 */
5954 function clone(color) {
5955 return {
5956 space: color.space,
5957 coords: (/** @type {Coords} */color.coords.slice()),
5958 alpha: color.alpha
5959 };
5960 }
5961
5962 var esnext_iterator_reduce = {};
5963
5964 var es_iterator_reduce = {};
5965
5966 var hasRequiredEs_iterator_reduce;
5967
5968 function requireEs_iterator_reduce () {
5969 if (hasRequiredEs_iterator_reduce) return es_iterator_reduce;
5970 hasRequiredEs_iterator_reduce = 1;
5971 var $ = require_export();
5972 var iterate = requireIterate();
5973 var aCallable = requireACallable();
5974 var anObject = requireAnObject();
5975 var getIteratorDirect = requireGetIteratorDirect();
5976
5977 var $TypeError = TypeError;
5978
5979 // `Iterator.prototype.reduce` method
5980 // https://tc39.es/ecma262/#sec-iterator.prototype.reduce
5981 $({ target: 'Iterator', proto: true, real: true }, {
5982 reduce: function reduce(reducer /* , initialValue */) {
5983 anObject(this);
5984 aCallable(reducer);
5985 var record = getIteratorDirect(this);
5986 var noInitial = arguments.length < 2;
5987 var accumulator = noInitial ? undefined : arguments[1];
5988 var counter = 0;
5989 iterate(record, function (value) {
5990 if (noInitial) {
5991 noInitial = false;
5992 accumulator = value;
5993 } else {
5994 accumulator = reducer(accumulator, value, counter);
5995 }
5996 counter++;
5997 }, { IS_RECORD: true });
5998 if (noInitial) throw new $TypeError('Reduce of empty iterator with no initial value');
5999 return accumulator;
6000 }
6001 });
6002 return es_iterator_reduce;
6003 }
6004
6005 var hasRequiredEsnext_iterator_reduce;
6006
6007 function requireEsnext_iterator_reduce () {
6008 if (hasRequiredEsnext_iterator_reduce) return esnext_iterator_reduce;
6009 hasRequiredEsnext_iterator_reduce = 1;
6010 // TODO: Remove from `core-js@4`
6011 requireEs_iterator_reduce();
6012 return esnext_iterator_reduce;
6013 }
6014
6015 requireEsnext_iterator_reduce();
6016
6017 /** @import { ColorTypes } from "./types.js" */
6018
6019 /**
6020 * Euclidean distance of colors in an arbitrary color space
6021 * @param {ColorTypes} color1
6022 * @param {ColorTypes} color2
6023 * @param {string | ColorSpace} space
6024 * @returns {number}
6025 */
6026 function distance(color1, color2, space = "lab") {
6027 space = ColorSpace.get(space);
6028
6029 // Assume getColor() is called on color in space.from()
6030 let coords1 = space.from(color1);
6031 let coords2 = space.from(color2);
6032 return Math.sqrt(coords1.reduce((acc, c1, i) => {
6033 let c2 = coords2[i];
6034 if (isNone(c1) || isNone(c2)) {
6035 return acc;
6036 }
6037 return acc + (c2 - c1) ** 2;
6038 }, 0));
6039 }
6040
6041 /**
6042 * @param {import("../types.js").ColorTypes} color
6043 * @param {import("../types.js").ColorTypes} sample
6044 * @returns {number}
6045 */
6046 function deltaE76(color, sample) {
6047 // Assume getColor() is called in the distance function
6048 return distance(color, sample, "lab");
6049 }
6050
6051 // More accurate color-difference formulae
6052 // than the simple 1976 Euclidean distance in Lab
6053
6054 // CMC by the Color Measurement Committee of the
6055 // Bradford Society of Dyeists and Colorsts, 1994.
6056 // Uses LCH rather than Lab,
6057 // with different weights for L, C and H differences
6058 // A nice increase in accuracy for modest increase in complexity
6059 const π = Math.PI;
6060 const d2r = π / 180;
6061
6062 /**
6063 * @param {import("../types.js").ColorTypes} color
6064 * @param {import("../types.js").ColorTypes} sample
6065 * @param {{ l?: number | undefined; c?: number | undefined }} options
6066 * @returns {number}
6067 */
6068 function deltaECMC (color, sample, {
6069 l = 2,
6070 c = 1
6071 } = {}) {
6072 [color, sample] = getColor([color, sample]);
6073
6074 // Given this color as the reference
6075 // and a sample,
6076 // calculate deltaE CMC.
6077
6078 // This implementation assumes the parametric
6079 // weighting factors l:c are 2:1
6080 // which is typical for non-textile uses.
6081
6082 let [L1, a1, b1] = lab.from(color);
6083 let [, C1, H1] = lch.from(lab, [L1, a1, b1]);
6084 let [L2, a2, b2] = lab.from(sample);
6085 let C2 = lch.from(lab, [L2, a2, b2])[1];
6086
6087 // let [L1, a1, b1] = color.getAll(lab);
6088 // let C1 = color.get("lch.c");
6089 // let H1 = color.get("lch.h");
6090 // let [L2, a2, b2] = sample.getAll(lab);
6091 // let C2 = sample.get("lch.c");
6092
6093 // Check for negative Chroma,
6094 // which might happen through
6095 // direct user input of LCH values
6096
6097 if (C1 < 0) {
6098 C1 = 0;
6099 }
6100 if (C2 < 0) {
6101 C2 = 0;
6102 }
6103
6104 // we don't need H2 as ΔH is calculated from Δa, Δb and ΔC
6105
6106 // Lightness and Chroma differences
6107 // These are (color - sample), unlike deltaE2000
6108 let ΔL = L1 - L2;
6109 let ΔC = C1 - C2;
6110 let Δa = a1 - a2;
6111 let Δb = b1 - b2;
6112
6113 // weighted Hue difference, less for larger Chroma difference
6114
6115 let H2 = Δa ** 2 + Δb ** 2 - ΔC ** 2;
6116 // due to roundoff error it is possible that, for zero a and b,
6117 // ΔC > Δa + Δb is 0, resulting in attempting
6118 // to take the square root of a negative number
6119
6120 // trying instead the equation from Industrial Color Physics
6121 // By Georg A. Klein
6122
6123 // let ΔH = ((a1 * b2) - (a2 * b1)) / Math.sqrt(0.5 * ((C2 * C1) + (a2 * a1) + (b2 * b1)));
6124 // console.log({ΔH});
6125 // This gives the same result to 12 decimal places
6126 // except it sometimes NaNs when trying to root a negative number
6127
6128 // let ΔH = Math.sqrt(H2); we never actually use the root, it gets squared again!!
6129
6130 // positional corrections to the lack of uniformity of CIELAB
6131 // These are all trying to make JND ellipsoids more like spheres
6132
6133 // SL Lightness crispening factor, depends entirely on L1 not L2
6134 let SL = 0.511; // linear portion of the Y to L transfer function
6135 if (L1 >= 16) {
6136 // cubic portion
6137 SL = 0.040975 * L1 / (1 + 0.01765 * L1);
6138 }
6139
6140 // SC Chroma factor
6141 let SC = 0.0638 * C1 / (1 + 0.0131 * C1) + 0.638;
6142
6143 // Cross term T for blue non-linearity
6144 let T;
6145 if (isNone(H1)) {
6146 H1 = 0;
6147 }
6148 if (H1 >= 164 && H1 <= 345) {
6149 T = 0.56 + Math.abs(0.2 * Math.cos((H1 + 168) * d2r));
6150 } else {
6151 T = 0.36 + Math.abs(0.4 * Math.cos((H1 + 35) * d2r));
6152 }
6153 // console.log({T});
6154
6155 // SH Hue factor also depends on C1,
6156 let C4 = Math.pow(C1, 4);
6157 let F = Math.sqrt(C4 / (C4 + 1900));
6158 let SH = SC * (F * T + 1 - F);
6159
6160 // Finally calculate the deltaE, term by term as root sume of squares
6161 let dE = (ΔL / (l * SL)) ** 2;
6162 dE += (ΔC / (c * SC)) ** 2;
6163 dE += H2 / SH ** 2;
6164 // dE += (ΔH / SH) ** 2;
6165 return Math.sqrt(dE);
6166 // Yay!!!
6167 }
6168
6169 const Yw$1 = 203; // absolute luminance of media white
6170
6171 var XYZ_Abs_D65 = new ColorSpace({
6172 // Absolute CIE XYZ, with a D65 whitepoint,
6173 // as used in most HDR colorspaces as a starting point.
6174 // SDR spaces are converted per BT.2048
6175 // so that diffuse, media white is 203 cd/m²
6176 id: "xyz-abs-d65",
6177 cssId: "--xyz-abs-d65",
6178 name: "Absolute XYZ D65",
6179 coords: {
6180 x: {
6181 refRange: [0, 9504.7],
6182 name: "Xa"
6183 },
6184 y: {
6185 refRange: [0, 10000],
6186 name: "Ya"
6187 },
6188 z: {
6189 refRange: [0, 10888.3],
6190 name: "Za"
6191 }
6192 },
6193 base: XYZ_D65,
6194 fromBase(XYZ) {
6195 // Make XYZ absolute, not relative to media white
6196 // Maximum luminance in PQ is 10,000 cd/m²
6197 // Relative XYZ has Y=1 for media white
6198 return XYZ.map(v => v * Yw$1);
6199 },
6200 toBase(AbsXYZ) {
6201 // Convert to media-white relative XYZ
6202 return AbsXYZ.map(v => v / Yw$1);
6203 }
6204 });
6205
6206 /** @import { Matrix3x3, Vector3 } from "../types.js" */
6207
6208 const b$1 = 1.15;
6209 const g = 0.66;
6210 const n$1 = 2610 / 2 ** 14;
6211 const ninv$1 = 2 ** 14 / 2610;
6212 const c1$2 = 3424 / 2 ** 12;
6213 const c2$2 = 2413 / 2 ** 7;
6214 const c3$2 = 2392 / 2 ** 7;
6215 const p$1 = 1.7 * 2523 / 2 ** 5;
6216 const pinv = 2 ** 5 / (1.7 * 2523);
6217 const d = -0.56;
6218 const d0 = 1.6295499532821566e-11;
6219
6220 /** @type {Matrix3x3} */
6221 // prettier-ignore
6222 const XYZtoCone_M = [[0.41478972, 0.579999, 0.0146480], [-0.2015100, 1.120649, 0.0531008], [-0.0166008, 0.264800, 0.6684799]];
6223 // XYZtoCone_M inverted
6224 /** @type {Matrix3x3} */
6225 // prettier-ignore
6226 const ConetoXYZ_M = [[1.9242264357876067, -1.0047923125953657, 0.037651404030618], [0.35031676209499907, 0.7264811939316552, -0.06538442294808501], [-0.09098281098284752, -0.3127282905230739, 1.5227665613052603]];
6227 /** @type {Matrix3x3} */
6228 // prettier-ignore
6229 const ConetoIab_M = [[0.5, 0.5, 0], [3.524000, -4.066708, 0.542708], [0.199076, 1.096799, -1.295875]];
6230 // ConetoIab_M inverted
6231 /** @type {Matrix3x3} */
6232 // prettier-ignore
6233 const IabtoCone_M = [[1, 0.13860504327153927, 0.05804731615611883], [1, -0.1386050432715393, -0.058047316156118904], [1, -0.09601924202631895, -0.81189189605603900]];
6234 var Jzazbz = new ColorSpace({
6235 id: "jzazbz",
6236 name: "Jzazbz",
6237 coords: {
6238 jz: {
6239 refRange: [0, 1],
6240 name: "Jz"
6241 },
6242 az: {
6243 refRange: [-0.21, 0.21]
6244 },
6245 bz: {
6246 refRange: [-0.21, 0.21]
6247 }
6248 },
6249 base: XYZ_Abs_D65,
6250 fromBase(XYZ) {
6251 // First make XYZ absolute, not relative to media white
6252 // Maximum luminance in PQ is 10,000 cd/m²
6253 // Relative XYZ has Y=1 for media white
6254 // BT.2048 says media white Y=203 at PQ 58
6255
6256 let [Xa, Ya, Za] = XYZ;
6257
6258 // modify X and Y to minimize blue curvature
6259 let Xm = b$1 * Xa - (b$1 - 1) * Za;
6260 let Ym = g * Ya - (g - 1) * Xa;
6261
6262 // move to LMS cone domain
6263 let LMS = multiply_v3_m3x3([Xm, Ym, Za], XYZtoCone_M);
6264
6265 // PQ-encode LMS
6266 let PQLMS = /** @type {Vector3} } */
6267 LMS.map(function (val) {
6268 let num = c1$2 + c2$2 * spow(val / 10000, n$1);
6269 let denom = 1 + c3$2 * spow(val / 10000, n$1);
6270 return spow(num / denom, p$1);
6271 });
6272
6273 // almost there, calculate Iz az bz
6274 let [Iz, az, bz] = multiply_v3_m3x3(PQLMS, ConetoIab_M);
6275 // console.log({Iz, az, bz});
6276
6277 let Jz = (1 + d) * Iz / (1 + d * Iz) - d0;
6278 return [Jz, az, bz];
6279 },
6280 toBase(Jzazbz) {
6281 let [Jz, az, bz] = Jzazbz;
6282 let Iz = (Jz + d0) / (1 + d - d * (Jz + d0));
6283
6284 // bring into LMS cone domain
6285 let PQLMS = multiply_v3_m3x3([Iz, az, bz], IabtoCone_M);
6286
6287 // convert from PQ-coded to linear-light
6288 let LMS = /** @type {Vector3} } */
6289 PQLMS.map(function (val) {
6290 let num = c1$2 - spow(val, pinv);
6291 let denom = c3$2 * spow(val, pinv) - c2$2;
6292 let x = 10000 * spow(num / denom, ninv$1);
6293 return x; // luminance relative to diffuse white, [0, 70 or so].
6294 });
6295
6296 // modified abs XYZ
6297 let [Xm, Ym, Za] = multiply_v3_m3x3(LMS, ConetoXYZ_M);
6298
6299 // un-modify X and Y to get D65 XYZ, relative to media white
6300 let Xa = (Xm + (b$1 - 1) * Za) / b$1;
6301 let Ya = (Ym + (g - 1) * Xa) / g;
6302 return [Xa, Ya, Za];
6303 },
6304 formats: {
6305 // https://drafts.csswg.org/css-color-hdr/#Jzazbz
6306 jzazbz: {
6307 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
6308 }
6309 }
6310 });
6311
6312 var jzczhz = new ColorSpace({
6313 id: "jzczhz",
6314 name: "JzCzHz",
6315 coords: {
6316 jz: {
6317 refRange: [0, 1],
6318 name: "Jz"
6319 },
6320 cz: {
6321 refRange: [0, 0.26],
6322 name: "Chroma"
6323 },
6324 hz: {
6325 refRange: [0, 360],
6326 type: "angle",
6327 name: "Hue"
6328 }
6329 },
6330 base: Jzazbz,
6331 fromBase: lch.fromBase,
6332 toBase: lch.toBase,
6333 formats: {
6334 // https://drafts.csswg.org/css-color-hdr/#JzCzhz
6335 jzczhz: {
6336 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
6337 }
6338 }
6339 });
6340
6341 /**
6342 * More accurate color-difference formulae
6343 * than the simple 1976 Euclidean distance in Lab
6344 *
6345 * Uses JzCzHz, which has improved perceptual uniformity
6346 * and thus a simple Euclidean root-sum of ΔL² ΔC² ΔH²
6347 * gives good results.
6348 * @param {import("../types.js").ColorTypes} color
6349 * @param {import("../types.js").ColorTypes} sample
6350 * @returns {number}
6351 */
6352 function deltaEJz (color, sample) {
6353 [color, sample] = getColor([color, sample]);
6354
6355 // Given this color as the reference
6356 // and a sample,
6357 // calculate deltaE in JzCzHz.
6358 let [Jz1, Cz1, Hz1] = jzczhz.from(color);
6359 let [Jz2, Cz2, Hz2] = jzczhz.from(sample);
6360
6361 // Lightness and Chroma differences
6362 // sign does not matter as they are squared.
6363 let ΔJ = Jz1 - Jz2;
6364 let ΔC = Cz1 - Cz2;
6365
6366 // length of chord for ΔH
6367 if (isNone(Hz1) && isNone(Hz2)) {
6368 // both undefined hues
6369 Hz1 = 0;
6370 Hz2 = 0;
6371 } else if (isNone(Hz1)) {
6372 // one undefined, set to the defined hue
6373 Hz1 = Hz2;
6374 } else if (isNone(Hz2)) {
6375 Hz2 = Hz1;
6376 }
6377 let Δh = Hz1 - Hz2;
6378 let ΔH = 2 * Math.sqrt(Cz1 * Cz2) * Math.sin(Δh / 2 * (Math.PI / 180));
6379 return Math.sqrt(ΔJ ** 2 + ΔC ** 2 + ΔH ** 2);
6380 }
6381
6382 /** @import { Matrix3x3, Vector3 } from "../types.js" */
6383
6384 const c1$1 = 3424 / 4096;
6385 const c2$1 = 2413 / 128;
6386 const c3$1 = 2392 / 128;
6387 const m1$1 = 2610 / 16384;
6388 const m2 = 2523 / 32;
6389 const im1 = 16384 / 2610;
6390 const im2 = 32 / 2523;
6391
6392 // The matrix below includes the 4% crosstalk components
6393 // and is from the Dolby "What is ICtCp" paper"
6394 /** @type {Matrix3x3} */
6395 // prettier-ignore
6396 const XYZtoLMS_M = [[0.3592832590121217, 0.6976051147779502, -0.0358915932320290], [-0.1920808463704993, 1.1004767970374321, 0.0753748658519118], [0.0070797844607479, 0.0748396662186362, 0.8433265453898765]];
6397 // linear-light Rec.2020 to LMS, again with crosstalk
6398 // rational terms from Jan Fröhlich,
6399 // Encoding High Dynamic Range andWide Color Gamut Imagery, p.97
6400 // and ITU-R BT.2124-0 p.2
6401 /*
6402 const Rec2020toLMS_M = [
6403 [ 1688 / 4096, 2146 / 4096, 262 / 4096 ],
6404 [ 683 / 4096, 2951 / 4096, 462 / 4096 ],
6405 [ 99 / 4096, 309 / 4096, 3688 / 4096 ]
6406 ];
6407 */
6408 // this includes the Ebner LMS coefficients,
6409 // the rotation, and the scaling to [-0.5,0.5] range
6410 // rational terms from Fröhlich p.97
6411 // and ITU-R BT.2124-0 pp.2-3
6412 /** @type {Matrix3x3} */
6413 // prettier-ignore
6414 const LMStoIPT_M = [[2048 / 4096, 2048 / 4096, 0], [6610 / 4096, -13613 / 4096, 7003 / 4096], [17933 / 4096, -17390 / 4096, -543 / 4096]];
6415
6416 // inverted matrices, calculated from the above
6417 /** @type {Matrix3x3} */
6418 // prettier-ignore
6419 const IPTtoLMS_M = [[0.9999999999999998, 0.0086090370379328, 0.1110296250030260], [0.9999999999999998, -0.0086090370379328, -0.1110296250030259], [0.9999999999999998, 0.5600313357106791, -0.3206271749873188]];
6420 /*
6421 // prettier-ignore
6422 const LMStoRec2020_M = [
6423 [ 3.4375568932814012112, -2.5072112125095058195, 0.069654319228104608382],
6424 [-0.79142868665644156125, 1.9838372198740089874, -0.19240853321756742626 ],
6425 [-0.025646662911506476363, -0.099240248643945566751, 1.1248869115554520431 ]
6426 ];
6427 */
6428 /** @type {Matrix3x3} */
6429 // prettier-ignore
6430 const LMStoXYZ_M = [[2.0701522183894223, -1.3263473389671563, 0.2066510476294053], [0.3647385209748072, 0.6805660249472273, -0.0453045459220347], [-0.0497472075358123, -0.0492609666966131, 1.1880659249923042]];
6431
6432 // Only the PQ form of ICtCp is implemented here. There is also an HLG form.
6433 // from Dolby, "WHAT IS ICTCP?"
6434 // https://professional.dolby.com/siteassets/pdfs/ictcp_dolbywhitepaper_v071.pdf
6435 // and
6436 // Dolby, "Perceptual Color Volume
6437 // Measuring the Distinguishable Colors of HDR and WCG Displays"
6438 // https://professional.dolby.com/siteassets/pdfs/dolby-vision-measuring-perceptual-color-volume-v7.1.pdf
6439 var ictcp = new ColorSpace({
6440 id: "ictcp",
6441 name: "ICTCP",
6442 // From BT.2100-2 page 7:
6443 // During production, signal values are expected to exceed the
6444 // range E′ = [0.0 : 1.0]. This provides processing headroom and avoids
6445 // signal degradation during cascaded processing. Such values of E′,
6446 // below 0.0 or exceeding 1.0, should not be clipped during production
6447 // and exchange.
6448 // Values below 0.0 should not be clipped in reference displays (even
6449 // though they represent “negative” light) to allow the black level of
6450 // the signal (LB) to be properly set using test signals known as “PLUGE”
6451 coords: {
6452 i: {
6453 refRange: [0, 1],
6454 // Constant luminance,
6455 name: "I"
6456 },
6457 ct: {
6458 refRange: [-0.5, 0.5],
6459 // Full BT.2020 gamut in range [-0.5, 0.5]
6460 name: "CT"
6461 },
6462 cp: {
6463 refRange: [-0.5, 0.5],
6464 name: "CP"
6465 }
6466 },
6467 base: XYZ_Abs_D65,
6468 fromBase(XYZ) {
6469 // move to LMS cone domain
6470 let LMS = multiply_v3_m3x3(XYZ, XYZtoLMS_M);
6471 return LMStoICtCp(LMS);
6472 },
6473 toBase(ICtCp) {
6474 let LMS = ICtCptoLMS(ICtCp);
6475 return multiply_v3_m3x3(LMS, LMStoXYZ_M);
6476 },
6477 formats: {
6478 ictcp: {
6479 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
6480 }
6481 }
6482 });
6483
6484 /**
6485 *
6486 * @param {Vector3} LMS
6487 * @returns {Vector3}
6488 */
6489 function LMStoICtCp(LMS) {
6490 // apply the PQ EOTF
6491 // we can't ever be dividing by zero because of the "1 +" in the denominator
6492 let PQLMS = /** @type {Vector3} */
6493 LMS.map(function (val) {
6494 let num = c1$1 + c2$1 * (val / 10000) ** m1$1;
6495 let denom = 1 + c3$1 * (val / 10000) ** m1$1;
6496 return (num / denom) ** m2;
6497 });
6498
6499 // LMS to IPT, with rotation for Y'C'bC'r compatibility
6500 return multiply_v3_m3x3(PQLMS, LMStoIPT_M);
6501 }
6502
6503 /**
6504 *
6505 * @param {Vector3} ICtCp
6506 * @returns {Vector3}
6507 */
6508 function ICtCptoLMS(ICtCp) {
6509 let PQLMS = multiply_v3_m3x3(ICtCp, IPTtoLMS_M);
6510
6511 // From BT.2124-0 Annex 2 Conversion 3
6512 let LMS = /** @type {Vector3} */
6513 PQLMS.map(function (val) {
6514 let num = Math.max(val ** im2 - c1$1, 0);
6515 let denom = c2$1 - c3$1 * val ** im2;
6516 return 10000 * (num / denom) ** im1;
6517 });
6518 return LMS;
6519 }
6520
6521 /**
6522 * Delta E in ICtCp space,
6523 * which the ITU calls Delta E ITP, which is shorter.
6524 * Formulae from ITU Rec. ITU-R BT.2124-0
6525 * @param {import("../types.js").ColorTypes} color
6526 * @param {import("../types.js").ColorTypes} sample
6527 * @returns {number}
6528 */
6529 function deltaEITP (color, sample) {
6530 [color, sample] = getColor([color, sample]);
6531
6532 // Given this color as the reference
6533 // and a sample,
6534 // calculate deltaE in ICtCp
6535 // which is simply the Euclidean distance
6536
6537 let [I1, T1, P1] = ictcp.from(color);
6538 let [I2, T2, P2] = ictcp.from(sample);
6539
6540 // the 0.25 factor is to undo the encoding scaling in Ct
6541 // the 720 is so that 1 deltaE = 1 JND
6542 // per ITU-R BT.2124-0 p.3
6543
6544 return 720 * Math.sqrt((I1 - I2) ** 2 + 0.25 * (T1 - T2) ** 2 + (P1 - P2) ** 2);
6545 }
6546
6547 /**
6548 * More accurate color-difference formulae
6549 * than the simple 1976 Euclidean distance in CIE Lab
6550 * The Oklab a and b axes are scaled relative to the L axis, for better uniformity
6551 * Björn Ottosson said:
6552 * "I've recently done some tests with color distance datasets as implemented
6553 * in Colorio and on both the Combvd dataset and the OSA-UCS dataset a
6554 * scale factor of slightly more than 2 for a and b would give the best results
6555 * (2.016 works best for Combvd and 2.045 for the OSA-UCS dataset)."
6556 * @see {@link <https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-945714988>}
6557 * @param {import("../types.js").ColorTypes} color
6558 * @param {import("../types.js").ColorTypes} sample
6559 * @returns {number}
6560 */
6561 function deltaEOK2 (color, sample) {
6562 [color, sample] = getColor([color, sample]);
6563
6564 // Given this color as the reference
6565 // and a sample,
6566 // calculate deltaEOK2, term by term as root sum of squares
6567 let abscale = 2;
6568 let [L1, a1, b1] = Oklab.from(color);
6569 let [L2, a2, b2] = Oklab.from(sample);
6570 let ΔL = L1 - L2;
6571 let Δa = abscale * (a1 - a2);
6572 let Δb = abscale * (b1 - b2);
6573 return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2);
6574 }
6575
6576 /** @import { Coords, Matrix3x3, Vector3 } from "../types.js" */
6577
6578 // Type re-exports
6579 /** @typedef {import("../types.js").Cam16Object} Cam16Object */
6580 /** @typedef {import("../types.js").Cam16Input} Cam16Input */
6581 /** @typedef {import("../types.js").Cam16Environment} Cam16Environment */
6582
6583 const white$3 = WHITES.D65;
6584 const adaptedCoef = 0.42;
6585 const adaptedCoefInv = 1 / adaptedCoef;
6586 const tau$1 = 2 * Math.PI;
6587
6588 /** @type {Matrix3x3} */
6589 // prettier-ignore
6590 const cat16 = [[0.401288, 0.650173, -0.051461], [-0.250268, 1.204414, 0.045854], [-0.002079, 0.048952, 0.953127]];
6591
6592 /** @type {Matrix3x3} */
6593 const cat16Inv = [[1.8620678550872327, -1.0112546305316843, 0.14918677544445175], [0.38752654323613717, 0.6214474419314753, -0.008973985167612518], [-0.015841498849333856, -0.03412293802851557, 1.0499644368778496]];
6594
6595 /** @type {Matrix3x3} */
6596 const m1 = [[460.0, 451.0, 288.0], [460.0, -891.0, -261.0], [460.0, -220.0, -6300.0]];
6597 const surroundMap = {
6598 dark: [0.8, 0.525, 0.8],
6599 dim: [0.9, 0.59, 0.9],
6600 average: [1, 0.69, 1]
6601 };
6602 const hueQuadMap = {
6603 // Red, Yellow, Green, Blue, Red
6604 h: [20.14, 90.0, 164.25, 237.53, 380.14],
6605 e: [0.8, 0.7, 1.0, 1.2, 0.8],
6606 H: [0.0, 100.0, 200.0, 300.0, 400.0]
6607 };
6608 const rad2deg = 180 / Math.PI;
6609 const deg2rad$1 = Math.PI / 180;
6610
6611 /**
6612 * @param {Coords} coords
6613 * @param {number} fl
6614 * @returns {[number, number, number]}
6615 */
6616 function adapt$1(coords, fl) {
6617 const temp = /** @type {[number, number, number]} */
6618 coords.map(c => {
6619 const x = spow(fl * Math.abs(c) * 0.01, adaptedCoef);
6620 return 400 * copySign(x, c) / (x + 27.13);
6621 });
6622 return temp;
6623 }
6624
6625 /**
6626 * @param {Coords} adapted
6627 * @param {number} fl
6628 * @returns {[number, number, number]}
6629 */
6630 function unadapt(adapted, fl) {
6631 const constant = 100 / fl * 27.13 ** adaptedCoefInv;
6632 return /** @type {[number, number, number]} */adapted.map(c => {
6633 const cabs = Math.abs(c);
6634 return copySign(constant * spow(cabs / (400 - cabs), adaptedCoefInv), c);
6635 });
6636 }
6637
6638 /**
6639 * @param {number} h
6640 */
6641 function hueQuadrature(h) {
6642 let hp = constrain(h);
6643 if (hp <= hueQuadMap.h[0]) {
6644 hp += 360;
6645 }
6646 const i = bisectLeft(hueQuadMap.h, hp) - 1;
6647 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
6648 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
6649 const Hi = hueQuadMap.H[i];
6650 const t = (hp - hi) / ei;
6651 return Hi + 100 * t / (t + (hii - hp) / eii);
6652 }
6653
6654 /**
6655 * @param {number} H
6656 */
6657 function invHueQuadrature(H) {
6658 let Hp = (H % 400 + 400) % 400;
6659 const i = Math.floor(0.01 * Hp);
6660 Hp = Hp % 100;
6661 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
6662 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
6663 return constrain((Hp * (eii * hi - ei * hii) - 100 * hi * eii) / (Hp * (eii - ei) - 100 * eii));
6664 }
6665
6666 /**
6667 * @param {[number, number, number]} refWhite
6668 * @param {number} adaptingLuminance
6669 * @param {number} backgroundLuminance
6670 * @param {keyof typeof surroundMap} surround
6671 * @param {boolean} discounting
6672 * @returns {Cam16Environment}
6673 */
6674 function environment(refWhite, adaptingLuminance, backgroundLuminance, surround, discounting) {
6675 const env = {};
6676 env.discounting = discounting;
6677 env.refWhite = refWhite;
6678 env.surround = surround;
6679 const xyzW = /** @type {Vector3} */
6680 refWhite.map(c => {
6681 return c * 100;
6682 });
6683
6684 // The average luminance of the environment in `cd/m^2cd/m` (a.k.a. nits)
6685 env.la = adaptingLuminance;
6686 // The relative luminance of the nearby background
6687 env.yb = backgroundLuminance;
6688 // Absolute luminance of the reference white.
6689 const yw = xyzW[1];
6690
6691 // Cone response for reference white
6692 const rgbW = multiply_v3_m3x3(xyzW, cat16);
6693
6694 // Surround: dark, dim, and average
6695 let values = surroundMap[env.surround];
6696 const f = values[0];
6697 env.c = values[1];
6698 env.nc = values[2];
6699 const k = 1 / (5 * env.la + 1);
6700 const k4 = k ** 4;
6701
6702 // Factor of luminance level adaptation
6703 env.fl = k4 * env.la + 0.1 * (1 - k4) * (1 - k4) * Math.cbrt(5 * env.la);
6704 env.flRoot = env.fl ** 0.25;
6705 env.n = env.yb / yw;
6706 env.z = 1.48 + Math.sqrt(env.n);
6707 env.nbb = 0.725 * env.n ** -0.2;
6708 env.ncb = env.nbb;
6709
6710 // Degree of adaptation calculating if not discounting
6711 // illuminant (assumed eye is fully adapted)
6712 const d = Math.max(Math.min(f * (1 - 1 / 3.6 * Math.exp((-env.la - 42) / 92)), 1), 0);
6713 env.dRgb = /** @type {[number, number, number]} */
6714 rgbW.map(c => {
6715 return interpolate(1, yw / c, d);
6716 });
6717 env.dRgbInv = /** @type {[number, number, number]} */
6718 env.dRgb.map(c => {
6719 return 1 / c;
6720 });
6721
6722 // Achromatic response
6723 const rgbCW = /** @type {[number, number, number]} */
6724 rgbW.map((c, i) => {
6725 return c * env.dRgb[i];
6726 });
6727 const rgbAW = adapt$1(rgbCW, env.fl);
6728 env.aW = env.nbb * (2 * rgbAW[0] + rgbAW[1] + 0.05 * rgbAW[2]);
6729
6730 // console.log(env);
6731
6732 return env;
6733 }
6734
6735 // Pre-calculate everything we can with the viewing conditions
6736 const viewingConditions$1 = environment(white$3, 64 / Math.PI * 0.2, 20, "average", false);
6737
6738 /**
6739 * @param {Cam16Input} cam16
6740 * @param {Cam16Environment} env
6741 * @returns {[number, number, number]}
6742 */
6743 function fromCam16(cam16, env) {
6744 // These check ensure one, and only one attribute for a
6745 // given category is provided.
6746 // @ts-expect-error The '^` operator is not allowed for boolean types
6747 if (!(cam16.J !== undefined ^ cam16.Q !== undefined)) {
6748 throw new Error("Conversion requires one and only one: 'J' or 'Q'");
6749 }
6750
6751 // @ts-expect-error - The '^` operator is not allowed for boolean types
6752 if (!(cam16.C !== undefined ^ cam16.M !== undefined ^ cam16.s !== undefined)) {
6753 throw new Error("Conversion requires one and only one: 'C', 'M' or 's'");
6754 }
6755
6756 // Hue is absolutely required
6757 // @ts-expect-error - The '^` operator is not allowed for boolean types
6758 if (!(cam16.h !== undefined ^ cam16.H !== undefined)) {
6759 throw new Error("Conversion requires one and only one: 'h' or 'H'");
6760 }
6761
6762 // Black
6763 if (cam16.J === 0.0 || cam16.Q === 0.0) {
6764 return [0.0, 0.0, 0.0];
6765 }
6766
6767 // Break hue into Cartesian components
6768 let hRad = 0.0;
6769 if (cam16.h !== undefined) {
6770 hRad = constrain(cam16.h) * deg2rad$1;
6771 } else {
6772 hRad = invHueQuadrature(cam16.H) * deg2rad$1;
6773 }
6774 const cosh = Math.cos(hRad);
6775 const sinh = Math.sin(hRad);
6776
6777 // Calculate `Jroot` from one of the lightness derived coordinates.
6778 let Jroot = 0.0;
6779 if (cam16.J !== undefined) {
6780 Jroot = spow(cam16.J, 1 / 2) * 0.1;
6781 } else if (cam16.Q !== undefined) {
6782 Jroot = 0.25 * env.c * cam16.Q / ((env.aW + 4) * env.flRoot);
6783 }
6784
6785 // Calculate the `t` value from one of the chroma derived coordinates
6786 let alpha = 0.0;
6787 if (cam16.C !== undefined) {
6788 alpha = cam16.C / Jroot;
6789 } else if (cam16.M !== undefined) {
6790 alpha = cam16.M / env.flRoot / Jroot;
6791 } else if (cam16.s !== undefined) {
6792 alpha = 0.0004 * cam16.s ** 2 * (env.aW + 4) / env.c;
6793 }
6794 const t = spow(alpha * Math.pow(1.64 - Math.pow(0.29, env.n), -0.73), 10 / 9);
6795
6796 // Eccentricity
6797 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
6798
6799 // Achromatic response
6800 const A = env.aW * spow(Jroot, 2 / env.c / env.z);
6801
6802 // Calculate red-green and yellow-blue components
6803 const p1 = 5e4 / 13 * env.nc * env.ncb * et;
6804 const p2 = A / env.nbb;
6805 const r = 23 * (p2 + 0.305) * zdiv(t, 23 * p1 + t * (11 * cosh + 108 * sinh));
6806 const a = r * cosh;
6807 const b = r * sinh;
6808
6809 // Calculate back from cone response to XYZ
6810 const rgb_c = unadapt(/** @type {Vector3} */
6811
6812 multiply_v3_m3x3([p2, a, b], m1).map(c => {
6813 return c * 1 / 1403;
6814 }), env.fl);
6815 return /** @type {Vector3} */multiply_v3_m3x3(/** @type {Vector3} */
6816 rgb_c.map((c, i) => {
6817 return c * env.dRgbInv[i];
6818 }), cat16Inv).map(c => {
6819 return c / 100;
6820 });
6821 }
6822
6823 /**
6824 * @param {[number, number, number]} xyzd65
6825 * @param {Cam16Environment} env
6826 * @returns {Cam16Object}
6827 */
6828 function toCam16(xyzd65, env) {
6829 // Cone response
6830 const xyz100 = /** @type {Vector3} */
6831 xyzd65.map(c => {
6832 return c * 100;
6833 });
6834 const rgbA = adapt$1(/** @type {[number, number, number]} */
6835
6836 multiply_v3_m3x3(xyz100, cat16).map((c, i) => {
6837 return c * env.dRgb[i];
6838 }), env.fl);
6839
6840 // Calculate hue from red-green and yellow-blue components
6841 const a = rgbA[0] + (-12 * rgbA[1] + rgbA[2]) / 11;
6842 const b = (rgbA[0] + rgbA[1] - 2 * rgbA[2]) / 9;
6843 const hRad = (Math.atan2(b, a) % tau$1 + tau$1) % tau$1;
6844
6845 // Eccentricity
6846 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
6847 const t = 5e4 / 13 * env.nc * env.ncb * zdiv(et * Math.sqrt(a ** 2 + b ** 2), rgbA[0] + rgbA[1] + 1.05 * rgbA[2] + 0.305);
6848 const alpha = spow(t, 0.9) * Math.pow(1.64 - Math.pow(0.29, env.n), 0.73);
6849
6850 // Achromatic response
6851 const A = env.nbb * (2 * rgbA[0] + rgbA[1] + 0.05 * rgbA[2]);
6852 const Jroot = spow(A / env.aW, 0.5 * env.c * env.z);
6853
6854 // Lightness
6855 const J = 100 * spow(Jroot, 2);
6856
6857 // Brightness
6858 const Q = 4 / env.c * Jroot * (env.aW + 4) * env.flRoot;
6859
6860 // Chroma
6861 const C = alpha * Jroot;
6862
6863 // Colorfulness
6864 const M = C * env.flRoot;
6865
6866 // Hue
6867 const h = constrain(hRad * rad2deg);
6868
6869 // Hue quadrature
6870 const H = hueQuadrature(h);
6871
6872 // Saturation
6873 const s = 50 * spow(env.c * alpha / (env.aW + 4), 1 / 2);
6874
6875 // console.log({J: J, C: C, h: h, s: s, Q: Q, M: M, H: H});
6876
6877 return {
6878 J: J,
6879 C: C,
6880 h: h,
6881 s: s,
6882 Q: Q,
6883 M: M,
6884 H: H
6885 };
6886 }
6887
6888 // Provided as a way to directly evaluate the CAM16 model
6889 // https://observablehq.com/@jrus/cam16: reference implementation
6890 // https://arxiv.org/pdf/1802.06067.pdf: Nico Schlömer
6891 // https://onlinelibrary.wiley.com/doi/pdf/10.1002/col.22324: hue quadrature
6892 // https://www.researchgate.net/publication/318152296_Comprehensive_color_solutions_CAM16_CAT16_and_CAM16-UCS
6893 // Results compared against: https://github.com/colour-science/colour
6894 var cam16 = new ColorSpace({
6895 id: "cam16-jmh",
6896 cssId: "--cam16-jmh",
6897 name: "CAM16-JMh",
6898 coords: {
6899 j: {
6900 refRange: [0, 100],
6901 name: "J"
6902 },
6903 m: {
6904 refRange: [0, 105.0],
6905 name: "Colorfulness"
6906 },
6907 h: {
6908 refRange: [0, 360],
6909 type: "angle",
6910 name: "Hue"
6911 }
6912 },
6913 base: XYZ_D65,
6914 fromBase(xyz) {
6915 // If another derivation is created, ε could vary, so we can't hardcode
6916 if (this.ε === undefined) {
6917 this.ε = Object.values(this.coords)[1].refRange[1] / 100000;
6918 }
6919 const cam16 = toCam16(xyz, viewingConditions$1);
6920 const isAchromatic = Math.abs(cam16.M) < this.ε;
6921 return [cam16.J, isAchromatic ? 0 : cam16.M, isAchromatic ? null : cam16.h];
6922 },
6923 toBase(cam16) {
6924 return fromCam16({
6925 J: cam16[0],
6926 M: cam16[1],
6927 h: cam16[2]
6928 }, viewingConditions$1);
6929 }
6930 });
6931
6932 const white$2 = WHITES.D65;
6933 const ε$4 = 216 / 24389; // 6^3/29^3 == (24/116)^3
6934 const κ$3 = 24389 / 27; // 29^3/3^3
6935
6936 function toLstar(y) {
6937 // Convert XYZ Y to L*
6938
6939 const fy = y > ε$4 ? Math.cbrt(y) : (κ$3 * y + 16) / 116;
6940 return 116.0 * fy - 16.0;
6941 }
6942 function fromLstar(lstar) {
6943 // Convert L* back to XYZ Y
6944
6945 return lstar > 8 ? Math.pow((lstar + 16) / 116, 3) : lstar / κ$3;
6946 }
6947 function fromHct(coords, env) {
6948 // Use Newton's method to try and converge as quick as possible or
6949 // converge as close as we can. While the requested precision is achieved
6950 // most of the time, it may not always be achievable. Especially past the
6951 // visible spectrum, the algorithm will likely struggle to get the same
6952 // precision. If, for whatever reason, we cannot achieve the accuracy we
6953 // seek in the allotted iterations, just return the closest we were able to
6954 // get.
6955
6956 let [h, c, t] = coords;
6957 let xyz = [];
6958 let j = 0;
6959
6960 // Shortcut out for black
6961 if (t === 0) {
6962 return [0.0, 0.0, 0.0];
6963 }
6964
6965 // Calculate the Y we need to target
6966 let y = fromLstar(t);
6967
6968 // A better initial guess yields better results. Polynomials come from
6969 // curve fitting the T vs J response.
6970 if (t > 0) {
6971 j = 0.00379058511492914 * t ** 2 + 0.608983189401032 * t + 0.9155088574762233;
6972 } else {
6973 j = 9.514440756550361e-6 * t ** 2 + 0.08693057439788597 * t - 21.928975842194614;
6974 }
6975
6976 // Threshold of how close is close enough, and max number of attempts.
6977 // More precision and more attempts means more time spent iterating. Higher
6978 // required precision gives more accuracy but also increases the chance of
6979 // not hitting the goal. 2e-12 allows us to convert round trip with
6980 // reasonable accuracy of six decimal places or more.
6981 const threshold = 2e-12;
6982 const max_attempts = 15;
6983 let attempt = 0;
6984 let last = Infinity;
6985 let best = [0, 0, 0];
6986
6987 // Try to find a J such that the returned y matches the returned y of the L*
6988 while (attempt <= max_attempts) {
6989 xyz = fromCam16({
6990 J: j,
6991 C: c,
6992 h: h
6993 }, env);
6994
6995 // If we are within range, return XYZ
6996 // If we are closer than last time, save the values
6997 const delta = Math.abs(xyz[1] - y);
6998 if (delta < last) {
6999 if (delta <= threshold) {
7000 return xyz;
7001 }
7002 best = xyz;
7003 last = delta;
7004 }
7005
7006 // f(j_root) = (j ** (1 / 2)) * 0.1
7007 // f(j) = ((f(j_root) * 100) ** 2) / j - 1 = 0
7008 // f(j_root) = Y = y / 100
7009 // f(j) = (y ** 2) / j - 1
7010 // f'(j) = (2 * y) / j
7011 j = j - (xyz[1] - y) * j / (2 * xyz[1]);
7012 attempt += 1;
7013 }
7014
7015 // We could not acquire the precision we desired,
7016 // return our closest attempt.
7017 return best;
7018 }
7019 function toHct(xyz, env) {
7020 // Calculate HCT by taking the L* of CIE LCh D65 and CAM16 chroma and hue.
7021
7022 const t = toLstar(xyz[1]);
7023 if (t === 0.0) {
7024 return [0.0, 0.0, 0.0];
7025 }
7026 const cam16 = toCam16(xyz, viewingConditions);
7027 return [constrain(cam16.h), cam16.C, t];
7028 }
7029
7030 // Pre-calculate everything we can with the viewing conditions
7031 const viewingConditions = environment(white$2, 200 / Math.PI * fromLstar(50.0), fromLstar(50.0) * 100, "average", false);
7032
7033 // https://material.io/blog/science-of-color-design
7034 // This is not a port of the material-color-utilities,
7035 // but instead implements the full color space as described,
7036 // combining CAM16 JCh and Lab D65. This does not clamp conversion
7037 // to HCT to specific chroma bands and provides support for wider
7038 // gamuts than Google currently supports and does so at a greater
7039 // precision (> 8 bits back to sRGB).
7040 // This implementation comes from https://github.com/facelessuser/coloraide
7041 // which is licensed under MIT.
7042 var hct = new ColorSpace({
7043 id: "hct",
7044 name: "HCT",
7045 coords: {
7046 h: {
7047 refRange: [0, 360],
7048 type: "angle",
7049 name: "Hue"
7050 },
7051 c: {
7052 refRange: [0, 145],
7053 name: "Colorfulness"
7054 },
7055 t: {
7056 refRange: [0, 100],
7057 name: "Tone"
7058 }
7059 },
7060 base: XYZ_D65,
7061 fromBase(xyz) {
7062 if (this.ε === undefined) {
7063 this.ε = Object.values(this.coords)[1].refRange[1] / 100000;
7064 }
7065 let hct = toHct(xyz);
7066 if (hct[1] < this.ε) {
7067 hct[1] = 0.0;
7068 hct[0] = null;
7069 }
7070 return hct;
7071 },
7072 toBase(hct) {
7073 return fromHct(hct, viewingConditions);
7074 },
7075 formats: {
7076 color: {
7077 id: "--hct",
7078 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
7079 }
7080 }
7081 });
7082
7083 const deg2rad = Math.PI / 180;
7084 const ucsCoeff = [1.0, 0.007, 0.0228];
7085
7086 /**
7087 * Convert HCT chroma and hue (CAM16 JMh colorfulness and hue) using UCS logic for a and b.
7088 * @param {Coords} coords - HCT coordinates.
7089 * @return {number[]}
7090 */
7091 function convertUcsAb(coords) {
7092 // We want the distance between the actual color.
7093 // If chroma is negative, it will throw off our calculations.
7094 // Normally, converting back to the base and forward will correct it.
7095 // If we have a negative chroma after this, then we have a color that
7096 // cannot resolve to positive chroma.
7097 if (coords[1] < 0) {
7098 coords = hct.fromBase(hct.toBase(coords));
7099 }
7100
7101 // Only in extreme cases (usually outside the visible spectrum)
7102 // can the input value for log become negative.
7103 // Avoid domain error by forcing a zero result via "max" if necessary.
7104 const M = Math.log(Math.max(1 + ucsCoeff[2] * coords[1] * viewingConditions.flRoot, 1.0)) / ucsCoeff[2];
7105 const hrad = coords[0] * deg2rad;
7106 const a = M * Math.cos(hrad);
7107 const b = M * Math.sin(hrad);
7108 return [coords[2], a, b];
7109 }
7110
7111 /**
7112 * Color distance using HCT.
7113 * @param {import("../types.js").ColorTypes} color
7114 * @param {import("../types.js").ColorTypes} sample
7115 * @returns {number}
7116 */
7117 function deltaEHCT (color, sample) {
7118 [color, sample] = getColor([color, sample]);
7119 let [t1, a1, b1] = convertUcsAb(hct.from(color));
7120 let [t2, a2, b2] = convertUcsAb(hct.from(sample));
7121
7122 // Use simple euclidean distance with a and b using UCS conversion
7123 // and LCh lightness (HCT tone).
7124 return Math.sqrt((t1 - t2) ** 2 + (a1 - a2) ** 2 + (b1 - b2) ** 2);
7125 }
7126
7127 /**
7128 * Helmlab MetricSpace — 13-stage perceptual color space.
7129 *
7130 * A data-driven analytical color space fit on COMBVD (3,813 paired human
7131 * color-difference judgments aggregating BFD-P, Witt 1999, RIT-DuPont, and
7132 * Leeds). Used internally by `deltaEHelmlab` and exposed as the CSS
7133 * color space `helmlab-metric` for inspectability. Its coordinate system
7134 * (asymmetric ab plane, L > 1 from H-K modeling, achromatic axis offset
7135 * from origin) is shaped for ΔE accuracy rather than author-facing
7136 * coordinates — for general CSS authoring use HelmGen (`helmgen`).
7137 *
7138 * Measured in this branch: ~24% lower STRESS than CIEDE2000 on COMBVD.
7139 *
7140 * Pipeline: XYZ → M1 → γ → M2 → hue correction → H-K → cubic L → dark L
7141 * → hue-dep chroma scale → chroma power → L-dep chroma scale
7142 * → HLC interaction → hue-dep lightness → rotation
7143 *
7144 * Reference: arXiv:2602.23010
7145 * @see https://github.com/Grkmyldz148/helmlab
7146 */
7147
7148 /** @import { Matrix3x3 } from "../types.js" */
7149
7150 const {
7151 cos,
7152 sin,
7153 sqrt,
7154 atan2,
7155 exp,
7156 abs,
7157 pow,
7158 PI
7159 } = Math;
7160
7161 /** Bradford CAT: Color.js D65 → Helmlab D65 (apply in fromBase before M1) */
7162 /** @type {Matrix3x3} */
7163 // prettier-ignore
7164 const CAT_TO_HELM = [[1.000042977349746, 2.0718877053183e-05, -4.361018085669474e-05], [2.6946201090235744e-05, 0.9999906145080147, -1.4898828405401079e-05], [-7.941753620756204e-06, 1.2875204405137254e-05, 0.9997859822609763]];
7165
7166 /** Bradford CAT: Helmlab D65 → Color.js D65 (apply in toBase after M1_INV) */
7167 /** @type {Matrix3x3} */
7168 // prettier-ignore
7169 const CAT_FROM_HELM = [[0.9999570254019492, -2.071874272730964e-05, 4.361733292468361e-05], [-2.694517763358666e-05, 1.000009385946497, 1.490098223546482e-05], [7.943459292954202e-06, -1.287824596735154e-05, 1.000214063706999]];
7170
7171 // ── Utility functions ──────────────────────────────────────────────
7172
7173 // ── Core parameters (v21, 72 params) ──────────────────────────────
7174
7175 /** @type {Matrix3x3} */
7176 // prettier-ignore
7177 const M1$1 = [[0.72129864331134985189, 0.45344826541531813024, -0.19288975751942616377], [-0.78821186949557897616, 1.79524137675723594043, 0.08761724511817850503], [-0.09177005999121559676, 0.45765588659459255361, 1.29220455139176770842]];
7178 /** @type {Matrix3x3} */
7179 // prettier-ignore
7180 const M1_INV$1 = [[1.06510729580885898926, -0.31500440753011210715, 0.18034923817410389302], [0.47211077138377960383, 0.42719957659624552271, 0.04150680489380984689], [-0.09156391926309541407, -0.17367093631949789834, 0.77197903825582936399]];
7181 const GAMMA = [0.47229813098762524, 0.5149184096354483, 0.5113233386366979];
7182 const INV_GAMMA = [2.1173067060606283, 1.9420552485353544, 1.9557096741686448];
7183
7184 /** @type {Matrix3x3} */
7185 // prettier-ignore
7186 const M2$1 = [[-0.26355622180094095963, 0.41683228837031738312, 0.49267631416564028335], [1.88975705087773215851, -3.12122320342057735232, 1.04216669210603840590], [0.35851086179620561545, 1.76940281937903676202, -1.41206260676953720967]];
7187 /** @type {Matrix3x3} */
7188 // prettier-ignore
7189 const M2_INV$1 = [[0.91838978228150214278, 0.52320512370886662623, 0.70658045980908557038], [1.08990905744330257576, 0.07005324849041903723, 0.43197768747870440853], [1.59889572926420897581, 0.22061850068770233468, 0.01250603735522095097]];
7190
7191 // Enrichment parameters
7192 const hue_cos1 = -0.02833024015436984,
7193 hue_sin1 = -0.21131429516166544;
7194 const hue_cos2 = 0.2189784817615645,
7195 hue_sin2 = -0.06871898981942523;
7196 const hue_cos3 = 0.005506053349515315,
7197 hue_sin3 = -0.0641329861299175;
7198 const hue_cos4 = -0.053592461436994296,
7199 hue_sin4 = -0.00954137464208059;
7200 const hk_weight = 0.2676231133101982,
7201 hk_power = 0.8934892185255707;
7202 const hk_hue_mod = 0.7173169828841472;
7203 const hk_sin1 = 0.6915224124600773,
7204 hk_cos2 = 0.48647127559605596,
7205 hk_sin2 = 0.9853124591201782;
7206 const L_corr_p1 = 0.5385456675962418,
7207 L_corr_p2 = 0.12508858146241716,
7208 L_corr_p3 = 0.6768950256217603;
7209 const Lh_cos1 = -0.4963251525324449,
7210 Lh_sin1 = -0.09564696283240552;
7211 const lp_dark = -0.029053748937210654,
7212 lp_dark_hcos = 1.3346761652952872,
7213 lp_dark_hsin = -0.1698908144723919;
7214 const cs_cos1 = -0.195370576218515,
7215 cs_sin1 = 0.5330819227283227;
7216 const cs_cos2 = 0.08863325582067766,
7217 cs_sin2 = 0.9365540137751136;
7218 const cs_cos3 = 0.13789738139719568,
7219 cs_sin3 = 0.061650260197979936;
7220 const cs_cos4 = 0.0641970862504494,
7221 cs_sin4 = -0.027401052793571013;
7222 const cp_cos1 = -0.09900209889026965,
7223 cp_sin1 = 0.059635520647228726;
7224 const cp_cos2 = -0.013586499967803128,
7225 cp_sin2 = 0.2253393118474472;
7226 const lc1 = -1.5239477450767043,
7227 lc2 = -1.751157310240011;
7228 const hlc_cos1 = -0.43576378069144767,
7229 hlc_sin1 = 1.060094063845983;
7230 const hlc_cos2 = 0.47931193034584496,
7231 hlc_sin2 = -0.2622579649434462;
7232 const hl_cos1 = 0.13610794232685908,
7233 hl_sin1 = 0.1168702235362288;
7234 const hl_cos2 = -0.01617739641422492,
7235 hl_sin2 = 0.038145638815030566;
7236
7237 // Rigid rotation φ = −28.2°
7238 const PHI = -28.2 * PI / 180;
7239 const ROT_COS = cos(PHI);
7240 const ROT_SIN = sin(PHI);
7241
7242 // ── Pipeline helper functions ──────────────────────────────────────
7243
7244 function hueDelta(h) {
7245 return hue_cos1 * cos(h) + hue_sin1 * sin(h) + hue_cos2 * cos(2 * h) + hue_sin2 * sin(2 * h) + hue_cos3 * cos(3 * h) + hue_sin3 * sin(3 * h) + hue_cos4 * cos(4 * h) + hue_sin4 * sin(4 * h);
7246 }
7247 function hueDeltaDeriv(h) {
7248 return -hue_cos1 * sin(h) + hue_sin1 * cos(h) + -2 * hue_cos2 * sin(2 * h) + 2 * hue_sin2 * cos(2 * h) + -3 * hue_cos3 * sin(3 * h) + 3 * hue_sin3 * cos(3 * h) + -4 * hue_cos4 * sin(4 * h) + 4 * hue_sin4 * cos(4 * h);
7249 }
7250 function chromaScaleH(h) {
7251 let logS = cs_cos1 * cos(h) + cs_sin1 * sin(h) + cs_cos2 * cos(2 * h) + cs_sin2 * sin(2 * h) + cs_cos3 * cos(3 * h) + cs_sin3 * sin(3 * h) + cs_cos4 * cos(4 * h) + cs_sin4 * sin(4 * h);
7252 return exp(logS);
7253 }
7254 function lChromaScale(L) {
7255 let dL = L - 0.5;
7256 return exp(clamp(-30, lc1 * dL + lc2 * dL * dL, 30));
7257 }
7258 function hlcScale(h, L) {
7259 let hueFactor = hlc_cos1 * cos(h) + hlc_sin1 * sin(h) + hlc_cos2 * cos(2 * h) + hlc_sin2 * sin(2 * h);
7260 return exp(clamp(-30, (L - 0.5) * hueFactor, 30));
7261 }
7262 function hueLightnessScale(h) {
7263 let logS = hl_cos1 * cos(h) + hl_sin1 * sin(h) + hl_cos2 * cos(2 * h) + hl_sin2 * sin(2 * h);
7264 return exp(logS);
7265 }
7266 function chromaPowerH(h) {
7267 return 1 + cp_cos1 * cos(h) + cp_sin1 * sin(h) + cp_cos2 * cos(2 * h) + cp_sin2 * sin(2 * h);
7268 }
7269 function lCorrectFwd(L, h) {
7270 let t = L * (1 - L);
7271 let result = L + L_corr_p1 * t + L_corr_p2 * t * (0.5 - L) + L_corr_p3 * t * t;
7272 result += t * (Lh_cos1 * cos(h) + Lh_sin1 * sin(h));
7273 return result;
7274 }
7275 function lCorrectInv(L1, h) {
7276 let Lh = Lh_cos1 * cos(h) + Lh_sin1 * sin(h);
7277 let L = L1;
7278 for (let i = 0; i < 15; i++) {
7279 let t = L * (1 - L);
7280 let dt = 1 - 2 * L;
7281 let f = L + (L_corr_p1 + Lh) * t + L_corr_p2 * t * (0.5 - L) + L_corr_p3 * t * t - L1;
7282 let dfdL = 1 + (L_corr_p1 + Lh) * dt + L_corr_p2 * (dt * (0.5 - L) - t) + L_corr_p3 * 2 * t * dt;
7283 if (abs(dfdL) < 1e-10) {
7284 dfdL = 1;
7285 }
7286 L -= f / dfdL;
7287 }
7288 return L;
7289 }
7290 function darkLFwd(L, h) {
7291 let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h);
7292 let oml = L < 1 ? 1 - L : 0; // clamp at L=1: identity for L≥1
7293 let g = coeff * L * oml * oml;
7294 return L * exp(clamp(-30, g, 30));
7295 }
7296 function darkLInv(Ln, h) {
7297 let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h);
7298 let L = Ln;
7299 for (let i = 0; i < 12; i++) {
7300 let oml = L < 1 ? 1 - L : 0;
7301 let g = coeff * L * oml * oml;
7302 let eg = exp(clamp(-30, g, 30));
7303 let f = L * eg - Ln;
7304 let gp = coeff * oml * (1 - 3 * L);
7305 let fp = eg * (1 + L * gp);
7306 if (abs(fp) < 1e-10) {
7307 fp = 1;
7308 }
7309 L -= f / fp;
7310 }
7311 return L;
7312 }
7313
7314 // ── Color space definition ─────────────────────────────────────────
7315 // Helmlab MetricSpace is the perceptual forward space behind `deltaEHelmlab`.
7316 // Its coordinate system is shaped to maximize ΔE prediction accuracy on
7317 // visual-difference datasets (COMBVD: BFD-P, Witt 1999, RIT-DuPont, Leeds),
7318 // not author convenience. As a result:
7319 // - the ab plane is asymmetric (the metric was fit to directionally
7320 // asymmetric human discrimination thresholds);
7321 // - the L axis exceeds 1 for highly chromatic colors because the
7322 // Helmholtz–Kohlrausch boost is modeled explicitly (high-chroma colors
7323 // appear brighter than equiluminant neutrals);
7324 // - the achromatic axis is not pinned to (0, 0) — the gray axis sits
7325 // slightly off-origin in this coordinate system. Distance is
7326 // translation-invariant, so this does not affect ΔE quality.
7327 //
7328 // For CSS-author-facing color authoring (palettes, gradients, gamut
7329 // mapping), use HelmGen (`helmgen`) instead. This space (`helmlab-metric`)
7330 // is exposed primarily so the metric forward is inspectable for
7331 // debugging, color-science exploration, and as the internal forward used
7332 // by `deltaEHelmlab`.
7333
7334 const fromXYZ = function (xyz) {
7335 // Stage 0: Chromatic adaptation (Color.js D65 → Helmlab D65)
7336 let adapted = multiply_v3_m3x3(xyz, CAT_TO_HELM);
7337
7338 // Stage 1: XYZ → LMS (M1)
7339 let [lms0, lms1, lms2] = multiply_v3_m3x3(adapted, M1$1);
7340
7341 // Stage 2: Power compression (signed)
7342 let c0 = spow(lms0, GAMMA[0]);
7343 let c1 = spow(lms1, GAMMA[1]);
7344 let c2 = spow(lms2, GAMMA[2]);
7345
7346 // Stage 3: LMS_c → Lab_raw (M2)
7347 let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M2$1);
7348
7349 // Stage 3.5: Hue correction (4-harmonic Fourier)
7350 let h = atan2(b, a);
7351 let C = sqrt(a * a + b * b);
7352 let delta = hueDelta(h);
7353 let hNew = h + delta;
7354 a = C * cos(hNew);
7355 b = C * sin(hNew);
7356
7357 // Stage 3.7: Helmholtz-Kohlrausch correction
7358 let Cr = sqrt(a * a + b * b);
7359 let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10));
7360 let hr = atan2(b, a);
7361 let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) + hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr);
7362 L += hkBoost * factor;
7363
7364 // Stage 4: Cubic L correction (with hue modulation)
7365 h = atan2(b, a);
7366 L = lCorrectFwd(L, h);
7367
7368 // Stage 4.5: Dark L compression
7369 h = atan2(b, a);
7370 L = darkLFwd(L, h);
7371
7372 // Stage 5: Hue-dependent chroma scaling
7373 h = atan2(b, a);
7374 let cs = chromaScaleH(h);
7375 a *= cs;
7376 b *= cs;
7377
7378 // Stage 5.5: Nonlinear chroma power
7379 h = atan2(b, a);
7380 C = sqrt(a * a + b * b);
7381 let p = chromaPowerH(h);
7382 let Cn = C > 0 ? pow(C, p) : 0;
7383 a = Cn * cos(h);
7384 b = Cn * sin(h);
7385
7386 // Stage 6: L-dependent chroma scaling
7387 let T = lChromaScale(L);
7388 a *= T;
7389 b *= T;
7390
7391 // Stage 6.5: HLC interaction
7392 h = atan2(b, a);
7393 let hlcS = hlcScale(h, L);
7394 a *= hlcS;
7395 b *= hlcS;
7396
7397 // Stage 8: Hue-dependent lightness scaling
7398 h = atan2(b, a);
7399 L *= hueLightnessScale(h);
7400
7401 // Stage 11: Rigid rotation (φ = −28.2°)
7402 let aRot = a * ROT_COS - b * ROT_SIN;
7403 let bRot = a * ROT_SIN + b * ROT_COS;
7404 return [L, aRot, bRot];
7405 };
7406 const toXYZ = function (lab) {
7407 let [L, a, b] = lab;
7408
7409 // Undo Stage 11: rotation
7410 let aUn = a * ROT_COS + b * ROT_SIN;
7411 let bUn = -a * ROT_SIN + b * ROT_COS;
7412 a = aUn;
7413 b = bUn;
7414
7415 // Undo Stage 8: hue-dep lightness
7416 let h = atan2(b, a);
7417 L /= hueLightnessScale(h);
7418
7419 // Undo Stage 6.5: HLC
7420 h = atan2(b, a);
7421 let hlcS = hlcScale(h, L);
7422 a /= hlcS;
7423 b /= hlcS;
7424
7425 // Undo Stage 6: L-dep chroma
7426 let T = lChromaScale(L);
7427 a /= T;
7428 b /= T;
7429
7430 // Undo Stage 5.5: chroma power
7431 h = atan2(b, a);
7432 let C = sqrt(a * a + b * b);
7433 let p = chromaPowerH(h);
7434 let Co = C > 0 ? pow(C, 1 / p) : 0;
7435 a = Co * cos(h);
7436 b = Co * sin(h);
7437
7438 // Undo Stage 5: chroma scaling
7439 h = atan2(b, a);
7440 let cs = chromaScaleH(h);
7441 a /= cs;
7442 b /= cs;
7443
7444 // Undo Stage 4.5: dark L
7445 h = atan2(b, a);
7446 L = darkLInv(L, h);
7447
7448 // Undo Stage 4: cubic L
7449 h = atan2(b, a);
7450 L = lCorrectInv(L, h);
7451
7452 // Undo Stage 3.7: H-K
7453 let Cr = sqrt(a * a + b * b);
7454 let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10));
7455 let hr = atan2(b, a);
7456 let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) + hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr);
7457 L -= hkBoost * factor;
7458
7459 // Undo Stage 3.5: hue correction (Newton iteration)
7460 let hOut = atan2(b, a);
7461 C = sqrt(a * a + b * b);
7462 let hRaw = hOut;
7463 for (let i = 0; i < 8; i++) {
7464 let f = hRaw + hueDelta(hRaw) - hOut;
7465 let fp = 1 + hueDeltaDeriv(hRaw);
7466 if (abs(fp) < 1e-10) {
7467 fp = 1;
7468 }
7469 hRaw -= f / fp;
7470 }
7471 a = C * cos(hRaw);
7472 b = C * sin(hRaw);
7473
7474 // Undo Stage 3: Lab → LMS_c (M2_inv)
7475 let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M2_INV$1);
7476
7477 // Undo Stage 2: power compression
7478 let l0 = spow(lc0, INV_GAMMA[0]);
7479 let l1 = spow(lc1, INV_GAMMA[1]);
7480 let l2 = spow(lc2, INV_GAMMA[2]);
7481
7482 // Undo Stage 1: LMS → XYZ (M1_inv)
7483 let xyz = multiply_v3_m3x3([l0, l1, l2], M1_INV$1);
7484
7485 // Undo Stage 0: Chromatic adaptation (Helmlab D65 → Color.js D65)
7486 return multiply_v3_m3x3(xyz, CAT_FROM_HELM);
7487 };
7488 var helmlab = new ColorSpace({
7489 id: "helmlab-metric",
7490 name: "Helmlab MetricSpace",
7491 cssId: "--helmlab-metric",
7492 coords: {
7493 l: {
7494 refRange: [0, 1.6],
7495 name: "Lightness"
7496 },
7497 a: {
7498 refRange: [-1.5, 1.5]
7499 },
7500 b: {
7501 refRange: [-1.5, 1.5]
7502 }
7503 },
7504 white: "D65",
7505 base: XYZ_D65,
7506 fromBase(xyz) {
7507 return fromXYZ(xyz);
7508 },
7509 toBase(lab) {
7510 return toXYZ(lab);
7511 }
7512 });
7513
7514 // Helmlab MetricSpace weighted distance (v21, 72 params).
7515 // Optimized on COMBVD human color-difference judgments.
7516 //
7517 // Formula:
7518 // SL = 1 + sl * (L_avg - 0.5)²
7519 // SC = 1 + sc * C_avg
7520 // raw = (ΔL²/SL² + wC * Δab²/SC²) ^ (p/2)
7521 // compressed = raw / (1 + c * raw)
7522 // ΔE = compressed ^ q
7523
7524 const sl = -0.9155125151657894;
7525 const sc = 2.9268353744941558;
7526 const wC = 3.966003089807536;
7527 const p = 1.9737081170404969;
7528 const compress = 52.473130649294724;
7529 const q = 0.47897301074925214;
7530
7531 /**
7532 * @param {import("../types.js").ColorTypes} color
7533 * @param {import("../types.js").ColorTypes} sample
7534 * @returns {number}
7535 */
7536 function deltaEHelmlab (color, sample) {
7537 [color, sample] = getColor([color, sample]);
7538 let [L1, a1, b1] = helmlab.from(color);
7539 let [L2, a2, b2] = helmlab.from(sample);
7540 let ΔL = L1 - L2;
7541 let Δa = a1 - a2;
7542 let Δb = b1 - b2;
7543
7544 // Pair-dependent weighting
7545 let Lavg = (L1 + L2) * 0.5;
7546 let SL = 1 + sl * (Lavg - 0.5) ** 2;
7547 let C1 = Math.sqrt(a1 ** 2 + b1 ** 2);
7548 let C2 = Math.sqrt(a2 ** 2 + b2 ** 2);
7549 let Cavg = (C1 + C2) * 0.5;
7550 let SC = 1 + sc * Cavg;
7551
7552 // Weighted Minkowski distance
7553 let raw = (ΔL ** 2 / SL ** 2 + wC * (Δa ** 2 + Δb ** 2) / SC ** 2) ** (p / 2);
7554
7555 // Monotonic compression
7556 let compressed = raw / (1 + compress * raw);
7557 return compressed ** q;
7558 }
7559
7560 /**
7561 * @packageDocumentation
7562 * This module defines all the builtin deltaE methods.
7563 */
7564 var deltaEMethods = {
7565 deltaE76,
7566 deltaECMC,
7567 deltaE2000,
7568 deltaEJz,
7569 deltaEITP,
7570 deltaEOK,
7571 deltaEOK2,
7572 deltaEHCT,
7573 deltaEHelmlab
7574 };
7575
7576 /** @typedef {keyof typeof import("./index.js").default extends `deltaE${infer Method}` ? Method : string} Methods */
7577
7578 /** @import { ColorTypes, PlainColorObject } from "./types.js" */
7579
7580 // Type re-exports
7581 /** @typedef {import("./types.js").ToGamutOptions} ToGamutOptions */
7582
7583 /**
7584 * Calculate the epsilon to 2 degrees smaller than the specified JND.
7585 * @param {number} jnd The target "just noticeable difference".
7586 * @returns {number}
7587 */
7588 function calcEpsilon(jnd) {
7589 // Calculate the epsilon to 2 degrees smaller than the specified JND.
7590
7591 const order = !jnd ? 0 : Math.floor(Math.log10(Math.abs(jnd)));
7592 // Limit to an arbitrary value to ensure value is never too small and causes infinite loops.
7593 return Math.max(parseFloat(`1e${order - 2}`), 1e-6);
7594 }
7595 const GMAPPRESET = {
7596 hct: {
7597 method: "hct.c",
7598 jnd: 2,
7599 deltaEMethod: "hct",
7600 blackWhiteClamp: {}
7601 },
7602 "hct-tonal": {
7603 method: "hct.c",
7604 jnd: 0,
7605 deltaEMethod: "hct",
7606 blackWhiteClamp: {
7607 channel: "hct.t",
7608 min: 0,
7609 max: 100
7610 }
7611 }
7612 };
7613
7614 /**
7615 * Force coordinates to be in gamut of a certain color space.
7616 * Mutates the color it is passed.
7617 * @overload
7618 * @param {ColorTypes} color
7619 * @param {ToGamutOptions} [options]
7620 * @returns {PlainColorObject}
7621 */
7622 /**
7623 * @overload
7624 * @param {ColorTypes} color
7625 * @param {string} [space]
7626 * @returns {PlainColorObject}
7627 */
7628 /**
7629 * @param {ColorTypes} color
7630 * @param {string & Partial<ToGamutOptions> | ToGamutOptions} [space]
7631 * @returns {PlainColorObject}
7632 */
7633 function toGamut(color, {
7634 method = defaults.gamut_mapping,
7635 space = undefined,
7636 deltaEMethod = "",
7637 jnd = 2,
7638 blackWhiteClamp = undefined,
7639 min = undefined,
7640 max = undefined
7641 } = {}) {
7642 color = getColor(color);
7643 if (isString(arguments[1])) {
7644 space = arguments[1];
7645 } else if (!space) {
7646 space = color.space;
7647 }
7648 space = ColorSpace.get(space);
7649
7650 // 3 spaces:
7651 // color.space: current color space
7652 // space: space whose gamut we are mapping to
7653 // mapSpace: space with the coord we're reducing
7654
7655 if (inGamut(color, space, {
7656 epsilon: 0
7657 })) {
7658 return /** @type {PlainColorObject} */color;
7659 }
7660 let spaceColor;
7661 if (method === "css") {
7662 spaceColor = toGamutCSS(color, {
7663 space
7664 });
7665 } else if (method === "raytrace") {
7666 spaceColor = toGamutRayTrace(color, {
7667 space
7668 });
7669 } else {
7670 if (method !== "clip") {
7671 if (Object.prototype.hasOwnProperty.call(GMAPPRESET, method)) {
7672 ({
7673 method,
7674 jnd,
7675 deltaEMethod,
7676 blackWhiteClamp
7677 } = GMAPPRESET[method]);
7678 }
7679
7680 // Get the correct delta E method
7681 let de = deltaE2000;
7682 if (deltaEMethod !== "") {
7683 for (let m in deltaEMethods) {
7684 if ("deltae" + deltaEMethod.toLowerCase() === m.toLowerCase()) {
7685 de = deltaEMethods[m];
7686 break;
7687 }
7688 }
7689 }
7690 if (jnd === 0) {
7691 jnd = 1e-16;
7692 }
7693 let clipped = toGamut(to(color, space), {
7694 method: "clip",
7695 space
7696 });
7697 if (de(color, clipped) > jnd) {
7698 var _min;
7699 // Clamp to SDR white and black if required
7700 if (blackWhiteClamp && Object.keys(blackWhiteClamp).length === 3) {
7701 let channelMeta = ColorSpace.resolveCoord(blackWhiteClamp.channel);
7702 let channel = get(to(color, channelMeta.space), channelMeta.id);
7703 if (isNone(channel)) {
7704 channel = 0;
7705 }
7706 if (channel >= blackWhiteClamp.max) {
7707 return to({
7708 space: "xyz-d65",
7709 coords: WHITES["D65"]
7710 }, color.space);
7711 } else if (channel <= blackWhiteClamp.min) {
7712 return to({
7713 space: "xyz-d65",
7714 coords: [0, 0, 0]
7715 }, color.space);
7716 }
7717 }
7718
7719 // Reduce a coordinate of a certain color space until the color is in gamut
7720 let coordMeta = ColorSpace.resolveCoord(method);
7721 let mapSpace = coordMeta.space;
7722 let coordId = coordMeta.id;
7723 let mappedColor = to(color, mapSpace);
7724 // If we were already in the mapped color space, we need to resolve undefined channels
7725 mappedColor.coords.forEach((c, i) => {
7726 if (isNone(c)) {
7727 mappedColor.coords[i] = 0;
7728 }
7729 });
7730 let bounds = coordMeta.range || coordMeta.refRange;
7731 (_min = min) !== null && _min !== void 0 ? _min : min = bounds[0];
7732 let ε = calcEpsilon(jnd);
7733 let low = min;
7734 let high = Math.min(get(mappedColor, coordId), max !== null && max !== void 0 ? max : Infinity);
7735 set(mappedColor, coordId, high);
7736 while (high - low > ε) {
7737 let clipped = clone(mappedColor);
7738 clipped = toGamut(clipped, {
7739 space,
7740 method: "clip"
7741 });
7742 let deltaE = de(mappedColor, clipped);
7743 if (deltaE - jnd < ε) {
7744 low = get(mappedColor, coordId);
7745 } else {
7746 high = get(mappedColor, coordId);
7747 }
7748 set(mappedColor, coordId, (low + high) / 2);
7749 }
7750 spaceColor = to(mappedColor, space);
7751 } else {
7752 spaceColor = clipped;
7753 }
7754 } else {
7755 spaceColor = to(color, space);
7756 }
7757 if (method === "clip" ||
7758 // Dumb coord clipping
7759 // finish off smarter gamut mapping with clip to get rid of ε, see #17
7760 !inGamut(spaceColor, space, {
7761 epsilon: 0
7762 })) {
7763 let bounds = Object.values(space.coords).map(c => c.range || []);
7764 spaceColor.coords = /** @type {[number, number, number]} */
7765 spaceColor.coords.map((c, i) => {
7766 let [min, max] = bounds[i];
7767 if (min !== undefined) {
7768 c = Math.max(min, c);
7769 }
7770 if (max !== undefined) {
7771 c = Math.min(c, max);
7772 }
7773 return c;
7774 });
7775 }
7776 }
7777 if (space !== color.space) {
7778 spaceColor = to(spaceColor, color.space);
7779 }
7780 color.coords = spaceColor.coords;
7781 return /** @type {PlainColorObject} */color;
7782 }
7783
7784 /** @type {"color"} */
7785 toGamut.returns = "color";
7786
7787 /**
7788 * The reference colors to be used if lightness is out of the range 0-1 in the
7789 * `Oklch` space. These are created in the `Oklab` space, as it is used by the
7790 * DeltaEOK calculation, so it is guaranteed to be imported.
7791 * @satisfies {Record<string, ColorTypes>}
7792 */
7793 const COLORS = {
7794 WHITE: {
7795 space: Oklab,
7796 coords: [1, 0, 0],
7797 alpha: 1
7798 },
7799 BLACK: {
7800 space: Oklab,
7801 coords: [0, 0, 0],
7802 alpha: 1
7803 }
7804 };
7805
7806 /**
7807 * Given a color `origin`, returns a new color that is in gamut using
7808 * the CSS Gamut Mapping Algorithm. If `space` is specified, it will be in gamut
7809 * in `space`, and returned in `space`. Otherwise, it will be in gamut and
7810 * returned in the color space of `origin`.
7811 * @param {ColorTypes} origin
7812 * @param {{ space?: string | ColorSpace | undefined }} options
7813 * @returns {PlainColorObject}
7814 */
7815 function toGamutCSS(origin, {
7816 space
7817 } = {}) {
7818 const JND = 0.02;
7819 const ε = 0.0001;
7820 origin = getColor(origin);
7821 if (!space) {
7822 space = origin.space;
7823 }
7824 space = ColorSpace.get(space);
7825 if (space.isUnbounded) {
7826 return to(origin, space);
7827 }
7828 const origin_OKLCH = to(origin, OKLCH);
7829 let L = origin_OKLCH.coords[0];
7830
7831 // return media white or black, if lightness is out of range
7832 if (L >= 1) {
7833 const white = to(COLORS.WHITE, space);
7834 white.alpha = origin.alpha;
7835 return to(white, space);
7836 }
7837 if (L <= 0) {
7838 const black = to(COLORS.BLACK, space);
7839 black.alpha = origin.alpha;
7840 return to(black, space);
7841 }
7842 if (inGamut(origin_OKLCH, space, {
7843 epsilon: 0
7844 })) {
7845 return to(origin_OKLCH, space);
7846 }
7847 function clip(_color) {
7848 const destColor = to(_color, space);
7849 const spaceCoords = Object.values(/** @type {ColorSpace} */space.coords);
7850 destColor.coords = /** @type {[number, number, number]} */
7851 destColor.coords.map((coord, index) => {
7852 if ("range" in spaceCoords[index]) {
7853 const [min, max] = spaceCoords[index].range;
7854 return clamp(min, coord, max);
7855 }
7856 return coord;
7857 });
7858 return destColor;
7859 }
7860 let min = 0;
7861 let max = origin_OKLCH.coords[1];
7862 let min_inGamut = true;
7863 let current = clone(origin_OKLCH);
7864 let clipped = clip(current);
7865 let E = deltaEOK(clipped, current);
7866 if (E < JND) {
7867 return clipped;
7868 }
7869 while (max - min > ε) {
7870 const chroma = (min + max) / 2;
7871 current.coords[1] = chroma;
7872 if (min_inGamut && inGamut(current, space, {
7873 epsilon: 0
7874 })) {
7875 min = chroma;
7876 } else {
7877 clipped = clip(current);
7878 E = deltaEOK(clipped, current);
7879 if (E < JND) {
7880 if (JND - E < ε) {
7881 break;
7882 } else {
7883 min_inGamut = false;
7884 min = chroma;
7885 }
7886 } else {
7887 max = chroma;
7888 }
7889 }
7890 }
7891 return clipped;
7892 }
7893
7894 /**
7895 * Given `start` and `end` coordinates of a 3D ray and a `bmin` and `bmax` bounding box,
7896 * find the intersection of the ray and box. Return an empty list if no intersect is found.`
7897 * @param {[number, number, number]} start
7898 * @param {[number, number, number]} end
7899 * @param {[number, number, number]} bmin
7900 * @param {[number, number, number]} bmax
7901 * @returns {[number, number, number] | []}
7902 */
7903 function raytrace_box(start, end, bmin = [0, 0, 0], bmax = [1, 1, 1]) {
7904 // Use slab method to detect intersection of ray and box and return intersect.
7905 // https://en.wikipedia.org/wiki/Slab_method
7906
7907 // Calculate whether there was a hit
7908 let tfar = Infinity;
7909 let tnear = -Infinity;
7910 let direction = [];
7911 for (let i = 0; i < 3; i++) {
7912 const a = start[i];
7913 const b = end[i];
7914 const d = b - a;
7915 const bn = bmin[i];
7916 const bx = bmax[i];
7917 direction.push(d);
7918
7919 // Non parallel cases
7920 if (Math.abs(d) > 1e-12) {
7921 const inv_d = 1 / d;
7922 const t1 = (bn - a) * inv_d;
7923 const t2 = (bx - a) * inv_d;
7924 tnear = Math.max(Math.min(t1, t2), tnear);
7925 tfar = Math.min(Math.max(t1, t2), tfar);
7926 }
7927
7928 // Impossible parallel case
7929 else if (a < bn || a > bx) {
7930 return [];
7931 }
7932 }
7933
7934 // No hit
7935 if (tnear > tfar || tfar < 0) {
7936 return [];
7937 }
7938
7939 // Favor the intersection first in the direction start -> end
7940 if (tnear < 0) {
7941 tnear = tfar;
7942 }
7943
7944 // A point, or something approaching a single point where start and end are the same.
7945 if (!isFinite(tnear)) {
7946 return [];
7947 }
7948
7949 // Calculate nearest intersection via interpolation
7950 return [start[0] + direction[0] * tnear, start[1] + direction[1] * tnear, start[2] + direction[2] * tnear];
7951 }
7952
7953 /**
7954 * Given a color `origin`, returns a new color that is in gamut using
7955 * the CSS Ray Trace Gamut Mapping Algorithm. If `space` is specified,
7956 * it will be in gamut `space`, and returned in `space`. Otherwise,
7957 * it will be in gamut and returned in the color space of `origin`.
7958 * @param {ColorTypes} origin
7959 * @param {{ space?: string | ColorSpace | undefined }} options
7960 * @returns {PlainColorObject}
7961 */
7962 function toGamutRayTrace(origin, {
7963 space
7964 } = {}) {
7965 origin = getColor(origin);
7966 if (!space) {
7967 space = origin.space;
7968 }
7969 space = ColorSpace.get(space);
7970
7971 // If the space is already in gamut, stop.
7972 if (space.isUnbounded) {
7973 return to(origin, space);
7974 }
7975
7976 // Get the OkLCh coordinates.
7977 let oklchOrigin = to(origin, OKLCH);
7978 let [lightness, chroma, hue] = oklchOrigin.coords;
7979
7980 // Return white or black if color's lightness exceeds the SDR range.
7981 if (lightness >= 1) {
7982 const white = to(COLORS.WHITE, space);
7983 white.alpha = origin.alpha;
7984 return to(white, space);
7985 } else if (lightness <= 0) {
7986 const black = to(COLORS.BLACK, space);
7987 black.alpha = origin.alpha;
7988 return to(black, space);
7989 }
7990
7991 // Get a copy of the origin color as the RGB target space.
7992 const originSpace = space;
7993 const rGamut = space.rgbGamut;
7994 if (rGamut !== undefined) {
7995 space = rGamut;
7996 }
7997 if (!isInstance(space, RGBColorSpace)) {
7998 throw Error("An RGB gamut is required");
7999 }
8000
8001 // Get SDR bounds. Some HDR spaces have headroom, so reduce max to SDR range.
8002 let [mn, mx] = Object.values(space.coords)[0].range;
8003 let max = /** @type {[number, number, number]} */[mx, mx, mx];
8004
8005 // See if we have a linear version of the color space
8006 const lGamut = space.linearGamut;
8007 if (lGamut !== undefined) {
8008 // Recalculate minimum and maximum relative to the linear space
8009 let temp = to({
8010 space: space,
8011 coords: max,
8012 alpha: origin.alpha
8013 }, lGamut);
8014 mx = temp.coords[0];
8015 max = /** @type {[number, number, number]} */[mx, mx, mx];
8016 space = lGamut;
8017 mn = Object.values(space.coords)[0].range[0];
8018 }
8019 let min = /** @type {[number, number, number]} */[mn, mn, mn];
8020 let rgbOrigin = to(oklchOrigin, space);
8021 if (!rgbOrigin.coords.every(x => mn <= x && x <= mx)) {
8022 // If this were performed within a perceptual space like CAM16, which has achromatics that do not align
8023 // with the RGB achromatic line, projecting the color onto the RGB achromatic line may be preferable,
8024 // but since OkLCh's achromatics align with all CSS RGB spaces, just set chroma to zero.
8025 let anchor = to({
8026 space: OKLCH,
8027 coords: [lightness, 0, hue]
8028 }, space).coords;
8029
8030 // Calculate bounds to adjust the anchor closer to the gamut surface.
8031 // We don't want to make the ray too short, so offset some amount from the low and high range.
8032 const low = mn + 1e-6;
8033 const high = mx - 1e-6;
8034
8035 // Cast a ray from the zero chroma color to the target color.
8036 // Trace the line to the RGB cube edge and find where it intersects.
8037 // Correct L and h within the perceptual OkLCh after each attempt.
8038 let last = rgbOrigin.coords;
8039 for (let i = 0; i < 4; i++) {
8040 if (i) {
8041 // For constant luminance, we correct the color by simply setting lightness and hue to
8042 // match the original color. In a non constant luminance reduction, it is better to
8043 // project the color onto the reduction path vector.
8044 const oklchColor = to(rgbOrigin, OKLCH);
8045 oklchColor.coords[0] = lightness;
8046 oklchColor.coords[2] = hue;
8047 rgbOrigin = to(oklchColor, space);
8048 }
8049 // Cast a ray from the achromatic anchor to the RGB target and find the gamut intersection.
8050 const intersection = raytrace_box(anchor, rgbOrigin.coords, min, max);
8051
8052 // If we cannot find an intersection, reset to last successful iteration of the color.
8053 // In OkLCh, this is only likely to happen if our ray gets too small, in that case, it is time to stop.
8054 if (intersection.length === 0) {
8055 rgbOrigin.coords = [...last];
8056 break;
8057 }
8058
8059 // Adjust anchor point closer to surface, when possible, to improve results for some spaces.
8060 if (i && rgbOrigin.coords.every(x => low < x && x < high)) {
8061 anchor = [...rgbOrigin.coords];
8062 }
8063
8064 // If we have an intersection, update the color.
8065 last = /** @type {[number, number, number]} */intersection;
8066 rgbOrigin.coords = [...intersection];
8067 }
8068 }
8069
8070 // Convert to the original, specified gamut
8071 rgbOrigin = to(rgbOrigin, originSpace);
8072 const spaceCoords = Object.values(/** @type {ColorSpace} */originSpace.coords);
8073
8074 // Remove noise from floating point math by clipping
8075 rgbOrigin.coords = /** @type {[number, number, number]} */
8076 rgbOrigin.coords.map((coord, index) => {
8077 if ("range" in spaceCoords[index]) {
8078 const [lower, upper] = spaceCoords[index].range;
8079 return clamp(lower, coord, upper);
8080 }
8081 return coord;
8082 });
8083 return rgbOrigin;
8084 }
8085
8086 /** @import { ColorTypes, PlainColorObject, ToGamutOptions } from "./types.js" */
8087
8088 /**
8089 * Convert to color space and return a new color
8090 * @param {ColorTypes} color
8091 * @param {string | ColorSpace} space
8092 * @param {{ inGamut?: boolean | ToGamutOptions | undefined }} options
8093 * @returns {PlainColorObject}
8094 */
8095 function to(color, space, {
8096 inGamut
8097 } = {}) {
8098 color = getColor(color);
8099 space = ColorSpace.get(space);
8100 let coords = space.from(color);
8101 let ret = {
8102 space,
8103 coords,
8104 alpha: color.alpha
8105 };
8106 if (inGamut) {
8107 ret = toGamut(ret, inGamut === true ? undefined : inGamut);
8108 }
8109 return ret;
8110 }
8111
8112 /** @type {"color"} */
8113 to.returns = "color";
8114
8115 /** @import { ColorTypes, ParseOptions, PlainColorObject } from "./types.js" */
8116
8117 // Type re-exports
8118 /** @typedef {import("./types.js").SerializeOptions} SerializeOptions */
8119
8120 /**
8121 * Generic toString() method, outputs a color(spaceId ...coords) function, a functional syntax, or custom formats defined by the color space
8122 * @param {ColorTypes} color
8123 * @param {SerializeOptions & Record<string, any>} options
8124 * @returns {string}
8125 */
8126 function serialize(color, options = {}) {
8127 let {
8128 precision = defaults.precision,
8129 format,
8130 inGamut: inGamut$1 = true,
8131 coords: coordFormat,
8132 alpha: alphaFormat,
8133 commas
8134 } = options;
8135 let ret;
8136 let colorWithMeta = /** @type {PlainColorObject & ParseOptions} */getColor(color);
8137 let formatId = format;
8138 let parseMeta = colorWithMeta.parseMeta;
8139 if (parseMeta && !format) {
8140 var _coordFormat, _alphaFormat, _commas;
8141 if (parseMeta.format.canSerialize()) {
8142 format = parseMeta.format;
8143 formatId = parseMeta.formatId;
8144 }
8145 (_coordFormat = coordFormat) !== null && _coordFormat !== void 0 ? _coordFormat : coordFormat = parseMeta.types;
8146 (_alphaFormat = alphaFormat) !== null && _alphaFormat !== void 0 ? _alphaFormat : alphaFormat = parseMeta.alphaType;
8147 (_commas = commas) !== null && _commas !== void 0 ? _commas : commas = parseMeta.commas;
8148 }
8149 if (formatId) {
8150 var _colorWithMeta$space$;
8151 // A format is explicitly specified
8152 format = (_colorWithMeta$space$ = colorWithMeta.space.getFormat(format)) !== null && _colorWithMeta$space$ !== void 0 ? _colorWithMeta$space$ : ColorSpace.findFormat(formatId);
8153 }
8154 if (!format) {
8155 var _colorWithMeta$space$2;
8156 // No format specified, or format not found
8157 format = (_colorWithMeta$space$2 = colorWithMeta.space.getFormat("default")) !== null && _colorWithMeta$space$2 !== void 0 ? _colorWithMeta$space$2 : ColorSpace.DEFAULT_FORMAT;
8158 formatId = format.name;
8159 }
8160 if (format && format.space && format.space !== colorWithMeta.space) {
8161 // Format specified belongs to a different color space,
8162 // need to convert to it first
8163 colorWithMeta = to(colorWithMeta, format.space);
8164 }
8165
8166 // The assignment to coords and inGamut needs to stay in the order they are now
8167 // The order of the assignment was changed as a workaround for a bug in Next.js
8168 // See this issue for details: https://github.com/color-js/color.js/issues/260
8169
8170 let coords = colorWithMeta.coords.slice(); // clone so we can manipulate it
8171
8172 inGamut$1 || (inGamut$1 = format.toGamut);
8173 if (inGamut$1 && !inGamut(colorWithMeta)) {
8174 // FIXME what happens if the color contains none values?
8175 coords = toGamut(clone(colorWithMeta), inGamut$1 === true ? undefined : inGamut$1).coords;
8176 }
8177 if (format.type === "custom") {
8178 if (format.serialize) {
8179 ret = format.serialize(coords, colorWithMeta.alpha, options);
8180 } else {
8181 throw new TypeError(`format ${formatId} can only be used to parse colors, not for serialization`);
8182 }
8183 } else {
8184 var _alphaFormat$type, _alphaFormat2, _alphaFormat3, _alphaFormat4, _commas2;
8185 // Functional syntax
8186 let name = format.name || "color";
8187 let args = format.serializeCoords(coords, precision, coordFormat);
8188 if (name === "color") {
8189 var _format$ids;
8190 // If output is a color() function, add colorspace id as first argument
8191 let cssId = format.id || ((_format$ids = format.ids) === null || _format$ids === void 0 ? void 0 : _format$ids[0]) || colorWithMeta.space.cssId || colorWithMeta.space.id;
8192 args.unshift(cssId);
8193 }
8194
8195 // Serialize alpha?
8196 /** @type {string | number} */
8197 let alpha = colorWithMeta.alpha;
8198 if (alphaFormat !== undefined && !(typeof alphaFormat === "object")) {
8199 alphaFormat = typeof alphaFormat === "string" ? {
8200 type: alphaFormat
8201 } : {
8202 include: alphaFormat
8203 };
8204 }
8205 let alphaType = (_alphaFormat$type = (_alphaFormat2 = alphaFormat) === null || _alphaFormat2 === void 0 ? void 0 : _alphaFormat2.type) !== null && _alphaFormat$type !== void 0 ? _alphaFormat$type : "<number>";
8206 let serializeAlpha = ((_alphaFormat3 = alphaFormat) === null || _alphaFormat3 === void 0 ? void 0 : _alphaFormat3.include) === true || format.alpha === true || ((_alphaFormat4 = alphaFormat) === null || _alphaFormat4 === void 0 ? void 0 : _alphaFormat4.include) !== false && format.alpha !== false && alpha < 1;
8207 let strAlpha = "";
8208 (_commas2 = commas) !== null && _commas2 !== void 0 ? _commas2 : commas = format.commas;
8209 if (serializeAlpha) {
8210 if (precision !== null) {
8211 let unit;
8212 if (alphaType === "<percentage>") {
8213 unit = "%";
8214 alpha *= 100;
8215 }
8216 alpha = serializeNumber(alpha, {
8217 precision,
8218 unit
8219 });
8220 }
8221 strAlpha = `${commas ? "," : " /"} ${alpha}`;
8222 }
8223 ret = `${name}(${args.join(commas ? ", " : " ")}${strAlpha})`;
8224 }
8225 return ret;
8226 }
8227
8228 var esnext_iterator_filter = {};
8229
8230 var es_iterator_filter = {};
8231
8232 var hasRequiredEs_iterator_filter;
8233
8234 function requireEs_iterator_filter () {
8235 if (hasRequiredEs_iterator_filter) return es_iterator_filter;
8236 hasRequiredEs_iterator_filter = 1;
8237 var $ = require_export();
8238 var call = requireFunctionCall();
8239 var aCallable = requireACallable();
8240 var anObject = requireAnObject();
8241 var getIteratorDirect = requireGetIteratorDirect();
8242 var createIteratorProxy = requireIteratorCreateProxy();
8243 var callWithSafeIterationClosing = requireCallWithSafeIterationClosing();
8244 var IS_PURE = requireIsPure();
8245
8246 var IteratorProxy = createIteratorProxy(function () {
8247 var iterator = this.iterator;
8248 var predicate = this.predicate;
8249 var next = this.next;
8250 var result, done, value;
8251 while (true) {
8252 result = anObject(call(next, iterator));
8253 done = this.done = !!result.done;
8254 if (done) return;
8255 value = result.value;
8256 if (callWithSafeIterationClosing(iterator, predicate, [value, this.counter++], true)) return value;
8257 }
8258 });
8259
8260 // `Iterator.prototype.filter` method
8261 // https://tc39.es/ecma262/#sec-iterator.prototype.filter
8262 $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
8263 filter: function filter(predicate) {
8264 anObject(this);
8265 aCallable(predicate);
8266 return new IteratorProxy(getIteratorDirect(this), {
8267 predicate: predicate
8268 });
8269 }
8270 });
8271 return es_iterator_filter;
8272 }
8273
8274 var hasRequiredEsnext_iterator_filter;
8275
8276 function requireEsnext_iterator_filter () {
8277 if (hasRequiredEsnext_iterator_filter) return esnext_iterator_filter;
8278 hasRequiredEsnext_iterator_filter = 1;
8279 // TODO: Remove from `core-js@4`
8280 requireEs_iterator_filter();
8281 return esnext_iterator_filter;
8282 }
8283
8284 requireEsnext_iterator_filter();
8285
8286 /** @import { Matrix3x3 } from "../types.js" */
8287
8288 // convert an array of linear-light rec2020 values to CIE XYZ
8289 // using D65 (no chromatic adaptation)
8290 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
8291 // 0 is actually calculated as 4.994106574466076e-17
8292 /** @type {Matrix3x3} */
8293 // prettier-ignore
8294 const toXYZ_M$5 = [[0.6369580483012914, 0.14461690358620832, 0.1688809751641721], [0.2627002120112671, 0.6779980715188708, 0.05930171646986196], [0.000000000000000, 0.028072693049087428, 1.060985057710791]];
8295
8296 // from ITU-R BT.2124-0 Annex 2 p.3
8297 /** @type {Matrix3x3} */
8298 // prettier-ignore
8299 const fromXYZ_M$5 = [[1.716651187971268, -0.355670783776392, -0.253366281373660], [-0.666684351832489, 1.616481236634939, 0.0157685458139111], [0.017639857445311, -0.042770613257809, 0.942103121235474]];
8300 var REC_2020_Linear = new RGBColorSpace({
8301 id: "rec2020-linear",
8302 cssId: "--rec2020-linear",
8303 name: "Linear REC.2020",
8304 white: "D65",
8305 toXYZ_M: toXYZ_M$5,
8306 fromXYZ_M: fromXYZ_M$5
8307 });
8308
8309 // import sRGB from "./srgb.js";
8310
8311 var REC2020 = new RGBColorSpace({
8312 id: "rec2020",
8313 name: "REC.2020",
8314 base: REC_2020_Linear,
8315 linearGamut: REC_2020_Linear,
8316 // Reference electro-optical transfer function from Rec. ITU-R BT.1886 Annex 1
8317 // with b (black lift) = 0 and a (user gain) = 1
8318 // defined over the extended range, not clamped
8319 toBase(RGB) {
8320 return RGB.map(function (val) {
8321 let sign = val < 0 ? -1 : 1;
8322 let abs = val * sign;
8323 return sign * Math.pow(abs, 2.4);
8324 });
8325 },
8326 fromBase(RGB) {
8327 return RGB.map(function (val) {
8328 let sign = val < 0 ? -1 : 1;
8329 let abs = val * sign;
8330 return sign * Math.pow(abs, 1 / 2.4);
8331 });
8332 }
8333 });
8334
8335 /** @import { Matrix3x3 } from "../types.js" */
8336
8337 /** @type {Matrix3x3} */
8338 // prettier-ignore
8339 const toXYZ_M$4 = [[0.4865709486482162, 0.26566769316909306, 0.1982172852343625], [0.2289745640697488, 0.6917385218365064, 0.079286914093745], [0.0000000000000000, 0.04511338185890264, 1.043944368900976]];
8340
8341 /** @type {Matrix3x3} */
8342 // prettier-ignore
8343 const fromXYZ_M$4 = [[2.493496911941425, -0.9313836179191239, -0.40271078445071684], [-0.8294889695615747, 1.7626640603183463, 0.023624685841943577], [0.03584583024378447, -0.07617238926804182, 0.9568845240076872]];
8344 var P3Linear = new RGBColorSpace({
8345 id: "p3-linear",
8346 cssId: "display-p3-linear",
8347 name: "Linear P3",
8348 white: "D65",
8349 toXYZ_M: toXYZ_M$4,
8350 fromXYZ_M: fromXYZ_M$4
8351 });
8352
8353 /** @import { Matrix3x3 } from "../types.js" */
8354
8355 // This is the linear-light version of sRGB
8356 // as used for example in SVG filters
8357 // or in Canvas
8358
8359 // This matrix was calculated directly from the RGB and white chromaticities
8360 // when rounded to 8 decimal places, it agrees completely with the official matrix
8361 // see https://github.com/w3c/csswg-drafts/issues/5922
8362 /** @type {Matrix3x3} */
8363 // prettier-ignore
8364 const toXYZ_M$3 = [[0.41239079926595934, 0.357584339383878, 0.1804807884018343], [0.21263900587151027, 0.715168678767756, 0.07219231536073371], [0.01933081871559182, 0.11919477979462598, 0.9505321522496607]];
8365
8366 // This matrix is the inverse of the above;
8367 // again it agrees with the official definition when rounded to 8 decimal places
8368 /** @type {Matrix3x3} */
8369 // prettier-ignore
8370 const fromXYZ_M$3 = [[3.2409699419045226, -1.537383177570094, -0.4986107602930034], [-0.9692436362808796, 1.8759675015077202, 0.04155505740717559], [0.05563007969699366, -0.20397695888897652, 1.0569715142428786]];
8371 var sRGBLinear = new RGBColorSpace({
8372 id: "srgb-linear",
8373 name: "Linear sRGB",
8374 white: "D65",
8375 toXYZ_M: toXYZ_M$3,
8376 fromXYZ_M: fromXYZ_M$3
8377 });
8378
8379 // To produce: Visit https://www.w3.org/TR/css-color-4/#named-colors
8380 // and run in the console:
8381 // copy($$("tr", $(".named-color-table tbody")).map(tr => `"${tr.cells[2].textContent.trim()}": [${tr.cells[4].textContent.trim().split(/\s+/).map(c => c === "0"? "0" : c === "255"? "1" : c + " / 255").join(", ")}]`).join(",\n"))
8382
8383 /** List of CSS color keywords
8384 * Note that this does not include currentColor, transparent,
8385 * or system colors
8386 *
8387 * @type {Record<string, [number, number, number]>}
8388 */
8389 var KEYWORDS = {
8390 aliceblue: [240 / 255, 248 / 255, 1],
8391 antiquewhite: [250 / 255, 235 / 255, 215 / 255],
8392 aqua: [0, 1, 1],
8393 aquamarine: [127 / 255, 1, 212 / 255],
8394 azure: [240 / 255, 1, 1],
8395 beige: [245 / 255, 245 / 255, 220 / 255],
8396 bisque: [1, 228 / 255, 196 / 255],
8397 black: [0, 0, 0],
8398 blanchedalmond: [1, 235 / 255, 205 / 255],
8399 blue: [0, 0, 1],
8400 blueviolet: [138 / 255, 43 / 255, 226 / 255],
8401 brown: [165 / 255, 42 / 255, 42 / 255],
8402 burlywood: [222 / 255, 184 / 255, 135 / 255],
8403 cadetblue: [95 / 255, 158 / 255, 160 / 255],
8404 chartreuse: [127 / 255, 1, 0],
8405 chocolate: [210 / 255, 105 / 255, 30 / 255],
8406 coral: [1, 127 / 255, 80 / 255],
8407 cornflowerblue: [100 / 255, 149 / 255, 237 / 255],
8408 cornsilk: [1, 248 / 255, 220 / 255],
8409 crimson: [220 / 255, 20 / 255, 60 / 255],
8410 cyan: [0, 1, 1],
8411 darkblue: [0, 0, 139 / 255],
8412 darkcyan: [0, 139 / 255, 139 / 255],
8413 darkgoldenrod: [184 / 255, 134 / 255, 11 / 255],
8414 darkgray: [169 / 255, 169 / 255, 169 / 255],
8415 darkgreen: [0, 100 / 255, 0],
8416 darkgrey: [169 / 255, 169 / 255, 169 / 255],
8417 darkkhaki: [189 / 255, 183 / 255, 107 / 255],
8418 darkmagenta: [139 / 255, 0, 139 / 255],
8419 darkolivegreen: [85 / 255, 107 / 255, 47 / 255],
8420 darkorange: [1, 140 / 255, 0],
8421 darkorchid: [153 / 255, 50 / 255, 204 / 255],
8422 darkred: [139 / 255, 0, 0],
8423 darksalmon: [233 / 255, 150 / 255, 122 / 255],
8424 darkseagreen: [143 / 255, 188 / 255, 143 / 255],
8425 darkslateblue: [72 / 255, 61 / 255, 139 / 255],
8426 darkslategray: [47 / 255, 79 / 255, 79 / 255],
8427 darkslategrey: [47 / 255, 79 / 255, 79 / 255],
8428 darkturquoise: [0, 206 / 255, 209 / 255],
8429 darkviolet: [148 / 255, 0, 211 / 255],
8430 deeppink: [1, 20 / 255, 147 / 255],
8431 deepskyblue: [0, 191 / 255, 1],
8432 dimgray: [105 / 255, 105 / 255, 105 / 255],
8433 dimgrey: [105 / 255, 105 / 255, 105 / 255],
8434 dodgerblue: [30 / 255, 144 / 255, 1],
8435 firebrick: [178 / 255, 34 / 255, 34 / 255],
8436 floralwhite: [1, 250 / 255, 240 / 255],
8437 forestgreen: [34 / 255, 139 / 255, 34 / 255],
8438 fuchsia: [1, 0, 1],
8439 gainsboro: [220 / 255, 220 / 255, 220 / 255],
8440 ghostwhite: [248 / 255, 248 / 255, 1],
8441 gold: [1, 215 / 255, 0],
8442 goldenrod: [218 / 255, 165 / 255, 32 / 255],
8443 gray: [128 / 255, 128 / 255, 128 / 255],
8444 green: [0, 128 / 255, 0],
8445 greenyellow: [173 / 255, 1, 47 / 255],
8446 grey: [128 / 255, 128 / 255, 128 / 255],
8447 honeydew: [240 / 255, 1, 240 / 255],
8448 hotpink: [1, 105 / 255, 180 / 255],
8449 indianred: [205 / 255, 92 / 255, 92 / 255],
8450 indigo: [75 / 255, 0, 130 / 255],
8451 ivory: [1, 1, 240 / 255],
8452 khaki: [240 / 255, 230 / 255, 140 / 255],
8453 lavender: [230 / 255, 230 / 255, 250 / 255],
8454 lavenderblush: [1, 240 / 255, 245 / 255],
8455 lawngreen: [124 / 255, 252 / 255, 0],
8456 lemonchiffon: [1, 250 / 255, 205 / 255],
8457 lightblue: [173 / 255, 216 / 255, 230 / 255],
8458 lightcoral: [240 / 255, 128 / 255, 128 / 255],
8459 lightcyan: [224 / 255, 1, 1],
8460 lightgoldenrodyellow: [250 / 255, 250 / 255, 210 / 255],
8461 lightgray: [211 / 255, 211 / 255, 211 / 255],
8462 lightgreen: [144 / 255, 238 / 255, 144 / 255],
8463 lightgrey: [211 / 255, 211 / 255, 211 / 255],
8464 lightpink: [1, 182 / 255, 193 / 255],
8465 lightsalmon: [1, 160 / 255, 122 / 255],
8466 lightseagreen: [32 / 255, 178 / 255, 170 / 255],
8467 lightskyblue: [135 / 255, 206 / 255, 250 / 255],
8468 lightslategray: [119 / 255, 136 / 255, 153 / 255],
8469 lightslategrey: [119 / 255, 136 / 255, 153 / 255],
8470 lightsteelblue: [176 / 255, 196 / 255, 222 / 255],
8471 lightyellow: [1, 1, 224 / 255],
8472 lime: [0, 1, 0],
8473 limegreen: [50 / 255, 205 / 255, 50 / 255],
8474 linen: [250 / 255, 240 / 255, 230 / 255],
8475 magenta: [1, 0, 1],
8476 maroon: [128 / 255, 0, 0],
8477 mediumaquamarine: [102 / 255, 205 / 255, 170 / 255],
8478 mediumblue: [0, 0, 205 / 255],
8479 mediumorchid: [186 / 255, 85 / 255, 211 / 255],
8480 mediumpurple: [147 / 255, 112 / 255, 219 / 255],
8481 mediumseagreen: [60 / 255, 179 / 255, 113 / 255],
8482 mediumslateblue: [123 / 255, 104 / 255, 238 / 255],
8483 mediumspringgreen: [0, 250 / 255, 154 / 255],
8484 mediumturquoise: [72 / 255, 209 / 255, 204 / 255],
8485 mediumvioletred: [199 / 255, 21 / 255, 133 / 255],
8486 midnightblue: [25 / 255, 25 / 255, 112 / 255],
8487 mintcream: [245 / 255, 1, 250 / 255],
8488 mistyrose: [1, 228 / 255, 225 / 255],
8489 moccasin: [1, 228 / 255, 181 / 255],
8490 navajowhite: [1, 222 / 255, 173 / 255],
8491 navy: [0, 0, 128 / 255],
8492 oldlace: [253 / 255, 245 / 255, 230 / 255],
8493 olive: [128 / 255, 128 / 255, 0],
8494 olivedrab: [107 / 255, 142 / 255, 35 / 255],
8495 orange: [1, 165 / 255, 0],
8496 orangered: [1, 69 / 255, 0],
8497 orchid: [218 / 255, 112 / 255, 214 / 255],
8498 palegoldenrod: [238 / 255, 232 / 255, 170 / 255],
8499 palegreen: [152 / 255, 251 / 255, 152 / 255],
8500 paleturquoise: [175 / 255, 238 / 255, 238 / 255],
8501 palevioletred: [219 / 255, 112 / 255, 147 / 255],
8502 papayawhip: [1, 239 / 255, 213 / 255],
8503 peachpuff: [1, 218 / 255, 185 / 255],
8504 peru: [205 / 255, 133 / 255, 63 / 255],
8505 pink: [1, 192 / 255, 203 / 255],
8506 plum: [221 / 255, 160 / 255, 221 / 255],
8507 powderblue: [176 / 255, 224 / 255, 230 / 255],
8508 purple: [128 / 255, 0, 128 / 255],
8509 rebeccapurple: [102 / 255, 51 / 255, 153 / 255],
8510 red: [1, 0, 0],
8511 rosybrown: [188 / 255, 143 / 255, 143 / 255],
8512 royalblue: [65 / 255, 105 / 255, 225 / 255],
8513 saddlebrown: [139 / 255, 69 / 255, 19 / 255],
8514 salmon: [250 / 255, 128 / 255, 114 / 255],
8515 sandybrown: [244 / 255, 164 / 255, 96 / 255],
8516 seagreen: [46 / 255, 139 / 255, 87 / 255],
8517 seashell: [1, 245 / 255, 238 / 255],
8518 sienna: [160 / 255, 82 / 255, 45 / 255],
8519 silver: [192 / 255, 192 / 255, 192 / 255],
8520 skyblue: [135 / 255, 206 / 255, 235 / 255],
8521 slateblue: [106 / 255, 90 / 255, 205 / 255],
8522 slategray: [112 / 255, 128 / 255, 144 / 255],
8523 slategrey: [112 / 255, 128 / 255, 144 / 255],
8524 snow: [1, 250 / 255, 250 / 255],
8525 springgreen: [0, 1, 127 / 255],
8526 steelblue: [70 / 255, 130 / 255, 180 / 255],
8527 tan: [210 / 255, 180 / 255, 140 / 255],
8528 teal: [0, 128 / 255, 128 / 255],
8529 thistle: [216 / 255, 191 / 255, 216 / 255],
8530 tomato: [1, 99 / 255, 71 / 255],
8531 turquoise: [64 / 255, 224 / 255, 208 / 255],
8532 violet: [238 / 255, 130 / 255, 238 / 255],
8533 wheat: [245 / 255, 222 / 255, 179 / 255],
8534 white: [1, 1, 1],
8535 whitesmoke: [245 / 255, 245 / 255, 245 / 255],
8536 yellow: [1, 1, 0],
8537 yellowgreen: [154 / 255, 205 / 255, 50 / 255]
8538 };
8539
8540 /** @import { Coords } from "../types.js" */
8541
8542 let coordGrammar = Array(3).fill("<percentage> | <number>[0, 255]");
8543 let coordGrammarNumber = Array(3).fill("<number>[0, 255]");
8544 var sRGB = new RGBColorSpace({
8545 id: "srgb",
8546 name: "sRGB",
8547 base: sRGBLinear,
8548 linearGamut: sRGBLinear,
8549 fromBase: rgb => {
8550 // convert an array of linear-light sRGB values in the range 0.0-1.0
8551 // to gamma corrected form
8552 // https://en.wikipedia.org/wiki/SRGB
8553 return rgb.map(val => {
8554 let sign = val < 0 ? -1 : 1;
8555 let abs = val * sign;
8556 if (abs > 0.0031308) {
8557 return sign * (1.055 * abs ** (1 / 2.4) - 0.055);
8558 }
8559 return 12.92 * val;
8560 });
8561 },
8562 toBase: rgb => {
8563 // convert an array of sRGB values in the range 0.0 - 1.0
8564 // to linear light (un-companded) form.
8565 // https://en.wikipedia.org/wiki/SRGB
8566 return rgb.map(val => {
8567 let sign = val < 0 ? -1 : 1;
8568 let abs = val * sign;
8569 if (abs <= 0.04045) {
8570 return val / 12.92;
8571 }
8572 return sign * ((abs + 0.055) / 1.055) ** 2.4;
8573 });
8574 },
8575 formats: {
8576 rgb: {
8577 coords: coordGrammar
8578 },
8579 rgb_number: {
8580 name: "rgb",
8581 commas: true,
8582 coords: coordGrammarNumber,
8583 alpha: false
8584 },
8585 color: {
8586 /* use defaults */
8587 },
8588 rgba: {
8589 coords: coordGrammar,
8590 commas: true,
8591 alpha: true
8592 },
8593 rgba_number: {
8594 name: "rgba",
8595 commas: true,
8596 coords: coordGrammarNumber
8597 },
8598 hex: {
8599 type: "custom",
8600 toGamut: true,
8601 test: str => /^#(([a-f0-9]{2}){3,4}|[a-f0-9]{3,4})$/i.test(str),
8602 parse(str) {
8603 if (str.length <= 5) {
8604 // #rgb or #rgba, duplicate digits
8605 str = str.replace(/[a-f0-9]/gi, "$&$&");
8606 }
8607
8608 /** @type {number[]} */
8609 let rgba = [];
8610 // @ts-expect-error Type 'void' is not assignable to type 'string'
8611 str.replace(/[a-f0-9]{2}/gi, component => {
8612 rgba.push(parseInt(component, 16) / 255);
8613 });
8614 return {
8615 spaceId: "srgb",
8616 coords: (/** @type {Coords} */rgba.slice(0, 3)),
8617 alpha: (/** @type {number} */rgba.slice(3)[0])
8618 };
8619 },
8620 serialize: (coords, alpha, {
8621 collapse = true,
8622 // collapse to 3-4 digit hex when possible?
8623 alpha: alphaFormat
8624 } = {}) => {
8625 if (alphaFormat !== false && alpha < 1 || alphaFormat === true) {
8626 coords.push(alpha);
8627 }
8628 coords = /** @type {[number, number, number]} */
8629 coords.map(c => Math.round(c * 255));
8630 let collapsible = collapse && coords.every(c => c % 17 === 0);
8631 let hex = coords.map(c => {
8632 if (collapsible) {
8633 return (c / 17).toString(16);
8634 }
8635 return c.toString(16).padStart(2, "0");
8636 }).join("");
8637 return "#" + hex;
8638 }
8639 },
8640 keyword: {
8641 type: "custom",
8642 test: str => /^[a-z]+$/i.test(str),
8643 parse(str) {
8644 str = str.toLowerCase();
8645 let ret = {
8646 spaceId: "srgb",
8647 coords: null,
8648 alpha: 1
8649 };
8650 if (str === "transparent") {
8651 ret.coords = KEYWORDS.black;
8652 ret.alpha = 0;
8653 } else {
8654 ret.coords = KEYWORDS[str];
8655 }
8656 if (ret.coords) {
8657 return ret;
8658 }
8659 }
8660 }
8661 }
8662 });
8663
8664 var P3 = new RGBColorSpace({
8665 id: "p3",
8666 cssId: "display-p3",
8667 name: "P3",
8668 base: P3Linear,
8669 linearGamut: P3Linear,
8670 // Gamma encoding/decoding is the same as sRGB
8671 fromBase: sRGB.fromBase,
8672 toBase: sRGB.toBase
8673 });
8674
8675 /** @import ColorSpace from "./ColorSpace.js" */
8676 /** @import { ColorTypes, PlainColorObject, DisplayOptions } from "./types.js" */
8677
8678 // Type re-exports
8679 /** @typedef {import("./types.js").Display} Display */
8680
8681 // Default space for CSS output. Code in Color.js makes this wider if there's a DOM available
8682 defaults.display_space = sRGB;
8683 let supportsNone;
8684 if (typeof CSS !== "undefined" && CSS.supports) {
8685 // Find widest supported color space for CSS
8686 for (let space of [lab, REC2020, P3]) {
8687 let coords = space.getMinCoords();
8688 let color = {
8689 space,
8690 coords,
8691 alpha: 1
8692 };
8693 let str = serialize(color);
8694 if (CSS.supports("color", str)) {
8695 defaults.display_space = space;
8696 break;
8697 }
8698 }
8699 }
8700
8701 /**
8702 * Returns a serialization of the color that can actually be displayed in the browser.
8703 * If the default serialization can be displayed, it is returned.
8704 * Otherwise, if a `space` is given, the color is converted directly to it.
8705 * If not, the color is converted to the first supported of its space's `displaySpaces` (if any),
8706 * else the closest supported space in its base color space chain (which preserves its gamut),
8707 * else the default fallback space (Lab, REC2020, or P3, whichever is the widest supported).
8708 * In Node.js, this is basically equivalent to `serialize()` but returns a `String` object instead.
8709 * @param {ColorTypes} color
8710 * @param {DisplayOptions} [options] Options. Any properties beyond `space` and `supports` are passed to `serialize()`.
8711 * @returns {Display} String object containing the serialized color
8712 * with a color property containing the converted color (or the original, if no conversion was necessary)
8713 */
8714 function display(color, {
8715 space,
8716 supports = (_globalThis$CSS => (_globalThis$CSS = globalThis.CSS) === null || _globalThis$CSS === void 0 ? void 0 : _globalThis$CSS.supports)(),
8717 ...options
8718 } = {}) {
8719 color = getColor(color);
8720 let ret = /** @type {Display} */serialize(color, options);
8721 if (!supports || supports("color", /** @type {string} */ret) || !defaults.display_space) {
8722 ret = /** @type {Display} */new String(ret);
8723 ret.color = /** @type {PlainColorObject} */color;
8724 } else {
8725 // If we're here, what we were about to output is not supported
8726 let fallbackColor = /** @type {PlainColorObject} */color;
8727
8728 // First, check if the culprit is none values
8729 let hasNone = color.coords.some(isNone) || isNone(color.alpha);
8730 if (hasNone) {
8731 var _supportsNone;
8732 // Does the browser support none values?
8733 if (!((_supportsNone = supportsNone) !== null && _supportsNone !== void 0 ? _supportsNone : supportsNone = supports("color", "hsl(none 50% 50%)"))) {
8734 // Nope, try again without none
8735 fallbackColor = clone(/** @type {PlainColorObject} */color);
8736 fallbackColor.coords = /** @type {[number, number, number]} */
8737 fallbackColor.coords.map(skipNone);
8738 fallbackColor.alpha = skipNone(fallbackColor.alpha);
8739
8740 // @ts-expect-error This is set to the correct type later
8741 ret = serialize(fallbackColor, options);
8742 if (supports("color", /** @type {string} */ret)) {
8743 // We're done, now it's supported
8744 ret = /** @type {Display} */new String(ret);
8745 ret.color = fallbackColor;
8746 return ret;
8747 }
8748 }
8749 }
8750
8751 // If we're here, the color function is not supported.
8752 // With no explicit space, try the color's own `displaySpaces`, or else walk up its base
8753 // color space chain (closest first, skipping XYZ connection spaces), and use the first
8754 // space the browser supports, before falling back to the default space.
8755 if (space === undefined) {
8756 var _space$displaySpaces;
8757 space = fallbackColor.space;
8758 let candidates = (_space$displaySpaces = space.displaySpaces) !== null && _space$displaySpaces !== void 0 ? _space$displaySpaces : space.bases;
8759
8760 // Skip XYZ connection spaces (unless the space itself is one, so it still has a fallback).
8761 if (!space.displaySpaces && !space.id.startsWith("xyz-")) {
8762 candidates = candidates.filter(space => !space.id.startsWith("xyz-"));
8763 }
8764 for (let candidate of candidates) {
8765 let candidateColor = to(fallbackColor, candidate);
8766 let str = serialize(candidateColor, options);
8767 if (supports("color", /** @type {string} */str)) {
8768 ret = /** @type {Display} */new String(str);
8769 ret.color = candidateColor;
8770 return ret;
8771 }
8772 }
8773 space = defaults.display_space;
8774 }
8775
8776 // Fall back to fallback space
8777 fallbackColor = to(fallbackColor, /** @type {string | ColorSpace} */space);
8778 ret = /** @type {Display} */new String(serialize(fallbackColor, options));
8779 ret.color = fallbackColor;
8780 }
8781 return ret;
8782 }
8783
8784 /** @import { ColorSpace as ColorSpaceType } from "./types.js" */
8785
8786 // Cell count per coordinate: each keyed coordinate's range is divided into this many cells.
8787 // Calibrated so a cell spans < 1e-4 of chroma for OKLCh + P3 (slopes measured by
8788 // scripts/oklch-gamut-bounds.js); finer precision would not change the result.
8789 const STEPS = 1e6;
8790
8791 // A specialized, memoized maxChroma function per (reduce space, gamut), built lazily on first use
8792 // and keyed by their ids. Each closes over a two-layer digit trie of cached results: the lightness
8793 // key descends the outer trie to a node whose `.h` holds a hue trie, descended in turn to a
8794 // `.value` holding the max chroma. Each key drops its trailing zeros, so a round l or h costs no levels.
8795 /** @typedef {Array<any> & { value?: number }} HueTrie A digit indexes into the next level; `.value` is the max chroma */
8796 /** @typedef {Array<any> & { h?: HueTrie }} LightnessTrie A digit indexes into the next level; `.h` is the hue trie at this lightness */
8797 /** @type {Record<string, Record<string, (l: number, h: number) => number>>} */
8798 const cache = {};
8799
8800 // Significant digits of a ≤ 6-digit integer key (trailing zeros omitted, so round numbers stay shallow)
8801 function digitsOf(n) {
8802 let digits = [];
8803 for (let div = STEPS / 10; n; div /= 10) {
8804 digits.push(Math.floor(n / div));
8805 n %= div;
8806 }
8807 return digits;
8808 }
8809
8810 /**
8811 * Maximum chroma within an RGB gamut for a given lightness and hue, in a polar space's chroma units.
8812 * @param {number} l Lightness, in the reduce space's units
8813 * @param {number} h Hue angle, in degrees
8814 * @param {{ space: string | ColorSpaceType, gamut: string | ColorSpaceType }} options
8815 * `space` is the polar space whose chroma is reduced; `gamut` is the RGB gamut to fit.
8816 * @returns {number}
8817 */
8818 function maxChroma(l, h, {
8819 space,
8820 gamut
8821 }) {
8822 var _cache$space$id, _gamut$id, _cache$space$id$_gamu, _space$id, _cache$_space$id;
8823 space = ColorSpace.get(space);
8824 gamut = ColorSpace.get(gamut);
8825 let fn = (_cache$space$id$_gamu = (_cache$space$id = (_cache$_space$id = cache[_space$id = space.id]) !== null && _cache$_space$id !== void 0 ? _cache$_space$id : cache[_space$id] = {})[_gamut$id = gamut.id]) !== null && _cache$space$id$_gamu !== void 0 ? _cache$space$id$_gamu : _cache$space$id[_gamut$id] = makeMaxChroma(space, gamut);
8826 return fn(l, h);
8827 }
8828
8829 /**
8830 * Build the specialized maxChroma function for one (space, gamut) pair, doing the per-pair setup
8831 * (validation, role identification, ranges) once and capturing it in the returned closure.
8832 * @param {ColorSpaceType} space Resolved polar space whose chroma is reduced
8833 * @param {ColorSpaceType} gamut Resolved RGB gamut to fit
8834 * @returns {(l: number, h: number) => number}
8835 */
8836 function makeMaxChroma(space, gamut) {
8837 if (!space.isPolar || !("c" in space.coords)) {
8838 throw new TypeError(`maxChroma() needs a polar space with a "c" coordinate, got ${space.id}`);
8839 }
8840
8841 // Identify coordinates by role
8842 let ids = Object.keys(space.coords);
8843 let hueId = ids.find(id => space.coords[id].type === "angle");
8844 let lightnessId = ids.find(id => id !== "c" && id !== hueId);
8845 let range = id => {
8846 var _space$coords$id$rang;
8847 return (_space$coords$id$rang = space.coords[id].range) !== null && _space$coords$id$rang !== void 0 ? _space$coords$id$rang : space.coords[id].refRange;
8848 };
8849 let [lMin, lMax] = range(lightnessId);
8850 let [hMin, hMax] = range(hueId);
8851 let cMax = range("c")[1];
8852 let cIndex = ids.indexOf("c");
8853 let method = `${space.id}.c`;
8854 let root = /** @type {LightnessTrie} */[];
8855 return function (l, h) {
8856 var _lNode2, _lNode2$h, _hNode2, _hNode2$value;
8857 if (l <= lMin || l >= lMax) {
8858 return 0;
8859 }
8860 let lNode = root;
8861 for (let d of digitsOf(Math.floor((l - lMin) / (lMax - lMin) * STEPS))) {
8862 var _lNode, _lNode$d;
8863 lNode = (_lNode$d = (_lNode = lNode)[d]) !== null && _lNode$d !== void 0 ? _lNode$d : _lNode[d] = [];
8864 }
8865 let hNode = (_lNode2$h = (_lNode2 = lNode).h) !== null && _lNode2$h !== void 0 ? _lNode2$h : _lNode2.h = [];
8866 for (let d of digitsOf(Math.floor((constrain(h) - hMin) / (hMax - hMin) * STEPS))) {
8867 var _hNode, _hNode$d;
8868 hNode = (_hNode$d = (_hNode = hNode)[d]) !== null && _hNode$d !== void 0 ? _hNode$d : _hNode[d] = [];
8869 }
8870 let coords = /** @type {[number, number, number]} */
8871 ids.map(id => id === "c" ? cMax : id === hueId ? h : l);
8872 return (_hNode2$value = (_hNode2 = hNode).value) !== null && _hNode2$value !== void 0 ? _hNode2$value : _hNode2.value = toGamut({
8873 space,
8874 coords
8875 },
8876 // deltaE OK stays sensitive near black, where deltaE 2000 is too forgiving of excess chroma
8877 {
8878 space: gamut,
8879 method,
8880 deltaEMethod: "OK",
8881 jnd: 0
8882 }).coords[cIndex];
8883 };
8884 }
8885
8886 /** @import { ColorTypes } from "./types.js" */
8887
8888 // Type re-exports
8889 /** @typedef {import("./types.js").DeltasReturn} DeltasReturn */
8890
8891 /**
8892 * Get color differences per-component, on any color space
8893 * @param {ColorTypes} c1
8894 * @param {ColorTypes} c2
8895 * @param {object} options
8896 * @param {string | ColorSpace} [options.space=c1.space] - The color space to use for the delta calculation. Defaults to the color space of the first color.
8897 * @param {Parameters<typeof adjust>[0]} [options.hue="shorter"] - How to handle hue differences. Same as hue interpolation option.
8898 * @returns {DeltasReturn}
8899 */
8900 function deltas(c1, c2, {
8901 space,
8902 hue = "shorter"
8903 } = {}) {
8904 c1 = getColor(c1);
8905 space || (space = c1.space);
8906 space = ColorSpace.get(space);
8907 let spaceCoords = Object.values(space.coords);
8908 [c1, c2] = [c1, c2].map(c => to(c, space));
8909 let [coords1, coords2] = [c1, c2].map(c => c.coords);
8910 let coords = /** @type {[number, number, number]} */
8911 coords1.map((coord1, i) => {
8912 let coordMeta = spaceCoords[i];
8913 let coord2 = coords2[i];
8914 if (coordMeta.type === "angle") {
8915 [coord1, coord2] = adjust(hue, [coord1, coord2]);
8916 }
8917 return subtractCoords(coord1, coord2);
8918 });
8919 let alpha = subtractCoords(c1.alpha, c2.alpha);
8920 return {
8921 space: (/** @type {ColorSpace} */space),
8922 coords,
8923 alpha
8924 };
8925 }
8926 function subtractCoords(c1, c2) {
8927 if (isNone(c1) || isNone(c2)) {
8928 return c1 === c2 ? null : 0;
8929 }
8930 return c1 - c2;
8931 }
8932
8933 /** @import { ColorTypes } from "./types.js" */
8934
8935 /**
8936 * @param {ColorTypes} color1
8937 * @param {ColorTypes} color2
8938 * @returns {boolean}
8939 */
8940 function equals(color1, color2) {
8941 color1 = getColor(color1);
8942 color2 = getColor(color2);
8943 return color1.space === color2.space && color1.alpha === color2.alpha && color1.coords.every((c, i) => c === color2.coords[i]);
8944 }
8945
8946 /**
8947 * Relative luminance
8948 */
8949
8950 /** @import { ColorTypes } from "./types.js" */
8951
8952 /**
8953 *
8954 * @param {ColorTypes} color
8955 * @returns {number}
8956 */
8957 function getLuminance(color) {
8958 // Assume getColor() is called on color in get()
8959 return get(color, [XYZ_D65, "y"]);
8960 }
8961
8962 /**
8963 * @param {ColorTypes} color
8964 * @param {number | ((coord: number) => number)} value
8965 */
8966 function setLuminance(color, value) {
8967 // Assume getColor() is called on color in set()
8968 set(color, [XYZ_D65, "y"], value);
8969 }
8970
8971 // WCAG 2.0 contrast https://www.w3.org/TR/WCAG20-TECHS/G18.html
8972 // Simple contrast, with fixed 5% viewing flare contribution
8973 // Symmetric, does not matter which is foreground and which is background
8974
8975
8976 /**
8977 * @param {import("../types.js").ColorTypes} color1
8978 * @param {import("../types.js").ColorTypes} color2
8979 * @returns {number}
8980 */
8981 function contrastWCAG21(color1, color2) {
8982 color1 = getColor(color1);
8983 color2 = getColor(color2);
8984 let Y1 = Math.max(getLuminance(color1), 0);
8985 let Y2 = Math.max(getLuminance(color2), 0);
8986 if (Y2 > Y1) {
8987 [Y1, Y2] = [Y2, Y1];
8988 }
8989 return (Y1 + 0.05) / (Y2 + 0.05);
8990 }
8991
8992 // exponents
8993 const normBG = 0.56;
8994 const normTXT = 0.57;
8995 const revTXT = 0.62;
8996 const revBG = 0.65;
8997
8998 // clamps
8999 const blkThrs = 0.022;
9000 const blkClmp = 1.414;
9001 const loClip = 0.1;
9002 const deltaYmin = 0.0005;
9003
9004 // scalers
9005 // see https://github.com/w3c/silver/issues/645
9006 const scaleBoW = 1.14;
9007 const loBoWoffset = 0.027;
9008 const scaleWoB = 1.14;
9009 function fclamp(Y) {
9010 if (Y >= blkThrs) {
9011 return Y;
9012 }
9013 return Y + (blkThrs - Y) ** blkClmp;
9014 }
9015 function linearize(val) {
9016 let sign = val < 0 ? -1 : 1;
9017 let abs = Math.abs(val);
9018 return sign * Math.pow(abs, 2.4);
9019 }
9020
9021 /**
9022 * Not symmetric, requires a foreground (text) color, and a background color
9023 * @param {import("../types.js").ColorTypes} background
9024 * @param {import("../types.js").ColorTypes} foreground
9025 * @returns {number}
9026 */
9027 function contrastAPCA(background, foreground) {
9028 foreground = getColor(foreground);
9029 background = getColor(background);
9030 let S;
9031 let C;
9032 let Sapc;
9033
9034 // Myndex as-published, assumes sRGB inputs
9035 let R, G, B;
9036 foreground = to(foreground, "srgb");
9037 // Should these be clamped to in-gamut values?
9038
9039 // Calculates "screen luminance" with non-standard simple gamma EOTF
9040 // weights should be from CSS Color 4, not the ones here which are via Myndex and copied from Lindbloom
9041 [R, G, B] = foreground.coords.map(c => {
9042 return isNone(c) ? 0 : c;
9043 });
9044 let lumTxt = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175;
9045 background = to(background, "srgb");
9046 [R, G, B] = background.coords.map(c => {
9047 return isNone(c) ? 0 : c;
9048 });
9049 let lumBg = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175;
9050
9051 // toe clamping of very dark values to account for flare
9052 let Ytxt = fclamp(lumTxt);
9053 let Ybg = fclamp(lumBg);
9054
9055 // are we "Black on White" (dark on light), or light on dark?
9056 let BoW = Ybg > Ytxt;
9057
9058 // why is this a delta, when Y is not perceptually uniform?
9059 // Answer: it is a noise gate, see
9060 // https://github.com/LeaVerou/color.js/issues/208
9061 if (Math.abs(Ybg - Ytxt) < deltaYmin) {
9062 C = 0;
9063 } else {
9064 if (BoW) {
9065 // dark text on light background
9066 S = Ybg ** normBG - Ytxt ** normTXT;
9067 C = S * scaleBoW;
9068 } else {
9069 // light text on dark background
9070 S = Ybg ** revBG - Ytxt ** revTXT;
9071 C = S * scaleWoB;
9072 }
9073 }
9074 if (Math.abs(C) < loClip) {
9075 Sapc = 0;
9076 } else if (C > 0) {
9077 // not clear whether Woffset is loBoWoffset or loWoBoffset
9078 // but they have the same value
9079 Sapc = C - loBoWoffset;
9080 } else {
9081 Sapc = C + loBoWoffset;
9082 }
9083 return Sapc * 100;
9084 }
9085
9086 // Michelson luminance contrast
9087 // the relation between the spread and the sum of the two luminances
9088 // Symmetric, does not matter which is foreground and which is background
9089 // No black level compensation for flare.
9090
9091
9092 /**
9093 * @param {import("../types.js").ColorTypes} color1
9094 * @param {import("../types.js").ColorTypes} color2
9095 * @returns {number}
9096 */
9097 function contrastMichelson(color1, color2) {
9098 color1 = getColor(color1);
9099 color2 = getColor(color2);
9100 let Y1 = Math.max(getLuminance(color1), 0);
9101 let Y2 = Math.max(getLuminance(color2), 0);
9102 if (Y2 > Y1) {
9103 [Y1, Y2] = [Y2, Y1];
9104 }
9105 let denom = Y1 + Y2;
9106 return denom === 0 ? 0 : (Y1 - Y2) / denom;
9107 }
9108
9109 // Weber luminance contrast
9110 // The difference between the two luminances divided by the lower luminance
9111 // Symmetric, does not matter which is foreground and which is background
9112 // No black level compensation for flare.
9113
9114
9115 // the darkest sRGB color above black is #000001 and this produces
9116 // a plain Weber contrast of ~45647.
9117 // So, setting the divide-by-zero result at 50000 is a reasonable
9118 // max clamp for the plain Weber
9119 const max = 50000;
9120
9121 /**
9122 * @param {import("../types.js").ColorTypes} color1
9123 * @param {import("../types.js").ColorTypes} color2
9124 * @returns {number}
9125 */
9126 function contrastWeber(color1, color2) {
9127 color1 = getColor(color1);
9128 color2 = getColor(color2);
9129 let Y1 = Math.max(getLuminance(color1), 0);
9130 let Y2 = Math.max(getLuminance(color2), 0);
9131 if (Y2 > Y1) {
9132 [Y1, Y2] = [Y2, Y1];
9133 }
9134 return Y2 === 0 ? max : (Y1 - Y2) / Y2;
9135 }
9136
9137 // CIE Lightness difference, as used by Google Material Design
9138 // Google HCT Tone is the same as CIE Lightness
9139 // https://material.io/blog/science-of-color-design
9140
9141
9142 /**
9143 * @param {import("../types.js").ColorTypes} color1
9144 * @param {import("../types.js").ColorTypes} color2
9145 * @returns {number}
9146 */
9147 function contrastLstar(color1, color2) {
9148 color1 = getColor(color1);
9149 color2 = getColor(color2);
9150 let L1 = get(color1, [lab, "l"]);
9151 let L2 = get(color2, [lab, "l"]);
9152 return Math.abs(L1 - L2);
9153 }
9154
9155 // κ * ε = 2^3 = 8
9156 const ε$3 = 216 / 24389; // 6^3/29^3 == (24/116)^3
9157 const ε3 = 24 / 116;
9158 const κ$2 = 24389 / 27; // 29^3/3^3
9159
9160 let white$1 = WHITES.D65;
9161 var lab_d65 = new ColorSpace({
9162 id: "lab-d65",
9163 name: "Lab D65",
9164 coords: {
9165 l: {
9166 refRange: [0, 100],
9167 name: "Lightness"
9168 },
9169 a: {
9170 refRange: [-125, 125]
9171 },
9172 b: {
9173 refRange: [-125, 125]
9174 }
9175 },
9176 // Assuming XYZ is relative to D65, convert to CIE Lab
9177 // from CIE standard, which now defines these as a rational fraction
9178 white: white$1,
9179 base: XYZ_D65,
9180 // Convert D65-adapted XYZ to Lab
9181 // CIE 15.3:2004 section 8.2.1.1
9182 fromBase(XYZ) {
9183 // compute xyz, which is XYZ scaled relative to reference white
9184 let xyz = XYZ.map((value, i) => value / white$1[i]);
9185
9186 // now compute f
9187 let f = xyz.map(value => value > ε$3 ? Math.cbrt(value) : (κ$2 * value + 16) / 116);
9188 return [116 * f[1] - 16,
9189 // L
9190 500 * (f[0] - f[1]),
9191 // a
9192 200 * (f[1] - f[2]) // b
9193 ];
9194 },
9195 // Convert Lab to D65-adapted XYZ
9196 // Same result as CIE 15.3:2004 Appendix D although the derivation is different
9197 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
9198 toBase(Lab) {
9199 // compute f, starting with the luminance-related term
9200 let f = [];
9201 f[1] = (Lab[0] + 16) / 116;
9202 f[0] = Lab[1] / 500 + f[1];
9203 f[2] = f[1] - Lab[2] / 200;
9204
9205 // compute xyz
9206 let xyz = [f[0] > ε3 ? Math.pow(f[0], 3) : (116 * f[0] - 16) / κ$2, Lab[0] > 8 ? Math.pow((Lab[0] + 16) / 116, 3) : Lab[0] / κ$2, f[2] > ε3 ? Math.pow(f[2], 3) : (116 * f[2] - 16) / κ$2];
9207
9208 // Compute XYZ by scaling xyz by reference white
9209 return xyz.map((value, i) => value * white$1[i]);
9210 },
9211 formats: {
9212 "lab-d65": {
9213 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <percentage>"]
9214 }
9215 }
9216 });
9217
9218 // Delta Phi Star perceptual lightness contrast
9219 // See https://github.com/Myndex/deltaphistar
9220 // The (difference between two Lstars each raised to phi) raised to (1/phi)
9221 // Symmetric, does not matter which is foreground and which is background
9222
9223 const phi = Math.pow(5, 0.5) * 0.5 + 0.5; // Math.phi can be used if Math.js
9224
9225 /**
9226 * @param {import("../types.js").ColorTypes} color1
9227 * @param {import("../types.js").ColorTypes} color2
9228 * @returns {number}
9229 */
9230 function contrastDeltaPhi(color1, color2) {
9231 color1 = getColor(color1);
9232 color2 = getColor(color2);
9233 let Lstr1 = get(color1, [lab_d65, "l"]);
9234 let Lstr2 = get(color2, [lab_d65, "l"]);
9235 let deltaPhiStar = Math.abs(Math.pow(Lstr1, phi) - Math.pow(Lstr2, phi));
9236 let contrast = Math.pow(deltaPhiStar, 1 / phi) * Math.SQRT2 - 40;
9237 return contrast < 7.5 ? 0.0 : contrast;
9238 }
9239
9240 /** @typedef {keyof typeof import("./index.js") extends `contrast${infer Alg}` ? Alg : string} Algorithms */
9241
9242 var contrastAlgorithms = /*#__PURE__*/Object.freeze({
9243 __proto__: null,
9244 contrastAPCA: contrastAPCA,
9245 contrastDeltaPhi: contrastDeltaPhi,
9246 contrastLstar: contrastLstar,
9247 contrastMichelson: contrastMichelson,
9248 contrastWCAG21: contrastWCAG21,
9249 contrastWeber: contrastWeber
9250 });
9251
9252 /** @import { ColorTypes } from "./types.js" */
9253
9254 // Type re-exports
9255 /** @typedef {import("./types.js").Algorithms} Algorithms */
9256
9257 /**
9258 *
9259 * @param {ColorTypes} background
9260 * @param {ColorTypes} foreground
9261 * @param {Algorithms | ({ algorithm: Algorithms } & Record<string, any>)} o
9262 * Algorithm to use as well as any other options to pass to the contrast function
9263 * @returns {number}
9264 * @throws {TypeError} Unknown or unspecified algorithm
9265 */
9266 function contrast(background, foreground, o) {
9267 if (isString(o)) {
9268 o = {
9269 algorithm: o
9270 };
9271 }
9272 let {
9273 algorithm,
9274 ...rest
9275 } = o || {};
9276 if (!algorithm) {
9277 let algorithms = Object.keys(contrastAlgorithms).map(a => a.replace(/^contrast/, "")).join(", ");
9278 throw new TypeError(`contrast() function needs a contrast algorithm. Please specify one of: ${algorithms}`);
9279 }
9280 background = getColor(background);
9281 foreground = getColor(foreground);
9282 for (let a in contrastAlgorithms) {
9283 if ("contrast" + algorithm.toLowerCase() === a.toLowerCase()) {
9284 return contrastAlgorithms[a](background, foreground, rest);
9285 }
9286 }
9287 throw new TypeError(`Unknown contrast algorithm: ${algorithm}`);
9288 }
9289
9290 /** @import Color, { ColorTypes } from "./color.js" */
9291
9292 // Chromaticity coordinates
9293 /**
9294 * @param {ColorTypes} color
9295 * @returns {[number, number]}
9296 */
9297 function uv(color) {
9298 // Assumes getAll() calls getColor() on color
9299 let [X, Y, Z] = getAll(color, XYZ_D65);
9300 let denom = X + 15 * Y + 3 * Z;
9301 return [4 * X / denom, 9 * Y / denom];
9302 }
9303
9304 /**
9305 * @param {ColorTypes} color
9306 * @returns {[number, number]}
9307 */
9308 function xy(color) {
9309 // Assumes getAll() calls getColor() on color
9310 let [X, Y, Z] = getAll(color, XYZ_D65);
9311 let sum = X + Y + Z;
9312 return [X / sum, Y / sum];
9313 }
9314
9315 /** @import { ColorTypes } from "./types.js" */
9316
9317 // Type re-exports
9318 /** @typedef {import("./types.js").Methods} Methods */
9319
9320 /**
9321 *
9322 * @param {ColorTypes} c1
9323 * @param {ColorTypes} c2
9324 * @param {Methods | ({ method?: Methods | undefined } & Record<string, any>)} [o]
9325 * deltaE method to use as well as any other options to pass to the deltaE function
9326 * @returns {number}
9327 * @throws {TypeError} Unknown or unspecified method
9328 */
9329 function deltaE(c1, c2, o = {}) {
9330 if (isString(o)) {
9331 o = {
9332 method: o
9333 };
9334 }
9335 let {
9336 method = defaults.deltaE,
9337 ...rest
9338 } = o;
9339 for (let m in deltaEMethods) {
9340 if ("deltae" + method.toLowerCase() === m.toLowerCase()) {
9341 return deltaEMethods[m](c1, c2, rest);
9342 }
9343 }
9344 throw new TypeError(`Unknown deltaE method: ${method}`);
9345 }
9346
9347 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
9348
9349 /**
9350 * @param {ColorTypes} color
9351 * @param {number} amount
9352 * @returns {PlainColorObject}
9353 */
9354 function lighten(color, amount = 0.25) {
9355 let space = ColorSpace.get("oklch", "lch");
9356 let /** @type {Ref} */lightness = [space, "l"];
9357 return set(color, lightness, l => l * (1 + amount));
9358 }
9359
9360 /**
9361 * @param {ColorTypes} color
9362 * @param {number} amount
9363 * @returns {PlainColorObject}
9364 */
9365 function darken(color, amount = 0.25) {
9366 let space = ColorSpace.get("oklch", "lch");
9367 let /** @type {Ref} */lightness = [space, "l"];
9368 return set(color, lightness, l => l * (1 - amount));
9369 }
9370
9371 /** @type {"color"} */
9372 lighten.returns = "color";
9373
9374 /** @type {"color"} */
9375 darken.returns = "color";
9376
9377 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
9378
9379 // Type re-exports
9380 /** @typedef {import("./types.js").MixOptions} MixOptions */
9381 /** @typedef {import("./types.js").Range} Range */
9382 /** @typedef {import("./types.js").RangeOptions} RangeOptions */
9383 /** @typedef {import("./types.js").StepsOptions} StepsOptions */
9384
9385 /**
9386 * Return an intermediate color between two colors
9387 * @overload
9388 * @param {ColorTypes} c1
9389 * @param {ColorTypes} c2
9390 * @param {MixOptions} [options]
9391 * @returns {PlainColorObject}
9392 */
9393 /**
9394 * @overload
9395 * @param {ColorTypes} c1
9396 * @param {ColorTypes} c2
9397 * @param {number} [p=0.5]
9398 * @param {MixOptions} [options]
9399 * @returns {PlainColorObject}
9400 */
9401 function mix(c1, c2, p, o = {}) {
9402 var _p;
9403 [c1, c2] = [getColor(c1), getColor(c2)];
9404 if (type(p) === "object") {
9405 [p, o] = [0.5, p];
9406 }
9407 let r = range(c1, c2, o);
9408 return r((_p = p) !== null && _p !== void 0 ? _p : 0.5); // why not give p a default value like we do for options? Overloading doesn't work, and TS complains
9409 }
9410
9411 /**
9412 * Get an array of discrete steps
9413 * @overload
9414 * @param {ColorTypes} c1
9415 * @param {ColorTypes} c2
9416 * @param {StepsOptions} [options]
9417 * @returns {PlainColorObject[]}
9418 */
9419 /**
9420 * @overload
9421 * @param {Range} range
9422 * @param {StepsOptions} [options]
9423 * @returns {PlainColorObject[]}
9424 */
9425 function steps(c1, c2, options = {}) {
9426 let colorRange;
9427 if (isRange(c1)) {
9428 // Tweaking existing range
9429 [colorRange, options] = [c1, c2];
9430 [c1, c2] = colorRange.rangeArgs.colors;
9431 }
9432 let {
9433 maxDeltaE,
9434 deltaEMethod,
9435 steps = 2,
9436 maxSteps = 1000,
9437 ...rangeOptions
9438 } = options;
9439 if (!colorRange) {
9440 [c1, c2] = [getColor(c1), getColor(c2)];
9441 colorRange = range(c1, c2, rangeOptions);
9442 }
9443 let totalDelta = deltaE(c1, c2);
9444 let actualSteps = maxDeltaE > 0 ? Math.max(steps, Math.ceil(totalDelta / maxDeltaE) + 1) : steps;
9445 let ret = [];
9446 if (maxSteps !== undefined) {
9447 actualSteps = Math.min(actualSteps, maxSteps);
9448 }
9449 if (actualSteps === 1) {
9450 ret = [{
9451 p: 0.5,
9452 color: colorRange(0.5)
9453 }];
9454 } else {
9455 let step = 1 / (actualSteps - 1);
9456 ret = Array.from({
9457 length: actualSteps
9458 }, (_, i) => {
9459 let p = i * step;
9460 return {
9461 p,
9462 color: colorRange(p)
9463 };
9464 });
9465 }
9466 if (maxDeltaE > 0) {
9467 // Iterate over all stops and find max deltaE
9468 let maxDelta = ret.reduce((acc, cur, i) => {
9469 if (i === 0) {
9470 return 0;
9471 }
9472 let ΔΕ = deltaE(cur.color, ret[i - 1].color, deltaEMethod);
9473 return Math.max(acc, ΔΕ);
9474 }, 0);
9475 while (maxDelta > maxDeltaE) {
9476 // Insert intermediate stops and measure maxDelta again
9477 // We need to do this for all pairs, otherwise the midpoint shifts
9478 maxDelta = 0;
9479 for (let i = 1; i < ret.length && ret.length < maxSteps; i++) {
9480 let prev = ret[i - 1];
9481 let cur = ret[i];
9482 let p = (cur.p + prev.p) / 2;
9483 let color = colorRange(p);
9484 maxDelta = Math.max(maxDelta, deltaE(color, prev.color), deltaE(color, cur.color));
9485 ret.splice(i, 0, {
9486 p,
9487 color: colorRange(p)
9488 });
9489 i++;
9490 }
9491 }
9492 }
9493 ret = ret.map(a => a.color);
9494 return ret;
9495 }
9496
9497 /**
9498 * Creates a function that accepts a number and returns a color.
9499 * For numbers in the range 0 to 1, the function interpolates;
9500 * for numbers outside that range, the function extrapolates
9501 * (and thus may not return the results you expect)
9502 * @overload
9503 * @param {Range} range
9504 * @param {RangeOptions} [options]
9505 * @returns {Range}
9506 */
9507 /**
9508 * @overload
9509 * @param {ColorTypes} color1
9510 * @param {ColorTypes} color2
9511 * @param {RangeOptions & Record<string, any>} [options]
9512 * @returns {Range}
9513 */
9514 function range(color1, color2, options = {}) {
9515 if (isRange(color1)) {
9516 // Tweaking existing range
9517 let [r, options] = [color1, color2];
9518 return range(...r.rangeArgs.colors, {
9519 ...r.rangeArgs.options,
9520 ...options
9521 });
9522 }
9523 let {
9524 space,
9525 outputSpace,
9526 progression,
9527 premultiplied
9528 } = options;
9529 color1 = getColor(color1);
9530 color2 = getColor(color2);
9531
9532 // Make sure we're working on copies of these colors
9533 color1 = clone(color1);
9534 color2 = clone(color2);
9535 let rangeArgs = {
9536 colors: [color1, color2],
9537 options
9538 };
9539 if (space) {
9540 space = ColorSpace.get(space);
9541 } else {
9542 space = ColorSpace.registry[defaults.interpolationSpace] || color1.space;
9543 }
9544 outputSpace = outputSpace ? ColorSpace.get(outputSpace) : space;
9545 color1 = to(color1, space);
9546 color2 = to(color2, space);
9547
9548 // Gamut map to avoid areas of flat color
9549 color1 = toGamut(color1);
9550 color2 = toGamut(color2);
9551
9552 // Handle hue interpolation
9553 // See https://github.com/w3c/csswg-drafts/issues/4735#issuecomment-635741840
9554 if (space.coords.h && space.coords.h.type === "angle") {
9555 let arc = options.hue = options.hue || "shorter";
9556 let /** @type {Ref} */hue = [space, "h"];
9557 let [θ1, θ2] = [get(color1, hue), get(color2, hue)];
9558 // Undefined hues must be evaluated before hue fix-up to properly
9559 // calculate hue arcs between undefined and defined hues.
9560 // See https://github.com/w3c/csswg-drafts/issues/9436#issuecomment-1746957545
9561 if (isNone(θ1) && !isNone(θ2)) {
9562 θ1 = θ2;
9563 } else if (isNone(θ2) && !isNone(θ1)) {
9564 θ2 = θ1;
9565 }
9566 [θ1, θ2] = adjust(arc, [θ1, θ2]);
9567 set(color1, hue, θ1);
9568 set(color2, hue, θ2);
9569 }
9570 if (premultiplied) {
9571 // not coping with polar spaces yet
9572 color1.coords = /** @type {[number, number, number]} */
9573 color1.coords.map(c => c * color1.alpha);
9574 color2.coords = /** @type {[number, number, number]} */
9575 color2.coords.map(c => c * color2.alpha);
9576 }
9577 return Object.assign(p => {
9578 p = progression ? progression(p) : p;
9579 let coords = color1.coords.map((start, i) => {
9580 let end = color2.coords[i];
9581 return interpolate(start, end, p);
9582 });
9583 let alpha = interpolate(color1.alpha, color2.alpha, p);
9584 let ret = {
9585 space,
9586 coords,
9587 alpha
9588 };
9589 if (premultiplied) {
9590 // undo premultiplication
9591 ret.coords = ret.coords.map(c => c / alpha);
9592 }
9593 if (outputSpace !== space) {
9594 ret = to(ret, outputSpace);
9595 }
9596 return ret;
9597 }, {
9598 rangeArgs
9599 });
9600 }
9601
9602 /**
9603 * @param {any} val
9604 * @returns {val is Range}
9605 */
9606 function isRange(val) {
9607 return type(val) === "function" && !!val.rangeArgs;
9608 }
9609 defaults.interpolationSpace = "lab";
9610
9611 var HSL = new ColorSpace({
9612 id: "hsl",
9613 name: "HSL",
9614 coords: {
9615 h: {
9616 refRange: [0, 360],
9617 type: "angle",
9618 name: "Hue"
9619 },
9620 s: {
9621 range: [0, 100],
9622 name: "Saturation"
9623 },
9624 l: {
9625 range: [0, 100],
9626 name: "Lightness"
9627 }
9628 },
9629 base: sRGB,
9630 rgbGamut: sRGB,
9631 // Adapted from https://drafts.csswg.org/css-color-4/better-rgbToHsl.js
9632 fromBase: rgb => {
9633 let max = Math.max(...rgb);
9634 let min = Math.min(...rgb);
9635 let [r, g, b] = rgb;
9636 let [h, s, l] = [null, 0, (min + max) / 2];
9637 let d = max - min;
9638 if (d !== 0) {
9639 s = l === 0 || l === 1 ? 0 : (max - l) / Math.min(l, 1 - l);
9640 switch (max) {
9641 case r:
9642 h = (g - b) / d + (g < b ? 6 : 0);
9643 break;
9644 case g:
9645 h = (b - r) / d + 2;
9646 break;
9647 case b:
9648 h = (r - g) / d + 4;
9649 }
9650 h = h * 60;
9651 }
9652
9653 // Very out of gamut colors can produce negative saturation
9654 // If so, just rotate the hue by 180 and use a positive saturation
9655 // see https://github.com/w3c/csswg-drafts/issues/9222
9656 if (s < 0) {
9657 h += 180;
9658 s = Math.abs(s);
9659 }
9660 if (h >= 360) {
9661 h -= 360;
9662 }
9663 return [h, s * 100, l * 100];
9664 },
9665 // Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB_alternative
9666 toBase: hsl => {
9667 let [h, s, l] = hsl;
9668 h = h % 360;
9669 if (h < 0) {
9670 h += 360;
9671 }
9672 s /= 100;
9673 l /= 100;
9674 function f(n) {
9675 let k = (n + h / 30) % 12;
9676 let a = s * Math.min(l, 1 - l);
9677 return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));
9678 }
9679 return [f(0), f(8), f(4)];
9680 },
9681 formats: {
9682 hsl: {
9683 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
9684 },
9685 hsla: {
9686 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
9687 commas: true,
9688 alpha: true
9689 }
9690 }
9691 });
9692
9693 var hslP3 = new ColorSpace({
9694 id: "hsl-p3",
9695 cssId: "--hsl-p3",
9696 name: "HSL P3",
9697 coords: {
9698 h: {
9699 refRange: [0, 360],
9700 type: "angle",
9701 name: "Hue"
9702 },
9703 s: {
9704 range: [0, 100],
9705 name: "Saturation"
9706 },
9707 l: {
9708 range: [0, 100],
9709 name: "Lightness"
9710 }
9711 },
9712 base: P3,
9713 rgbGamut: P3,
9714 fromBase: HSL.fromBase,
9715 toBase: HSL.toBase
9716 });
9717
9718 var hslRec2020 = new ColorSpace({
9719 id: "hsl-rec2020",
9720 cssId: "--hsl-rec2020",
9721 name: "HSL Rec.2020",
9722 coords: {
9723 h: {
9724 refRange: [0, 360],
9725 type: "angle",
9726 name: "Hue"
9727 },
9728 s: {
9729 range: [0, 100],
9730 name: "Saturation"
9731 },
9732 l: {
9733 range: [0, 100],
9734 name: "Lightness"
9735 }
9736 },
9737 base: REC2020,
9738 rgbGamut: REC2020,
9739 fromBase: HSL.fromBase,
9740 toBase: HSL.toBase
9741 });
9742
9743 // Note that, like HSL, calculations are done directly on
9744 // gamma-corrected sRGB values rather than linearising them first.
9745
9746 var HSV = new ColorSpace({
9747 id: "hsv",
9748 name: "HSV",
9749 coords: {
9750 h: {
9751 refRange: [0, 360],
9752 type: "angle",
9753 name: "Hue"
9754 },
9755 s: {
9756 range: [0, 100],
9757 name: "Saturation"
9758 },
9759 v: {
9760 range: [0, 100],
9761 name: "Value"
9762 }
9763 },
9764 base: sRGB,
9765 rgbGamut: sRGB,
9766 // https://en.wikipedia.org/wiki/HSL_and_HSV#Formal_derivation
9767 fromBase(rgb) {
9768 let max = Math.max(...rgb);
9769 let min = Math.min(...rgb);
9770 let [r, g, b] = rgb;
9771 let [h, s, v] = [null, 0, max];
9772 let d = max - min;
9773 if (d !== 0) {
9774 switch (max) {
9775 case r:
9776 h = (g - b) / d + (g < b ? 6 : 0);
9777 break;
9778 case g:
9779 h = (b - r) / d + 2;
9780 break;
9781 case b:
9782 h = (r - g) / d + 4;
9783 }
9784 h = h * 60;
9785 }
9786 if (v) {
9787 s = d / v;
9788 }
9789 if (h >= 360) {
9790 h -= 360;
9791 }
9792 return [h, s * 100, v * 100];
9793 },
9794 // Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB_alternative
9795 toBase(hsv) {
9796 let [h, s, v] = hsv;
9797 h = h % 360;
9798 if (h < 0) {
9799 h += 360;
9800 }
9801 s /= 100;
9802 v /= 100;
9803 function f(n) {
9804 let k = (n + h / 60) % 6;
9805 return v - v * s * Math.max(0, Math.min(k, 4 - k, 1));
9806 }
9807 return [f(5), f(3), f(1)];
9808 },
9809 formats: {
9810 color: {
9811 id: "--hsv",
9812 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
9813 }
9814 }
9815 });
9816
9817 // The Hue, Whiteness Blackness (HWB) colorspace
9818 // See https://drafts.csswg.org/css-color-4/#the-hwb-notation
9819 // Note that, like HSL, calculations are done directly on
9820 // gamma-corrected sRGB values rather than linearising them first.
9821
9822 var hwb = new ColorSpace({
9823 id: "hwb",
9824 name: "HWB",
9825 coords: {
9826 h: {
9827 refRange: [0, 360],
9828 type: "angle",
9829 name: "Hue"
9830 },
9831 w: {
9832 range: [0, 100],
9833 name: "Whiteness"
9834 },
9835 b: {
9836 range: [0, 100],
9837 name: "Blackness"
9838 }
9839 },
9840 base: HSV,
9841 rgbGamut: sRGB,
9842 fromBase(hsv) {
9843 let [h, s, v] = hsv;
9844 return [h, v * (100 - s) / 100, 100 - v];
9845 },
9846 toBase(hwb) {
9847 let [h, w, b] = hwb;
9848
9849 // Now convert percentages to [0..1]
9850 w /= 100;
9851 b /= 100;
9852
9853 // Achromatic check (white plus black >= 1)
9854 let sum = w + b;
9855 if (sum >= 1) {
9856 let gray = w / sum;
9857 return [h, 0, gray * 100];
9858 }
9859 let v = 1 - b;
9860 let s = v === 0 ? 0 : 1 - w / v;
9861 return [h, s * 100, v * 100];
9862 },
9863 formats: {
9864 hwb: {
9865 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
9866 }
9867 }
9868 });
9869
9870 /** @import { Matrix3x3 } from "../types.js" */
9871
9872 // convert an array of linear-light a98-rgb values to CIE XYZ
9873 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
9874 // has greater numerical precision than section 4.3.5.3 of
9875 // https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf
9876 // but the values below were calculated from first principles
9877 // from the chromaticity coordinates of R G B W
9878
9879 /** @type {Matrix3x3} */
9880 // prettier-ignore
9881 const toXYZ_M$2 = [[0.5766690429101305, 0.1855582379065463, 0.1882286462349947], [0.29734497525053605, 0.6273635662554661, 0.07529145849399788], [0.02703136138641234, 0.07068885253582723, 0.9913375368376388]];
9882
9883 /** @type {Matrix3x3} */
9884 // prettier-ignore
9885 const fromXYZ_M$2 = [[2.0415879038107465, -0.5650069742788596, -0.34473135077832956], [-0.9692436362808795, 1.8759675015077202, 0.04155505740717557], [0.013444280632031142, -0.11836239223101838, 1.0151749943912054]];
9886 var A98Linear = new RGBColorSpace({
9887 id: "a98rgb-linear",
9888 cssId: "--a98-rgb-linear",
9889 name: "Linear Adobe® 98 RGB compatible",
9890 white: "D65",
9891 toXYZ_M: toXYZ_M$2,
9892 fromXYZ_M: fromXYZ_M$2
9893 });
9894
9895 var a98rgb = new RGBColorSpace({
9896 id: "a98rgb",
9897 cssId: "a98-rgb",
9898 name: "Adobe® 98 RGB compatible",
9899 base: A98Linear,
9900 linearGamut: A98Linear,
9901 toBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 563 / 256) * Math.sign(val)),
9902 fromBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 256 / 563) * Math.sign(val))
9903 });
9904
9905 /** @import { Matrix3x3 } from "../types.js" */
9906
9907 // convert an array of prophoto-rgb values to CIE XYZ
9908 // using D50 (so no chromatic adaptation needed afterwards)
9909 // matrix cannot be expressed in rational form, but is calculated to 64 bit accuracy
9910 // see https://github.com/w3c/csswg-drafts/issues/7675
9911 /** @type {Matrix3x3} */
9912 // prettier-ignore
9913 const toXYZ_M$1 = [[0.79776664490064230, 0.13518129740053308, 0.03134773412839220], [0.28807482881940130, 0.71183523424187300, 0.00008993693872564], [0.00000000000000000, 0.00000000000000000, 0.82510460251046020]];
9914
9915 /** @type {Matrix3x3} */
9916 // prettier-ignore
9917 const fromXYZ_M$1 = [[1.34578688164715830, -0.25557208737979464, -0.05110186497554526], [-0.54463070512490190, 1.50824774284514680, 0.02052744743642139], [0.00000000000000000, 0.00000000000000000, 1.21196754563894520]];
9918 var ProPhotoLinear = new RGBColorSpace({
9919 id: "prophoto-linear",
9920 cssId: "--prophoto-rgb-linear",
9921 name: "Linear ProPhoto",
9922 white: "D50",
9923 base: XYZ_D50,
9924 toXYZ_M: toXYZ_M$1,
9925 fromXYZ_M: fromXYZ_M$1
9926 });
9927
9928 const Et = 1 / 512;
9929 const Et2 = 16 / 512;
9930 var prophoto = new RGBColorSpace({
9931 id: "prophoto",
9932 cssId: "prophoto-rgb",
9933 name: "ProPhoto",
9934 base: ProPhotoLinear,
9935 linearGamut: ProPhotoLinear,
9936 toBase(RGB) {
9937 // Transfer curve is gamma 1.8 with a small linear portion
9938 return RGB.map(v => {
9939 let sign = v < 0 ? -1 : 1;
9940 let abs = v * sign;
9941 if (abs < Et2) {
9942 return v / 16;
9943 }
9944 return sign * abs ** 1.8;
9945 });
9946 },
9947 fromBase(RGB) {
9948 return RGB.map(v => {
9949 let sign = v < 0 ? -1 : 1;
9950 let abs = v * sign;
9951 if (abs >= Et) {
9952 return sign * abs ** (1 / 1.8);
9953 }
9954 return 16 * v;
9955 });
9956 }
9957 });
9958
9959 // import sRGB from "./srgb.js";
9960
9961 const α = 1.09929682680944;
9962 const β = 0.018053968510807;
9963 var rec2020Oetf = new RGBColorSpace({
9964 id: "--rec2020-oetf",
9965 name: "REC.2020_Scene_Referred",
9966 base: REC_2020_Linear,
9967 linearGamut: REC_2020_Linear,
9968 referred: "scene",
9969 // Non-linear transfer function from Rec. ITU-R BT.2020-2 table 4
9970 toBase(RGB) {
9971 return RGB.map(function (val) {
9972 let sign = val < 0 ? -1 : 1;
9973 let abs = val * sign;
9974 if (abs < β * 4.5) {
9975 return val / 4.5;
9976 }
9977 return sign * Math.pow((abs + α - 1) / α, 1 / 0.45);
9978 });
9979 },
9980 fromBase(RGB) {
9981 return RGB.map(function (val) {
9982 let sign = val < 0 ? -1 : 1;
9983 let abs = val * sign;
9984 if (abs >= β) {
9985 return sign * (α * Math.pow(abs, 0.45) - (α - 1));
9986 }
9987 return 4.5 * val;
9988 });
9989 }
9990 });
9991
9992 var oklchP3 = new ColorSpace({
9993 id: "oklch-p3",
9994 name: "OKLCh P3",
9995 coords: {
9996 l: {
9997 refRange: [0, 1],
9998 name: "Lightness"
9999 },
10000 c: {
10001 range: [0, 1],
10002 name: "Chroma"
10003 },
10004 h: {
10005 refRange: [0, 360],
10006 type: "angle",
10007 name: "Hue"
10008 }
10009 },
10010 white: "D65",
10011 base: OKLCH,
10012 toBase([l, c, h]) {
10013 if (![l, c, h].some(isNone)) {
10014 c *= maxChroma(l, h, {
10015 space: OKLCH,
10016 gamut: "p3"
10017 });
10018 }
10019 return [l, c, h];
10020 },
10021 fromBase([l, c, h]) {
10022 if (![l, c, h].some(isNone)) {
10023 let cMax = maxChroma(l, h, {
10024 space: OKLCH,
10025 gamut: "p3"
10026 });
10027 c = cMax ? c / cMax : 0;
10028 }
10029 return [l, c, h];
10030 },
10031 formats: {
10032 color: {
10033 id: "--oklch-p3",
10034 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
10035 }
10036 }
10037 });
10038
10039 /** @import { Matrix3x3, Vector3 } from "../types.js" */
10040
10041 // Type re-exports
10042 /** @typedef {import("../types.js").OKCoeff} OKCoeff */
10043
10044 const tau = 2 * Math.PI;
10045
10046 /** @type {Matrix3x3} */
10047 // prettier-ignore
10048 const toSRGBLinear = [[4.0767416360759583, -3.3077115392580629, 0.2309699031821043], [-1.2684379732850315, 2.6097573492876882, -0.3413193760026570], [-0.0041960761386756, -0.7034186179359362, 1.7076146940746117]];
10049
10050 /** @type {OKCoeff} */
10051 const RGBCoeff = [
10052 // Red
10053 [
10054 // Limit
10055 [-1.8817031, -0.80936501],
10056 // `Kn` coefficients
10057 [1.19086277, 1.76576728, 0.59662641, 0.75515197, 0.56771245]],
10058 // Green
10059 [
10060 // Limit
10061 [1.8144408, -1.19445267],
10062 // `Kn` coefficients
10063 [0.73956515, -0.45954404, 0.08285427, 0.12541073, -0.14503204]],
10064 // Blue
10065 [
10066 // Limit
10067 [0.13110758, 1.81333971],
10068 // `Kn` coefficients
10069 [1.35733652, -0.00915799, -1.1513021, -0.50559606, 0.00692167]]];
10070 const floatMax = Number.MAX_VALUE;
10071 const K1 = 0.206;
10072 const K2 = 0.03;
10073 const K3 = (1.0 + K1) / (1.0 + K2);
10074 function vdot(a, b) {
10075 // Dot two vectors
10076
10077 let l = a.length;
10078 if (l !== b.length) {
10079 throw new Error(`Vectors of size ${l} and ${b.length} are not aligned`);
10080 }
10081 let s = 0.0;
10082 a.forEach((c, i) => {
10083 s += c * b[i];
10084 });
10085 return s;
10086 }
10087
10088 /**
10089 * Toe function for L_r
10090 * @param {number} x
10091 */
10092 function toe(x) {
10093 return 0.5 * (K3 * x - K1 + Math.sqrt((K3 * x - K1) * (K3 * x - K1) + 4 * K2 * K3 * x));
10094 }
10095
10096 /**
10097 * Inverse toe function for L_r
10098 * @param {number} x
10099 */
10100 function toeInv(x) {
10101 return (x ** 2 + K1 * x) / (K3 * (x + K2));
10102 }
10103
10104 /**
10105 * @param {readonly [number, number]} cusp
10106 * @returns {[number, number]}
10107 */
10108 function toSt(cusp) {
10109 // To ST.
10110
10111 let [l, c] = cusp;
10112 return [c / l, c / (1 - l)];
10113 }
10114 function getStMid(a, b) {
10115 // Returns a smooth approximation of the location of the cusp.
10116 //
10117 // This polynomial was created by an optimization process.
10118 // It has been designed so that S_mid < S_max and T_mid < T_max.
10119
10120 // prettier-ignore
10121 let s = 0.11516993 + 1.0 / (7.44778970 + 4.15901240 * b + a * (-2.19557347 + 1.75198401 * b + a * (-2.13704948 - 10.02301043 * b + a * (-4.24894561 + 5.38770819 * b + 4.69891013 * a))));
10122
10123 // prettier-ignore
10124 let t = 0.11239642 + 1.0 / (1.61320320 - 0.68124379 * b + a * (0.40370612 + 0.90148123 * b + a * (-0.27087943 + 0.61223990 * b + a * (0.00299215 - 0.45399568 * b - 0.14661872 * a))));
10125 return [s, t];
10126 }
10127
10128 /**
10129 * @param {Vector3} lab
10130 * @param {Matrix3x3} lmsToRgb
10131 */
10132 function oklabToLinearRGB(lab, lmsToRgb) {
10133 // Convert from Oklab to linear RGB.
10134 //
10135 // Can be any gamut as long as `lmsToRgb` is a matrix
10136 // that transform the LMS values to the linear RGB space.
10137
10138 let lms = multiply_v3_m3x3(lab, LabtoLMS_M);
10139 lms[0] = lms[0] ** 3;
10140 lms[1] = lms[1] ** 3;
10141 lms[2] = lms[2] ** 3;
10142 return multiply_v3_m3x3(lms, lmsToRgb, lms);
10143 }
10144
10145 /**
10146 * @param {number} a
10147 * @param {number} b
10148 * @param {Matrix3x3} lmsToRgb
10149 * @param {OKCoeff} okCoeff
10150 * @returns {[number, number]}
10151 * @todo Could probably make these types more specific/better-documented if desired
10152 */
10153 function findCusp(a, b, lmsToRgb, okCoeff) {
10154 // Finds L_cusp and C_cusp for a given hue.
10155 //
10156 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
10157
10158 // First, find the maximum saturation (saturation `S = C/L`)
10159 let sCusp = computeMaxSaturation(a, b, lmsToRgb, okCoeff);
10160
10161 // Convert to linear RGB to find the first point where at least one of r, g or b >= 1:
10162 let rgb = oklabToLinearRGB([1, sCusp * a, sCusp * b], lmsToRgb);
10163 let lCusp = spow(1.0 / Math.max(...rgb), 1 / 3);
10164 let cCusp = lCusp * sCusp;
10165 return [lCusp, cCusp];
10166 }
10167
10168 /**
10169 * @param {number} a
10170 * @param {number} b
10171 * @param {number} l1
10172 * @param {number} c1
10173 * @param {number} l0
10174 * @param {Matrix3x3} lmsToRgb
10175 * @param {OKCoeff} okCoeff
10176 * @param {[number, number]} cusp
10177 * @returns {Number}
10178 * @todo Could probably make these types more specific/better-documented if desired
10179 */
10180 function findGamutIntersection(a, b, l1, c1, l0, lmsToRgb, okCoeff, cusp) {
10181 // Finds intersection of the line.
10182 //
10183 // Defined by the following:
10184 //
10185 // ```
10186 // L = L0 * (1 - t) + t * L1
10187 // C = t * C1
10188 // ```
10189 //
10190 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
10191
10192 let t;
10193 if (cusp === undefined) {
10194 cusp = findCusp(a, b, lmsToRgb, okCoeff);
10195 }
10196
10197 // Find the intersection for upper and lower half separately
10198 if ((l1 - l0) * cusp[1] - (cusp[0] - l0) * c1 <= 0.0) {
10199 // Lower half
10200 t = cusp[1] * l0 / (c1 * cusp[0] + cusp[1] * (l0 - l1));
10201 } else {
10202 // Upper half
10203
10204 // First intersect with triangle
10205 t = cusp[1] * (l0 - 1.0) / (c1 * (cusp[0] - 1.0) + cusp[1] * (l0 - l1));
10206
10207 // Then one step Halley's method
10208 let dl = l1 - l0;
10209 let dc = c1;
10210 let kl = vdot(LabtoLMS_M[0].slice(1), [a, b]);
10211 let km = vdot(LabtoLMS_M[1].slice(1), [a, b]);
10212 let ks = vdot(LabtoLMS_M[2].slice(1), [a, b]);
10213 let ldt_ = dl + dc * kl;
10214 let mdt_ = dl + dc * km;
10215 let sdt_ = dl + dc * ks;
10216
10217 // If higher accuracy is required, 2 or 3 iterations of the following block can be used:
10218 let L = l0 * (1.0 - t) + t * l1;
10219 let C = t * c1;
10220 let l_ = L + C * kl;
10221 let m_ = L + C * km;
10222 let s_ = L + C * ks;
10223 let l = l_ ** 3;
10224 let m = m_ ** 3;
10225 let s = s_ ** 3;
10226 let ldt = 3 * ldt_ * l_ ** 2;
10227 let mdt = 3 * mdt_ * m_ ** 2;
10228 let sdt = 3 * sdt_ * s_ ** 2;
10229 let ldt2 = 6 * ldt_ ** 2 * l_;
10230 let mdt2 = 6 * mdt_ ** 2 * m_;
10231 let sdt2 = 6 * sdt_ ** 2 * s_;
10232 let r_ = vdot(lmsToRgb[0], [l, m, s]) - 1;
10233 let r1 = vdot(lmsToRgb[0], [ldt, mdt, sdt]);
10234 let r2 = vdot(lmsToRgb[0], [ldt2, mdt2, sdt2]);
10235 let ur = r1 / (r1 * r1 - 0.5 * r_ * r2);
10236 let tr = -r_ * ur;
10237 let g_ = vdot(lmsToRgb[1], [l, m, s]) - 1;
10238 let g1 = vdot(lmsToRgb[1], [ldt, mdt, sdt]);
10239 let g2 = vdot(lmsToRgb[1], [ldt2, mdt2, sdt2]);
10240 let ug = g1 / (g1 * g1 - 0.5 * g_ * g2);
10241 let tg = -g_ * ug;
10242 let b_ = vdot(lmsToRgb[2], [l, m, s]) - 1;
10243 let b1 = vdot(lmsToRgb[2], [ldt, mdt, sdt]);
10244 let b2 = vdot(lmsToRgb[2], [ldt2, mdt2, sdt2]);
10245 let ub = b1 / (b1 * b1 - 0.5 * b_ * b2);
10246 let tb = -b_ * ub;
10247 tr = ur >= 0.0 ? tr : floatMax;
10248 tg = ug >= 0.0 ? tg : floatMax;
10249 tb = ub >= 0.0 ? tb : floatMax;
10250 t += Math.min(tr, Math.min(tg, tb));
10251 }
10252 return t;
10253 }
10254 function getCs(lab, lmsToRgb, okCoeff) {
10255 // Get Cs
10256
10257 let [l, a, b] = lab;
10258 let cusp = findCusp(a, b, lmsToRgb, okCoeff);
10259 let cMax = findGamutIntersection(a, b, l, 1, l, lmsToRgb, okCoeff, cusp);
10260 let stMax = toSt(cusp);
10261
10262 // Scale factor to compensate for the curved part of gamut shape:
10263 let k = cMax / Math.min(l * stMax[0], (1 - l) * stMax[1]);
10264 let stMid = getStMid(a, b);
10265
10266 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
10267 let ca = l * stMid[0];
10268 let cb = (1.0 - l) * stMid[1];
10269 let cMid = 0.9 * k * Math.sqrt(Math.sqrt(1.0 / (1.0 / ca ** 4 + 1.0 / cb ** 4)));
10270
10271 // For `C_0`, the shape is independent of hue, so `ST` are constant.
10272 // Values picked to roughly be the average values of `ST`.
10273 ca = l * 0.4;
10274 cb = (1.0 - l) * 0.8;
10275
10276 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
10277 let c0 = Math.sqrt(1.0 / (1.0 / ca ** 2 + 1.0 / cb ** 2));
10278 return [c0, cMid, cMax];
10279 }
10280 function computeMaxSaturation(a, b, lmsToRgb, okCoeff) {
10281 // Finds the maximum saturation possible for a given hue that fits in RGB.
10282 //
10283 // Saturation here is defined as `S = C/L`.
10284 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
10285
10286 // Max saturation will be when one of r, g or b goes below zero.
10287
10288 // Select different coefficients depending on which component goes below zero first.
10289
10290 let k0, k1, k2, k3, k4, wl, wm, ws;
10291 if (vdot(okCoeff[0][0], [a, b]) > 1) {
10292 // Red component
10293 [k0, k1, k2, k3, k4] = okCoeff[0][1];
10294 [wl, wm, ws] = lmsToRgb[0];
10295 } else if (vdot(okCoeff[1][0], [a, b]) > 1) {
10296 // Green component
10297 [k0, k1, k2, k3, k4] = okCoeff[1][1];
10298 [wl, wm, ws] = lmsToRgb[1];
10299 } else {
10300 // Blue component
10301 [k0, k1, k2, k3, k4] = okCoeff[2][1];
10302 [wl, wm, ws] = lmsToRgb[2];
10303 }
10304
10305 // Approximate max saturation using a polynomial:
10306 let sat = k0 + k1 * a + k2 * b + k3 * a ** 2 + k4 * a * b;
10307
10308 // Do one step Halley's method to get closer.
10309 // This gives an error less than 10e6, except for some blue hues where the `dS/dh` is close to infinite.
10310 // This should be sufficient for most applications, otherwise do two/three steps.
10311
10312 let kl = vdot(LabtoLMS_M[0].slice(1), [a, b]);
10313 let km = vdot(LabtoLMS_M[1].slice(1), [a, b]);
10314 let ks = vdot(LabtoLMS_M[2].slice(1), [a, b]);
10315 let l_ = 1.0 + sat * kl;
10316 let m_ = 1.0 + sat * km;
10317 let s_ = 1.0 + sat * ks;
10318 let l = l_ ** 3;
10319 let m = m_ ** 3;
10320 let s = s_ ** 3;
10321 let lds = 3.0 * kl * l_ ** 2;
10322 let mds = 3.0 * km * m_ ** 2;
10323 let sds = 3.0 * ks * s_ ** 2;
10324 let lds2 = 6.0 * kl ** 2 * l_;
10325 let mds2 = 6.0 * km ** 2 * m_;
10326 let sds2 = 6.0 * ks ** 2 * s_;
10327 let f = wl * l + wm * m + ws * s;
10328 let f1 = wl * lds + wm * mds + ws * sds;
10329 let f2 = wl * lds2 + wm * mds2 + ws * sds2;
10330 sat = sat - f * f1 / (f1 ** 2 - 0.5 * f * f2);
10331 return sat;
10332 }
10333 function okhslToOklab(hsl, lmsToRgb, okCoeff) {
10334 // Convert Okhsl to Oklab.
10335
10336 let [h, s, l] = hsl;
10337 let L = toeInv(l);
10338 let a = null;
10339 let b = null;
10340 h = constrain(h) / 360.0;
10341 if (L !== 0.0 && L !== 1.0 && s !== 0) {
10342 let a_ = Math.cos(tau * h);
10343 let b_ = Math.sin(tau * h);
10344 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
10345
10346 // Interpolate the three values for C so that:
10347 // ```
10348 // At s=0: dC/ds = C_0, C=0
10349 // At s=0.8: C=C_mid
10350 // At s=1.0: C=C_max
10351 // ```
10352
10353 let mid = 0.8;
10354 let midInv = 1.25;
10355 let t, k0, k1, k2;
10356 if (s < mid) {
10357 t = midInv * s;
10358 k0 = 0.0;
10359 k1 = mid * c0;
10360 k2 = 1.0 - k1 / cMid;
10361 } else {
10362 t = 5 * (s - 0.8);
10363 k0 = cMid;
10364 k1 = 0.2 * cMid ** 2 * 1.25 ** 2 / c0;
10365 k2 = 1.0 - k1 / (cMax - cMid);
10366 }
10367 let c = k0 + t * k1 / (1.0 - k2 * t);
10368 a = c * a_;
10369 b = c * b_;
10370 }
10371 return [L, a, b];
10372 }
10373 function oklabToOkhsl(lab, lmsToRgb, okCoeff) {
10374 // Oklab to Okhsl.
10375
10376 // Epsilon for lightness should approach close to 32 bit lightness
10377 // Epsilon for saturation just needs to be sufficiently close when denoting achromatic
10378 let εL = 1e-7;
10379 let εS = 1e-4;
10380 let L = lab[0];
10381 let s = 0.0;
10382 let l = toe(L);
10383 let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2);
10384 let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau;
10385 if (l !== 0.0 && l !== 1.0 && c !== 0) {
10386 let a_ = lab[1] / c;
10387 let b_ = lab[2] / c;
10388 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
10389 let mid = 0.8;
10390 let midInv = 1.25;
10391 let k0, k1, k2, t;
10392 if (c < cMid) {
10393 k1 = mid * c0;
10394 k2 = 1.0 - k1 / cMid;
10395 t = c / (k1 + k2 * c);
10396 s = t * mid;
10397 } else {
10398 k0 = cMid;
10399 k1 = 0.2 * cMid ** 2 * midInv ** 2 / c0;
10400 k2 = 1.0 - k1 / (cMax - cMid);
10401 t = (c - k0) / (k1 + k2 * (c - k0));
10402 s = mid + 0.2 * t;
10403 }
10404 }
10405 const achromatic = Math.abs(s) < εS;
10406 if (achromatic || l === 0.0 || Math.abs(1 - l) < εL) {
10407 h = null;
10408 // Due to floating point imprecision near lightness of 1, we can end up
10409 // with really high around white, this is to provide consistency as
10410 // saturation can be really high for white due this imprecision.
10411 if (!achromatic) {
10412 s = 0.0;
10413 }
10414 } else {
10415 h = constrain(h * 360);
10416 }
10417 return [h, s, l];
10418 }
10419 const Okhsl = new ColorSpace({
10420 id: "okhsl",
10421 name: "Okhsl",
10422 coords: {
10423 h: {
10424 refRange: [0, 360],
10425 type: "angle",
10426 name: "Hue"
10427 },
10428 s: {
10429 range: [0, 1],
10430 name: "Saturation"
10431 },
10432 l: {
10433 range: [0, 1],
10434 name: "Lightness"
10435 }
10436 },
10437 base: Oklab,
10438 gamutSpace: "self",
10439 // Convert Oklab to Okhsl
10440 fromBase(lab) {
10441 return oklabToOkhsl(lab, toSRGBLinear, RGBCoeff);
10442 },
10443 // Convert Okhsl to Oklab
10444 toBase(hsl) {
10445 return okhslToOklab(hsl, toSRGBLinear, RGBCoeff);
10446 },
10447 formats: {
10448 color: {
10449 id: "--okhsl",
10450 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
10451 }
10452 }
10453 });
10454 Okhsl.rgbGamut = new RGBColorSpace({
10455 id: "okhsl-prism",
10456 cssId: "--okhsl-prism",
10457 name: "Okhsl Prism",
10458 base: Okhsl,
10459 fromBase(hsl) {
10460 return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]);
10461 },
10462 toBase(rgb) {
10463 const hsl = HSL.fromBase(rgb);
10464 hsl[1] /= 100;
10465 hsl[2] /= 100;
10466 return hsl;
10467 }
10468 });
10469
10470 var OKLrab = new ColorSpace({
10471 id: "oklrab",
10472 name: "Oklrab",
10473 coords: {
10474 l: {
10475 refRange: [0, 1],
10476 name: "Lightness"
10477 },
10478 a: {
10479 refRange: [-0.4, 0.4]
10480 },
10481 b: {
10482 refRange: [-0.4, 0.4]
10483 }
10484 },
10485 // Note that XYZ is relative to D65
10486 white: "D65",
10487 base: Oklab,
10488 fromBase(oklab) {
10489 return [toe(oklab[0]), oklab[1], oklab[2]];
10490 },
10491 toBase(oklrab) {
10492 return [toeInv(oklrab[0]), oklrab[1], oklrab[2]];
10493 },
10494 formats: {
10495 color: {
10496 coords: ["<percentage> | <number>", "<number> | <percentage>[-1,1]", "<number> | <percentage>[-1,1]"]
10497 }
10498 }
10499 });
10500
10501 var oklrch = new ColorSpace({
10502 id: "oklrch",
10503 name: "Oklrch",
10504 coords: {
10505 l: {
10506 refRange: [0, 1],
10507 name: "Lightness"
10508 },
10509 c: {
10510 refRange: [0, 0.4],
10511 name: "Chroma"
10512 },
10513 h: {
10514 refRange: [0, 360],
10515 type: "angle",
10516 name: "Hue"
10517 }
10518 },
10519 white: "D65",
10520 base: OKLrab,
10521 fromBase: lch.fromBase,
10522 toBase: lch.toBase,
10523 formats: {
10524 color: {
10525 coords: ["<percentage> | <number>", "<number> | <percentage>[0,1]", "<number> | <angle>"]
10526 }
10527 }
10528 });
10529
10530 // Okhsv class.
10531 //
10532 // ---- License ----
10533 //
10534 // Copyright (c) 2021 Björn Ottosson
10535 //
10536 // Permission is hereby granted, free of charge, to any person obtaining a copy of
10537 // this software and associated documentation files (the "Software"), to deal in
10538 // the Software without restriction, including without limitation the rights to
10539 // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10540 // of the Software, and to permit persons to whom the Software is furnished to do
10541 // so, subject to the following conditions:
10542 //
10543 // The above copyright notice and this permission notice shall be included in all
10544 // copies or substantial portions of the Software.
10545 //
10546 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
10547 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
10548 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
10549 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
10550 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
10551 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
10552 // SOFTWARE.
10553
10554 /** @import { Coords, Matrix3x3, OKCoeff, Vector3 } from "../types.js" */
10555
10556 /**
10557 *
10558 * @param {Vector3} hsv
10559 * @param {Matrix3x3} lmsToRgb
10560 * @param {OKCoeff} okCoeff
10561 * @returns {Coords}
10562 */
10563 function okhsvToOklab(hsv, lmsToRgb, okCoeff) {
10564 // Convert from Okhsv to Oklab."""
10565
10566 let [h, s, v] = hsv;
10567 h = constrain(h) / 360.0;
10568 let l = toeInv(v);
10569 let a = null;
10570 let b = null;
10571
10572 // Avoid processing gray or colors with undefined hues
10573 if (l !== 0.0 && s !== 0.0) {
10574 let a_ = Math.cos(tau * h);
10575 let b_ = Math.sin(tau * h);
10576 let cusp = findCusp(a_, b_, lmsToRgb, okCoeff);
10577 let [sMax, tMax] = toSt(cusp);
10578 let s0 = 0.5;
10579 let k = 1 - s0 / sMax;
10580
10581 // first we compute L and V as if the gamut is a perfect triangle:
10582
10583 // L, C when v==1:
10584 let lv = 1 - s * s0 / (s0 + tMax - tMax * k * s);
10585 let cv = s * tMax * s0 / (s0 + tMax - tMax * k * s);
10586 l = v * lv;
10587 let c = v * cv;
10588
10589 // then we compensate for both toe and the curved top part of the triangle:
10590 let lvt = toeInv(lv);
10591 let cvt = cv * lvt / lv;
10592 let lNew = toeInv(l);
10593 c = c * lNew / l;
10594 l = lNew;
10595
10596 // RGB scale
10597 let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb);
10598 let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3);
10599 l = l * scaleL;
10600 c = c * scaleL;
10601 a = c * a_;
10602 b = c * b_;
10603 }
10604 return [l, a, b];
10605 }
10606
10607 /**
10608 *
10609 * @param {Vector3} lab
10610 * @param {Matrix3x3} lmsToRgb
10611 * @param {OKCoeff} okCoeff
10612 * @returns {Coords}
10613 */
10614 function oklabToOkhsv(lab, lmsToRgb, okCoeff) {
10615 // Oklab to Okhsv.
10616
10617 // Epsilon for saturation just needs to be sufficiently close when denoting achromatic
10618 let ε = 1e-4;
10619 let l = lab[0];
10620 let s = 0.0;
10621 let v = toe(l);
10622 let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2);
10623 let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau;
10624 if (l !== 0.0 && l !== 1 && c !== 0.0) {
10625 let a_ = lab[1] / c;
10626 let b_ = lab[2] / c;
10627 let cusp = findCusp(a_, b_, lmsToRgb, okCoeff);
10628 let [sMax, tMax] = toSt(cusp);
10629 let s0 = 0.5;
10630 let k = 1 - s0 / sMax;
10631
10632 // first we find `L_v`, `C_v`, `L_vt` and `C_vt`
10633 let t = tMax / (c + l * tMax);
10634 let lv = t * l;
10635 let cv = t * c;
10636 let lvt = toeInv(lv);
10637 let cvt = cv * lvt / lv;
10638
10639 // we can then use these to invert the step that compensates
10640 // for the toe and the curved top part of the triangle:
10641 let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb);
10642 let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3);
10643 l = l / scaleL;
10644 c = c / scaleL;
10645 c = c * toe(l) / l;
10646 l = toe(l);
10647
10648 // we can now compute v and s:
10649 v = l / lv;
10650 s = (s0 + tMax) * cv / (tMax * s0 + tMax * k * cv);
10651 }
10652 if (Math.abs(s) < ε || v === 0.0) {
10653 h = null;
10654 } else {
10655 h = constrain(h * 360);
10656 }
10657 return [h, s, v];
10658 }
10659 const Okhsv = new ColorSpace({
10660 id: "okhsv",
10661 name: "Okhsv",
10662 coords: {
10663 h: {
10664 refRange: [0, 360],
10665 type: "angle",
10666 name: "Hue"
10667 },
10668 s: {
10669 range: [0, 1],
10670 name: "Saturation"
10671 },
10672 v: {
10673 range: [0, 1],
10674 name: "Value"
10675 }
10676 },
10677 base: Oklab,
10678 gamutSpace: "self",
10679 // Convert Oklab to Okhsl
10680 fromBase(lab) {
10681 return oklabToOkhsv(lab, toSRGBLinear, RGBCoeff);
10682 },
10683 // Convert Okhsl to Oklab
10684 toBase(hsl) {
10685 return okhsvToOklab(hsl, toSRGBLinear, RGBCoeff);
10686 },
10687 formats: {
10688 color: {
10689 id: "--okhsv",
10690 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
10691 }
10692 }
10693 });
10694 Okhsv.rgbGamut = new RGBColorSpace({
10695 id: "okhsv-prism",
10696 cssId: "--okhsv-prism",
10697 name: "Okhsv Prism",
10698 base: Okhsv,
10699 fromBase(hsl) {
10700 return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]);
10701 },
10702 toBase(rgb) {
10703 const hsl = HSL.fromBase(rgb);
10704 hsl[1] /= 100;
10705 hsl[2] /= 100;
10706 return hsl;
10707 }
10708 });
10709
10710 let white = WHITES.D65;
10711 const ε$2 = 216 / 24389; // 6^3/29^3 == (24/116)^3
10712 const κ$1 = 24389 / 27; // 29^3/3^3
10713 const [U_PRIME_WHITE, V_PRIME_WHITE] = uv({
10714 space: XYZ_D65,
10715 coords: white
10716 });
10717 var Luv = new ColorSpace({
10718 id: "luv",
10719 name: "Luv",
10720 coords: {
10721 l: {
10722 refRange: [0, 100],
10723 name: "Lightness"
10724 },
10725 // Reference ranges from https://facelessuser.github.io/coloraide/colors/luv/
10726 u: {
10727 refRange: [-215, 215]
10728 },
10729 v: {
10730 refRange: [-215, 215]
10731 }
10732 },
10733 white: white,
10734 base: XYZ_D65,
10735 // Convert D65-adapted XYZ to Luv
10736 // https://en.wikipedia.org/wiki/CIELUV#The_forward_transformation
10737 fromBase(XYZ) {
10738 let xyz = /** @type {[number, number, number]} */[skipNone(XYZ[0]), skipNone(XYZ[1]), skipNone(XYZ[2])];
10739 let y = xyz[1];
10740 let [up, vp] = uv({
10741 space: XYZ_D65,
10742 coords: xyz
10743 });
10744
10745 // Protect against XYZ of [0, 0, 0]
10746 if (!Number.isFinite(up) || !Number.isFinite(vp)) {
10747 return [0, 0, 0];
10748 }
10749 let L = y <= ε$2 ? κ$1 * y : 116 * Math.cbrt(y) - 16;
10750 return [L, 13 * L * (up - U_PRIME_WHITE), 13 * L * (vp - V_PRIME_WHITE)];
10751 },
10752 // Convert Luv to D65-adapted XYZ
10753 // https://en.wikipedia.org/wiki/CIELUV#The_reverse_transformation
10754 toBase(Luv) {
10755 let [L, u, v] = Luv;
10756
10757 // Protect against division by zero and none Lightness
10758 if (L === 0 || isNone(L)) {
10759 return [0, 0, 0];
10760 }
10761 u = skipNone(u);
10762 v = skipNone(v);
10763 let up = u / (13 * L) + U_PRIME_WHITE;
10764 let vp = v / (13 * L) + V_PRIME_WHITE;
10765 let y = L <= 8 ? L / κ$1 : Math.pow((L + 16) / 116, 3);
10766 return [y * (9 * up / (4 * vp)), y, y * ((12 - 3 * up - 20 * vp) / (4 * vp))];
10767 },
10768 formats: {
10769 color: {
10770 id: "--luv",
10771 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <percentage>"]
10772 }
10773 }
10774 });
10775
10776 var LCHuv = new ColorSpace({
10777 id: "lchuv",
10778 name: "LChuv",
10779 coords: {
10780 l: {
10781 refRange: [0, 100],
10782 name: "Lightness"
10783 },
10784 c: {
10785 refRange: [0, 220],
10786 name: "Chroma"
10787 },
10788 h: {
10789 refRange: [0, 360],
10790 type: "angle",
10791 name: "Hue"
10792 }
10793 },
10794 base: Luv,
10795 fromBase: lch.fromBase,
10796 toBase: lch.toBase,
10797 formats: {
10798 color: {
10799 id: "--lchuv",
10800 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <angle>"]
10801 }
10802 }
10803 });
10804
10805 /*
10806 Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts
10807
10808 Copyright (c) 2012-2022 Alexei Boronine
10809
10810 Permission is hereby granted, free of charge, to any person obtaining a copy
10811 of this software and associated documentation files (the "Software"), to deal
10812 in the Software without restriction, including without limitation the rights
10813 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10814 copies of the Software, and to permit persons to whom the Software is
10815 furnished to do so, subject to the following conditions:
10816
10817 The above copyright notice and this permission notice shall be included in all
10818 copies or substantial portions of the Software.
10819
10820 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
10821 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
10822 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
10823 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
10824 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
10825 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
10826 SOFTWARE.
10827 */
10828
10829 const ε$1 = 216 / 24389; // 6^3/29^3 == (24/116)^3
10830 const κ = 24389 / 27; // 29^3/3^3
10831
10832 const m_r0 = fromXYZ_M$3[0][0];
10833 const m_r1 = fromXYZ_M$3[0][1];
10834 const m_r2 = fromXYZ_M$3[0][2];
10835 const m_g0 = fromXYZ_M$3[1][0];
10836 const m_g1 = fromXYZ_M$3[1][1];
10837 const m_g2 = fromXYZ_M$3[1][2];
10838 const m_b0 = fromXYZ_M$3[2][0];
10839 const m_b1 = fromXYZ_M$3[2][1];
10840 const m_b2 = fromXYZ_M$3[2][2];
10841 function distanceFromOriginAngle(slope, intercept, angle) {
10842 const d = intercept / (Math.sin(angle) - slope * Math.cos(angle));
10843 return d < 0 ? Infinity : d;
10844 }
10845
10846 /**
10847 * @param {number} l
10848 */
10849 function calculateBoundingLines(l) {
10850 const sub1 = Math.pow(l + 16, 3) / 1560896;
10851 const sub2 = sub1 > ε$1 ? sub1 : l / κ;
10852 const s1r = sub2 * (284517 * m_r0 - 94839 * m_r2);
10853 const s2r = sub2 * (838422 * m_r2 + 769860 * m_r1 + 731718 * m_r0);
10854 const s3r = sub2 * (632260 * m_r2 - 126452 * m_r1);
10855 const s1g = sub2 * (284517 * m_g0 - 94839 * m_g2);
10856 const s2g = sub2 * (838422 * m_g2 + 769860 * m_g1 + 731718 * m_g0);
10857 const s3g = sub2 * (632260 * m_g2 - 126452 * m_g1);
10858 const s1b = sub2 * (284517 * m_b0 - 94839 * m_b2);
10859 const s2b = sub2 * (838422 * m_b2 + 769860 * m_b1 + 731718 * m_b0);
10860 const s3b = sub2 * (632260 * m_b2 - 126452 * m_b1);
10861 return {
10862 r0s: s1r / s3r,
10863 r0i: s2r * l / s3r,
10864 r1s: s1r / (s3r + 126452),
10865 r1i: (s2r - 769860) * l / (s3r + 126452),
10866 g0s: s1g / s3g,
10867 g0i: s2g * l / s3g,
10868 g1s: s1g / (s3g + 126452),
10869 g1i: (s2g - 769860) * l / (s3g + 126452),
10870 b0s: s1b / s3b,
10871 b0i: s2b * l / s3b,
10872 b1s: s1b / (s3b + 126452),
10873 b1i: (s2b - 769860) * l / (s3b + 126452)
10874 };
10875 }
10876 function calcMaxChromaHsluv(lines, h) {
10877 const hueRad = h / 360 * Math.PI * 2;
10878 const r0 = distanceFromOriginAngle(lines.r0s, lines.r0i, hueRad);
10879 const r1 = distanceFromOriginAngle(lines.r1s, lines.r1i, hueRad);
10880 const g0 = distanceFromOriginAngle(lines.g0s, lines.g0i, hueRad);
10881 const g1 = distanceFromOriginAngle(lines.g1s, lines.g1i, hueRad);
10882 const b0 = distanceFromOriginAngle(lines.b0s, lines.b0i, hueRad);
10883 const b1 = distanceFromOriginAngle(lines.b1s, lines.b1i, hueRad);
10884 return Math.min(r0, r1, g0, g1, b0, b1);
10885 }
10886 var hsluv = new ColorSpace({
10887 id: "hsluv",
10888 name: "HSLuv",
10889 coords: {
10890 h: {
10891 refRange: [0, 360],
10892 type: "angle",
10893 name: "Hue"
10894 },
10895 s: {
10896 range: [0, 100],
10897 name: "Saturation"
10898 },
10899 l: {
10900 range: [0, 100],
10901 name: "Lightness"
10902 }
10903 },
10904 base: LCHuv,
10905 gamutSpace: sRGB,
10906 rgbGamut: sRGB,
10907 // Convert LCHuv to HSLuv
10908 fromBase(lch) {
10909 let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])];
10910 let s;
10911 if (l > 99.9999999) {
10912 s = 0;
10913 l = 100;
10914 } else if (l < 0.00000001) {
10915 s = 0;
10916 l = 0;
10917 } else {
10918 let lines = calculateBoundingLines(l);
10919 let max = calcMaxChromaHsluv(lines, h);
10920 s = c / max * 100;
10921 }
10922 return [h, s, l];
10923 },
10924 // Convert HSLuv to LCHuv
10925 toBase(hsl) {
10926 let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])];
10927 let c;
10928 if (l > 99.9999999) {
10929 l = 100;
10930 c = 0;
10931 } else if (l < 0.00000001) {
10932 l = 0;
10933 c = 0;
10934 } else {
10935 let lines = calculateBoundingLines(l);
10936 let max = calcMaxChromaHsluv(lines, h);
10937 c = max / 100 * s;
10938 }
10939 return [l, c, h];
10940 },
10941 formats: {
10942 color: {
10943 id: "--hsluv",
10944 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
10945 }
10946 }
10947 });
10948
10949 /*
10950 Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts
10951
10952 Copyright (c) 2012-2022 Alexei Boronine
10953
10954 Permission is hereby granted, free of charge, to any person obtaining a copy
10955 of this software and associated documentation files (the "Software"), to deal
10956 in the Software without restriction, including without limitation the rights
10957 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10958 copies of the Software, and to permit persons to whom the Software is
10959 furnished to do so, subject to the following conditions:
10960
10961 The above copyright notice and this permission notice shall be included in all
10962 copies or substantial portions of the Software.
10963
10964 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
10965 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
10966 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
10967 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
10968 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
10969 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
10970 SOFTWARE.
10971 */
10972
10973
10974 fromXYZ_M$3[0][0];
10975 fromXYZ_M$3[0][1];
10976 fromXYZ_M$3[0][2];
10977 fromXYZ_M$3[1][0];
10978 fromXYZ_M$3[1][1];
10979 fromXYZ_M$3[1][2];
10980 fromXYZ_M$3[2][0];
10981 fromXYZ_M$3[2][1];
10982 fromXYZ_M$3[2][2];
10983 function distanceFromOrigin(slope, intercept) {
10984 return Math.abs(intercept) / Math.sqrt(Math.pow(slope, 2) + 1);
10985 }
10986 function calcMaxChromaHpluv(lines) {
10987 let r0 = distanceFromOrigin(lines.r0s, lines.r0i);
10988 let r1 = distanceFromOrigin(lines.r1s, lines.r1i);
10989 let g0 = distanceFromOrigin(lines.g0s, lines.g0i);
10990 let g1 = distanceFromOrigin(lines.g1s, lines.g1i);
10991 let b0 = distanceFromOrigin(lines.b0s, lines.b0i);
10992 let b1 = distanceFromOrigin(lines.b1s, lines.b1i);
10993 return Math.min(r0, r1, g0, g1, b0, b1);
10994 }
10995 const HPLuv = new ColorSpace({
10996 id: "hpluv",
10997 name: "HPLuv",
10998 coords: {
10999 h: {
11000 refRange: [0, 360],
11001 type: "angle",
11002 name: "Hue"
11003 },
11004 s: {
11005 range: [0, 100],
11006 name: "Saturation"
11007 },
11008 l: {
11009 range: [0, 100],
11010 name: "Lightness"
11011 }
11012 },
11013 base: LCHuv,
11014 gamutSpace: "self",
11015 // Convert LCHuv to HPLuv
11016 fromBase(lch) {
11017 let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])];
11018 let s;
11019 if (l > 99.9999999) {
11020 s = 0;
11021 l = 100;
11022 } else if (l < 0.00000001) {
11023 s = 0;
11024 l = 0;
11025 } else {
11026 let lines = calculateBoundingLines(l);
11027 let max = calcMaxChromaHpluv(lines);
11028 s = c / max * 100;
11029 }
11030 return [h, s, l];
11031 },
11032 // Convert HPLuv to LCHuv
11033 toBase(hsl) {
11034 let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])];
11035 let c;
11036 if (l > 99.9999999) {
11037 l = 100;
11038 c = 0;
11039 } else if (l < 0.00000001) {
11040 l = 0;
11041 c = 0;
11042 } else {
11043 let lines = calculateBoundingLines(l);
11044 let max = calcMaxChromaHpluv(lines);
11045 c = max / 100 * s;
11046 }
11047 return [l, c, h];
11048 },
11049 formats: {
11050 color: {
11051 id: "--hpluv",
11052 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
11053 }
11054 }
11055 });
11056 HPLuv.rgbGamut = new RGBColorSpace({
11057 id: "hpluv-prism",
11058 cssId: "--hpluv-prism",
11059 name: "HPLuv Prism",
11060 base: HPLuv,
11061 fromBase(hsl) {
11062 return HSL.toBase(hsl);
11063 },
11064 toBase(rgb) {
11065 return HSL.fromBase(rgb);
11066 }
11067 });
11068
11069 /**
11070 * Helmlab GenSpace — generation-optimized color space for interpolation.
11071 *
11072 * Pipeline (v0.11.1, depressed cubic + chroma power + L-gated enrichment):
11073 * XYZ → M1 → depcubic(α=0.021) → M2 → chroma_power(0.978) →
11074 * PW_L → L-gated hue enrichment → Lab
11075 *
11076 * Optimized for perceptually uniform gradients, palette generation,
11077 * and color-mix. 59-8 vs OKLab in head-to-head benchmarks (83 metrics,
11078 * 3038 gradient pairs, sRGB/P3/Rec.2020). 360/360/360 cusps.
11079 *
11080 * Key properties:
11081 * - Depressed cubic: y³ + αy = x, finite derivative at zero
11082 * - Chroma power (0.978): improves gradient CV uniformity
11083 * - L-gated hue enrichment: fixes blue→white purple shift
11084 * - Structurally achromatic: a=b≈0 for all grays
11085 *
11086 * Note on blue-region gamut fold:
11087 * All M1→f→M2 spaces (OKLab, IPT, HelmGen) exhibit a tiny non-contiguous
11088 * gamut region near h≈260° in sRGB. This is a mathematical consequence of
11089 * mixing LMS channels before applying a power-like transfer: the inverse
11090 * creates a cubic polynomial that can have two positive roots in the blue
11091 * region. OKLab has 46 such holes; HelmGen has 5, each ~0.001 chroma wide
11092 * (sub-pixel, invisible). See: color.js#81, csswg-drafts#7071.
11093 *
11094 * Reference: arXiv:2602.23010
11095 * @see https://github.com/Grkmyldz148/helmlab
11096 */
11097
11098 /** @import { Matrix3x3 } from "../types.js" */
11099
11100 // ── Depressed cubic parameter ──────────────────────────────────────
11101 const ALPHA = 0.021;
11102 const S = Math.sqrt(ALPHA / 3);
11103 const S3 = S * S * S;
11104
11105 // ── Chroma power ───────────────────────────────────────────────────
11106 const CP = 0.978;
11107
11108 // ── L-gated hue enrichment parameters ──────────────────────────────
11109 const ENR_AMP = 0.058;
11110 const ENR_CENTER = 264.5 * Math.PI / 180; // radians
11111 const ENR_SIGMA = 0.7;
11112 const ENR_LLO = 0.37;
11113 const ENR_LHI = 1.0;
11114
11115 // ── Core matrices (v0.11.1) ────────────────────────────────────────
11116
11117 /** @type {Matrix3x3} */
11118 // prettier-ignore
11119 // M1 = M1_orig @ CAT_TO_HELM (Bradford CAT baked in: Color.js D65 → Helmlab D65 → LMS)
11120 const M1 = [[8.1548321559412884e-01, 3.6033406153856506e-01, -1.2434135574228214e-01], [3.3010083527450780e-02, 9.2928650570661686e-01, 3.6121927165754429e-02], [4.8188273564568611e-02, 2.6428415753384238e-01, 6.3349717841955344e-01]];
11121 /** @type {Matrix3x3} */
11122 // prettier-ignore
11123 const M1_INV = [[1.2325947975032656e+00, -5.5575902392875232e-01, 2.7362015347715829e-01], [-4.0801327874216024e-02, 1.1122288637386530e+00, -7.1427535864437813e-02], [-7.6738259283377658e-02, -4.2172784577108585e-01, 1.5875238558143416e+00]];
11124
11125 /** @type {Matrix3x3} */
11126 // prettier-ignore
11127 const M2 = [[0.21193779684470104, 0.7992121834263127, -0.00410075161564345], [2.4672018828033475, -2.9877348024830788, 0.520532919679731], [-0.11390787868068575, 1.3932982808117473, -1.279390402131062]];
11128 /** @type {Matrix3x3} */
11129 // prettier-ignore
11130 const M2_INV = [[0.9930001151336143, 0.32599327253052285, 0.12945085631713921], [0.9930001151336139, -0.08708353111074627, -0.03861361743004929], [0.9930001151336136, -0.12386097008215022, -0.8351991365871061]];
11131
11132 // ── Piecewise-linear L correction (21 breakpoints, v0.11.1) ───────
11133 // prettier-ignore
11134 const PW_L_IN = [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0];
11135 // prettier-ignore
11136 const PW_L_OUT = [0, 0.009494013522189627, 0.02564569838030986, 0.055259661658689105, 0.10574901531227408, 0.16055853320726027, 0.21405964892993756, 0.26786230508811226, 0.3220435246104499, 0.3739052098520243, 0.43020997780918835, 0.4835465162128873, 0.5399824670411353, 0.5956710081330342, 0.6542161666450478, 0.7115380216519989, 0.7702762412711669, 0.8293313467712837, 0.889406386197059, 0.9462829573474728, 1.0];
11137 const PW_N = PW_L_IN.length;
11138
11139 // ── Depressed cubic: y³ + αy = x ──────────────────────────────────
11140
11141 function depcubicFwd(x) {
11142 let t = x / (2 * S3);
11143 let y = 2 * S * Math.sinh(Math.asinh(t) / 3);
11144 // Halley refinement
11145 let f = y * y * y + ALPHA * y - x;
11146 let fp = 3 * y * y + ALPHA;
11147 let fpp = 6 * y;
11148 let denom = 2 * fp * fp - f * fpp;
11149 if (Math.abs(denom) > 1e-30) {
11150 y -= 2 * f * fp / denom;
11151 }
11152 return y;
11153 }
11154 function depcubicInv(y) {
11155 return y * y * y + ALPHA * y;
11156 }
11157
11158 // ── L-gated hue enrichment ─────────────────────────────────────────
11159
11160 function enrichGate(L) {
11161 let t = Math.max(0, Math.min(1, (L - ENR_LLO) / (ENR_LHI - ENR_LLO)));
11162 return Math.sin(Math.PI * t) ** 2;
11163 }
11164 function enrichFwd(L, a, b) {
11165 let C = Math.sqrt(a * a + b * b);
11166 if (C < 1e-12) {
11167 return [a, b];
11168 }
11169 let gate = enrichGate(L);
11170 if (gate < 1e-12) {
11171 return [a, b];
11172 }
11173 let h = Math.atan2(b, a);
11174 let dh = h - ENR_CENTER;
11175 dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI;
11176 let gauss = Math.exp(-0.5 * (dh / ENR_SIGMA) ** 2);
11177 let hNew = h + ENR_AMP * gate * gauss;
11178 return [C * Math.cos(hNew), C * Math.sin(hNew)];
11179 }
11180 function enrichInv(L, a, b) {
11181 let C = Math.sqrt(a * a + b * b);
11182 if (C < 1e-12) {
11183 return [a, b];
11184 }
11185 let gate = enrichGate(L);
11186 if (gate < 1e-12) {
11187 return [a, b];
11188 }
11189 let hTarget = Math.atan2(b, a);
11190 let sig2 = ENR_SIGMA * ENR_SIGMA;
11191 let ag = ENR_AMP * gate;
11192 let h = hTarget;
11193 for (let i = 0; i < 8; i++) {
11194 let dh = h - ENR_CENTER;
11195 dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI;
11196 let gauss = Math.exp(-0.5 * dh * dh / sig2);
11197 let F = h + ag * gauss - hTarget;
11198 let Fp = 1 + ag * gauss * (-dh / sig2);
11199 let Fpp = ag * gauss * (-1 / sig2 + dh * dh / (sig2 * sig2));
11200 let den = 2 * Fp * Fp - F * Fpp;
11201 if (Math.abs(den) > 1e-30) {
11202 h -= 2 * F * Fp / den;
11203 }
11204 }
11205 return [C * Math.cos(h), C * Math.sin(h)];
11206 }
11207
11208 // ── PW L correction ───────────────────────────────────────────────
11209
11210 function pwLForward(L) {
11211 if (L <= 0 || L >= 1) {
11212 return L;
11213 }
11214 let lo = 0,
11215 hi = PW_N - 1;
11216 while (hi - lo > 1) {
11217 let mid = lo + hi >> 1;
11218 if (PW_L_IN[mid] <= L) {
11219 lo = mid;
11220 } else {
11221 hi = mid;
11222 }
11223 }
11224 let t = (L - PW_L_IN[lo]) / (PW_L_IN[hi] - PW_L_IN[lo]);
11225 return PW_L_OUT[lo] + t * (PW_L_OUT[hi] - PW_L_OUT[lo]);
11226 }
11227 function pwLInverse(L) {
11228 if (L <= PW_L_OUT[0] || L >= PW_L_OUT[PW_N - 1]) {
11229 return L;
11230 }
11231 let lo = 0,
11232 hi = PW_N - 1;
11233 while (hi - lo > 1) {
11234 let mid = lo + hi >> 1;
11235 if (PW_L_OUT[mid] <= L) {
11236 lo = mid;
11237 } else {
11238 hi = mid;
11239 }
11240 }
11241 let t = (L - PW_L_OUT[lo]) / (PW_L_OUT[hi] - PW_L_OUT[lo]);
11242 return PW_L_IN[lo] + t * (PW_L_IN[hi] - PW_L_IN[lo]);
11243 }
11244
11245 // ── Color space definition ─────────────────────────────────────────
11246
11247 var HelmGen = new ColorSpace({
11248 id: "helmgen",
11249 name: "HelmGen",
11250 cssId: "--helmgen",
11251 coords: {
11252 l: {
11253 refRange: [0, 1],
11254 name: "Lightness"
11255 },
11256 a: {
11257 refRange: [-0.6, 0.6]
11258 },
11259 b: {
11260 refRange: [-0.6, 0.6]
11261 }
11262 },
11263 white: "D65",
11264 base: XYZ_D65,
11265 fromBase(xyz) {
11266 // Stage 1: XYZ → LMS (M1)
11267 let lms = multiply_v3_m3x3(xyz, M1);
11268
11269 // Stage 2: Depressed cubic transfer (y³ + αy = x)
11270 let c0 = depcubicFwd(Math.max(lms[0], 0));
11271 let c1 = depcubicFwd(Math.max(lms[1], 0));
11272 let c2 = depcubicFwd(Math.max(lms[2], 0));
11273
11274 // Stage 2.5: Smooth neutral blend (C∞ correction for achromatic precision)
11275 {
11276 let mean = (c0 + c1 + c2) / 3;
11277 let mx = Math.max(c0, c1, c2);
11278 let mn = Math.min(c0, c1, c2);
11279 let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30);
11280 let w = Math.exp(-((spread / 1e-5) ** 2));
11281 c0 += w * (mean - c0);
11282 c1 += w * (mean - c1);
11283 c2 += w * (mean - c2);
11284 }
11285
11286 // Stage 3: LMS_c → Lab (M2)
11287 let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M2);
11288
11289 // Stage 3.5: Chroma power (cp=0.978)
11290 {
11291 let C = Math.sqrt(a * a + b * b);
11292 if (C > 1e-12) {
11293 let Cnew = Math.pow(C, CP);
11294 let s = Cnew / C;
11295 a *= s;
11296 b *= s;
11297 }
11298 }
11299
11300 // Stage 4: Piecewise-linear L correction
11301 L = pwLForward(L);
11302
11303 // Stage 5: L-gated hue enrichment
11304 [a, b] = enrichFwd(L, a, b);
11305 return [L, a, b];
11306 },
11307 toBase(lab) {
11308 let [L, a, b] = lab;
11309
11310 // Undo Stage 5: L-gated hue enrichment
11311 [a, b] = enrichInv(L, a, b);
11312
11313 // Undo Stage 4: PW L correction
11314 L = pwLInverse(L);
11315
11316 // Undo Stage 3.5: Chroma power inverse (C^(1/cp))
11317 {
11318 let C = Math.sqrt(a * a + b * b);
11319 if (C > 1e-12) {
11320 let Corig = Math.pow(C, 1 / CP);
11321 let s = Corig / C;
11322 a *= s;
11323 b *= s;
11324 }
11325 }
11326
11327 // Undo Stage 3: Lab → LMS_c (M2_inv)
11328 let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M2_INV);
11329
11330 // Undo Stage 2.5: Smooth neutral blend
11331 {
11332 let mean = (lc0 + lc1 + lc2) / 3;
11333 let mx = Math.max(lc0, lc1, lc2);
11334 let mn = Math.min(lc0, lc1, lc2);
11335 let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30);
11336 let w = Math.exp(-((spread / 1e-5) ** 2));
11337 lc0 += w * (mean - lc0);
11338 lc1 += w * (mean - lc1);
11339 lc2 += w * (mean - lc2);
11340 }
11341
11342 // Undo Stage 2: Inverse depressed cubic (x = y³ + αy)
11343 let l0 = depcubicInv(lc0);
11344 let l1 = depcubicInv(lc1);
11345 let l2 = depcubicInv(lc2);
11346
11347 // Undo Stage 1: LMS → XYZ (M1_inv)
11348 return multiply_v3_m3x3([l0, l1, l2], M1_INV);
11349 }
11350 });
11351
11352 /**
11353 * HelmGenLCh — cylindrical form of Helmlab GenSpace.
11354 *
11355 * Converts GenSpace's rectangular (L, a, b) coordinates to
11356 * cylindrical (L, C, h). Ideal for CSS interpolation contexts
11357 * like gradients and color-mix where hue angle matters.
11358 *
11359 * @see https://github.com/Grkmyldz148/helmlab
11360 */
11361 var helmgenlch = new ColorSpace({
11362 id: "helmgenlch",
11363 name: "HelmGenLCh",
11364 coords: {
11365 l: {
11366 refRange: [0, 1],
11367 name: "Lightness"
11368 },
11369 c: {
11370 refRange: [0, 0.65],
11371 name: "Chroma"
11372 },
11373 h: {
11374 refRange: [0, 360],
11375 type: "angle",
11376 name: "Hue"
11377 }
11378 },
11379 white: "D65",
11380 base: HelmGen,
11381 fromBase: lch.fromBase,
11382 toBase: lch.toBase
11383 });
11384
11385 var REC_2100_Linear = new RGBColorSpace({
11386 id: "rec2100-linear",
11387 name: "Linear REC.2100",
11388 white: "D65",
11389 toBase: REC_2020_Linear.toBase,
11390 fromBase: REC_2020_Linear.fromBase
11391 });
11392
11393 const Yw = 203; // absolute luminance of media white, cd/m²
11394 const n = 2610 / 2 ** 14;
11395 const ninv = 2 ** 14 / 2610;
11396 const m = 2523 / 2 ** 5;
11397 const minv = 2 ** 5 / 2523;
11398 const c1 = 3424 / 2 ** 12;
11399 const c2 = 2413 / 2 ** 7;
11400 const c3 = 2392 / 2 ** 7;
11401 var rec2100Pq = new RGBColorSpace({
11402 id: "rec2100pq",
11403 cssId: "rec2100-pq",
11404 name: "REC.2100-PQ",
11405 base: REC_2100_Linear,
11406 linearGamut: REC_2100_Linear,
11407 toBase(RGB) {
11408 // given PQ encoded component in range [0, 1]
11409 // return media-white relative linear-light
11410 return RGB.map(function (val) {
11411 let x = (Math.max(val ** minv - c1, 0) / (c2 - c3 * val ** minv)) ** ninv;
11412 return x * 10000 / Yw; // luminance relative to diffuse white, [0, 70 or so].
11413 });
11414 },
11415 fromBase(RGB) {
11416 // given media-white relative linear-light
11417 // returnPQ encoded component in range [0, 1]
11418 return RGB.map(function (val) {
11419 let x = Math.max(val * Yw / 10000, 0); // absolute luminance of peak white is 10,000 cd/m².
11420 let num = c1 + c2 * x ** n;
11421 let denom = 1 + c3 * x ** n;
11422 return (num / denom) ** m;
11423 });
11424 }
11425 });
11426
11427 const a = 0.17883277;
11428 const b = 0.28466892; // 1 - (4 * a)
11429 const c = 0.55991073; // 0.5 - a * Math.log(4 *a)
11430
11431 const scale = 3.7743; // Place 18% grey at HLG 0.38, so media white at 0.75
11432
11433 var rec2100Hlg = new RGBColorSpace({
11434 id: "rec2100hlg",
11435 cssId: "rec2100-hlg",
11436 name: "REC.2100-HLG",
11437 referred: "scene",
11438 base: REC_2100_Linear,
11439 linearGamut: REC_2100_Linear,
11440 toBase(RGB) {
11441 // given HLG encoded component in range [0, 1]
11442 // return media-white relative linear-light
11443 return RGB.map(function (val) {
11444 // first the HLG EOTF
11445 // ITU-R BT.2390-10 p.30 section
11446 // 6.3 The hybrid log-gamma electro-optical transfer function (EOTF)
11447 // Then scale by 3 so media white is 1.0
11448 if (val <= 0.5) {
11449 return val ** 2 / 3 * scale;
11450 }
11451 return (Math.exp((val - c) / a) + b) / 12 * scale;
11452 });
11453 },
11454 fromBase(RGB) {
11455 // given media-white relative linear-light
11456 // where diffuse white is 1.0,
11457 // return HLG encoded component in range [0, 1]
11458 return RGB.map(function (val) {
11459 // first scale to put linear-light media white at 1/3
11460 val /= scale;
11461 // now the HLG OETF
11462 // ITU-R BT.2390-10 p.23
11463 // 6.1 The hybrid log-gamma opto-electronic transfer function (OETF)
11464 if (val <= 1 / 12) {
11465 return spow(3 * val, 0.5);
11466 }
11467 return a * Math.log(12 * val - b) + c;
11468 });
11469 }
11470 });
11471
11472 /** @import { White } from "./types.js" */
11473
11474 // Type re-exports
11475 /** @typedef {import("./types.js").CAT} CAT */
11476
11477 /** @type {Record<string, CAT>} */
11478 const CATs = {};
11479 hooks.add("chromatic-adaptation-start", env => {
11480 if (env.options.method) {
11481 env.M = adapt(env.W1, env.W2, env.options.method);
11482 }
11483 });
11484 hooks.add("chromatic-adaptation-end", env => {
11485 if (!env.M) {
11486 env.M = adapt(env.W1, env.W2, env.options.method);
11487 }
11488 });
11489 function defineCAT(/** @type {CAT} */{
11490 id,
11491 toCone_M,
11492 fromCone_M
11493 }) {
11494 // Use id, toCone_M, fromCone_M like variables
11495 CATs[id] = arguments[0];
11496 }
11497
11498 /**
11499 *
11500 * @param {White} W1
11501 * @param {White} W2
11502 * @param {string} id
11503 * @returns {number[][]}
11504 */
11505 function adapt(W1, W2, id = "Bradford") {
11506 // adapt from a source whitepoint or illuminant W1
11507 // to a destination whitepoint or illuminant W2,
11508 // using the given chromatic adaptation transform (CAT)
11509 // debugger;
11510 let method = CATs[id];
11511 let [ρs, γs, βs] = multiplyMatrices(method.toCone_M, W1);
11512 let [ρd, γd, βd] = multiplyMatrices(method.toCone_M, W2);
11513
11514 // all practical illuminants have non-zero XYZ so no division by zero can occur below
11515 // prettier-ignore
11516 let scale = [[ρd / ρs, 0, 0], [0, γd / γs, 0], [0, 0, βd / βs]];
11517 // console.log({scale});
11518
11519 let scaled_cone_M = multiplyMatrices(scale, method.toCone_M);
11520 let adapt_M = multiplyMatrices(method.fromCone_M, scaled_cone_M);
11521 // console.log({scaled_cone_M, adapt_M});
11522 return adapt_M;
11523 }
11524
11525 // prettier-ignore
11526 defineCAT({
11527 id: "von Kries",
11528 toCone_M: [[0.4002400, 0.7076000, -0.0808100], [-0.2263000, 1.1653200, 0.0457000], [0.0000000, 0.0000000, 0.9182200]],
11529 fromCone_M: [[1.8599363874558397, -1.1293816185800916, 0.21989740959619328], [0.3611914362417676, 0.6388124632850422, -0.000006370596838649899], [0, 0, 1.0890636230968613]]
11530 });
11531
11532 // prettier-ignore
11533 defineCAT({
11534 id: "Bradford",
11535 // Convert an array of XYZ values in the range 0.0 - 1.0
11536 // to cone fundamentals
11537 toCone_M: [[0.8951000, 0.2664000, -0.1614000], [-0.7502000, 1.7135000, 0.0367000], [0.0389000, -0.0685000, 1.0296000]],
11538 // and back
11539 fromCone_M: [[0.9869929054667121, -0.14705425642099013, 0.15996265166373122], [0.4323052697233945, 0.5183602715367774, 0.049291228212855594], [-0.00852866457517732, 0.04004282165408486, 0.96848669578755]]
11540 });
11541
11542 // prettier-ignore
11543 defineCAT({
11544 id: "CAT02",
11545 // with complete chromatic adaptation to W2, so D = 1.0
11546 toCone_M: [[0.7328000, 0.4296000, -0.1624000], [-0.7036000, 1.6975000, 0.0061000], [0.0030000, 0.0136000, 0.9834000]],
11547 fromCone_M: [[1.0961238208355142, -0.27886900021828726, 0.18274517938277307], [0.4543690419753592, 0.4735331543074117, 0.07209780371722911], [-0.009627608738429355, -0.00569803121611342, 1.0153256399545427]]
11548 });
11549
11550 // prettier-ignore
11551 defineCAT({
11552 id: "CAT16",
11553 toCone_M: [[0.401288, 0.650173, -0.051461], [-0.250268, 1.204414, 0.045854], [-0.002079, 0.048952, 0.953127]],
11554 // the extra precision is needed to avoid roundtripping errors
11555 fromCone_M: [[1.862067855087233, -1.0112546305316845, 0.14918677544445172], [0.3875265432361372, 0.6214474419314753, -0.008973985167612521], [-0.01584149884933386, -0.03412293802851557, 1.0499644368778496]]
11556 });
11557
11558 // prettier-ignore
11559 Object.assign(WHITES, {
11560 // whitepoint values from ASTM E308-01 with 10nm spacing, 1931 2 degree observer
11561 // all normalized to Y (luminance) = 1.00000
11562 // Illuminant A is a tungsten electric light, giving a very warm, orange light.
11563 A: [1.09850, 1.00000, 0.35585],
11564 // Illuminant C was an early approximation to daylight: illuminant A with a blue filter.
11565 C: [0.98074, 1.000000, 1.18232],
11566 // The daylight series of illuminants simulate natural daylight.
11567 // The color temperature (in degrees Kelvin/100) ranges from
11568 // cool, overcast daylight (D50) to bright, direct sunlight (D65).
11569 D55: [0.95682, 1.00000, 0.92149],
11570 D75: [0.94972, 1.00000, 1.22638],
11571 // Equal-energy illuminant, used in two-stage CAT16
11572 E: [1.00000, 1.00000, 1.00000],
11573 // The F series of illuminants represent fluorescent lights
11574 F2: [0.99186, 1.00000, 0.67393],
11575 F7: [0.95041, 1.00000, 1.08747],
11576 F11: [1.00962, 1.00000, 0.64350]
11577 });
11578
11579 /** @import { Matrix3x3 } from "../types.js" */
11580
11581 // The ACES whitepoint
11582 // see TB-2018-001 Derivation of the ACES White Point CIE Chromaticity Coordinates
11583 // also https://github.com/ampas/aces-dev/blob/master/documents/python/TB-2018-001/aces_wp.py
11584 // Similar to D60
11585 WHITES.ACES = [0.32168 / 0.33767, 1.0, (1.0 - 0.32168 - 0.33767) / 0.33767];
11586
11587 // convert an array of linear-light ACEScc values to CIE XYZ
11588 /** @type {Matrix3x3} */
11589 // prettier-ignore
11590 const toXYZ_M = [[0.6624541811085053, 0.13400420645643313, 0.1561876870049078], [0.27222871678091454, 0.6740817658111484, 0.05368951740793705], [-0.005574649490394108, 0.004060733528982826, 1.0103391003129971]];
11591 /** @type {Matrix3x3} */
11592 // prettier-ignore
11593 const fromXYZ_M = [[1.6410233796943257, -0.32480329418479, -0.23642469523761225], [-0.6636628587229829, 1.6153315916573379, 0.016756347685530137], [0.011721894328375376, -0.008284441996237409, 0.9883948585390215]];
11594 var ACEScg = new RGBColorSpace({
11595 id: "acescg",
11596 cssId: "--acescg",
11597 name: "ACEScg",
11598 // ACEScg – A scene-referred, linear-light encoding of ACES Data
11599 // https://docs.acescentral.com/specifications/acescg/
11600 // uses the AP1 primaries, see section 4.3.1 Color primaries
11601 coords: {
11602 r: {
11603 range: [0, 65504],
11604 name: "Red"
11605 },
11606 g: {
11607 range: [0, 65504],
11608 name: "Green"
11609 },
11610 b: {
11611 range: [0, 65504],
11612 name: "Blue"
11613 }
11614 },
11615 referred: "scene",
11616 white: WHITES.ACES,
11617 toXYZ_M,
11618 fromXYZ_M
11619 });
11620
11621 // export default Color;
11622
11623 const ε = 2 ** -16;
11624
11625 // the smallest value which, in the 32bit IEEE 754 float encoding,
11626 // decodes as a non-negative value
11627 const ACES_min_nonzero = -0.35828683;
11628
11629 // brightest encoded value, decodes to 65504
11630 const ACES_cc_max = (Math.log2(65504) + 9.72) / 17.52; // 1.468
11631
11632 var acescc = new RGBColorSpace({
11633 id: "acescc",
11634 cssId: "--acescc",
11635 name: "ACEScc",
11636 // see S-2014-003 ACEScc – A Logarithmic Encoding of ACES Data
11637 // https://docs.acescentral.com/specifications/acescc/
11638 // uses the AP1 primaries, see section 4.3.1 Color primaries
11639
11640 // Appendix A: "Very small ACES scene referred values below 7 1/4 stops
11641 // below 18% middle gray are encoded as negative ACEScc values.
11642 // These values should be preserved per the encoding in Section 4.4
11643 // so that all positive ACES values are maintained."
11644 coords: {
11645 r: {
11646 range: [ACES_min_nonzero, ACES_cc_max],
11647 name: "Red"
11648 },
11649 g: {
11650 range: [ACES_min_nonzero, ACES_cc_max],
11651 name: "Green"
11652 },
11653 b: {
11654 range: [ACES_min_nonzero, ACES_cc_max],
11655 name: "Blue"
11656 }
11657 },
11658 referred: "scene",
11659 base: ACEScg,
11660 linearGamut: ACEScg,
11661 // from section 4.4.2 Decoding Function
11662 toBase(RGB) {
11663 const low = (9.72 - 15) / 17.52; // -0.3014
11664
11665 return RGB.map(function (val) {
11666 if (val <= low) {
11667 return (2 ** (val * 17.52 - 9.72) - ε) * 2; // very low values, below -0.3014
11668 } else if (val < ACES_cc_max) {
11669 return 2 ** (val * 17.52 - 9.72);
11670 } else {
11671 // val >= ACES_cc_max
11672 return 65504;
11673 }
11674 });
11675 },
11676 // Non-linear encoding function from S-2014-003, section 4.4.1 Encoding Function
11677 fromBase(RGB) {
11678 return RGB.map(function (val) {
11679 if (val <= 0) {
11680 return (Math.log2(ε) + 9.72) / 17.52; // -0.3584
11681 } else if (val < ε) {
11682 return (Math.log2(ε + val * 0.5) + 9.72) / 17.52;
11683 } else {
11684 // val >= ε
11685 return (Math.log2(val) + 9.72) / 17.52;
11686 }
11687 });
11688 }
11689 // encoded media white (rgb 1,1,1) => linear [ 222.861, 222.861, 222.861 ]
11690 // encoded media black (rgb 0,0,0) => linear [ 0.0011857, 0.0011857, 0.0011857]
11691 });
11692
11693 /**
11694 * @packageDocumentation
11695 * Re-exports all the spaces built into Color.js.
11696 */
11697
11698 var indexFn = /*#__PURE__*/Object.freeze({
11699 __proto__: null,
11700 A98RGB: a98rgb,
11701 A98RGB_Linear: A98Linear,
11702 ACEScc: acescc,
11703 ACEScg: ACEScg,
11704 CAM16_JMh: cam16,
11705 HCT: hct,
11706 HPLuv: HPLuv,
11707 HSL: HSL,
11708 HSL_P3: hslP3,
11709 HSL_REC2020: hslRec2020,
11710 HSLuv: hsluv,
11711 HSV: HSV,
11712 HWB: hwb,
11713 HelmGen: HelmGen,
11714 HelmGenLCh: helmgenlch,
11715 Helmlab: helmlab,
11716 ICTCP: ictcp,
11717 JzCzHz: jzczhz,
11718 Jzazbz: Jzazbz,
11719 LCH: lch,
11720 LCHuv: LCHuv,
11721 Lab: lab,
11722 Lab_D65: lab_d65,
11723 Luv: Luv,
11724 OKLCH: OKLCH,
11725 OKLCH_P3: oklchP3,
11726 OKLab: Oklab,
11727 OKLrCH: oklrch,
11728 OKLrab: OKLrab,
11729 Okhsl: Okhsl,
11730 Okhsv: Okhsv,
11731 P3: P3,
11732 P3_Linear: P3Linear,
11733 ProPhoto: prophoto,
11734 ProPhoto_Linear: ProPhotoLinear,
11735 REC_2020: REC2020,
11736 REC_2020_Linear: REC_2020_Linear,
11737 REC_2020_Scene_Referred: rec2020Oetf,
11738 REC_2100_HLG: rec2100Hlg,
11739 REC_2100_Linear: REC_2100_Linear,
11740 REC_2100_PQ: rec2100Pq,
11741 XYZ_ABS_D65: XYZ_Abs_D65,
11742 XYZ_D50: XYZ_D50,
11743 XYZ_D65: XYZ_D65,
11744 sRGB: sRGB,
11745 sRGB_Linear: sRGBLinear
11746 });
11747
11748 export { a98rgb as A98RGB, A98Linear as A98RGB_Linear, acescc as ACEScc, ACEScg, cam16 as CAM16_JMh, ColorSpace, hct as HCT, HPLuv, HSL, hslP3 as HSL_P3, hslRec2020 as HSL_REC2020, hsluv as HSLuv, HSV, hwb as HWB, HelmGen, helmgenlch as HelmGenLCh, helmlab as Helmlab, Hooks, ictcp as ICTCP, jzczhz as JzCzHz, Jzazbz, lch as LCH, LCHuv, lab as Lab, lab_d65 as Lab_D65, Luv, OKLCH, oklchP3 as OKLCH_P3, Oklab as OKLab, oklrch as OKLrCH, OKLrab, Okhsl, Okhsv, P3, P3Linear as P3_Linear, prophoto as ProPhoto, ProPhotoLinear as ProPhoto_Linear, REC2020 as REC_2020, REC_2020_Linear, rec2020Oetf as REC_2020_Scene_Referred, rec2100Hlg as REC_2100_HLG, REC_2100_Linear, rec2100Pq as REC_2100_PQ, RGBColorSpace, XYZ_Abs_D65 as XYZ_ABS_D65, XYZ_D50, XYZ_D65, clone, contrast, contrastAPCA, contrastDeltaPhi, contrastLstar, contrastMichelson, contrastWCAG21, contrastWeber, darken, defaults, deltaE, deltaE2000, deltaE76, deltaECMC, deltaEHCT, deltaEHelmlab, deltaEITP, deltaEJz, deltaEMethods, deltaEOK, deltaEOK2, deltas, display, distance, equals, get, getAll, getColor, getLuminance, hooks, inGamut, isRange, lighten, maxChroma, mix, parse, range, sRGB, sRGBLinear as sRGB_Linear, serialize, set, setAll, setLuminance, indexFn as spaces, steps, to, toGamut, toGamutCSS, tryColor, uv, xy };
11749 //# sourceMappingURL=color-fn.legacy.js.map