Debian Codegraph @

node/colorjs.io/dist/color.legacy.cjs

raw
1 'use strict';
2
3 Object.defineProperty(exports, '__esModule', { value: true });
4
5 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
6
7 var esnext_iterator_map = {};
8
9 var es_iterator_map = {};
10
11 var globalThis_1;
12 var hasRequiredGlobalThis;
13
14 function requireGlobalThis () {
15 if (hasRequiredGlobalThis) return globalThis_1;
16 hasRequiredGlobalThis = 1;
17 var check = function (it) {
18 return it && it.Math === Math && it;
19 };
20
21 // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
22 globalThis_1 =
23 // eslint-disable-next-line es/no-global-this -- safe
24 check(typeof globalThis == 'object' && globalThis) ||
25 check(typeof window == 'object' && window) ||
26 // eslint-disable-next-line no-restricted-globals -- safe
27 check(typeof self == 'object' && self) ||
28 check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
29 check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
30 // eslint-disable-next-line no-new-func -- fallback
31 (function () { return this; })() || Function('return this')();
32 return globalThis_1;
33 }
34
35 var objectGetOwnPropertyDescriptor = {};
36
37 var fails;
38 var hasRequiredFails;
39
40 function requireFails () {
41 if (hasRequiredFails) return fails;
42 hasRequiredFails = 1;
43 fails = function (exec) {
44 try {
45 return !!exec();
46 } catch (error) {
47 return true;
48 }
49 };
50 return fails;
51 }
52
53 var descriptors;
54 var hasRequiredDescriptors;
55
56 function requireDescriptors () {
57 if (hasRequiredDescriptors) return descriptors;
58 hasRequiredDescriptors = 1;
59 var fails = requireFails();
60
61 // Detect IE8's incomplete defineProperty implementation
62 descriptors = !fails(function () {
63 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
64 return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7;
65 });
66 return descriptors;
67 }
68
69 var functionBindNative;
70 var hasRequiredFunctionBindNative;
71
72 function requireFunctionBindNative () {
73 if (hasRequiredFunctionBindNative) return functionBindNative;
74 hasRequiredFunctionBindNative = 1;
75 var fails = requireFails();
76
77 functionBindNative = !fails(function () {
78 // eslint-disable-next-line es/no-function-prototype-bind -- safe
79 var test = (function () { /* empty */ }).bind();
80 // eslint-disable-next-line no-prototype-builtins -- safe
81 return typeof test != 'function' || test.hasOwnProperty('prototype');
82 });
83 return functionBindNative;
84 }
85
86 var functionCall;
87 var hasRequiredFunctionCall;
88
89 function requireFunctionCall () {
90 if (hasRequiredFunctionCall) return functionCall;
91 hasRequiredFunctionCall = 1;
92 var NATIVE_BIND = requireFunctionBindNative();
93
94 var call = Function.prototype.call;
95
96 functionCall = NATIVE_BIND ? call.bind(call) : function () {
97 return call.apply(call, arguments);
98 };
99 return functionCall;
100 }
101
102 var objectPropertyIsEnumerable = {};
103
104 var hasRequiredObjectPropertyIsEnumerable;
105
106 function requireObjectPropertyIsEnumerable () {
107 if (hasRequiredObjectPropertyIsEnumerable) return objectPropertyIsEnumerable;
108 hasRequiredObjectPropertyIsEnumerable = 1;
109 var $propertyIsEnumerable = {}.propertyIsEnumerable;
110 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
111 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
112
113 // Nashorn ~ JDK8 bug
114 var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);
115
116 // `Object.prototype.propertyIsEnumerable` method implementation
117 // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
118 objectPropertyIsEnumerable.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
119 var descriptor = getOwnPropertyDescriptor(this, V);
120 return !!descriptor && descriptor.enumerable;
121 } : $propertyIsEnumerable;
122 return objectPropertyIsEnumerable;
123 }
124
125 var createPropertyDescriptor;
126 var hasRequiredCreatePropertyDescriptor;
127
128 function requireCreatePropertyDescriptor () {
129 if (hasRequiredCreatePropertyDescriptor) return createPropertyDescriptor;
130 hasRequiredCreatePropertyDescriptor = 1;
131 createPropertyDescriptor = function (bitmap, value) {
132 return {
133 enumerable: !(bitmap & 1),
134 configurable: !(bitmap & 2),
135 writable: !(bitmap & 4),
136 value: value
137 };
138 };
139 return createPropertyDescriptor;
140 }
141
142 var functionUncurryThis;
143 var hasRequiredFunctionUncurryThis;
144
145 function requireFunctionUncurryThis () {
146 if (hasRequiredFunctionUncurryThis) return functionUncurryThis;
147 hasRequiredFunctionUncurryThis = 1;
148 var NATIVE_BIND = requireFunctionBindNative();
149
150 var FunctionPrototype = Function.prototype;
151 var call = FunctionPrototype.call;
152 var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call);
153
154 functionUncurryThis = NATIVE_BIND ? uncurryThisWithBind : function (fn) {
155 return function () {
156 return call.apply(fn, arguments);
157 };
158 };
159 return functionUncurryThis;
160 }
161
162 var classofRaw;
163 var hasRequiredClassofRaw;
164
165 function requireClassofRaw () {
166 if (hasRequiredClassofRaw) return classofRaw;
167 hasRequiredClassofRaw = 1;
168 var uncurryThis = requireFunctionUncurryThis();
169
170 var toString = uncurryThis({}.toString);
171 var stringSlice = uncurryThis(''.slice);
172
173 classofRaw = function (it) {
174 return stringSlice(toString(it), 8, -1);
175 };
176 return classofRaw;
177 }
178
179 var indexedObject;
180 var hasRequiredIndexedObject;
181
182 function requireIndexedObject () {
183 if (hasRequiredIndexedObject) return indexedObject;
184 hasRequiredIndexedObject = 1;
185 var uncurryThis = requireFunctionUncurryThis();
186 var fails = requireFails();
187 var classof = requireClassofRaw();
188
189 var $Object = Object;
190 var split = uncurryThis(''.split);
191
192 // fallback for non-array-like ES3 and non-enumerable old V8 strings
193 indexedObject = fails(function () {
194 // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
195 // eslint-disable-next-line no-prototype-builtins -- safe
196 return !$Object('z').propertyIsEnumerable(0);
197 }) ? function (it) {
198 return classof(it) === 'String' ? split(it, '') : $Object(it);
199 } : $Object;
200 return indexedObject;
201 }
202
203 var isNullOrUndefined;
204 var hasRequiredIsNullOrUndefined;
205
206 function requireIsNullOrUndefined () {
207 if (hasRequiredIsNullOrUndefined) return isNullOrUndefined;
208 hasRequiredIsNullOrUndefined = 1;
209 // we can't use just `it == null` since of `document.all` special case
210 // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
211 isNullOrUndefined = function (it) {
212 return it === null || it === undefined;
213 };
214 return isNullOrUndefined;
215 }
216
217 var requireObjectCoercible;
218 var hasRequiredRequireObjectCoercible;
219
220 function requireRequireObjectCoercible () {
221 if (hasRequiredRequireObjectCoercible) return requireObjectCoercible;
222 hasRequiredRequireObjectCoercible = 1;
223 var isNullOrUndefined = requireIsNullOrUndefined();
224
225 var $TypeError = TypeError;
226
227 // `RequireObjectCoercible` abstract operation
228 // https://tc39.es/ecma262/#sec-requireobjectcoercible
229 requireObjectCoercible = function (it) {
230 if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it);
231 return it;
232 };
233 return requireObjectCoercible;
234 }
235
236 var toIndexedObject;
237 var hasRequiredToIndexedObject;
238
239 function requireToIndexedObject () {
240 if (hasRequiredToIndexedObject) return toIndexedObject;
241 hasRequiredToIndexedObject = 1;
242 // toObject with fallback for non-array-like ES3 strings
243 var IndexedObject = requireIndexedObject();
244 var requireObjectCoercible = requireRequireObjectCoercible();
245
246 toIndexedObject = function (it) {
247 return IndexedObject(requireObjectCoercible(it));
248 };
249 return toIndexedObject;
250 }
251
252 var isCallable;
253 var hasRequiredIsCallable;
254
255 function requireIsCallable () {
256 if (hasRequiredIsCallable) return isCallable;
257 hasRequiredIsCallable = 1;
258 // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
259 var documentAll = typeof document == 'object' && document.all;
260
261 // `IsCallable` abstract operation
262 // https://tc39.es/ecma262/#sec-iscallable
263 // eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing
264 isCallable = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) {
265 return typeof argument == 'function' || argument === documentAll;
266 } : function (argument) {
267 return typeof argument == 'function';
268 };
269 return isCallable;
270 }
271
272 var isObject;
273 var hasRequiredIsObject;
274
275 function requireIsObject () {
276 if (hasRequiredIsObject) return isObject;
277 hasRequiredIsObject = 1;
278 var isCallable = requireIsCallable();
279
280 isObject = function (it) {
281 return typeof it == 'object' ? it !== null : isCallable(it);
282 };
283 return isObject;
284 }
285
286 var getBuiltIn;
287 var hasRequiredGetBuiltIn;
288
289 function requireGetBuiltIn () {
290 if (hasRequiredGetBuiltIn) return getBuiltIn;
291 hasRequiredGetBuiltIn = 1;
292 var globalThis = requireGlobalThis();
293 var isCallable = requireIsCallable();
294
295 var aFunction = function (argument) {
296 return isCallable(argument) ? argument : undefined;
297 };
298
299 getBuiltIn = function (namespace, method) {
300 return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method];
301 };
302 return getBuiltIn;
303 }
304
305 var objectIsPrototypeOf;
306 var hasRequiredObjectIsPrototypeOf;
307
308 function requireObjectIsPrototypeOf () {
309 if (hasRequiredObjectIsPrototypeOf) return objectIsPrototypeOf;
310 hasRequiredObjectIsPrototypeOf = 1;
311 var uncurryThis = requireFunctionUncurryThis();
312
313 objectIsPrototypeOf = uncurryThis({}.isPrototypeOf);
314 return objectIsPrototypeOf;
315 }
316
317 var environmentUserAgent;
318 var hasRequiredEnvironmentUserAgent;
319
320 function requireEnvironmentUserAgent () {
321 if (hasRequiredEnvironmentUserAgent) return environmentUserAgent;
322 hasRequiredEnvironmentUserAgent = 1;
323 var globalThis = requireGlobalThis();
324
325 var navigator = globalThis.navigator;
326 var userAgent = navigator && navigator.userAgent;
327
328 environmentUserAgent = userAgent ? String(userAgent) : '';
329 return environmentUserAgent;
330 }
331
332 var environmentV8Version;
333 var hasRequiredEnvironmentV8Version;
334
335 function requireEnvironmentV8Version () {
336 if (hasRequiredEnvironmentV8Version) return environmentV8Version;
337 hasRequiredEnvironmentV8Version = 1;
338 var globalThis = requireGlobalThis();
339 var userAgent = requireEnvironmentUserAgent();
340
341 var process = globalThis.process;
342 var Deno = globalThis.Deno;
343 var versions = process && process.versions || Deno && Deno.version;
344 var v8 = versions && versions.v8;
345 var match, version;
346
347 if (v8) {
348 match = v8.split('.');
349 // in old Chrome, versions of V8 isn't V8 = Chrome / 10
350 // but their correct versions are not interesting for us
351 version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
352 }
353
354 // BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
355 // so check `userAgent` even if `.v8` exists, but 0
356 if (!version && userAgent) {
357 match = userAgent.match(/Edge\/(\d+)/);
358 if (!match || match[1] >= 74) {
359 match = userAgent.match(/Chrome\/(\d+)/);
360 if (match) version = +match[1];
361 }
362 }
363
364 environmentV8Version = version;
365 return environmentV8Version;
366 }
367
368 var symbolConstructorDetection;
369 var hasRequiredSymbolConstructorDetection;
370
371 function requireSymbolConstructorDetection () {
372 if (hasRequiredSymbolConstructorDetection) return symbolConstructorDetection;
373 hasRequiredSymbolConstructorDetection = 1;
374 /* eslint-disable es/no-symbol -- required for testing */
375 var V8_VERSION = requireEnvironmentV8Version();
376 var fails = requireFails();
377 var globalThis = requireGlobalThis();
378
379 var $String = globalThis.String;
380
381 // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
382 symbolConstructorDetection = !!Object.getOwnPropertySymbols && !fails(function () {
383 var symbol = Symbol('symbol detection');
384 // Chrome 38 Symbol has incorrect toString conversion
385 // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
386 // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will,
387 // of course, fail.
388 return !$String(symbol) || !(Object(symbol) instanceof Symbol) ||
389 // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
390 !Symbol.sham && V8_VERSION && V8_VERSION < 41;
391 });
392 return symbolConstructorDetection;
393 }
394
395 var useSymbolAsUid;
396 var hasRequiredUseSymbolAsUid;
397
398 function requireUseSymbolAsUid () {
399 if (hasRequiredUseSymbolAsUid) return useSymbolAsUid;
400 hasRequiredUseSymbolAsUid = 1;
401 /* eslint-disable es/no-symbol -- required for testing */
402 var NATIVE_SYMBOL = requireSymbolConstructorDetection();
403
404 useSymbolAsUid = NATIVE_SYMBOL &&
405 !Symbol.sham &&
406 typeof Symbol.iterator == 'symbol';
407 return useSymbolAsUid;
408 }
409
410 var isSymbol;
411 var hasRequiredIsSymbol;
412
413 function requireIsSymbol () {
414 if (hasRequiredIsSymbol) return isSymbol;
415 hasRequiredIsSymbol = 1;
416 var getBuiltIn = requireGetBuiltIn();
417 var isCallable = requireIsCallable();
418 var isPrototypeOf = requireObjectIsPrototypeOf();
419 var USE_SYMBOL_AS_UID = requireUseSymbolAsUid();
420
421 var $Object = Object;
422
423 isSymbol = USE_SYMBOL_AS_UID ? function (it) {
424 return typeof it == 'symbol';
425 } : function (it) {
426 var $Symbol = getBuiltIn('Symbol');
427 return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it));
428 };
429 return isSymbol;
430 }
431
432 var tryToString;
433 var hasRequiredTryToString;
434
435 function requireTryToString () {
436 if (hasRequiredTryToString) return tryToString;
437 hasRequiredTryToString = 1;
438 var $String = String;
439
440 tryToString = function (argument) {
441 try {
442 return $String(argument);
443 } catch (error) {
444 return 'Object';
445 }
446 };
447 return tryToString;
448 }
449
450 var aCallable;
451 var hasRequiredACallable;
452
453 function requireACallable () {
454 if (hasRequiredACallable) return aCallable;
455 hasRequiredACallable = 1;
456 var isCallable = requireIsCallable();
457 var tryToString = requireTryToString();
458
459 var $TypeError = TypeError;
460
461 // `Assert: IsCallable(argument) is true`
462 aCallable = function (argument) {
463 if (isCallable(argument)) return argument;
464 throw new $TypeError(tryToString(argument) + ' is not a function');
465 };
466 return aCallable;
467 }
468
469 var getMethod;
470 var hasRequiredGetMethod;
471
472 function requireGetMethod () {
473 if (hasRequiredGetMethod) return getMethod;
474 hasRequiredGetMethod = 1;
475 var aCallable = requireACallable();
476 var isNullOrUndefined = requireIsNullOrUndefined();
477
478 // `GetMethod` abstract operation
479 // https://tc39.es/ecma262/#sec-getmethod
480 getMethod = function (V, P) {
481 var func = V[P];
482 return isNullOrUndefined(func) ? undefined : aCallable(func);
483 };
484 return getMethod;
485 }
486
487 var ordinaryToPrimitive;
488 var hasRequiredOrdinaryToPrimitive;
489
490 function requireOrdinaryToPrimitive () {
491 if (hasRequiredOrdinaryToPrimitive) return ordinaryToPrimitive;
492 hasRequiredOrdinaryToPrimitive = 1;
493 var call = requireFunctionCall();
494 var isCallable = requireIsCallable();
495 var isObject = requireIsObject();
496
497 var $TypeError = TypeError;
498
499 // `OrdinaryToPrimitive` abstract operation
500 // https://tc39.es/ecma262/#sec-ordinarytoprimitive
501 ordinaryToPrimitive = function (input, pref) {
502 var fn, val;
503 if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
504 if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
505 if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
506 throw new $TypeError("Can't convert object to primitive value");
507 };
508 return ordinaryToPrimitive;
509 }
510
511 var sharedStore = {exports: {}};
512
513 var isPure;
514 var hasRequiredIsPure;
515
516 function requireIsPure () {
517 if (hasRequiredIsPure) return isPure;
518 hasRequiredIsPure = 1;
519 isPure = false;
520 return isPure;
521 }
522
523 var defineGlobalProperty;
524 var hasRequiredDefineGlobalProperty;
525
526 function requireDefineGlobalProperty () {
527 if (hasRequiredDefineGlobalProperty) return defineGlobalProperty;
528 hasRequiredDefineGlobalProperty = 1;
529 var globalThis = requireGlobalThis();
530
531 // eslint-disable-next-line es/no-object-defineproperty -- safe
532 var defineProperty = Object.defineProperty;
533
534 defineGlobalProperty = function (key, value) {
535 try {
536 defineProperty(globalThis, key, { value: value, configurable: true, writable: true });
537 } catch (error) {
538 globalThis[key] = value;
539 } return value;
540 };
541 return defineGlobalProperty;
542 }
543
544 var hasRequiredSharedStore;
545
546 function requireSharedStore () {
547 if (hasRequiredSharedStore) return sharedStore.exports;
548 hasRequiredSharedStore = 1;
549 var IS_PURE = requireIsPure();
550 var globalThis = requireGlobalThis();
551 var defineGlobalProperty = requireDefineGlobalProperty();
552
553 var SHARED = '__core-js_shared__';
554 var store = sharedStore.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {});
555
556 (store.versions || (store.versions = [])).push({
557 version: '3.39.0',
558 mode: IS_PURE ? 'pure' : 'global',
559 copyright: '© 2014-2024 Denis Pushkarev (zloirock.ru)',
560 license: 'https://github.com/zloirock/core-js/blob/v3.39.0/LICENSE',
561 source: 'https://github.com/zloirock/core-js'
562 });
563 return sharedStore.exports;
564 }
565
566 var shared;
567 var hasRequiredShared;
568
569 function requireShared () {
570 if (hasRequiredShared) return shared;
571 hasRequiredShared = 1;
572 var store = requireSharedStore();
573
574 shared = function (key, value) {
575 return store[key] || (store[key] = value || {});
576 };
577 return shared;
578 }
579
580 var toObject;
581 var hasRequiredToObject;
582
583 function requireToObject () {
584 if (hasRequiredToObject) return toObject;
585 hasRequiredToObject = 1;
586 var requireObjectCoercible = requireRequireObjectCoercible();
587
588 var $Object = Object;
589
590 // `ToObject` abstract operation
591 // https://tc39.es/ecma262/#sec-toobject
592 toObject = function (argument) {
593 return $Object(requireObjectCoercible(argument));
594 };
595 return toObject;
596 }
597
598 var hasOwnProperty_1;
599 var hasRequiredHasOwnProperty;
600
601 function requireHasOwnProperty () {
602 if (hasRequiredHasOwnProperty) return hasOwnProperty_1;
603 hasRequiredHasOwnProperty = 1;
604 var uncurryThis = requireFunctionUncurryThis();
605 var toObject = requireToObject();
606
607 var hasOwnProperty = uncurryThis({}.hasOwnProperty);
608
609 // `HasOwnProperty` abstract operation
610 // https://tc39.es/ecma262/#sec-hasownproperty
611 // eslint-disable-next-line es/no-object-hasown -- safe
612 hasOwnProperty_1 = Object.hasOwn || function hasOwn(it, key) {
613 return hasOwnProperty(toObject(it), key);
614 };
615 return hasOwnProperty_1;
616 }
617
618 var uid;
619 var hasRequiredUid;
620
621 function requireUid () {
622 if (hasRequiredUid) return uid;
623 hasRequiredUid = 1;
624 var uncurryThis = requireFunctionUncurryThis();
625
626 var id = 0;
627 var postfix = Math.random();
628 var toString = uncurryThis(1.0.toString);
629
630 uid = function (key) {
631 return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36);
632 };
633 return uid;
634 }
635
636 var wellKnownSymbol;
637 var hasRequiredWellKnownSymbol;
638
639 function requireWellKnownSymbol () {
640 if (hasRequiredWellKnownSymbol) return wellKnownSymbol;
641 hasRequiredWellKnownSymbol = 1;
642 var globalThis = requireGlobalThis();
643 var shared = requireShared();
644 var hasOwn = requireHasOwnProperty();
645 var uid = requireUid();
646 var NATIVE_SYMBOL = requireSymbolConstructorDetection();
647 var USE_SYMBOL_AS_UID = requireUseSymbolAsUid();
648
649 var Symbol = globalThis.Symbol;
650 var WellKnownSymbolsStore = shared('wks');
651 var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid;
652
653 wellKnownSymbol = function (name) {
654 if (!hasOwn(WellKnownSymbolsStore, name)) {
655 WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name)
656 ? Symbol[name]
657 : createWellKnownSymbol('Symbol.' + name);
658 } return WellKnownSymbolsStore[name];
659 };
660 return wellKnownSymbol;
661 }
662
663 var toPrimitive;
664 var hasRequiredToPrimitive;
665
666 function requireToPrimitive () {
667 if (hasRequiredToPrimitive) return toPrimitive;
668 hasRequiredToPrimitive = 1;
669 var call = requireFunctionCall();
670 var isObject = requireIsObject();
671 var isSymbol = requireIsSymbol();
672 var getMethod = requireGetMethod();
673 var ordinaryToPrimitive = requireOrdinaryToPrimitive();
674 var wellKnownSymbol = requireWellKnownSymbol();
675
676 var $TypeError = TypeError;
677 var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
678
679 // `ToPrimitive` abstract operation
680 // https://tc39.es/ecma262/#sec-toprimitive
681 toPrimitive = function (input, pref) {
682 if (!isObject(input) || isSymbol(input)) return input;
683 var exoticToPrim = getMethod(input, TO_PRIMITIVE);
684 var result;
685 if (exoticToPrim) {
686 if (pref === undefined) pref = 'default';
687 result = call(exoticToPrim, input, pref);
688 if (!isObject(result) || isSymbol(result)) return result;
689 throw new $TypeError("Can't convert object to primitive value");
690 }
691 if (pref === undefined) pref = 'number';
692 return ordinaryToPrimitive(input, pref);
693 };
694 return toPrimitive;
695 }
696
697 var toPropertyKey;
698 var hasRequiredToPropertyKey;
699
700 function requireToPropertyKey () {
701 if (hasRequiredToPropertyKey) return toPropertyKey;
702 hasRequiredToPropertyKey = 1;
703 var toPrimitive = requireToPrimitive();
704 var isSymbol = requireIsSymbol();
705
706 // `ToPropertyKey` abstract operation
707 // https://tc39.es/ecma262/#sec-topropertykey
708 toPropertyKey = function (argument) {
709 var key = toPrimitive(argument, 'string');
710 return isSymbol(key) ? key : key + '';
711 };
712 return toPropertyKey;
713 }
714
715 var documentCreateElement;
716 var hasRequiredDocumentCreateElement;
717
718 function requireDocumentCreateElement () {
719 if (hasRequiredDocumentCreateElement) return documentCreateElement;
720 hasRequiredDocumentCreateElement = 1;
721 var globalThis = requireGlobalThis();
722 var isObject = requireIsObject();
723
724 var document = globalThis.document;
725 // typeof document.createElement is 'object' in old IE
726 var EXISTS = isObject(document) && isObject(document.createElement);
727
728 documentCreateElement = function (it) {
729 return EXISTS ? document.createElement(it) : {};
730 };
731 return documentCreateElement;
732 }
733
734 var ie8DomDefine;
735 var hasRequiredIe8DomDefine;
736
737 function requireIe8DomDefine () {
738 if (hasRequiredIe8DomDefine) return ie8DomDefine;
739 hasRequiredIe8DomDefine = 1;
740 var DESCRIPTORS = requireDescriptors();
741 var fails = requireFails();
742 var createElement = requireDocumentCreateElement();
743
744 // Thanks to IE8 for its funny defineProperty
745 ie8DomDefine = !DESCRIPTORS && !fails(function () {
746 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
747 return Object.defineProperty(createElement('div'), 'a', {
748 get: function () { return 7; }
749 }).a !== 7;
750 });
751 return ie8DomDefine;
752 }
753
754 var hasRequiredObjectGetOwnPropertyDescriptor;
755
756 function requireObjectGetOwnPropertyDescriptor () {
757 if (hasRequiredObjectGetOwnPropertyDescriptor) return objectGetOwnPropertyDescriptor;
758 hasRequiredObjectGetOwnPropertyDescriptor = 1;
759 var DESCRIPTORS = requireDescriptors();
760 var call = requireFunctionCall();
761 var propertyIsEnumerableModule = requireObjectPropertyIsEnumerable();
762 var createPropertyDescriptor = requireCreatePropertyDescriptor();
763 var toIndexedObject = requireToIndexedObject();
764 var toPropertyKey = requireToPropertyKey();
765 var hasOwn = requireHasOwnProperty();
766 var IE8_DOM_DEFINE = requireIe8DomDefine();
767
768 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
769 var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
770
771 // `Object.getOwnPropertyDescriptor` method
772 // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
773 objectGetOwnPropertyDescriptor.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
774 O = toIndexedObject(O);
775 P = toPropertyKey(P);
776 if (IE8_DOM_DEFINE) try {
777 return $getOwnPropertyDescriptor(O, P);
778 } catch (error) { /* empty */ }
779 if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);
780 };
781 return objectGetOwnPropertyDescriptor;
782 }
783
784 var objectDefineProperty = {};
785
786 var v8PrototypeDefineBug;
787 var hasRequiredV8PrototypeDefineBug;
788
789 function requireV8PrototypeDefineBug () {
790 if (hasRequiredV8PrototypeDefineBug) return v8PrototypeDefineBug;
791 hasRequiredV8PrototypeDefineBug = 1;
792 var DESCRIPTORS = requireDescriptors();
793 var fails = requireFails();
794
795 // V8 ~ Chrome 36-
796 // https://bugs.chromium.org/p/v8/issues/detail?id=3334
797 v8PrototypeDefineBug = DESCRIPTORS && fails(function () {
798 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
799 return Object.defineProperty(function () { /* empty */ }, 'prototype', {
800 value: 42,
801 writable: false
802 }).prototype !== 42;
803 });
804 return v8PrototypeDefineBug;
805 }
806
807 var anObject;
808 var hasRequiredAnObject;
809
810 function requireAnObject () {
811 if (hasRequiredAnObject) return anObject;
812 hasRequiredAnObject = 1;
813 var isObject = requireIsObject();
814
815 var $String = String;
816 var $TypeError = TypeError;
817
818 // `Assert: Type(argument) is Object`
819 anObject = function (argument) {
820 if (isObject(argument)) return argument;
821 throw new $TypeError($String(argument) + ' is not an object');
822 };
823 return anObject;
824 }
825
826 var hasRequiredObjectDefineProperty;
827
828 function requireObjectDefineProperty () {
829 if (hasRequiredObjectDefineProperty) return objectDefineProperty;
830 hasRequiredObjectDefineProperty = 1;
831 var DESCRIPTORS = requireDescriptors();
832 var IE8_DOM_DEFINE = requireIe8DomDefine();
833 var V8_PROTOTYPE_DEFINE_BUG = requireV8PrototypeDefineBug();
834 var anObject = requireAnObject();
835 var toPropertyKey = requireToPropertyKey();
836
837 var $TypeError = TypeError;
838 // eslint-disable-next-line es/no-object-defineproperty -- safe
839 var $defineProperty = Object.defineProperty;
840 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
841 var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
842 var ENUMERABLE = 'enumerable';
843 var CONFIGURABLE = 'configurable';
844 var WRITABLE = 'writable';
845
846 // `Object.defineProperty` method
847 // https://tc39.es/ecma262/#sec-object.defineproperty
848 objectDefineProperty.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) {
849 anObject(O);
850 P = toPropertyKey(P);
851 anObject(Attributes);
852 if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
853 var current = $getOwnPropertyDescriptor(O, P);
854 if (current && current[WRITABLE]) {
855 O[P] = Attributes.value;
856 Attributes = {
857 configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
858 enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
859 writable: false
860 };
861 }
862 } return $defineProperty(O, P, Attributes);
863 } : $defineProperty : function defineProperty(O, P, Attributes) {
864 anObject(O);
865 P = toPropertyKey(P);
866 anObject(Attributes);
867 if (IE8_DOM_DEFINE) try {
868 return $defineProperty(O, P, Attributes);
869 } catch (error) { /* empty */ }
870 if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported');
871 if ('value' in Attributes) O[P] = Attributes.value;
872 return O;
873 };
874 return objectDefineProperty;
875 }
876
877 var createNonEnumerableProperty;
878 var hasRequiredCreateNonEnumerableProperty;
879
880 function requireCreateNonEnumerableProperty () {
881 if (hasRequiredCreateNonEnumerableProperty) return createNonEnumerableProperty;
882 hasRequiredCreateNonEnumerableProperty = 1;
883 var DESCRIPTORS = requireDescriptors();
884 var definePropertyModule = requireObjectDefineProperty();
885 var createPropertyDescriptor = requireCreatePropertyDescriptor();
886
887 createNonEnumerableProperty = DESCRIPTORS ? function (object, key, value) {
888 return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
889 } : function (object, key, value) {
890 object[key] = value;
891 return object;
892 };
893 return createNonEnumerableProperty;
894 }
895
896 var makeBuiltIn = {exports: {}};
897
898 var functionName;
899 var hasRequiredFunctionName;
900
901 function requireFunctionName () {
902 if (hasRequiredFunctionName) return functionName;
903 hasRequiredFunctionName = 1;
904 var DESCRIPTORS = requireDescriptors();
905 var hasOwn = requireHasOwnProperty();
906
907 var FunctionPrototype = Function.prototype;
908 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
909 var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;
910
911 var EXISTS = hasOwn(FunctionPrototype, 'name');
912 // additional protection from minified / mangled / dropped function names
913 var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
914 var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable));
915
916 functionName = {
917 EXISTS: EXISTS,
918 PROPER: PROPER,
919 CONFIGURABLE: CONFIGURABLE
920 };
921 return functionName;
922 }
923
924 var inspectSource;
925 var hasRequiredInspectSource;
926
927 function requireInspectSource () {
928 if (hasRequiredInspectSource) return inspectSource;
929 hasRequiredInspectSource = 1;
930 var uncurryThis = requireFunctionUncurryThis();
931 var isCallable = requireIsCallable();
932 var store = requireSharedStore();
933
934 var functionToString = uncurryThis(Function.toString);
935
936 // this helper broken in `[email protected]`, so we can't use `shared` helper
937 if (!isCallable(store.inspectSource)) {
938 store.inspectSource = function (it) {
939 return functionToString(it);
940 };
941 }
942
943 inspectSource = store.inspectSource;
944 return inspectSource;
945 }
946
947 var weakMapBasicDetection;
948 var hasRequiredWeakMapBasicDetection;
949
950 function requireWeakMapBasicDetection () {
951 if (hasRequiredWeakMapBasicDetection) return weakMapBasicDetection;
952 hasRequiredWeakMapBasicDetection = 1;
953 var globalThis = requireGlobalThis();
954 var isCallable = requireIsCallable();
955
956 var WeakMap = globalThis.WeakMap;
957
958 weakMapBasicDetection = isCallable(WeakMap) && /native code/.test(String(WeakMap));
959 return weakMapBasicDetection;
960 }
961
962 var sharedKey;
963 var hasRequiredSharedKey;
964
965 function requireSharedKey () {
966 if (hasRequiredSharedKey) return sharedKey;
967 hasRequiredSharedKey = 1;
968 var shared = requireShared();
969 var uid = requireUid();
970
971 var keys = shared('keys');
972
973 sharedKey = function (key) {
974 return keys[key] || (keys[key] = uid(key));
975 };
976 return sharedKey;
977 }
978
979 var hiddenKeys;
980 var hasRequiredHiddenKeys;
981
982 function requireHiddenKeys () {
983 if (hasRequiredHiddenKeys) return hiddenKeys;
984 hasRequiredHiddenKeys = 1;
985 hiddenKeys = {};
986 return hiddenKeys;
987 }
988
989 var internalState;
990 var hasRequiredInternalState;
991
992 function requireInternalState () {
993 if (hasRequiredInternalState) return internalState;
994 hasRequiredInternalState = 1;
995 var NATIVE_WEAK_MAP = requireWeakMapBasicDetection();
996 var globalThis = requireGlobalThis();
997 var isObject = requireIsObject();
998 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
999 var hasOwn = requireHasOwnProperty();
1000 var shared = requireSharedStore();
1001 var sharedKey = requireSharedKey();
1002 var hiddenKeys = requireHiddenKeys();
1003
1004 var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
1005 var TypeError = globalThis.TypeError;
1006 var WeakMap = globalThis.WeakMap;
1007 var set, get, has;
1008
1009 var enforce = function (it) {
1010 return has(it) ? get(it) : set(it, {});
1011 };
1012
1013 var getterFor = function (TYPE) {
1014 return function (it) {
1015 var state;
1016 if (!isObject(it) || (state = get(it)).type !== TYPE) {
1017 throw new TypeError('Incompatible receiver, ' + TYPE + ' required');
1018 } return state;
1019 };
1020 };
1021
1022 if (NATIVE_WEAK_MAP || shared.state) {
1023 var store = shared.state || (shared.state = new WeakMap());
1024 /* eslint-disable no-self-assign -- prototype methods protection */
1025 store.get = store.get;
1026 store.has = store.has;
1027 store.set = store.set;
1028 /* eslint-enable no-self-assign -- prototype methods protection */
1029 set = function (it, metadata) {
1030 if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
1031 metadata.facade = it;
1032 store.set(it, metadata);
1033 return metadata;
1034 };
1035 get = function (it) {
1036 return store.get(it) || {};
1037 };
1038 has = function (it) {
1039 return store.has(it);
1040 };
1041 } else {
1042 var STATE = sharedKey('state');
1043 hiddenKeys[STATE] = true;
1044 set = function (it, metadata) {
1045 if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
1046 metadata.facade = it;
1047 createNonEnumerableProperty(it, STATE, metadata);
1048 return metadata;
1049 };
1050 get = function (it) {
1051 return hasOwn(it, STATE) ? it[STATE] : {};
1052 };
1053 has = function (it) {
1054 return hasOwn(it, STATE);
1055 };
1056 }
1057
1058 internalState = {
1059 set: set,
1060 get: get,
1061 has: has,
1062 enforce: enforce,
1063 getterFor: getterFor
1064 };
1065 return internalState;
1066 }
1067
1068 var hasRequiredMakeBuiltIn;
1069
1070 function requireMakeBuiltIn () {
1071 if (hasRequiredMakeBuiltIn) return makeBuiltIn.exports;
1072 hasRequiredMakeBuiltIn = 1;
1073 var uncurryThis = requireFunctionUncurryThis();
1074 var fails = requireFails();
1075 var isCallable = requireIsCallable();
1076 var hasOwn = requireHasOwnProperty();
1077 var DESCRIPTORS = requireDescriptors();
1078 var CONFIGURABLE_FUNCTION_NAME = requireFunctionName().CONFIGURABLE;
1079 var inspectSource = requireInspectSource();
1080 var InternalStateModule = requireInternalState();
1081
1082 var enforceInternalState = InternalStateModule.enforce;
1083 var getInternalState = InternalStateModule.get;
1084 var $String = String;
1085 // eslint-disable-next-line es/no-object-defineproperty -- safe
1086 var defineProperty = Object.defineProperty;
1087 var stringSlice = uncurryThis(''.slice);
1088 var replace = uncurryThis(''.replace);
1089 var join = uncurryThis([].join);
1090
1091 var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () {
1092 return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8;
1093 });
1094
1095 var TEMPLATE = String(String).split('String');
1096
1097 var makeBuiltIn$1 = makeBuiltIn.exports = function (value, name, options) {
1098 if (stringSlice($String(name), 0, 7) === 'Symbol(') {
1099 name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']';
1100 }
1101 if (options && options.getter) name = 'get ' + name;
1102 if (options && options.setter) name = 'set ' + name;
1103 if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
1104 if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true });
1105 else value.name = name;
1106 }
1107 if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) {
1108 defineProperty(value, 'length', { value: options.arity });
1109 }
1110 try {
1111 if (options && hasOwn(options, 'constructor') && options.constructor) {
1112 if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false });
1113 // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable
1114 } else if (value.prototype) value.prototype = undefined;
1115 } catch (error) { /* empty */ }
1116 var state = enforceInternalState(value);
1117 if (!hasOwn(state, 'source')) {
1118 state.source = join(TEMPLATE, typeof name == 'string' ? name : '');
1119 } return value;
1120 };
1121
1122 // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
1123 // eslint-disable-next-line no-extend-native -- required
1124 Function.prototype.toString = makeBuiltIn$1(function toString() {
1125 return isCallable(this) && getInternalState(this).source || inspectSource(this);
1126 }, 'toString');
1127 return makeBuiltIn.exports;
1128 }
1129
1130 var defineBuiltIn;
1131 var hasRequiredDefineBuiltIn;
1132
1133 function requireDefineBuiltIn () {
1134 if (hasRequiredDefineBuiltIn) return defineBuiltIn;
1135 hasRequiredDefineBuiltIn = 1;
1136 var isCallable = requireIsCallable();
1137 var definePropertyModule = requireObjectDefineProperty();
1138 var makeBuiltIn = requireMakeBuiltIn();
1139 var defineGlobalProperty = requireDefineGlobalProperty();
1140
1141 defineBuiltIn = function (O, key, value, options) {
1142 if (!options) options = {};
1143 var simple = options.enumerable;
1144 var name = options.name !== undefined ? options.name : key;
1145 if (isCallable(value)) makeBuiltIn(value, name, options);
1146 if (options.global) {
1147 if (simple) O[key] = value;
1148 else defineGlobalProperty(key, value);
1149 } else {
1150 try {
1151 if (!options.unsafe) delete O[key];
1152 else if (O[key]) simple = true;
1153 } catch (error) { /* empty */ }
1154 if (simple) O[key] = value;
1155 else definePropertyModule.f(O, key, {
1156 value: value,
1157 enumerable: false,
1158 configurable: !options.nonConfigurable,
1159 writable: !options.nonWritable
1160 });
1161 } return O;
1162 };
1163 return defineBuiltIn;
1164 }
1165
1166 var objectGetOwnPropertyNames = {};
1167
1168 var mathTrunc;
1169 var hasRequiredMathTrunc;
1170
1171 function requireMathTrunc () {
1172 if (hasRequiredMathTrunc) return mathTrunc;
1173 hasRequiredMathTrunc = 1;
1174 var ceil = Math.ceil;
1175 var floor = Math.floor;
1176
1177 // `Math.trunc` method
1178 // https://tc39.es/ecma262/#sec-math.trunc
1179 // eslint-disable-next-line es/no-math-trunc -- safe
1180 mathTrunc = Math.trunc || function trunc(x) {
1181 var n = +x;
1182 return (n > 0 ? floor : ceil)(n);
1183 };
1184 return mathTrunc;
1185 }
1186
1187 var toIntegerOrInfinity;
1188 var hasRequiredToIntegerOrInfinity;
1189
1190 function requireToIntegerOrInfinity () {
1191 if (hasRequiredToIntegerOrInfinity) return toIntegerOrInfinity;
1192 hasRequiredToIntegerOrInfinity = 1;
1193 var trunc = requireMathTrunc();
1194
1195 // `ToIntegerOrInfinity` abstract operation
1196 // https://tc39.es/ecma262/#sec-tointegerorinfinity
1197 toIntegerOrInfinity = function (argument) {
1198 var number = +argument;
1199 // eslint-disable-next-line no-self-compare -- NaN check
1200 return number !== number || number === 0 ? 0 : trunc(number);
1201 };
1202 return toIntegerOrInfinity;
1203 }
1204
1205 var toAbsoluteIndex;
1206 var hasRequiredToAbsoluteIndex;
1207
1208 function requireToAbsoluteIndex () {
1209 if (hasRequiredToAbsoluteIndex) return toAbsoluteIndex;
1210 hasRequiredToAbsoluteIndex = 1;
1211 var toIntegerOrInfinity = requireToIntegerOrInfinity();
1212
1213 var max = Math.max;
1214 var min = Math.min;
1215
1216 // Helper for a popular repeating case of the spec:
1217 // Let integer be ? ToInteger(index).
1218 // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
1219 toAbsoluteIndex = function (index, length) {
1220 var integer = toIntegerOrInfinity(index);
1221 return integer < 0 ? max(integer + length, 0) : min(integer, length);
1222 };
1223 return toAbsoluteIndex;
1224 }
1225
1226 var toLength;
1227 var hasRequiredToLength;
1228
1229 function requireToLength () {
1230 if (hasRequiredToLength) return toLength;
1231 hasRequiredToLength = 1;
1232 var toIntegerOrInfinity = requireToIntegerOrInfinity();
1233
1234 var min = Math.min;
1235
1236 // `ToLength` abstract operation
1237 // https://tc39.es/ecma262/#sec-tolength
1238 toLength = function (argument) {
1239 var len = toIntegerOrInfinity(argument);
1240 return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
1241 };
1242 return toLength;
1243 }
1244
1245 var lengthOfArrayLike;
1246 var hasRequiredLengthOfArrayLike;
1247
1248 function requireLengthOfArrayLike () {
1249 if (hasRequiredLengthOfArrayLike) return lengthOfArrayLike;
1250 hasRequiredLengthOfArrayLike = 1;
1251 var toLength = requireToLength();
1252
1253 // `LengthOfArrayLike` abstract operation
1254 // https://tc39.es/ecma262/#sec-lengthofarraylike
1255 lengthOfArrayLike = function (obj) {
1256 return toLength(obj.length);
1257 };
1258 return lengthOfArrayLike;
1259 }
1260
1261 var arrayIncludes;
1262 var hasRequiredArrayIncludes;
1263
1264 function requireArrayIncludes () {
1265 if (hasRequiredArrayIncludes) return arrayIncludes;
1266 hasRequiredArrayIncludes = 1;
1267 var toIndexedObject = requireToIndexedObject();
1268 var toAbsoluteIndex = requireToAbsoluteIndex();
1269 var lengthOfArrayLike = requireLengthOfArrayLike();
1270
1271 // `Array.prototype.{ indexOf, includes }` methods implementation
1272 var createMethod = function (IS_INCLUDES) {
1273 return function ($this, el, fromIndex) {
1274 var O = toIndexedObject($this);
1275 var length = lengthOfArrayLike(O);
1276 if (length === 0) return !IS_INCLUDES && -1;
1277 var index = toAbsoluteIndex(fromIndex, length);
1278 var value;
1279 // Array#includes uses SameValueZero equality algorithm
1280 // eslint-disable-next-line no-self-compare -- NaN check
1281 if (IS_INCLUDES && el !== el) while (length > index) {
1282 value = O[index++];
1283 // eslint-disable-next-line no-self-compare -- NaN check
1284 if (value !== value) return true;
1285 // Array#indexOf ignores holes, Array#includes - not
1286 } else for (;length > index; index++) {
1287 if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
1288 } return !IS_INCLUDES && -1;
1289 };
1290 };
1291
1292 arrayIncludes = {
1293 // `Array.prototype.includes` method
1294 // https://tc39.es/ecma262/#sec-array.prototype.includes
1295 includes: createMethod(true),
1296 // `Array.prototype.indexOf` method
1297 // https://tc39.es/ecma262/#sec-array.prototype.indexof
1298 indexOf: createMethod(false)
1299 };
1300 return arrayIncludes;
1301 }
1302
1303 var objectKeysInternal;
1304 var hasRequiredObjectKeysInternal;
1305
1306 function requireObjectKeysInternal () {
1307 if (hasRequiredObjectKeysInternal) return objectKeysInternal;
1308 hasRequiredObjectKeysInternal = 1;
1309 var uncurryThis = requireFunctionUncurryThis();
1310 var hasOwn = requireHasOwnProperty();
1311 var toIndexedObject = requireToIndexedObject();
1312 var indexOf = requireArrayIncludes().indexOf;
1313 var hiddenKeys = requireHiddenKeys();
1314
1315 var push = uncurryThis([].push);
1316
1317 objectKeysInternal = function (object, names) {
1318 var O = toIndexedObject(object);
1319 var i = 0;
1320 var result = [];
1321 var key;
1322 for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);
1323 // Don't enum bug & hidden keys
1324 while (names.length > i) if (hasOwn(O, key = names[i++])) {
1325 ~indexOf(result, key) || push(result, key);
1326 }
1327 return result;
1328 };
1329 return objectKeysInternal;
1330 }
1331
1332 var enumBugKeys;
1333 var hasRequiredEnumBugKeys;
1334
1335 function requireEnumBugKeys () {
1336 if (hasRequiredEnumBugKeys) return enumBugKeys;
1337 hasRequiredEnumBugKeys = 1;
1338 // IE8- don't enum bug keys
1339 enumBugKeys = [
1340 'constructor',
1341 'hasOwnProperty',
1342 'isPrototypeOf',
1343 'propertyIsEnumerable',
1344 'toLocaleString',
1345 'toString',
1346 'valueOf'
1347 ];
1348 return enumBugKeys;
1349 }
1350
1351 var hasRequiredObjectGetOwnPropertyNames;
1352
1353 function requireObjectGetOwnPropertyNames () {
1354 if (hasRequiredObjectGetOwnPropertyNames) return objectGetOwnPropertyNames;
1355 hasRequiredObjectGetOwnPropertyNames = 1;
1356 var internalObjectKeys = requireObjectKeysInternal();
1357 var enumBugKeys = requireEnumBugKeys();
1358
1359 var hiddenKeys = enumBugKeys.concat('length', 'prototype');
1360
1361 // `Object.getOwnPropertyNames` method
1362 // https://tc39.es/ecma262/#sec-object.getownpropertynames
1363 // eslint-disable-next-line es/no-object-getownpropertynames -- safe
1364 objectGetOwnPropertyNames.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
1365 return internalObjectKeys(O, hiddenKeys);
1366 };
1367 return objectGetOwnPropertyNames;
1368 }
1369
1370 var objectGetOwnPropertySymbols = {};
1371
1372 var hasRequiredObjectGetOwnPropertySymbols;
1373
1374 function requireObjectGetOwnPropertySymbols () {
1375 if (hasRequiredObjectGetOwnPropertySymbols) return objectGetOwnPropertySymbols;
1376 hasRequiredObjectGetOwnPropertySymbols = 1;
1377 // eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
1378 objectGetOwnPropertySymbols.f = Object.getOwnPropertySymbols;
1379 return objectGetOwnPropertySymbols;
1380 }
1381
1382 var ownKeys;
1383 var hasRequiredOwnKeys;
1384
1385 function requireOwnKeys () {
1386 if (hasRequiredOwnKeys) return ownKeys;
1387 hasRequiredOwnKeys = 1;
1388 var getBuiltIn = requireGetBuiltIn();
1389 var uncurryThis = requireFunctionUncurryThis();
1390 var getOwnPropertyNamesModule = requireObjectGetOwnPropertyNames();
1391 var getOwnPropertySymbolsModule = requireObjectGetOwnPropertySymbols();
1392 var anObject = requireAnObject();
1393
1394 var concat = uncurryThis([].concat);
1395
1396 // all object keys, includes non-enumerable and symbols
1397 ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
1398 var keys = getOwnPropertyNamesModule.f(anObject(it));
1399 var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
1400 return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
1401 };
1402 return ownKeys;
1403 }
1404
1405 var copyConstructorProperties;
1406 var hasRequiredCopyConstructorProperties;
1407
1408 function requireCopyConstructorProperties () {
1409 if (hasRequiredCopyConstructorProperties) return copyConstructorProperties;
1410 hasRequiredCopyConstructorProperties = 1;
1411 var hasOwn = requireHasOwnProperty();
1412 var ownKeys = requireOwnKeys();
1413 var getOwnPropertyDescriptorModule = requireObjectGetOwnPropertyDescriptor();
1414 var definePropertyModule = requireObjectDefineProperty();
1415
1416 copyConstructorProperties = function (target, source, exceptions) {
1417 var keys = ownKeys(source);
1418 var defineProperty = definePropertyModule.f;
1419 var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
1420 for (var i = 0; i < keys.length; i++) {
1421 var key = keys[i];
1422 if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) {
1423 defineProperty(target, key, getOwnPropertyDescriptor(source, key));
1424 }
1425 }
1426 };
1427 return copyConstructorProperties;
1428 }
1429
1430 var isForced_1;
1431 var hasRequiredIsForced;
1432
1433 function requireIsForced () {
1434 if (hasRequiredIsForced) return isForced_1;
1435 hasRequiredIsForced = 1;
1436 var fails = requireFails();
1437 var isCallable = requireIsCallable();
1438
1439 var replacement = /#|\.prototype\./;
1440
1441 var isForced = function (feature, detection) {
1442 var value = data[normalize(feature)];
1443 return value === POLYFILL ? true
1444 : value === NATIVE ? false
1445 : isCallable(detection) ? fails(detection)
1446 : !!detection;
1447 };
1448
1449 var normalize = isForced.normalize = function (string) {
1450 return String(string).replace(replacement, '.').toLowerCase();
1451 };
1452
1453 var data = isForced.data = {};
1454 var NATIVE = isForced.NATIVE = 'N';
1455 var POLYFILL = isForced.POLYFILL = 'P';
1456
1457 isForced_1 = isForced;
1458 return isForced_1;
1459 }
1460
1461 var _export;
1462 var hasRequired_export;
1463
1464 function require_export () {
1465 if (hasRequired_export) return _export;
1466 hasRequired_export = 1;
1467 var globalThis = requireGlobalThis();
1468 var getOwnPropertyDescriptor = requireObjectGetOwnPropertyDescriptor().f;
1469 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1470 var defineBuiltIn = requireDefineBuiltIn();
1471 var defineGlobalProperty = requireDefineGlobalProperty();
1472 var copyConstructorProperties = requireCopyConstructorProperties();
1473 var isForced = requireIsForced();
1474
1475 /*
1476 options.target - name of the target object
1477 options.global - target is the global object
1478 options.stat - export as static methods of target
1479 options.proto - export as prototype methods of target
1480 options.real - real prototype method for the `pure` version
1481 options.forced - export even if the native feature is available
1482 options.bind - bind methods to the target, required for the `pure` version
1483 options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
1484 options.unsafe - use the simple assignment of property instead of delete + defineProperty
1485 options.sham - add a flag to not completely full polyfills
1486 options.enumerable - export as enumerable property
1487 options.dontCallGetSet - prevent calling a getter on target
1488 options.name - the .name of the function if it does not match the key
1489 */
1490 _export = function (options, source) {
1491 var TARGET = options.target;
1492 var GLOBAL = options.global;
1493 var STATIC = options.stat;
1494 var FORCED, target, key, targetProperty, sourceProperty, descriptor;
1495 if (GLOBAL) {
1496 target = globalThis;
1497 } else if (STATIC) {
1498 target = globalThis[TARGET] || defineGlobalProperty(TARGET, {});
1499 } else {
1500 target = globalThis[TARGET] && globalThis[TARGET].prototype;
1501 }
1502 if (target) for (key in source) {
1503 sourceProperty = source[key];
1504 if (options.dontCallGetSet) {
1505 descriptor = getOwnPropertyDescriptor(target, key);
1506 targetProperty = descriptor && descriptor.value;
1507 } else targetProperty = target[key];
1508 FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
1509 // contained in target
1510 if (!FORCED && targetProperty !== undefined) {
1511 if (typeof sourceProperty == typeof targetProperty) continue;
1512 copyConstructorProperties(sourceProperty, targetProperty);
1513 }
1514 // add a flag to not completely full polyfills
1515 if (options.sham || (targetProperty && targetProperty.sham)) {
1516 createNonEnumerableProperty(sourceProperty, 'sham', true);
1517 }
1518 defineBuiltIn(target, key, sourceProperty, options);
1519 }
1520 };
1521 return _export;
1522 }
1523
1524 var getIteratorDirect;
1525 var hasRequiredGetIteratorDirect;
1526
1527 function requireGetIteratorDirect () {
1528 if (hasRequiredGetIteratorDirect) return getIteratorDirect;
1529 hasRequiredGetIteratorDirect = 1;
1530 // `GetIteratorDirect(obj)` abstract operation
1531 // https://tc39.es/proposal-iterator-helpers/#sec-getiteratordirect
1532 getIteratorDirect = function (obj) {
1533 return {
1534 iterator: obj,
1535 next: obj.next,
1536 done: false
1537 };
1538 };
1539 return getIteratorDirect;
1540 }
1541
1542 var objectDefineProperties = {};
1543
1544 var objectKeys;
1545 var hasRequiredObjectKeys;
1546
1547 function requireObjectKeys () {
1548 if (hasRequiredObjectKeys) return objectKeys;
1549 hasRequiredObjectKeys = 1;
1550 var internalObjectKeys = requireObjectKeysInternal();
1551 var enumBugKeys = requireEnumBugKeys();
1552
1553 // `Object.keys` method
1554 // https://tc39.es/ecma262/#sec-object.keys
1555 // eslint-disable-next-line es/no-object-keys -- safe
1556 objectKeys = Object.keys || function keys(O) {
1557 return internalObjectKeys(O, enumBugKeys);
1558 };
1559 return objectKeys;
1560 }
1561
1562 var hasRequiredObjectDefineProperties;
1563
1564 function requireObjectDefineProperties () {
1565 if (hasRequiredObjectDefineProperties) return objectDefineProperties;
1566 hasRequiredObjectDefineProperties = 1;
1567 var DESCRIPTORS = requireDescriptors();
1568 var V8_PROTOTYPE_DEFINE_BUG = requireV8PrototypeDefineBug();
1569 var definePropertyModule = requireObjectDefineProperty();
1570 var anObject = requireAnObject();
1571 var toIndexedObject = requireToIndexedObject();
1572 var objectKeys = requireObjectKeys();
1573
1574 // `Object.defineProperties` method
1575 // https://tc39.es/ecma262/#sec-object.defineproperties
1576 // eslint-disable-next-line es/no-object-defineproperties -- safe
1577 objectDefineProperties.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
1578 anObject(O);
1579 var props = toIndexedObject(Properties);
1580 var keys = objectKeys(Properties);
1581 var length = keys.length;
1582 var index = 0;
1583 var key;
1584 while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);
1585 return O;
1586 };
1587 return objectDefineProperties;
1588 }
1589
1590 var html;
1591 var hasRequiredHtml;
1592
1593 function requireHtml () {
1594 if (hasRequiredHtml) return html;
1595 hasRequiredHtml = 1;
1596 var getBuiltIn = requireGetBuiltIn();
1597
1598 html = getBuiltIn('document', 'documentElement');
1599 return html;
1600 }
1601
1602 var objectCreate;
1603 var hasRequiredObjectCreate;
1604
1605 function requireObjectCreate () {
1606 if (hasRequiredObjectCreate) return objectCreate;
1607 hasRequiredObjectCreate = 1;
1608 /* global ActiveXObject -- old IE, WSH */
1609 var anObject = requireAnObject();
1610 var definePropertiesModule = requireObjectDefineProperties();
1611 var enumBugKeys = requireEnumBugKeys();
1612 var hiddenKeys = requireHiddenKeys();
1613 var html = requireHtml();
1614 var documentCreateElement = requireDocumentCreateElement();
1615 var sharedKey = requireSharedKey();
1616
1617 var GT = '>';
1618 var LT = '<';
1619 var PROTOTYPE = 'prototype';
1620 var SCRIPT = 'script';
1621 var IE_PROTO = sharedKey('IE_PROTO');
1622
1623 var EmptyConstructor = function () { /* empty */ };
1624
1625 var scriptTag = function (content) {
1626 return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
1627 };
1628
1629 // Create object with fake `null` prototype: use ActiveX Object with cleared prototype
1630 var NullProtoObjectViaActiveX = function (activeXDocument) {
1631 activeXDocument.write(scriptTag(''));
1632 activeXDocument.close();
1633 var temp = activeXDocument.parentWindow.Object;
1634 // eslint-disable-next-line no-useless-assignment -- avoid memory leak
1635 activeXDocument = null;
1636 return temp;
1637 };
1638
1639 // Create object with fake `null` prototype: use iframe Object with cleared prototype
1640 var NullProtoObjectViaIFrame = function () {
1641 // Thrash, waste and sodomy: IE GC bug
1642 var iframe = documentCreateElement('iframe');
1643 var JS = 'java' + SCRIPT + ':';
1644 var iframeDocument;
1645 iframe.style.display = 'none';
1646 html.appendChild(iframe);
1647 // https://github.com/zloirock/core-js/issues/475
1648 iframe.src = String(JS);
1649 iframeDocument = iframe.contentWindow.document;
1650 iframeDocument.open();
1651 iframeDocument.write(scriptTag('document.F=Object'));
1652 iframeDocument.close();
1653 return iframeDocument.F;
1654 };
1655
1656 // Check for document.domain and active x support
1657 // No need to use active x approach when document.domain is not set
1658 // see https://github.com/es-shims/es5-shim/issues/150
1659 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
1660 // avoid IE GC bug
1661 var activeXDocument;
1662 var NullProtoObject = function () {
1663 try {
1664 activeXDocument = new ActiveXObject('htmlfile');
1665 } catch (error) { /* ignore */ }
1666 NullProtoObject = typeof document != 'undefined'
1667 ? document.domain && activeXDocument
1668 ? NullProtoObjectViaActiveX(activeXDocument) // old IE
1669 : NullProtoObjectViaIFrame()
1670 : NullProtoObjectViaActiveX(activeXDocument); // WSH
1671 var length = enumBugKeys.length;
1672 while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
1673 return NullProtoObject();
1674 };
1675
1676 hiddenKeys[IE_PROTO] = true;
1677
1678 // `Object.create` method
1679 // https://tc39.es/ecma262/#sec-object.create
1680 // eslint-disable-next-line es/no-object-create -- safe
1681 objectCreate = Object.create || function create(O, Properties) {
1682 var result;
1683 if (O !== null) {
1684 EmptyConstructor[PROTOTYPE] = anObject(O);
1685 result = new EmptyConstructor();
1686 EmptyConstructor[PROTOTYPE] = null;
1687 // add "__proto__" for Object.getPrototypeOf polyfill
1688 result[IE_PROTO] = O;
1689 } else result = NullProtoObject();
1690 return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
1691 };
1692 return objectCreate;
1693 }
1694
1695 var defineBuiltIns;
1696 var hasRequiredDefineBuiltIns;
1697
1698 function requireDefineBuiltIns () {
1699 if (hasRequiredDefineBuiltIns) return defineBuiltIns;
1700 hasRequiredDefineBuiltIns = 1;
1701 var defineBuiltIn = requireDefineBuiltIn();
1702
1703 defineBuiltIns = function (target, src, options) {
1704 for (var key in src) defineBuiltIn(target, key, src[key], options);
1705 return target;
1706 };
1707 return defineBuiltIns;
1708 }
1709
1710 var correctPrototypeGetter;
1711 var hasRequiredCorrectPrototypeGetter;
1712
1713 function requireCorrectPrototypeGetter () {
1714 if (hasRequiredCorrectPrototypeGetter) return correctPrototypeGetter;
1715 hasRequiredCorrectPrototypeGetter = 1;
1716 var fails = requireFails();
1717
1718 correctPrototypeGetter = !fails(function () {
1719 function F() { /* empty */ }
1720 F.prototype.constructor = null;
1721 // eslint-disable-next-line es/no-object-getprototypeof -- required for testing
1722 return Object.getPrototypeOf(new F()) !== F.prototype;
1723 });
1724 return correctPrototypeGetter;
1725 }
1726
1727 var objectGetPrototypeOf;
1728 var hasRequiredObjectGetPrototypeOf;
1729
1730 function requireObjectGetPrototypeOf () {
1731 if (hasRequiredObjectGetPrototypeOf) return objectGetPrototypeOf;
1732 hasRequiredObjectGetPrototypeOf = 1;
1733 var hasOwn = requireHasOwnProperty();
1734 var isCallable = requireIsCallable();
1735 var toObject = requireToObject();
1736 var sharedKey = requireSharedKey();
1737 var CORRECT_PROTOTYPE_GETTER = requireCorrectPrototypeGetter();
1738
1739 var IE_PROTO = sharedKey('IE_PROTO');
1740 var $Object = Object;
1741 var ObjectPrototype = $Object.prototype;
1742
1743 // `Object.getPrototypeOf` method
1744 // https://tc39.es/ecma262/#sec-object.getprototypeof
1745 // eslint-disable-next-line es/no-object-getprototypeof -- safe
1746 objectGetPrototypeOf = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) {
1747 var object = toObject(O);
1748 if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];
1749 var constructor = object.constructor;
1750 if (isCallable(constructor) && object instanceof constructor) {
1751 return constructor.prototype;
1752 } return object instanceof $Object ? ObjectPrototype : null;
1753 };
1754 return objectGetPrototypeOf;
1755 }
1756
1757 var iteratorsCore;
1758 var hasRequiredIteratorsCore;
1759
1760 function requireIteratorsCore () {
1761 if (hasRequiredIteratorsCore) return iteratorsCore;
1762 hasRequiredIteratorsCore = 1;
1763 var fails = requireFails();
1764 var isCallable = requireIsCallable();
1765 var isObject = requireIsObject();
1766 var create = requireObjectCreate();
1767 var getPrototypeOf = requireObjectGetPrototypeOf();
1768 var defineBuiltIn = requireDefineBuiltIn();
1769 var wellKnownSymbol = requireWellKnownSymbol();
1770 var IS_PURE = requireIsPure();
1771
1772 var ITERATOR = wellKnownSymbol('iterator');
1773 var BUGGY_SAFARI_ITERATORS = false;
1774
1775 // `%IteratorPrototype%` object
1776 // https://tc39.es/ecma262/#sec-%iteratorprototype%-object
1777 var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
1778
1779 /* eslint-disable es/no-array-prototype-keys -- safe */
1780 if ([].keys) {
1781 arrayIterator = [].keys();
1782 // Safari 8 has buggy iterators w/o `next`
1783 if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
1784 else {
1785 PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
1786 if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
1787 }
1788 }
1789
1790 var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () {
1791 var test = {};
1792 // FF44- legacy iterators case
1793 return IteratorPrototype[ITERATOR].call(test) !== test;
1794 });
1795
1796 if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};
1797 else if (IS_PURE) IteratorPrototype = create(IteratorPrototype);
1798
1799 // `%IteratorPrototype%[@@iterator]()` method
1800 // https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
1801 if (!isCallable(IteratorPrototype[ITERATOR])) {
1802 defineBuiltIn(IteratorPrototype, ITERATOR, function () {
1803 return this;
1804 });
1805 }
1806
1807 iteratorsCore = {
1808 IteratorPrototype: IteratorPrototype,
1809 BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
1810 };
1811 return iteratorsCore;
1812 }
1813
1814 var createIterResultObject;
1815 var hasRequiredCreateIterResultObject;
1816
1817 function requireCreateIterResultObject () {
1818 if (hasRequiredCreateIterResultObject) return createIterResultObject;
1819 hasRequiredCreateIterResultObject = 1;
1820 // `CreateIterResultObject` abstract operation
1821 // https://tc39.es/ecma262/#sec-createiterresultobject
1822 createIterResultObject = function (value, done) {
1823 return { value: value, done: done };
1824 };
1825 return createIterResultObject;
1826 }
1827
1828 var iteratorClose;
1829 var hasRequiredIteratorClose;
1830
1831 function requireIteratorClose () {
1832 if (hasRequiredIteratorClose) return iteratorClose;
1833 hasRequiredIteratorClose = 1;
1834 var call = requireFunctionCall();
1835 var anObject = requireAnObject();
1836 var getMethod = requireGetMethod();
1837
1838 iteratorClose = function (iterator, kind, value) {
1839 var innerResult, innerError;
1840 anObject(iterator);
1841 try {
1842 innerResult = getMethod(iterator, 'return');
1843 if (!innerResult) {
1844 if (kind === 'throw') throw value;
1845 return value;
1846 }
1847 innerResult = call(innerResult, iterator);
1848 } catch (error) {
1849 innerError = true;
1850 innerResult = error;
1851 }
1852 if (kind === 'throw') throw value;
1853 if (innerError) throw innerResult;
1854 anObject(innerResult);
1855 return value;
1856 };
1857 return iteratorClose;
1858 }
1859
1860 var iteratorCreateProxy;
1861 var hasRequiredIteratorCreateProxy;
1862
1863 function requireIteratorCreateProxy () {
1864 if (hasRequiredIteratorCreateProxy) return iteratorCreateProxy;
1865 hasRequiredIteratorCreateProxy = 1;
1866 var call = requireFunctionCall();
1867 var create = requireObjectCreate();
1868 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1869 var defineBuiltIns = requireDefineBuiltIns();
1870 var wellKnownSymbol = requireWellKnownSymbol();
1871 var InternalStateModule = requireInternalState();
1872 var getMethod = requireGetMethod();
1873 var IteratorPrototype = requireIteratorsCore().IteratorPrototype;
1874 var createIterResultObject = requireCreateIterResultObject();
1875 var iteratorClose = requireIteratorClose();
1876
1877 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
1878 var ITERATOR_HELPER = 'IteratorHelper';
1879 var WRAP_FOR_VALID_ITERATOR = 'WrapForValidIterator';
1880 var setInternalState = InternalStateModule.set;
1881
1882 var createIteratorProxyPrototype = function (IS_ITERATOR) {
1883 var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER);
1884
1885 return defineBuiltIns(create(IteratorPrototype), {
1886 next: function next() {
1887 var state = getInternalState(this);
1888 // for simplification:
1889 // for `%WrapForValidIteratorPrototype%.next` our `nextHandler` returns `IterResultObject`
1890 // for `%IteratorHelperPrototype%.next` - just a value
1891 if (IS_ITERATOR) return state.nextHandler();
1892 try {
1893 var result = state.done ? undefined : state.nextHandler();
1894 return createIterResultObject(result, state.done);
1895 } catch (error) {
1896 state.done = true;
1897 throw error;
1898 }
1899 },
1900 'return': function () {
1901 var state = getInternalState(this);
1902 var iterator = state.iterator;
1903 state.done = true;
1904 if (IS_ITERATOR) {
1905 var returnMethod = getMethod(iterator, 'return');
1906 return returnMethod ? call(returnMethod, iterator) : createIterResultObject(undefined, true);
1907 }
1908 if (state.inner) try {
1909 iteratorClose(state.inner.iterator, 'normal');
1910 } catch (error) {
1911 return iteratorClose(iterator, 'throw', error);
1912 }
1913 if (iterator) iteratorClose(iterator, 'normal');
1914 return createIterResultObject(undefined, true);
1915 }
1916 });
1917 };
1918
1919 var WrapForValidIteratorPrototype = createIteratorProxyPrototype(true);
1920 var IteratorHelperPrototype = createIteratorProxyPrototype(false);
1921
1922 createNonEnumerableProperty(IteratorHelperPrototype, TO_STRING_TAG, 'Iterator Helper');
1923
1924 iteratorCreateProxy = function (nextHandler, IS_ITERATOR) {
1925 var IteratorProxy = function Iterator(record, state) {
1926 if (state) {
1927 state.iterator = record.iterator;
1928 state.next = record.next;
1929 } else state = record;
1930 state.type = IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER;
1931 state.nextHandler = nextHandler;
1932 state.counter = 0;
1933 state.done = false;
1934 setInternalState(this, state);
1935 };
1936
1937 IteratorProxy.prototype = IS_ITERATOR ? WrapForValidIteratorPrototype : IteratorHelperPrototype;
1938
1939 return IteratorProxy;
1940 };
1941 return iteratorCreateProxy;
1942 }
1943
1944 var callWithSafeIterationClosing;
1945 var hasRequiredCallWithSafeIterationClosing;
1946
1947 function requireCallWithSafeIterationClosing () {
1948 if (hasRequiredCallWithSafeIterationClosing) return callWithSafeIterationClosing;
1949 hasRequiredCallWithSafeIterationClosing = 1;
1950 var anObject = requireAnObject();
1951 var iteratorClose = requireIteratorClose();
1952
1953 // call something on iterator step with safe closing on error
1954 callWithSafeIterationClosing = function (iterator, fn, value, ENTRIES) {
1955 try {
1956 return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
1957 } catch (error) {
1958 iteratorClose(iterator, 'throw', error);
1959 }
1960 };
1961 return callWithSafeIterationClosing;
1962 }
1963
1964 var iteratorMap;
1965 var hasRequiredIteratorMap;
1966
1967 function requireIteratorMap () {
1968 if (hasRequiredIteratorMap) return iteratorMap;
1969 hasRequiredIteratorMap = 1;
1970 var call = requireFunctionCall();
1971 var aCallable = requireACallable();
1972 var anObject = requireAnObject();
1973 var getIteratorDirect = requireGetIteratorDirect();
1974 var createIteratorProxy = requireIteratorCreateProxy();
1975 var callWithSafeIterationClosing = requireCallWithSafeIterationClosing();
1976
1977 var IteratorProxy = createIteratorProxy(function () {
1978 var iterator = this.iterator;
1979 var result = anObject(call(this.next, iterator));
1980 var done = this.done = !!result.done;
1981 if (!done) return callWithSafeIterationClosing(iterator, this.mapper, [result.value, this.counter++], true);
1982 });
1983
1984 // `Iterator.prototype.map` method
1985 // https://github.com/tc39/proposal-iterator-helpers
1986 iteratorMap = function map(mapper) {
1987 anObject(this);
1988 aCallable(mapper);
1989 return new IteratorProxy(getIteratorDirect(this), {
1990 mapper: mapper
1991 });
1992 };
1993 return iteratorMap;
1994 }
1995
1996 var hasRequiredEs_iterator_map;
1997
1998 function requireEs_iterator_map () {
1999 if (hasRequiredEs_iterator_map) return es_iterator_map;
2000 hasRequiredEs_iterator_map = 1;
2001 var $ = require_export();
2002 var map = requireIteratorMap();
2003 var IS_PURE = requireIsPure();
2004
2005 // `Iterator.prototype.map` method
2006 // https://tc39.es/ecma262/#sec-iterator.prototype.map
2007 $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
2008 map: map
2009 });
2010 return es_iterator_map;
2011 }
2012
2013 var hasRequiredEsnext_iterator_map;
2014
2015 function requireEsnext_iterator_map () {
2016 if (hasRequiredEsnext_iterator_map) return esnext_iterator_map;
2017 hasRequiredEsnext_iterator_map = 1;
2018 // TODO: Remove from `core-js@4`
2019 requireEs_iterator_map();
2020 return esnext_iterator_map;
2021 }
2022
2023 requireEsnext_iterator_map();
2024
2025 var es_error_cause = {};
2026
2027 var functionApply;
2028 var hasRequiredFunctionApply;
2029
2030 function requireFunctionApply () {
2031 if (hasRequiredFunctionApply) return functionApply;
2032 hasRequiredFunctionApply = 1;
2033 var NATIVE_BIND = requireFunctionBindNative();
2034
2035 var FunctionPrototype = Function.prototype;
2036 var apply = FunctionPrototype.apply;
2037 var call = FunctionPrototype.call;
2038
2039 // eslint-disable-next-line es/no-reflect -- safe
2040 functionApply = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () {
2041 return call.apply(apply, arguments);
2042 });
2043 return functionApply;
2044 }
2045
2046 var functionUncurryThisAccessor;
2047 var hasRequiredFunctionUncurryThisAccessor;
2048
2049 function requireFunctionUncurryThisAccessor () {
2050 if (hasRequiredFunctionUncurryThisAccessor) return functionUncurryThisAccessor;
2051 hasRequiredFunctionUncurryThisAccessor = 1;
2052 var uncurryThis = requireFunctionUncurryThis();
2053 var aCallable = requireACallable();
2054
2055 functionUncurryThisAccessor = function (object, key, method) {
2056 try {
2057 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
2058 return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method]));
2059 } catch (error) { /* empty */ }
2060 };
2061 return functionUncurryThisAccessor;
2062 }
2063
2064 var isPossiblePrototype;
2065 var hasRequiredIsPossiblePrototype;
2066
2067 function requireIsPossiblePrototype () {
2068 if (hasRequiredIsPossiblePrototype) return isPossiblePrototype;
2069 hasRequiredIsPossiblePrototype = 1;
2070 var isObject = requireIsObject();
2071
2072 isPossiblePrototype = function (argument) {
2073 return isObject(argument) || argument === null;
2074 };
2075 return isPossiblePrototype;
2076 }
2077
2078 var aPossiblePrototype;
2079 var hasRequiredAPossiblePrototype;
2080
2081 function requireAPossiblePrototype () {
2082 if (hasRequiredAPossiblePrototype) return aPossiblePrototype;
2083 hasRequiredAPossiblePrototype = 1;
2084 var isPossiblePrototype = requireIsPossiblePrototype();
2085
2086 var $String = String;
2087 var $TypeError = TypeError;
2088
2089 aPossiblePrototype = function (argument) {
2090 if (isPossiblePrototype(argument)) return argument;
2091 throw new $TypeError("Can't set " + $String(argument) + ' as a prototype');
2092 };
2093 return aPossiblePrototype;
2094 }
2095
2096 var objectSetPrototypeOf;
2097 var hasRequiredObjectSetPrototypeOf;
2098
2099 function requireObjectSetPrototypeOf () {
2100 if (hasRequiredObjectSetPrototypeOf) return objectSetPrototypeOf;
2101 hasRequiredObjectSetPrototypeOf = 1;
2102 /* eslint-disable no-proto -- safe */
2103 var uncurryThisAccessor = requireFunctionUncurryThisAccessor();
2104 var isObject = requireIsObject();
2105 var requireObjectCoercible = requireRequireObjectCoercible();
2106 var aPossiblePrototype = requireAPossiblePrototype();
2107
2108 // `Object.setPrototypeOf` method
2109 // https://tc39.es/ecma262/#sec-object.setprototypeof
2110 // Works with __proto__ only. Old v8 can't work with null proto objects.
2111 // eslint-disable-next-line es/no-object-setprototypeof -- safe
2112 objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
2113 var CORRECT_SETTER = false;
2114 var test = {};
2115 var setter;
2116 try {
2117 setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set');
2118 setter(test, []);
2119 CORRECT_SETTER = test instanceof Array;
2120 } catch (error) { /* empty */ }
2121 return function setPrototypeOf(O, proto) {
2122 requireObjectCoercible(O);
2123 aPossiblePrototype(proto);
2124 if (!isObject(O)) return O;
2125 if (CORRECT_SETTER) setter(O, proto);
2126 else O.__proto__ = proto;
2127 return O;
2128 };
2129 }() : undefined);
2130 return objectSetPrototypeOf;
2131 }
2132
2133 var proxyAccessor;
2134 var hasRequiredProxyAccessor;
2135
2136 function requireProxyAccessor () {
2137 if (hasRequiredProxyAccessor) return proxyAccessor;
2138 hasRequiredProxyAccessor = 1;
2139 var defineProperty = requireObjectDefineProperty().f;
2140
2141 proxyAccessor = function (Target, Source, key) {
2142 key in Target || defineProperty(Target, key, {
2143 configurable: true,
2144 get: function () { return Source[key]; },
2145 set: function (it) { Source[key] = it; }
2146 });
2147 };
2148 return proxyAccessor;
2149 }
2150
2151 var inheritIfRequired;
2152 var hasRequiredInheritIfRequired;
2153
2154 function requireInheritIfRequired () {
2155 if (hasRequiredInheritIfRequired) return inheritIfRequired;
2156 hasRequiredInheritIfRequired = 1;
2157 var isCallable = requireIsCallable();
2158 var isObject = requireIsObject();
2159 var setPrototypeOf = requireObjectSetPrototypeOf();
2160
2161 // makes subclassing work correct for wrapped built-ins
2162 inheritIfRequired = function ($this, dummy, Wrapper) {
2163 var NewTarget, NewTargetPrototype;
2164 if (
2165 // it can work only with native `setPrototypeOf`
2166 setPrototypeOf &&
2167 // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
2168 isCallable(NewTarget = dummy.constructor) &&
2169 NewTarget !== Wrapper &&
2170 isObject(NewTargetPrototype = NewTarget.prototype) &&
2171 NewTargetPrototype !== Wrapper.prototype
2172 ) setPrototypeOf($this, NewTargetPrototype);
2173 return $this;
2174 };
2175 return inheritIfRequired;
2176 }
2177
2178 var toStringTagSupport;
2179 var hasRequiredToStringTagSupport;
2180
2181 function requireToStringTagSupport () {
2182 if (hasRequiredToStringTagSupport) return toStringTagSupport;
2183 hasRequiredToStringTagSupport = 1;
2184 var wellKnownSymbol = requireWellKnownSymbol();
2185
2186 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2187 var test = {};
2188
2189 test[TO_STRING_TAG] = 'z';
2190
2191 toStringTagSupport = String(test) === '[object z]';
2192 return toStringTagSupport;
2193 }
2194
2195 var classof;
2196 var hasRequiredClassof;
2197
2198 function requireClassof () {
2199 if (hasRequiredClassof) return classof;
2200 hasRequiredClassof = 1;
2201 var TO_STRING_TAG_SUPPORT = requireToStringTagSupport();
2202 var isCallable = requireIsCallable();
2203 var classofRaw = requireClassofRaw();
2204 var wellKnownSymbol = requireWellKnownSymbol();
2205
2206 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2207 var $Object = Object;
2208
2209 // ES3 wrong here
2210 var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments';
2211
2212 // fallback for IE11 Script Access Denied error
2213 var tryGet = function (it, key) {
2214 try {
2215 return it[key];
2216 } catch (error) { /* empty */ }
2217 };
2218
2219 // getting tag from ES6+ `Object.prototype.toString`
2220 classof = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
2221 var O, tag, result;
2222 return it === undefined ? 'Undefined' : it === null ? 'Null'
2223 // @@toStringTag case
2224 : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag
2225 // builtinTag case
2226 : CORRECT_ARGUMENTS ? classofRaw(O)
2227 // ES3 arguments fallback
2228 : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result;
2229 };
2230 return classof;
2231 }
2232
2233 var toString;
2234 var hasRequiredToString;
2235
2236 function requireToString () {
2237 if (hasRequiredToString) return toString;
2238 hasRequiredToString = 1;
2239 var classof = requireClassof();
2240
2241 var $String = String;
2242
2243 toString = function (argument) {
2244 if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string');
2245 return $String(argument);
2246 };
2247 return toString;
2248 }
2249
2250 var normalizeStringArgument;
2251 var hasRequiredNormalizeStringArgument;
2252
2253 function requireNormalizeStringArgument () {
2254 if (hasRequiredNormalizeStringArgument) return normalizeStringArgument;
2255 hasRequiredNormalizeStringArgument = 1;
2256 var toString = requireToString();
2257
2258 normalizeStringArgument = function (argument, $default) {
2259 return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument);
2260 };
2261 return normalizeStringArgument;
2262 }
2263
2264 var installErrorCause;
2265 var hasRequiredInstallErrorCause;
2266
2267 function requireInstallErrorCause () {
2268 if (hasRequiredInstallErrorCause) return installErrorCause;
2269 hasRequiredInstallErrorCause = 1;
2270 var isObject = requireIsObject();
2271 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
2272
2273 // `InstallErrorCause` abstract operation
2274 // https://tc39.es/proposal-error-cause/#sec-errorobjects-install-error-cause
2275 installErrorCause = function (O, options) {
2276 if (isObject(options) && 'cause' in options) {
2277 createNonEnumerableProperty(O, 'cause', options.cause);
2278 }
2279 };
2280 return installErrorCause;
2281 }
2282
2283 var errorStackClear;
2284 var hasRequiredErrorStackClear;
2285
2286 function requireErrorStackClear () {
2287 if (hasRequiredErrorStackClear) return errorStackClear;
2288 hasRequiredErrorStackClear = 1;
2289 var uncurryThis = requireFunctionUncurryThis();
2290
2291 var $Error = Error;
2292 var replace = uncurryThis(''.replace);
2293
2294 var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd');
2295 // eslint-disable-next-line redos/no-vulnerable, sonarjs/slow-regex -- safe
2296 var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/;
2297 var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);
2298
2299 errorStackClear = function (stack, dropEntries) {
2300 if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) {
2301 while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, '');
2302 } return stack;
2303 };
2304 return errorStackClear;
2305 }
2306
2307 var errorStackInstallable;
2308 var hasRequiredErrorStackInstallable;
2309
2310 function requireErrorStackInstallable () {
2311 if (hasRequiredErrorStackInstallable) return errorStackInstallable;
2312 hasRequiredErrorStackInstallable = 1;
2313 var fails = requireFails();
2314 var createPropertyDescriptor = requireCreatePropertyDescriptor();
2315
2316 errorStackInstallable = !fails(function () {
2317 var error = new Error('a');
2318 if (!('stack' in error)) return true;
2319 // eslint-disable-next-line es/no-object-defineproperty -- safe
2320 Object.defineProperty(error, 'stack', createPropertyDescriptor(1, 7));
2321 return error.stack !== 7;
2322 });
2323 return errorStackInstallable;
2324 }
2325
2326 var errorStackInstall;
2327 var hasRequiredErrorStackInstall;
2328
2329 function requireErrorStackInstall () {
2330 if (hasRequiredErrorStackInstall) return errorStackInstall;
2331 hasRequiredErrorStackInstall = 1;
2332 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
2333 var clearErrorStack = requireErrorStackClear();
2334 var ERROR_STACK_INSTALLABLE = requireErrorStackInstallable();
2335
2336 // non-standard V8
2337 var captureStackTrace = Error.captureStackTrace;
2338
2339 errorStackInstall = function (error, C, stack, dropEntries) {
2340 if (ERROR_STACK_INSTALLABLE) {
2341 if (captureStackTrace) captureStackTrace(error, C);
2342 else createNonEnumerableProperty(error, 'stack', clearErrorStack(stack, dropEntries));
2343 }
2344 };
2345 return errorStackInstall;
2346 }
2347
2348 var wrapErrorConstructorWithCause;
2349 var hasRequiredWrapErrorConstructorWithCause;
2350
2351 function requireWrapErrorConstructorWithCause () {
2352 if (hasRequiredWrapErrorConstructorWithCause) return wrapErrorConstructorWithCause;
2353 hasRequiredWrapErrorConstructorWithCause = 1;
2354 var getBuiltIn = requireGetBuiltIn();
2355 var hasOwn = requireHasOwnProperty();
2356 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
2357 var isPrototypeOf = requireObjectIsPrototypeOf();
2358 var setPrototypeOf = requireObjectSetPrototypeOf();
2359 var copyConstructorProperties = requireCopyConstructorProperties();
2360 var proxyAccessor = requireProxyAccessor();
2361 var inheritIfRequired = requireInheritIfRequired();
2362 var normalizeStringArgument = requireNormalizeStringArgument();
2363 var installErrorCause = requireInstallErrorCause();
2364 var installErrorStack = requireErrorStackInstall();
2365 var DESCRIPTORS = requireDescriptors();
2366 var IS_PURE = requireIsPure();
2367
2368 wrapErrorConstructorWithCause = function (FULL_NAME, wrapper, FORCED, IS_AGGREGATE_ERROR) {
2369 var STACK_TRACE_LIMIT = 'stackTraceLimit';
2370 var OPTIONS_POSITION = IS_AGGREGATE_ERROR ? 2 : 1;
2371 var path = FULL_NAME.split('.');
2372 var ERROR_NAME = path[path.length - 1];
2373 var OriginalError = getBuiltIn.apply(null, path);
2374
2375 if (!OriginalError) return;
2376
2377 var OriginalErrorPrototype = OriginalError.prototype;
2378
2379 // V8 9.3- bug https://bugs.chromium.org/p/v8/issues/detail?id=12006
2380 if (!IS_PURE && hasOwn(OriginalErrorPrototype, 'cause')) delete OriginalErrorPrototype.cause;
2381
2382 if (!FORCED) return OriginalError;
2383
2384 var BaseError = getBuiltIn('Error');
2385
2386 var WrappedError = wrapper(function (a, b) {
2387 var message = normalizeStringArgument(IS_AGGREGATE_ERROR ? b : a, undefined);
2388 var result = IS_AGGREGATE_ERROR ? new OriginalError(a) : new OriginalError();
2389 if (message !== undefined) createNonEnumerableProperty(result, 'message', message);
2390 installErrorStack(result, WrappedError, result.stack, 2);
2391 if (this && isPrototypeOf(OriginalErrorPrototype, this)) inheritIfRequired(result, this, WrappedError);
2392 if (arguments.length > OPTIONS_POSITION) installErrorCause(result, arguments[OPTIONS_POSITION]);
2393 return result;
2394 });
2395
2396 WrappedError.prototype = OriginalErrorPrototype;
2397
2398 if (ERROR_NAME !== 'Error') {
2399 if (setPrototypeOf) setPrototypeOf(WrappedError, BaseError);
2400 else copyConstructorProperties(WrappedError, BaseError, { name: true });
2401 } else if (DESCRIPTORS && STACK_TRACE_LIMIT in OriginalError) {
2402 proxyAccessor(WrappedError, OriginalError, STACK_TRACE_LIMIT);
2403 proxyAccessor(WrappedError, OriginalError, 'prepareStackTrace');
2404 }
2405
2406 copyConstructorProperties(WrappedError, OriginalError);
2407
2408 if (!IS_PURE) try {
2409 // Safari 13- bug: WebAssembly errors does not have a proper `.name`
2410 if (OriginalErrorPrototype.name !== ERROR_NAME) {
2411 createNonEnumerableProperty(OriginalErrorPrototype, 'name', ERROR_NAME);
2412 }
2413 OriginalErrorPrototype.constructor = WrappedError;
2414 } catch (error) { /* empty */ }
2415
2416 return WrappedError;
2417 };
2418 return wrapErrorConstructorWithCause;
2419 }
2420
2421 var hasRequiredEs_error_cause;
2422
2423 function requireEs_error_cause () {
2424 if (hasRequiredEs_error_cause) return es_error_cause;
2425 hasRequiredEs_error_cause = 1;
2426 /* eslint-disable no-unused-vars -- required for functions `.length` */
2427 var $ = require_export();
2428 var globalThis = requireGlobalThis();
2429 var apply = requireFunctionApply();
2430 var wrapErrorConstructorWithCause = requireWrapErrorConstructorWithCause();
2431
2432 var WEB_ASSEMBLY = 'WebAssembly';
2433 var WebAssembly = globalThis[WEB_ASSEMBLY];
2434
2435 // eslint-disable-next-line es/no-error-cause -- feature detection
2436 var FORCED = new Error('e', { cause: 7 }).cause !== 7;
2437
2438 var exportGlobalErrorCauseWrapper = function (ERROR_NAME, wrapper) {
2439 var O = {};
2440 O[ERROR_NAME] = wrapErrorConstructorWithCause(ERROR_NAME, wrapper, FORCED);
2441 $({ global: true, constructor: true, arity: 1, forced: FORCED }, O);
2442 };
2443
2444 var exportWebAssemblyErrorCauseWrapper = function (ERROR_NAME, wrapper) {
2445 if (WebAssembly && WebAssembly[ERROR_NAME]) {
2446 var O = {};
2447 O[ERROR_NAME] = wrapErrorConstructorWithCause(WEB_ASSEMBLY + '.' + ERROR_NAME, wrapper, FORCED);
2448 $({ target: WEB_ASSEMBLY, stat: true, constructor: true, arity: 1, forced: FORCED }, O);
2449 }
2450 };
2451
2452 // https://tc39.es/ecma262/#sec-nativeerror
2453 exportGlobalErrorCauseWrapper('Error', function (init) {
2454 return function Error(message) { return apply(init, this, arguments); };
2455 });
2456 exportGlobalErrorCauseWrapper('EvalError', function (init) {
2457 return function EvalError(message) { return apply(init, this, arguments); };
2458 });
2459 exportGlobalErrorCauseWrapper('RangeError', function (init) {
2460 return function RangeError(message) { return apply(init, this, arguments); };
2461 });
2462 exportGlobalErrorCauseWrapper('ReferenceError', function (init) {
2463 return function ReferenceError(message) { return apply(init, this, arguments); };
2464 });
2465 exportGlobalErrorCauseWrapper('SyntaxError', function (init) {
2466 return function SyntaxError(message) { return apply(init, this, arguments); };
2467 });
2468 exportGlobalErrorCauseWrapper('TypeError', function (init) {
2469 return function TypeError(message) { return apply(init, this, arguments); };
2470 });
2471 exportGlobalErrorCauseWrapper('URIError', function (init) {
2472 return function URIError(message) { return apply(init, this, arguments); };
2473 });
2474 exportWebAssemblyErrorCauseWrapper('CompileError', function (init) {
2475 return function CompileError(message) { return apply(init, this, arguments); };
2476 });
2477 exportWebAssemblyErrorCauseWrapper('LinkError', function (init) {
2478 return function LinkError(message) { return apply(init, this, arguments); };
2479 });
2480 exportWebAssemblyErrorCauseWrapper('RuntimeError', function (init) {
2481 return function RuntimeError(message) { return apply(init, this, arguments); };
2482 });
2483 return es_error_cause;
2484 }
2485
2486 requireEs_error_cause();
2487
2488 var esnext_iterator_constructor = {};
2489
2490 var es_iterator_constructor = {};
2491
2492 var anInstance;
2493 var hasRequiredAnInstance;
2494
2495 function requireAnInstance () {
2496 if (hasRequiredAnInstance) return anInstance;
2497 hasRequiredAnInstance = 1;
2498 var isPrototypeOf = requireObjectIsPrototypeOf();
2499
2500 var $TypeError = TypeError;
2501
2502 anInstance = function (it, Prototype) {
2503 if (isPrototypeOf(Prototype, it)) return it;
2504 throw new $TypeError('Incorrect invocation');
2505 };
2506 return anInstance;
2507 }
2508
2509 var defineBuiltInAccessor;
2510 var hasRequiredDefineBuiltInAccessor;
2511
2512 function requireDefineBuiltInAccessor () {
2513 if (hasRequiredDefineBuiltInAccessor) return defineBuiltInAccessor;
2514 hasRequiredDefineBuiltInAccessor = 1;
2515 var makeBuiltIn = requireMakeBuiltIn();
2516 var defineProperty = requireObjectDefineProperty();
2517
2518 defineBuiltInAccessor = function (target, name, descriptor) {
2519 if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true });
2520 if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true });
2521 return defineProperty.f(target, name, descriptor);
2522 };
2523 return defineBuiltInAccessor;
2524 }
2525
2526 var createProperty;
2527 var hasRequiredCreateProperty;
2528
2529 function requireCreateProperty () {
2530 if (hasRequiredCreateProperty) return createProperty;
2531 hasRequiredCreateProperty = 1;
2532 var DESCRIPTORS = requireDescriptors();
2533 var definePropertyModule = requireObjectDefineProperty();
2534 var createPropertyDescriptor = requireCreatePropertyDescriptor();
2535
2536 createProperty = function (object, key, value) {
2537 if (DESCRIPTORS) definePropertyModule.f(object, key, createPropertyDescriptor(0, value));
2538 else object[key] = value;
2539 };
2540 return createProperty;
2541 }
2542
2543 var hasRequiredEs_iterator_constructor;
2544
2545 function requireEs_iterator_constructor () {
2546 if (hasRequiredEs_iterator_constructor) return es_iterator_constructor;
2547 hasRequiredEs_iterator_constructor = 1;
2548 var $ = require_export();
2549 var globalThis = requireGlobalThis();
2550 var anInstance = requireAnInstance();
2551 var anObject = requireAnObject();
2552 var isCallable = requireIsCallable();
2553 var getPrototypeOf = requireObjectGetPrototypeOf();
2554 var defineBuiltInAccessor = requireDefineBuiltInAccessor();
2555 var createProperty = requireCreateProperty();
2556 var fails = requireFails();
2557 var hasOwn = requireHasOwnProperty();
2558 var wellKnownSymbol = requireWellKnownSymbol();
2559 var IteratorPrototype = requireIteratorsCore().IteratorPrototype;
2560 var DESCRIPTORS = requireDescriptors();
2561 var IS_PURE = requireIsPure();
2562
2563 var CONSTRUCTOR = 'constructor';
2564 var ITERATOR = 'Iterator';
2565 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2566
2567 var $TypeError = TypeError;
2568 var NativeIterator = globalThis[ITERATOR];
2569
2570 // FF56- have non-standard global helper `Iterator`
2571 var FORCED = IS_PURE
2572 || !isCallable(NativeIterator)
2573 || NativeIterator.prototype !== IteratorPrototype
2574 // FF44- non-standard `Iterator` passes previous tests
2575 || !fails(function () { NativeIterator({}); });
2576
2577 var IteratorConstructor = function Iterator() {
2578 anInstance(this, IteratorPrototype);
2579 if (getPrototypeOf(this) === IteratorPrototype) throw new $TypeError('Abstract class Iterator not directly constructable');
2580 };
2581
2582 var defineIteratorPrototypeAccessor = function (key, value) {
2583 if (DESCRIPTORS) {
2584 defineBuiltInAccessor(IteratorPrototype, key, {
2585 configurable: true,
2586 get: function () {
2587 return value;
2588 },
2589 set: function (replacement) {
2590 anObject(this);
2591 if (this === IteratorPrototype) throw new $TypeError("You can't redefine this property");
2592 if (hasOwn(this, key)) this[key] = replacement;
2593 else createProperty(this, key, replacement);
2594 }
2595 });
2596 } else IteratorPrototype[key] = value;
2597 };
2598
2599 if (!hasOwn(IteratorPrototype, TO_STRING_TAG)) defineIteratorPrototypeAccessor(TO_STRING_TAG, ITERATOR);
2600
2601 if (FORCED || !hasOwn(IteratorPrototype, CONSTRUCTOR) || IteratorPrototype[CONSTRUCTOR] === Object) {
2602 defineIteratorPrototypeAccessor(CONSTRUCTOR, IteratorConstructor);
2603 }
2604
2605 IteratorConstructor.prototype = IteratorPrototype;
2606
2607 // `Iterator` constructor
2608 // https://tc39.es/ecma262/#sec-iterator
2609 $({ global: true, constructor: true, forced: FORCED }, {
2610 Iterator: IteratorConstructor
2611 });
2612 return es_iterator_constructor;
2613 }
2614
2615 var hasRequiredEsnext_iterator_constructor;
2616
2617 function requireEsnext_iterator_constructor () {
2618 if (hasRequiredEsnext_iterator_constructor) return esnext_iterator_constructor;
2619 hasRequiredEsnext_iterator_constructor = 1;
2620 // TODO: Remove from `core-js@4`
2621 requireEs_iterator_constructor();
2622 return esnext_iterator_constructor;
2623 }
2624
2625 requireEsnext_iterator_constructor();
2626
2627 var esnext_iterator_reduce = {};
2628
2629 var es_iterator_reduce = {};
2630
2631 var functionUncurryThisClause;
2632 var hasRequiredFunctionUncurryThisClause;
2633
2634 function requireFunctionUncurryThisClause () {
2635 if (hasRequiredFunctionUncurryThisClause) return functionUncurryThisClause;
2636 hasRequiredFunctionUncurryThisClause = 1;
2637 var classofRaw = requireClassofRaw();
2638 var uncurryThis = requireFunctionUncurryThis();
2639
2640 functionUncurryThisClause = function (fn) {
2641 // Nashorn bug:
2642 // https://github.com/zloirock/core-js/issues/1128
2643 // https://github.com/zloirock/core-js/issues/1130
2644 if (classofRaw(fn) === 'Function') return uncurryThis(fn);
2645 };
2646 return functionUncurryThisClause;
2647 }
2648
2649 var functionBindContext;
2650 var hasRequiredFunctionBindContext;
2651
2652 function requireFunctionBindContext () {
2653 if (hasRequiredFunctionBindContext) return functionBindContext;
2654 hasRequiredFunctionBindContext = 1;
2655 var uncurryThis = requireFunctionUncurryThisClause();
2656 var aCallable = requireACallable();
2657 var NATIVE_BIND = requireFunctionBindNative();
2658
2659 var bind = uncurryThis(uncurryThis.bind);
2660
2661 // optional / simple context binding
2662 functionBindContext = function (fn, that) {
2663 aCallable(fn);
2664 return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) {
2665 return fn.apply(that, arguments);
2666 };
2667 };
2668 return functionBindContext;
2669 }
2670
2671 var iterators;
2672 var hasRequiredIterators;
2673
2674 function requireIterators () {
2675 if (hasRequiredIterators) return iterators;
2676 hasRequiredIterators = 1;
2677 iterators = {};
2678 return iterators;
2679 }
2680
2681 var isArrayIteratorMethod;
2682 var hasRequiredIsArrayIteratorMethod;
2683
2684 function requireIsArrayIteratorMethod () {
2685 if (hasRequiredIsArrayIteratorMethod) return isArrayIteratorMethod;
2686 hasRequiredIsArrayIteratorMethod = 1;
2687 var wellKnownSymbol = requireWellKnownSymbol();
2688 var Iterators = requireIterators();
2689
2690 var ITERATOR = wellKnownSymbol('iterator');
2691 var ArrayPrototype = Array.prototype;
2692
2693 // check on default Array iterator
2694 isArrayIteratorMethod = function (it) {
2695 return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
2696 };
2697 return isArrayIteratorMethod;
2698 }
2699
2700 var getIteratorMethod;
2701 var hasRequiredGetIteratorMethod;
2702
2703 function requireGetIteratorMethod () {
2704 if (hasRequiredGetIteratorMethod) return getIteratorMethod;
2705 hasRequiredGetIteratorMethod = 1;
2706 var classof = requireClassof();
2707 var getMethod = requireGetMethod();
2708 var isNullOrUndefined = requireIsNullOrUndefined();
2709 var Iterators = requireIterators();
2710 var wellKnownSymbol = requireWellKnownSymbol();
2711
2712 var ITERATOR = wellKnownSymbol('iterator');
2713
2714 getIteratorMethod = function (it) {
2715 if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR)
2716 || getMethod(it, '@@iterator')
2717 || Iterators[classof(it)];
2718 };
2719 return getIteratorMethod;
2720 }
2721
2722 var getIterator;
2723 var hasRequiredGetIterator;
2724
2725 function requireGetIterator () {
2726 if (hasRequiredGetIterator) return getIterator;
2727 hasRequiredGetIterator = 1;
2728 var call = requireFunctionCall();
2729 var aCallable = requireACallable();
2730 var anObject = requireAnObject();
2731 var tryToString = requireTryToString();
2732 var getIteratorMethod = requireGetIteratorMethod();
2733
2734 var $TypeError = TypeError;
2735
2736 getIterator = function (argument, usingIterator) {
2737 var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
2738 if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument));
2739 throw new $TypeError(tryToString(argument) + ' is not iterable');
2740 };
2741 return getIterator;
2742 }
2743
2744 var iterate;
2745 var hasRequiredIterate;
2746
2747 function requireIterate () {
2748 if (hasRequiredIterate) return iterate;
2749 hasRequiredIterate = 1;
2750 var bind = requireFunctionBindContext();
2751 var call = requireFunctionCall();
2752 var anObject = requireAnObject();
2753 var tryToString = requireTryToString();
2754 var isArrayIteratorMethod = requireIsArrayIteratorMethod();
2755 var lengthOfArrayLike = requireLengthOfArrayLike();
2756 var isPrototypeOf = requireObjectIsPrototypeOf();
2757 var getIterator = requireGetIterator();
2758 var getIteratorMethod = requireGetIteratorMethod();
2759 var iteratorClose = requireIteratorClose();
2760
2761 var $TypeError = TypeError;
2762
2763 var Result = function (stopped, result) {
2764 this.stopped = stopped;
2765 this.result = result;
2766 };
2767
2768 var ResultPrototype = Result.prototype;
2769
2770 iterate = function (iterable, unboundFunction, options) {
2771 var that = options && options.that;
2772 var AS_ENTRIES = !!(options && options.AS_ENTRIES);
2773 var IS_RECORD = !!(options && options.IS_RECORD);
2774 var IS_ITERATOR = !!(options && options.IS_ITERATOR);
2775 var INTERRUPTED = !!(options && options.INTERRUPTED);
2776 var fn = bind(unboundFunction, that);
2777 var iterator, iterFn, index, length, result, next, step;
2778
2779 var stop = function (condition) {
2780 if (iterator) iteratorClose(iterator, 'normal', condition);
2781 return new Result(true, condition);
2782 };
2783
2784 var callFn = function (value) {
2785 if (AS_ENTRIES) {
2786 anObject(value);
2787 return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
2788 } return INTERRUPTED ? fn(value, stop) : fn(value);
2789 };
2790
2791 if (IS_RECORD) {
2792 iterator = iterable.iterator;
2793 } else if (IS_ITERATOR) {
2794 iterator = iterable;
2795 } else {
2796 iterFn = getIteratorMethod(iterable);
2797 if (!iterFn) throw new $TypeError(tryToString(iterable) + ' is not iterable');
2798 // optimisation for array iterators
2799 if (isArrayIteratorMethod(iterFn)) {
2800 for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
2801 result = callFn(iterable[index]);
2802 if (result && isPrototypeOf(ResultPrototype, result)) return result;
2803 } return new Result(false);
2804 }
2805 iterator = getIterator(iterable, iterFn);
2806 }
2807
2808 next = IS_RECORD ? iterable.next : iterator.next;
2809 while (!(step = call(next, iterator)).done) {
2810 try {
2811 result = callFn(step.value);
2812 } catch (error) {
2813 iteratorClose(iterator, 'throw', error);
2814 }
2815 if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
2816 } return new Result(false);
2817 };
2818 return iterate;
2819 }
2820
2821 var hasRequiredEs_iterator_reduce;
2822
2823 function requireEs_iterator_reduce () {
2824 if (hasRequiredEs_iterator_reduce) return es_iterator_reduce;
2825 hasRequiredEs_iterator_reduce = 1;
2826 var $ = require_export();
2827 var iterate = requireIterate();
2828 var aCallable = requireACallable();
2829 var anObject = requireAnObject();
2830 var getIteratorDirect = requireGetIteratorDirect();
2831
2832 var $TypeError = TypeError;
2833
2834 // `Iterator.prototype.reduce` method
2835 // https://tc39.es/ecma262/#sec-iterator.prototype.reduce
2836 $({ target: 'Iterator', proto: true, real: true }, {
2837 reduce: function reduce(reducer /* , initialValue */) {
2838 anObject(this);
2839 aCallable(reducer);
2840 var record = getIteratorDirect(this);
2841 var noInitial = arguments.length < 2;
2842 var accumulator = noInitial ? undefined : arguments[1];
2843 var counter = 0;
2844 iterate(record, function (value) {
2845 if (noInitial) {
2846 noInitial = false;
2847 accumulator = value;
2848 } else {
2849 accumulator = reducer(accumulator, value, counter);
2850 }
2851 counter++;
2852 }, { IS_RECORD: true });
2853 if (noInitial) throw new $TypeError('Reduce of empty iterator with no initial value');
2854 return accumulator;
2855 }
2856 });
2857 return es_iterator_reduce;
2858 }
2859
2860 var hasRequiredEsnext_iterator_reduce;
2861
2862 function requireEsnext_iterator_reduce () {
2863 if (hasRequiredEsnext_iterator_reduce) return esnext_iterator_reduce;
2864 hasRequiredEsnext_iterator_reduce = 1;
2865 // TODO: Remove from `core-js@4`
2866 requireEs_iterator_reduce();
2867 return esnext_iterator_reduce;
2868 }
2869
2870 requireEsnext_iterator_reduce();
2871
2872 var web_domException_constructor = {};
2873
2874 var environment$1;
2875 var hasRequiredEnvironment;
2876
2877 function requireEnvironment () {
2878 if (hasRequiredEnvironment) return environment$1;
2879 hasRequiredEnvironment = 1;
2880 /* global Bun, Deno -- detection */
2881 var globalThis = requireGlobalThis();
2882 var userAgent = requireEnvironmentUserAgent();
2883 var classof = requireClassofRaw();
2884
2885 var userAgentStartsWith = function (string) {
2886 return userAgent.slice(0, string.length) === string;
2887 };
2888
2889 environment$1 = (function () {
2890 if (userAgentStartsWith('Bun/')) return 'BUN';
2891 if (userAgentStartsWith('Cloudflare-Workers')) return 'CLOUDFLARE';
2892 if (userAgentStartsWith('Deno/')) return 'DENO';
2893 if (userAgentStartsWith('Node.js/')) return 'NODE';
2894 if (globalThis.Bun && typeof Bun.version == 'string') return 'BUN';
2895 if (globalThis.Deno && typeof Deno.version == 'object') return 'DENO';
2896 if (classof(globalThis.process) === 'process') return 'NODE';
2897 if (globalThis.window && globalThis.document) return 'BROWSER';
2898 return 'REST';
2899 })();
2900 return environment$1;
2901 }
2902
2903 var environmentIsNode;
2904 var hasRequiredEnvironmentIsNode;
2905
2906 function requireEnvironmentIsNode () {
2907 if (hasRequiredEnvironmentIsNode) return environmentIsNode;
2908 hasRequiredEnvironmentIsNode = 1;
2909 var ENVIRONMENT = requireEnvironment();
2910
2911 environmentIsNode = ENVIRONMENT === 'NODE';
2912 return environmentIsNode;
2913 }
2914
2915 var getBuiltInNodeModule;
2916 var hasRequiredGetBuiltInNodeModule;
2917
2918 function requireGetBuiltInNodeModule () {
2919 if (hasRequiredGetBuiltInNodeModule) return getBuiltInNodeModule;
2920 hasRequiredGetBuiltInNodeModule = 1;
2921 var globalThis = requireGlobalThis();
2922 var IS_NODE = requireEnvironmentIsNode();
2923
2924 getBuiltInNodeModule = function (name) {
2925 if (IS_NODE) {
2926 try {
2927 return globalThis.process.getBuiltinModule(name);
2928 } catch (error) { /* empty */ }
2929 try {
2930 // eslint-disable-next-line no-new-func -- safe
2931 return Function('return require("' + name + '")')();
2932 } catch (error) { /* empty */ }
2933 }
2934 };
2935 return getBuiltInNodeModule;
2936 }
2937
2938 var errorToString;
2939 var hasRequiredErrorToString;
2940
2941 function requireErrorToString () {
2942 if (hasRequiredErrorToString) return errorToString;
2943 hasRequiredErrorToString = 1;
2944 var DESCRIPTORS = requireDescriptors();
2945 var fails = requireFails();
2946 var anObject = requireAnObject();
2947 var normalizeStringArgument = requireNormalizeStringArgument();
2948
2949 var nativeErrorToString = Error.prototype.toString;
2950
2951 var INCORRECT_TO_STRING = fails(function () {
2952 if (DESCRIPTORS) {
2953 // Chrome 32- incorrectly call accessor
2954 // eslint-disable-next-line es/no-object-create, es/no-object-defineproperty -- safe
2955 var object = Object.create(Object.defineProperty({}, 'name', { get: function () {
2956 return this === object;
2957 } }));
2958 if (nativeErrorToString.call(object) !== 'true') return true;
2959 }
2960 // FF10- does not properly handle non-strings
2961 return nativeErrorToString.call({ message: 1, name: 2 }) !== '2: 1'
2962 // IE8 does not properly handle defaults
2963 || nativeErrorToString.call({}) !== 'Error';
2964 });
2965
2966 errorToString = INCORRECT_TO_STRING ? function toString() {
2967 var O = anObject(this);
2968 var name = normalizeStringArgument(O.name, 'Error');
2969 var message = normalizeStringArgument(O.message);
2970 return !name ? message : !message ? name : name + ': ' + message;
2971 } : nativeErrorToString;
2972 return errorToString;
2973 }
2974
2975 var domExceptionConstants;
2976 var hasRequiredDomExceptionConstants;
2977
2978 function requireDomExceptionConstants () {
2979 if (hasRequiredDomExceptionConstants) return domExceptionConstants;
2980 hasRequiredDomExceptionConstants = 1;
2981 domExceptionConstants = {
2982 IndexSizeError: { s: 'INDEX_SIZE_ERR', c: 1, m: 1 },
2983 DOMStringSizeError: { s: 'DOMSTRING_SIZE_ERR', c: 2, m: 0 },
2984 HierarchyRequestError: { s: 'HIERARCHY_REQUEST_ERR', c: 3, m: 1 },
2985 WrongDocumentError: { s: 'WRONG_DOCUMENT_ERR', c: 4, m: 1 },
2986 InvalidCharacterError: { s: 'INVALID_CHARACTER_ERR', c: 5, m: 1 },
2987 NoDataAllowedError: { s: 'NO_DATA_ALLOWED_ERR', c: 6, m: 0 },
2988 NoModificationAllowedError: { s: 'NO_MODIFICATION_ALLOWED_ERR', c: 7, m: 1 },
2989 NotFoundError: { s: 'NOT_FOUND_ERR', c: 8, m: 1 },
2990 NotSupportedError: { s: 'NOT_SUPPORTED_ERR', c: 9, m: 1 },
2991 InUseAttributeError: { s: 'INUSE_ATTRIBUTE_ERR', c: 10, m: 1 },
2992 InvalidStateError: { s: 'INVALID_STATE_ERR', c: 11, m: 1 },
2993 SyntaxError: { s: 'SYNTAX_ERR', c: 12, m: 1 },
2994 InvalidModificationError: { s: 'INVALID_MODIFICATION_ERR', c: 13, m: 1 },
2995 NamespaceError: { s: 'NAMESPACE_ERR', c: 14, m: 1 },
2996 InvalidAccessError: { s: 'INVALID_ACCESS_ERR', c: 15, m: 1 },
2997 ValidationError: { s: 'VALIDATION_ERR', c: 16, m: 0 },
2998 TypeMismatchError: { s: 'TYPE_MISMATCH_ERR', c: 17, m: 1 },
2999 SecurityError: { s: 'SECURITY_ERR', c: 18, m: 1 },
3000 NetworkError: { s: 'NETWORK_ERR', c: 19, m: 1 },
3001 AbortError: { s: 'ABORT_ERR', c: 20, m: 1 },
3002 URLMismatchError: { s: 'URL_MISMATCH_ERR', c: 21, m: 1 },
3003 QuotaExceededError: { s: 'QUOTA_EXCEEDED_ERR', c: 22, m: 1 },
3004 TimeoutError: { s: 'TIMEOUT_ERR', c: 23, m: 1 },
3005 InvalidNodeTypeError: { s: 'INVALID_NODE_TYPE_ERR', c: 24, m: 1 },
3006 DataCloneError: { s: 'DATA_CLONE_ERR', c: 25, m: 1 }
3007 };
3008 return domExceptionConstants;
3009 }
3010
3011 var hasRequiredWeb_domException_constructor;
3012
3013 function requireWeb_domException_constructor () {
3014 if (hasRequiredWeb_domException_constructor) return web_domException_constructor;
3015 hasRequiredWeb_domException_constructor = 1;
3016 var $ = require_export();
3017 var getBuiltIn = requireGetBuiltIn();
3018 var getBuiltInNodeModule = requireGetBuiltInNodeModule();
3019 var fails = requireFails();
3020 var create = requireObjectCreate();
3021 var createPropertyDescriptor = requireCreatePropertyDescriptor();
3022 var defineProperty = requireObjectDefineProperty().f;
3023 var defineBuiltIn = requireDefineBuiltIn();
3024 var defineBuiltInAccessor = requireDefineBuiltInAccessor();
3025 var hasOwn = requireHasOwnProperty();
3026 var anInstance = requireAnInstance();
3027 var anObject = requireAnObject();
3028 var errorToString = requireErrorToString();
3029 var normalizeStringArgument = requireNormalizeStringArgument();
3030 var DOMExceptionConstants = requireDomExceptionConstants();
3031 var clearErrorStack = requireErrorStackClear();
3032 var InternalStateModule = requireInternalState();
3033 var DESCRIPTORS = requireDescriptors();
3034 var IS_PURE = requireIsPure();
3035
3036 var DOM_EXCEPTION = 'DOMException';
3037 var DATA_CLONE_ERR = 'DATA_CLONE_ERR';
3038 var Error = getBuiltIn('Error');
3039 // NodeJS < 17.0 does not expose `DOMException` to global
3040 var NativeDOMException = getBuiltIn(DOM_EXCEPTION) || (function () {
3041 try {
3042 // NodeJS < 15.0 does not expose `MessageChannel` to global
3043 var MessageChannel = getBuiltIn('MessageChannel') || getBuiltInNodeModule('worker_threads').MessageChannel;
3044 // eslint-disable-next-line es/no-weak-map, unicorn/require-post-message-target-origin -- safe
3045 new MessageChannel().port1.postMessage(new WeakMap());
3046 } catch (error) {
3047 if (error.name === DATA_CLONE_ERR && error.code === 25) return error.constructor;
3048 }
3049 })();
3050 var NativeDOMExceptionPrototype = NativeDOMException && NativeDOMException.prototype;
3051 var ErrorPrototype = Error.prototype;
3052 var setInternalState = InternalStateModule.set;
3053 var getInternalState = InternalStateModule.getterFor(DOM_EXCEPTION);
3054 var HAS_STACK = 'stack' in new Error(DOM_EXCEPTION);
3055
3056 var codeFor = function (name) {
3057 return hasOwn(DOMExceptionConstants, name) && DOMExceptionConstants[name].m ? DOMExceptionConstants[name].c : 0;
3058 };
3059
3060 var $DOMException = function DOMException() {
3061 anInstance(this, DOMExceptionPrototype);
3062 var argumentsLength = arguments.length;
3063 var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]);
3064 var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], 'Error');
3065 var code = codeFor(name);
3066 setInternalState(this, {
3067 type: DOM_EXCEPTION,
3068 name: name,
3069 message: message,
3070 code: code
3071 });
3072 if (!DESCRIPTORS) {
3073 this.name = name;
3074 this.message = message;
3075 this.code = code;
3076 }
3077 if (HAS_STACK) {
3078 var error = new Error(message);
3079 error.name = DOM_EXCEPTION;
3080 defineProperty(this, 'stack', createPropertyDescriptor(1, clearErrorStack(error.stack, 1)));
3081 }
3082 };
3083
3084 var DOMExceptionPrototype = $DOMException.prototype = create(ErrorPrototype);
3085
3086 var createGetterDescriptor = function (get) {
3087 return { enumerable: true, configurable: true, get: get };
3088 };
3089
3090 var getterFor = function (key) {
3091 return createGetterDescriptor(function () {
3092 return getInternalState(this)[key];
3093 });
3094 };
3095
3096 if (DESCRIPTORS) {
3097 // `DOMException.prototype.code` getter
3098 defineBuiltInAccessor(DOMExceptionPrototype, 'code', getterFor('code'));
3099 // `DOMException.prototype.message` getter
3100 defineBuiltInAccessor(DOMExceptionPrototype, 'message', getterFor('message'));
3101 // `DOMException.prototype.name` getter
3102 defineBuiltInAccessor(DOMExceptionPrototype, 'name', getterFor('name'));
3103 }
3104
3105 defineProperty(DOMExceptionPrototype, 'constructor', createPropertyDescriptor(1, $DOMException));
3106
3107 // FF36- DOMException is a function, but can't be constructed
3108 var INCORRECT_CONSTRUCTOR = fails(function () {
3109 return !(new NativeDOMException() instanceof Error);
3110 });
3111
3112 // Safari 10.1 / Chrome 32- / IE8- DOMException.prototype.toString bugs
3113 var INCORRECT_TO_STRING = INCORRECT_CONSTRUCTOR || fails(function () {
3114 return ErrorPrototype.toString !== errorToString || String(new NativeDOMException(1, 2)) !== '2: 1';
3115 });
3116
3117 // Deno 1.6.3- DOMException.prototype.code just missed
3118 var INCORRECT_CODE = INCORRECT_CONSTRUCTOR || fails(function () {
3119 return new NativeDOMException(1, 'DataCloneError').code !== 25;
3120 });
3121
3122 // Deno 1.6.3- DOMException constants just missed
3123 var MISSED_CONSTANTS = INCORRECT_CONSTRUCTOR
3124 || NativeDOMException[DATA_CLONE_ERR] !== 25
3125 || NativeDOMExceptionPrototype[DATA_CLONE_ERR] !== 25;
3126
3127 var FORCED_CONSTRUCTOR = IS_PURE ? INCORRECT_TO_STRING || INCORRECT_CODE || MISSED_CONSTANTS : INCORRECT_CONSTRUCTOR;
3128
3129 // `DOMException` constructor
3130 // https://webidl.spec.whatwg.org/#idl-DOMException
3131 $({ global: true, constructor: true, forced: FORCED_CONSTRUCTOR }, {
3132 DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException
3133 });
3134
3135 var PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION);
3136 var PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype;
3137
3138 if (INCORRECT_TO_STRING && (IS_PURE || NativeDOMException === PolyfilledDOMException)) {
3139 defineBuiltIn(PolyfilledDOMExceptionPrototype, 'toString', errorToString);
3140 }
3141
3142 if (INCORRECT_CODE && DESCRIPTORS && NativeDOMException === PolyfilledDOMException) {
3143 defineBuiltInAccessor(PolyfilledDOMExceptionPrototype, 'code', createGetterDescriptor(function () {
3144 return codeFor(anObject(this).name);
3145 }));
3146 }
3147
3148 // `DOMException` constants
3149 for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) {
3150 var constant = DOMExceptionConstants[key];
3151 var constantName = constant.s;
3152 var descriptor = createPropertyDescriptor(6, constant.c);
3153 if (!hasOwn(PolyfilledDOMException, constantName)) {
3154 defineProperty(PolyfilledDOMException, constantName, descriptor);
3155 }
3156 if (!hasOwn(PolyfilledDOMExceptionPrototype, constantName)) {
3157 defineProperty(PolyfilledDOMExceptionPrototype, constantName, descriptor);
3158 }
3159 }
3160 return web_domException_constructor;
3161 }
3162
3163 requireWeb_domException_constructor();
3164
3165 var web_domException_stack = {};
3166
3167 var hasRequiredWeb_domException_stack;
3168
3169 function requireWeb_domException_stack () {
3170 if (hasRequiredWeb_domException_stack) return web_domException_stack;
3171 hasRequiredWeb_domException_stack = 1;
3172 var $ = require_export();
3173 var globalThis = requireGlobalThis();
3174 var getBuiltIn = requireGetBuiltIn();
3175 var createPropertyDescriptor = requireCreatePropertyDescriptor();
3176 var defineProperty = requireObjectDefineProperty().f;
3177 var hasOwn = requireHasOwnProperty();
3178 var anInstance = requireAnInstance();
3179 var inheritIfRequired = requireInheritIfRequired();
3180 var normalizeStringArgument = requireNormalizeStringArgument();
3181 var DOMExceptionConstants = requireDomExceptionConstants();
3182 var clearErrorStack = requireErrorStackClear();
3183 var DESCRIPTORS = requireDescriptors();
3184 var IS_PURE = requireIsPure();
3185
3186 var DOM_EXCEPTION = 'DOMException';
3187 var Error = getBuiltIn('Error');
3188 var NativeDOMException = getBuiltIn(DOM_EXCEPTION);
3189
3190 var $DOMException = function DOMException() {
3191 anInstance(this, DOMExceptionPrototype);
3192 var argumentsLength = arguments.length;
3193 var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]);
3194 var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], 'Error');
3195 var that = new NativeDOMException(message, name);
3196 var error = new Error(message);
3197 error.name = DOM_EXCEPTION;
3198 defineProperty(that, 'stack', createPropertyDescriptor(1, clearErrorStack(error.stack, 1)));
3199 inheritIfRequired(that, this, $DOMException);
3200 return that;
3201 };
3202
3203 var DOMExceptionPrototype = $DOMException.prototype = NativeDOMException.prototype;
3204
3205 var ERROR_HAS_STACK = 'stack' in new Error(DOM_EXCEPTION);
3206 var DOM_EXCEPTION_HAS_STACK = 'stack' in new NativeDOMException(1, 2);
3207
3208 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
3209 var descriptor = NativeDOMException && DESCRIPTORS && Object.getOwnPropertyDescriptor(globalThis, DOM_EXCEPTION);
3210
3211 // Bun ~ 0.1.1 DOMException have incorrect descriptor and we can't redefine it
3212 // https://github.com/Jarred-Sumner/bun/issues/399
3213 var BUGGY_DESCRIPTOR = !!descriptor && !(descriptor.writable && descriptor.configurable);
3214
3215 var FORCED_CONSTRUCTOR = ERROR_HAS_STACK && !BUGGY_DESCRIPTOR && !DOM_EXCEPTION_HAS_STACK;
3216
3217 // `DOMException` constructor patch for `.stack` where it's required
3218 // https://webidl.spec.whatwg.org/#es-DOMException-specialness
3219 $({ global: true, constructor: true, forced: IS_PURE || FORCED_CONSTRUCTOR }, { // TODO: fix export logic
3220 DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException
3221 });
3222
3223 var PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION);
3224 var PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype;
3225
3226 if (PolyfilledDOMExceptionPrototype.constructor !== PolyfilledDOMException) {
3227 if (!IS_PURE) {
3228 defineProperty(PolyfilledDOMExceptionPrototype, 'constructor', createPropertyDescriptor(1, PolyfilledDOMException));
3229 }
3230
3231 for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) {
3232 var constant = DOMExceptionConstants[key];
3233 var constantName = constant.s;
3234 if (!hasOwn(PolyfilledDOMException, constantName)) {
3235 defineProperty(PolyfilledDOMException, constantName, createPropertyDescriptor(6, constant.c));
3236 }
3237 }
3238 }
3239 return web_domException_stack;
3240 }
3241
3242 requireWeb_domException_stack();
3243
3244 var web_domException_toStringTag = {};
3245
3246 var setToStringTag;
3247 var hasRequiredSetToStringTag;
3248
3249 function requireSetToStringTag () {
3250 if (hasRequiredSetToStringTag) return setToStringTag;
3251 hasRequiredSetToStringTag = 1;
3252 var defineProperty = requireObjectDefineProperty().f;
3253 var hasOwn = requireHasOwnProperty();
3254 var wellKnownSymbol = requireWellKnownSymbol();
3255
3256 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
3257
3258 setToStringTag = function (target, TAG, STATIC) {
3259 if (target && !STATIC) target = target.prototype;
3260 if (target && !hasOwn(target, TO_STRING_TAG)) {
3261 defineProperty(target, TO_STRING_TAG, { configurable: true, value: TAG });
3262 }
3263 };
3264 return setToStringTag;
3265 }
3266
3267 var hasRequiredWeb_domException_toStringTag;
3268
3269 function requireWeb_domException_toStringTag () {
3270 if (hasRequiredWeb_domException_toStringTag) return web_domException_toStringTag;
3271 hasRequiredWeb_domException_toStringTag = 1;
3272 var getBuiltIn = requireGetBuiltIn();
3273 var setToStringTag = requireSetToStringTag();
3274
3275 var DOM_EXCEPTION = 'DOMException';
3276
3277 // `DOMException.prototype[@@toStringTag]` property
3278 setToStringTag(getBuiltIn(DOM_EXCEPTION), DOM_EXCEPTION);
3279 return web_domException_toStringTag;
3280 }
3281
3282 requireWeb_domException_toStringTag();
3283
3284 var web_structuredClone = {};
3285
3286 var isConstructor;
3287 var hasRequiredIsConstructor;
3288
3289 function requireIsConstructor () {
3290 if (hasRequiredIsConstructor) return isConstructor;
3291 hasRequiredIsConstructor = 1;
3292 var uncurryThis = requireFunctionUncurryThis();
3293 var fails = requireFails();
3294 var isCallable = requireIsCallable();
3295 var classof = requireClassof();
3296 var getBuiltIn = requireGetBuiltIn();
3297 var inspectSource = requireInspectSource();
3298
3299 var noop = function () { /* empty */ };
3300 var construct = getBuiltIn('Reflect', 'construct');
3301 var constructorRegExp = /^\s*(?:class|function)\b/;
3302 var exec = uncurryThis(constructorRegExp.exec);
3303 var INCORRECT_TO_STRING = !constructorRegExp.test(noop);
3304
3305 var isConstructorModern = function isConstructor(argument) {
3306 if (!isCallable(argument)) return false;
3307 try {
3308 construct(noop, [], argument);
3309 return true;
3310 } catch (error) {
3311 return false;
3312 }
3313 };
3314
3315 var isConstructorLegacy = function isConstructor(argument) {
3316 if (!isCallable(argument)) return false;
3317 switch (classof(argument)) {
3318 case 'AsyncFunction':
3319 case 'GeneratorFunction':
3320 case 'AsyncGeneratorFunction': return false;
3321 }
3322 try {
3323 // we can't check .prototype since constructors produced by .bind haven't it
3324 // `Function#toString` throws on some built-it function in some legacy engines
3325 // (for example, `DOMQuad` and similar in FF41-)
3326 return INCORRECT_TO_STRING || !!exec(constructorRegExp, inspectSource(argument));
3327 } catch (error) {
3328 return true;
3329 }
3330 };
3331
3332 isConstructorLegacy.sham = true;
3333
3334 // `IsConstructor` abstract operation
3335 // https://tc39.es/ecma262/#sec-isconstructor
3336 isConstructor = !construct || fails(function () {
3337 var called;
3338 return isConstructorModern(isConstructorModern.call)
3339 || !isConstructorModern(Object)
3340 || !isConstructorModern(function () { called = true; })
3341 || called;
3342 }) ? isConstructorLegacy : isConstructorModern;
3343 return isConstructor;
3344 }
3345
3346 var validateArgumentsLength;
3347 var hasRequiredValidateArgumentsLength;
3348
3349 function requireValidateArgumentsLength () {
3350 if (hasRequiredValidateArgumentsLength) return validateArgumentsLength;
3351 hasRequiredValidateArgumentsLength = 1;
3352 var $TypeError = TypeError;
3353
3354 validateArgumentsLength = function (passed, required) {
3355 if (passed < required) throw new $TypeError('Not enough arguments');
3356 return passed;
3357 };
3358 return validateArgumentsLength;
3359 }
3360
3361 var regexpFlags;
3362 var hasRequiredRegexpFlags;
3363
3364 function requireRegexpFlags () {
3365 if (hasRequiredRegexpFlags) return regexpFlags;
3366 hasRequiredRegexpFlags = 1;
3367 var anObject = requireAnObject();
3368
3369 // `RegExp.prototype.flags` getter implementation
3370 // https://tc39.es/ecma262/#sec-get-regexp.prototype.flags
3371 regexpFlags = function () {
3372 var that = anObject(this);
3373 var result = '';
3374 if (that.hasIndices) result += 'd';
3375 if (that.global) result += 'g';
3376 if (that.ignoreCase) result += 'i';
3377 if (that.multiline) result += 'm';
3378 if (that.dotAll) result += 's';
3379 if (that.unicode) result += 'u';
3380 if (that.unicodeSets) result += 'v';
3381 if (that.sticky) result += 'y';
3382 return result;
3383 };
3384 return regexpFlags;
3385 }
3386
3387 var regexpGetFlags;
3388 var hasRequiredRegexpGetFlags;
3389
3390 function requireRegexpGetFlags () {
3391 if (hasRequiredRegexpGetFlags) return regexpGetFlags;
3392 hasRequiredRegexpGetFlags = 1;
3393 var call = requireFunctionCall();
3394 var hasOwn = requireHasOwnProperty();
3395 var isPrototypeOf = requireObjectIsPrototypeOf();
3396 var regExpFlags = requireRegexpFlags();
3397
3398 var RegExpPrototype = RegExp.prototype;
3399
3400 regexpGetFlags = function (R) {
3401 var flags = R.flags;
3402 return flags === undefined && !('flags' in RegExpPrototype) && !hasOwn(R, 'flags') && isPrototypeOf(RegExpPrototype, R)
3403 ? call(regExpFlags, R) : flags;
3404 };
3405 return regexpGetFlags;
3406 }
3407
3408 var mapHelpers;
3409 var hasRequiredMapHelpers;
3410
3411 function requireMapHelpers () {
3412 if (hasRequiredMapHelpers) return mapHelpers;
3413 hasRequiredMapHelpers = 1;
3414 var uncurryThis = requireFunctionUncurryThis();
3415
3416 // eslint-disable-next-line es/no-map -- safe
3417 var MapPrototype = Map.prototype;
3418
3419 mapHelpers = {
3420 // eslint-disable-next-line es/no-map -- safe
3421 Map: Map,
3422 set: uncurryThis(MapPrototype.set),
3423 get: uncurryThis(MapPrototype.get),
3424 has: uncurryThis(MapPrototype.has),
3425 remove: uncurryThis(MapPrototype['delete']),
3426 proto: MapPrototype
3427 };
3428 return mapHelpers;
3429 }
3430
3431 var setHelpers;
3432 var hasRequiredSetHelpers;
3433
3434 function requireSetHelpers () {
3435 if (hasRequiredSetHelpers) return setHelpers;
3436 hasRequiredSetHelpers = 1;
3437 var uncurryThis = requireFunctionUncurryThis();
3438
3439 // eslint-disable-next-line es/no-set -- safe
3440 var SetPrototype = Set.prototype;
3441
3442 setHelpers = {
3443 // eslint-disable-next-line es/no-set -- safe
3444 Set: Set,
3445 add: uncurryThis(SetPrototype.add),
3446 has: uncurryThis(SetPrototype.has),
3447 remove: uncurryThis(SetPrototype['delete']),
3448 proto: SetPrototype
3449 };
3450 return setHelpers;
3451 }
3452
3453 var iterateSimple;
3454 var hasRequiredIterateSimple;
3455
3456 function requireIterateSimple () {
3457 if (hasRequiredIterateSimple) return iterateSimple;
3458 hasRequiredIterateSimple = 1;
3459 var call = requireFunctionCall();
3460
3461 iterateSimple = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) {
3462 var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator;
3463 var next = record.next;
3464 var step, result;
3465 while (!(step = call(next, iterator)).done) {
3466 result = fn(step.value);
3467 if (result !== undefined) return result;
3468 }
3469 };
3470 return iterateSimple;
3471 }
3472
3473 var setIterate;
3474 var hasRequiredSetIterate;
3475
3476 function requireSetIterate () {
3477 if (hasRequiredSetIterate) return setIterate;
3478 hasRequiredSetIterate = 1;
3479 var uncurryThis = requireFunctionUncurryThis();
3480 var iterateSimple = requireIterateSimple();
3481 var SetHelpers = requireSetHelpers();
3482
3483 var Set = SetHelpers.Set;
3484 var SetPrototype = SetHelpers.proto;
3485 var forEach = uncurryThis(SetPrototype.forEach);
3486 var keys = uncurryThis(SetPrototype.keys);
3487 var next = keys(new Set()).next;
3488
3489 setIterate = function (set, fn, interruptible) {
3490 return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn);
3491 };
3492 return setIterate;
3493 }
3494
3495 var structuredCloneProperTransfer;
3496 var hasRequiredStructuredCloneProperTransfer;
3497
3498 function requireStructuredCloneProperTransfer () {
3499 if (hasRequiredStructuredCloneProperTransfer) return structuredCloneProperTransfer;
3500 hasRequiredStructuredCloneProperTransfer = 1;
3501 var globalThis = requireGlobalThis();
3502 var fails = requireFails();
3503 var V8 = requireEnvironmentV8Version();
3504 var ENVIRONMENT = requireEnvironment();
3505
3506 var structuredClone = globalThis.structuredClone;
3507
3508 structuredCloneProperTransfer = !!structuredClone && !fails(function () {
3509 // prevent V8 ArrayBufferDetaching protector cell invalidation and performance degradation
3510 // https://github.com/zloirock/core-js/issues/679
3511 if ((ENVIRONMENT === 'DENO' && V8 > 92) || (ENVIRONMENT === 'NODE' && V8 > 94) || (ENVIRONMENT === 'BROWSER' && V8 > 97)) return false;
3512 var buffer = new ArrayBuffer(8);
3513 var clone = structuredClone(buffer, { transfer: [buffer] });
3514 return buffer.byteLength !== 0 || clone.byteLength !== 8;
3515 });
3516 return structuredCloneProperTransfer;
3517 }
3518
3519 var detachTransferable;
3520 var hasRequiredDetachTransferable;
3521
3522 function requireDetachTransferable () {
3523 if (hasRequiredDetachTransferable) return detachTransferable;
3524 hasRequiredDetachTransferable = 1;
3525 var globalThis = requireGlobalThis();
3526 var getBuiltInNodeModule = requireGetBuiltInNodeModule();
3527 var PROPER_STRUCTURED_CLONE_TRANSFER = requireStructuredCloneProperTransfer();
3528
3529 var structuredClone = globalThis.structuredClone;
3530 var $ArrayBuffer = globalThis.ArrayBuffer;
3531 var $MessageChannel = globalThis.MessageChannel;
3532 var detach = false;
3533 var WorkerThreads, channel, buffer, $detach;
3534
3535 if (PROPER_STRUCTURED_CLONE_TRANSFER) {
3536 detach = function (transferable) {
3537 structuredClone(transferable, { transfer: [transferable] });
3538 };
3539 } else if ($ArrayBuffer) try {
3540 if (!$MessageChannel) {
3541 WorkerThreads = getBuiltInNodeModule('worker_threads');
3542 if (WorkerThreads) $MessageChannel = WorkerThreads.MessageChannel;
3543 }
3544
3545 if ($MessageChannel) {
3546 channel = new $MessageChannel();
3547 buffer = new $ArrayBuffer(2);
3548
3549 $detach = function (transferable) {
3550 channel.port1.postMessage(null, [transferable]);
3551 };
3552
3553 if (buffer.byteLength === 2) {
3554 $detach(buffer);
3555 if (buffer.byteLength === 0) detach = $detach;
3556 }
3557 }
3558 } catch (error) { /* empty */ }
3559
3560 detachTransferable = detach;
3561 return detachTransferable;
3562 }
3563
3564 var hasRequiredWeb_structuredClone;
3565
3566 function requireWeb_structuredClone () {
3567 if (hasRequiredWeb_structuredClone) return web_structuredClone;
3568 hasRequiredWeb_structuredClone = 1;
3569 var IS_PURE = requireIsPure();
3570 var $ = require_export();
3571 var globalThis = requireGlobalThis();
3572 var getBuiltIn = requireGetBuiltIn();
3573 var uncurryThis = requireFunctionUncurryThis();
3574 var fails = requireFails();
3575 var uid = requireUid();
3576 var isCallable = requireIsCallable();
3577 var isConstructor = requireIsConstructor();
3578 var isNullOrUndefined = requireIsNullOrUndefined();
3579 var isObject = requireIsObject();
3580 var isSymbol = requireIsSymbol();
3581 var iterate = requireIterate();
3582 var anObject = requireAnObject();
3583 var classof = requireClassof();
3584 var hasOwn = requireHasOwnProperty();
3585 var createProperty = requireCreateProperty();
3586 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
3587 var lengthOfArrayLike = requireLengthOfArrayLike();
3588 var validateArgumentsLength = requireValidateArgumentsLength();
3589 var getRegExpFlags = requireRegexpGetFlags();
3590 var MapHelpers = requireMapHelpers();
3591 var SetHelpers = requireSetHelpers();
3592 var setIterate = requireSetIterate();
3593 var detachTransferable = requireDetachTransferable();
3594 var ERROR_STACK_INSTALLABLE = requireErrorStackInstallable();
3595 var PROPER_STRUCTURED_CLONE_TRANSFER = requireStructuredCloneProperTransfer();
3596
3597 var Object = globalThis.Object;
3598 var Array = globalThis.Array;
3599 var Date = globalThis.Date;
3600 var Error = globalThis.Error;
3601 var TypeError = globalThis.TypeError;
3602 var PerformanceMark = globalThis.PerformanceMark;
3603 var DOMException = getBuiltIn('DOMException');
3604 var Map = MapHelpers.Map;
3605 var mapHas = MapHelpers.has;
3606 var mapGet = MapHelpers.get;
3607 var mapSet = MapHelpers.set;
3608 var Set = SetHelpers.Set;
3609 var setAdd = SetHelpers.add;
3610 var setHas = SetHelpers.has;
3611 var objectKeys = getBuiltIn('Object', 'keys');
3612 var push = uncurryThis([].push);
3613 var thisBooleanValue = uncurryThis(true.valueOf);
3614 var thisNumberValue = uncurryThis(1.0.valueOf);
3615 var thisStringValue = uncurryThis(''.valueOf);
3616 var thisTimeValue = uncurryThis(Date.prototype.getTime);
3617 var PERFORMANCE_MARK = uid('structuredClone');
3618 var DATA_CLONE_ERROR = 'DataCloneError';
3619 var TRANSFERRING = 'Transferring';
3620
3621 var checkBasicSemantic = function (structuredCloneImplementation) {
3622 return !fails(function () {
3623 var set1 = new globalThis.Set([7]);
3624 var set2 = structuredCloneImplementation(set1);
3625 var number = structuredCloneImplementation(Object(7));
3626 return set2 === set1 || !set2.has(7) || !isObject(number) || +number !== 7;
3627 }) && structuredCloneImplementation;
3628 };
3629
3630 var checkErrorsCloning = function (structuredCloneImplementation, $Error) {
3631 return !fails(function () {
3632 var error = new $Error();
3633 var test = structuredCloneImplementation({ a: error, b: error });
3634 return !(test && test.a === test.b && test.a instanceof $Error && test.a.stack === error.stack);
3635 });
3636 };
3637
3638 // https://github.com/whatwg/html/pull/5749
3639 var checkNewErrorsCloningSemantic = function (structuredCloneImplementation) {
3640 return !fails(function () {
3641 var test = structuredCloneImplementation(new globalThis.AggregateError([1], PERFORMANCE_MARK, { cause: 3 }));
3642 return test.name !== 'AggregateError' || test.errors[0] !== 1 || test.message !== PERFORMANCE_MARK || test.cause !== 3;
3643 });
3644 };
3645
3646 // FF94+, Safari 15.4+, Chrome 98+, NodeJS 17.0+, Deno 1.13+
3647 // FF<103 and Safari implementations can't clone errors
3648 // https://bugzilla.mozilla.org/show_bug.cgi?id=1556604
3649 // FF103 can clone errors, but `.stack` of clone is an empty string
3650 // https://bugzilla.mozilla.org/show_bug.cgi?id=1778762
3651 // FF104+ fixed it on usual errors, but not on DOMExceptions
3652 // https://bugzilla.mozilla.org/show_bug.cgi?id=1777321
3653 // Chrome <102 returns `null` if cloned object contains multiple references to one error
3654 // https://bugs.chromium.org/p/v8/issues/detail?id=12542
3655 // NodeJS implementation can't clone DOMExceptions
3656 // https://github.com/nodejs/node/issues/41038
3657 // only FF103+ supports new (html/5749) error cloning semantic
3658 var nativeStructuredClone = globalThis.structuredClone;
3659
3660 var FORCED_REPLACEMENT = IS_PURE
3661 || !checkErrorsCloning(nativeStructuredClone, Error)
3662 || !checkErrorsCloning(nativeStructuredClone, DOMException)
3663 || !checkNewErrorsCloningSemantic(nativeStructuredClone);
3664
3665 // Chrome 82+, Safari 14.1+, Deno 1.11+
3666 // Chrome 78-81 implementation swaps `.name` and `.message` of cloned `DOMException`
3667 // Chrome returns `null` if cloned object contains multiple references to one error
3668 // Safari 14.1 implementation doesn't clone some `RegExp` flags, so requires a workaround
3669 // Safari implementation can't clone errors
3670 // Deno 1.2-1.10 implementations too naive
3671 // NodeJS 16.0+ does not have `PerformanceMark` constructor
3672 // NodeJS <17.2 structured cloning implementation from `performance.mark` is too naive
3673 // and can't clone, for example, `RegExp` or some boxed primitives
3674 // https://github.com/nodejs/node/issues/40840
3675 // no one of those implementations supports new (html/5749) error cloning semantic
3676 var structuredCloneFromMark = !nativeStructuredClone && checkBasicSemantic(function (value) {
3677 return new PerformanceMark(PERFORMANCE_MARK, { detail: value }).detail;
3678 });
3679
3680 var nativeRestrictedStructuredClone = checkBasicSemantic(nativeStructuredClone) || structuredCloneFromMark;
3681
3682 var throwUncloneable = function (type) {
3683 throw new DOMException('Uncloneable type: ' + type, DATA_CLONE_ERROR);
3684 };
3685
3686 var throwUnpolyfillable = function (type, action) {
3687 throw new DOMException((action || 'Cloning') + ' of ' + type + ' cannot be properly polyfilled in this engine', DATA_CLONE_ERROR);
3688 };
3689
3690 var tryNativeRestrictedStructuredClone = function (value, type) {
3691 if (!nativeRestrictedStructuredClone) throwUnpolyfillable(type);
3692 return nativeRestrictedStructuredClone(value);
3693 };
3694
3695 var createDataTransfer = function () {
3696 var dataTransfer;
3697 try {
3698 dataTransfer = new globalThis.DataTransfer();
3699 } catch (error) {
3700 try {
3701 dataTransfer = new globalThis.ClipboardEvent('').clipboardData;
3702 } catch (error2) { /* empty */ }
3703 }
3704 return dataTransfer && dataTransfer.items && dataTransfer.files ? dataTransfer : null;
3705 };
3706
3707 var cloneBuffer = function (value, map, $type) {
3708 if (mapHas(map, value)) return mapGet(map, value);
3709
3710 var type = $type || classof(value);
3711 var clone, length, options, source, target, i;
3712
3713 if (type === 'SharedArrayBuffer') {
3714 if (nativeRestrictedStructuredClone) clone = nativeRestrictedStructuredClone(value);
3715 // SharedArrayBuffer should use shared memory, we can't polyfill it, so return the original
3716 else clone = value;
3717 } else {
3718 var DataView = globalThis.DataView;
3719
3720 // `ArrayBuffer#slice` is not available in IE10
3721 // `ArrayBuffer#slice` and `DataView` are not available in old FF
3722 if (!DataView && !isCallable(value.slice)) throwUnpolyfillable('ArrayBuffer');
3723 // detached buffers throws in `DataView` and `.slice`
3724 try {
3725 if (isCallable(value.slice) && !value.resizable) {
3726 clone = value.slice(0);
3727 } else {
3728 length = value.byteLength;
3729 options = 'maxByteLength' in value ? { maxByteLength: value.maxByteLength } : undefined;
3730 // eslint-disable-next-line es/no-resizable-and-growable-arraybuffers -- safe
3731 clone = new ArrayBuffer(length, options);
3732 source = new DataView(value);
3733 target = new DataView(clone);
3734 for (i = 0; i < length; i++) {
3735 target.setUint8(i, source.getUint8(i));
3736 }
3737 }
3738 } catch (error) {
3739 throw new DOMException('ArrayBuffer is detached', DATA_CLONE_ERROR);
3740 }
3741 }
3742
3743 mapSet(map, value, clone);
3744
3745 return clone;
3746 };
3747
3748 var cloneView = function (value, type, offset, length, map) {
3749 var C = globalThis[type];
3750 // in some old engines like Safari 9, typeof C is 'object'
3751 // on Uint8ClampedArray or some other constructors
3752 if (!isObject(C)) throwUnpolyfillable(type);
3753 return new C(cloneBuffer(value.buffer, map), offset, length);
3754 };
3755
3756 var structuredCloneInternal = function (value, map) {
3757 if (isSymbol(value)) throwUncloneable('Symbol');
3758 if (!isObject(value)) return value;
3759 // effectively preserves circular references
3760 if (map) {
3761 if (mapHas(map, value)) return mapGet(map, value);
3762 } else map = new Map();
3763
3764 var type = classof(value);
3765 var C, name, cloned, dataTransfer, i, length, keys, key;
3766
3767 switch (type) {
3768 case 'Array':
3769 cloned = Array(lengthOfArrayLike(value));
3770 break;
3771 case 'Object':
3772 cloned = {};
3773 break;
3774 case 'Map':
3775 cloned = new Map();
3776 break;
3777 case 'Set':
3778 cloned = new Set();
3779 break;
3780 case 'RegExp':
3781 // in this block because of a Safari 14.1 bug
3782 // old FF does not clone regexes passed to the constructor, so get the source and flags directly
3783 cloned = new RegExp(value.source, getRegExpFlags(value));
3784 break;
3785 case 'Error':
3786 name = value.name;
3787 switch (name) {
3788 case 'AggregateError':
3789 cloned = new (getBuiltIn(name))([]);
3790 break;
3791 case 'EvalError':
3792 case 'RangeError':
3793 case 'ReferenceError':
3794 case 'SuppressedError':
3795 case 'SyntaxError':
3796 case 'TypeError':
3797 case 'URIError':
3798 cloned = new (getBuiltIn(name))();
3799 break;
3800 case 'CompileError':
3801 case 'LinkError':
3802 case 'RuntimeError':
3803 cloned = new (getBuiltIn('WebAssembly', name))();
3804 break;
3805 default:
3806 cloned = new Error();
3807 }
3808 break;
3809 case 'DOMException':
3810 cloned = new DOMException(value.message, value.name);
3811 break;
3812 case 'ArrayBuffer':
3813 case 'SharedArrayBuffer':
3814 cloned = cloneBuffer(value, map, type);
3815 break;
3816 case 'DataView':
3817 case 'Int8Array':
3818 case 'Uint8Array':
3819 case 'Uint8ClampedArray':
3820 case 'Int16Array':
3821 case 'Uint16Array':
3822 case 'Int32Array':
3823 case 'Uint32Array':
3824 case 'Float16Array':
3825 case 'Float32Array':
3826 case 'Float64Array':
3827 case 'BigInt64Array':
3828 case 'BigUint64Array':
3829 length = type === 'DataView' ? value.byteLength : value.length;
3830 cloned = cloneView(value, type, value.byteOffset, length, map);
3831 break;
3832 case 'DOMQuad':
3833 try {
3834 cloned = new DOMQuad(
3835 structuredCloneInternal(value.p1, map),
3836 structuredCloneInternal(value.p2, map),
3837 structuredCloneInternal(value.p3, map),
3838 structuredCloneInternal(value.p4, map)
3839 );
3840 } catch (error) {
3841 cloned = tryNativeRestrictedStructuredClone(value, type);
3842 }
3843 break;
3844 case 'File':
3845 if (nativeRestrictedStructuredClone) try {
3846 cloned = nativeRestrictedStructuredClone(value);
3847 // NodeJS 20.0.0 bug, https://github.com/nodejs/node/issues/47612
3848 if (classof(cloned) !== type) cloned = undefined;
3849 } catch (error) { /* empty */ }
3850 if (!cloned) try {
3851 cloned = new File([value], value.name, value);
3852 } catch (error) { /* empty */ }
3853 if (!cloned) throwUnpolyfillable(type);
3854 break;
3855 case 'FileList':
3856 dataTransfer = createDataTransfer();
3857 if (dataTransfer) {
3858 for (i = 0, length = lengthOfArrayLike(value); i < length; i++) {
3859 dataTransfer.items.add(structuredCloneInternal(value[i], map));
3860 }
3861 cloned = dataTransfer.files;
3862 } else cloned = tryNativeRestrictedStructuredClone(value, type);
3863 break;
3864 case 'ImageData':
3865 // Safari 9 ImageData is a constructor, but typeof ImageData is 'object'
3866 try {
3867 cloned = new ImageData(
3868 structuredCloneInternal(value.data, map),
3869 value.width,
3870 value.height,
3871 { colorSpace: value.colorSpace }
3872 );
3873 } catch (error) {
3874 cloned = tryNativeRestrictedStructuredClone(value, type);
3875 } break;
3876 default:
3877 if (nativeRestrictedStructuredClone) {
3878 cloned = nativeRestrictedStructuredClone(value);
3879 } else switch (type) {
3880 case 'BigInt':
3881 // can be a 3rd party polyfill
3882 cloned = Object(value.valueOf());
3883 break;
3884 case 'Boolean':
3885 cloned = Object(thisBooleanValue(value));
3886 break;
3887 case 'Number':
3888 cloned = Object(thisNumberValue(value));
3889 break;
3890 case 'String':
3891 cloned = Object(thisStringValue(value));
3892 break;
3893 case 'Date':
3894 cloned = new Date(thisTimeValue(value));
3895 break;
3896 case 'Blob':
3897 try {
3898 cloned = value.slice(0, value.size, value.type);
3899 } catch (error) {
3900 throwUnpolyfillable(type);
3901 } break;
3902 case 'DOMPoint':
3903 case 'DOMPointReadOnly':
3904 C = globalThis[type];
3905 try {
3906 cloned = C.fromPoint
3907 ? C.fromPoint(value)
3908 : new C(value.x, value.y, value.z, value.w);
3909 } catch (error) {
3910 throwUnpolyfillable(type);
3911 } break;
3912 case 'DOMRect':
3913 case 'DOMRectReadOnly':
3914 C = globalThis[type];
3915 try {
3916 cloned = C.fromRect
3917 ? C.fromRect(value)
3918 : new C(value.x, value.y, value.width, value.height);
3919 } catch (error) {
3920 throwUnpolyfillable(type);
3921 } break;
3922 case 'DOMMatrix':
3923 case 'DOMMatrixReadOnly':
3924 C = globalThis[type];
3925 try {
3926 cloned = C.fromMatrix
3927 ? C.fromMatrix(value)
3928 : new C(value);
3929 } catch (error) {
3930 throwUnpolyfillable(type);
3931 } break;
3932 case 'AudioData':
3933 case 'VideoFrame':
3934 if (!isCallable(value.clone)) throwUnpolyfillable(type);
3935 try {
3936 cloned = value.clone();
3937 } catch (error) {
3938 throwUncloneable(type);
3939 } break;
3940 case 'CropTarget':
3941 case 'CryptoKey':
3942 case 'FileSystemDirectoryHandle':
3943 case 'FileSystemFileHandle':
3944 case 'FileSystemHandle':
3945 case 'GPUCompilationInfo':
3946 case 'GPUCompilationMessage':
3947 case 'ImageBitmap':
3948 case 'RTCCertificate':
3949 case 'WebAssembly.Module':
3950 throwUnpolyfillable(type);
3951 // break omitted
3952 default:
3953 throwUncloneable(type);
3954 }
3955 }
3956
3957 mapSet(map, value, cloned);
3958
3959 switch (type) {
3960 case 'Array':
3961 case 'Object':
3962 keys = objectKeys(value);
3963 for (i = 0, length = lengthOfArrayLike(keys); i < length; i++) {
3964 key = keys[i];
3965 createProperty(cloned, key, structuredCloneInternal(value[key], map));
3966 } break;
3967 case 'Map':
3968 value.forEach(function (v, k) {
3969 mapSet(cloned, structuredCloneInternal(k, map), structuredCloneInternal(v, map));
3970 });
3971 break;
3972 case 'Set':
3973 value.forEach(function (v) {
3974 setAdd(cloned, structuredCloneInternal(v, map));
3975 });
3976 break;
3977 case 'Error':
3978 createNonEnumerableProperty(cloned, 'message', structuredCloneInternal(value.message, map));
3979 if (hasOwn(value, 'cause')) {
3980 createNonEnumerableProperty(cloned, 'cause', structuredCloneInternal(value.cause, map));
3981 }
3982 if (name === 'AggregateError') {
3983 cloned.errors = structuredCloneInternal(value.errors, map);
3984 } else if (name === 'SuppressedError') {
3985 cloned.error = structuredCloneInternal(value.error, map);
3986 cloned.suppressed = structuredCloneInternal(value.suppressed, map);
3987 } // break omitted
3988 case 'DOMException':
3989 if (ERROR_STACK_INSTALLABLE) {
3990 createNonEnumerableProperty(cloned, 'stack', structuredCloneInternal(value.stack, map));
3991 }
3992 }
3993
3994 return cloned;
3995 };
3996
3997 var tryToTransfer = function (rawTransfer, map) {
3998 if (!isObject(rawTransfer)) throw new TypeError('Transfer option cannot be converted to a sequence');
3999
4000 var transfer = [];
4001
4002 iterate(rawTransfer, function (value) {
4003 push(transfer, anObject(value));
4004 });
4005
4006 var i = 0;
4007 var length = lengthOfArrayLike(transfer);
4008 var buffers = new Set();
4009 var value, type, C, transferred, canvas, context;
4010
4011 while (i < length) {
4012 value = transfer[i++];
4013
4014 type = classof(value);
4015
4016 if (type === 'ArrayBuffer' ? setHas(buffers, value) : mapHas(map, value)) {
4017 throw new DOMException('Duplicate transferable', DATA_CLONE_ERROR);
4018 }
4019
4020 if (type === 'ArrayBuffer') {
4021 setAdd(buffers, value);
4022 continue;
4023 }
4024
4025 if (PROPER_STRUCTURED_CLONE_TRANSFER) {
4026 transferred = nativeStructuredClone(value, { transfer: [value] });
4027 } else switch (type) {
4028 case 'ImageBitmap':
4029 C = globalThis.OffscreenCanvas;
4030 if (!isConstructor(C)) throwUnpolyfillable(type, TRANSFERRING);
4031 try {
4032 canvas = new C(value.width, value.height);
4033 context = canvas.getContext('bitmaprenderer');
4034 context.transferFromImageBitmap(value);
4035 transferred = canvas.transferToImageBitmap();
4036 } catch (error) { /* empty */ }
4037 break;
4038 case 'AudioData':
4039 case 'VideoFrame':
4040 if (!isCallable(value.clone) || !isCallable(value.close)) throwUnpolyfillable(type, TRANSFERRING);
4041 try {
4042 transferred = value.clone();
4043 value.close();
4044 } catch (error) { /* empty */ }
4045 break;
4046 case 'MediaSourceHandle':
4047 case 'MessagePort':
4048 case 'MIDIAccess':
4049 case 'OffscreenCanvas':
4050 case 'ReadableStream':
4051 case 'RTCDataChannel':
4052 case 'TransformStream':
4053 case 'WebTransportReceiveStream':
4054 case 'WebTransportSendStream':
4055 case 'WritableStream':
4056 throwUnpolyfillable(type, TRANSFERRING);
4057 }
4058
4059 if (transferred === undefined) throw new DOMException('This object cannot be transferred: ' + type, DATA_CLONE_ERROR);
4060
4061 mapSet(map, value, transferred);
4062 }
4063
4064 return buffers;
4065 };
4066
4067 var detachBuffers = function (buffers) {
4068 setIterate(buffers, function (buffer) {
4069 if (PROPER_STRUCTURED_CLONE_TRANSFER) {
4070 nativeRestrictedStructuredClone(buffer, { transfer: [buffer] });
4071 } else if (isCallable(buffer.transfer)) {
4072 buffer.transfer();
4073 } else if (detachTransferable) {
4074 detachTransferable(buffer);
4075 } else {
4076 throwUnpolyfillable('ArrayBuffer', TRANSFERRING);
4077 }
4078 });
4079 };
4080
4081 // `structuredClone` method
4082 // https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
4083 $({ global: true, enumerable: true, sham: !PROPER_STRUCTURED_CLONE_TRANSFER, forced: FORCED_REPLACEMENT }, {
4084 structuredClone: function structuredClone(value /* , { transfer } */) {
4085 var options = validateArgumentsLength(arguments.length, 1) > 1 && !isNullOrUndefined(arguments[1]) ? anObject(arguments[1]) : undefined;
4086 var transfer = options ? options.transfer : undefined;
4087 var map, buffers;
4088
4089 if (transfer !== undefined) {
4090 map = new Map();
4091 buffers = tryToTransfer(transfer, map);
4092 }
4093
4094 var clone = structuredCloneInternal(value, map);
4095
4096 // since of an issue with cloning views of transferred buffers, we a forced to detach them later
4097 // https://github.com/zloirock/core-js/issues/1265
4098 if (buffers) detachBuffers(buffers);
4099
4100 return clone;
4101 }
4102 });
4103 return web_structuredClone;
4104 }
4105
4106 requireWeb_structuredClone();
4107
4108 /** @import { Matrix3x3, Vector3 } from "./types.js" */
4109
4110 /**
4111 * A is m x n. B is n x p. product is m x p.
4112 *
4113 * Array arguments are treated like vectors:
4114 * - A becomes 1 x n
4115 * - B becomes n x 1
4116 *
4117 * Returns Matrix m x p or equivalent array or number
4118 *
4119 * @overload
4120 * @param {number[]} A Vector 1 x n
4121 * @param {number[]} B Vector n x 1
4122 * @returns {number} Scalar number
4123 *
4124 * @overload
4125 * @param {number[][]} A Matrix m x n
4126 * @param {number[]} B Vector n x 1
4127 * @returns {number[]} Array with length m
4128 *
4129 * @overload
4130 * @param {number[]} A Vector 1 x n
4131 * @param {number[][]} B Matrix n x p
4132 * @returns {number[]} Array with length p
4133 *
4134 * @overload
4135 * @param {number[][]} A Matrix m x n
4136 * @param {number[][]} B Matrix n x p
4137 * @returns {number[][]} Matrix m x p
4138 *
4139 * @param {number[] | number[][]} A Matrix m x n or a vector
4140 * @param {number[] | number[][]} B Matrix n x p or a vector
4141 * @returns {number | number[] | number[][]} Matrix m x p or equivalent array or number
4142 */
4143 function multiplyMatrices(A, B) {
4144 let m = A.length;
4145 /** @type {number[][]} */
4146 let AM;
4147 /** @type {number[][]} */
4148 let BM;
4149 let aVec = false;
4150 let bVec = false;
4151 if (!Array.isArray(A[0])) {
4152 // A is vector, convert to [[a, b, c, ...]]
4153 AM = [(/** @type {number[]} */A)];
4154 m = AM.length;
4155 aVec = true;
4156 } else {
4157 AM = /** @type {number[][]} */A;
4158 }
4159 if (!Array.isArray(B[0])) {
4160 // B is vector, convert to [[a], [b], [c], ...]]
4161 BM = B.length > 0 ? B.map(x => [x]) : [[]]; // Avoid mapping empty array
4162 bVec = true;
4163 } else {
4164 BM = /** @type {number[][]} */B;
4165 }
4166 let p = BM[0].length;
4167 let BM_cols = BM[0].map((_, i) => BM.map(x => x[i])); // transpose B
4168 /** @type {number[] | number[][]} */
4169 let product = AM.map(row => BM_cols.map(col => {
4170 let ret = 0;
4171 if (!Array.isArray(row)) {
4172 for (let c of col) {
4173 ret += row * c;
4174 }
4175 return ret;
4176 }
4177 for (let i = 0; i < row.length; i++) {
4178 ret += row[i] * (col[i] || 0);
4179 }
4180 return ret;
4181 }));
4182 if (m === 1 && aVec) {
4183 product = product[0]; // Avoid [[a, b, c, ...]]
4184 }
4185 if (p === 1 && bVec) {
4186 if (m === 1 && aVec) {
4187 return product[0]; // Avoid [[a]], return a number
4188 } else {
4189 return product.map(x => x[0]); // Avoid [[a], [b], [c], ...]]
4190 }
4191 }
4192 return product;
4193 }
4194
4195 // dot3 and transform functions adapted from https://github.com/texel-org/color/blob/9793c7d4d02b51f068e0f3fd37131129a4270396/src/core.js
4196 //
4197 // The MIT License (MIT)
4198 // Copyright (c) 2024 Matt DesLauriers
4199
4200 // Permission is hereby granted, free of charge, to any person obtaining a copy
4201 // of this software and associated documentation files (the "Software"), to deal
4202 // in the Software without restriction, including without limitation the rights
4203 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4204 // copies of the Software, and to permit persons to whom the Software is
4205 // furnished to do so, subject to the following conditions:
4206
4207 // The above copyright notice and this permission notice shall be included in all
4208 // copies or substantial portions of the Software.
4209
4210 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
4211 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4212 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
4213 // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4214 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4215 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
4216 // OR OTHER DEALINGS IN THE SOFTWARE.
4217
4218 /**
4219 * Returns the dot product of two vectors each with a length of 3.
4220 *
4221 * @param {Vector3} a
4222 * @param {Vector3} b
4223 * @returns {number}
4224 */
4225 function dot3(a, b) {
4226 return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
4227 }
4228
4229 /**
4230 * Transforms a vector of length 3 by a 3x3 matrix. Specify the same input and output
4231 * vector to transform in place.
4232 *
4233 * @param {Vector3} input
4234 * @param {Matrix3x3} matrix
4235 * @param {Vector3} [out]
4236 * @returns {Vector3}
4237 */
4238 function multiply_v3_m3x3(input, matrix, out = [0, 0, 0]) {
4239 const x = dot3(input, matrix[0]);
4240 const y = dot3(input, matrix[1]);
4241 const z = dot3(input, matrix[2]);
4242 out[0] = x;
4243 out[1] = y;
4244 out[2] = z;
4245 return out;
4246 }
4247
4248 /**
4249 * Check if a value is a string (including a String object)
4250 * @param {any} str - Value to check
4251 * @returns {str is string}
4252 */
4253 function isString(str) {
4254 return type(str) === "string";
4255 }
4256
4257 /**
4258 * Determine the internal JavaScript [[Class]] of an object.
4259 * @param {any} o - Value to check
4260 * @returns {string}
4261 */
4262 function type(o) {
4263 let str = Object.prototype.toString.call(o);
4264 return (str.match(/^\[object\s+(.*?)\]$/)[1] || "").toLowerCase();
4265 }
4266
4267 /**
4268 * @param {number} n
4269 * @param {{ precision?: number | undefined, unit?: string | undefined }} options
4270 * @returns {string}
4271 */
4272 function serializeNumber(n, {
4273 precision = 16,
4274 unit
4275 }) {
4276 if (isNone(n)) {
4277 return "none";
4278 }
4279 n = +toPrecision(n, precision);
4280 return n + (unit !== null && unit !== void 0 ? unit : "");
4281 }
4282
4283 /**
4284 * Check if a value corresponds to a none argument
4285 * @param {any} n - Value to check
4286 * @returns {n is null}
4287 */
4288 function isNone(n) {
4289 return n === null;
4290 }
4291
4292 /**
4293 * Replace none values with 0
4294 * @param {number | null} n
4295 * @returns {number}
4296 */
4297 function skipNone(n) {
4298 return isNone(n) ? 0 : n;
4299 }
4300
4301 /**
4302 * Round a number to a certain number of significant digits
4303 * @param {number} n - The number to round
4304 * @param {number} precision - Number of significant digits
4305 */
4306 function toPrecision(n, precision) {
4307 if (n === 0) {
4308 return 0;
4309 }
4310 let integer = ~~n;
4311 let digits = 0;
4312 if (integer && precision) {
4313 digits = ~~Math.log10(Math.abs(integer)) + 1;
4314 }
4315 const multiplier = 10.0 ** (precision - digits);
4316 return Math.floor(n * multiplier + 0.5) / multiplier;
4317 }
4318
4319 /**
4320 * Interpolate between two values, either of which may be a `none` value.
4321 * A `none` endpoint is treated as having the other endpoint's value;
4322 * if both are `none`, the result is `none` as well.
4323 * @param {number | null} start
4324 * @param {number | null} end
4325 * @param {number} p
4326 * @returns {number | null}
4327 */
4328 function interpolate(start, end, p) {
4329 if (isNone(start) || isNaN(start)) {
4330 return end;
4331 }
4332 if (isNone(end) || isNaN(end)) {
4333 return start;
4334 }
4335 return start + (end - start) * p;
4336 }
4337
4338 /**
4339 * @param {number} start
4340 * @param {number} end
4341 * @param {number} value
4342 */
4343 function interpolateInv(start, end, value) {
4344 return (value - start) / (end - start);
4345 }
4346
4347 /**
4348 * @param {[number, number]} from
4349 * @param {[number, number]} to
4350 * @param {number} value
4351 */
4352 function mapRange(from, to, value) {
4353 if (!from || !to || from === to || from[0] === to[0] && from[1] === to[1] || isNaN(value) || value === null) {
4354 // Ranges missing or the same
4355 return value;
4356 }
4357 return interpolate(to[0], to[1], interpolateInv(from[0], from[1], value));
4358 }
4359
4360 /**
4361 * Clamp value between the minimum and maximum
4362 * @param {number} min minimum value to return
4363 * @param {number} val the value to return if it is between min and max
4364 * @param {number} max maximum value to return
4365 */
4366 function clamp(min, val, max) {
4367 return Math.max(Math.min(max, val), min);
4368 }
4369
4370 /**
4371 * Copy sign of one value to another.
4372 * @param {number} to - Number to copy sign to
4373 * @param {number} from - Number to copy sign from
4374 */
4375 function copySign(to, from) {
4376 return Math.sign(to) === Math.sign(from) ? to : -to;
4377 }
4378
4379 /**
4380 * Perform pow on a signed number and copy sign to result
4381 * @param {number} base The base number
4382 * @param {number} exp The exponent
4383 */
4384 function spow(base, exp) {
4385 return copySign(Math.abs(base) ** exp, base);
4386 }
4387
4388 /**
4389 * Perform a divide, but return zero if the denominator is zero
4390 * @param {number} n The numerator
4391 * @param {number} d The denominator
4392 */
4393 function zdiv(n, d) {
4394 return d === 0 ? 0 : n / d;
4395 }
4396
4397 /**
4398 * Perform a bisect on a sorted list and locate the insertion point for
4399 * a value in arr to maintain sorted order.
4400 * @param {number[]} arr - array of sorted numbers
4401 * @param {number} value - value to find insertion point for
4402 * @param {number} lo - used to specify a the low end of a subset of the list
4403 * @param {number} hi - used to specify a the high end of a subset of the list
4404 */
4405 function bisectLeft(arr, value, lo = 0, hi = arr.length) {
4406 while (lo < hi) {
4407 const mid = lo + hi >> 1;
4408 if (arr[mid] < value) {
4409 lo = mid + 1;
4410 } else {
4411 hi = mid;
4412 }
4413 }
4414 return lo;
4415 }
4416
4417 /**
4418 * Determines whether an argument is an instance of a constructor, including subclasses.
4419 * This is done by first just checking `instanceof`,
4420 * and then comparing the string names of the constructors if that fails.
4421 * @param {any} arg
4422 * @param {C} constructor
4423 * @template {new (...args: any) => any} C
4424 * @returns {arg is InstanceType<C>}
4425 */
4426 function isInstance(arg, constructor) {
4427 if (arg instanceof constructor) {
4428 return true;
4429 }
4430 const targetName = constructor.name;
4431 while (arg) {
4432 var _proto$constructor;
4433 const proto = Object.getPrototypeOf(arg);
4434 const constructorName = proto === null || proto === void 0 || (_proto$constructor = proto.constructor) === null || _proto$constructor === void 0 ? void 0 : _proto$constructor.name;
4435 if (constructorName === targetName) {
4436 return true;
4437 }
4438 if (!constructorName || constructorName === "Object") {
4439 return false;
4440 }
4441 arg = proto;
4442 }
4443 return false;
4444 }
4445
4446 /**
4447 * Generate a matrix of size NxN with the given diagonal values of length N.
4448 *
4449 * @param {number[]} values
4450 * @returns {number[][]}
4451 */
4452 function diag(values) {
4453 const n = values.length;
4454 const matrix = [];
4455 for (let i = 0; i < n; i++) {
4456 matrix[i] = [];
4457 for (let j = 0; j < n; j++) {
4458 matrix[i][j] = i === j ? values[i] : 0;
4459 }
4460 }
4461 return matrix;
4462 }
4463
4464 /**
4465 * Calculate the LU decomposition of an NxN matrix.
4466 *
4467 * P is returned as PA = UL or A = P'UL which follows Matlab and Octave opposed to Scipy which returns P as
4468 * A = PUL or P'A = UL. For matrix inverse, we need P such that PA = UL and it is faster not having to invert
4469 * P, even if we can invert it fairly fast as it is just a shuffled identity matrix.
4470 *
4471 * P is returned as a permutation matrix unless pIndices is true, in which case P would be returned as
4472 * a vector containing the indexes such that A[P,:] = L*U.
4473 *
4474 * Reference:
4475 * - https://www.statlect.com/matrix-algebra/Gaussian-elimination
4476 * - https://www.sciencedirect.com/topics/mathematics/partial-pivoting
4477 *
4478 * @overload
4479 * @param {number[][]} matrix
4480 * @param {{ pIndices?: false | undefined }} [options]
4481 * @returns {[number[][], number[][], number[][]]}
4482 */
4483 /**
4484 * @overload
4485 * @param {number[][]} matrix
4486 * @param {{ pIndices?: true }} [options]
4487 * @returns {[number[], number[][], number[][]]}
4488 */
4489 /**
4490 * @param {number[][]} matrix
4491 * @param {{ pIndices?: boolean | undefined }} [options]
4492 * @returns {[number[] | number[][], number[][], number[][]]}
4493 */
4494 function lu(matrix, {
4495 pIndices = false
4496 } = {}) {
4497 let p1, p2, l, u;
4498 const n = matrix.length;
4499
4500 // Initialize the triangle matrices along with the permutation matrix.
4501 if (pIndices) {
4502 p1 = Array.from({
4503 length: n
4504 }, (_, index) => index);
4505 l = diag(new Array(n).fill(1));
4506 } else {
4507 p2 = diag(new Array(n).fill(1));
4508 l = structuredClone(p2);
4509 }
4510 u = structuredClone(matrix);
4511
4512 // Create upper and lower triangle in 'u' and 'l'. 'p' tracks the permutation (relative position of rows)
4513 for (let i = 0; i < n - 1; i++) {
4514 // Partial pivoting: identify the row with the maximal value in the column
4515 let j = i;
4516 let maximum = Math.abs(u[i][i]);
4517 for (let k = i + 1; k < n; k++) {
4518 const a = Math.abs(u[k][i]);
4519 if (a > maximum) {
4520 j = k;
4521 maximum = a;
4522 }
4523 }
4524
4525 // Partial pivoting: Swap rows
4526 if (j != i) {
4527 // Exchange current upper triangle row with row with maximal value at pivot
4528 // Update permutation matrix as well
4529 [u[i], u[j]] = [u[j], u[i]];
4530 if (pIndices) {
4531 [p1[i], p1[j]] = [p1[j], p1[i]];
4532 } else {
4533 [p2[i], p2[j]] = [p2[j], p2[i]];
4534 }
4535
4536 // Only swap columns up to the pivot for the lower triangle,
4537 // if on first row, there is nothing to swap
4538 if (i) {
4539 for (let k = 0; k < i; k++) {
4540 [l[i][k], l[j][k]] = [l[j][k], l[i][k]];
4541 }
4542 }
4543 }
4544
4545 // Zero at pivot point, nothing to do
4546 else if (!maximum) {
4547 continue;
4548 }
4549
4550 // We have a pivot point, let's zero out everything above and below
4551 // the 'l' and 'u' diagonal respectively
4552 for (let j = i + 1; j < n; j++) {
4553 const scalar = u[j][i] / u[i][i];
4554 for (let k = i; k < n; k++) {
4555 u[j][k] += -u[i][k] * scalar;
4556 l[j][k] += l[i][k] * scalar;
4557 }
4558 }
4559 }
4560 if (pIndices) {
4561 return [p1, l, u];
4562 }
4563 return [p2, l, u];
4564 }
4565
4566 /**
4567 * Forward substitution for solution of ax = b where a and b are matricies.
4568 *
4569 * @param {number[][]} a
4570 * @param {number[][]} b
4571 * @param {number} n
4572 * @returns {number[][]}
4573 */
4574 function forwardSubMatrix(a, b, n) {
4575 for (let i = 0; i < n; i++) {
4576 const v = b[i];
4577 for (let j = 0; j < i; j++) {
4578 for (let k = 0; k < n; k++) {
4579 v[k] -= a[i][j] * b[j][k];
4580 }
4581 }
4582 for (let j = 0; j < n; j++) {
4583 v[j] /= a[i][i];
4584 }
4585 }
4586 return b;
4587 }
4588
4589 /**
4590 * Back substitution for solution of ax = b where a and b are matricies.
4591 *
4592 * @param {number[][]} a
4593 * @param {number[][]} b
4594 * @param {number} n
4595 * @returns {number[][]}
4596 */
4597 function backSubMatrix(a, b, n) {
4598 for (let i = n - 1; i > -1; i--) {
4599 const v = b[i];
4600 for (let j = i + 1; j < n; j++) {
4601 for (var k = 0; k < n; k++) {
4602 v[k] -= a[i][j] * b[j][k];
4603 }
4604 }
4605 for (let j = 0; j < n; j++) {
4606 b[i][j] /= a[i][i];
4607 }
4608 }
4609 return b;
4610 }
4611
4612 /**
4613 * Forward substitution for solution of ax = b where a is a matrix and b is a vector.
4614 *
4615 * @param {number[][]} a
4616 * @param {number[]} b
4617 * @param {number} n
4618 * @returns {number[]}
4619 */
4620 function forwardSubVector(a, b, n) {
4621 for (let i = 0; i < n; i++) {
4622 let v = b[i];
4623 for (let j = 0; j < i; j++) {
4624 v -= a[i][j] * b[j];
4625 }
4626 b[i] = v / a[i][i];
4627 }
4628 return b;
4629 }
4630
4631 /**
4632 * Back substitution for solution of ax = b where a is a matrix and b is a vector.
4633 *
4634 * @param {number[][]} a
4635 * @param {number[]} b
4636 * @param {number} n
4637 * @returns {number[]}
4638 */
4639 function backSubVector(a, b, n) {
4640 for (let i = n - 1; i > -1; i--) {
4641 let v = b[i];
4642 for (let j = i + 1; j < n; j++) {
4643 v -= a[i][j] * b[j];
4644 }
4645 b[i] = v / a[i][i];
4646 }
4647 return b;
4648 }
4649
4650 /**
4651 * Invert a NxN matrix.
4652 *
4653 * @param {number[][]} matrix
4654 * @returns {number[][]}
4655 */
4656 function inv(matrix) {
4657 // Calculate the LU decomposition.
4658 const [p, l, u] = lu(matrix);
4659 const n = l.length;
4660
4661 // Floating point math can produce very small, non-zero determinants for singular matrices.
4662 // This seems to happen in Numpy as well.
4663 // Don't bother calculating sign as we only care about how close to zero we are.
4664 if (l.map((row, i) => row[i] * u[i][i]).reduce((acc, val) => acc * val, 1) === 0.0) {
4665 throw new Error("Matrix is singular");
4666 }
4667
4668 // Solve for the identity matrix (will give us inverse)
4669 // Permutation matrix is the identity matrix, even if shuffled.
4670 return backSubMatrix(u, forwardSubMatrix(l, p, n), n);
4671 }
4672
4673 /**
4674 * Solve a NxN matrix representing a system of equations.
4675 *
4676 * @param {number[][]} matrix
4677 * @param {number[]} vector
4678 * @returns {number[]}
4679 */
4680 function solve(matrix, vector) {
4681 // Calculate the LU decomposition.
4682 const [p, l, u] = lu(matrix, {
4683 pIndices: true
4684 });
4685 const n = l.length;
4686
4687 // If determinant is zero, we can't solve.
4688 if (l.map((row, i) => row[i] * u[i][i]).reduce((acc, val) => acc * val, 1) === 0.0) {
4689 throw new Error("Matrix is singular");
4690 }
4691 return backSubVector(u, forwardSubVector(l, p.map(i => vector[i]), n), n);
4692 }
4693
4694 var util = /*#__PURE__*/Object.freeze({
4695 __proto__: null,
4696 bisectLeft: bisectLeft,
4697 clamp: clamp,
4698 copySign: copySign,
4699 diag: diag,
4700 interpolate: interpolate,
4701 interpolateInv: interpolateInv,
4702 inv: inv,
4703 isInstance: isInstance,
4704 isNone: isNone,
4705 isString: isString,
4706 lu: lu,
4707 mapRange: mapRange,
4708 multiplyMatrices: multiplyMatrices,
4709 multiply_v3_m3x3: multiply_v3_m3x3,
4710 serializeNumber: serializeNumber,
4711 skipNone: skipNone,
4712 solve: solve,
4713 spow: spow,
4714 toPrecision: toPrecision,
4715 type: type,
4716 zdiv: zdiv
4717 });
4718
4719 var esnext_iterator_forEach = {};
4720
4721 var es_iterator_forEach = {};
4722
4723 var hasRequiredEs_iterator_forEach;
4724
4725 function requireEs_iterator_forEach () {
4726 if (hasRequiredEs_iterator_forEach) return es_iterator_forEach;
4727 hasRequiredEs_iterator_forEach = 1;
4728 var $ = require_export();
4729 var iterate = requireIterate();
4730 var aCallable = requireACallable();
4731 var anObject = requireAnObject();
4732 var getIteratorDirect = requireGetIteratorDirect();
4733
4734 // `Iterator.prototype.forEach` method
4735 // https://tc39.es/ecma262/#sec-iterator.prototype.foreach
4736 $({ target: 'Iterator', proto: true, real: true }, {
4737 forEach: function forEach(fn) {
4738 anObject(this);
4739 aCallable(fn);
4740 var record = getIteratorDirect(this);
4741 var counter = 0;
4742 iterate(record, function (value) {
4743 fn(value, counter++);
4744 }, { IS_RECORD: true });
4745 }
4746 });
4747 return es_iterator_forEach;
4748 }
4749
4750 var hasRequiredEsnext_iterator_forEach;
4751
4752 function requireEsnext_iterator_forEach () {
4753 if (hasRequiredEsnext_iterator_forEach) return esnext_iterator_forEach;
4754 hasRequiredEsnext_iterator_forEach = 1;
4755 // TODO: Remove from `core-js@4`
4756 requireEs_iterator_forEach();
4757 return esnext_iterator_forEach;
4758 }
4759
4760 requireEsnext_iterator_forEach();
4761
4762 /**
4763 * A class for adding deep extensibility to any piece of JS code
4764 */
4765 class Hooks {
4766 add(name, callback, first) {
4767 if (typeof arguments[0] != "string") {
4768 // Multiple hooks
4769 for (var name in arguments[0]) {
4770 this.add(name, arguments[0][name], arguments[1]);
4771 }
4772 return;
4773 }
4774 (Array.isArray(name) ? name : [name]).forEach(function (name) {
4775 this[name] = this[name] || [];
4776 if (callback) {
4777 this[name][first ? "unshift" : "push"](callback);
4778 }
4779 }, this);
4780 }
4781 run(name, env) {
4782 this[name] = this[name] || [];
4783 this[name].forEach(function (callback) {
4784 callback.call(env && env.context ? env.context : env, env);
4785 });
4786 }
4787 }
4788
4789 /**
4790 * The instance of {@link Hooks} used throughout Color.js
4791 */
4792 const hooks = new Hooks();
4793
4794 var _globalThis$process;
4795 // Global defaults one may want to configure
4796 var defaults = {
4797 gamut_mapping: "css",
4798 precision: 5,
4799 deltaE: "76",
4800 // Default deltaE method
4801 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",
4802 warn: function warn(msg) {
4803 if (this.verbose) {
4804 var _globalThis$console, _globalThis$console$w;
4805 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);
4806 }
4807 }
4808 };
4809
4810 var es_array_push = {};
4811
4812 var isArray;
4813 var hasRequiredIsArray;
4814
4815 function requireIsArray () {
4816 if (hasRequiredIsArray) return isArray;
4817 hasRequiredIsArray = 1;
4818 var classof = requireClassofRaw();
4819
4820 // `IsArray` abstract operation
4821 // https://tc39.es/ecma262/#sec-isarray
4822 // eslint-disable-next-line es/no-array-isarray -- safe
4823 isArray = Array.isArray || function isArray(argument) {
4824 return classof(argument) === 'Array';
4825 };
4826 return isArray;
4827 }
4828
4829 var arraySetLength;
4830 var hasRequiredArraySetLength;
4831
4832 function requireArraySetLength () {
4833 if (hasRequiredArraySetLength) return arraySetLength;
4834 hasRequiredArraySetLength = 1;
4835 var DESCRIPTORS = requireDescriptors();
4836 var isArray = requireIsArray();
4837
4838 var $TypeError = TypeError;
4839 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
4840 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
4841
4842 // Safari < 13 does not throw an error in this case
4843 var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () {
4844 // makes no sense without proper strict mode support
4845 if (this !== undefined) return true;
4846 try {
4847 // eslint-disable-next-line es/no-object-defineproperty -- safe
4848 Object.defineProperty([], 'length', { writable: false }).length = 1;
4849 } catch (error) {
4850 return error instanceof TypeError;
4851 }
4852 }();
4853
4854 arraySetLength = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
4855 if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) {
4856 throw new $TypeError('Cannot set read only .length');
4857 } return O.length = length;
4858 } : function (O, length) {
4859 return O.length = length;
4860 };
4861 return arraySetLength;
4862 }
4863
4864 var doesNotExceedSafeInteger;
4865 var hasRequiredDoesNotExceedSafeInteger;
4866
4867 function requireDoesNotExceedSafeInteger () {
4868 if (hasRequiredDoesNotExceedSafeInteger) return doesNotExceedSafeInteger;
4869 hasRequiredDoesNotExceedSafeInteger = 1;
4870 var $TypeError = TypeError;
4871 var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991
4872
4873 doesNotExceedSafeInteger = function (it) {
4874 if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded');
4875 return it;
4876 };
4877 return doesNotExceedSafeInteger;
4878 }
4879
4880 var hasRequiredEs_array_push;
4881
4882 function requireEs_array_push () {
4883 if (hasRequiredEs_array_push) return es_array_push;
4884 hasRequiredEs_array_push = 1;
4885 var $ = require_export();
4886 var toObject = requireToObject();
4887 var lengthOfArrayLike = requireLengthOfArrayLike();
4888 var setArrayLength = requireArraySetLength();
4889 var doesNotExceedSafeInteger = requireDoesNotExceedSafeInteger();
4890 var fails = requireFails();
4891
4892 var INCORRECT_TO_LENGTH = fails(function () {
4893 return [].push.call({ length: 0x100000000 }, 1) !== 4294967297;
4894 });
4895
4896 // V8 <= 121 and Safari <= 15.4; FF < 23 throws InternalError
4897 // https://bugs.chromium.org/p/v8/issues/detail?id=12681
4898 var properErrorOnNonWritableLength = function () {
4899 try {
4900 // eslint-disable-next-line es/no-object-defineproperty -- safe
4901 Object.defineProperty([], 'length', { writable: false }).push();
4902 } catch (error) {
4903 return error instanceof TypeError;
4904 }
4905 };
4906
4907 var FORCED = INCORRECT_TO_LENGTH || !properErrorOnNonWritableLength();
4908
4909 // `Array.prototype.push` method
4910 // https://tc39.es/ecma262/#sec-array.prototype.push
4911 $({ target: 'Array', proto: true, arity: 1, forced: FORCED }, {
4912 // eslint-disable-next-line no-unused-vars -- required for `.length`
4913 push: function push(item) {
4914 var O = toObject(this);
4915 var len = lengthOfArrayLike(O);
4916 var argCount = arguments.length;
4917 doesNotExceedSafeInteger(len + argCount);
4918 for (var i = 0; i < argCount; i++) {
4919 O[len] = arguments[i];
4920 len++;
4921 }
4922 setArrayLength(O, len);
4923 return len;
4924 }
4925 });
4926 return es_array_push;
4927 }
4928
4929 requireEs_array_push();
4930
4931 var esnext_iterator_every = {};
4932
4933 var es_iterator_every = {};
4934
4935 var hasRequiredEs_iterator_every;
4936
4937 function requireEs_iterator_every () {
4938 if (hasRequiredEs_iterator_every) return es_iterator_every;
4939 hasRequiredEs_iterator_every = 1;
4940 var $ = require_export();
4941 var iterate = requireIterate();
4942 var aCallable = requireACallable();
4943 var anObject = requireAnObject();
4944 var getIteratorDirect = requireGetIteratorDirect();
4945
4946 // `Iterator.prototype.every` method
4947 // https://tc39.es/ecma262/#sec-iterator.prototype.every
4948 $({ target: 'Iterator', proto: true, real: true }, {
4949 every: function every(predicate) {
4950 anObject(this);
4951 aCallable(predicate);
4952 var record = getIteratorDirect(this);
4953 var counter = 0;
4954 return !iterate(record, function (value, stop) {
4955 if (!predicate(value, counter++)) return stop();
4956 }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
4957 }
4958 });
4959 return es_iterator_every;
4960 }
4961
4962 var hasRequiredEsnext_iterator_every;
4963
4964 function requireEsnext_iterator_every () {
4965 if (hasRequiredEsnext_iterator_every) return esnext_iterator_every;
4966 hasRequiredEsnext_iterator_every = 1;
4967 // TODO: Remove from `core-js@4`
4968 requireEs_iterator_every();
4969 return esnext_iterator_every;
4970 }
4971
4972 requireEsnext_iterator_every();
4973
4974 var esnext_iterator_some = {};
4975
4976 var es_iterator_some = {};
4977
4978 var hasRequiredEs_iterator_some;
4979
4980 function requireEs_iterator_some () {
4981 if (hasRequiredEs_iterator_some) return es_iterator_some;
4982 hasRequiredEs_iterator_some = 1;
4983 var $ = require_export();
4984 var iterate = requireIterate();
4985 var aCallable = requireACallable();
4986 var anObject = requireAnObject();
4987 var getIteratorDirect = requireGetIteratorDirect();
4988
4989 // `Iterator.prototype.some` method
4990 // https://tc39.es/ecma262/#sec-iterator.prototype.some
4991 $({ target: 'Iterator', proto: true, real: true }, {
4992 some: function some(predicate) {
4993 anObject(this);
4994 aCallable(predicate);
4995 var record = getIteratorDirect(this);
4996 var counter = 0;
4997 return iterate(record, function (value, stop) {
4998 if (predicate(value, counter++)) return stop();
4999 }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
5000 }
5001 });
5002 return es_iterator_some;
5003 }
5004
5005 var hasRequiredEsnext_iterator_some;
5006
5007 function requireEsnext_iterator_some () {
5008 if (hasRequiredEsnext_iterator_some) return esnext_iterator_some;
5009 hasRequiredEsnext_iterator_some = 1;
5010 // TODO: Remove from `core-js@4`
5011 requireEs_iterator_some();
5012 return esnext_iterator_some;
5013 }
5014
5015 requireEsnext_iterator_some();
5016
5017 var esnext_set_difference_v2 = {};
5018
5019 var es_set_difference_v2 = {};
5020
5021 var aSet;
5022 var hasRequiredASet;
5023
5024 function requireASet () {
5025 if (hasRequiredASet) return aSet;
5026 hasRequiredASet = 1;
5027 var has = requireSetHelpers().has;
5028
5029 // Perform ? RequireInternalSlot(M, [[SetData]])
5030 aSet = function (it) {
5031 has(it);
5032 return it;
5033 };
5034 return aSet;
5035 }
5036
5037 var setClone;
5038 var hasRequiredSetClone;
5039
5040 function requireSetClone () {
5041 if (hasRequiredSetClone) return setClone;
5042 hasRequiredSetClone = 1;
5043 var SetHelpers = requireSetHelpers();
5044 var iterate = requireSetIterate();
5045
5046 var Set = SetHelpers.Set;
5047 var add = SetHelpers.add;
5048
5049 setClone = function (set) {
5050 var result = new Set();
5051 iterate(set, function (it) {
5052 add(result, it);
5053 });
5054 return result;
5055 };
5056 return setClone;
5057 }
5058
5059 var setSize;
5060 var hasRequiredSetSize;
5061
5062 function requireSetSize () {
5063 if (hasRequiredSetSize) return setSize;
5064 hasRequiredSetSize = 1;
5065 var uncurryThisAccessor = requireFunctionUncurryThisAccessor();
5066 var SetHelpers = requireSetHelpers();
5067
5068 setSize = uncurryThisAccessor(SetHelpers.proto, 'size', 'get') || function (set) {
5069 return set.size;
5070 };
5071 return setSize;
5072 }
5073
5074 var getSetRecord;
5075 var hasRequiredGetSetRecord;
5076
5077 function requireGetSetRecord () {
5078 if (hasRequiredGetSetRecord) return getSetRecord;
5079 hasRequiredGetSetRecord = 1;
5080 var aCallable = requireACallable();
5081 var anObject = requireAnObject();
5082 var call = requireFunctionCall();
5083 var toIntegerOrInfinity = requireToIntegerOrInfinity();
5084 var getIteratorDirect = requireGetIteratorDirect();
5085
5086 var INVALID_SIZE = 'Invalid size';
5087 var $RangeError = RangeError;
5088 var $TypeError = TypeError;
5089 var max = Math.max;
5090
5091 var SetRecord = function (set, intSize) {
5092 this.set = set;
5093 this.size = max(intSize, 0);
5094 this.has = aCallable(set.has);
5095 this.keys = aCallable(set.keys);
5096 };
5097
5098 SetRecord.prototype = {
5099 getIterator: function () {
5100 return getIteratorDirect(anObject(call(this.keys, this.set)));
5101 },
5102 includes: function (it) {
5103 return call(this.has, this.set, it);
5104 }
5105 };
5106
5107 // `GetSetRecord` abstract operation
5108 // https://tc39.es/proposal-set-methods/#sec-getsetrecord
5109 getSetRecord = function (obj) {
5110 anObject(obj);
5111 var numSize = +obj.size;
5112 // NOTE: If size is undefined, then numSize will be NaN
5113 // eslint-disable-next-line no-self-compare -- NaN check
5114 if (numSize !== numSize) throw new $TypeError(INVALID_SIZE);
5115 var intSize = toIntegerOrInfinity(numSize);
5116 if (intSize < 0) throw new $RangeError(INVALID_SIZE);
5117 return new SetRecord(obj, intSize);
5118 };
5119 return getSetRecord;
5120 }
5121
5122 var setDifference;
5123 var hasRequiredSetDifference;
5124
5125 function requireSetDifference () {
5126 if (hasRequiredSetDifference) return setDifference;
5127 hasRequiredSetDifference = 1;
5128 var aSet = requireASet();
5129 var SetHelpers = requireSetHelpers();
5130 var clone = requireSetClone();
5131 var size = requireSetSize();
5132 var getSetRecord = requireGetSetRecord();
5133 var iterateSet = requireSetIterate();
5134 var iterateSimple = requireIterateSimple();
5135
5136 var has = SetHelpers.has;
5137 var remove = SetHelpers.remove;
5138
5139 // `Set.prototype.difference` method
5140 // https://github.com/tc39/proposal-set-methods
5141 setDifference = function difference(other) {
5142 var O = aSet(this);
5143 var otherRec = getSetRecord(other);
5144 var result = clone(O);
5145 if (size(O) <= otherRec.size) iterateSet(O, function (e) {
5146 if (otherRec.includes(e)) remove(result, e);
5147 });
5148 else iterateSimple(otherRec.getIterator(), function (e) {
5149 if (has(O, e)) remove(result, e);
5150 });
5151 return result;
5152 };
5153 return setDifference;
5154 }
5155
5156 var setMethodAcceptSetLike;
5157 var hasRequiredSetMethodAcceptSetLike;
5158
5159 function requireSetMethodAcceptSetLike () {
5160 if (hasRequiredSetMethodAcceptSetLike) return setMethodAcceptSetLike;
5161 hasRequiredSetMethodAcceptSetLike = 1;
5162 var getBuiltIn = requireGetBuiltIn();
5163
5164 var createSetLike = function (size) {
5165 return {
5166 size: size,
5167 has: function () {
5168 return false;
5169 },
5170 keys: function () {
5171 return {
5172 next: function () {
5173 return { done: true };
5174 }
5175 };
5176 }
5177 };
5178 };
5179
5180 setMethodAcceptSetLike = function (name) {
5181 var Set = getBuiltIn('Set');
5182 try {
5183 new Set()[name](createSetLike(0));
5184 try {
5185 // late spec change, early WebKit ~ Safari 17.0 beta implementation does not pass it
5186 // https://github.com/tc39/proposal-set-methods/pull/88
5187 new Set()[name](createSetLike(-1));
5188 return false;
5189 } catch (error2) {
5190 return true;
5191 }
5192 } catch (error) {
5193 return false;
5194 }
5195 };
5196 return setMethodAcceptSetLike;
5197 }
5198
5199 var hasRequiredEs_set_difference_v2;
5200
5201 function requireEs_set_difference_v2 () {
5202 if (hasRequiredEs_set_difference_v2) return es_set_difference_v2;
5203 hasRequiredEs_set_difference_v2 = 1;
5204 var $ = require_export();
5205 var difference = requireSetDifference();
5206 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5207
5208 // `Set.prototype.difference` method
5209 // https://tc39.es/ecma262/#sec-set.prototype.difference
5210 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('difference') }, {
5211 difference: difference
5212 });
5213 return es_set_difference_v2;
5214 }
5215
5216 var hasRequiredEsnext_set_difference_v2;
5217
5218 function requireEsnext_set_difference_v2 () {
5219 if (hasRequiredEsnext_set_difference_v2) return esnext_set_difference_v2;
5220 hasRequiredEsnext_set_difference_v2 = 1;
5221 // TODO: Remove from `core-js@4`
5222 requireEs_set_difference_v2();
5223 return esnext_set_difference_v2;
5224 }
5225
5226 requireEsnext_set_difference_v2();
5227
5228 var esnext_set_intersection_v2 = {};
5229
5230 var es_set_intersection_v2 = {};
5231
5232 var setIntersection;
5233 var hasRequiredSetIntersection;
5234
5235 function requireSetIntersection () {
5236 if (hasRequiredSetIntersection) return setIntersection;
5237 hasRequiredSetIntersection = 1;
5238 var aSet = requireASet();
5239 var SetHelpers = requireSetHelpers();
5240 var size = requireSetSize();
5241 var getSetRecord = requireGetSetRecord();
5242 var iterateSet = requireSetIterate();
5243 var iterateSimple = requireIterateSimple();
5244
5245 var Set = SetHelpers.Set;
5246 var add = SetHelpers.add;
5247 var has = SetHelpers.has;
5248
5249 // `Set.prototype.intersection` method
5250 // https://github.com/tc39/proposal-set-methods
5251 setIntersection = function intersection(other) {
5252 var O = aSet(this);
5253 var otherRec = getSetRecord(other);
5254 var result = new Set();
5255
5256 if (size(O) > otherRec.size) {
5257 iterateSimple(otherRec.getIterator(), function (e) {
5258 if (has(O, e)) add(result, e);
5259 });
5260 } else {
5261 iterateSet(O, function (e) {
5262 if (otherRec.includes(e)) add(result, e);
5263 });
5264 }
5265
5266 return result;
5267 };
5268 return setIntersection;
5269 }
5270
5271 var hasRequiredEs_set_intersection_v2;
5272
5273 function requireEs_set_intersection_v2 () {
5274 if (hasRequiredEs_set_intersection_v2) return es_set_intersection_v2;
5275 hasRequiredEs_set_intersection_v2 = 1;
5276 var $ = require_export();
5277 var fails = requireFails();
5278 var intersection = requireSetIntersection();
5279 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5280
5281 var INCORRECT = !setMethodAcceptSetLike('intersection') || fails(function () {
5282 // eslint-disable-next-line es/no-array-from, es/no-set -- testing
5283 return String(Array.from(new Set([1, 2, 3]).intersection(new Set([3, 2])))) !== '3,2';
5284 });
5285
5286 // `Set.prototype.intersection` method
5287 // https://tc39.es/ecma262/#sec-set.prototype.intersection
5288 $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, {
5289 intersection: intersection
5290 });
5291 return es_set_intersection_v2;
5292 }
5293
5294 var hasRequiredEsnext_set_intersection_v2;
5295
5296 function requireEsnext_set_intersection_v2 () {
5297 if (hasRequiredEsnext_set_intersection_v2) return esnext_set_intersection_v2;
5298 hasRequiredEsnext_set_intersection_v2 = 1;
5299 // TODO: Remove from `core-js@4`
5300 requireEs_set_intersection_v2();
5301 return esnext_set_intersection_v2;
5302 }
5303
5304 requireEsnext_set_intersection_v2();
5305
5306 var esnext_set_isDisjointFrom_v2 = {};
5307
5308 var es_set_isDisjointFrom_v2 = {};
5309
5310 var setIsDisjointFrom;
5311 var hasRequiredSetIsDisjointFrom;
5312
5313 function requireSetIsDisjointFrom () {
5314 if (hasRequiredSetIsDisjointFrom) return setIsDisjointFrom;
5315 hasRequiredSetIsDisjointFrom = 1;
5316 var aSet = requireASet();
5317 var has = requireSetHelpers().has;
5318 var size = requireSetSize();
5319 var getSetRecord = requireGetSetRecord();
5320 var iterateSet = requireSetIterate();
5321 var iterateSimple = requireIterateSimple();
5322 var iteratorClose = requireIteratorClose();
5323
5324 // `Set.prototype.isDisjointFrom` method
5325 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isDisjointFrom
5326 setIsDisjointFrom = function isDisjointFrom(other) {
5327 var O = aSet(this);
5328 var otherRec = getSetRecord(other);
5329 if (size(O) <= otherRec.size) return iterateSet(O, function (e) {
5330 if (otherRec.includes(e)) return false;
5331 }, true) !== false;
5332 var iterator = otherRec.getIterator();
5333 return iterateSimple(iterator, function (e) {
5334 if (has(O, e)) return iteratorClose(iterator, 'normal', false);
5335 }) !== false;
5336 };
5337 return setIsDisjointFrom;
5338 }
5339
5340 var hasRequiredEs_set_isDisjointFrom_v2;
5341
5342 function requireEs_set_isDisjointFrom_v2 () {
5343 if (hasRequiredEs_set_isDisjointFrom_v2) return es_set_isDisjointFrom_v2;
5344 hasRequiredEs_set_isDisjointFrom_v2 = 1;
5345 var $ = require_export();
5346 var isDisjointFrom = requireSetIsDisjointFrom();
5347 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5348
5349 // `Set.prototype.isDisjointFrom` method
5350 // https://tc39.es/ecma262/#sec-set.prototype.isdisjointfrom
5351 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isDisjointFrom') }, {
5352 isDisjointFrom: isDisjointFrom
5353 });
5354 return es_set_isDisjointFrom_v2;
5355 }
5356
5357 var hasRequiredEsnext_set_isDisjointFrom_v2;
5358
5359 function requireEsnext_set_isDisjointFrom_v2 () {
5360 if (hasRequiredEsnext_set_isDisjointFrom_v2) return esnext_set_isDisjointFrom_v2;
5361 hasRequiredEsnext_set_isDisjointFrom_v2 = 1;
5362 // TODO: Remove from `core-js@4`
5363 requireEs_set_isDisjointFrom_v2();
5364 return esnext_set_isDisjointFrom_v2;
5365 }
5366
5367 requireEsnext_set_isDisjointFrom_v2();
5368
5369 var esnext_set_isSubsetOf_v2 = {};
5370
5371 var es_set_isSubsetOf_v2 = {};
5372
5373 var setIsSubsetOf;
5374 var hasRequiredSetIsSubsetOf;
5375
5376 function requireSetIsSubsetOf () {
5377 if (hasRequiredSetIsSubsetOf) return setIsSubsetOf;
5378 hasRequiredSetIsSubsetOf = 1;
5379 var aSet = requireASet();
5380 var size = requireSetSize();
5381 var iterate = requireSetIterate();
5382 var getSetRecord = requireGetSetRecord();
5383
5384 // `Set.prototype.isSubsetOf` method
5385 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSubsetOf
5386 setIsSubsetOf = function isSubsetOf(other) {
5387 var O = aSet(this);
5388 var otherRec = getSetRecord(other);
5389 if (size(O) > otherRec.size) return false;
5390 return iterate(O, function (e) {
5391 if (!otherRec.includes(e)) return false;
5392 }, true) !== false;
5393 };
5394 return setIsSubsetOf;
5395 }
5396
5397 var hasRequiredEs_set_isSubsetOf_v2;
5398
5399 function requireEs_set_isSubsetOf_v2 () {
5400 if (hasRequiredEs_set_isSubsetOf_v2) return es_set_isSubsetOf_v2;
5401 hasRequiredEs_set_isSubsetOf_v2 = 1;
5402 var $ = require_export();
5403 var isSubsetOf = requireSetIsSubsetOf();
5404 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5405
5406 // `Set.prototype.isSubsetOf` method
5407 // https://tc39.es/ecma262/#sec-set.prototype.issubsetof
5408 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSubsetOf') }, {
5409 isSubsetOf: isSubsetOf
5410 });
5411 return es_set_isSubsetOf_v2;
5412 }
5413
5414 var hasRequiredEsnext_set_isSubsetOf_v2;
5415
5416 function requireEsnext_set_isSubsetOf_v2 () {
5417 if (hasRequiredEsnext_set_isSubsetOf_v2) return esnext_set_isSubsetOf_v2;
5418 hasRequiredEsnext_set_isSubsetOf_v2 = 1;
5419 // TODO: Remove from `core-js@4`
5420 requireEs_set_isSubsetOf_v2();
5421 return esnext_set_isSubsetOf_v2;
5422 }
5423
5424 requireEsnext_set_isSubsetOf_v2();
5425
5426 var esnext_set_isSupersetOf_v2 = {};
5427
5428 var es_set_isSupersetOf_v2 = {};
5429
5430 var setIsSupersetOf;
5431 var hasRequiredSetIsSupersetOf;
5432
5433 function requireSetIsSupersetOf () {
5434 if (hasRequiredSetIsSupersetOf) return setIsSupersetOf;
5435 hasRequiredSetIsSupersetOf = 1;
5436 var aSet = requireASet();
5437 var has = requireSetHelpers().has;
5438 var size = requireSetSize();
5439 var getSetRecord = requireGetSetRecord();
5440 var iterateSimple = requireIterateSimple();
5441 var iteratorClose = requireIteratorClose();
5442
5443 // `Set.prototype.isSupersetOf` method
5444 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSupersetOf
5445 setIsSupersetOf = function isSupersetOf(other) {
5446 var O = aSet(this);
5447 var otherRec = getSetRecord(other);
5448 if (size(O) < otherRec.size) return false;
5449 var iterator = otherRec.getIterator();
5450 return iterateSimple(iterator, function (e) {
5451 if (!has(O, e)) return iteratorClose(iterator, 'normal', false);
5452 }) !== false;
5453 };
5454 return setIsSupersetOf;
5455 }
5456
5457 var hasRequiredEs_set_isSupersetOf_v2;
5458
5459 function requireEs_set_isSupersetOf_v2 () {
5460 if (hasRequiredEs_set_isSupersetOf_v2) return es_set_isSupersetOf_v2;
5461 hasRequiredEs_set_isSupersetOf_v2 = 1;
5462 var $ = require_export();
5463 var isSupersetOf = requireSetIsSupersetOf();
5464 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5465
5466 // `Set.prototype.isSupersetOf` method
5467 // https://tc39.es/ecma262/#sec-set.prototype.issupersetof
5468 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSupersetOf') }, {
5469 isSupersetOf: isSupersetOf
5470 });
5471 return es_set_isSupersetOf_v2;
5472 }
5473
5474 var hasRequiredEsnext_set_isSupersetOf_v2;
5475
5476 function requireEsnext_set_isSupersetOf_v2 () {
5477 if (hasRequiredEsnext_set_isSupersetOf_v2) return esnext_set_isSupersetOf_v2;
5478 hasRequiredEsnext_set_isSupersetOf_v2 = 1;
5479 // TODO: Remove from `core-js@4`
5480 requireEs_set_isSupersetOf_v2();
5481 return esnext_set_isSupersetOf_v2;
5482 }
5483
5484 requireEsnext_set_isSupersetOf_v2();
5485
5486 var esnext_set_symmetricDifference_v2 = {};
5487
5488 var es_set_symmetricDifference_v2 = {};
5489
5490 var setSymmetricDifference;
5491 var hasRequiredSetSymmetricDifference;
5492
5493 function requireSetSymmetricDifference () {
5494 if (hasRequiredSetSymmetricDifference) return setSymmetricDifference;
5495 hasRequiredSetSymmetricDifference = 1;
5496 var aSet = requireASet();
5497 var SetHelpers = requireSetHelpers();
5498 var clone = requireSetClone();
5499 var getSetRecord = requireGetSetRecord();
5500 var iterateSimple = requireIterateSimple();
5501
5502 var add = SetHelpers.add;
5503 var has = SetHelpers.has;
5504 var remove = SetHelpers.remove;
5505
5506 // `Set.prototype.symmetricDifference` method
5507 // https://github.com/tc39/proposal-set-methods
5508 setSymmetricDifference = function symmetricDifference(other) {
5509 var O = aSet(this);
5510 var keysIter = getSetRecord(other).getIterator();
5511 var result = clone(O);
5512 iterateSimple(keysIter, function (e) {
5513 if (has(O, e)) remove(result, e);
5514 else add(result, e);
5515 });
5516 return result;
5517 };
5518 return setSymmetricDifference;
5519 }
5520
5521 var hasRequiredEs_set_symmetricDifference_v2;
5522
5523 function requireEs_set_symmetricDifference_v2 () {
5524 if (hasRequiredEs_set_symmetricDifference_v2) return es_set_symmetricDifference_v2;
5525 hasRequiredEs_set_symmetricDifference_v2 = 1;
5526 var $ = require_export();
5527 var symmetricDifference = requireSetSymmetricDifference();
5528 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5529
5530 // `Set.prototype.symmetricDifference` method
5531 // https://tc39.es/ecma262/#sec-set.prototype.symmetricdifference
5532 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('symmetricDifference') }, {
5533 symmetricDifference: symmetricDifference
5534 });
5535 return es_set_symmetricDifference_v2;
5536 }
5537
5538 var hasRequiredEsnext_set_symmetricDifference_v2;
5539
5540 function requireEsnext_set_symmetricDifference_v2 () {
5541 if (hasRequiredEsnext_set_symmetricDifference_v2) return esnext_set_symmetricDifference_v2;
5542 hasRequiredEsnext_set_symmetricDifference_v2 = 1;
5543 // TODO: Remove from `core-js@4`
5544 requireEs_set_symmetricDifference_v2();
5545 return esnext_set_symmetricDifference_v2;
5546 }
5547
5548 requireEsnext_set_symmetricDifference_v2();
5549
5550 var esnext_set_union_v2 = {};
5551
5552 var es_set_union_v2 = {};
5553
5554 var setUnion;
5555 var hasRequiredSetUnion;
5556
5557 function requireSetUnion () {
5558 if (hasRequiredSetUnion) return setUnion;
5559 hasRequiredSetUnion = 1;
5560 var aSet = requireASet();
5561 var add = requireSetHelpers().add;
5562 var clone = requireSetClone();
5563 var getSetRecord = requireGetSetRecord();
5564 var iterateSimple = requireIterateSimple();
5565
5566 // `Set.prototype.union` method
5567 // https://github.com/tc39/proposal-set-methods
5568 setUnion = function union(other) {
5569 var O = aSet(this);
5570 var keysIter = getSetRecord(other).getIterator();
5571 var result = clone(O);
5572 iterateSimple(keysIter, function (it) {
5573 add(result, it);
5574 });
5575 return result;
5576 };
5577 return setUnion;
5578 }
5579
5580 var hasRequiredEs_set_union_v2;
5581
5582 function requireEs_set_union_v2 () {
5583 if (hasRequiredEs_set_union_v2) return es_set_union_v2;
5584 hasRequiredEs_set_union_v2 = 1;
5585 var $ = require_export();
5586 var union = requireSetUnion();
5587 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5588
5589 // `Set.prototype.union` method
5590 // https://tc39.es/ecma262/#sec-set.prototype.union
5591 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('union') }, {
5592 union: union
5593 });
5594 return es_set_union_v2;
5595 }
5596
5597 var hasRequiredEsnext_set_union_v2;
5598
5599 function requireEsnext_set_union_v2 () {
5600 if (hasRequiredEsnext_set_union_v2) return esnext_set_union_v2;
5601 hasRequiredEsnext_set_union_v2 = 1;
5602 // TODO: Remove from `core-js@4`
5603 requireEs_set_union_v2();
5604 return esnext_set_union_v2;
5605 }
5606
5607 requireEsnext_set_union_v2();
5608
5609 var esnext_iterator_find = {};
5610
5611 var es_iterator_find = {};
5612
5613 var hasRequiredEs_iterator_find;
5614
5615 function requireEs_iterator_find () {
5616 if (hasRequiredEs_iterator_find) return es_iterator_find;
5617 hasRequiredEs_iterator_find = 1;
5618 var $ = require_export();
5619 var iterate = requireIterate();
5620 var aCallable = requireACallable();
5621 var anObject = requireAnObject();
5622 var getIteratorDirect = requireGetIteratorDirect();
5623
5624 // `Iterator.prototype.find` method
5625 // https://tc39.es/ecma262/#sec-iterator.prototype.find
5626 $({ target: 'Iterator', proto: true, real: true }, {
5627 find: function find(predicate) {
5628 anObject(this);
5629 aCallable(predicate);
5630 var record = getIteratorDirect(this);
5631 var counter = 0;
5632 return iterate(record, function (value, stop) {
5633 if (predicate(value, counter++)) return stop(value);
5634 }, { IS_RECORD: true, INTERRUPTED: true }).result;
5635 }
5636 });
5637 return es_iterator_find;
5638 }
5639
5640 var hasRequiredEsnext_iterator_find;
5641
5642 function requireEsnext_iterator_find () {
5643 if (hasRequiredEsnext_iterator_find) return esnext_iterator_find;
5644 hasRequiredEsnext_iterator_find = 1;
5645 // TODO: Remove from `core-js@4`
5646 requireEs_iterator_find();
5647 return esnext_iterator_find;
5648 }
5649
5650 requireEsnext_iterator_find();
5651
5652 class Type {
5653 // Class properties - declared here so that type inference works
5654 type;
5655 coordMeta;
5656 coordRange;
5657 /** @type {[number, number]} */
5658 range;
5659
5660 /**
5661 * @param {any} type
5662 * @param {import("./types.js").CoordMeta} coordMeta
5663 */
5664 constructor(type, coordMeta) {
5665 if (typeof type === "object") {
5666 this.coordMeta = type;
5667 }
5668 if (coordMeta) {
5669 var _coordMeta$range;
5670 this.coordMeta = coordMeta;
5671 this.coordRange = (_coordMeta$range = coordMeta.range) !== null && _coordMeta$range !== void 0 ? _coordMeta$range : coordMeta.refRange;
5672 }
5673 if (typeof type === "string") {
5674 let params = type.trim().match(/^(?<type><[a-z]+>)(\[(?<min>-?[.\d]+),\s*(?<max>-?[.\d]+)\])?$/);
5675 if (!params) {
5676 throw new TypeError(`Cannot parse ${type} as a type definition.`);
5677 }
5678 this.type = params.groups.type;
5679 let {
5680 min,
5681 max
5682 } = params.groups;
5683 if (min || max) {
5684 this.range = [+min, +max];
5685 }
5686 }
5687 }
5688
5689 /** @returns {[number, number]} */
5690 get computedRange() {
5691 if (this.range) {
5692 return this.range;
5693 }
5694 if (this.type === "<percentage>") {
5695 return this.percentageRange();
5696 } else if (this.type === "<angle>") {
5697 return [0, 360];
5698 }
5699 return null;
5700 }
5701 get unit() {
5702 if (this.type === "<percentage>") {
5703 return "%";
5704 } else if (this.type === "<angle>") {
5705 return "deg";
5706 }
5707 return "";
5708 }
5709
5710 /**
5711 * Map a number to the internal representation
5712 * @param {number} number
5713 */
5714 resolve(number) {
5715 if (this.type === "<angle>") {
5716 return number;
5717 }
5718 let fromRange = this.computedRange;
5719 let toRange = this.coordRange;
5720 if (this.type === "<percentage>") {
5721 var _toRange;
5722 (_toRange = toRange) !== null && _toRange !== void 0 ? _toRange : toRange = this.percentageRange();
5723 }
5724 return mapRange(fromRange, toRange, number);
5725 }
5726
5727 /**
5728 * Serialize a number from the internal representation to a string
5729 * @param {number} number
5730 * @param {number} [precision]
5731 */
5732 serialize(number, precision) {
5733 let toRange = this.type === "<percentage>" ? this.percentageRange(100) : this.computedRange;
5734 let unit = this.unit;
5735 number = mapRange(this.coordRange, toRange, number);
5736 return serializeNumber(number, {
5737 unit,
5738 precision
5739 });
5740 }
5741 toString() {
5742 let ret = this.type;
5743 if (this.range) {
5744 let [min = "", max = ""] = this.range;
5745 ret += `[${min},${max}]`;
5746 }
5747 return ret;
5748 }
5749
5750 /**
5751 * Returns a percentage range for values of this type
5752 * @param {number} scale
5753 * @returns {[number, number]}
5754 */
5755 percentageRange(scale = 1) {
5756 let range;
5757 if (this.coordMeta && this.coordMeta.range || this.coordRange && this.coordRange[0] >= 0) {
5758 range = [0, 1];
5759 } else {
5760 range = [-1, 1];
5761 }
5762 return [range[0] * scale, range[1] * scale];
5763 }
5764 static get(type, coordMeta) {
5765 if (isInstance(type, this)) {
5766 return type;
5767 }
5768 return new this(type, coordMeta);
5769 }
5770 }
5771
5772 /** @import { ColorSpace, Coords } from "./types.js" */
5773
5774 // Type re-exports
5775 /** @typedef {import("./types.js").Format} FormatInterface */
5776
5777 /**
5778 * @internal
5779 * Used to index {@link FormatInterface Format} objects and store an instance.
5780 * Not meant for external use
5781 */
5782 const instance = Symbol("instance");
5783
5784 /**
5785 * Remove the first element of an array type
5786 * @template {any[]} T
5787 * @typedef {T extends [any, ...infer R] ? R : T[number][]} RemoveFirstElement
5788 */
5789
5790 /**
5791 * @class Format
5792 * @implements {Omit<FormatInterface, "coords" | "serializeCoords">}
5793 * Class to hold a color serialization format
5794 */
5795 class Format {
5796 // Class properties - declared here so that type inference works
5797 type;
5798 name;
5799 spaceCoords;
5800 /** @type {Type[][]} */
5801 coords;
5802 /** @type {string | undefined} */
5803 id;
5804 /** @type {boolean | undefined} */
5805 alpha;
5806
5807 /**
5808 * @param {FormatInterface} format
5809 * @param {ColorSpace} space
5810 */
5811 constructor(format, space = format.space) {
5812 format[instance] = this;
5813 this.type = "function";
5814 this.name = "color";
5815 Object.assign(this, format);
5816 this.space = space;
5817 if (this.type === "custom") {
5818 // Nothing else to do here
5819 return;
5820 }
5821 this.spaceCoords = Object.values(space.coords);
5822 if (!this.coords) {
5823 // @ts-expect-error Strings are converted to the correct type later
5824 this.coords = this.spaceCoords.map(coordMeta => {
5825 let ret = ["<number>", "<percentage>"];
5826 if (coordMeta.type === "angle") {
5827 ret.push("<angle>");
5828 }
5829 return ret;
5830 });
5831 }
5832 this.coords = this.coords.map(/** @param {string | string[] | Type[]} types */(types, i) => {
5833 let coordMeta = this.spaceCoords[i];
5834 if (typeof types === "string") {
5835 types = types.trim().split(/\s*\|\s*/);
5836 }
5837 return types.map(type => Type.get(type, coordMeta));
5838 });
5839 }
5840
5841 /**
5842 * @param {Coords} coords
5843 * @param {number} precision
5844 * @param {Type[]} types
5845 */
5846 serializeCoords(coords, precision, types) {
5847 types = coords.map((_, i) => {
5848 var _types$i, _types;
5849 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]);
5850 });
5851 return coords.map((c, i) => types[i].serialize(c, precision));
5852 }
5853
5854 /**
5855 * Validates the coordinates of a color against a format's coord grammar and
5856 * maps the coordinates to the range or refRange of the coordinates.
5857 * @param {Coords} coords
5858 * @param {[string, string, string]} types
5859 */
5860 coerceCoords(coords, types) {
5861 return Object.entries(this.space.coords).map(([id, coordMeta], i) => {
5862 let arg = coords[i];
5863 if (isNone(arg) || isNaN(arg)) {
5864 // Nothing to do here
5865 return arg;
5866 }
5867
5868 // Find grammar alternative that matches the provided type
5869 // Non-strict equals is intentional because we are comparing w/ string objects
5870 let providedType = types[i];
5871 let type = this.coords[i].find(c => c.type == providedType);
5872
5873 // Check that each coord conforms to its grammar
5874 if (!type) {
5875 var _ref, _arg;
5876 // Type does not exist in the grammar, throw
5877 let coordName = coordMeta.name || id;
5878 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}()`);
5879 }
5880 arg = type.resolve(arg);
5881 if (type.range) {
5882 // Adjust type to include range
5883 types[i] = type.toString();
5884 }
5885 return arg;
5886 });
5887 }
5888
5889 /**
5890 * @returns {boolean | Required<FormatInterface>["serialize"]}
5891 */
5892 canSerialize() {
5893 return this.type === "function" || /** @type {any} */this.serialize;
5894 }
5895
5896 /**
5897 * @param {string} str
5898 * @returns {(import("./types.js").ColorConstructor) | undefined | null}
5899 */
5900 parse(str) {
5901 return null;
5902 }
5903
5904 /**
5905 * @param {Format | FormatInterface} format
5906 * @param {RemoveFirstElement<ConstructorParameters<typeof Format>>} args
5907 * @returns {Format}
5908 */
5909 static get(format, ...args) {
5910 if (!format || isInstance(format, this)) {
5911 return /** @type {Format} */format;
5912 }
5913 if (format[instance]) {
5914 return format[instance];
5915 }
5916 return new Format(format, ...args);
5917 }
5918 }
5919
5920 // Type re-exports
5921 /** @typedef {import("./types.js").White} White */
5922
5923 /** @type {Record<string, White>} */
5924 // prettier-ignore
5925 const WHITES = {
5926 // for compatibility, the four-digit chromaticity-derived ones everyone else uses
5927 D50: [0.3457 / 0.3585, 1.00000, (1.0 - 0.3457 - 0.3585) / 0.3585],
5928 D65: [0.3127 / 0.3290, 1.00000, (1.0 - 0.3127 - 0.3290) / 0.3290]
5929 };
5930
5931 /**
5932 *
5933 * @param {string | White} name
5934 * @returns {White}
5935 */
5936 function getWhite(name) {
5937 if (Array.isArray(name)) {
5938 return name;
5939 }
5940 return WHITES[name];
5941 }
5942
5943 /**
5944 * Adapt XYZ from white point W1 to W2
5945 * @param {White | string} W1
5946 * @param {White | string} W2
5947 * @param {[number, number, number]} XYZ
5948 * @param {{ method?: string | undefined }} options
5949 * @returns {[number, number, number]}
5950 */
5951 function adapt$2(W1, W2, XYZ, options = {}) {
5952 W1 = getWhite(W1);
5953 W2 = getWhite(W2);
5954 if (!W1 || !W2) {
5955 throw new TypeError(`Missing white point to convert ${!W1 ? "from" : ""}${!W1 && !W2 ? "/" : ""}${!W2 ? "to" : ""}`);
5956 }
5957 if (W1 === W2) {
5958 // Same whitepoints, no conversion needed
5959 return XYZ;
5960 }
5961 let env = {
5962 W1,
5963 W2,
5964 XYZ,
5965 options
5966 };
5967 hooks.run("chromatic-adaptation-start", env);
5968 if (!env.M) {
5969 if (env.W1 === WHITES.D65 && env.W2 === WHITES.D50) {
5970 // prettier-ignore
5971 env.M = [[1.0479297925449969, 0.022946870601609652, -0.05019226628920524], [0.02962780877005599, 0.9904344267538799, -0.017073799063418826], [-0.009243040646204504, 0.015055191490298152, 0.7518742814281371]];
5972 } else if (env.W1 === WHITES.D50 && env.W2 === WHITES.D65) {
5973 // prettier-ignore
5974 env.M = [[0.955473421488075, -0.02309845494876471, 0.06325924320057072], [-0.0283697093338637, 1.0099953980813041, 0.021041441191917323], [0.012314014864481998, -0.020507649298898964, 1.330365926242124]];
5975 }
5976 }
5977 hooks.run("chromatic-adaptation-end", env);
5978 if (env.M) {
5979 return multiply_v3_m3x3(env.XYZ, env.M);
5980 } else {
5981 throw new TypeError("Only Bradford CAT with white points D50 and D65 supported for now.");
5982 }
5983 }
5984
5985 /** @import { ColorConstructor } from "./types.js" */
5986
5987 // Type re-exports
5988 /** @typedef {import("./types.js").ArgumentMeta} ArgumentMeta */
5989 /** @typedef {import("./types.js").ParseFunctionReturn} ParseFunctionReturn */
5990 /** @typedef {import("./types.js").ParseOptions} ParseOptions */
5991
5992 /**
5993 * Convert a CSS Color string to a color object
5994 * @param {string} str
5995 * @param {ParseOptions} [options]
5996 * @returns {ColorConstructor}
5997 */
5998 function parse(str, options) {
5999 var _String, _env$options$parseMet;
6000 let env = {
6001 str: (_String = String(str)) === null || _String === void 0 ? void 0 : _String.trim(),
6002 options
6003 };
6004 hooks.run("parse-start", env);
6005 if (env.color) {
6006 return env.color;
6007 }
6008 env.parsed = parseFunction(env.str);
6009 let ret;
6010 let meta = env.options ? (_env$options$parseMet = env.options.parseMeta) !== null && _env$options$parseMet !== void 0 ? _env$options$parseMet : env.options.meta : null;
6011 if (env.parsed) {
6012 // Is a functional syntax
6013 let name = env.parsed.name;
6014 let format;
6015 let space;
6016 let coords = env.parsed.args;
6017 let types = coords.map((c, i) => {
6018 var _env$parsed$argMeta$i;
6019 return (_env$parsed$argMeta$i = env.parsed.argMeta[i]) === null || _env$parsed$argMeta$i === void 0 ? void 0 : _env$parsed$argMeta$i.type;
6020 });
6021 if (name === "color") {
6022 // color() function
6023 let id = coords.shift();
6024 types.shift();
6025 // Check against both <dashed-ident> and <ident> versions
6026 let alternateId = id.startsWith("--") ? id.substring(2) : `--${id}`;
6027 let ids = [id, alternateId];
6028 format = ColorSpace.findFormat({
6029 name,
6030 id: ids,
6031 type: "function"
6032 });
6033 if (!format) {
6034 var _didYouMean;
6035 // Not found
6036 let didYouMean;
6037 let registryId = id in ColorSpace.registry ? id : alternateId;
6038 if (registryId in ColorSpace.registry) {
6039 var _ColorSpace$registry$;
6040 // Used color space id instead of color() id, these are often different
6041 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;
6042 if (cssId) {
6043 let altColor = str.replace("color(" + id, "color(" + cssId);
6044 didYouMean = `Did you mean ${altColor}?`;
6045 }
6046 }
6047 throw new TypeError(`Cannot parse ${env.str}. ` + ((_didYouMean = didYouMean) !== null && _didYouMean !== void 0 ? _didYouMean : "Missing a plugin?"));
6048 }
6049 space = format.space;
6050 if (format.id.startsWith("--") && !id.startsWith("--")) {
6051 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}).`);
6052 }
6053 if (id.startsWith("--") && !format.id.startsWith("--")) {
6054 defaults.warn(`${space.name} is a standard space and supported in the CSS spec. ` + `Use color(${format.id}) instead of prefixed color(${id}).`);
6055 }
6056 } else {
6057 format = ColorSpace.findFormat({
6058 name,
6059 type: "function"
6060 });
6061 space = format.space;
6062 }
6063 if (meta) {
6064 Object.assign(meta, {
6065 format,
6066 formatId: format.name,
6067 types,
6068 commas: env.parsed.commas
6069 });
6070 }
6071 let alpha = 1;
6072 if (env.parsed.lastAlpha) {
6073 alpha = env.parsed.args.pop();
6074 if (meta) {
6075 meta.alphaType = types.pop();
6076 }
6077 }
6078 let coordCount = format.coords.length;
6079 if (coords.length !== coordCount) {
6080 throw new TypeError(`Expected ${coordCount} coordinates for ${space.id} in ${env.str}), got ${coords.length}`);
6081 }
6082 coords = format.coerceCoords(coords, types);
6083 ret = {
6084 spaceId: space.id,
6085 coords,
6086 alpha
6087 };
6088 } else {
6089 // Custom, colorspace-specific format
6090 spaceloop: for (let space of ColorSpace.all) {
6091 for (let formatId in space.formats) {
6092 let format = space.formats[formatId];
6093 if (format.type !== "custom") {
6094 continue;
6095 }
6096 if (format.test && !format.test(env.str)) {
6097 continue;
6098 }
6099
6100 // Convert to Format object
6101 let formatObject = space.getFormat(format);
6102 let color = formatObject.parse(env.str);
6103 if (color) {
6104 if (meta) {
6105 Object.assign(meta, {
6106 format: formatObject,
6107 formatId
6108 });
6109 }
6110 ret = color;
6111 break spaceloop;
6112 }
6113 }
6114 }
6115 }
6116 if (!ret) {
6117 // If we're here, we couldn't parse
6118 throw new TypeError(`Could not parse ${str} as a color. Missing a plugin?`);
6119 }
6120
6121 // Clamp alpha to [0, 1]
6122 ret.alpha = isNone(ret.alpha) ? ret.alpha : ret.alpha === undefined ? 1 : clamp(0, ret.alpha, 1);
6123 return ret;
6124 }
6125
6126 /**
6127 * Units and multiplication factors for the internally stored numbers
6128 */
6129 const units = {
6130 "%": 0.01,
6131 deg: 1,
6132 grad: 0.9,
6133 rad: 180 / Math.PI,
6134 turn: 360
6135 };
6136 const regex = {
6137 // Need to list calc(NaN) explicitly as otherwise its ending paren would terminate the function call
6138 function: /^([a-z]+)\(((?:calc\(NaN\)|.)+?)\)$/i,
6139 number: /^([-+]?(?:[0-9]*\.)?[0-9]+(e[-+]?[0-9]+)?)$/i,
6140 unitValue: RegExp(`(${Object.keys(units).join("|")})$`),
6141 // NOTE The -+ are not just for prefix, but also for idents, and e+N notation!
6142 singleArgument: /\/?\s*(none|NaN|calc\(NaN\)|[-+\w.]+(?:%|deg|g?rad|turn)?)/g
6143 };
6144
6145 /**
6146 * Parse a single function argument
6147 * @param {string} rawArg
6148 * @returns {{value: number, meta: ArgumentMeta}}
6149 */
6150 function parseArgument(rawArg) {
6151 var _rawArg$match;
6152 /** @type {Partial<ArgumentMeta>} */
6153 let meta = {};
6154 let unit = (_rawArg$match = rawArg.match(regex.unitValue)) === null || _rawArg$match === void 0 ? void 0 : _rawArg$match[0];
6155 /** @type {string | number} */
6156 let value = meta.raw = rawArg;
6157 if (unit) {
6158 // It’s a dimension token
6159 meta.type = unit === "%" ? "<percentage>" : "<angle>";
6160 meta.unit = unit;
6161 meta.unitless = Number(value.slice(0, -unit.length)); // unitless number
6162
6163 value = meta.unitless * units[unit];
6164 } else if (regex.number.test(value)) {
6165 // It's a number
6166 // Convert numerical args to numbers
6167 value = Number(value);
6168 meta.type = "<number>";
6169 } else if (value === "none") {
6170 value = null;
6171 } else if (value === "NaN" || value === "calc(NaN)") {
6172 value = NaN;
6173 meta.type = "<number>";
6174 } else {
6175 meta.type = "<ident>";
6176 }
6177 return {
6178 value: (/** @type {number} */value),
6179 meta: (/** @type {ArgumentMeta} */meta)
6180 };
6181 }
6182
6183 /**
6184 * Parse a CSS function, regardless of its name and arguments
6185 * @param {string} str String to parse
6186 * @return {ParseFunctionReturn | void}
6187 */
6188 function parseFunction(str) {
6189 if (!str) {
6190 return;
6191 }
6192 str = str.trim();
6193 let parts = str.match(regex.function);
6194 if (parts) {
6195 // It is a function, parse args
6196 let args = [];
6197 let argMeta = [];
6198 let lastAlpha = false;
6199 let name = parts[1].toLowerCase();
6200 let separators = parts[2].replace(regex.singleArgument, ($0, rawArg) => {
6201 let {
6202 value,
6203 meta
6204 } = parseArgument(rawArg);
6205 if (
6206 // If there's a slash here, it's modern syntax
6207 $0.startsWith("/") ||
6208 // 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)"
6209 name !== "color" && args.length === 3) {
6210 // It's alpha
6211 lastAlpha = true;
6212 }
6213 args.push(value);
6214 argMeta.push(meta);
6215 return "";
6216 });
6217 return {
6218 name,
6219 args,
6220 argMeta,
6221 lastAlpha,
6222 commas: separators.includes(","),
6223 rawName: parts[1],
6224 rawArgs: parts[2]
6225 };
6226 }
6227 }
6228
6229 /** @import { ColorTypes, ParseOptions as GetColorOptions, PlainColorObject } from "./types.js" */
6230
6231 /**
6232 * Resolves a color reference (object or string) to a plain color object
6233 * @overload
6234 * @param {ColorTypes} color
6235 * @param {GetColorOptions} [options]
6236 * @returns {PlainColorObject}
6237 */
6238 /**
6239 * @overload
6240 * @param {ColorTypes[]} color
6241 * @param {GetColorOptions} [options]
6242 * @returns {PlainColorObject[]}
6243 */
6244 function getColor(color, options) {
6245 if (Array.isArray(color)) {
6246 return color.map(c => getColor(c, options));
6247 }
6248 if (!color) {
6249 throw new TypeError("Empty color reference");
6250 }
6251 if (isString(color)) {
6252 color = parse(color, options);
6253 }
6254
6255 // Object fixup
6256 let space = color.space || color.spaceId;
6257 if (typeof space === "string") {
6258 // Convert string id to color space object
6259 color.space = ColorSpace.get(space);
6260 }
6261 if (color.alpha === undefined) {
6262 color.alpha = 1;
6263 }
6264 return color;
6265 }
6266
6267 const ε$7 = 0.000075;
6268
6269 /**
6270 * Class to represent a color space
6271 */
6272 class ColorSpace {
6273 constructor(options) {
6274 var _options$displaySpace, _options$coords, _ref, _options$white, _options$formats, _this$formats$color, _options$M;
6275 this.id = options.id;
6276 this.name = options.name;
6277 this.base = options.base ? ColorSpace.get(options.base) : null;
6278 this.aliases = options.aliases;
6279 this.displaySpaces = (_options$displaySpace = options.displaySpaces) === null || _options$displaySpace === void 0 ? void 0 : _options$displaySpace.map(space => ColorSpace.get(space));
6280
6281 // This space's ancestors, closest first (immediate base → root), excluding the space itself.
6282 this.bases = [];
6283 for (let base = this.base; base; base = base.base) {
6284 this.bases.push(base);
6285 }
6286 if (options.rgbGamut) {
6287 this.rgbGamut = options.rgbGamut;
6288 }
6289 if (options.linearGamut) {
6290 this.linearGamut = options.linearGamut;
6291 }
6292 if (this.base) {
6293 // Keep a subclass's own methods if the options don't override them
6294 if (options.fromBase) {
6295 this.fromBase = options.fromBase;
6296 }
6297 if (options.toBase) {
6298 this.toBase = options.toBase;
6299 }
6300 }
6301
6302 // Coordinate metadata
6303
6304 let coords = (_options$coords = options.coords) !== null && _options$coords !== void 0 ? _options$coords : this.base.coords;
6305 for (let name in coords) {
6306 if (!("name" in coords[name])) {
6307 coords[name].name = name;
6308 }
6309 }
6310 this.coords = coords;
6311
6312 // White point
6313
6314 let white = (_ref = (_options$white = options.white) !== null && _options$white !== void 0 ? _options$white : this.base.white) !== null && _ref !== void 0 ? _ref : "D65";
6315 this.white = getWhite(white);
6316
6317 // Sort out formats
6318
6319 this.formats = (_options$formats = options.formats) !== null && _options$formats !== void 0 ? _options$formats : {};
6320 for (let name in this.formats) {
6321 let format = this.formats[name];
6322 format.type || (format.type = "function");
6323 format.name || (format.name = name);
6324 }
6325 if (!((_this$formats$color = this.formats.color) !== null && _this$formats$color !== void 0 && _this$formats$color.id)) {
6326 var _this$formats$color2;
6327 this.formats.color = {
6328 ...((_this$formats$color2 = this.formats.color) !== null && _this$formats$color2 !== void 0 ? _this$formats$color2 : {}),
6329 id: options.cssId || this.id
6330 };
6331 }
6332
6333 // Gamut space
6334
6335 if (options.gamutSpace) {
6336 // Gamut space explicitly specified
6337 this.gamutSpace = options.gamutSpace === "self" ? this : ColorSpace.get(options.gamutSpace);
6338 } else {
6339 // No gamut space specified, calculate a sensible default
6340 if (this.isPolar) {
6341 // Do not check gamut through polar coordinates
6342 this.gamutSpace = this.base;
6343 } else {
6344 this.gamutSpace = this;
6345 }
6346 }
6347
6348 // Optimize inGamut for unbounded spaces
6349 if (this.gamutSpace.isUnbounded) {
6350 this.inGamut = (coords, options) => {
6351 return true;
6352 };
6353 }
6354
6355 // Matrices used by this color space, exposed so that consumer code
6356 // can reuse them instead of duplicating the data. E.g. `this.M.toXYZ`.
6357 this.M = (_options$M = options.M) !== null && _options$M !== void 0 ? _options$M : {};
6358
6359 // Other stuff
6360 this.referred = options.referred;
6361
6362 // Compute ancestors and store them, since they will never change
6363 Object.defineProperty(this, "path", {
6364 value: getPath(this).reverse(),
6365 writable: false,
6366 enumerable: true,
6367 configurable: true
6368 });
6369 hooks.run("colorspace-init-end", this);
6370 }
6371 inGamut(coords, {
6372 epsilon = ε$7
6373 } = {}) {
6374 if (!this.equals(this.gamutSpace)) {
6375 coords = this.to(this.gamutSpace, coords);
6376 return this.gamutSpace.inGamut(coords, {
6377 epsilon
6378 });
6379 }
6380 let coordMeta = Object.values(this.coords);
6381 return coords.every((c, i) => {
6382 let meta = coordMeta[i];
6383 if (meta.type !== "angle" && meta.range) {
6384 if (isNone(c)) {
6385 // NaN is always in gamut
6386 return true;
6387 }
6388 let [min, max] = meta.range;
6389 return (min === undefined || c >= min - epsilon) && (max === undefined || c <= max + epsilon);
6390 }
6391 return true;
6392 });
6393 }
6394 get isUnbounded() {
6395 return Object.values(this.coords).every(coord => !("range" in coord));
6396 }
6397 get cssId() {
6398 var _this$formats;
6399 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;
6400 }
6401
6402 /**
6403 * The id of this space's hue coordinate, or null if the space is not polar
6404 * @returns {string | null}
6405 */
6406 get hueId() {
6407 for (let id in this.coords) {
6408 if (this.coords[id].type === "angle") {
6409 return id;
6410 }
6411 }
6412 return null;
6413 }
6414
6415 /**
6416 * The index of this space's hue coordinate within its coords array, or -1 if the space is not polar
6417 * @returns {number}
6418 */
6419 get hueIndex() {
6420 return Object.keys(this.coords).findIndex(id => this.coords[id].type === "angle");
6421 }
6422 get isPolar() {
6423 return this.hueId !== null;
6424 }
6425
6426 /**
6427 * Lookup a format in this color space
6428 * @param {string | object | Format} format - Format id if string. If object, it's converted to a `Format` object and returned.
6429 * @returns {Format}
6430 */
6431 getFormat(format) {
6432 if (!format) {
6433 return null;
6434 }
6435 if (format === "default") {
6436 format = Object.values(this.formats)[0];
6437 } else if (typeof format === "string") {
6438 format = this.formats[format];
6439 }
6440 let ret = Format.get(format, this);
6441 if (ret !== format && format.name in this.formats) {
6442 // Update the format we have on file so we can find it more quickly next time
6443 this.formats[format.name] = ret;
6444 }
6445 return ret;
6446 }
6447
6448 /**
6449 * Check if this color space is the same as another color space reference.
6450 * Allows proxying color space objects and comparing color spaces with ids.
6451 * @param {string | ColorSpace} space ColorSpace object or id to compare to
6452 * @returns {boolean}
6453 */
6454 equals(space) {
6455 if (!space) {
6456 return false;
6457 }
6458 return this === space || this.id === space || this.id === space.id;
6459 }
6460 to(space, coords) {
6461 if (arguments.length === 1) {
6462 const color = getColor(space);
6463 [space, coords] = [color.space, color.coords];
6464 }
6465 space = ColorSpace.get(space);
6466 if (this.equals(space)) {
6467 // Same space, no change needed
6468 return coords;
6469 }
6470
6471 // Convert NaN to 0, which seems to be valid in every coordinate of every color space
6472 coords = coords.map(c => isNone(c) ? 0 : c);
6473
6474 // Find connection space = lowest common ancestor in the base tree
6475 let myPath = this.path;
6476 let otherPath = space.path;
6477 let connectionSpace, connectionSpaceIndex;
6478 for (let i = 0; i < myPath.length; i++) {
6479 if (myPath[i].equals(otherPath[i])) {
6480 connectionSpace = myPath[i];
6481 connectionSpaceIndex = i;
6482 } else {
6483 break;
6484 }
6485 }
6486 if (!connectionSpace) {
6487 // This should never happen
6488 throw new Error(`Cannot convert between color spaces ${this} and ${space}: no connection space was found`);
6489 }
6490
6491 // Go up from current space to connection space
6492 for (let i = myPath.length - 1; i > connectionSpaceIndex; i--) {
6493 coords = myPath[i].toBase(coords);
6494 }
6495
6496 // Go down from connection space to target space
6497 for (let i = connectionSpaceIndex + 1; i < otherPath.length; i++) {
6498 coords = otherPath[i].fromBase(coords);
6499 }
6500 return coords;
6501 }
6502 from(space, coords) {
6503 if (arguments.length === 1) {
6504 const color = getColor(space);
6505 [space, coords] = [color.space, color.coords];
6506 }
6507 space = ColorSpace.get(space);
6508 return space.to(this, coords);
6509 }
6510 toString() {
6511 return `${this.name} (${this.id})`;
6512 }
6513 getMinCoords() {
6514 let ret = [];
6515 for (let id in this.coords) {
6516 var _range$min;
6517 let meta = this.coords[id];
6518 let range = meta.range || meta.refRange;
6519 ret.push((_range$min = range === null || range === void 0 ? void 0 : range.min) !== null && _range$min !== void 0 ? _range$min : 0);
6520 }
6521 return ret;
6522 }
6523 static registry = {};
6524
6525 // Returns array of unique color spaces
6526 static get all() {
6527 return [...new Set(Object.values(ColorSpace.registry))];
6528 }
6529 static register(id, space) {
6530 if (arguments.length === 1) {
6531 space = arguments[0];
6532 id = space.id;
6533 }
6534 space = this.get(space);
6535 if (this.registry[id] && this.registry[id] !== space) {
6536 throw new Error(`Duplicate color space registration: '${id}'`);
6537 }
6538 this.registry[id] = space;
6539
6540 // Register aliases when called without an explicit ID.
6541 if (arguments.length === 1 && space.aliases) {
6542 for (let alias of space.aliases) {
6543 this.register(alias, space);
6544 }
6545 }
6546 return space;
6547 }
6548
6549 /**
6550 * Lookup ColorSpace object by name
6551 * @param {ColorSpace | string} name
6552 */
6553 static get(space, ...alternatives) {
6554 if (!space || isInstance(space, this)) {
6555 return space;
6556 }
6557 let argType = type(space);
6558 if (argType === "string") {
6559 // It's a color space id
6560 let ret = ColorSpace.registry[space.toLowerCase()];
6561 if (!ret) {
6562 throw new TypeError(`No color space found with id = "${space}"`);
6563 }
6564 return ret;
6565 }
6566 if (alternatives.length) {
6567 return ColorSpace.get(...alternatives);
6568 }
6569 throw new TypeError(`${space} is not a valid color space`);
6570 }
6571
6572 /**
6573 * Look up all color spaces for a format that matches certain criteria
6574 * @param {object | string} filters
6575 * @param {Array<ColorSpace>} [spaces=ColorSpace.all]
6576 * @returns {Format | null}
6577 */
6578 static findFormat(filters, spaces = ColorSpace.all) {
6579 if (!filters) {
6580 return null;
6581 }
6582 if (typeof filters === "string") {
6583 filters = {
6584 name: filters
6585 };
6586 }
6587 for (let space of spaces) {
6588 for (let [name, format] of Object.entries(space.formats)) {
6589 var _format$name, _format$type;
6590 (_format$name = format.name) !== null && _format$name !== void 0 ? _format$name : format.name = name;
6591 (_format$type = format.type) !== null && _format$type !== void 0 ? _format$type : format.type = "function";
6592 let matches = (!filters.name || format.name === filters.name) && (!filters.type || format.type === filters.type);
6593 if (filters.id) {
6594 let ids = format.ids || [format.id];
6595 let filterIds = Array.isArray(filters.id) ? filters.id : [filters.id];
6596 matches && (matches = filterIds.some(id => ids.includes(id)));
6597 }
6598 if (matches) {
6599 let ret = Format.get(format, space);
6600 if (ret !== format) {
6601 space.formats[format.name] = ret;
6602 }
6603 return ret;
6604 }
6605 }
6606 }
6607 return null;
6608 }
6609
6610 /**
6611 * Get metadata about a coordinate of a color space
6612 *
6613 * @static
6614 * @param {Array | string} ref
6615 * @param {ColorSpace | string} [workingSpace]
6616 * @return {Object}
6617 */
6618 static resolveCoord(ref, workingSpace) {
6619 let coordType = type(ref);
6620 let space, coord;
6621 if (coordType === "string") {
6622 if (ref.includes(".")) {
6623 // Absolute coordinate
6624 [space, coord] = ref.split(".");
6625 } else {
6626 // Relative coordinate
6627 [space, coord] = [, ref];
6628 }
6629 } else if (Array.isArray(ref)) {
6630 [space, coord] = ref;
6631 } else {
6632 // Object
6633 space = ref.space;
6634 coord = ref.coordId;
6635 }
6636 space = ColorSpace.get(space);
6637 if (!space) {
6638 space = workingSpace;
6639 }
6640 if (!space) {
6641 throw new TypeError(`Cannot resolve coordinate reference ${ref}: No color space specified and relative references are not allowed here`);
6642 }
6643 coordType = type(coord);
6644 if (coordType === "number" || coordType === "string" && coord >= 0) {
6645 // Resolve numerical coord
6646 let meta = Object.entries(space.coords)[coord];
6647 if (meta) {
6648 return {
6649 space,
6650 id: meta[0],
6651 index: coord,
6652 ...meta[1]
6653 };
6654 }
6655 }
6656 space = ColorSpace.get(space);
6657 let normalizedCoord = coord.toLowerCase();
6658 let i = 0;
6659 for (let id in space.coords) {
6660 var _meta$name;
6661 let meta = space.coords[id];
6662 if (id.toLowerCase() === normalizedCoord || ((_meta$name = meta.name) === null || _meta$name === void 0 ? void 0 : _meta$name.toLowerCase()) === normalizedCoord) {
6663 return {
6664 space,
6665 id,
6666 index: i,
6667 ...meta
6668 };
6669 }
6670 i++;
6671 }
6672 throw new TypeError(`No "${coord}" coordinate found in ${space.name}. Its coordinates are: ${Object.keys(space.coords).join(", ")}`);
6673 }
6674 static DEFAULT_FORMAT = {
6675 type: "functions",
6676 name: "color"
6677 };
6678 }
6679 function getPath(space) {
6680 let ret = [space];
6681 for (let s = space; s = s.base;) {
6682 ret.push(s);
6683 }
6684 return ret;
6685 }
6686
6687 var XYZ_D65 = new ColorSpace({
6688 id: "xyz-d65",
6689 name: "XYZ D65",
6690 coords: {
6691 x: {
6692 refRange: [0, 1],
6693 name: "X"
6694 },
6695 y: {
6696 refRange: [0, 1],
6697 name: "Y"
6698 },
6699 z: {
6700 refRange: [0, 1],
6701 name: "Z"
6702 }
6703 },
6704 white: "D65",
6705 formats: {
6706 color: {
6707 ids: ["xyz-d65", "xyz"]
6708 }
6709 },
6710 aliases: ["xyz"]
6711 });
6712
6713 // Type re-exports
6714 /** @typedef {import("./types.js").RGBOptions} RGBOptions */
6715
6716 /** Convenience class for RGB color spaces */
6717 class RGBColorSpace extends ColorSpace {
6718 /**
6719 * Creates a new RGB ColorSpace.
6720 * If coords are not specified, they will use the default RGB coords.
6721 * Instead of `fromBase()` and `toBase()` functions,
6722 * you can specify to/from XYZ matrices and have the default `toBase()` and `fromBase()`
6723 * methods use them via `this.M.toXYZ` and `this.M.fromXYZ`.
6724 * @param {RGBOptions} options
6725 */
6726 constructor(options) {
6727 var _options$toXYZ_M, _options$M, _options$fromXYZ_M, _options$M2, _options$referred;
6728 if (!options.coords) {
6729 options.coords = {
6730 r: {
6731 range: [0, 1],
6732 name: "Red"
6733 },
6734 g: {
6735 range: [0, 1],
6736 name: "Green"
6737 },
6738 b: {
6739 range: [0, 1],
6740 name: "Blue"
6741 }
6742 };
6743 }
6744 if (!options.base) {
6745 options.base = XYZ_D65;
6746 }
6747
6748 // Accept matrices either as dedicated options or via the generic `M` object
6749 let toXYZ = (_options$toXYZ_M = options.toXYZ_M) !== null && _options$toXYZ_M !== void 0 ? _options$toXYZ_M : (_options$M = options.M) === null || _options$M === void 0 ? void 0 : _options$M.toXYZ;
6750 let fromXYZ = (_options$fromXYZ_M = options.fromXYZ_M) !== null && _options$fromXYZ_M !== void 0 ? _options$fromXYZ_M : (_options$M2 = options.M) === null || _options$M2 === void 0 ? void 0 : _options$M2.fromXYZ;
6751 (_options$referred = options.referred) !== null && _options$referred !== void 0 ? _options$referred : options.referred = "display";
6752 super(options);
6753
6754 // Expose the matrices on the color space (via `this.M`) so consumers can reuse them.
6755 if (toXYZ && fromXYZ) {
6756 this.M.toXYZ = toXYZ;
6757 this.M.fromXYZ = fromXYZ;
6758 }
6759 }
6760 toBase(rgb) {
6761 let xyz = multiply_v3_m3x3(rgb, this.M.toXYZ);
6762 if (this.white !== this.base.white) {
6763 // Perform chromatic adaptation
6764 xyz = adapt$2(this.white, this.base.white, xyz);
6765 }
6766 return xyz;
6767 }
6768 fromBase(xyz) {
6769 xyz = adapt$2(this.base.white, this.white, xyz);
6770 return multiply_v3_m3x3(xyz, this.M.fromXYZ);
6771 }
6772 }
6773
6774 var XYZ_D50 = new ColorSpace({
6775 id: "xyz-d50",
6776 name: "XYZ D50",
6777 white: "D50",
6778 base: XYZ_D65,
6779 fromBase: coords => adapt$2(XYZ_D65.white, "D50", coords),
6780 toBase: coords => adapt$2("D50", XYZ_D65.white, coords)
6781 });
6782
6783 // κ * ε = 2^3 = 8
6784 const ε$6 = 216 / 24389; // 6^3/29^3 == (24/116)^3
6785 const ε3$1 = 24 / 116;
6786 const κ$4 = 24389 / 27; // 29^3/3^3
6787
6788 let white$4 = WHITES.D50;
6789 var lab = new ColorSpace({
6790 id: "lab",
6791 name: "Lab",
6792 coords: {
6793 l: {
6794 refRange: [0, 100],
6795 name: "Lightness"
6796 },
6797 a: {
6798 refRange: [-125, 125]
6799 },
6800 b: {
6801 refRange: [-125, 125]
6802 }
6803 },
6804 // Assuming XYZ is relative to D50, convert to CIE Lab
6805 // from CIE standard, which now defines these as a rational fraction
6806 white: white$4,
6807 base: XYZ_D50,
6808 // Convert D50-adapted XYX to Lab
6809 // CIE 15.3:2004 section 8.2.1.1
6810 fromBase(XYZ) {
6811 // XYZ scaled relative to reference white
6812 let xyz = XYZ.map((value, i) => value / white$4[i]);
6813 let f = xyz.map(value => value > ε$6 ? Math.cbrt(value) : (κ$4 * value + 16) / 116);
6814 let L = 116 * f[1] - 16;
6815 let a = 500 * (f[0] - f[1]);
6816 let b = 200 * (f[1] - f[2]);
6817 return [L, a, b];
6818 },
6819 // Convert Lab to D50-adapted XYZ
6820 // Same result as CIE 15.3:2004 Appendix D although the derivation is different
6821 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
6822 toBase(Lab) {
6823 // compute f, starting with the luminance-related term
6824 let [L, a, b] = Lab;
6825 let f = [];
6826 f[1] = (L + 16) / 116;
6827 f[0] = a / 500 + f[1];
6828 f[2] = f[1] - b / 200;
6829
6830 // compute xyz
6831 // prettier-ignore
6832 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];
6833
6834 // Compute XYZ by scaling xyz by reference white
6835 return xyz.map((value, i) => value * white$4[i]);
6836 },
6837 formats: {
6838 lab: {
6839 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
6840 }
6841 }
6842 });
6843
6844 /**
6845 * Constrain an angle to 360 degrees
6846 * @param {number} angle
6847 * @returns {number}
6848 */
6849 function constrain(angle) {
6850 if (typeof angle !== "number") {
6851 return angle;
6852 }
6853 return (angle % 360 + 360) % 360;
6854 }
6855
6856 /**
6857 * @param {"raw" | "increasing" | "decreasing" | "longer" | "shorter"} arc
6858 * @param {[number, number]} angles
6859 * @returns {[number, number]}
6860 */
6861 function adjust(arc, angles) {
6862 let [a1, a2] = angles;
6863 let none1 = isNone(a1);
6864 let none2 = isNone(a2);
6865 if (none1 && none2) {
6866 return [a1, a2];
6867 } else if (none1) {
6868 a1 = a2;
6869 } else if (none2) {
6870 a2 = a1;
6871 }
6872 if (arc === "raw") {
6873 return angles;
6874 }
6875 a1 = constrain(a1);
6876 a2 = constrain(a2);
6877 let angleDiff = a2 - a1;
6878 if (arc === "increasing") {
6879 if (angleDiff < 0) {
6880 a2 += 360;
6881 }
6882 } else if (arc === "decreasing") {
6883 if (angleDiff > 0) {
6884 a1 += 360;
6885 }
6886 } else if (arc === "longer") {
6887 if (-180 < angleDiff && angleDiff < 180) {
6888 if (angleDiff > 0) {
6889 a1 += 360;
6890 } else {
6891 a2 += 360;
6892 }
6893 }
6894 } else if (arc === "shorter") {
6895 if (angleDiff > 180) {
6896 a1 += 360;
6897 } else if (angleDiff < -180) {
6898 a2 += 360;
6899 }
6900 }
6901 return [a1, a2];
6902 }
6903
6904 var lch = new ColorSpace({
6905 id: "lch",
6906 name: "LCH",
6907 coords: {
6908 l: {
6909 refRange: [0, 100],
6910 name: "Lightness"
6911 },
6912 c: {
6913 refRange: [0, 150],
6914 name: "Chroma"
6915 },
6916 h: {
6917 refRange: [0, 360],
6918 type: "angle",
6919 name: "Hue"
6920 }
6921 },
6922 base: lab,
6923 fromBase(Lab) {
6924 // These methods are used for other polar forms as well, so we can't hardcode the ε
6925 if (this.ε === undefined) {
6926 // @ts-expect-error Property 'coords' does not exist on type 'string | ColorSpace'
6927 let range = Object.values(this.base.coords)[1].refRange;
6928 let extent = range[1] - range[0];
6929 this.ε = extent / 100000;
6930 }
6931
6932 // Convert to polar form
6933 let [L, a, b] = Lab;
6934 let isAchromatic = Math.abs(a) < this.ε && Math.abs(b) < this.ε;
6935 let h = isAchromatic ? null : constrain(Math.atan2(b, a) * 180 / Math.PI);
6936 let C = isAchromatic ? 0 : Math.sqrt(a ** 2 + b ** 2);
6937 return [L, C, h];
6938 },
6939 toBase(lch) {
6940 // Convert from polar form
6941 let [L, C, h] = lch;
6942 let a = null,
6943 b = null;
6944 if (!isNone(h)) {
6945 C = C < 0 ? 0 : C; // Clamp negative Chroma
6946 a = C * Math.cos(h * Math.PI / 180);
6947 b = C * Math.sin(h * Math.PI / 180);
6948 }
6949 return [L, a, b];
6950 },
6951 formats: {
6952 lch: {
6953 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
6954 }
6955 }
6956 });
6957
6958 // deltaE2000 is a statistically significant improvement
6959 // and is recommended by the CIE and Idealliance
6960 // especially for color differences less than 10 deltaE76
6961 // but is wicked complicated
6962 // and many implementations have small errors!
6963 // DeltaE2000 is also discontinuous; in case this
6964 // matters to you, use deltaECMC instead.
6965
6966 const Gfactor = 25 ** 7;
6967 const π$1 = Math.PI;
6968 const r2d = 180 / π$1;
6969 const d2r$1 = π$1 / 180;
6970 function pow7(x) {
6971 // Faster than x ** 7 or Math.pow(x, 7)
6972
6973 const x2 = x * x;
6974 const x7 = x2 * x2 * x2 * x;
6975 return x7;
6976 }
6977
6978 /**
6979 * @param {import("../types.js").ColorTypes} color
6980 * @param {import("../types.js").ColorTypes} sample
6981 * @param {{ kL?: number | undefined; kC?: number | undefined; kH?: number | undefined }} options
6982 * @returns {number}
6983 */
6984 function deltaE2000 (color, sample, {
6985 kL = 1,
6986 kC = 1,
6987 kH = 1
6988 } = {}) {
6989 [color, sample] = getColor([color, sample]);
6990
6991 // Given this color as the reference
6992 // and the function parameter as the sample,
6993 // calculate deltaE 2000.
6994
6995 // This implementation assumes the parametric
6996 // weighting factors kL, kC and kH
6997 // for the influence of viewing conditions
6998 // are all 1, as sadly seems typical.
6999 // kL should be increased for lightness texture or noise
7000 // and kC increased for chroma noise
7001
7002 let [L1, a1, b1] = lab.from(color);
7003 let C1 = lch.from(lab, [L1, a1, b1])[1];
7004 let [L2, a2, b2] = lab.from(sample);
7005 let C2 = lch.from(lab, [L2, a2, b2])[1];
7006
7007 // Check for negative Chroma,
7008 // which might happen through
7009 // direct user input of LCH values
7010
7011 if (C1 < 0) {
7012 C1 = 0;
7013 }
7014 if (C2 < 0) {
7015 C2 = 0;
7016 }
7017 let Cbar = (C1 + C2) / 2; // mean Chroma
7018
7019 // calculate a-axis asymmetry factor from mean Chroma
7020 // this turns JND ellipses for near-neutral colors back into circles
7021 let C7 = pow7(Cbar);
7022 let G = 0.5 * (1 - Math.sqrt(C7 / (C7 + Gfactor)));
7023
7024 // scale a axes by asymmetry factor
7025 // this by the way is why there is no Lab2000 colorspace
7026 let adash1 = (1 + G) * a1;
7027 let adash2 = (1 + G) * a2;
7028
7029 // calculate new Chroma from scaled a and original b axes
7030 let Cdash1 = Math.sqrt(adash1 ** 2 + b1 ** 2);
7031 let Cdash2 = Math.sqrt(adash2 ** 2 + b2 ** 2);
7032
7033 // calculate new hues, with zero hue for true neutrals
7034 // and in degrees, not radians
7035
7036 let h1 = adash1 === 0 && b1 === 0 ? 0 : Math.atan2(b1, adash1);
7037 let h2 = adash2 === 0 && b2 === 0 ? 0 : Math.atan2(b2, adash2);
7038 if (h1 < 0) {
7039 h1 += 2 * π$1;
7040 }
7041 if (h2 < 0) {
7042 h2 += 2 * π$1;
7043 }
7044 h1 *= r2d;
7045 h2 *= r2d;
7046
7047 // Lightness and Chroma differences; sign matters
7048 let ΔL = L2 - L1;
7049 let ΔC = Cdash2 - Cdash1;
7050
7051 // Hue difference, getting the sign correct
7052 let hdiff = h2 - h1;
7053 let hsum = h1 + h2;
7054 let habs = Math.abs(hdiff);
7055 let Δh;
7056 if (Cdash1 * Cdash2 === 0) {
7057 Δh = 0;
7058 } else if (habs <= 180) {
7059 Δh = hdiff;
7060 } else if (hdiff > 180) {
7061 Δh = hdiff - 360;
7062 } else if (hdiff < -180) {
7063 Δh = hdiff + 360;
7064 } else {
7065 defaults.warn("the unthinkable has happened");
7066 }
7067
7068 // weighted Hue difference, more for larger Chroma
7069 let ΔH = 2 * Math.sqrt(Cdash2 * Cdash1) * Math.sin(Δh * d2r$1 / 2);
7070
7071 // calculate mean Lightness and Chroma
7072 let Ldash = (L1 + L2) / 2;
7073 let Cdash = (Cdash1 + Cdash2) / 2;
7074 let Cdash7 = pow7(Cdash);
7075
7076 // Compensate for non-linearity in the blue region of Lab.
7077 // Four possibilities for hue weighting factor,
7078 // depending on the angles, to get the correct sign
7079 let hdash;
7080 if (Cdash1 * Cdash2 === 0) {
7081 hdash = hsum; // which should be zero
7082 } else if (habs <= 180) {
7083 hdash = hsum / 2;
7084 } else if (hsum < 360) {
7085 hdash = (hsum + 360) / 2;
7086 } else {
7087 hdash = (hsum - 360) / 2;
7088 }
7089
7090 // positional corrections to the lack of uniformity of CIELAB
7091 // These are all trying to make JND ellipsoids more like spheres
7092
7093 // SL Lightness crispening factor
7094 // a background with L=50 is assumed
7095 let lsq = (Ldash - 50) ** 2;
7096 let SL = 1 + 0.015 * lsq / Math.sqrt(20 + lsq);
7097
7098 // SC Chroma factor, similar to those in CMC and deltaE 94 formulae
7099 let SC = 1 + 0.045 * Cdash;
7100
7101 // Cross term T for blue non-linearity
7102 let T = 1;
7103 T -= 0.17 * Math.cos((hdash - 30) * d2r$1);
7104 T += 0.24 * Math.cos(2 * hdash * d2r$1);
7105 T += 0.32 * Math.cos((3 * hdash + 6) * d2r$1);
7106 T -= 0.2 * Math.cos((4 * hdash - 63) * d2r$1);
7107
7108 // SH Hue factor depends on Chroma,
7109 // as well as adjusted hue angle like deltaE94.
7110 let SH = 1 + 0.015 * Cdash * T;
7111
7112 // RT Hue rotation term compensates for rotation of JND ellipses
7113 // and Munsell constant hue lines
7114 // in the medium-high Chroma blue region
7115 // (Hue 225 to 315)
7116 let Δθ = 30 * Math.exp(-1 * ((hdash - 275) / 25) ** 2);
7117 let RC = 2 * Math.sqrt(Cdash7 / (Cdash7 + Gfactor));
7118 let RT = -1 * Math.sin(2 * Δθ * d2r$1) * RC;
7119
7120 // Finally calculate the deltaE, term by term as root sume of squares
7121 let dE = (ΔL / (kL * SL)) ** 2;
7122 dE += (ΔC / (kC * SC)) ** 2;
7123 dE += (ΔH / (kH * SH)) ** 2;
7124 dE += RT * (ΔC / (kC * SC)) * (ΔH / (kH * SH));
7125 return Math.sqrt(dE);
7126 // Yay!!!
7127 }
7128
7129 /** @import { Matrix3x3 } from "../types.js" */
7130
7131 /**
7132 * Matrices used by this color space, also available as `Oklab.M`.
7133 * Recalculated for consistent reference white,
7134 * see https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-943521484
7135 * @type {Record<string, Matrix3x3>}
7136 */
7137 // prettier-ignore
7138 const M$d = {
7139 XYZtoLMS: [[0.8190224379967030, 0.3619062600528904, -0.1288737815209879], [0.0329836539323885, 0.9292868615863434, 0.0361446663506424], [0.0481771893596242, 0.2642395317527308, 0.6335478284694309]],
7140 // inverse of XYZtoLMS
7141 LMStoXYZ: [[1.2268798758459243, -0.5578149944602171, 0.2813910456659647], [-0.0405757452148008, 1.1122868032803170, -0.0717110580655164], [-0.0763729366746601, -0.4214933324022432, 1.5869240198367816]],
7142 LMStoLab: [[0.2104542683093140, 0.7936177747023054, -0.0040720430116193], [1.9779985324311684, -2.4285922420485799, 0.4505937096174110], [0.0259040424655478, 0.7827717124575296, -0.8086757549230774]],
7143 // LMStoLab inverted
7144 LabtoLMS: [[1.0000000000000000, 0.3963377773761749, 0.2158037573099136], [1.0000000000000000, -0.1055613458156586, -0.0638541728258133], [1.0000000000000000, -0.0894841775298119, -1.2914855480194092]]
7145 };
7146 var Oklab = new ColorSpace({
7147 id: "oklab",
7148 name: "Oklab",
7149 coords: {
7150 l: {
7151 refRange: [0, 1],
7152 name: "Lightness"
7153 },
7154 a: {
7155 refRange: [-0.4, 0.4]
7156 },
7157 b: {
7158 refRange: [-0.4, 0.4]
7159 }
7160 },
7161 // Note that XYZ is relative to D65
7162 white: "D65",
7163 base: XYZ_D65,
7164 M: M$d,
7165 fromBase(XYZ) {
7166 // move to LMS cone domain
7167 let LMS = multiply_v3_m3x3(XYZ, M$d.XYZtoLMS);
7168
7169 // non-linearity
7170 LMS[0] = Math.cbrt(LMS[0]);
7171 LMS[1] = Math.cbrt(LMS[1]);
7172 LMS[2] = Math.cbrt(LMS[2]);
7173 return multiply_v3_m3x3(LMS, M$d.LMStoLab, LMS);
7174 },
7175 toBase(OKLab) {
7176 // move to LMS cone domain
7177 let LMSg = multiply_v3_m3x3(OKLab, M$d.LabtoLMS);
7178
7179 // restore linearity
7180 LMSg[0] = LMSg[0] ** 3;
7181 LMSg[1] = LMSg[1] ** 3;
7182 LMSg[2] = LMSg[2] ** 3;
7183 return multiply_v3_m3x3(LMSg, M$d.LMStoXYZ, LMSg);
7184 },
7185 formats: {
7186 oklab: {
7187 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
7188 }
7189 }
7190 });
7191
7192 /**
7193 * More accurate color-difference formulae
7194 * than the simple 1976 Euclidean distance in CIE Lab
7195 * @param {import("../types.js").ColorTypes} color
7196 * @param {import("../types.js").ColorTypes} sample
7197 * @returns {number}
7198 */
7199 function deltaEOK (color, sample) {
7200 [color, sample] = getColor([color, sample]);
7201
7202 // Given this color as the reference
7203 // and a sample,
7204 // calculate deltaEOK, term by term as root sum of squares
7205 let [L1, a1, b1] = Oklab.from(color);
7206 let [L2, a2, b2] = Oklab.from(sample);
7207 let ΔL = L1 - L2;
7208 let Δa = a1 - a2;
7209 let Δb = b1 - b2;
7210 return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2);
7211 }
7212
7213 /** @import { ColorTypes } from "./types.js" */
7214
7215 const ε$5 = 0.000075;
7216
7217 /**
7218 * Check if a color is in gamut of either its own or another color space
7219 * @param {ColorTypes} color
7220 * @param {string | ColorSpace} [space]
7221 * @param {{ epsilon?: number | undefined }} [param2]
7222 * @returns {boolean}
7223 */
7224 function inGamut(color, space, {
7225 epsilon = ε$5
7226 } = {}) {
7227 color = getColor(color);
7228 if (!space) {
7229 space = color.space;
7230 }
7231 space = ColorSpace.get(space);
7232 let coords = color.coords;
7233 if (space !== color.space) {
7234 coords = space.from(color);
7235 }
7236 return space.inGamut(coords, {
7237 epsilon
7238 });
7239 }
7240
7241 /** @import { ColorTypes, PlainColorObject, ToGamutOptions } from "./types.js" */
7242
7243 /**
7244 * Convert to color space and return a new color
7245 * @param {ColorTypes} color
7246 * @param {string | ColorSpace} space
7247 * @param {{ inGamut?: boolean | ToGamutOptions | undefined }} options
7248 * @returns {PlainColorObject}
7249 */
7250 function to(color, space, {
7251 inGamut
7252 } = {}) {
7253 color = getColor(color);
7254 space = ColorSpace.get(space);
7255 let coords = space.from(color);
7256 let ret = {
7257 space,
7258 coords,
7259 alpha: color.alpha
7260 };
7261 if (inGamut) {
7262 ret = toGamut(ret, inGamut === true ? undefined : inGamut);
7263 }
7264 return ret;
7265 }
7266
7267 /** @type {"color"} */
7268 to.returns = "color";
7269
7270 /** @import { ColorTypes, Coords } from "./types.js" */
7271
7272 /**
7273 * Options for {@link getAll}
7274 * @typedef GetAllOptions
7275 * @property {string | ColorSpace | undefined} [space]
7276 * The color space to convert to. Defaults to the color's current space
7277 * @property {number | undefined} [precision]
7278 * The number of significant digits to round the coordinates to
7279 */
7280
7281 /**
7282 * Get the coordinates of a color in any color space
7283 * @overload
7284 * @param {ColorTypes} color
7285 * @param {string | ColorSpace} [options=color.space] The color space to convert to. Defaults to the color's current space
7286 * @returns {Coords} The color coordinates in the given color space
7287 */
7288 /**
7289 * @overload
7290 * @param {ColorTypes} color
7291 * @param {GetAllOptions} [options]
7292 * @returns {Coords} The color coordinates in the given color space
7293 */
7294 function getAll(color, options) {
7295 color = getColor(color);
7296 let space = ColorSpace.get(options, options === null || options === void 0 ? void 0 : options.space);
7297 let precision = options === null || options === void 0 ? void 0 : options.precision;
7298 let coords;
7299 if (!space || color.space.equals(space)) {
7300 // No conversion needed
7301 coords = color.coords.slice();
7302 } else {
7303 coords = space.from(color);
7304 }
7305 return precision === undefined ? coords : coords.map(coord => toPrecision(coord, precision));
7306 }
7307
7308 /** @import { ColorTypes, Ref } from "./types.js" */
7309
7310 /**
7311 * @param {ColorTypes} color
7312 * @param {Ref} prop
7313 * @returns {number}
7314 */
7315 function get(color, prop) {
7316 color = getColor(color);
7317 if (prop === "alpha") {
7318 var _color$alpha;
7319 return (_color$alpha = color.alpha) !== null && _color$alpha !== void 0 ? _color$alpha : 1;
7320 }
7321 let {
7322 space,
7323 index
7324 } = ColorSpace.resolveCoord(prop, color.space);
7325 let coords = getAll(color, space);
7326 return coords[index];
7327 }
7328
7329 var OKLCH = new ColorSpace({
7330 id: "oklch",
7331 name: "OkLCh",
7332 coords: {
7333 l: {
7334 refRange: [0, 1],
7335 name: "Lightness"
7336 },
7337 c: {
7338 refRange: [0, 0.4],
7339 name: "Chroma"
7340 },
7341 h: {
7342 refRange: [0, 360],
7343 type: "angle",
7344 name: "Hue"
7345 }
7346 },
7347 white: "D65",
7348 base: Oklab,
7349 fromBase: lch.fromBase,
7350 toBase: lch.toBase,
7351 formats: {
7352 oklch: {
7353 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
7354 }
7355 }
7356 });
7357
7358 /** @import { ColorTypes, Coords, PlainColorObject } from "./types.js" */
7359
7360 /**
7361 * Set all coordinates of a color at once, in its own color space or another.
7362 * Modifies the color in place.
7363 * @overload
7364 * @param {ColorTypes} color
7365 * @param {Coords} coords Array of coordinates
7366 * @param {number} [alpha]
7367 * @returns {PlainColorObject}
7368 */
7369 /**
7370 * @overload
7371 * @param {ColorTypes} color
7372 * @param {string | ColorSpace} space The color space of the provided coordinates.
7373 * @param {Coords} coords Array of coordinates
7374 * @param {number} [alpha]
7375 * @returns {PlainColorObject}
7376 */
7377 function setAll(color, space, coords, alpha) {
7378 color = getColor(color);
7379 if (Array.isArray(space)) {
7380 // Space is omitted
7381 [space, coords, alpha] = [color.space, space, coords];
7382 }
7383 space = ColorSpace.get(space); // Make sure we have a ColorSpace object
7384 color.coords = space === color.space ? coords.slice() : space.to(color.space, coords);
7385 if (alpha !== undefined) {
7386 color.alpha = alpha;
7387 }
7388 return color;
7389 }
7390
7391 /** @type {"color"} */
7392 setAll.returns = "color";
7393
7394 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
7395
7396 /**
7397 * Set properties and return current instance
7398 * @overload
7399 * @param {ColorTypes} color
7400 * @param {Ref} prop
7401 * @param {number | ((coord: number) => number)} value
7402 * @returns {PlainColorObject}
7403 */
7404 /**
7405 * @overload
7406 * @param {ColorTypes} color
7407 * @param {Record<string, number | ((coord: number) => number)>} props
7408 * @returns {PlainColorObject}
7409 */
7410 function set(color, prop, value) {
7411 color = getColor(color);
7412 if (arguments.length === 2 && type(arguments[1]) === "object") {
7413 // Argument is an object literal
7414 let object = arguments[1];
7415 for (let p in object) {
7416 set(color, p, object[p]);
7417 }
7418 } else {
7419 if (typeof value === "function") {
7420 value = value(get(color, prop));
7421 }
7422 if (prop === "alpha") {
7423 color.alpha = value;
7424 } else {
7425 let {
7426 space,
7427 index
7428 } = ColorSpace.resolveCoord(prop, color.space);
7429 let coords = getAll(color, space);
7430 coords[index] = value;
7431 setAll(color, space, coords);
7432 }
7433 }
7434 return color;
7435 }
7436
7437 /** @type {"color"} */
7438 set.returns = "color";
7439
7440 /** @import { Coords, PlainColorObject } from "./types.js" */
7441
7442 /**
7443 * @param {PlainColorObject} color
7444 * @returns {PlainColorObject}
7445 */
7446 function clone(color) {
7447 return {
7448 space: color.space,
7449 coords: (/** @type {Coords} */color.coords.slice()),
7450 alpha: color.alpha
7451 };
7452 }
7453
7454 /** @import { ColorTypes } from "./types.js" */
7455
7456 /**
7457 * Euclidean distance of colors in an arbitrary color space
7458 * @param {ColorTypes} color1
7459 * @param {ColorTypes} color2
7460 * @param {string | ColorSpace} space
7461 * @returns {number}
7462 */
7463 function distance(color1, color2, space = "lab") {
7464 space = ColorSpace.get(space);
7465
7466 // Assume getColor() is called on color in space.from()
7467 let coords1 = space.from(color1);
7468 let coords2 = space.from(color2);
7469 return Math.sqrt(coords1.reduce((acc, c1, i) => {
7470 let c2 = coords2[i];
7471 if (isNone(c1) || isNone(c2)) {
7472 return acc;
7473 }
7474 return acc + (c2 - c1) ** 2;
7475 }, 0));
7476 }
7477
7478 /**
7479 * @param {import("../types.js").ColorTypes} color
7480 * @param {import("../types.js").ColorTypes} sample
7481 * @returns {number}
7482 */
7483 function deltaE76(color, sample) {
7484 // Assume getColor() is called in the distance function
7485 return distance(color, sample, "lab");
7486 }
7487
7488 // More accurate color-difference formulae
7489 // than the simple 1976 Euclidean distance in Lab
7490
7491 // CMC by the Color Measurement Committee of the
7492 // Bradford Society of Dyeists and Colorsts, 1994.
7493 // Uses LCH rather than Lab,
7494 // with different weights for L, C and H differences
7495 // A nice increase in accuracy for modest increase in complexity
7496 const π = Math.PI;
7497 const d2r = π / 180;
7498
7499 /**
7500 * @param {import("../types.js").ColorTypes} color
7501 * @param {import("../types.js").ColorTypes} sample
7502 * @param {{ l?: number | undefined; c?: number | undefined }} options
7503 * @returns {number}
7504 */
7505 function deltaECMC (color, sample, {
7506 l = 2,
7507 c = 1
7508 } = {}) {
7509 [color, sample] = getColor([color, sample]);
7510
7511 // Given this color as the reference
7512 // and a sample,
7513 // calculate deltaE CMC.
7514
7515 // This implementation assumes the parametric
7516 // weighting factors l:c are 2:1
7517 // which is typical for non-textile uses.
7518
7519 let [L1, a1, b1] = lab.from(color);
7520 let [, C1, H1] = lch.from(lab, [L1, a1, b1]);
7521 let [L2, a2, b2] = lab.from(sample);
7522 let C2 = lch.from(lab, [L2, a2, b2])[1];
7523
7524 // let [L1, a1, b1] = color.getAll(lab);
7525 // let C1 = color.get("lch.c");
7526 // let H1 = color.get("lch.h");
7527 // let [L2, a2, b2] = sample.getAll(lab);
7528 // let C2 = sample.get("lch.c");
7529
7530 // Check for negative Chroma,
7531 // which might happen through
7532 // direct user input of LCH values
7533
7534 if (C1 < 0) {
7535 C1 = 0;
7536 }
7537 if (C2 < 0) {
7538 C2 = 0;
7539 }
7540
7541 // we don't need H2 as ΔH is calculated from Δa, Δb and ΔC
7542
7543 // Lightness and Chroma differences
7544 // These are (color - sample), unlike deltaE2000
7545 let ΔL = L1 - L2;
7546 let ΔC = C1 - C2;
7547 let Δa = a1 - a2;
7548 let Δb = b1 - b2;
7549
7550 // weighted Hue difference, less for larger Chroma difference
7551
7552 let H2 = Δa ** 2 + Δb ** 2 - ΔC ** 2;
7553 // due to roundoff error it is possible that, for zero a and b,
7554 // ΔC > Δa + Δb is 0, resulting in attempting
7555 // to take the square root of a negative number
7556
7557 // trying instead the equation from Industrial Color Physics
7558 // By Georg A. Klein
7559
7560 // let ΔH = ((a1 * b2) - (a2 * b1)) / Math.sqrt(0.5 * ((C2 * C1) + (a2 * a1) + (b2 * b1)));
7561 // console.log({ΔH});
7562 // This gives the same result to 12 decimal places
7563 // except it sometimes NaNs when trying to root a negative number
7564
7565 // let ΔH = Math.sqrt(H2); we never actually use the root, it gets squared again!!
7566
7567 // positional corrections to the lack of uniformity of CIELAB
7568 // These are all trying to make JND ellipsoids more like spheres
7569
7570 // SL Lightness crispening factor, depends entirely on L1 not L2
7571 let SL = 0.511; // linear portion of the Y to L transfer function
7572 if (L1 >= 16) {
7573 // cubic portion
7574 SL = 0.040975 * L1 / (1 + 0.01765 * L1);
7575 }
7576
7577 // SC Chroma factor
7578 let SC = 0.0638 * C1 / (1 + 0.0131 * C1) + 0.638;
7579
7580 // Cross term T for blue non-linearity
7581 let T;
7582 if (isNone(H1)) {
7583 H1 = 0;
7584 }
7585 if (H1 >= 164 && H1 <= 345) {
7586 T = 0.56 + Math.abs(0.2 * Math.cos((H1 + 168) * d2r));
7587 } else {
7588 T = 0.36 + Math.abs(0.4 * Math.cos((H1 + 35) * d2r));
7589 }
7590 // console.log({T});
7591
7592 // SH Hue factor also depends on C1,
7593 let C4 = Math.pow(C1, 4);
7594 let F = Math.sqrt(C4 / (C4 + 1900));
7595 let SH = SC * (F * T + 1 - F);
7596
7597 // Finally calculate the deltaE, term by term as root sume of squares
7598 let dE = (ΔL / (l * SL)) ** 2;
7599 dE += (ΔC / (c * SC)) ** 2;
7600 dE += H2 / SH ** 2;
7601 // dE += (ΔH / SH) ** 2;
7602 return Math.sqrt(dE);
7603 // Yay!!!
7604 }
7605
7606 const Yw$1 = 203; // absolute luminance of media white
7607
7608 var XYZ_Abs_D65 = new ColorSpace({
7609 // Absolute CIE XYZ, with a D65 whitepoint,
7610 // as used in most HDR colorspaces as a starting point.
7611 // SDR spaces are converted per BT.2048
7612 // so that diffuse, media white is 203 cd/m²
7613 id: "xyz-abs-d65",
7614 cssId: "--xyz-abs-d65",
7615 name: "Absolute XYZ D65",
7616 coords: {
7617 x: {
7618 refRange: [0, 9504.7],
7619 name: "Xa"
7620 },
7621 y: {
7622 refRange: [0, 10000],
7623 name: "Ya"
7624 },
7625 z: {
7626 refRange: [0, 10888.3],
7627 name: "Za"
7628 }
7629 },
7630 base: XYZ_D65,
7631 fromBase(XYZ) {
7632 // Make XYZ absolute, not relative to media white
7633 // Maximum luminance in PQ is 10,000 cd/m²
7634 // Relative XYZ has Y=1 for media white
7635 return XYZ.map(v => v * Yw$1);
7636 },
7637 toBase(AbsXYZ) {
7638 // Convert to media-white relative XYZ
7639 return AbsXYZ.map(v => v / Yw$1);
7640 }
7641 });
7642
7643 /** @import { Matrix3x3, Vector3 } from "../types.js" */
7644
7645 const b$1 = 1.15;
7646 const g = 0.66;
7647 const n$1 = 2610 / 2 ** 14;
7648 const ninv$1 = 2 ** 14 / 2610;
7649 const c1$2 = 3424 / 2 ** 12;
7650 const c2$2 = 2413 / 2 ** 7;
7651 const c3$2 = 2392 / 2 ** 7;
7652 const p$1 = 1.7 * 2523 / 2 ** 5;
7653 const pinv = 2 ** 5 / (1.7 * 2523);
7654 const d = -0.56;
7655 const d0 = 1.6295499532821566e-11;
7656
7657 /**
7658 * Matrices used by this color space, also available as `Jzazbz.M`
7659 * @type {Record<string, Matrix3x3>}
7660 */
7661 // prettier-ignore
7662 const M$c = {
7663 XYZtoCone: [[0.41478972, 0.579999, 0.0146480], [-0.2015100, 1.120649, 0.0531008], [-0.0166008, 0.264800, 0.6684799]],
7664 // XYZtoCone inverted
7665 ConetoXYZ: [[1.9242264357876067, -1.0047923125953657, 0.037651404030618], [0.35031676209499907, 0.7264811939316552, -0.06538442294808501], [-0.09098281098284752, -0.3127282905230739, 1.5227665613052603]],
7666 ConetoIab: [[0.5, 0.5, 0], [3.524000, -4.066708, 0.542708], [0.199076, 1.096799, -1.295875]],
7667 // ConetoIab inverted
7668 IabtoCone: [[1, 0.13860504327153927, 0.05804731615611883], [1, -0.1386050432715393, -0.058047316156118904], [1, -0.09601924202631895, -0.81189189605603900]]
7669 };
7670 var Jzazbz = new ColorSpace({
7671 id: "jzazbz",
7672 name: "Jzazbz",
7673 coords: {
7674 jz: {
7675 refRange: [0, 1],
7676 name: "Jz"
7677 },
7678 az: {
7679 refRange: [-0.21, 0.21]
7680 },
7681 bz: {
7682 refRange: [-0.21, 0.21]
7683 }
7684 },
7685 base: XYZ_Abs_D65,
7686 M: M$c,
7687 fromBase(XYZ) {
7688 // First make XYZ absolute, not relative to media white
7689 // Maximum luminance in PQ is 10,000 cd/m²
7690 // Relative XYZ has Y=1 for media white
7691 // BT.2048 says media white Y=203 at PQ 58
7692
7693 let [Xa, Ya, Za] = XYZ;
7694
7695 // modify X and Y to minimize blue curvature
7696 let Xm = b$1 * Xa - (b$1 - 1) * Za;
7697 let Ym = g * Ya - (g - 1) * Xa;
7698
7699 // move to LMS cone domain
7700 let LMS = multiply_v3_m3x3([Xm, Ym, Za], M$c.XYZtoCone);
7701
7702 // PQ-encode LMS
7703 let PQLMS = /** @type {Vector3} } */
7704 LMS.map(function (val) {
7705 let num = c1$2 + c2$2 * spow(val / 10000, n$1);
7706 let denom = 1 + c3$2 * spow(val / 10000, n$1);
7707 return spow(num / denom, p$1);
7708 });
7709
7710 // almost there, calculate Iz az bz
7711 let [Iz, az, bz] = multiply_v3_m3x3(PQLMS, M$c.ConetoIab);
7712 // console.log({Iz, az, bz});
7713
7714 let Jz = (1 + d) * Iz / (1 + d * Iz) - d0;
7715 return [Jz, az, bz];
7716 },
7717 toBase(Jzazbz) {
7718 let [Jz, az, bz] = Jzazbz;
7719 let Iz = (Jz + d0) / (1 + d - d * (Jz + d0));
7720
7721 // bring into LMS cone domain
7722 let PQLMS = multiply_v3_m3x3([Iz, az, bz], M$c.IabtoCone);
7723
7724 // convert from PQ-coded to linear-light
7725 let LMS = /** @type {Vector3} } */
7726 PQLMS.map(function (val) {
7727 let num = c1$2 - spow(val, pinv);
7728 let denom = c3$2 * spow(val, pinv) - c2$2;
7729 let x = 10000 * spow(num / denom, ninv$1);
7730 return x; // luminance relative to diffuse white, [0, 70 or so].
7731 });
7732
7733 // modified abs XYZ
7734 let [Xm, Ym, Za] = multiply_v3_m3x3(LMS, M$c.ConetoXYZ);
7735
7736 // un-modify X and Y to get D65 XYZ, relative to media white
7737 let Xa = (Xm + (b$1 - 1) * Za) / b$1;
7738 let Ya = (Ym + (g - 1) * Xa) / g;
7739 return [Xa, Ya, Za];
7740 },
7741 formats: {
7742 // https://drafts.csswg.org/css-color-hdr/#Jzazbz
7743 jzazbz: {
7744 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
7745 }
7746 }
7747 });
7748
7749 var jzczhz = new ColorSpace({
7750 id: "jzczhz",
7751 name: "JzCzHz",
7752 coords: {
7753 jz: {
7754 refRange: [0, 1],
7755 name: "Jz"
7756 },
7757 cz: {
7758 refRange: [0, 0.26],
7759 name: "Chroma"
7760 },
7761 hz: {
7762 refRange: [0, 360],
7763 type: "angle",
7764 name: "Hue"
7765 }
7766 },
7767 base: Jzazbz,
7768 fromBase: lch.fromBase,
7769 toBase: lch.toBase,
7770 formats: {
7771 // https://drafts.csswg.org/css-color-hdr/#JzCzhz
7772 jzczhz: {
7773 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
7774 }
7775 }
7776 });
7777
7778 /**
7779 * More accurate color-difference formulae
7780 * than the simple 1976 Euclidean distance in Lab
7781 *
7782 * Uses JzCzHz, which has improved perceptual uniformity
7783 * and thus a simple Euclidean root-sum of ΔL² ΔC² ΔH²
7784 * gives good results.
7785 * @param {import("../types.js").ColorTypes} color
7786 * @param {import("../types.js").ColorTypes} sample
7787 * @returns {number}
7788 */
7789 function deltaEJz (color, sample) {
7790 [color, sample] = getColor([color, sample]);
7791
7792 // Given this color as the reference
7793 // and a sample,
7794 // calculate deltaE in JzCzHz.
7795 let [Jz1, Cz1, Hz1] = jzczhz.from(color);
7796 let [Jz2, Cz2, Hz2] = jzczhz.from(sample);
7797
7798 // Lightness and Chroma differences
7799 // sign does not matter as they are squared.
7800 let ΔJ = Jz1 - Jz2;
7801 let ΔC = Cz1 - Cz2;
7802
7803 // length of chord for ΔH
7804 if (isNone(Hz1) && isNone(Hz2)) {
7805 // both undefined hues
7806 Hz1 = 0;
7807 Hz2 = 0;
7808 } else if (isNone(Hz1)) {
7809 // one undefined, set to the defined hue
7810 Hz1 = Hz2;
7811 } else if (isNone(Hz2)) {
7812 Hz2 = Hz1;
7813 }
7814 let Δh = Hz1 - Hz2;
7815 let ΔH = 2 * Math.sqrt(Cz1 * Cz2) * Math.sin(Δh / 2 * (Math.PI / 180));
7816 return Math.sqrt(ΔJ ** 2 + ΔC ** 2 + ΔH ** 2);
7817 }
7818
7819 /** @import { Matrix3x3, Vector3 } from "../types.js" */
7820
7821 const c1$1 = 3424 / 4096;
7822 const c2$1 = 2413 / 128;
7823 const c3$1 = 2392 / 128;
7824 const m1 = 2610 / 16384;
7825 const m2 = 2523 / 32;
7826 const im1 = 16384 / 2610;
7827 const im2 = 32 / 2523;
7828
7829 // Reference (rational-form) matrices, kept for documentation but not used directly:
7830 // linear-light Rec.2020 to LMS (with crosstalk) and its inverse
7831 // rational terms from Jan Fröhlich, Encoding High Dynamic Range
7832 // and Wide Color Gamut Imagery, p.97 and ITU-R BT.2124-0 pp.2-3
7833 /*
7834 const Rec2020toLMS = [
7835 [ 1688 / 4096, 2146 / 4096, 262 / 4096 ],
7836 [ 683 / 4096, 2951 / 4096, 462 / 4096 ],
7837 [ 99 / 4096, 309 / 4096, 3688 / 4096 ]
7838 ];
7839 const LMStoRec2020 = [
7840 [ 3.4375568932814012112, -2.5072112125095058195, 0.069654319228104608382],
7841 [-0.79142868665644156125, 1.9838372198740089874, -0.19240853321756742626 ],
7842 [-0.025646662911506476363, -0.099240248643945566751, 1.1248869115554520431 ]
7843 ];
7844 */
7845
7846 /**
7847 * Matrices used by this color space, also available as `ICTCP.M`
7848 * @type {Record<string, Matrix3x3>}
7849 */
7850 // prettier-ignore
7851 const M$b = {
7852 // includes the 4% crosstalk components, from the Dolby "What is ICtCp" paper
7853 XYZtoLMS: [[0.3592832590121217, 0.6976051147779502, -0.0358915932320290], [-0.1920808463704993, 1.1004767970374321, 0.0753748658519118], [0.0070797844607479, 0.0748396662186362, 0.8433265453898765]],
7854 // includes the Ebner LMS coefficients, the rotation,
7855 // and the scaling to the [-0.5,0.5] range
7856 LMStoIPT: [[2048 / 4096, 2048 / 4096, 0], [6610 / 4096, -13613 / 4096, 7003 / 4096], [17933 / 4096, -17390 / 4096, -543 / 4096]],
7857 // inverted matrices, calculated from the above
7858 IPTtoLMS: [[0.9999999999999998, 0.0086090370379328, 0.1110296250030260], [0.9999999999999998, -0.0086090370379328, -0.1110296250030259], [0.9999999999999998, 0.5600313357106791, -0.3206271749873188]],
7859 LMStoXYZ: [[2.0701522183894223, -1.3263473389671563, 0.2066510476294053], [0.3647385209748072, 0.6805660249472273, -0.0453045459220347], [-0.0497472075358123, -0.0492609666966131, 1.1880659249923042]]
7860 };
7861
7862 // Only the PQ form of ICtCp is implemented here. There is also an HLG form.
7863 // from Dolby, "WHAT IS ICTCP?"
7864 // https://professional.dolby.com/siteassets/pdfs/ictcp_dolbywhitepaper_v071.pdf
7865 // and
7866 // Dolby, "Perceptual Color Volume
7867 // Measuring the Distinguishable Colors of HDR and WCG Displays"
7868 // https://professional.dolby.com/siteassets/pdfs/dolby-vision-measuring-perceptual-color-volume-v7.1.pdf
7869 var ictcp = new ColorSpace({
7870 id: "ictcp",
7871 name: "ICTCP",
7872 // From BT.2100-2 page 7:
7873 // During production, signal values are expected to exceed the
7874 // range E′ = [0.0 : 1.0]. This provides processing headroom and avoids
7875 // signal degradation during cascaded processing. Such values of E′,
7876 // below 0.0 or exceeding 1.0, should not be clipped during production
7877 // and exchange.
7878 // Values below 0.0 should not be clipped in reference displays (even
7879 // though they represent “negative” light) to allow the black level of
7880 // the signal (LB) to be properly set using test signals known as “PLUGE”
7881 coords: {
7882 i: {
7883 refRange: [0, 1],
7884 // Constant luminance,
7885 name: "I"
7886 },
7887 ct: {
7888 refRange: [-0.5, 0.5],
7889 // Full BT.2020 gamut in range [-0.5, 0.5]
7890 name: "CT"
7891 },
7892 cp: {
7893 refRange: [-0.5, 0.5],
7894 name: "CP"
7895 }
7896 },
7897 base: XYZ_Abs_D65,
7898 M: M$b,
7899 fromBase(XYZ) {
7900 // move to LMS cone domain
7901 let LMS = multiply_v3_m3x3(XYZ, M$b.XYZtoLMS);
7902 return LMStoICtCp(LMS);
7903 },
7904 toBase(ICtCp) {
7905 let LMS = ICtCptoLMS(ICtCp);
7906 return multiply_v3_m3x3(LMS, M$b.LMStoXYZ);
7907 },
7908 formats: {
7909 ictcp: {
7910 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
7911 }
7912 }
7913 });
7914
7915 /**
7916 *
7917 * @param {Vector3} LMS
7918 * @returns {Vector3}
7919 */
7920 function LMStoICtCp(LMS) {
7921 // apply the PQ EOTF
7922 // we can't ever be dividing by zero because of the "1 +" in the denominator
7923 let PQLMS = /** @type {Vector3} */
7924 LMS.map(function (val) {
7925 let num = c1$1 + c2$1 * (val / 10000) ** m1;
7926 let denom = 1 + c3$1 * (val / 10000) ** m1;
7927 return (num / denom) ** m2;
7928 });
7929
7930 // LMS to IPT, with rotation for Y'C'bC'r compatibility
7931 return multiply_v3_m3x3(PQLMS, M$b.LMStoIPT);
7932 }
7933
7934 /**
7935 *
7936 * @param {Vector3} ICtCp
7937 * @returns {Vector3}
7938 */
7939 function ICtCptoLMS(ICtCp) {
7940 let PQLMS = multiply_v3_m3x3(ICtCp, M$b.IPTtoLMS);
7941
7942 // From BT.2124-0 Annex 2 Conversion 3
7943 let LMS = /** @type {Vector3} */
7944 PQLMS.map(function (val) {
7945 let num = Math.max(val ** im2 - c1$1, 0);
7946 let denom = c2$1 - c3$1 * val ** im2;
7947 return 10000 * (num / denom) ** im1;
7948 });
7949 return LMS;
7950 }
7951
7952 /**
7953 * Delta E in ICtCp space,
7954 * which the ITU calls Delta E ITP, which is shorter.
7955 * Formulae from ITU Rec. ITU-R BT.2124-0
7956 * @param {import("../types.js").ColorTypes} color
7957 * @param {import("../types.js").ColorTypes} sample
7958 * @returns {number}
7959 */
7960 function deltaEITP (color, sample) {
7961 [color, sample] = getColor([color, sample]);
7962
7963 // Given this color as the reference
7964 // and a sample,
7965 // calculate deltaE in ICtCp
7966 // which is simply the Euclidean distance
7967
7968 let [I1, T1, P1] = ictcp.from(color);
7969 let [I2, T2, P2] = ictcp.from(sample);
7970
7971 // the 0.25 factor is to undo the encoding scaling in Ct
7972 // the 720 is so that 1 deltaE = 1 JND
7973 // per ITU-R BT.2124-0 p.3
7974
7975 return 720 * Math.sqrt((I1 - I2) ** 2 + 0.25 * (T1 - T2) ** 2 + (P1 - P2) ** 2);
7976 }
7977
7978 /**
7979 * More accurate color-difference formulae
7980 * than the simple 1976 Euclidean distance in CIE Lab
7981 * The Oklab a and b axes are scaled relative to the L axis, for better uniformity
7982 * Björn Ottosson said:
7983 * "I've recently done some tests with color distance datasets as implemented
7984 * in Colorio and on both the Combvd dataset and the OSA-UCS dataset a
7985 * scale factor of slightly more than 2 for a and b would give the best results
7986 * (2.016 works best for Combvd and 2.045 for the OSA-UCS dataset)."
7987 * @see {@link <https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-945714988>}
7988 * @param {import("../types.js").ColorTypes} color
7989 * @param {import("../types.js").ColorTypes} sample
7990 * @returns {number}
7991 */
7992 function deltaEOK2 (color, sample) {
7993 [color, sample] = getColor([color, sample]);
7994
7995 // Given this color as the reference
7996 // and a sample,
7997 // calculate deltaEOK2, term by term as root sum of squares
7998 let abscale = 2;
7999 let [L1, a1, b1] = Oklab.from(color);
8000 let [L2, a2, b2] = Oklab.from(sample);
8001 let ΔL = L1 - L2;
8002 let Δa = abscale * (a1 - a2);
8003 let Δb = abscale * (b1 - b2);
8004 return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2);
8005 }
8006
8007 /** @import { Coords, Matrix3x3, Vector3 } from "../types.js" */
8008
8009 // Type re-exports
8010 /** @typedef {import("../types.js").Cam16Object} Cam16Object */
8011 /** @typedef {import("../types.js").Cam16Input} Cam16Input */
8012 /** @typedef {import("../types.js").Cam16Environment} Cam16Environment */
8013
8014 const white$3 = WHITES.D65;
8015 const adaptedCoef = 0.42;
8016 const adaptedCoefInv = 1 / adaptedCoef;
8017 const tau$1 = 2 * Math.PI;
8018
8019 /**
8020 * Matrices used by this color space, also available as `CAM16_JMh.M`
8021 * @type {Record<string, Matrix3x3>}
8022 */
8023 // prettier-ignore
8024 const M$a = {
8025 cat16: [[0.401288, 0.650173, -0.051461], [-0.250268, 1.204414, 0.045854], [-0.002079, 0.048952, 0.953127]],
8026 cat16Inv: [[1.8620678550872327, -1.0112546305316843, 0.14918677544445175], [0.38752654323613717, 0.6214474419314753, -0.008973985167612518], [-0.015841498849333856, -0.03412293802851557, 1.0499644368778496]],
8027 m1: [[460.0, 451.0, 288.0], [460.0, -891.0, -261.0], [460.0, -220.0, -6300.0]]
8028 };
8029 const surroundMap = {
8030 dark: [0.8, 0.525, 0.8],
8031 dim: [0.9, 0.59, 0.9],
8032 average: [1, 0.69, 1]
8033 };
8034 const hueQuadMap = {
8035 // Red, Yellow, Green, Blue, Red
8036 h: [20.14, 90.0, 164.25, 237.53, 380.14],
8037 e: [0.8, 0.7, 1.0, 1.2, 0.8],
8038 H: [0.0, 100.0, 200.0, 300.0, 400.0]
8039 };
8040 const rad2deg = 180 / Math.PI;
8041 const deg2rad$1 = Math.PI / 180;
8042
8043 /**
8044 * @param {Coords} coords
8045 * @param {number} fl
8046 * @returns {[number, number, number]}
8047 */
8048 function adapt$1(coords, fl) {
8049 const temp = /** @type {[number, number, number]} */
8050 coords.map(c => {
8051 const x = spow(fl * Math.abs(c) * 0.01, adaptedCoef);
8052 return 400 * copySign(x, c) / (x + 27.13);
8053 });
8054 return temp;
8055 }
8056
8057 /**
8058 * @param {Coords} adapted
8059 * @param {number} fl
8060 * @returns {[number, number, number]}
8061 */
8062 function unadapt(adapted, fl) {
8063 const constant = 100 / fl * 27.13 ** adaptedCoefInv;
8064 return /** @type {[number, number, number]} */adapted.map(c => {
8065 const cabs = Math.abs(c);
8066 return copySign(constant * spow(cabs / (400 - cabs), adaptedCoefInv), c);
8067 });
8068 }
8069
8070 /**
8071 * @param {number} h
8072 */
8073 function hueQuadrature(h) {
8074 let hp = constrain(h);
8075 if (hp <= hueQuadMap.h[0]) {
8076 hp += 360;
8077 }
8078 const i = bisectLeft(hueQuadMap.h, hp) - 1;
8079 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
8080 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
8081 const Hi = hueQuadMap.H[i];
8082 const t = (hp - hi) / ei;
8083 return Hi + 100 * t / (t + (hii - hp) / eii);
8084 }
8085
8086 /**
8087 * @param {number} H
8088 */
8089 function invHueQuadrature(H) {
8090 let Hp = (H % 400 + 400) % 400;
8091 const i = Math.floor(0.01 * Hp);
8092 Hp = Hp % 100;
8093 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
8094 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
8095 return constrain((Hp * (eii * hi - ei * hii) - 100 * hi * eii) / (Hp * (eii - ei) - 100 * eii));
8096 }
8097
8098 /**
8099 * @param {[number, number, number]} refWhite
8100 * @param {number} adaptingLuminance
8101 * @param {number} backgroundLuminance
8102 * @param {keyof typeof surroundMap} surround
8103 * @param {boolean} discounting
8104 * @returns {Cam16Environment}
8105 */
8106 function environment(refWhite, adaptingLuminance, backgroundLuminance, surround, discounting) {
8107 const env = {};
8108 env.discounting = discounting;
8109 env.refWhite = refWhite;
8110 env.surround = surround;
8111 const xyzW = /** @type {Vector3} */
8112 refWhite.map(c => {
8113 return c * 100;
8114 });
8115
8116 // The average luminance of the environment in `cd/m^2cd/m` (a.k.a. nits)
8117 env.la = adaptingLuminance;
8118 // The relative luminance of the nearby background
8119 env.yb = backgroundLuminance;
8120 // Absolute luminance of the reference white.
8121 const yw = xyzW[1];
8122
8123 // Cone response for reference white
8124 const rgbW = multiply_v3_m3x3(xyzW, M$a.cat16);
8125
8126 // Surround: dark, dim, and average
8127 let values = surroundMap[env.surround];
8128 const f = values[0];
8129 env.c = values[1];
8130 env.nc = values[2];
8131 const k = 1 / (5 * env.la + 1);
8132 const k4 = k ** 4;
8133
8134 // Factor of luminance level adaptation
8135 env.fl = k4 * env.la + 0.1 * (1 - k4) * (1 - k4) * Math.cbrt(5 * env.la);
8136 env.flRoot = env.fl ** 0.25;
8137 env.n = env.yb / yw;
8138 env.z = 1.48 + Math.sqrt(env.n);
8139 env.nbb = 0.725 * env.n ** -0.2;
8140 env.ncb = env.nbb;
8141
8142 // Degree of adaptation calculating if not discounting
8143 // illuminant (assumed eye is fully adapted)
8144 const d = Math.max(Math.min(f * (1 - 1 / 3.6 * Math.exp((-env.la - 42) / 92)), 1), 0);
8145 env.dRgb = /** @type {[number, number, number]} */
8146 rgbW.map(c => {
8147 return interpolate(1, yw / c, d);
8148 });
8149 env.dRgbInv = /** @type {[number, number, number]} */
8150 env.dRgb.map(c => {
8151 return 1 / c;
8152 });
8153
8154 // Achromatic response
8155 const rgbCW = /** @type {[number, number, number]} */
8156 rgbW.map((c, i) => {
8157 return c * env.dRgb[i];
8158 });
8159 const rgbAW = adapt$1(rgbCW, env.fl);
8160 env.aW = env.nbb * (2 * rgbAW[0] + rgbAW[1] + 0.05 * rgbAW[2]);
8161
8162 // console.log(env);
8163
8164 return env;
8165 }
8166
8167 // Pre-calculate everything we can with the viewing conditions
8168 const viewingConditions$1 = environment(white$3, 64 / Math.PI * 0.2, 20, "average", false);
8169
8170 /**
8171 * @param {Cam16Input} cam16
8172 * @param {Cam16Environment} env
8173 * @returns {[number, number, number]}
8174 */
8175 function fromCam16(cam16, env) {
8176 // These check ensure one, and only one attribute for a
8177 // given category is provided.
8178 // @ts-expect-error The '^` operator is not allowed for boolean types
8179 if (!(cam16.J !== undefined ^ cam16.Q !== undefined)) {
8180 throw new Error("Conversion requires one and only one: 'J' or 'Q'");
8181 }
8182
8183 // @ts-expect-error - The '^` operator is not allowed for boolean types
8184 if (!(cam16.C !== undefined ^ cam16.M !== undefined ^ cam16.s !== undefined)) {
8185 throw new Error("Conversion requires one and only one: 'C', 'M' or 's'");
8186 }
8187
8188 // Hue is absolutely required
8189 // @ts-expect-error - The '^` operator is not allowed for boolean types
8190 if (!(cam16.h !== undefined ^ cam16.H !== undefined)) {
8191 throw new Error("Conversion requires one and only one: 'h' or 'H'");
8192 }
8193
8194 // Black
8195 if (cam16.J === 0.0 || cam16.Q === 0.0) {
8196 return [0.0, 0.0, 0.0];
8197 }
8198
8199 // Break hue into Cartesian components
8200 let hRad = 0.0;
8201 if (cam16.h !== undefined) {
8202 hRad = constrain(cam16.h) * deg2rad$1;
8203 } else {
8204 hRad = invHueQuadrature(cam16.H) * deg2rad$1;
8205 }
8206 const cosh = Math.cos(hRad);
8207 const sinh = Math.sin(hRad);
8208
8209 // Calculate `Jroot` from one of the lightness derived coordinates.
8210 let Jroot = 0.0;
8211 if (cam16.J !== undefined) {
8212 Jroot = spow(cam16.J, 1 / 2) * 0.1;
8213 } else if (cam16.Q !== undefined) {
8214 Jroot = 0.25 * env.c * cam16.Q / ((env.aW + 4) * env.flRoot);
8215 }
8216
8217 // Calculate the `t` value from one of the chroma derived coordinates
8218 let alpha = 0.0;
8219 if (cam16.C !== undefined) {
8220 alpha = cam16.C / Jroot;
8221 } else if (cam16.M !== undefined) {
8222 alpha = cam16.M / env.flRoot / Jroot;
8223 } else if (cam16.s !== undefined) {
8224 alpha = 0.0004 * cam16.s ** 2 * (env.aW + 4) / env.c;
8225 }
8226 const t = spow(alpha * Math.pow(1.64 - Math.pow(0.29, env.n), -0.73), 10 / 9);
8227
8228 // Eccentricity
8229 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
8230
8231 // Achromatic response
8232 const A = env.aW * spow(Jroot, 2 / env.c / env.z);
8233
8234 // Calculate red-green and yellow-blue components
8235 const p1 = 5e4 / 13 * env.nc * env.ncb * et;
8236 const p2 = A / env.nbb;
8237 const r = 23 * (p2 + 0.305) * zdiv(t, 23 * p1 + t * (11 * cosh + 108 * sinh));
8238 const a = r * cosh;
8239 const b = r * sinh;
8240
8241 // Calculate back from cone response to XYZ
8242 const rgb_c = unadapt(/** @type {Vector3} */
8243
8244 multiply_v3_m3x3([p2, a, b], M$a.m1).map(c => {
8245 return c * 1 / 1403;
8246 }), env.fl);
8247 return /** @type {Vector3} */multiply_v3_m3x3(/** @type {Vector3} */
8248 rgb_c.map((c, i) => {
8249 return c * env.dRgbInv[i];
8250 }), M$a.cat16Inv).map(c => {
8251 return c / 100;
8252 });
8253 }
8254
8255 /**
8256 * @param {[number, number, number]} xyzd65
8257 * @param {Cam16Environment} env
8258 * @returns {Cam16Object}
8259 */
8260 function toCam16(xyzd65, env) {
8261 // Cone response
8262 const xyz100 = /** @type {Vector3} */
8263 xyzd65.map(c => {
8264 return c * 100;
8265 });
8266 const rgbA = adapt$1(/** @type {[number, number, number]} */
8267
8268 multiply_v3_m3x3(xyz100, M$a.cat16).map((c, i) => {
8269 return c * env.dRgb[i];
8270 }), env.fl);
8271
8272 // Calculate hue from red-green and yellow-blue components
8273 const a = rgbA[0] + (-12 * rgbA[1] + rgbA[2]) / 11;
8274 const b = (rgbA[0] + rgbA[1] - 2 * rgbA[2]) / 9;
8275 const hRad = (Math.atan2(b, a) % tau$1 + tau$1) % tau$1;
8276
8277 // Eccentricity
8278 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
8279 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);
8280 const alpha = spow(t, 0.9) * Math.pow(1.64 - Math.pow(0.29, env.n), 0.73);
8281
8282 // Achromatic response
8283 const A = env.nbb * (2 * rgbA[0] + rgbA[1] + 0.05 * rgbA[2]);
8284 const Jroot = spow(A / env.aW, 0.5 * env.c * env.z);
8285
8286 // Lightness
8287 const J = 100 * spow(Jroot, 2);
8288
8289 // Brightness
8290 const Q = 4 / env.c * Jroot * (env.aW + 4) * env.flRoot;
8291
8292 // Chroma
8293 const C = alpha * Jroot;
8294
8295 // Colorfulness
8296 const colorfulness = C * env.flRoot;
8297
8298 // Hue
8299 const h = constrain(hRad * rad2deg);
8300
8301 // Hue quadrature
8302 const H = hueQuadrature(h);
8303
8304 // Saturation
8305 const s = 50 * spow(env.c * alpha / (env.aW + 4), 1 / 2);
8306
8307 // console.log({J: J, C: C, h: h, s: s, Q: Q, M: colorfulness, H: H});
8308
8309 return {
8310 J: J,
8311 C: C,
8312 h: h,
8313 s: s,
8314 Q: Q,
8315 M: colorfulness,
8316 H: H
8317 };
8318 }
8319
8320 // Provided as a way to directly evaluate the CAM16 model
8321 // https://observablehq.com/@jrus/cam16: reference implementation
8322 // https://arxiv.org/pdf/1802.06067.pdf: Nico Schlömer
8323 // https://onlinelibrary.wiley.com/doi/pdf/10.1002/col.22324: hue quadrature
8324 // https://www.researchgate.net/publication/318152296_Comprehensive_color_solutions_CAM16_CAT16_and_CAM16-UCS
8325 // Results compared against: https://github.com/colour-science/colour
8326 var cam16 = new ColorSpace({
8327 id: "cam16-jmh",
8328 cssId: "--cam16-jmh",
8329 name: "CAM16-JMh",
8330 coords: {
8331 j: {
8332 refRange: [0, 100],
8333 name: "J"
8334 },
8335 m: {
8336 refRange: [0, 105.0],
8337 name: "Colorfulness"
8338 },
8339 h: {
8340 refRange: [0, 360],
8341 type: "angle",
8342 name: "Hue"
8343 }
8344 },
8345 base: XYZ_D65,
8346 M: M$a,
8347 fromBase(xyz) {
8348 // If another derivation is created, ε could vary, so we can't hardcode
8349 if (this.ε === undefined) {
8350 this.ε = Object.values(this.coords)[1].refRange[1] / 100000;
8351 }
8352 const cam16 = toCam16(xyz, viewingConditions$1);
8353 const isAchromatic = Math.abs(cam16.M) < this.ε;
8354 return [cam16.J, isAchromatic ? 0 : cam16.M, isAchromatic ? null : cam16.h];
8355 },
8356 toBase(cam16) {
8357 return fromCam16({
8358 J: cam16[0],
8359 M: cam16[1],
8360 h: cam16[2]
8361 }, viewingConditions$1);
8362 }
8363 });
8364
8365 const white$2 = WHITES.D65;
8366 const ε$4 = 216 / 24389; // 6^3/29^3 == (24/116)^3
8367 const κ$3 = 24389 / 27; // 29^3/3^3
8368
8369 function toLstar(y) {
8370 // Convert XYZ Y to L*
8371
8372 const fy = y > ε$4 ? Math.cbrt(y) : (κ$3 * y + 16) / 116;
8373 return 116.0 * fy - 16.0;
8374 }
8375 function fromLstar(lstar) {
8376 // Convert L* back to XYZ Y
8377
8378 return lstar > 8 ? Math.pow((lstar + 16) / 116, 3) : lstar / κ$3;
8379 }
8380 function fromHct(coords, env) {
8381 // Use Newton's method to try and converge as quick as possible or
8382 // converge as close as we can. While the requested precision is achieved
8383 // most of the time, it may not always be achievable. Especially past the
8384 // visible spectrum, the algorithm will likely struggle to get the same
8385 // precision. If, for whatever reason, we cannot achieve the accuracy we
8386 // seek in the allotted iterations, just return the closest we were able to
8387 // get.
8388
8389 let [h, c, t] = coords;
8390 let xyz = [];
8391 let j = 0;
8392
8393 // Shortcut out for black
8394 if (t === 0) {
8395 return [0.0, 0.0, 0.0];
8396 }
8397
8398 // Calculate the Y we need to target
8399 let y = fromLstar(t);
8400
8401 // A better initial guess yields better results. Polynomials come from
8402 // curve fitting the T vs J response.
8403 if (t > 0) {
8404 j = 0.00379058511492914 * t ** 2 + 0.608983189401032 * t + 0.9155088574762233;
8405 } else {
8406 j = 9.514440756550361e-6 * t ** 2 + 0.08693057439788597 * t - 21.928975842194614;
8407 }
8408
8409 // Threshold of how close is close enough, and max number of attempts.
8410 // More precision and more attempts means more time spent iterating. Higher
8411 // required precision gives more accuracy but also increases the chance of
8412 // not hitting the goal. 2e-12 allows us to convert round trip with
8413 // reasonable accuracy of six decimal places or more.
8414 const threshold = 2e-12;
8415 const max_attempts = 15;
8416 let attempt = 0;
8417 let last = Infinity;
8418 let best = [0, 0, 0];
8419
8420 // Try to find a J such that the returned y matches the returned y of the L*
8421 while (attempt <= max_attempts) {
8422 xyz = fromCam16({
8423 J: j,
8424 C: c,
8425 h: h
8426 }, env);
8427
8428 // If we are within range, return XYZ
8429 // If we are closer than last time, save the values
8430 const delta = Math.abs(xyz[1] - y);
8431 if (delta < last) {
8432 if (delta <= threshold) {
8433 return xyz;
8434 }
8435 best = xyz;
8436 last = delta;
8437 }
8438
8439 // f(j_root) = (j ** (1 / 2)) * 0.1
8440 // f(j) = ((f(j_root) * 100) ** 2) / j - 1 = 0
8441 // f(j_root) = Y = y / 100
8442 // f(j) = (y ** 2) / j - 1
8443 // f'(j) = (2 * y) / j
8444 j = j - (xyz[1] - y) * j / (2 * xyz[1]);
8445 attempt += 1;
8446 }
8447
8448 // We could not acquire the precision we desired,
8449 // return our closest attempt.
8450 return best;
8451 }
8452 function toHct(xyz, env) {
8453 // Calculate HCT by taking the L* of CIE LCh D65 and CAM16 chroma and hue.
8454
8455 const t = toLstar(xyz[1]);
8456 if (t === 0.0) {
8457 return [0.0, 0.0, 0.0];
8458 }
8459 const cam16 = toCam16(xyz, viewingConditions);
8460 return [constrain(cam16.h), cam16.C, t];
8461 }
8462
8463 // Pre-calculate everything we can with the viewing conditions
8464 const viewingConditions = environment(white$2, 200 / Math.PI * fromLstar(50.0), fromLstar(50.0) * 100, "average", false);
8465
8466 // https://material.io/blog/science-of-color-design
8467 // This is not a port of the material-color-utilities,
8468 // but instead implements the full color space as described,
8469 // combining CAM16 JCh and Lab D65. This does not clamp conversion
8470 // to HCT to specific chroma bands and provides support for wider
8471 // gamuts than Google currently supports and does so at a greater
8472 // precision (> 8 bits back to sRGB).
8473 // This implementation comes from https://github.com/facelessuser/coloraide
8474 // which is licensed under MIT.
8475 var hct = new ColorSpace({
8476 id: "hct",
8477 name: "HCT",
8478 coords: {
8479 h: {
8480 refRange: [0, 360],
8481 type: "angle",
8482 name: "Hue"
8483 },
8484 c: {
8485 refRange: [0, 145],
8486 name: "Colorfulness"
8487 },
8488 t: {
8489 refRange: [0, 100],
8490 name: "Tone"
8491 }
8492 },
8493 base: XYZ_D65,
8494 fromBase(xyz) {
8495 if (this.ε === undefined) {
8496 this.ε = Object.values(this.coords)[1].refRange[1] / 100000;
8497 }
8498 let hct = toHct(xyz);
8499 if (hct[1] < this.ε) {
8500 hct[1] = 0.0;
8501 hct[0] = null;
8502 }
8503 return hct;
8504 },
8505 toBase(hct) {
8506 return fromHct(hct, viewingConditions);
8507 },
8508 formats: {
8509 color: {
8510 id: "--hct",
8511 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
8512 }
8513 }
8514 });
8515
8516 const deg2rad = Math.PI / 180;
8517 const ucsCoeff = [1.0, 0.007, 0.0228];
8518
8519 /**
8520 * Convert HCT chroma and hue (CAM16 JMh colorfulness and hue) using UCS logic for a and b.
8521 * @param {Coords} coords - HCT coordinates.
8522 * @return {number[]}
8523 */
8524 function convertUcsAb(coords) {
8525 // We want the distance between the actual color.
8526 // If chroma is negative, it will throw off our calculations.
8527 // Normally, converting back to the base and forward will correct it.
8528 // If we have a negative chroma after this, then we have a color that
8529 // cannot resolve to positive chroma.
8530 if (coords[1] < 0) {
8531 coords = hct.fromBase(hct.toBase(coords));
8532 }
8533
8534 // Only in extreme cases (usually outside the visible spectrum)
8535 // can the input value for log become negative.
8536 // Avoid domain error by forcing a zero result via "max" if necessary.
8537 const M = Math.log(Math.max(1 + ucsCoeff[2] * coords[1] * viewingConditions.flRoot, 1.0)) / ucsCoeff[2];
8538 const hrad = coords[0] * deg2rad;
8539 const a = M * Math.cos(hrad);
8540 const b = M * Math.sin(hrad);
8541 return [coords[2], a, b];
8542 }
8543
8544 /**
8545 * Color distance using HCT.
8546 * @param {import("../types.js").ColorTypes} color
8547 * @param {import("../types.js").ColorTypes} sample
8548 * @returns {number}
8549 */
8550 function deltaEHCT (color, sample) {
8551 [color, sample] = getColor([color, sample]);
8552 let [t1, a1, b1] = convertUcsAb(hct.from(color));
8553 let [t2, a2, b2] = convertUcsAb(hct.from(sample));
8554
8555 // Use simple euclidean distance with a and b using UCS conversion
8556 // and LCh lightness (HCT tone).
8557 return Math.sqrt((t1 - t2) ** 2 + (a1 - a2) ** 2 + (b1 - b2) ** 2);
8558 }
8559
8560 /**
8561 * Helmlab MetricSpace — 13-stage perceptual color space.
8562 *
8563 * A data-driven analytical color space fit on COMBVD (3,813 paired human
8564 * color-difference judgments aggregating BFD-P, Witt 1999, RIT-DuPont, and
8565 * Leeds). Used internally by `deltaEHelmlab` and exposed as the CSS
8566 * color space `helmlab-metric` for inspectability. Its coordinate system
8567 * (asymmetric ab plane, L > 1 from H-K modeling, achromatic axis offset
8568 * from origin) is shaped for ΔE accuracy rather than author-facing
8569 * coordinates — for general CSS authoring use HelmGen (`helmgen`).
8570 *
8571 * Measured in this branch: ~24% lower STRESS than CIEDE2000 on COMBVD.
8572 *
8573 * Pipeline: XYZ → M1 → γ → M2 → hue correction → H-K → cubic L → dark L
8574 * → hue-dep chroma scale → chroma power → L-dep chroma scale
8575 * → HLC interaction → hue-dep lightness → rotation
8576 *
8577 * Reference: arXiv:2602.23010
8578 * @see https://github.com/Grkmyldz148/helmlab
8579 */
8580
8581 /** @import { Matrix3x3 } from "../types.js" */
8582
8583 const {
8584 cos,
8585 sin,
8586 sqrt,
8587 atan2,
8588 exp,
8589 abs,
8590 pow,
8591 PI
8592 } = Math;
8593
8594 /** Bradford CAT: Color.js D65 → Helmlab D65 (apply in fromBase before M1) */
8595 /** @type {Matrix3x3} */
8596 // prettier-ignore
8597 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]];
8598
8599 /** Bradford CAT: Helmlab D65 → Color.js D65 (apply in toBase after M1_INV) */
8600 /** @type {Matrix3x3} */
8601 // prettier-ignore
8602 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]];
8603
8604 // ── Utility functions ──────────────────────────────────────────────
8605
8606 // ── Core parameters (v21, 72 params) ──────────────────────────────
8607
8608 /** @type {Matrix3x3} */
8609 // prettier-ignore
8610 const M1 = [[0.72129864331134985189, 0.45344826541531813024, -0.19288975751942616377], [-0.78821186949557897616, 1.79524137675723594043, 0.08761724511817850503], [-0.09177005999121559676, 0.45765588659459255361, 1.29220455139176770842]];
8611 /** @type {Matrix3x3} */
8612 // prettier-ignore
8613 const M1_INV = [[1.06510729580885898926, -0.31500440753011210715, 0.18034923817410389302], [0.47211077138377960383, 0.42719957659624552271, 0.04150680489380984689], [-0.09156391926309541407, -0.17367093631949789834, 0.77197903825582936399]];
8614 const GAMMA = [0.47229813098762524, 0.5149184096354483, 0.5113233386366979];
8615 const INV_GAMMA = [2.1173067060606283, 1.9420552485353544, 1.9557096741686448];
8616
8617 /** @type {Matrix3x3} */
8618 // prettier-ignore
8619 const M2 = [[-0.26355622180094095963, 0.41683228837031738312, 0.49267631416564028335], [1.88975705087773215851, -3.12122320342057735232, 1.04216669210603840590], [0.35851086179620561545, 1.76940281937903676202, -1.41206260676953720967]];
8620 /** @type {Matrix3x3} */
8621 // prettier-ignore
8622 const M2_INV = [[0.91838978228150214278, 0.52320512370886662623, 0.70658045980908557038], [1.08990905744330257576, 0.07005324849041903723, 0.43197768747870440853], [1.59889572926420897581, 0.22061850068770233468, 0.01250603735522095097]];
8623
8624 /** Matrices used by this color space, also available as `Helmlab.M` */
8625 const M$9 = {
8626 CAT_TO_HELM,
8627 CAT_FROM_HELM,
8628 M1,
8629 M1_INV,
8630 M2,
8631 M2_INV
8632 };
8633
8634 // Enrichment parameters
8635 const hue_cos1 = -0.02833024015436984,
8636 hue_sin1 = -0.21131429516166544;
8637 const hue_cos2 = 0.2189784817615645,
8638 hue_sin2 = -0.06871898981942523;
8639 const hue_cos3 = 0.005506053349515315,
8640 hue_sin3 = -0.0641329861299175;
8641 const hue_cos4 = -0.053592461436994296,
8642 hue_sin4 = -0.00954137464208059;
8643 const hk_weight = 0.2676231133101982,
8644 hk_power = 0.8934892185255707;
8645 const hk_hue_mod = 0.7173169828841472;
8646 const hk_sin1 = 0.6915224124600773,
8647 hk_cos2 = 0.48647127559605596,
8648 hk_sin2 = 0.9853124591201782;
8649 const L_corr_p1 = 0.5385456675962418,
8650 L_corr_p2 = 0.12508858146241716,
8651 L_corr_p3 = 0.6768950256217603;
8652 const Lh_cos1 = -0.4963251525324449,
8653 Lh_sin1 = -0.09564696283240552;
8654 const lp_dark = -0.029053748937210654,
8655 lp_dark_hcos = 1.3346761652952872,
8656 lp_dark_hsin = -0.1698908144723919;
8657 const cs_cos1 = -0.195370576218515,
8658 cs_sin1 = 0.5330819227283227;
8659 const cs_cos2 = 0.08863325582067766,
8660 cs_sin2 = 0.9365540137751136;
8661 const cs_cos3 = 0.13789738139719568,
8662 cs_sin3 = 0.061650260197979936;
8663 const cs_cos4 = 0.0641970862504494,
8664 cs_sin4 = -0.027401052793571013;
8665 const cp_cos1 = -0.09900209889026965,
8666 cp_sin1 = 0.059635520647228726;
8667 const cp_cos2 = -0.013586499967803128,
8668 cp_sin2 = 0.2253393118474472;
8669 const lc1 = -1.5239477450767043,
8670 lc2 = -1.751157310240011;
8671 const hlc_cos1 = -0.43576378069144767,
8672 hlc_sin1 = 1.060094063845983;
8673 const hlc_cos2 = 0.47931193034584496,
8674 hlc_sin2 = -0.2622579649434462;
8675 const hl_cos1 = 0.13610794232685908,
8676 hl_sin1 = 0.1168702235362288;
8677 const hl_cos2 = -0.01617739641422492,
8678 hl_sin2 = 0.038145638815030566;
8679
8680 // Rigid rotation φ = −28.2°
8681 const PHI = -28.2 * PI / 180;
8682 const ROT_COS = cos(PHI);
8683 const ROT_SIN = sin(PHI);
8684
8685 // ── Pipeline helper functions ──────────────────────────────────────
8686
8687 function hueDelta(h) {
8688 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);
8689 }
8690 function hueDeltaDeriv(h) {
8691 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);
8692 }
8693 function chromaScaleH(h) {
8694 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);
8695 return exp(logS);
8696 }
8697 function lChromaScale(L) {
8698 let dL = L - 0.5;
8699 return exp(clamp(-30, lc1 * dL + lc2 * dL * dL, 30));
8700 }
8701 function hlcScale(h, L) {
8702 let hueFactor = hlc_cos1 * cos(h) + hlc_sin1 * sin(h) + hlc_cos2 * cos(2 * h) + hlc_sin2 * sin(2 * h);
8703 return exp(clamp(-30, (L - 0.5) * hueFactor, 30));
8704 }
8705 function hueLightnessScale(h) {
8706 let logS = hl_cos1 * cos(h) + hl_sin1 * sin(h) + hl_cos2 * cos(2 * h) + hl_sin2 * sin(2 * h);
8707 return exp(logS);
8708 }
8709 function chromaPowerH(h) {
8710 return 1 + cp_cos1 * cos(h) + cp_sin1 * sin(h) + cp_cos2 * cos(2 * h) + cp_sin2 * sin(2 * h);
8711 }
8712 function lCorrectFwd(L, h) {
8713 let t = L * (1 - L);
8714 let result = L + L_corr_p1 * t + L_corr_p2 * t * (0.5 - L) + L_corr_p3 * t * t;
8715 result += t * (Lh_cos1 * cos(h) + Lh_sin1 * sin(h));
8716 return result;
8717 }
8718 function lCorrectInv(L1, h) {
8719 let Lh = Lh_cos1 * cos(h) + Lh_sin1 * sin(h);
8720 let L = L1;
8721 for (let i = 0; i < 15; i++) {
8722 let t = L * (1 - L);
8723 let dt = 1 - 2 * L;
8724 let f = L + (L_corr_p1 + Lh) * t + L_corr_p2 * t * (0.5 - L) + L_corr_p3 * t * t - L1;
8725 let dfdL = 1 + (L_corr_p1 + Lh) * dt + L_corr_p2 * (dt * (0.5 - L) - t) + L_corr_p3 * 2 * t * dt;
8726 if (abs(dfdL) < 1e-10) {
8727 dfdL = 1;
8728 }
8729 L -= f / dfdL;
8730 }
8731 return L;
8732 }
8733 function darkLFwd(L, h) {
8734 let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h);
8735 let oml = L < 1 ? 1 - L : 0; // clamp at L=1: identity for L≥1
8736 let g = coeff * L * oml * oml;
8737 return L * exp(clamp(-30, g, 30));
8738 }
8739 function darkLInv(Ln, h) {
8740 let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h);
8741 let L = Ln;
8742 for (let i = 0; i < 12; i++) {
8743 let oml = L < 1 ? 1 - L : 0;
8744 let g = coeff * L * oml * oml;
8745 let eg = exp(clamp(-30, g, 30));
8746 let f = L * eg - Ln;
8747 let gp = coeff * oml * (1 - 3 * L);
8748 let fp = eg * (1 + L * gp);
8749 if (abs(fp) < 1e-10) {
8750 fp = 1;
8751 }
8752 L -= f / fp;
8753 }
8754 return L;
8755 }
8756
8757 // ── Color space definition ─────────────────────────────────────────
8758 // Helmlab MetricSpace is the perceptual forward space behind `deltaEHelmlab`.
8759 // Its coordinate system is shaped to maximize ΔE prediction accuracy on
8760 // visual-difference datasets (COMBVD: BFD-P, Witt 1999, RIT-DuPont, Leeds),
8761 // not author convenience. As a result:
8762 // - the ab plane is asymmetric (the metric was fit to directionally
8763 // asymmetric human discrimination thresholds);
8764 // - the L axis exceeds 1 for highly chromatic colors because the
8765 // Helmholtz–Kohlrausch boost is modeled explicitly (high-chroma colors
8766 // appear brighter than equiluminant neutrals);
8767 // - the achromatic axis is not pinned to (0, 0) — the gray axis sits
8768 // slightly off-origin in this coordinate system. Distance is
8769 // translation-invariant, so this does not affect ΔE quality.
8770 //
8771 // For CSS-author-facing color authoring (palettes, gradients, gamut
8772 // mapping), use HelmGen (`helmgen`) instead. This space (`helmlab-metric`)
8773 // is exposed primarily so the metric forward is inspectable for
8774 // debugging, color-science exploration, and as the internal forward used
8775 // by `deltaEHelmlab`.
8776
8777 const fromXYZ = function (xyz) {
8778 // Stage 0: Chromatic adaptation (Color.js D65 → Helmlab D65)
8779 let adapted = multiply_v3_m3x3(xyz, M$9.CAT_TO_HELM);
8780
8781 // Stage 1: XYZ → LMS (M1)
8782 let [lms0, lms1, lms2] = multiply_v3_m3x3(adapted, M$9.M1);
8783
8784 // Stage 2: Power compression (signed)
8785 let c0 = spow(lms0, GAMMA[0]);
8786 let c1 = spow(lms1, GAMMA[1]);
8787 let c2 = spow(lms2, GAMMA[2]);
8788
8789 // Stage 3: LMS_c → Lab_raw (M2)
8790 let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M$9.M2);
8791
8792 // Stage 3.5: Hue correction (4-harmonic Fourier)
8793 let h = atan2(b, a);
8794 let C = sqrt(a * a + b * b);
8795 let delta = hueDelta(h);
8796 let hNew = h + delta;
8797 a = C * cos(hNew);
8798 b = C * sin(hNew);
8799
8800 // Stage 3.7: Helmholtz-Kohlrausch correction
8801 let Cr = sqrt(a * a + b * b);
8802 let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10));
8803 let hr = atan2(b, a);
8804 let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) + hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr);
8805 L += hkBoost * factor;
8806
8807 // Stage 4: Cubic L correction (with hue modulation)
8808 h = atan2(b, a);
8809 L = lCorrectFwd(L, h);
8810
8811 // Stage 4.5: Dark L compression
8812 h = atan2(b, a);
8813 L = darkLFwd(L, h);
8814
8815 // Stage 5: Hue-dependent chroma scaling
8816 h = atan2(b, a);
8817 let cs = chromaScaleH(h);
8818 a *= cs;
8819 b *= cs;
8820
8821 // Stage 5.5: Nonlinear chroma power
8822 h = atan2(b, a);
8823 C = sqrt(a * a + b * b);
8824 let p = chromaPowerH(h);
8825 let Cn = C > 0 ? pow(C, p) : 0;
8826 a = Cn * cos(h);
8827 b = Cn * sin(h);
8828
8829 // Stage 6: L-dependent chroma scaling
8830 let T = lChromaScale(L);
8831 a *= T;
8832 b *= T;
8833
8834 // Stage 6.5: HLC interaction
8835 h = atan2(b, a);
8836 let hlcS = hlcScale(h, L);
8837 a *= hlcS;
8838 b *= hlcS;
8839
8840 // Stage 8: Hue-dependent lightness scaling
8841 h = atan2(b, a);
8842 L *= hueLightnessScale(h);
8843
8844 // Stage 11: Rigid rotation (φ = −28.2°)
8845 let aRot = a * ROT_COS - b * ROT_SIN;
8846 let bRot = a * ROT_SIN + b * ROT_COS;
8847 return [L, aRot, bRot];
8848 };
8849 const toXYZ = function (lab) {
8850 let [L, a, b] = lab;
8851
8852 // Undo Stage 11: rotation
8853 let aUn = a * ROT_COS + b * ROT_SIN;
8854 let bUn = -a * ROT_SIN + b * ROT_COS;
8855 a = aUn;
8856 b = bUn;
8857
8858 // Undo Stage 8: hue-dep lightness
8859 let h = atan2(b, a);
8860 L /= hueLightnessScale(h);
8861
8862 // Undo Stage 6.5: HLC
8863 h = atan2(b, a);
8864 let hlcS = hlcScale(h, L);
8865 a /= hlcS;
8866 b /= hlcS;
8867
8868 // Undo Stage 6: L-dep chroma
8869 let T = lChromaScale(L);
8870 a /= T;
8871 b /= T;
8872
8873 // Undo Stage 5.5: chroma power
8874 h = atan2(b, a);
8875 let C = sqrt(a * a + b * b);
8876 let p = chromaPowerH(h);
8877 let Co = C > 0 ? pow(C, 1 / p) : 0;
8878 a = Co * cos(h);
8879 b = Co * sin(h);
8880
8881 // Undo Stage 5: chroma scaling
8882 h = atan2(b, a);
8883 let cs = chromaScaleH(h);
8884 a /= cs;
8885 b /= cs;
8886
8887 // Undo Stage 4.5: dark L
8888 h = atan2(b, a);
8889 L = darkLInv(L, h);
8890
8891 // Undo Stage 4: cubic L
8892 h = atan2(b, a);
8893 L = lCorrectInv(L, h);
8894
8895 // Undo Stage 3.7: H-K
8896 let Cr = sqrt(a * a + b * b);
8897 let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10));
8898 let hr = atan2(b, a);
8899 let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) + hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr);
8900 L -= hkBoost * factor;
8901
8902 // Undo Stage 3.5: hue correction (Newton iteration)
8903 let hOut = atan2(b, a);
8904 C = sqrt(a * a + b * b);
8905 let hRaw = hOut;
8906 for (let i = 0; i < 8; i++) {
8907 let f = hRaw + hueDelta(hRaw) - hOut;
8908 let fp = 1 + hueDeltaDeriv(hRaw);
8909 if (abs(fp) < 1e-10) {
8910 fp = 1;
8911 }
8912 hRaw -= f / fp;
8913 }
8914 a = C * cos(hRaw);
8915 b = C * sin(hRaw);
8916
8917 // Undo Stage 3: Lab → LMS_c (M2_inv)
8918 let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M$9.M2_INV);
8919
8920 // Undo Stage 2: power compression
8921 let l0 = spow(lc0, INV_GAMMA[0]);
8922 let l1 = spow(lc1, INV_GAMMA[1]);
8923 let l2 = spow(lc2, INV_GAMMA[2]);
8924
8925 // Undo Stage 1: LMS → XYZ (M1_inv)
8926 let xyz = multiply_v3_m3x3([l0, l1, l2], M$9.M1_INV);
8927
8928 // Undo Stage 0: Chromatic adaptation (Helmlab D65 → Color.js D65)
8929 return multiply_v3_m3x3(xyz, M$9.CAT_FROM_HELM);
8930 };
8931 var helmlab = new ColorSpace({
8932 id: "helmlab-metric",
8933 name: "Helmlab MetricSpace",
8934 cssId: "--helmlab-metric",
8935 coords: {
8936 l: {
8937 refRange: [0, 1.6],
8938 name: "Lightness"
8939 },
8940 a: {
8941 refRange: [-1.5, 1.5]
8942 },
8943 b: {
8944 refRange: [-1.5, 1.5]
8945 }
8946 },
8947 white: "D65",
8948 base: XYZ_D65,
8949 M: M$9,
8950 fromBase(xyz) {
8951 return fromXYZ(xyz);
8952 },
8953 toBase(lab) {
8954 return toXYZ(lab);
8955 }
8956 });
8957
8958 // Helmlab MetricSpace weighted distance (v21, 72 params).
8959 // Optimized on COMBVD human color-difference judgments.
8960 //
8961 // Formula:
8962 // SL = 1 + sl * (L_avg - 0.5)²
8963 // SC = 1 + sc * C_avg
8964 // raw = (ΔL²/SL² + wC * Δab²/SC²) ^ (p/2)
8965 // compressed = raw / (1 + c * raw)
8966 // ΔE = compressed ^ q
8967
8968 const sl = -0.9155125151657894;
8969 const sc = 2.9268353744941558;
8970 const wC = 3.966003089807536;
8971 const p = 1.9737081170404969;
8972 const compress = 52.473130649294724;
8973 const q = 0.47897301074925214;
8974
8975 /**
8976 * @param {import("../types.js").ColorTypes} color
8977 * @param {import("../types.js").ColorTypes} sample
8978 * @returns {number}
8979 */
8980 function deltaEHelmlab (color, sample) {
8981 [color, sample] = getColor([color, sample]);
8982 let [L1, a1, b1] = helmlab.from(color);
8983 let [L2, a2, b2] = helmlab.from(sample);
8984 let ΔL = L1 - L2;
8985 let Δa = a1 - a2;
8986 let Δb = b1 - b2;
8987
8988 // Pair-dependent weighting
8989 let Lavg = (L1 + L2) * 0.5;
8990 let SL = 1 + sl * (Lavg - 0.5) ** 2;
8991 let C1 = Math.sqrt(a1 ** 2 + b1 ** 2);
8992 let C2 = Math.sqrt(a2 ** 2 + b2 ** 2);
8993 let Cavg = (C1 + C2) * 0.5;
8994 let SC = 1 + sc * Cavg;
8995
8996 // Weighted Minkowski distance
8997 let raw = (ΔL ** 2 / SL ** 2 + wC * (Δa ** 2 + Δb ** 2) / SC ** 2) ** (p / 2);
8998
8999 // Monotonic compression
9000 let compressed = raw / (1 + compress * raw);
9001 return compressed ** q;
9002 }
9003
9004 /**
9005 * @packageDocumentation
9006 * This module defines all the builtin deltaE methods.
9007 */
9008 var deltaEMethods = {
9009 deltaE76,
9010 deltaECMC,
9011 deltaE2000,
9012 deltaEJz,
9013 deltaEITP,
9014 deltaEOK,
9015 deltaEOK2,
9016 deltaEHCT,
9017 deltaEHelmlab
9018 };
9019
9020 /** @typedef {keyof typeof import("./index.js").default extends `deltaE${infer Method}` ? Method : string} Methods */
9021
9022 /** @import { ColorTypes, PlainColorObject } from "./types.js" */
9023
9024 // Type re-exports
9025 /** @typedef {import("./types.js").ToGamutOptions} ToGamutOptions */
9026
9027 /**
9028 * Calculate the epsilon to 2 degrees smaller than the specified JND.
9029 * @param {number} jnd The target "just noticeable difference".
9030 * @returns {number}
9031 */
9032 function calcEpsilon(jnd) {
9033 // Calculate the epsilon to 2 degrees smaller than the specified JND.
9034
9035 const order = !jnd ? 0 : Math.floor(Math.log10(Math.abs(jnd)));
9036 // Limit to an arbitrary value to ensure value is never too small and causes infinite loops.
9037 return Math.max(parseFloat(`1e${order - 2}`), 1e-6);
9038 }
9039 const GMAPPRESET = {
9040 hct: {
9041 method: "hct.c",
9042 jnd: 2,
9043 deltaEMethod: "hct",
9044 blackWhiteClamp: {}
9045 },
9046 "hct-tonal": {
9047 method: "hct.c",
9048 jnd: 0,
9049 deltaEMethod: "hct",
9050 blackWhiteClamp: {
9051 channel: "hct.t",
9052 min: 0,
9053 max: 100
9054 }
9055 }
9056 };
9057
9058 /**
9059 * Force coordinates to be in gamut of a certain color space.
9060 * Mutates the color it is passed.
9061 * @overload
9062 * @param {ColorTypes} color
9063 * @param {ToGamutOptions} [options]
9064 * @returns {PlainColorObject}
9065 */
9066 /**
9067 * @overload
9068 * @param {ColorTypes} color
9069 * @param {string} [space]
9070 * @returns {PlainColorObject}
9071 */
9072 /**
9073 * @param {ColorTypes} color
9074 * @param {string & Partial<ToGamutOptions> | ToGamutOptions} [space]
9075 * @returns {PlainColorObject}
9076 */
9077 function toGamut(color, {
9078 method = defaults.gamut_mapping,
9079 space = undefined,
9080 deltaEMethod = "",
9081 jnd = 2,
9082 blackWhiteClamp = undefined
9083 } = {}) {
9084 color = getColor(color);
9085 if (isString(arguments[1])) {
9086 space = arguments[1];
9087 } else if (!space) {
9088 space = color.space;
9089 }
9090 space = ColorSpace.get(space);
9091
9092 // 3 spaces:
9093 // color.space: current color space
9094 // space: space whose gamut we are mapping to
9095 // mapSpace: space with the coord we're reducing
9096
9097 if (inGamut(color, space, {
9098 epsilon: 0
9099 })) {
9100 return /** @type {PlainColorObject} */color;
9101 }
9102 let spaceColor;
9103 if (method === "css") {
9104 spaceColor = toGamutCSS(color, {
9105 space
9106 });
9107 } else if (method === "raytrace") {
9108 spaceColor = toGamutRayTrace(color, {
9109 space
9110 });
9111 } else {
9112 if (method !== "clip") {
9113 if (Object.prototype.hasOwnProperty.call(GMAPPRESET, method)) {
9114 ({
9115 method,
9116 jnd,
9117 deltaEMethod,
9118 blackWhiteClamp
9119 } = GMAPPRESET[method]);
9120 }
9121
9122 // Get the correct delta E method
9123 let de = deltaE2000;
9124 if (deltaEMethod !== "") {
9125 for (let m in deltaEMethods) {
9126 if ("deltae" + deltaEMethod.toLowerCase() === m.toLowerCase()) {
9127 de = deltaEMethods[m];
9128 break;
9129 }
9130 }
9131 }
9132 if (jnd === 0) {
9133 jnd = 1e-16;
9134 }
9135 let clipped = toGamut(to(color, space), {
9136 method: "clip",
9137 space
9138 });
9139 if (de(color, clipped) > jnd) {
9140 // Clamp to SDR white and black if required
9141 if (blackWhiteClamp && Object.keys(blackWhiteClamp).length === 3) {
9142 let channelMeta = ColorSpace.resolveCoord(blackWhiteClamp.channel);
9143 let channel = get(to(color, channelMeta.space), channelMeta.id);
9144 if (isNone(channel)) {
9145 channel = 0;
9146 }
9147 if (channel >= blackWhiteClamp.max) {
9148 return to({
9149 space: "xyz-d65",
9150 coords: WHITES["D65"]
9151 }, color.space);
9152 } else if (channel <= blackWhiteClamp.min) {
9153 return to({
9154 space: "xyz-d65",
9155 coords: [0, 0, 0]
9156 }, color.space);
9157 }
9158 }
9159
9160 // Reduce a coordinate of a certain color space until the color is in gamut
9161 let coordMeta = ColorSpace.resolveCoord(method);
9162 let mapSpace = coordMeta.space;
9163 let coordId = coordMeta.id;
9164 let mappedColor = to(color, mapSpace);
9165 // If we were already in the mapped color space, we need to resolve undefined channels
9166 mappedColor.coords.forEach((c, i) => {
9167 if (isNone(c)) {
9168 mappedColor.coords[i] = 0;
9169 }
9170 });
9171 let bounds = coordMeta.range || coordMeta.refRange;
9172 let min = bounds[0];
9173 let ε = calcEpsilon(jnd);
9174 let low = min;
9175 let high = get(mappedColor, coordId);
9176 while (high - low > ε) {
9177 let clipped = clone(mappedColor);
9178 clipped = toGamut(clipped, {
9179 space,
9180 method: "clip"
9181 });
9182 let deltaE = de(mappedColor, clipped);
9183 if (deltaE - jnd < ε) {
9184 low = get(mappedColor, coordId);
9185 } else {
9186 high = get(mappedColor, coordId);
9187 }
9188 set(mappedColor, coordId, (low + high) / 2);
9189 }
9190 spaceColor = to(mappedColor, space);
9191 } else {
9192 spaceColor = clipped;
9193 }
9194 } else {
9195 spaceColor = to(color, space);
9196 }
9197 if (method === "clip" ||
9198 // Dumb coord clipping
9199 // finish off smarter gamut mapping with clip to get rid of ε, see #17
9200 !inGamut(spaceColor, space, {
9201 epsilon: 0
9202 })) {
9203 let bounds = Object.values(space.coords).map(c => c.range || []);
9204 spaceColor.coords = /** @type {[number, number, number]} */
9205 spaceColor.coords.map((c, i) => {
9206 let [min, max] = bounds[i];
9207 if (min !== undefined) {
9208 c = Math.max(min, c);
9209 }
9210 if (max !== undefined) {
9211 c = Math.min(c, max);
9212 }
9213 return c;
9214 });
9215 }
9216 }
9217 if (space !== color.space) {
9218 spaceColor = to(spaceColor, color.space);
9219 }
9220 color.coords = spaceColor.coords;
9221 return /** @type {PlainColorObject} */color;
9222 }
9223
9224 /** @type {"color"} */
9225 toGamut.returns = "color";
9226
9227 /**
9228 * The reference colors to be used if lightness is out of the range 0-1 in the
9229 * `Oklch` space. These are created in the `Oklab` space, as it is used by the
9230 * DeltaEOK calculation, so it is guaranteed to be imported.
9231 * @satisfies {Record<string, ColorTypes>}
9232 */
9233 const COLORS = {
9234 WHITE: {
9235 space: Oklab,
9236 coords: [1, 0, 0],
9237 alpha: 1
9238 },
9239 BLACK: {
9240 space: Oklab,
9241 coords: [0, 0, 0],
9242 alpha: 1
9243 }
9244 };
9245
9246 /**
9247 * Given a color `origin`, returns a new color that is in gamut using
9248 * the CSS Gamut Mapping Algorithm. If `space` is specified, it will be in gamut
9249 * in `space`, and returned in `space`. Otherwise, it will be in gamut and
9250 * returned in the color space of `origin`.
9251 * @param {ColorTypes} origin
9252 * @param {{ space?: string | ColorSpace | undefined }} options
9253 * @returns {PlainColorObject}
9254 */
9255 function toGamutCSS(origin, {
9256 space
9257 } = {}) {
9258 const JND = 0.02;
9259 const ε = 0.0001;
9260 origin = getColor(origin);
9261 if (!space) {
9262 space = origin.space;
9263 }
9264 space = ColorSpace.get(space);
9265 if (space.isUnbounded) {
9266 return to(origin, space);
9267 }
9268 const origin_OKLCH = to(origin, OKLCH);
9269 let L = origin_OKLCH.coords[0];
9270
9271 // return media white or black, if lightness is out of range
9272 if (L >= 1) {
9273 const white = to(COLORS.WHITE, space);
9274 white.alpha = origin.alpha;
9275 return to(white, space);
9276 }
9277 if (L <= 0) {
9278 const black = to(COLORS.BLACK, space);
9279 black.alpha = origin.alpha;
9280 return to(black, space);
9281 }
9282 if (inGamut(origin_OKLCH, space, {
9283 epsilon: 0
9284 })) {
9285 return to(origin_OKLCH, space);
9286 }
9287 function clip(_color) {
9288 const destColor = to(_color, space);
9289 const spaceCoords = Object.values(/** @type {ColorSpace} */space.coords);
9290 destColor.coords = /** @type {[number, number, number]} */
9291 destColor.coords.map((coord, index) => {
9292 if ("range" in spaceCoords[index]) {
9293 const [min, max] = spaceCoords[index].range;
9294 return clamp(min, coord, max);
9295 }
9296 return coord;
9297 });
9298 return destColor;
9299 }
9300 let min = 0;
9301 let max = origin_OKLCH.coords[1];
9302 let min_inGamut = true;
9303 let current = clone(origin_OKLCH);
9304 let clipped = clip(current);
9305 let E = deltaEOK(clipped, current);
9306 if (E < JND) {
9307 return clipped;
9308 }
9309 while (max - min > ε) {
9310 const chroma = (min + max) / 2;
9311 current.coords[1] = chroma;
9312 if (min_inGamut && inGamut(current, space, {
9313 epsilon: 0
9314 })) {
9315 min = chroma;
9316 } else {
9317 clipped = clip(current);
9318 E = deltaEOK(clipped, current);
9319 if (E < JND) {
9320 if (JND - E < ε) {
9321 break;
9322 } else {
9323 min_inGamut = false;
9324 min = chroma;
9325 }
9326 } else {
9327 max = chroma;
9328 }
9329 }
9330 }
9331 return clipped;
9332 }
9333
9334 /**
9335 * Given `start` and `end` coordinates of a 3D ray and a `bmin` and `bmax` bounding box,
9336 * find the intersection of the ray and box. Return an empty list if no intersect is found.`
9337 * @param {[number, number, number]} start
9338 * @param {[number, number, number]} end
9339 * @param {[number, number, number]} bmin
9340 * @param {[number, number, number]} bmax
9341 * @returns {[number, number, number] | []}
9342 */
9343 function raytrace_box(start, end, bmin = [0, 0, 0], bmax = [1, 1, 1]) {
9344 // Use slab method to detect intersection of ray and box and return intersect.
9345 // https://en.wikipedia.org/wiki/Slab_method
9346
9347 // Calculate whether there was a hit
9348 let tfar = Infinity;
9349 let tnear = -Infinity;
9350 let direction = [];
9351 for (let i = 0; i < 3; i++) {
9352 const a = start[i];
9353 const b = end[i];
9354 const d = b - a;
9355 const bn = bmin[i];
9356 const bx = bmax[i];
9357 direction.push(d);
9358
9359 // Non parallel cases
9360 // 1e-12 for 64 bit unit types and 1e-6 for 32 bit unit types
9361 if (Math.abs(d) > 1e-12) {
9362 const inv_d = 1 / d;
9363 const t1 = (bn - a) * inv_d;
9364 const t2 = (bx - a) * inv_d;
9365 tnear = Math.max(Math.min(t1, t2), tnear);
9366 tfar = Math.min(Math.max(t1, t2), tfar);
9367 }
9368
9369 // Impossible parallel case
9370 else if (a < bn || a > bx) {
9371 return [];
9372 }
9373 }
9374
9375 // No hit
9376 if (tnear > tfar || tfar < 0) {
9377 return [];
9378 }
9379
9380 // Favor the intersection first in the direction start -> end
9381 if (tnear < 0) {
9382 tnear = tfar;
9383 }
9384
9385 // A point, or something approaching a single point where start and end are the same.
9386 if (!isFinite(tnear)) {
9387 return [];
9388 }
9389
9390 // Calculate nearest intersection via interpolation
9391 return [start[0] + direction[0] * tnear, start[1] + direction[1] * tnear, start[2] + direction[2] * tnear];
9392 }
9393
9394 /**
9395 * Given a color `origin`, returns a new color that is in gamut using
9396 * the CSS Ray Trace Gamut Mapping Algorithm. If `space` is specified,
9397 * it will be in gamut `space`, and returned in `space`. Otherwise,
9398 * it will be in gamut and returned in the color space of `origin`.
9399 * @param {ColorTypes} origin
9400 * @param {{ space?: string | ColorSpace | undefined }} options
9401 * @returns {PlainColorObject}
9402 */
9403 function toGamutRayTrace(origin, {
9404 space
9405 } = {}) {
9406 origin = getColor(origin);
9407 if (!space) {
9408 space = origin.space;
9409 }
9410 space = ColorSpace.get(space);
9411
9412 // If the space is already in gamut, stop.
9413 if (space.isUnbounded) {
9414 return to(origin, space);
9415 }
9416
9417 // Get the OkLCh coordinates.
9418 let oklchOrigin = to(origin, OKLCH);
9419 let [lightness, chroma, hue] = oklchOrigin.coords;
9420
9421 // Return white or black if color's lightness exceeds the SDR range.
9422 if (lightness >= 1) {
9423 const white = to(COLORS.WHITE, space);
9424 white.alpha = origin.alpha;
9425 return to(white, space);
9426 } else if (lightness <= 0) {
9427 const black = to(COLORS.BLACK, space);
9428 black.alpha = origin.alpha;
9429 return to(black, space);
9430 }
9431
9432 // Get a copy of the origin color as the RGB target space.
9433 const originSpace = space;
9434 const rGamut = space.rgbGamut;
9435 if (rGamut !== undefined) {
9436 space = rGamut;
9437 }
9438 if (!isInstance(space, RGBColorSpace)) {
9439 throw Error('An RGB gamut is required');
9440 }
9441
9442 // Get SDR bounds. Some HDR spaces have headroom, so reduce max to SDR range.
9443 let [mn, mx] = Object.values(space.coords)[0].range;
9444 let max = /** @type {[number, number, number]} */[mx, mx, mx];
9445
9446 // See if we have a linear version of the color space
9447 const lGamut = space.linearGamut;
9448 if (lGamut !== undefined) {
9449 // Recalculate minimum and maximum relative to the linear space
9450 let temp = to({
9451 space: space,
9452 coords: max,
9453 alpha: origin.alpha
9454 }, lGamut);
9455 mx = temp.coords[0];
9456 max = /** @type {[number, number, number]} */[mx, mx, mx];
9457 space = lGamut;
9458 mn = Object.values(space.coords)[0].range[0];
9459 }
9460 let min = /** @type {[number, number, number]} */[mn, mn, mn];
9461 let rgbOrigin = to(oklchOrigin, space);
9462 if (!rgbOrigin.coords.every(x => mn <= x && x <= mx)) {
9463 // If this were performed within a perceptual space like CAM16, which has achromatics that do not align
9464 // with the RGB achromatic line, projecting the color onto the RGB achromatic line may be preferable,
9465 // but since OkLCh's achromatics align with all CSS RGB spaces, just set chroma to zero.
9466 let anchor = to({
9467 space: OKLCH,
9468 coords: [lightness, 0, hue]
9469 }, space).coords;
9470
9471 // Calculate bounds to adjust the anchor closer to the gamut surface.
9472 // We don't want to make the ray too short, so offset some amount from the low and high range.
9473 // 1e-12 for 64 bit unit types and 1e-6 for 32 bit unit types.
9474 const low = mn + 1e-12;
9475 const high = mx - 1e-12;
9476
9477 // Cast a ray from the zero chroma color to the target color.
9478 // Trace the line to the RGB cube edge and find where it intersects.
9479 // Correct L and h within the perceptual OkLCh after each attempt.
9480 let last = rgbOrigin.coords;
9481 for (let i = 0; i < 4; i++) {
9482 if (i) {
9483 // For constant luminance, we correct the color by simply setting lightness and hue to
9484 // match the original color. In a non constant luminance reduction, it is better to
9485 // project the color onto the reduction path vector.
9486 const oklchColor = to(rgbOrigin, OKLCH);
9487 oklchColor.coords[0] = lightness;
9488 oklchColor.coords[2] = hue;
9489 rgbOrigin = to(oklchColor, space);
9490 }
9491 // Cast a ray from the achromatic anchor to the RGB target and find the gamut intersection.
9492 const intersection = raytrace_box(anchor, rgbOrigin.coords, min, max);
9493
9494 // If we cannot find an intersection, reset to last successful iteration of the color.
9495 // In OkLCh, this is only likely to happen if our ray gets too small, in that case, it is time to stop.
9496 if (intersection.length === 0) {
9497 rgbOrigin.coords = [...last];
9498 break;
9499 }
9500
9501 // Adjust anchor point closer to surface, when possible, to improve results for some spaces.
9502 if (i && rgbOrigin.coords.every(x => low < x && x < high)) {
9503 anchor = [...rgbOrigin.coords];
9504 }
9505
9506 // If we have an intersection, update the color.
9507 last = /** @type {[number, number, number]} */intersection;
9508 rgbOrigin.coords = [...intersection];
9509 }
9510 }
9511
9512 // Convert to the original, specified gamut
9513 rgbOrigin = to(rgbOrigin, originSpace);
9514 const spaceCoords = Object.values(/** @type {ColorSpace} */originSpace.coords);
9515
9516 // Remove noise from floating point math by clipping
9517 rgbOrigin.coords = /** @type {[number, number, number]} */
9518 rgbOrigin.coords.map((coord, index) => {
9519 if ("range" in spaceCoords[index]) {
9520 const [lower, upper] = spaceCoords[index].range;
9521 return clamp(lower, coord, upper);
9522 }
9523 return coord;
9524 });
9525 return rgbOrigin;
9526 }
9527
9528 /** @import { SpaceOptions } from "./ColorSpace.js" */
9529
9530 /**
9531 * A color space whose chroma-like coordinate is expressed relative to an RGB gamut: chroma = 1 is
9532 * the most colorful in-gamut color for the rest of the coordinates, so any chroma in [0, 1] stays
9533 * in gamut. The reduced coordinate (`chroma`, default `"c"`) is rescaled against `gamutSpace`; every
9534 * other coordinate is inherited unchanged from `base`. Works for any base whose chroma coordinate
9535 * brings the color into gamut as it is reduced (e.g. OKLCh, LCH).
9536 */
9537 class GamutRelativeColorSpace extends ColorSpace {
9538 /**
9539 * @param {SpaceOptions & { gamutSpace: string | ColorSpace, chroma?: string }} options
9540 * Requires `base` (the source space) and `gamutSpace` (the RGB gamut). `chroma` names the
9541 * coordinate to rescale (default `"c"`).
9542 */
9543 constructor(options) {
9544 var _options$chroma, _options$coords, _options$formats;
9545 let base = ColorSpace.get(options.base);
9546 let chroma = (_options$chroma = options.chroma) !== null && _options$chroma !== void 0 ? _options$chroma : "c";
9547 let ids = Object.keys(base.coords);
9548 let chromaIndex = ids.indexOf(chroma);
9549 if (chromaIndex === -1) {
9550 throw new TypeError(`GamutRelativeColorSpace needs a "${chroma}" coordinate, got ${base.id}`);
9551 }
9552
9553 // Inherit the base's coords; the reduced coordinate becomes a 0–1 fraction of its gamut maximum
9554 let coords = Object.fromEntries(Object.entries(base.coords).map(([id, meta]) => [id, {
9555 ...meta
9556 }]));
9557 coords[chroma].range = [0, 1];
9558 delete coords[chroma].refRange;
9559 (_options$coords = options.coords) !== null && _options$coords !== void 0 ? _options$coords : options.coords = coords;
9560
9561 // Serialize the reduced coordinate and any other 0–1 coordinate as percentages; angles as angles
9562 (_options$formats = options.formats) !== null && _options$formats !== void 0 ? _options$formats : options.formats = {
9563 color: {
9564 coords: ids.map(id => {
9565 var _ref, _base$coords$id$range;
9566 if (base.coords[id].type === "angle") {
9567 return "<number> | <angle>";
9568 }
9569 let [min, max] = (_ref = (_base$coords$id$range = base.coords[id].range) !== null && _base$coords$id$range !== void 0 ? _base$coords$id$range : base.coords[id].refRange) !== null && _ref !== void 0 ? _ref : [];
9570 let pctFirst = id === chroma || min === 0 && max === 1;
9571 return pctFirst ? "<percentage> | <number>" : "<number> | <percentage>";
9572 })
9573 }
9574 };
9575 super(options);
9576 this.chromaIndex = chromaIndex;
9577 this.method = `${base.id}.${chroma}`;
9578
9579 // A chroma that is out of gamut at every lightness and hue: the gamut's most saturated corner
9580 // (its primaries/secondaries are its chroma maxima) plus headroom. Seeding the gamut search
9581 // from here lands on the first in-gamut crossing — the highest contiguous in-gamut chroma —
9582 // and avoids clamping wide gamuts (e.g. Rec.2020 exceeds OKLCh's nominal 0.4 chroma).
9583 // prettier-ignore
9584 let corners = /** @type {[number, number, number][]} */
9585 [[0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0]];
9586 this.oogChroma = 1.01 * Math.max(...corners.map(rgb => base.from(this.gamutSpace, rgb)[this.chromaIndex] || 0));
9587 }
9588
9589 /**
9590 * The highest in-gamut value of the reduced coordinate for the given coordinates. The reduced
9591 * coordinate's own value is ignored; the others determine the result.
9592 * @param {number[]} coords
9593 * @returns {number}
9594 */
9595 maxChroma(coords) {
9596 let seed = /** @type {[number, number, number]} */[...coords];
9597 seed[this.chromaIndex] = this.oogChroma;
9598 return toGamut({
9599 space: this.base,
9600 coords: seed
9601 },
9602 // deltaE OK stays sensitive near black, where deltaE 2000 is too forgiving of excess chroma
9603 {
9604 space: this.gamutSpace,
9605 method: this.method,
9606 deltaEMethod: "OK",
9607 jnd: 0
9608 }).coords[this.chromaIndex];
9609 }
9610 toBase(coords) {
9611 coords = [...coords];
9612 if (coords.some((c, i) => i !== this.chromaIndex && isNone(c))) {
9613 // chroma is a fraction of maxChroma(the other coords); without them all it is undefined
9614 if (coords[this.chromaIndex] !== 0) {
9615 coords[this.chromaIndex] = null;
9616 }
9617 } else if (!isNone(coords[this.chromaIndex])) {
9618 coords[this.chromaIndex] *= this.maxChroma(coords);
9619 }
9620 return coords;
9621 }
9622 fromBase(coords) {
9623 coords = [...coords];
9624 if (coords.some((c, i) => i !== this.chromaIndex && isNone(c))) {
9625 if (coords[this.chromaIndex] !== 0) {
9626 coords[this.chromaIndex] = null;
9627 }
9628 } else if (!isNone(coords[this.chromaIndex])) {
9629 let cMax = this.maxChroma(coords);
9630 coords[this.chromaIndex] = cMax ? coords[this.chromaIndex] / cMax : 0;
9631 }
9632 return coords;
9633 }
9634 }
9635
9636 /** @import { ColorTypes, PlainColorObject } from "./types.js" */
9637
9638 // Type re-exports
9639 /** @typedef {import("./types.js").TryColorOptions} TryColorOptions */
9640
9641 /**
9642 * Resolves a color reference (object or string) to a plain color object, or `null` if resolution fails.
9643 * Can resolve more complex CSS colors (e.g. relative colors, `calc()`, CSS variables, `color-mix()`, etc.) through the DOM.
9644 *
9645 * @overload
9646 * @param {ColorTypes} color
9647 * @param {TryColorOptions} [options]
9648 * @returns {PlainColorObject | null}
9649 */
9650 /**
9651 * @overload
9652 * @param {ColorTypes[]} color
9653 * @param {TryColorOptions} [options]
9654 * @returns {(PlainColorObject | null)[]}
9655 */
9656 function tryColor(color, options = {}) {
9657 if (Array.isArray(color)) {
9658 return color.map(c => tryColor(c, options));
9659 }
9660 let {
9661 cssProperty = "background-color",
9662 element,
9663 ...getColorOptions
9664 } = options;
9665 let error = null;
9666 try {
9667 return getColor(color, getColorOptions);
9668 } catch (e) {
9669 error = e;
9670 }
9671 let {
9672 CSS,
9673 getComputedStyle
9674 } = globalThis;
9675 if (isString(color) && element && CSS && getComputedStyle) {
9676 // Try resolving the color using the DOM, if supported in CSS
9677 if (CSS.supports(cssProperty, color)) {
9678 let previousValue = element.style[cssProperty];
9679 if (color !== previousValue) {
9680 element.style[cssProperty] = color;
9681 }
9682 let computedColor = getComputedStyle(element).getPropertyValue(cssProperty);
9683 if (color !== previousValue) {
9684 element.style[cssProperty] = previousValue;
9685 }
9686 if (computedColor !== color) {
9687 // getComputedStyle() changed the color, try again
9688 try {
9689 return getColor(computedColor, getColorOptions);
9690 } catch (e) {
9691 error = e;
9692 }
9693 } else {
9694 // Still not resolved
9695 error = {
9696 message: "Color value is a valid CSS color, but it could not be resolved :("
9697 };
9698 }
9699 }
9700 }
9701
9702 // If we're here, we failed to resolve the color
9703 if (options.errorMeta) {
9704 options.errorMeta.error = error;
9705 }
9706 return null;
9707 }
9708
9709 /** @import { ColorTypes, ParseOptions, PlainColorObject } from "./types.js" */
9710
9711 // Type re-exports
9712 /** @typedef {import("./types.js").SerializeOptions} SerializeOptions */
9713
9714 /**
9715 * Generic toString() method, outputs a color(spaceId ...coords) function, a functional syntax, or custom formats defined by the color space
9716 * @param {ColorTypes} color
9717 * @param {SerializeOptions & Record<string, any>} options
9718 * @returns {string}
9719 */
9720 function serialize(color, options = {}) {
9721 let {
9722 precision = defaults.precision,
9723 format,
9724 inGamut: inGamut$1 = true,
9725 coords: coordFormat,
9726 alpha: alphaFormat,
9727 commas
9728 } = options;
9729 let ret;
9730 let colorWithMeta = /** @type {PlainColorObject & ParseOptions} */getColor(color);
9731 let formatId = format;
9732 let parseMeta = colorWithMeta.parseMeta;
9733 if (parseMeta && !format) {
9734 var _coordFormat, _alphaFormat, _commas;
9735 if (parseMeta.format.canSerialize()) {
9736 format = parseMeta.format;
9737 formatId = parseMeta.formatId;
9738 }
9739 (_coordFormat = coordFormat) !== null && _coordFormat !== void 0 ? _coordFormat : coordFormat = parseMeta.types;
9740 (_alphaFormat = alphaFormat) !== null && _alphaFormat !== void 0 ? _alphaFormat : alphaFormat = parseMeta.alphaType;
9741 (_commas = commas) !== null && _commas !== void 0 ? _commas : commas = parseMeta.commas;
9742 }
9743 if (formatId) {
9744 var _colorWithMeta$space$;
9745 // A format is explicitly specified
9746 format = (_colorWithMeta$space$ = colorWithMeta.space.getFormat(format)) !== null && _colorWithMeta$space$ !== void 0 ? _colorWithMeta$space$ : ColorSpace.findFormat(formatId);
9747 }
9748 if (!format) {
9749 var _colorWithMeta$space$2;
9750 // No format specified, or format not found
9751 format = (_colorWithMeta$space$2 = colorWithMeta.space.getFormat("default")) !== null && _colorWithMeta$space$2 !== void 0 ? _colorWithMeta$space$2 : ColorSpace.DEFAULT_FORMAT;
9752 formatId = format.name;
9753 }
9754 if (format && format.space && format.space !== colorWithMeta.space) {
9755 // Format specified belongs to a different color space,
9756 // need to convert to it first
9757 colorWithMeta = to(colorWithMeta, format.space);
9758 }
9759
9760 // The assignment to coords and inGamut needs to stay in the order they are now
9761 // The order of the assignment was changed as a workaround for a bug in Next.js
9762 // See this issue for details: https://github.com/color-js/color.js/issues/260
9763
9764 let coords = colorWithMeta.coords.slice(); // clone so we can manipulate it
9765
9766 inGamut$1 || (inGamut$1 = format.toGamut);
9767 if (inGamut$1 && !inGamut(colorWithMeta)) {
9768 // FIXME what happens if the color contains none values?
9769 coords = toGamut(clone(colorWithMeta), inGamut$1 === true ? undefined : inGamut$1).coords;
9770 }
9771 if (format.type === "custom") {
9772 if (format.serialize) {
9773 ret = format.serialize(coords, colorWithMeta.alpha, options);
9774 } else {
9775 throw new TypeError(`format ${formatId} can only be used to parse colors, not for serialization`);
9776 }
9777 } else {
9778 var _alphaFormat$type, _alphaFormat2, _alphaFormat3, _alphaFormat4, _commas2;
9779 // Functional syntax
9780 let name = format.name || "color";
9781 let args = format.serializeCoords(coords, precision, coordFormat);
9782 if (name === "color") {
9783 var _format$ids;
9784 // If output is a color() function, add colorspace id as first argument
9785 let cssId = format.id || ((_format$ids = format.ids) === null || _format$ids === void 0 ? void 0 : _format$ids[0]) || colorWithMeta.space.cssId || colorWithMeta.space.id;
9786 args.unshift(cssId);
9787 }
9788
9789 // Serialize alpha?
9790 /** @type {string | number} */
9791 let alpha = colorWithMeta.alpha;
9792 if (alphaFormat !== undefined && !(typeof alphaFormat === "object")) {
9793 alphaFormat = typeof alphaFormat === "string" ? {
9794 type: alphaFormat
9795 } : {
9796 include: alphaFormat
9797 };
9798 }
9799 let alphaType = (_alphaFormat$type = (_alphaFormat2 = alphaFormat) === null || _alphaFormat2 === void 0 ? void 0 : _alphaFormat2.type) !== null && _alphaFormat$type !== void 0 ? _alphaFormat$type : "<number>";
9800 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;
9801 let strAlpha = "";
9802 (_commas2 = commas) !== null && _commas2 !== void 0 ? _commas2 : commas = format.commas;
9803 if (serializeAlpha) {
9804 if (precision !== null) {
9805 let unit;
9806 if (alphaType === "<percentage>") {
9807 unit = "%";
9808 alpha *= 100;
9809 }
9810 alpha = serializeNumber(alpha, {
9811 precision,
9812 unit
9813 });
9814 }
9815 strAlpha = `${commas ? "," : " /"} ${alpha}`;
9816 }
9817 ret = `${name}(${args.join(commas ? ", " : " ")}${strAlpha})`;
9818 }
9819 return ret;
9820 }
9821
9822 var esnext_iterator_filter = {};
9823
9824 var es_iterator_filter = {};
9825
9826 var hasRequiredEs_iterator_filter;
9827
9828 function requireEs_iterator_filter () {
9829 if (hasRequiredEs_iterator_filter) return es_iterator_filter;
9830 hasRequiredEs_iterator_filter = 1;
9831 var $ = require_export();
9832 var call = requireFunctionCall();
9833 var aCallable = requireACallable();
9834 var anObject = requireAnObject();
9835 var getIteratorDirect = requireGetIteratorDirect();
9836 var createIteratorProxy = requireIteratorCreateProxy();
9837 var callWithSafeIterationClosing = requireCallWithSafeIterationClosing();
9838 var IS_PURE = requireIsPure();
9839
9840 var IteratorProxy = createIteratorProxy(function () {
9841 var iterator = this.iterator;
9842 var predicate = this.predicate;
9843 var next = this.next;
9844 var result, done, value;
9845 while (true) {
9846 result = anObject(call(next, iterator));
9847 done = this.done = !!result.done;
9848 if (done) return;
9849 value = result.value;
9850 if (callWithSafeIterationClosing(iterator, predicate, [value, this.counter++], true)) return value;
9851 }
9852 });
9853
9854 // `Iterator.prototype.filter` method
9855 // https://tc39.es/ecma262/#sec-iterator.prototype.filter
9856 $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
9857 filter: function filter(predicate) {
9858 anObject(this);
9859 aCallable(predicate);
9860 return new IteratorProxy(getIteratorDirect(this), {
9861 predicate: predicate
9862 });
9863 }
9864 });
9865 return es_iterator_filter;
9866 }
9867
9868 var hasRequiredEsnext_iterator_filter;
9869
9870 function requireEsnext_iterator_filter () {
9871 if (hasRequiredEsnext_iterator_filter) return esnext_iterator_filter;
9872 hasRequiredEsnext_iterator_filter = 1;
9873 // TODO: Remove from `core-js@4`
9874 requireEs_iterator_filter();
9875 return esnext_iterator_filter;
9876 }
9877
9878 requireEsnext_iterator_filter();
9879
9880 /** @import { Matrix3x3 } from "../types.js" */
9881
9882 /**
9883 * Matrices used by this color space, also available as `REC_2020_Linear.M`.
9884 * Uses D65 (no chromatic adaptation).
9885 * http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
9886 * @type {Record<string, Matrix3x3>}
9887 */
9888 // prettier-ignore
9889 const M$8 = {
9890 // 0 is actually calculated as 4.994106574466076e-17
9891 toXYZ: [[0.6369580483012914, 0.14461690358620832, 0.1688809751641721], [0.2627002120112671, 0.6779980715188708, 0.05930171646986196], [0.000000000000000, 0.028072693049087428, 1.060985057710791]],
9892 // from ITU-R BT.2124-0 Annex 2 p.3
9893 fromXYZ: [[1.716651187971268, -0.355670783776392, -0.253366281373660], [-0.666684351832489, 1.616481236634939, 0.0157685458139111], [0.017639857445311, -0.042770613257809, 0.942103121235474]]
9894 };
9895 var REC2020Linear = new RGBColorSpace({
9896 id: "rec2020-linear",
9897 cssId: "--rec2020-linear",
9898 name: "Linear REC.2020",
9899 white: "D65",
9900 M: M$8
9901 });
9902
9903 // import sRGB from "./srgb.js";
9904
9905 var REC2020 = new RGBColorSpace({
9906 id: "rec2020",
9907 name: "REC.2020",
9908 base: REC2020Linear,
9909 linearGamut: REC2020Linear,
9910 // Reference electro-optical transfer function from Rec. ITU-R BT.1886 Annex 1
9911 // with b (black lift) = 0 and a (user gain) = 1
9912 // defined over the extended range, not clamped
9913 toBase(RGB) {
9914 return RGB.map(function (val) {
9915 let sign = val < 0 ? -1 : 1;
9916 let abs = val * sign;
9917 return sign * Math.pow(abs, 2.4);
9918 });
9919 },
9920 fromBase(RGB) {
9921 return RGB.map(function (val) {
9922 let sign = val < 0 ? -1 : 1;
9923 let abs = val * sign;
9924 return sign * Math.pow(abs, 1 / 2.4);
9925 });
9926 }
9927 });
9928
9929 /** @import { Matrix3x3 } from "../types.js" */
9930
9931 /**
9932 * Matrices used by this color space, also available as `P3_Linear.M`
9933 * @type {Record<string, Matrix3x3>}
9934 */
9935 // prettier-ignore
9936 const M$7 = {
9937 toXYZ: [[0.4865709486482162, 0.26566769316909306, 0.1982172852343625], [0.2289745640697488, 0.6917385218365064, 0.079286914093745], [0.0000000000000000, 0.04511338185890264, 1.043944368900976]],
9938 fromXYZ: [[2.493496911941425, -0.9313836179191239, -0.40271078445071684], [-0.8294889695615747, 1.7626640603183463, 0.023624685841943577], [0.03584583024378447, -0.07617238926804182, 0.9568845240076872]]
9939 };
9940 var P3Linear = new RGBColorSpace({
9941 id: "p3-linear",
9942 cssId: "display-p3-linear",
9943 name: "Linear P3",
9944 white: "D65",
9945 M: M$7
9946 });
9947
9948 /** @import { Matrix3x3 } from "../types.js" */
9949
9950 // This is the linear-light version of sRGB
9951 // as used for example in SVG filters
9952 // or in Canvas
9953
9954 /**
9955 * Matrices used by this color space, also available as `sRGB_Linear.M`
9956 * @type {Record<string, Matrix3x3>}
9957 */
9958 // prettier-ignore
9959 const M$6 = {
9960 // calculated directly from the RGB and white chromaticities; when rounded to
9961 // 8 decimal places, agrees completely with the official matrix
9962 // see https://github.com/w3c/csswg-drafts/issues/5922
9963 toXYZ: [[0.41239079926595934, 0.357584339383878, 0.1804807884018343], [0.21263900587151027, 0.715168678767756, 0.07219231536073371], [0.01933081871559182, 0.11919477979462598, 0.9505321522496607]],
9964 // the inverse of the above; again agrees with the official definition
9965 // when rounded to 8 decimal places
9966 fromXYZ: [[3.2409699419045226, -1.537383177570094, -0.4986107602930034], [-0.9692436362808796, 1.8759675015077202, 0.04155505740717559], [0.05563007969699366, -0.20397695888897652, 1.0569715142428786]]
9967 };
9968 var sRGBLinear = new RGBColorSpace({
9969 id: "srgb-linear",
9970 name: "Linear sRGB",
9971 white: "D65",
9972 M: M$6
9973 });
9974
9975 // To produce: Visit https://www.w3.org/TR/css-color-4/#named-colors
9976 // and run in the console:
9977 // 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"))
9978
9979 /** List of CSS color keywords
9980 * Note that this does not include currentColor, transparent,
9981 * or system colors
9982 *
9983 * @type {Record<string, [number, number, number]>}
9984 */
9985 var KEYWORDS = {
9986 aliceblue: [240 / 255, 248 / 255, 1],
9987 antiquewhite: [250 / 255, 235 / 255, 215 / 255],
9988 aqua: [0, 1, 1],
9989 aquamarine: [127 / 255, 1, 212 / 255],
9990 azure: [240 / 255, 1, 1],
9991 beige: [245 / 255, 245 / 255, 220 / 255],
9992 bisque: [1, 228 / 255, 196 / 255],
9993 black: [0, 0, 0],
9994 blanchedalmond: [1, 235 / 255, 205 / 255],
9995 blue: [0, 0, 1],
9996 blueviolet: [138 / 255, 43 / 255, 226 / 255],
9997 brown: [165 / 255, 42 / 255, 42 / 255],
9998 burlywood: [222 / 255, 184 / 255, 135 / 255],
9999 cadetblue: [95 / 255, 158 / 255, 160 / 255],
10000 chartreuse: [127 / 255, 1, 0],
10001 chocolate: [210 / 255, 105 / 255, 30 / 255],
10002 coral: [1, 127 / 255, 80 / 255],
10003 cornflowerblue: [100 / 255, 149 / 255, 237 / 255],
10004 cornsilk: [1, 248 / 255, 220 / 255],
10005 crimson: [220 / 255, 20 / 255, 60 / 255],
10006 cyan: [0, 1, 1],
10007 darkblue: [0, 0, 139 / 255],
10008 darkcyan: [0, 139 / 255, 139 / 255],
10009 darkgoldenrod: [184 / 255, 134 / 255, 11 / 255],
10010 darkgray: [169 / 255, 169 / 255, 169 / 255],
10011 darkgreen: [0, 100 / 255, 0],
10012 darkgrey: [169 / 255, 169 / 255, 169 / 255],
10013 darkkhaki: [189 / 255, 183 / 255, 107 / 255],
10014 darkmagenta: [139 / 255, 0, 139 / 255],
10015 darkolivegreen: [85 / 255, 107 / 255, 47 / 255],
10016 darkorange: [1, 140 / 255, 0],
10017 darkorchid: [153 / 255, 50 / 255, 204 / 255],
10018 darkred: [139 / 255, 0, 0],
10019 darksalmon: [233 / 255, 150 / 255, 122 / 255],
10020 darkseagreen: [143 / 255, 188 / 255, 143 / 255],
10021 darkslateblue: [72 / 255, 61 / 255, 139 / 255],
10022 darkslategray: [47 / 255, 79 / 255, 79 / 255],
10023 darkslategrey: [47 / 255, 79 / 255, 79 / 255],
10024 darkturquoise: [0, 206 / 255, 209 / 255],
10025 darkviolet: [148 / 255, 0, 211 / 255],
10026 deeppink: [1, 20 / 255, 147 / 255],
10027 deepskyblue: [0, 191 / 255, 1],
10028 dimgray: [105 / 255, 105 / 255, 105 / 255],
10029 dimgrey: [105 / 255, 105 / 255, 105 / 255],
10030 dodgerblue: [30 / 255, 144 / 255, 1],
10031 firebrick: [178 / 255, 34 / 255, 34 / 255],
10032 floralwhite: [1, 250 / 255, 240 / 255],
10033 forestgreen: [34 / 255, 139 / 255, 34 / 255],
10034 fuchsia: [1, 0, 1],
10035 gainsboro: [220 / 255, 220 / 255, 220 / 255],
10036 ghostwhite: [248 / 255, 248 / 255, 1],
10037 gold: [1, 215 / 255, 0],
10038 goldenrod: [218 / 255, 165 / 255, 32 / 255],
10039 gray: [128 / 255, 128 / 255, 128 / 255],
10040 green: [0, 128 / 255, 0],
10041 greenyellow: [173 / 255, 1, 47 / 255],
10042 grey: [128 / 255, 128 / 255, 128 / 255],
10043 honeydew: [240 / 255, 1, 240 / 255],
10044 hotpink: [1, 105 / 255, 180 / 255],
10045 indianred: [205 / 255, 92 / 255, 92 / 255],
10046 indigo: [75 / 255, 0, 130 / 255],
10047 ivory: [1, 1, 240 / 255],
10048 khaki: [240 / 255, 230 / 255, 140 / 255],
10049 lavender: [230 / 255, 230 / 255, 250 / 255],
10050 lavenderblush: [1, 240 / 255, 245 / 255],
10051 lawngreen: [124 / 255, 252 / 255, 0],
10052 lemonchiffon: [1, 250 / 255, 205 / 255],
10053 lightblue: [173 / 255, 216 / 255, 230 / 255],
10054 lightcoral: [240 / 255, 128 / 255, 128 / 255],
10055 lightcyan: [224 / 255, 1, 1],
10056 lightgoldenrodyellow: [250 / 255, 250 / 255, 210 / 255],
10057 lightgray: [211 / 255, 211 / 255, 211 / 255],
10058 lightgreen: [144 / 255, 238 / 255, 144 / 255],
10059 lightgrey: [211 / 255, 211 / 255, 211 / 255],
10060 lightpink: [1, 182 / 255, 193 / 255],
10061 lightsalmon: [1, 160 / 255, 122 / 255],
10062 lightseagreen: [32 / 255, 178 / 255, 170 / 255],
10063 lightskyblue: [135 / 255, 206 / 255, 250 / 255],
10064 lightslategray: [119 / 255, 136 / 255, 153 / 255],
10065 lightslategrey: [119 / 255, 136 / 255, 153 / 255],
10066 lightsteelblue: [176 / 255, 196 / 255, 222 / 255],
10067 lightyellow: [1, 1, 224 / 255],
10068 lime: [0, 1, 0],
10069 limegreen: [50 / 255, 205 / 255, 50 / 255],
10070 linen: [250 / 255, 240 / 255, 230 / 255],
10071 magenta: [1, 0, 1],
10072 maroon: [128 / 255, 0, 0],
10073 mediumaquamarine: [102 / 255, 205 / 255, 170 / 255],
10074 mediumblue: [0, 0, 205 / 255],
10075 mediumorchid: [186 / 255, 85 / 255, 211 / 255],
10076 mediumpurple: [147 / 255, 112 / 255, 219 / 255],
10077 mediumseagreen: [60 / 255, 179 / 255, 113 / 255],
10078 mediumslateblue: [123 / 255, 104 / 255, 238 / 255],
10079 mediumspringgreen: [0, 250 / 255, 154 / 255],
10080 mediumturquoise: [72 / 255, 209 / 255, 204 / 255],
10081 mediumvioletred: [199 / 255, 21 / 255, 133 / 255],
10082 midnightblue: [25 / 255, 25 / 255, 112 / 255],
10083 mintcream: [245 / 255, 1, 250 / 255],
10084 mistyrose: [1, 228 / 255, 225 / 255],
10085 moccasin: [1, 228 / 255, 181 / 255],
10086 navajowhite: [1, 222 / 255, 173 / 255],
10087 navy: [0, 0, 128 / 255],
10088 oldlace: [253 / 255, 245 / 255, 230 / 255],
10089 olive: [128 / 255, 128 / 255, 0],
10090 olivedrab: [107 / 255, 142 / 255, 35 / 255],
10091 orange: [1, 165 / 255, 0],
10092 orangered: [1, 69 / 255, 0],
10093 orchid: [218 / 255, 112 / 255, 214 / 255],
10094 palegoldenrod: [238 / 255, 232 / 255, 170 / 255],
10095 palegreen: [152 / 255, 251 / 255, 152 / 255],
10096 paleturquoise: [175 / 255, 238 / 255, 238 / 255],
10097 palevioletred: [219 / 255, 112 / 255, 147 / 255],
10098 papayawhip: [1, 239 / 255, 213 / 255],
10099 peachpuff: [1, 218 / 255, 185 / 255],
10100 peru: [205 / 255, 133 / 255, 63 / 255],
10101 pink: [1, 192 / 255, 203 / 255],
10102 plum: [221 / 255, 160 / 255, 221 / 255],
10103 powderblue: [176 / 255, 224 / 255, 230 / 255],
10104 purple: [128 / 255, 0, 128 / 255],
10105 rebeccapurple: [102 / 255, 51 / 255, 153 / 255],
10106 red: [1, 0, 0],
10107 rosybrown: [188 / 255, 143 / 255, 143 / 255],
10108 royalblue: [65 / 255, 105 / 255, 225 / 255],
10109 saddlebrown: [139 / 255, 69 / 255, 19 / 255],
10110 salmon: [250 / 255, 128 / 255, 114 / 255],
10111 sandybrown: [244 / 255, 164 / 255, 96 / 255],
10112 seagreen: [46 / 255, 139 / 255, 87 / 255],
10113 seashell: [1, 245 / 255, 238 / 255],
10114 sienna: [160 / 255, 82 / 255, 45 / 255],
10115 silver: [192 / 255, 192 / 255, 192 / 255],
10116 skyblue: [135 / 255, 206 / 255, 235 / 255],
10117 slateblue: [106 / 255, 90 / 255, 205 / 255],
10118 slategray: [112 / 255, 128 / 255, 144 / 255],
10119 slategrey: [112 / 255, 128 / 255, 144 / 255],
10120 snow: [1, 250 / 255, 250 / 255],
10121 springgreen: [0, 1, 127 / 255],
10122 steelblue: [70 / 255, 130 / 255, 180 / 255],
10123 tan: [210 / 255, 180 / 255, 140 / 255],
10124 teal: [0, 128 / 255, 128 / 255],
10125 thistle: [216 / 255, 191 / 255, 216 / 255],
10126 tomato: [1, 99 / 255, 71 / 255],
10127 turquoise: [64 / 255, 224 / 255, 208 / 255],
10128 violet: [238 / 255, 130 / 255, 238 / 255],
10129 wheat: [245 / 255, 222 / 255, 179 / 255],
10130 white: [1, 1, 1],
10131 whitesmoke: [245 / 255, 245 / 255, 245 / 255],
10132 yellow: [1, 1, 0],
10133 yellowgreen: [154 / 255, 205 / 255, 50 / 255]
10134 };
10135
10136 /** @import { Coords } from "../types.js" */
10137
10138 let coordGrammar = Array(3).fill("<percentage> | <number>[0, 255]");
10139 let coordGrammarNumber = Array(3).fill("<number>[0, 255]");
10140 var sRGB = new RGBColorSpace({
10141 id: "srgb",
10142 name: "sRGB",
10143 base: sRGBLinear,
10144 linearGamut: sRGBLinear,
10145 fromBase: rgb => {
10146 // convert an array of linear-light sRGB values in the range 0.0-1.0
10147 // to gamma corrected form
10148 // https://en.wikipedia.org/wiki/SRGB
10149 return rgb.map(val => {
10150 let sign = val < 0 ? -1 : 1;
10151 let abs = val * sign;
10152 if (abs > 0.0031308) {
10153 return sign * (1.055 * abs ** (1 / 2.4) - 0.055);
10154 }
10155 return 12.92 * val;
10156 });
10157 },
10158 toBase: rgb => {
10159 // convert an array of sRGB values in the range 0.0 - 1.0
10160 // to linear light (un-companded) form.
10161 // https://en.wikipedia.org/wiki/SRGB
10162 return rgb.map(val => {
10163 let sign = val < 0 ? -1 : 1;
10164 let abs = val * sign;
10165 if (abs <= 0.04045) {
10166 return val / 12.92;
10167 }
10168 return sign * ((abs + 0.055) / 1.055) ** 2.4;
10169 });
10170 },
10171 formats: {
10172 rgb: {
10173 coords: coordGrammar
10174 },
10175 rgb_number: {
10176 name: "rgb",
10177 commas: true,
10178 coords: coordGrammarNumber,
10179 alpha: false
10180 },
10181 color: {
10182 /* use defaults */
10183 },
10184 rgba: {
10185 coords: coordGrammar,
10186 commas: true,
10187 alpha: true
10188 },
10189 rgba_number: {
10190 name: "rgba",
10191 commas: true,
10192 coords: coordGrammarNumber
10193 },
10194 hex: {
10195 type: "custom",
10196 toGamut: true,
10197 test: str => /^#(([a-f0-9]{2}){3,4}|[a-f0-9]{3,4})$/i.test(str),
10198 parse(str) {
10199 if (str.length <= 5) {
10200 // #rgb or #rgba, duplicate digits
10201 str = str.replace(/[a-f0-9]/gi, "$&$&");
10202 }
10203
10204 /** @type {number[]} */
10205 let rgba = [];
10206 // @ts-expect-error Type 'void' is not assignable to type 'string'
10207 str.replace(/[a-f0-9]{2}/gi, component => {
10208 rgba.push(parseInt(component, 16) / 255);
10209 });
10210 return {
10211 spaceId: "srgb",
10212 coords: (/** @type {Coords} */rgba.slice(0, 3)),
10213 alpha: (/** @type {number} */rgba.slice(3)[0])
10214 };
10215 },
10216 serialize: (coords, alpha, {
10217 collapse = true,
10218 // collapse to 3-4 digit hex when possible?
10219 alpha: alphaFormat
10220 } = {}) => {
10221 if (alphaFormat !== false && alpha < 1 || alphaFormat === true) {
10222 coords.push(alpha);
10223 }
10224 coords = /** @type {[number, number, number]} */
10225 coords.map(c => Math.round(c * 255));
10226 let collapsible = collapse && coords.every(c => c % 17 === 0);
10227 let hex = coords.map(c => {
10228 if (collapsible) {
10229 return (c / 17).toString(16);
10230 }
10231 return c.toString(16).padStart(2, "0");
10232 }).join("");
10233 return "#" + hex;
10234 }
10235 },
10236 keyword: {
10237 type: "custom",
10238 test: str => /^[a-z]+$/i.test(str),
10239 parse(str) {
10240 str = str.toLowerCase();
10241 let ret = {
10242 spaceId: "srgb",
10243 coords: null,
10244 alpha: 1
10245 };
10246 if (str === "transparent") {
10247 ret.coords = KEYWORDS.black;
10248 ret.alpha = 0;
10249 } else {
10250 ret.coords = KEYWORDS[str];
10251 }
10252 if (ret.coords) {
10253 return ret;
10254 }
10255 }
10256 }
10257 }
10258 });
10259
10260 var P3 = new RGBColorSpace({
10261 id: "p3",
10262 cssId: "display-p3",
10263 name: "P3",
10264 base: P3Linear,
10265 linearGamut: P3Linear,
10266 // Gamma encoding/decoding is the same as sRGB
10267 fromBase: sRGB.fromBase,
10268 toBase: sRGB.toBase
10269 });
10270
10271 /** @import ColorSpace from "./ColorSpace.js" */
10272 /** @import { ColorTypes, PlainColorObject, DisplayOptions } from "./types.js" */
10273
10274 // Type re-exports
10275 /** @typedef {import("./types.js").Display} Display */
10276
10277 // Default space for CSS output. Code in Color.js makes this wider if there's a DOM available
10278 defaults.display_space = sRGB;
10279 let supportsNone;
10280 if (typeof CSS !== "undefined" && CSS.supports) {
10281 // Find widest supported color space for CSS
10282 for (let space of [lab, REC2020, P3]) {
10283 let coords = space.getMinCoords();
10284 let color = {
10285 space,
10286 coords,
10287 alpha: 1
10288 };
10289 let str = serialize(color);
10290 if (CSS.supports("color", str)) {
10291 defaults.display_space = space;
10292 break;
10293 }
10294 }
10295 }
10296
10297 /**
10298 * Returns a serialization of the color that can actually be displayed in the browser.
10299 * If the default serialization can be displayed, it is returned.
10300 * Otherwise, if a `space` is given, the color is converted directly to it.
10301 * If not, the color is converted to the first supported of its space's `displaySpaces` (if any),
10302 * else the closest supported space in its base color space chain (which preserves its gamut),
10303 * else the default fallback space (Lab, REC2020, or P3, whichever is the widest supported).
10304 * In Node.js, this is basically equivalent to `serialize()` but returns a `String` object instead.
10305 * @param {ColorTypes} color
10306 * @param {DisplayOptions} [options] Options. Any properties beyond `space` and `supports` are passed to `serialize()`.
10307 * @returns {Display} String object containing the serialized color
10308 * with a color property containing the converted color (or the original, if no conversion was necessary)
10309 */
10310 function display(color, {
10311 space,
10312 supports = (_globalThis$CSS => (_globalThis$CSS = globalThis.CSS) === null || _globalThis$CSS === void 0 ? void 0 : _globalThis$CSS.supports)(),
10313 ...options
10314 } = {}) {
10315 color = getColor(color);
10316 let ret = /** @type {Display} */serialize(color, options);
10317 if (!supports || supports("color", /** @type {string} */ret) || !defaults.display_space) {
10318 ret = /** @type {Display} */new String(ret);
10319 ret.color = /** @type {PlainColorObject} */color;
10320 } else {
10321 // If we're here, what we were about to output is not supported
10322 let fallbackColor = /** @type {PlainColorObject} */color;
10323
10324 // First, check if the culprit is none values
10325 let hasNone = color.coords.some(isNone) || isNone(color.alpha);
10326 if (hasNone) {
10327 var _supportsNone;
10328 // Does the browser support none values?
10329 if (!((_supportsNone = supportsNone) !== null && _supportsNone !== void 0 ? _supportsNone : supportsNone = supports("color", "hsl(none 50% 50%)"))) {
10330 // Nope, try again without none
10331 fallbackColor = clone(/** @type {PlainColorObject} */color);
10332 fallbackColor.coords = /** @type {[number, number, number]} */
10333 fallbackColor.coords.map(skipNone);
10334 fallbackColor.alpha = skipNone(fallbackColor.alpha);
10335
10336 // @ts-expect-error This is set to the correct type later
10337 ret = serialize(fallbackColor, options);
10338 if (supports("color", /** @type {string} */ret)) {
10339 // We're done, now it's supported
10340 ret = /** @type {Display} */new String(ret);
10341 ret.color = fallbackColor;
10342 return ret;
10343 }
10344 }
10345 }
10346
10347 // If we're here, the color function is not supported.
10348 // With no explicit space, try the color's own `displaySpaces`, or else walk up its base
10349 // color space chain (closest first, skipping XYZ connection spaces), and use the first
10350 // space the browser supports, before falling back to the default space.
10351 if (space === undefined) {
10352 var _space$displaySpaces;
10353 space = fallbackColor.space;
10354 let candidates = (_space$displaySpaces = space.displaySpaces) !== null && _space$displaySpaces !== void 0 ? _space$displaySpaces : space.bases;
10355
10356 // Skip XYZ connection spaces (unless the space itself is one, so it still has a fallback).
10357 if (!space.displaySpaces && !space.id.startsWith("xyz-")) {
10358 candidates = candidates.filter(space => !space.id.startsWith("xyz-"));
10359 }
10360 for (let candidate of candidates) {
10361 let candidateColor = to(fallbackColor, candidate);
10362 let str = serialize(candidateColor, options);
10363 if (supports("color", /** @type {string} */str)) {
10364 ret = /** @type {Display} */new String(str);
10365 ret.color = candidateColor;
10366 return ret;
10367 }
10368 }
10369 space = defaults.display_space;
10370 }
10371
10372 // Fall back to fallback space
10373 fallbackColor = to(fallbackColor, /** @type {string | ColorSpace} */space);
10374 ret = /** @type {Display} */new String(serialize(fallbackColor, options));
10375 ret.color = fallbackColor;
10376 }
10377 return ret;
10378 }
10379
10380 /** @import { ColorTypes } from "./types.js" */
10381
10382 // Type re-exports
10383 /** @typedef {import("./types.js").DeltasReturn} DeltasReturn */
10384
10385 /**
10386 * Get color differences per-component, on any color space
10387 * @param {ColorTypes} c1
10388 * @param {ColorTypes} c2
10389 * @param {object} options
10390 * @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.
10391 * @param {Parameters<typeof adjust>[0]} [options.hue="shorter"] - How to handle hue differences. Same as hue interpolation option.
10392 * @returns {DeltasReturn}
10393 */
10394 function deltas(c1, c2, {
10395 space,
10396 hue = "shorter"
10397 } = {}) {
10398 c1 = getColor(c1);
10399 space || (space = c1.space);
10400 space = ColorSpace.get(space);
10401 let spaceCoords = Object.values(space.coords);
10402 [c1, c2] = [c1, c2].map(c => to(c, space));
10403 let [coords1, coords2] = [c1, c2].map(c => c.coords);
10404 let coords = /** @type {[number, number, number]} */
10405 coords1.map((coord1, i) => {
10406 let coordMeta = spaceCoords[i];
10407 let coord2 = coords2[i];
10408 if (coordMeta.type === "angle") {
10409 [coord1, coord2] = adjust(hue, [coord1, coord2]);
10410 }
10411 return subtractCoords(coord1, coord2);
10412 });
10413 let alpha = subtractCoords(c1.alpha, c2.alpha);
10414 return {
10415 space: (/** @type {ColorSpace} */space),
10416 coords,
10417 alpha
10418 };
10419 }
10420 function subtractCoords(c1, c2) {
10421 if (isNone(c1) || isNone(c2)) {
10422 return c1 === c2 ? null : 0;
10423 }
10424 return c1 - c2;
10425 }
10426
10427 /** @import { ColorTypes } from "./types.js" */
10428
10429 /**
10430 * @param {ColorTypes} color1
10431 * @param {ColorTypes} color2
10432 * @returns {boolean}
10433 */
10434 function equals(color1, color2) {
10435 color1 = getColor(color1);
10436 color2 = getColor(color2);
10437 return color1.space === color2.space && color1.alpha === color2.alpha && color1.coords.every((c, i) => c === color2.coords[i]);
10438 }
10439
10440 /**
10441 * Relative luminance
10442 */
10443
10444 /** @import { ColorTypes } from "./types.js" */
10445
10446 /**
10447 *
10448 * @param {ColorTypes} color
10449 * @returns {number}
10450 */
10451 function getLuminance(color) {
10452 // Assume getColor() is called on color in get()
10453 return get(color, [XYZ_D65, "y"]);
10454 }
10455
10456 /**
10457 * @param {ColorTypes} color
10458 * @param {number | ((coord: number) => number)} value
10459 */
10460 function setLuminance(color, value) {
10461 // Assume getColor() is called on color in set()
10462 set(color, [XYZ_D65, "y"], value);
10463 }
10464
10465 /**
10466 * @param {typeof import("./color.js").default} Color
10467 */
10468 function register$2(Color) {
10469 Object.defineProperty(Color.prototype, "luminance", {
10470 get() {
10471 return getLuminance(this);
10472 },
10473 set(value) {
10474 setLuminance(this, value);
10475 }
10476 });
10477 }
10478
10479 var luminance = /*#__PURE__*/Object.freeze({
10480 __proto__: null,
10481 getLuminance: getLuminance,
10482 register: register$2,
10483 setLuminance: setLuminance
10484 });
10485
10486 // WCAG 2.0 contrast https://www.w3.org/TR/WCAG20-TECHS/G18.html
10487 // Simple contrast, with fixed 5% viewing flare contribution
10488 // Symmetric, does not matter which is foreground and which is background
10489
10490
10491 /**
10492 * @param {import("../types.js").ColorTypes} color1
10493 * @param {import("../types.js").ColorTypes} color2
10494 * @returns {number}
10495 */
10496 function contrastWCAG21(color1, color2) {
10497 color1 = getColor(color1);
10498 color2 = getColor(color2);
10499 let Y1 = Math.max(getLuminance(color1), 0);
10500 let Y2 = Math.max(getLuminance(color2), 0);
10501 if (Y2 > Y1) {
10502 [Y1, Y2] = [Y2, Y1];
10503 }
10504 return (Y1 + 0.05) / (Y2 + 0.05);
10505 }
10506
10507 // exponents
10508 const normBG = 0.56;
10509 const normTXT = 0.57;
10510 const revTXT = 0.62;
10511 const revBG = 0.65;
10512
10513 // clamps
10514 const blkThrs = 0.022;
10515 const blkClmp = 1.414;
10516 const loClip = 0.1;
10517 const deltaYmin = 0.0005;
10518
10519 // scalers
10520 // see https://github.com/w3c/silver/issues/645
10521 const scaleBoW = 1.14;
10522 const loBoWoffset = 0.027;
10523 const scaleWoB = 1.14;
10524 function fclamp(Y) {
10525 if (Y >= blkThrs) {
10526 return Y;
10527 }
10528 return Y + (blkThrs - Y) ** blkClmp;
10529 }
10530 function linearize(val) {
10531 let sign = val < 0 ? -1 : 1;
10532 let abs = Math.abs(val);
10533 return sign * Math.pow(abs, 2.4);
10534 }
10535
10536 /**
10537 * Not symmetric, requires a foreground (text) color, and a background color
10538 * @param {import("../types.js").ColorTypes} background
10539 * @param {import("../types.js").ColorTypes} foreground
10540 * @returns {number}
10541 */
10542 function contrastAPCA(background, foreground) {
10543 foreground = getColor(foreground);
10544 background = getColor(background);
10545 let S;
10546 let C;
10547 let Sapc;
10548
10549 // Myndex as-published, assumes sRGB inputs
10550 let R, G, B;
10551 foreground = to(foreground, "srgb");
10552 // Should these be clamped to in-gamut values?
10553
10554 // Calculates "screen luminance" with non-standard simple gamma EOTF
10555 // weights should be from CSS Color 4, not the ones here which are via Myndex and copied from Lindbloom
10556 [R, G, B] = foreground.coords.map(c => {
10557 return isNone(c) ? 0 : c;
10558 });
10559 let lumTxt = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175;
10560 background = to(background, "srgb");
10561 [R, G, B] = background.coords.map(c => {
10562 return isNone(c) ? 0 : c;
10563 });
10564 let lumBg = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175;
10565
10566 // toe clamping of very dark values to account for flare
10567 let Ytxt = fclamp(lumTxt);
10568 let Ybg = fclamp(lumBg);
10569
10570 // are we "Black on White" (dark on light), or light on dark?
10571 let BoW = Ybg > Ytxt;
10572
10573 // why is this a delta, when Y is not perceptually uniform?
10574 // Answer: it is a noise gate, see
10575 // https://github.com/LeaVerou/color.js/issues/208
10576 if (Math.abs(Ybg - Ytxt) < deltaYmin) {
10577 C = 0;
10578 } else {
10579 if (BoW) {
10580 // dark text on light background
10581 S = Ybg ** normBG - Ytxt ** normTXT;
10582 C = S * scaleBoW;
10583 } else {
10584 // light text on dark background
10585 S = Ybg ** revBG - Ytxt ** revTXT;
10586 C = S * scaleWoB;
10587 }
10588 }
10589 if (Math.abs(C) < loClip) {
10590 Sapc = 0;
10591 } else if (C > 0) {
10592 // not clear whether Woffset is loBoWoffset or loWoBoffset
10593 // but they have the same value
10594 Sapc = C - loBoWoffset;
10595 } else {
10596 Sapc = C + loBoWoffset;
10597 }
10598 return Sapc * 100;
10599 }
10600
10601 // Michelson luminance contrast
10602 // the relation between the spread and the sum of the two luminances
10603 // Symmetric, does not matter which is foreground and which is background
10604 // No black level compensation for flare.
10605
10606
10607 /**
10608 * @param {import("../types.js").ColorTypes} color1
10609 * @param {import("../types.js").ColorTypes} color2
10610 * @returns {number}
10611 */
10612 function contrastMichelson(color1, color2) {
10613 color1 = getColor(color1);
10614 color2 = getColor(color2);
10615 let Y1 = Math.max(getLuminance(color1), 0);
10616 let Y2 = Math.max(getLuminance(color2), 0);
10617 if (Y2 > Y1) {
10618 [Y1, Y2] = [Y2, Y1];
10619 }
10620 let denom = Y1 + Y2;
10621 return denom === 0 ? 0 : (Y1 - Y2) / denom;
10622 }
10623
10624 // Weber luminance contrast
10625 // The difference between the two luminances divided by the lower luminance
10626 // Symmetric, does not matter which is foreground and which is background
10627 // No black level compensation for flare.
10628
10629
10630 // the darkest sRGB color above black is #000001 and this produces
10631 // a plain Weber contrast of ~45647.
10632 // So, setting the divide-by-zero result at 50000 is a reasonable
10633 // max clamp for the plain Weber
10634 const max = 50000;
10635
10636 /**
10637 * @param {import("../types.js").ColorTypes} color1
10638 * @param {import("../types.js").ColorTypes} color2
10639 * @returns {number}
10640 */
10641 function contrastWeber(color1, color2) {
10642 color1 = getColor(color1);
10643 color2 = getColor(color2);
10644 let Y1 = Math.max(getLuminance(color1), 0);
10645 let Y2 = Math.max(getLuminance(color2), 0);
10646 if (Y2 > Y1) {
10647 [Y1, Y2] = [Y2, Y1];
10648 }
10649 return Y2 === 0 ? max : (Y1 - Y2) / Y2;
10650 }
10651
10652 // CIE Lightness difference, as used by Google Material Design
10653 // Google HCT Tone is the same as CIE Lightness
10654 // https://material.io/blog/science-of-color-design
10655
10656
10657 /**
10658 * @param {import("../types.js").ColorTypes} color1
10659 * @param {import("../types.js").ColorTypes} color2
10660 * @returns {number}
10661 */
10662 function contrastLstar(color1, color2) {
10663 color1 = getColor(color1);
10664 color2 = getColor(color2);
10665 let L1 = get(color1, [lab, "l"]);
10666 let L2 = get(color2, [lab, "l"]);
10667 return Math.abs(L1 - L2);
10668 }
10669
10670 // κ * ε = 2^3 = 8
10671 const ε$3 = 216 / 24389; // 6^3/29^3 == (24/116)^3
10672 const ε3 = 24 / 116;
10673 const κ$2 = 24389 / 27; // 29^3/3^3
10674
10675 let white$1 = WHITES.D65;
10676 var lab_d65 = new ColorSpace({
10677 id: "lab-d65",
10678 name: "Lab D65",
10679 coords: {
10680 l: {
10681 refRange: [0, 100],
10682 name: "Lightness"
10683 },
10684 a: {
10685 refRange: [-125, 125]
10686 },
10687 b: {
10688 refRange: [-125, 125]
10689 }
10690 },
10691 // Assuming XYZ is relative to D65, convert to CIE Lab
10692 // from CIE standard, which now defines these as a rational fraction
10693 white: white$1,
10694 base: XYZ_D65,
10695 // Convert D65-adapted XYZ to Lab
10696 // CIE 15.3:2004 section 8.2.1.1
10697 fromBase(XYZ) {
10698 // compute xyz, which is XYZ scaled relative to reference white
10699 let xyz = XYZ.map((value, i) => value / white$1[i]);
10700
10701 // now compute f
10702 let f = xyz.map(value => value > ε$3 ? Math.cbrt(value) : (κ$2 * value + 16) / 116);
10703 return [116 * f[1] - 16,
10704 // L
10705 500 * (f[0] - f[1]),
10706 // a
10707 200 * (f[1] - f[2]) // b
10708 ];
10709 },
10710 // Convert Lab to D65-adapted XYZ
10711 // Same result as CIE 15.3:2004 Appendix D although the derivation is different
10712 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
10713 toBase(Lab) {
10714 // compute f, starting with the luminance-related term
10715 let f = [];
10716 f[1] = (Lab[0] + 16) / 116;
10717 f[0] = Lab[1] / 500 + f[1];
10718 f[2] = f[1] - Lab[2] / 200;
10719
10720 // compute xyz
10721 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];
10722
10723 // Compute XYZ by scaling xyz by reference white
10724 return xyz.map((value, i) => value * white$1[i]);
10725 },
10726 formats: {
10727 "lab-d65": {
10728 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <percentage>"]
10729 }
10730 }
10731 });
10732
10733 // Delta Phi Star perceptual lightness contrast
10734 // See https://github.com/Myndex/deltaphistar
10735 // The (difference between two Lstars each raised to phi) raised to (1/phi)
10736 // Symmetric, does not matter which is foreground and which is background
10737
10738 const phi = Math.pow(5, 0.5) * 0.5 + 0.5; // Math.phi can be used if Math.js
10739
10740 /**
10741 * @param {import("../types.js").ColorTypes} color1
10742 * @param {import("../types.js").ColorTypes} color2
10743 * @returns {number}
10744 */
10745 function contrastDeltaPhi(color1, color2) {
10746 color1 = getColor(color1);
10747 color2 = getColor(color2);
10748 let Lstr1 = get(color1, [lab_d65, "l"]);
10749 let Lstr2 = get(color2, [lab_d65, "l"]);
10750 let deltaPhiStar = Math.abs(Math.pow(Lstr1, phi) - Math.pow(Lstr2, phi));
10751 let contrast = Math.pow(deltaPhiStar, 1 / phi) * Math.SQRT2 - 40;
10752 return contrast < 7.5 ? 0.0 : contrast;
10753 }
10754
10755 /** @typedef {keyof typeof import("./index.js") extends `contrast${infer Alg}` ? Alg : string} Algorithms */
10756
10757 var contrastMethods = /*#__PURE__*/Object.freeze({
10758 __proto__: null,
10759 contrastAPCA: contrastAPCA,
10760 contrastDeltaPhi: contrastDeltaPhi,
10761 contrastLstar: contrastLstar,
10762 contrastMichelson: contrastMichelson,
10763 contrastWCAG21: contrastWCAG21,
10764 contrastWeber: contrastWeber
10765 });
10766
10767 /** @import { ColorTypes } from "./types.js" */
10768
10769 // Type re-exports
10770 /** @typedef {import("./types.js").Algorithms} Algorithms */
10771
10772 /**
10773 *
10774 * @param {ColorTypes} background
10775 * @param {ColorTypes} foreground
10776 * @param {Algorithms | ({ algorithm: Algorithms } & Record<string, any>)} o
10777 * Algorithm to use as well as any other options to pass to the contrast function
10778 * @returns {number}
10779 * @throws {TypeError} Unknown or unspecified algorithm
10780 */
10781 function contrast(background, foreground, o) {
10782 if (isString(o)) {
10783 o = {
10784 algorithm: o
10785 };
10786 }
10787 let {
10788 algorithm,
10789 ...rest
10790 } = o || {};
10791 if (!algorithm) {
10792 let algorithms = Object.keys(contrastMethods).map(a => a.replace(/^contrast/, "")).join(", ");
10793 throw new TypeError(`contrast() function needs a contrast algorithm. Please specify one of: ${algorithms}`);
10794 }
10795 background = getColor(background);
10796 foreground = getColor(foreground);
10797 for (let a in contrastMethods) {
10798 if ("contrast" + algorithm.toLowerCase() === a.toLowerCase()) {
10799 return contrastMethods[a](background, foreground, rest);
10800 }
10801 }
10802 throw new TypeError(`Unknown contrast algorithm: ${algorithm}`);
10803 }
10804
10805 /** @import Color, { ColorTypes } from "./color.js" */
10806
10807 // Chromaticity coordinates
10808 /**
10809 * @param {ColorTypes} color
10810 * @returns {[number, number]}
10811 */
10812 function uv(color) {
10813 // Assumes getAll() calls getColor() on color
10814 let [X, Y, Z] = getAll(color, XYZ_D65);
10815 let denom = X + 15 * Y + 3 * Z;
10816 return [4 * X / denom, 9 * Y / denom];
10817 }
10818
10819 /**
10820 * @param {ColorTypes} color
10821 * @returns {[number, number]}
10822 */
10823 function xy(color) {
10824 // Assumes getAll() calls getColor() on color
10825 let [X, Y, Z] = getAll(color, XYZ_D65);
10826 let sum = X + Y + Z;
10827 return [X / sum, Y / sum];
10828 }
10829
10830 /**
10831 * @param {typeof Color} Color
10832 */
10833 function register$1(Color) {
10834 // no setters, as lightness information is lost
10835 // when converting color to chromaticity
10836 Object.defineProperty(Color.prototype, "uv", {
10837 get() {
10838 return uv(this);
10839 }
10840 });
10841 Object.defineProperty(Color.prototype, "xy", {
10842 get() {
10843 return xy(this);
10844 }
10845 });
10846 }
10847
10848 var chromaticity = /*#__PURE__*/Object.freeze({
10849 __proto__: null,
10850 register: register$1,
10851 uv: uv,
10852 xy: xy
10853 });
10854
10855 /** @import { ColorTypes } from "./types.js" */
10856
10857 // Type re-exports
10858 /** @typedef {import("./types.js").Methods} Methods */
10859
10860 /**
10861 *
10862 * @param {ColorTypes} c1
10863 * @param {ColorTypes} c2
10864 * @param {Methods | ({ method?: Methods | undefined } & Record<string, any>)} [o]
10865 * deltaE method to use as well as any other options to pass to the deltaE function
10866 * @returns {number}
10867 * @throws {TypeError} Unknown or unspecified method
10868 */
10869 function deltaE(c1, c2, o = {}) {
10870 if (isString(o)) {
10871 o = {
10872 method: o
10873 };
10874 }
10875 let {
10876 method = defaults.deltaE,
10877 ...rest
10878 } = o;
10879 for (let m in deltaEMethods) {
10880 if ("deltae" + method.toLowerCase() === m.toLowerCase()) {
10881 return deltaEMethods[m](c1, c2, rest);
10882 }
10883 }
10884 throw new TypeError(`Unknown deltaE method: ${method}`);
10885 }
10886
10887 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
10888
10889 /**
10890 * @param {ColorTypes} color
10891 * @param {number} amount
10892 * @returns {PlainColorObject}
10893 */
10894 function lighten(color, amount = 0.25) {
10895 let space = ColorSpace.get("oklch", "lch");
10896 let /** @type {Ref} */lightness = [space, "l"];
10897 return set(color, lightness, l => l * (1 + amount));
10898 }
10899
10900 /**
10901 * @param {ColorTypes} color
10902 * @param {number} amount
10903 * @returns {PlainColorObject}
10904 */
10905 function darken(color, amount = 0.25) {
10906 let space = ColorSpace.get("oklch", "lch");
10907 let /** @type {Ref} */lightness = [space, "l"];
10908 return set(color, lightness, l => l * (1 - amount));
10909 }
10910
10911 /** @type {"color"} */
10912 lighten.returns = "color";
10913
10914 /** @type {"color"} */
10915 darken.returns = "color";
10916
10917 var variations = /*#__PURE__*/Object.freeze({
10918 __proto__: null,
10919 darken: darken,
10920 lighten: lighten
10921 });
10922
10923 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
10924
10925 // Type re-exports
10926 /** @typedef {import("./types.js").MixOptions} MixOptions */
10927 /** @typedef {import("./types.js").Range} Range */
10928 /** @typedef {import("./types.js").RangeOptions} RangeOptions */
10929 /** @typedef {import("./types.js").StepsOptions} StepsOptions */
10930
10931 /**
10932 * Return an intermediate color between two colors
10933 * @overload
10934 * @param {ColorTypes} c1
10935 * @param {ColorTypes} c2
10936 * @param {MixOptions} [options]
10937 * @returns {PlainColorObject}
10938 */
10939 /**
10940 * @overload
10941 * @param {ColorTypes} c1
10942 * @param {ColorTypes} c2
10943 * @param {number} [p=0.5]
10944 * @param {MixOptions} [options]
10945 * @returns {PlainColorObject}
10946 */
10947 function mix(c1, c2, p, o = {}) {
10948 var _p;
10949 [c1, c2] = [getColor(c1), getColor(c2)];
10950 if (type(p) === "object") {
10951 [p, o] = [0.5, p];
10952 }
10953 let r = range(c1, c2, o);
10954 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
10955 }
10956
10957 /**
10958 * Get an array of discrete steps
10959 * @overload
10960 * @param {ColorTypes} c1
10961 * @param {ColorTypes} c2
10962 * @param {StepsOptions} [options]
10963 * @returns {PlainColorObject[]}
10964 */
10965 /**
10966 * @overload
10967 * @param {Range} range
10968 * @param {StepsOptions} [options]
10969 * @returns {PlainColorObject[]}
10970 */
10971 function steps(c1, c2, options = {}) {
10972 let colorRange;
10973 if (isRange(c1)) {
10974 // Tweaking existing range
10975 [colorRange, options] = [c1, c2];
10976 [c1, c2] = colorRange.rangeArgs.colors;
10977 }
10978 let {
10979 maxDeltaE,
10980 deltaEMethod,
10981 steps = 2,
10982 maxSteps = 1000,
10983 ...rangeOptions
10984 } = options;
10985 if (!colorRange) {
10986 [c1, c2] = [getColor(c1), getColor(c2)];
10987 colorRange = range(c1, c2, rangeOptions);
10988 }
10989 let totalDelta = deltaE(c1, c2, deltaEMethod);
10990 let actualSteps = maxDeltaE > 0 ? Math.max(steps, Math.ceil(totalDelta / maxDeltaE) + 1) : steps;
10991 let ret = [];
10992 if (maxSteps !== undefined) {
10993 actualSteps = Math.min(actualSteps, maxSteps);
10994 }
10995 if (actualSteps === 1) {
10996 ret = [{
10997 p: 0.5,
10998 color: colorRange(0.5)
10999 }];
11000 } else {
11001 let step = 1 / (actualSteps - 1);
11002 ret = Array.from({
11003 length: actualSteps
11004 }, (_, i) => {
11005 let p = i * step;
11006 return {
11007 p,
11008 color: colorRange(p)
11009 };
11010 });
11011 }
11012 if (maxDeltaE > 0) {
11013 // Iterate over all stops and find max deltaE
11014 let maxDelta = ret.reduce((acc, cur, i) => {
11015 if (i === 0) {
11016 return 0;
11017 }
11018 let ΔΕ = deltaE(cur.color, ret[i - 1].color, deltaEMethod);
11019 return Math.max(acc, ΔΕ);
11020 }, 0);
11021 while (maxDelta > maxDeltaE) {
11022 // Insert intermediate stops and measure maxDelta again
11023 // We need to do this for all pairs, otherwise the midpoint shifts
11024 maxDelta = 0;
11025 for (let i = 1; i < ret.length && ret.length < maxSteps; i++) {
11026 let prev = ret[i - 1];
11027 let cur = ret[i];
11028 let p = (cur.p + prev.p) / 2;
11029 let color = colorRange(p);
11030 maxDelta = Math.max(maxDelta, deltaE(color, prev.color, deltaEMethod), deltaE(color, cur.color, deltaEMethod));
11031 ret.splice(i, 0, {
11032 p,
11033 color: colorRange(p)
11034 });
11035 i++;
11036 }
11037 }
11038 }
11039 ret = ret.map(a => a.color);
11040 return ret;
11041 }
11042
11043 /**
11044 * Creates a function that accepts a number and returns a color.
11045 * For numbers in the range 0 to 1, the function interpolates;
11046 * for numbers outside that range, the function extrapolates
11047 * (and thus may not return the results you expect)
11048 * @overload
11049 * @param {Range} range
11050 * @param {RangeOptions} [options]
11051 * @returns {Range}
11052 */
11053 /**
11054 * @overload
11055 * @param {ColorTypes} color1
11056 * @param {ColorTypes} color2
11057 * @param {RangeOptions & Record<string, any>} [options]
11058 * @returns {Range}
11059 */
11060 function range(color1, color2, options = {}) {
11061 if (isRange(color1)) {
11062 // Tweaking existing range
11063 let [r, options] = [color1, color2];
11064 return range(...r.rangeArgs.colors, {
11065 ...r.rangeArgs.options,
11066 ...options
11067 });
11068 }
11069 let {
11070 space,
11071 outputSpace,
11072 progression,
11073 premultiplied
11074 } = options;
11075 color1 = getColor(color1);
11076 color2 = getColor(color2);
11077
11078 // Make sure we're working on copies of these colors
11079 color1 = clone(color1);
11080 color2 = clone(color2);
11081 let rangeArgs = {
11082 colors: [color1, color2],
11083 options
11084 };
11085 if (space) {
11086 space = ColorSpace.get(space);
11087 } else {
11088 space = ColorSpace.registry[defaults.interpolationSpace] || color1.space;
11089 }
11090 outputSpace = outputSpace ? ColorSpace.get(outputSpace) : space;
11091 color1 = to(color1, space);
11092 color2 = to(color2, space);
11093
11094 // Gamut map to avoid areas of flat color
11095 color1 = toGamut(color1);
11096 color2 = toGamut(color2);
11097
11098 // The hue coordinate is not always called "h" (e.g. it's "hz" in Jzczhz)
11099 let hueId = space.hueId;
11100 let hueIndex = space.hueIndex;
11101
11102 // Handle hue interpolation
11103 // See https://github.com/w3c/csswg-drafts/issues/4735#issuecomment-635741840
11104 if (hueId) {
11105 let arc = options.hue = options.hue || "shorter";
11106 let /** @type {Ref} */hue = [space, hueId];
11107 let [θ1, θ2] = [get(color1, hue), get(color2, hue)];
11108 // Undefined hues must be evaluated before hue fix-up to properly
11109 // calculate hue arcs between undefined and defined hues.
11110 // See https://github.com/w3c/csswg-drafts/issues/9436#issuecomment-1746957545
11111 if (isNone(θ1) && !isNone(θ2)) {
11112 θ1 = θ2;
11113 } else if (isNone(θ2) && !isNone(θ1)) {
11114 θ2 = θ1;
11115 }
11116 [θ1, θ2] = adjust(arc, [θ1, θ2]);
11117 set(color1, hue, θ1);
11118 set(color2, hue, θ2);
11119 }
11120
11121 // An undefined alpha takes the other color's alpha, and premultiplication must use
11122 // that carried forward value, rather than the zero it would otherwise be treated as.
11123 // If both alphas are undefined, they stay that way, and no premultiplication happens.
11124 // See https://drafts.csswg.org/css-color-4/#interpolation-missing
11125 if (isNone(color1.alpha) && !isNone(color2.alpha)) {
11126 color1.alpha = color2.alpha;
11127 } else if (isNone(color2.alpha) && !isNone(color1.alpha)) {
11128 color2.alpha = color1.alpha;
11129 }
11130 if (premultiplied) {
11131 color1.coords = premultiply(color1.coords, color1.alpha, hueIndex);
11132 color2.coords = premultiply(color2.coords, color2.alpha, hueIndex);
11133 }
11134 return Object.assign(p => {
11135 p = progression ? progression(p) : p;
11136 let coords = color1.coords.map((start, i) => {
11137 let end = color2.coords[i];
11138 return interpolate(start, end, p);
11139 });
11140 let alpha = interpolate(color1.alpha, color2.alpha, p);
11141 let ret = {
11142 space,
11143 coords,
11144 alpha
11145 };
11146 if (premultiplied) {
11147 // Undo premultiplication, again leaving any hue angle untouched
11148 ret.coords = premultiply(ret.coords, alpha, hueIndex, true);
11149 }
11150 if (outputSpace !== space) {
11151 ret = to(ret, outputSpace);
11152 }
11153 return ret;
11154 }, {
11155 rangeArgs
11156 });
11157 }
11158
11159 /**
11160 * Premultiply a color's coordinates by its alpha, or undo premultiplication by dividing by it.
11161 * Per CSS Color 4, the hue angle of a polar space is never premultiplied,
11162 * `none` components stay `none`, a `none` alpha means no (un)premultiplication happens at all,
11163 * and un-premultiplying by a zero alpha leaves the coords as they are, rather than dividing by zero.
11164 * See https://drafts.csswg.org/css-color-4/#interpolation-alpha
11165 * @param {(number | null)[]} coords
11166 * @param {number | null} alpha
11167 * @param {number} hueIndex - Index of the hue coordinate, or -1 if the space has none
11168 * @param {boolean} [undo=false] - Divide by alpha instead of multiplying by it
11169 * @returns {[number, number, number]}
11170 */
11171 function premultiply(coords, alpha, hueIndex, undo = false) {
11172 if (isNone(alpha) || undo && alpha === 0) {
11173 // The (un-)premultiplied value is the value itself
11174 return /** @type {[number, number, number]} */coords;
11175 }
11176 return /** @type {[number, number, number]} */coords.map((c, i) => {
11177 if (i === hueIndex || isNone(c)) {
11178 return c;
11179 }
11180 return undo ? c / alpha : c * alpha;
11181 });
11182 }
11183
11184 /**
11185 * @param {any} val
11186 * @returns {val is Range}
11187 */
11188 function isRange(val) {
11189 return type(val) === "function" && !!val.rangeArgs;
11190 }
11191 defaults.interpolationSpace = "lab";
11192
11193 /**
11194 * @param {typeof import("./color.js").default} Color
11195 */
11196 function register(Color) {
11197 Color.defineFunction("mix", mix, {
11198 returns: "color"
11199 });
11200 Color.defineFunction("range", range, {
11201 returns: "function<color>"
11202 });
11203 Color.defineFunction("steps", steps, {
11204 returns: "array<color>"
11205 });
11206 }
11207
11208 var interpolation = /*#__PURE__*/Object.freeze({
11209 __proto__: null,
11210 isRange: isRange,
11211 mix: mix,
11212 range: range,
11213 register: register,
11214 steps: steps
11215 });
11216
11217 var HSL = new ColorSpace({
11218 id: "hsl",
11219 name: "HSL",
11220 coords: {
11221 h: {
11222 refRange: [0, 360],
11223 type: "angle",
11224 name: "Hue"
11225 },
11226 s: {
11227 range: [0, 100],
11228 name: "Saturation"
11229 },
11230 l: {
11231 range: [0, 100],
11232 name: "Lightness"
11233 }
11234 },
11235 base: sRGB,
11236 rgbGamut: sRGB,
11237 // Adapted from https://drafts.csswg.org/css-color-4/better-rgbToHsl.js
11238 fromBase: rgb => {
11239 let max = Math.max(...rgb);
11240 let min = Math.min(...rgb);
11241 let [r, g, b] = rgb;
11242 let [h, s, l] = [null, 0, (min + max) / 2];
11243 let d = max - min;
11244 if (d !== 0) {
11245 s = l === 0 || l === 1 ? 0 : (max - l) / Math.min(l, 1 - l);
11246 switch (max) {
11247 case r:
11248 h = (g - b) / d + (g < b ? 6 : 0);
11249 break;
11250 case g:
11251 h = (b - r) / d + 2;
11252 break;
11253 case b:
11254 h = (r - g) / d + 4;
11255 }
11256 h = h * 60;
11257 }
11258
11259 // Very out of gamut colors can produce negative saturation
11260 // If so, just rotate the hue by 180 and use a positive saturation
11261 // see https://github.com/w3c/csswg-drafts/issues/9222
11262 if (s < 0) {
11263 h += 180;
11264 s = Math.abs(s);
11265 }
11266 if (h >= 360) {
11267 h -= 360;
11268 }
11269 return [h, s * 100, l * 100];
11270 },
11271 // Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB_alternative
11272 toBase: hsl => {
11273 let [h, s, l] = hsl;
11274 h = h % 360;
11275 if (h < 0) {
11276 h += 360;
11277 }
11278 s /= 100;
11279 l /= 100;
11280 function f(n) {
11281 let k = (n + h / 30) % 12;
11282 let a = s * Math.min(l, 1 - l);
11283 return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));
11284 }
11285 return [f(0), f(8), f(4)];
11286 },
11287 formats: {
11288 hsl: {
11289 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
11290 },
11291 hsla: {
11292 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
11293 commas: true,
11294 alpha: true
11295 }
11296 }
11297 });
11298
11299 var hslP3 = new ColorSpace({
11300 id: "hsl-p3",
11301 cssId: "--hsl-p3",
11302 name: "HSL P3",
11303 coords: {
11304 h: {
11305 refRange: [0, 360],
11306 type: "angle",
11307 name: "Hue"
11308 },
11309 s: {
11310 range: [0, 100],
11311 name: "Saturation"
11312 },
11313 l: {
11314 range: [0, 100],
11315 name: "Lightness"
11316 }
11317 },
11318 base: P3,
11319 rgbGamut: P3,
11320 fromBase: HSL.fromBase,
11321 toBase: HSL.toBase
11322 });
11323
11324 var hslRec2020 = new ColorSpace({
11325 id: "hsl-rec2020",
11326 cssId: "--hsl-rec2020",
11327 name: "HSL Rec.2020",
11328 coords: {
11329 h: {
11330 refRange: [0, 360],
11331 type: "angle",
11332 name: "Hue"
11333 },
11334 s: {
11335 range: [0, 100],
11336 name: "Saturation"
11337 },
11338 l: {
11339 range: [0, 100],
11340 name: "Lightness"
11341 }
11342 },
11343 base: REC2020,
11344 rgbGamut: REC2020,
11345 fromBase: HSL.fromBase,
11346 toBase: HSL.toBase
11347 });
11348
11349 // Note that, like HSL, calculations are done directly on
11350 // gamma-corrected sRGB values rather than linearising them first.
11351
11352 var HSV = new ColorSpace({
11353 id: "hsv",
11354 name: "HSV",
11355 coords: {
11356 h: {
11357 refRange: [0, 360],
11358 type: "angle",
11359 name: "Hue"
11360 },
11361 s: {
11362 range: [0, 100],
11363 name: "Saturation"
11364 },
11365 v: {
11366 range: [0, 100],
11367 name: "Value"
11368 }
11369 },
11370 base: sRGB,
11371 rgbGamut: sRGB,
11372 // https://en.wikipedia.org/wiki/HSL_and_HSV#Formal_derivation
11373 fromBase(rgb) {
11374 let max = Math.max(...rgb);
11375 let min = Math.min(...rgb);
11376 let [r, g, b] = rgb;
11377 let [h, s, v] = [null, 0, max];
11378 let d = max - min;
11379 if (d !== 0) {
11380 switch (max) {
11381 case r:
11382 h = (g - b) / d + (g < b ? 6 : 0);
11383 break;
11384 case g:
11385 h = (b - r) / d + 2;
11386 break;
11387 case b:
11388 h = (r - g) / d + 4;
11389 }
11390 h = h * 60;
11391 }
11392 if (v) {
11393 s = d / v;
11394 }
11395 if (h >= 360) {
11396 h -= 360;
11397 }
11398 return [h, s * 100, v * 100];
11399 },
11400 // Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB_alternative
11401 toBase(hsv) {
11402 let [h, s, v] = hsv;
11403 h = h % 360;
11404 if (h < 0) {
11405 h += 360;
11406 }
11407 s /= 100;
11408 v /= 100;
11409 function f(n) {
11410 let k = (n + h / 60) % 6;
11411 return v - v * s * Math.max(0, Math.min(k, 4 - k, 1));
11412 }
11413 return [f(5), f(3), f(1)];
11414 },
11415 formats: {
11416 color: {
11417 id: "--hsv",
11418 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
11419 }
11420 }
11421 });
11422
11423 // The Hue, Whiteness Blackness (HWB) colorspace
11424 // See https://drafts.csswg.org/css-color-4/#the-hwb-notation
11425 // Note that, like HSL, calculations are done directly on
11426 // gamma-corrected sRGB values rather than linearising them first.
11427
11428 var hwb = new ColorSpace({
11429 id: "hwb",
11430 name: "HWB",
11431 coords: {
11432 h: {
11433 refRange: [0, 360],
11434 type: "angle",
11435 name: "Hue"
11436 },
11437 w: {
11438 range: [0, 100],
11439 name: "Whiteness"
11440 },
11441 b: {
11442 range: [0, 100],
11443 name: "Blackness"
11444 }
11445 },
11446 base: HSV,
11447 rgbGamut: sRGB,
11448 fromBase(hsv) {
11449 let [h, s, v] = hsv;
11450 return [h, v * (100 - s) / 100, 100 - v];
11451 },
11452 toBase(hwb) {
11453 let [h, w, b] = hwb;
11454
11455 // Now convert percentages to [0..1]
11456 w /= 100;
11457 b /= 100;
11458
11459 // Achromatic check (white plus black >= 1)
11460 let sum = w + b;
11461 if (sum >= 1) {
11462 let gray = w / sum;
11463 return [h, 0, gray * 100];
11464 }
11465 let v = 1 - b;
11466 let s = v === 0 ? 0 : 1 - w / v;
11467 return [h, s * 100, v * 100];
11468 },
11469 formats: {
11470 hwb: {
11471 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
11472 }
11473 }
11474 });
11475
11476 /** @import { Matrix3x3 } from "../types.js" */
11477
11478 // convert an array of linear-light a98-rgb values to CIE XYZ
11479 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
11480 // has greater numerical precision than section 4.3.5.3 of
11481 // https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf
11482 // but the values below were calculated from first principles
11483 // from the chromaticity coordinates of R G B W
11484
11485 /**
11486 * Matrices used by this color space, also available as `A98RGB_Linear.M`
11487 * @type {Record<string, Matrix3x3>}
11488 */
11489 // prettier-ignore
11490 const M$5 = {
11491 toXYZ: [[0.5766690429101305, 0.1855582379065463, 0.1882286462349947], [0.29734497525053605, 0.6273635662554661, 0.07529145849399788], [0.02703136138641234, 0.07068885253582723, 0.9913375368376388]],
11492 fromXYZ: [[2.0415879038107465, -0.5650069742788596, -0.34473135077832956], [-0.9692436362808795, 1.8759675015077202, 0.04155505740717557], [0.013444280632031142, -0.11836239223101838, 1.0151749943912054]]
11493 };
11494 var A98Linear = new RGBColorSpace({
11495 id: "a98rgb-linear",
11496 cssId: "--a98-rgb-linear",
11497 name: "Linear Adobe® 98 RGB compatible",
11498 white: "D65",
11499 M: M$5
11500 });
11501
11502 var a98rgb = new RGBColorSpace({
11503 id: "a98rgb",
11504 cssId: "a98-rgb",
11505 name: "Adobe® 98 RGB compatible",
11506 base: A98Linear,
11507 linearGamut: A98Linear,
11508 toBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 563 / 256) * Math.sign(val)),
11509 fromBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 256 / 563) * Math.sign(val))
11510 });
11511
11512 /** @import { Matrix3x3 } from "../types.js" */
11513
11514 /**
11515 * Matrices used by this color space, also available as `ProPhoto_Linear.M`.
11516 * Uses D50 (so no chromatic adaptation needed afterwards). The matrix cannot
11517 * be expressed in rational form, but is calculated to 64 bit accuracy.
11518 * see https://github.com/w3c/csswg-drafts/issues/7675
11519 * @type {Record<string, Matrix3x3>}
11520 */
11521 // prettier-ignore
11522 const M$4 = {
11523 toXYZ: [[0.79776664490064230, 0.13518129740053308, 0.03134773412839220], [0.28807482881940130, 0.71183523424187300, 0.00008993693872564], [0.00000000000000000, 0.00000000000000000, 0.82510460251046020]],
11524 fromXYZ: [[1.34578688164715830, -0.25557208737979464, -0.05110186497554526], [-0.54463070512490190, 1.50824774284514680, 0.02052744743642139], [0.00000000000000000, 0.00000000000000000, 1.21196754563894520]]
11525 };
11526 var ProPhotoLinear = new RGBColorSpace({
11527 id: "prophoto-linear",
11528 cssId: "--prophoto-rgb-linear",
11529 name: "Linear ProPhoto",
11530 white: "D50",
11531 base: XYZ_D50,
11532 M: M$4
11533 });
11534
11535 const Et = 1 / 512;
11536 const Et2 = 16 / 512;
11537 var prophoto = new RGBColorSpace({
11538 id: "prophoto",
11539 cssId: "prophoto-rgb",
11540 name: "ProPhoto",
11541 base: ProPhotoLinear,
11542 linearGamut: ProPhotoLinear,
11543 toBase(RGB) {
11544 // Transfer curve is gamma 1.8 with a small linear portion
11545 return RGB.map(v => {
11546 let sign = v < 0 ? -1 : 1;
11547 let abs = v * sign;
11548 if (abs < Et2) {
11549 return v / 16;
11550 }
11551 return sign * abs ** 1.8;
11552 });
11553 },
11554 fromBase(RGB) {
11555 return RGB.map(v => {
11556 let sign = v < 0 ? -1 : 1;
11557 let abs = v * sign;
11558 if (abs >= Et) {
11559 return sign * abs ** (1 / 1.8);
11560 }
11561 return 16 * v;
11562 });
11563 }
11564 });
11565
11566 // import sRGB from "./srgb.js";
11567
11568 const α = 1.09929682680944;
11569 const β = 0.018053968510807;
11570 var rec2020Oetf = new RGBColorSpace({
11571 id: "--rec2020-oetf",
11572 name: "REC.2020_Scene_Referred",
11573 base: REC2020Linear,
11574 linearGamut: REC2020Linear,
11575 referred: "scene",
11576 // Non-linear transfer function from Rec. ITU-R BT.2020-2 table 4
11577 toBase(RGB) {
11578 return RGB.map(function (val) {
11579 let sign = val < 0 ? -1 : 1;
11580 let abs = val * sign;
11581 if (abs < β * 4.5) {
11582 return val / 4.5;
11583 }
11584 return sign * Math.pow((abs + α - 1) / α, 1 / 0.45);
11585 });
11586 },
11587 fromBase(RGB) {
11588 return RGB.map(function (val) {
11589 let sign = val < 0 ? -1 : 1;
11590 let abs = val * sign;
11591 if (abs >= β) {
11592 return sign * (α * Math.pow(abs, 0.45) - (α - 1));
11593 }
11594 return 4.5 * val;
11595 });
11596 }
11597 });
11598
11599 var oklchP3 = new GamutRelativeColorSpace({
11600 id: "oklch-p3",
11601 cssId: "--oklch-p3",
11602 name: "OKLCh P3",
11603 base: OKLCH,
11604 gamutSpace: P3
11605 });
11606
11607 var oklchSrgb = new GamutRelativeColorSpace({
11608 id: "oklch-srgb",
11609 cssId: "--oklch-srgb",
11610 name: "OKLCh sRGB",
11611 base: OKLCH,
11612 gamutSpace: sRGB
11613 });
11614
11615 var oklchRec2020 = new GamutRelativeColorSpace({
11616 id: "oklch-rec2020",
11617 cssId: "--oklch-rec2020",
11618 name: "OKLCh Rec.2020",
11619 base: OKLCH,
11620 gamutSpace: REC2020
11621 });
11622
11623 var lchP3 = new GamutRelativeColorSpace({
11624 id: "lch-p3",
11625 cssId: "--lch-p3",
11626 name: "LCH P3",
11627 base: lch,
11628 gamutSpace: P3
11629 });
11630
11631 var lchSrgb = new GamutRelativeColorSpace({
11632 id: "lch-srgb",
11633 cssId: "--lch-srgb",
11634 name: "LCH sRGB",
11635 base: lch,
11636 gamutSpace: sRGB
11637 });
11638
11639 var lchRec2020 = new GamutRelativeColorSpace({
11640 id: "lch-rec2020",
11641 cssId: "--lch-rec2020",
11642 name: "LCH Rec.2020",
11643 base: lch,
11644 gamutSpace: REC2020
11645 });
11646
11647 /** @import { Matrix3x3, Vector3 } from "../types.js" */
11648
11649 // Type re-exports
11650 /** @typedef {import("../types.js").OKCoeff} OKCoeff */
11651
11652 const tau = 2 * Math.PI;
11653
11654 /**
11655 * Matrices used by this color space (Oklab's, plus its own),
11656 * also available as `Okhsl.M`
11657 * @type {Record<string, Matrix3x3>}
11658 */
11659 // prettier-ignore
11660 const M$3 = {
11661 ...Oklab.M,
11662 toLMS: [[0.4122214694707629, 0.5363325372617349, 0.0514459932675022], [0.2119034958178251, 0.6806995506452344, 0.1073969535369405], [0.0883024591900564, 0.2817188391361215, 0.6299787016738222]],
11663 toSRGBLinear: [[4.0767416360759583, -3.3077115392580629, 0.2309699031821043], [-1.2684379732850315, 2.6097573492876882, -0.3413193760026570], [-0.0041960761386756, -0.7034186179359362, 1.7076146940746117]]
11664 };
11665
11666 /** @type {OKCoeff} */
11667 const RGBCoeff = [
11668 // Red
11669 [
11670 // Limit
11671 [-1.8817031, -0.80936501],
11672 // `Kn` coefficients
11673 [1.19086277, 1.76576728, 0.59662641, 0.75515197, 0.56771245]],
11674 // Green
11675 [
11676 // Limit
11677 [1.8144408, -1.19445267],
11678 // `Kn` coefficients
11679 [0.73956515, -0.45954404, 0.08285427, 0.12541073, -0.14503204]],
11680 // Blue
11681 [
11682 // Limit
11683 [0.13110758, 1.81333971],
11684 // `Kn` coefficients
11685 [1.35733652, -0.00915799, -1.1513021, -0.50559606, 0.00692167]]];
11686 const floatMax = Number.MAX_VALUE;
11687 const K1 = 0.206;
11688 const K2 = 0.03;
11689 const K3 = (1.0 + K1) / (1.0 + K2);
11690 function vdot(a, b) {
11691 // Dot two vectors
11692
11693 let l = a.length;
11694 if (l !== b.length) {
11695 throw new Error(`Vectors of size ${l} and ${b.length} are not aligned`);
11696 }
11697 let s = 0.0;
11698 a.forEach((c, i) => {
11699 s += c * b[i];
11700 });
11701 return s;
11702 }
11703
11704 /**
11705 * Toe function for L_r
11706 * @param {number} x
11707 */
11708 function toe(x) {
11709 return 0.5 * (K3 * x - K1 + Math.sqrt((K3 * x - K1) * (K3 * x - K1) + 4 * K2 * K3 * x));
11710 }
11711
11712 /**
11713 * Inverse toe function for L_r
11714 * @param {number} x
11715 */
11716 function toeInv(x) {
11717 return (x ** 2 + K1 * x) / (K3 * (x + K2));
11718 }
11719
11720 /**
11721 * @param {readonly [number, number]} cusp
11722 * @returns {[number, number]}
11723 */
11724 function toSt(cusp) {
11725 // To ST.
11726
11727 let [l, c] = cusp;
11728 return [c / l, c / (1 - l)];
11729 }
11730 function getStMid(a, b) {
11731 // Returns a smooth approximation of the location of the cusp.
11732 //
11733 // This polynomial was created by an optimization process.
11734 // It has been designed so that S_mid < S_max and T_mid < T_max.
11735
11736 // prettier-ignore
11737 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))));
11738
11739 // prettier-ignore
11740 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))));
11741 return [s, t];
11742 }
11743
11744 /**
11745 * @param {Vector3} lab
11746 * @param {Matrix3x3} lmsToRgb
11747 */
11748 function oklabToLinearRGB(lab, lmsToRgb) {
11749 // Convert from Oklab to linear RGB.
11750 //
11751 // Can be any gamut as long as `lmsToRgb` is a matrix
11752 // that transform the LMS values to the linear RGB space.
11753
11754 let lms = multiply_v3_m3x3(lab, M$3.LabtoLMS);
11755 lms[0] = lms[0] ** 3;
11756 lms[1] = lms[1] ** 3;
11757 lms[2] = lms[2] ** 3;
11758 return multiply_v3_m3x3(lms, lmsToRgb, lms);
11759 }
11760
11761 /**
11762 * @param {number} a
11763 * @param {number} b
11764 * @param {Matrix3x3} lmsToRgb
11765 * @param {OKCoeff} okCoeff
11766 * @returns {[number, number]}
11767 * @todo Could probably make these types more specific/better-documented if desired
11768 */
11769 function findCusp(a, b, lmsToRgb, okCoeff) {
11770 // Finds L_cusp and C_cusp for a given hue.
11771 //
11772 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
11773
11774 // First, find the maximum saturation (saturation `S = C/L`)
11775 let sCusp = computeMaxSaturation(a, b, lmsToRgb, okCoeff);
11776
11777 // Convert to linear RGB to find the first point where at least one of r, g or b >= 1:
11778 let rgb = oklabToLinearRGB([1, sCusp * a, sCusp * b], lmsToRgb);
11779 let lCusp = spow(1.0 / Math.max(...rgb), 1 / 3);
11780 let cCusp = lCusp * sCusp;
11781 return [lCusp, cCusp];
11782 }
11783
11784 /**
11785 * @param {number} a
11786 * @param {number} b
11787 * @param {number} l1
11788 * @param {number} c1
11789 * @param {number} l0
11790 * @param {Matrix3x3} lmsToRgb
11791 * @param {OKCoeff} okCoeff
11792 * @param {[number, number]} cusp
11793 * @returns {Number}
11794 * @todo Could probably make these types more specific/better-documented if desired
11795 */
11796 function findGamutIntersection(a, b, l1, c1, l0, lmsToRgb, okCoeff, cusp) {
11797 // Finds intersection of the line.
11798 //
11799 // Defined by the following:
11800 //
11801 // ```
11802 // L = L0 * (1 - t) + t * L1
11803 // C = t * C1
11804 // ```
11805 //
11806 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
11807
11808 let t;
11809 if (cusp === undefined) {
11810 cusp = findCusp(a, b, lmsToRgb, okCoeff);
11811 }
11812
11813 // Find the intersection for upper and lower half separately
11814 if ((l1 - l0) * cusp[1] - (cusp[0] - l0) * c1 <= 0.0) {
11815 // Lower half
11816 t = cusp[1] * l0 / (c1 * cusp[0] + cusp[1] * (l0 - l1));
11817 } else {
11818 // Upper half
11819
11820 // First intersect with triangle
11821 t = cusp[1] * (l0 - 1.0) / (c1 * (cusp[0] - 1.0) + cusp[1] * (l0 - l1));
11822
11823 // Then one step Halley's method
11824 let dl = l1 - l0;
11825 let dc = c1;
11826 let kl = vdot(M$3.LabtoLMS[0].slice(1), [a, b]);
11827 let km = vdot(M$3.LabtoLMS[1].slice(1), [a, b]);
11828 let ks = vdot(M$3.LabtoLMS[2].slice(1), [a, b]);
11829 let ldt_ = dl + dc * kl;
11830 let mdt_ = dl + dc * km;
11831 let sdt_ = dl + dc * ks;
11832
11833 // If higher accuracy is required, 2 or 3 iterations of the following block can be used:
11834 let L = l0 * (1.0 - t) + t * l1;
11835 let C = t * c1;
11836 let l_ = L + C * kl;
11837 let m_ = L + C * km;
11838 let s_ = L + C * ks;
11839 let l = l_ ** 3;
11840 let m = m_ ** 3;
11841 let s = s_ ** 3;
11842 let ldt = 3 * ldt_ * l_ ** 2;
11843 let mdt = 3 * mdt_ * m_ ** 2;
11844 let sdt = 3 * sdt_ * s_ ** 2;
11845 let ldt2 = 6 * ldt_ ** 2 * l_;
11846 let mdt2 = 6 * mdt_ ** 2 * m_;
11847 let sdt2 = 6 * sdt_ ** 2 * s_;
11848 let r_ = vdot(lmsToRgb[0], [l, m, s]) - 1;
11849 let r1 = vdot(lmsToRgb[0], [ldt, mdt, sdt]);
11850 let r2 = vdot(lmsToRgb[0], [ldt2, mdt2, sdt2]);
11851 let ur = r1 / (r1 * r1 - 0.5 * r_ * r2);
11852 let tr = -r_ * ur;
11853 let g_ = vdot(lmsToRgb[1], [l, m, s]) - 1;
11854 let g1 = vdot(lmsToRgb[1], [ldt, mdt, sdt]);
11855 let g2 = vdot(lmsToRgb[1], [ldt2, mdt2, sdt2]);
11856 let ug = g1 / (g1 * g1 - 0.5 * g_ * g2);
11857 let tg = -g_ * ug;
11858 let b_ = vdot(lmsToRgb[2], [l, m, s]) - 1;
11859 let b1 = vdot(lmsToRgb[2], [ldt, mdt, sdt]);
11860 let b2 = vdot(lmsToRgb[2], [ldt2, mdt2, sdt2]);
11861 let ub = b1 / (b1 * b1 - 0.5 * b_ * b2);
11862 let tb = -b_ * ub;
11863 tr = ur >= 0.0 ? tr : floatMax;
11864 tg = ug >= 0.0 ? tg : floatMax;
11865 tb = ub >= 0.0 ? tb : floatMax;
11866 t += Math.min(tr, Math.min(tg, tb));
11867 }
11868 return t;
11869 }
11870 function getCs(lab, lmsToRgb, okCoeff) {
11871 // Get Cs
11872
11873 let [l, a, b] = lab;
11874 let cusp = findCusp(a, b, lmsToRgb, okCoeff);
11875 let cMax = findGamutIntersection(a, b, l, 1, l, lmsToRgb, okCoeff, cusp);
11876 let stMax = toSt(cusp);
11877
11878 // Scale factor to compensate for the curved part of gamut shape:
11879 let k = cMax / Math.min(l * stMax[0], (1 - l) * stMax[1]);
11880 let stMid = getStMid(a, b);
11881
11882 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
11883 let ca = l * stMid[0];
11884 let cb = (1.0 - l) * stMid[1];
11885 let cMid = 0.9 * k * Math.sqrt(Math.sqrt(1.0 / (1.0 / ca ** 4 + 1.0 / cb ** 4)));
11886
11887 // For `C_0`, the shape is independent of hue, so `ST` are constant.
11888 // Values picked to roughly be the average values of `ST`.
11889 ca = l * 0.4;
11890 cb = (1.0 - l) * 0.8;
11891
11892 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
11893 let c0 = Math.sqrt(1.0 / (1.0 / ca ** 2 + 1.0 / cb ** 2));
11894 return [c0, cMid, cMax];
11895 }
11896 function computeMaxSaturation(a, b, lmsToRgb, okCoeff) {
11897 // Finds the maximum saturation possible for a given hue that fits in RGB.
11898 //
11899 // Saturation here is defined as `S = C/L`.
11900 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
11901
11902 // Max saturation will be when one of r, g or b goes below zero.
11903
11904 // Select different coefficients depending on which component goes below zero first.
11905
11906 let k0, k1, k2, k3, k4, wl, wm, ws;
11907 if (vdot(okCoeff[0][0], [a, b]) > 1) {
11908 // Red component
11909 [k0, k1, k2, k3, k4] = okCoeff[0][1];
11910 [wl, wm, ws] = lmsToRgb[0];
11911 } else if (vdot(okCoeff[1][0], [a, b]) > 1) {
11912 // Green component
11913 [k0, k1, k2, k3, k4] = okCoeff[1][1];
11914 [wl, wm, ws] = lmsToRgb[1];
11915 } else {
11916 // Blue component
11917 [k0, k1, k2, k3, k4] = okCoeff[2][1];
11918 [wl, wm, ws] = lmsToRgb[2];
11919 }
11920
11921 // Approximate max saturation using a polynomial:
11922 let sat = k0 + k1 * a + k2 * b + k3 * a ** 2 + k4 * a * b;
11923
11924 // Do one step Halley's method to get closer.
11925 // This gives an error less than 10e6, except for some blue hues where the `dS/dh` is close to infinite.
11926 // This should be sufficient for most applications, otherwise do two/three steps.
11927
11928 let kl = vdot(M$3.LabtoLMS[0].slice(1), [a, b]);
11929 let km = vdot(M$3.LabtoLMS[1].slice(1), [a, b]);
11930 let ks = vdot(M$3.LabtoLMS[2].slice(1), [a, b]);
11931 let l_ = 1.0 + sat * kl;
11932 let m_ = 1.0 + sat * km;
11933 let s_ = 1.0 + sat * ks;
11934 let l = l_ ** 3;
11935 let m = m_ ** 3;
11936 let s = s_ ** 3;
11937 let lds = 3.0 * kl * l_ ** 2;
11938 let mds = 3.0 * km * m_ ** 2;
11939 let sds = 3.0 * ks * s_ ** 2;
11940 let lds2 = 6.0 * kl ** 2 * l_;
11941 let mds2 = 6.0 * km ** 2 * m_;
11942 let sds2 = 6.0 * ks ** 2 * s_;
11943 let f = wl * l + wm * m + ws * s;
11944 let f1 = wl * lds + wm * mds + ws * sds;
11945 let f2 = wl * lds2 + wm * mds2 + ws * sds2;
11946 sat = sat - f * f1 / (f1 ** 2 - 0.5 * f * f2);
11947 return sat;
11948 }
11949 function okhslToOklab(hsl, lmsToRgb, okCoeff) {
11950 // Convert Okhsl to Oklab.
11951
11952 let [h, s, l] = hsl;
11953 let L = toeInv(l);
11954 let a = null;
11955 let b = null;
11956 h = constrain(h) / 360.0;
11957 if (L !== 0.0 && L !== 1.0 && s !== 0) {
11958 let a_ = Math.cos(tau * h);
11959 let b_ = Math.sin(tau * h);
11960 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
11961
11962 // Interpolate the three values for C so that:
11963 // ```
11964 // At s=0: dC/ds = C_0, C=0
11965 // At s=0.8: C=C_mid
11966 // At s=1.0: C=C_max
11967 // ```
11968
11969 let mid = 0.8;
11970 let midInv = 1.25;
11971 let t, k0, k1, k2;
11972 if (s < mid) {
11973 t = midInv * s;
11974 k0 = 0.0;
11975 k1 = mid * c0;
11976 k2 = 1.0 - k1 / cMid;
11977 } else {
11978 t = 5 * (s - 0.8);
11979 k0 = cMid;
11980 k1 = 0.2 * cMid ** 2 * 1.25 ** 2 / c0;
11981 k2 = 1.0 - k1 / (cMax - cMid);
11982 }
11983 let c = k0 + t * k1 / (1.0 - k2 * t);
11984 a = c * a_;
11985 b = c * b_;
11986 }
11987 return [L, a, b];
11988 }
11989 function oklabToOkhsl(lab, lmsToRgb, okCoeff) {
11990 // Oklab to Okhsl.
11991
11992 // Epsilon for lightness should approach close to 32 bit lightness
11993 // Epsilon for saturation just needs to be sufficiently close when denoting achromatic
11994 let εL = 1e-7;
11995 let εS = 1e-4;
11996 let L = lab[0];
11997 let s = 0.0;
11998 let l = toe(L);
11999 let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2);
12000 let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau;
12001 if (l !== 0.0 && l !== 1.0 && c !== 0) {
12002 let a_ = lab[1] / c;
12003 let b_ = lab[2] / c;
12004 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
12005 let mid = 0.8;
12006 let midInv = 1.25;
12007 let k0, k1, k2, t;
12008 if (c < cMid) {
12009 k1 = mid * c0;
12010 k2 = 1.0 - k1 / cMid;
12011 t = c / (k1 + k2 * c);
12012 s = t * mid;
12013 } else {
12014 k0 = cMid;
12015 k1 = 0.2 * cMid ** 2 * midInv ** 2 / c0;
12016 k2 = 1.0 - k1 / (cMax - cMid);
12017 t = (c - k0) / (k1 + k2 * (c - k0));
12018 s = mid + 0.2 * t;
12019 }
12020 }
12021 const achromatic = Math.abs(s) < εS;
12022 if (achromatic || l === 0.0 || Math.abs(1 - l) < εL) {
12023 h = null;
12024 // Due to floating point imprecision near lightness of 1, we can end up
12025 // with really high around white, this is to provide consistency as
12026 // saturation can be really high for white due this imprecision.
12027 if (!achromatic) {
12028 s = 0.0;
12029 }
12030 } else {
12031 h = constrain(h * 360);
12032 }
12033 return [h, s, l];
12034 }
12035 const Okhsl = new ColorSpace({
12036 id: "okhsl",
12037 name: "Okhsl",
12038 coords: {
12039 h: {
12040 refRange: [0, 360],
12041 type: "angle",
12042 name: "Hue"
12043 },
12044 s: {
12045 range: [0, 1],
12046 name: "Saturation"
12047 },
12048 l: {
12049 range: [0, 1],
12050 name: "Lightness"
12051 }
12052 },
12053 base: Oklab,
12054 gamutSpace: "self",
12055 M: M$3,
12056 // Convert Oklab to Okhsl
12057 fromBase(lab) {
12058 return oklabToOkhsl(lab, M$3.toSRGBLinear, RGBCoeff);
12059 },
12060 // Convert Okhsl to Oklab
12061 toBase(hsl) {
12062 return okhslToOklab(hsl, M$3.toSRGBLinear, RGBCoeff);
12063 },
12064 formats: {
12065 color: {
12066 id: "--okhsl",
12067 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
12068 }
12069 }
12070 });
12071 Okhsl.rgbGamut = new RGBColorSpace({
12072 id: "okhsl-prism",
12073 cssId: "--okhsl-prism",
12074 name: "Okhsl Prism",
12075 base: Okhsl,
12076 fromBase(hsl) {
12077 return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]);
12078 },
12079 toBase(rgb) {
12080 const hsl = HSL.fromBase(rgb);
12081 hsl[1] /= 100;
12082 hsl[2] /= 100;
12083 return hsl;
12084 }
12085 });
12086
12087 var OKLrab = new ColorSpace({
12088 id: "oklrab",
12089 name: "Oklrab",
12090 coords: {
12091 l: {
12092 refRange: [0, 1],
12093 name: "Lightness"
12094 },
12095 a: {
12096 refRange: [-0.4, 0.4]
12097 },
12098 b: {
12099 refRange: [-0.4, 0.4]
12100 }
12101 },
12102 // Note that XYZ is relative to D65
12103 white: "D65",
12104 base: Oklab,
12105 fromBase(oklab) {
12106 return [toe(oklab[0]), oklab[1], oklab[2]];
12107 },
12108 toBase(oklrab) {
12109 return [toeInv(oklrab[0]), oklrab[1], oklrab[2]];
12110 },
12111 formats: {
12112 color: {
12113 coords: ["<percentage> | <number>", "<number> | <percentage>[-1,1]", "<number> | <percentage>[-1,1]"]
12114 }
12115 }
12116 });
12117
12118 var oklrch = new ColorSpace({
12119 id: "oklrch",
12120 name: "Oklrch",
12121 coords: {
12122 l: {
12123 refRange: [0, 1],
12124 name: "Lightness"
12125 },
12126 c: {
12127 refRange: [0, 0.4],
12128 name: "Chroma"
12129 },
12130 h: {
12131 refRange: [0, 360],
12132 type: "angle",
12133 name: "Hue"
12134 }
12135 },
12136 white: "D65",
12137 base: OKLrab,
12138 fromBase: lch.fromBase,
12139 toBase: lch.toBase,
12140 formats: {
12141 color: {
12142 coords: ["<percentage> | <number>", "<number> | <percentage>[0,1]", "<number> | <angle>"]
12143 }
12144 }
12145 });
12146
12147 // Okhsv class.
12148 //
12149 // ---- License ----
12150 //
12151 // Copyright (c) 2021 Björn Ottosson
12152 //
12153 // Permission is hereby granted, free of charge, to any person obtaining a copy of
12154 // this software and associated documentation files (the "Software"), to deal in
12155 // the Software without restriction, including without limitation the rights to
12156 // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
12157 // of the Software, and to permit persons to whom the Software is furnished to do
12158 // so, subject to the following conditions:
12159 //
12160 // The above copyright notice and this permission notice shall be included in all
12161 // copies or substantial portions of the Software.
12162 //
12163 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12164 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12165 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12166 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
12167 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12168 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
12169 // SOFTWARE.
12170
12171 /**
12172 * Matrices used by this color space (reused from Okhsl), also available as `Okhsv.M`
12173 * @type {Record<string, Matrix3x3>}
12174 */
12175 const M$2 = {
12176 toSRGBLinear: Okhsl.M.toSRGBLinear
12177 };
12178
12179 /** @import { Coords, Matrix3x3, OKCoeff, Vector3 } from "../types.js" */
12180
12181 /**
12182 *
12183 * @param {Vector3} hsv
12184 * @param {Matrix3x3} lmsToRgb
12185 * @param {OKCoeff} okCoeff
12186 * @returns {Coords}
12187 */
12188 function okhsvToOklab(hsv, lmsToRgb, okCoeff) {
12189 // Convert from Okhsv to Oklab."""
12190
12191 let [h, s, v] = hsv;
12192 h = constrain(h) / 360.0;
12193 let l = toeInv(v);
12194 let a = null;
12195 let b = null;
12196
12197 // Avoid processing gray or colors with undefined hues
12198 if (l !== 0.0 && s !== 0.0) {
12199 let a_ = Math.cos(tau * h);
12200 let b_ = Math.sin(tau * h);
12201 let cusp = findCusp(a_, b_, lmsToRgb, okCoeff);
12202 let [sMax, tMax] = toSt(cusp);
12203 let s0 = 0.5;
12204 let k = 1 - s0 / sMax;
12205
12206 // first we compute L and V as if the gamut is a perfect triangle:
12207
12208 // L, C when v==1:
12209 let lv = 1 - s * s0 / (s0 + tMax - tMax * k * s);
12210 let cv = s * tMax * s0 / (s0 + tMax - tMax * k * s);
12211 l = v * lv;
12212 let c = v * cv;
12213
12214 // then we compensate for both toe and the curved top part of the triangle:
12215 let lvt = toeInv(lv);
12216 let cvt = cv * lvt / lv;
12217 let lNew = toeInv(l);
12218 c = c * lNew / l;
12219 l = lNew;
12220
12221 // RGB scale
12222 let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb);
12223 let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3);
12224 l = l * scaleL;
12225 c = c * scaleL;
12226 a = c * a_;
12227 b = c * b_;
12228 }
12229 return [l, a, b];
12230 }
12231
12232 /**
12233 *
12234 * @param {Vector3} lab
12235 * @param {Matrix3x3} lmsToRgb
12236 * @param {OKCoeff} okCoeff
12237 * @returns {Coords}
12238 */
12239 function oklabToOkhsv(lab, lmsToRgb, okCoeff) {
12240 // Oklab to Okhsv.
12241
12242 // Epsilon for saturation just needs to be sufficiently close when denoting achromatic
12243 let ε = 1e-4;
12244 let l = lab[0];
12245 let s = 0.0;
12246 let v = toe(l);
12247 let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2);
12248 let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau;
12249 if (l !== 0.0 && l !== 1 && c !== 0.0) {
12250 let a_ = lab[1] / c;
12251 let b_ = lab[2] / c;
12252 let cusp = findCusp(a_, b_, lmsToRgb, okCoeff);
12253 let [sMax, tMax] = toSt(cusp);
12254 let s0 = 0.5;
12255 let k = 1 - s0 / sMax;
12256
12257 // first we find `L_v`, `C_v`, `L_vt` and `C_vt`
12258 let t = tMax / (c + l * tMax);
12259 let lv = t * l;
12260 let cv = t * c;
12261 let lvt = toeInv(lv);
12262 let cvt = cv * lvt / lv;
12263
12264 // we can then use these to invert the step that compensates
12265 // for the toe and the curved top part of the triangle:
12266 let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb);
12267 let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3);
12268 l = l / scaleL;
12269 c = c / scaleL;
12270 c = c * toe(l) / l;
12271 l = toe(l);
12272
12273 // we can now compute v and s:
12274 v = l / lv;
12275 s = (s0 + tMax) * cv / (tMax * s0 + tMax * k * cv);
12276 }
12277 if (Math.abs(s) < ε || v === 0.0) {
12278 h = null;
12279 } else {
12280 h = constrain(h * 360);
12281 }
12282 return [h, s, v];
12283 }
12284 const Okhsv = new ColorSpace({
12285 id: "okhsv",
12286 name: "Okhsv",
12287 coords: {
12288 h: {
12289 refRange: [0, 360],
12290 type: "angle",
12291 name: "Hue"
12292 },
12293 s: {
12294 range: [0, 1],
12295 name: "Saturation"
12296 },
12297 v: {
12298 range: [0, 1],
12299 name: "Value"
12300 }
12301 },
12302 base: Oklab,
12303 gamutSpace: "self",
12304 M: M$2,
12305 // Convert Oklab to Okhsl
12306 fromBase(lab) {
12307 return oklabToOkhsv(lab, M$2.toSRGBLinear, RGBCoeff);
12308 },
12309 // Convert Okhsl to Oklab
12310 toBase(hsl) {
12311 return okhsvToOklab(hsl, M$2.toSRGBLinear, RGBCoeff);
12312 },
12313 formats: {
12314 color: {
12315 id: "--okhsv",
12316 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
12317 }
12318 }
12319 });
12320 Okhsv.rgbGamut = new RGBColorSpace({
12321 id: "okhsv-prism",
12322 cssId: "--okhsv-prism",
12323 name: "Okhsv Prism",
12324 base: Okhsv,
12325 fromBase(hsl) {
12326 return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]);
12327 },
12328 toBase(rgb) {
12329 const hsl = HSL.fromBase(rgb);
12330 hsl[1] /= 100;
12331 hsl[2] /= 100;
12332 return hsl;
12333 }
12334 });
12335
12336 let white = WHITES.D65;
12337 const ε$2 = 216 / 24389; // 6^3/29^3 == (24/116)^3
12338 const κ$1 = 24389 / 27; // 29^3/3^3
12339 const [U_PRIME_WHITE, V_PRIME_WHITE] = uv({
12340 space: XYZ_D65,
12341 coords: white
12342 });
12343 var Luv = new ColorSpace({
12344 id: "luv",
12345 name: "Luv",
12346 coords: {
12347 l: {
12348 refRange: [0, 100],
12349 name: "Lightness"
12350 },
12351 // Reference ranges from https://facelessuser.github.io/coloraide/colors/luv/
12352 u: {
12353 refRange: [-215, 215]
12354 },
12355 v: {
12356 refRange: [-215, 215]
12357 }
12358 },
12359 white: white,
12360 base: XYZ_D65,
12361 // Convert D65-adapted XYZ to Luv
12362 // https://en.wikipedia.org/wiki/CIELUV#The_forward_transformation
12363 fromBase(XYZ) {
12364 let xyz = /** @type {[number, number, number]} */[skipNone(XYZ[0]), skipNone(XYZ[1]), skipNone(XYZ[2])];
12365 let y = xyz[1];
12366 let [up, vp] = uv({
12367 space: XYZ_D65,
12368 coords: xyz
12369 });
12370
12371 // Protect against XYZ of [0, 0, 0]
12372 if (!Number.isFinite(up) || !Number.isFinite(vp)) {
12373 return [0, 0, 0];
12374 }
12375 let L = y <= ε$2 ? κ$1 * y : 116 * Math.cbrt(y) - 16;
12376 return [L, 13 * L * (up - U_PRIME_WHITE), 13 * L * (vp - V_PRIME_WHITE)];
12377 },
12378 // Convert Luv to D65-adapted XYZ
12379 // https://en.wikipedia.org/wiki/CIELUV#The_reverse_transformation
12380 toBase(Luv) {
12381 let [L, u, v] = Luv;
12382
12383 // Protect against division by zero and none Lightness
12384 if (L === 0 || isNone(L)) {
12385 return [0, 0, 0];
12386 }
12387 u = skipNone(u);
12388 v = skipNone(v);
12389 let up = u / (13 * L) + U_PRIME_WHITE;
12390 let vp = v / (13 * L) + V_PRIME_WHITE;
12391 let y = L <= 8 ? L / κ$1 : Math.pow((L + 16) / 116, 3);
12392 return [y * (9 * up / (4 * vp)), y, y * ((12 - 3 * up - 20 * vp) / (4 * vp))];
12393 },
12394 formats: {
12395 color: {
12396 id: "--luv",
12397 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <percentage>"]
12398 }
12399 }
12400 });
12401
12402 var LCHuv = new ColorSpace({
12403 id: "lchuv",
12404 name: "LChuv",
12405 coords: {
12406 l: {
12407 refRange: [0, 100],
12408 name: "Lightness"
12409 },
12410 c: {
12411 refRange: [0, 220],
12412 name: "Chroma"
12413 },
12414 h: {
12415 refRange: [0, 360],
12416 type: "angle",
12417 name: "Hue"
12418 }
12419 },
12420 base: Luv,
12421 fromBase: lch.fromBase,
12422 toBase: lch.toBase,
12423 formats: {
12424 color: {
12425 id: "--lchuv",
12426 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <angle>"]
12427 }
12428 }
12429 });
12430
12431 /*
12432 Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts
12433
12434 Copyright (c) 2012-2022 Alexei Boronine
12435
12436 Permission is hereby granted, free of charge, to any person obtaining a copy
12437 of this software and associated documentation files (the "Software"), to deal
12438 in the Software without restriction, including without limitation the rights
12439 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12440 copies of the Software, and to permit persons to whom the Software is
12441 furnished to do so, subject to the following conditions:
12442
12443 The above copyright notice and this permission notice shall be included in all
12444 copies or substantial portions of the Software.
12445
12446 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12447 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12448 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12449 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
12450 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12451 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
12452 SOFTWARE.
12453 */
12454
12455 const ε$1 = 216 / 24389; // 6^3/29^3 == (24/116)^3
12456 const κ = 24389 / 27; // 29^3/3^3
12457
12458 const fromXYZ_M$1 = M$6.fromXYZ;
12459 const m_r0 = fromXYZ_M$1[0][0];
12460 const m_r1 = fromXYZ_M$1[0][1];
12461 const m_r2 = fromXYZ_M$1[0][2];
12462 const m_g0 = fromXYZ_M$1[1][0];
12463 const m_g1 = fromXYZ_M$1[1][1];
12464 const m_g2 = fromXYZ_M$1[1][2];
12465 const m_b0 = fromXYZ_M$1[2][0];
12466 const m_b1 = fromXYZ_M$1[2][1];
12467 const m_b2 = fromXYZ_M$1[2][2];
12468 function distanceFromOriginAngle(slope, intercept, angle) {
12469 const d = intercept / (Math.sin(angle) - slope * Math.cos(angle));
12470 return d < 0 ? Infinity : d;
12471 }
12472
12473 /**
12474 * @param {number} l
12475 */
12476 function calculateBoundingLines(l) {
12477 const sub1 = Math.pow(l + 16, 3) / 1560896;
12478 const sub2 = sub1 > ε$1 ? sub1 : l / κ;
12479 const s1r = sub2 * (284517 * m_r0 - 94839 * m_r2);
12480 const s2r = sub2 * (838422 * m_r2 + 769860 * m_r1 + 731718 * m_r0);
12481 const s3r = sub2 * (632260 * m_r2 - 126452 * m_r1);
12482 const s1g = sub2 * (284517 * m_g0 - 94839 * m_g2);
12483 const s2g = sub2 * (838422 * m_g2 + 769860 * m_g1 + 731718 * m_g0);
12484 const s3g = sub2 * (632260 * m_g2 - 126452 * m_g1);
12485 const s1b = sub2 * (284517 * m_b0 - 94839 * m_b2);
12486 const s2b = sub2 * (838422 * m_b2 + 769860 * m_b1 + 731718 * m_b0);
12487 const s3b = sub2 * (632260 * m_b2 - 126452 * m_b1);
12488 return {
12489 r0s: s1r / s3r,
12490 r0i: s2r * l / s3r,
12491 r1s: s1r / (s3r + 126452),
12492 r1i: (s2r - 769860) * l / (s3r + 126452),
12493 g0s: s1g / s3g,
12494 g0i: s2g * l / s3g,
12495 g1s: s1g / (s3g + 126452),
12496 g1i: (s2g - 769860) * l / (s3g + 126452),
12497 b0s: s1b / s3b,
12498 b0i: s2b * l / s3b,
12499 b1s: s1b / (s3b + 126452),
12500 b1i: (s2b - 769860) * l / (s3b + 126452)
12501 };
12502 }
12503 function calcMaxChromaHsluv(lines, h) {
12504 const hueRad = h / 360 * Math.PI * 2;
12505 const r0 = distanceFromOriginAngle(lines.r0s, lines.r0i, hueRad);
12506 const r1 = distanceFromOriginAngle(lines.r1s, lines.r1i, hueRad);
12507 const g0 = distanceFromOriginAngle(lines.g0s, lines.g0i, hueRad);
12508 const g1 = distanceFromOriginAngle(lines.g1s, lines.g1i, hueRad);
12509 const b0 = distanceFromOriginAngle(lines.b0s, lines.b0i, hueRad);
12510 const b1 = distanceFromOriginAngle(lines.b1s, lines.b1i, hueRad);
12511 return Math.min(r0, r1, g0, g1, b0, b1);
12512 }
12513 var hsluv = new ColorSpace({
12514 id: "hsluv",
12515 name: "HSLuv",
12516 coords: {
12517 h: {
12518 refRange: [0, 360],
12519 type: "angle",
12520 name: "Hue"
12521 },
12522 s: {
12523 range: [0, 100],
12524 name: "Saturation"
12525 },
12526 l: {
12527 range: [0, 100],
12528 name: "Lightness"
12529 }
12530 },
12531 base: LCHuv,
12532 gamutSpace: sRGB,
12533 rgbGamut: sRGB,
12534 // Convert LCHuv to HSLuv
12535 fromBase(lch) {
12536 let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])];
12537 let s;
12538 if (l > 99.9999999) {
12539 s = 0;
12540 l = 100;
12541 } else if (l < 0.00000001) {
12542 s = 0;
12543 l = 0;
12544 } else {
12545 let lines = calculateBoundingLines(l);
12546 let max = calcMaxChromaHsluv(lines, h);
12547 s = c / max * 100;
12548 }
12549 return [h, s, l];
12550 },
12551 // Convert HSLuv to LCHuv
12552 toBase(hsl) {
12553 let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])];
12554 let c;
12555 if (l > 99.9999999) {
12556 l = 100;
12557 c = 0;
12558 } else if (l < 0.00000001) {
12559 l = 0;
12560 c = 0;
12561 } else {
12562 let lines = calculateBoundingLines(l);
12563 let max = calcMaxChromaHsluv(lines, h);
12564 c = max / 100 * s;
12565 }
12566 return [l, c, h];
12567 },
12568 formats: {
12569 color: {
12570 id: "--hsluv",
12571 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
12572 }
12573 }
12574 });
12575
12576 /*
12577 Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts
12578
12579 Copyright (c) 2012-2022 Alexei Boronine
12580
12581 Permission is hereby granted, free of charge, to any person obtaining a copy
12582 of this software and associated documentation files (the "Software"), to deal
12583 in the Software without restriction, including without limitation the rights
12584 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12585 copies of the Software, and to permit persons to whom the Software is
12586 furnished to do so, subject to the following conditions:
12587
12588 The above copyright notice and this permission notice shall be included in all
12589 copies or substantial portions of the Software.
12590
12591 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12592 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12593 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12594 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
12595 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12596 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
12597 SOFTWARE.
12598 */
12599
12600
12601 const fromXYZ_M = M$6.fromXYZ;
12602 fromXYZ_M[0][0];
12603 fromXYZ_M[0][1];
12604 fromXYZ_M[0][2];
12605 fromXYZ_M[1][0];
12606 fromXYZ_M[1][1];
12607 fromXYZ_M[1][2];
12608 fromXYZ_M[2][0];
12609 fromXYZ_M[2][1];
12610 fromXYZ_M[2][2];
12611 function distanceFromOrigin(slope, intercept) {
12612 return Math.abs(intercept) / Math.sqrt(Math.pow(slope, 2) + 1);
12613 }
12614 function calcMaxChromaHpluv(lines) {
12615 let r0 = distanceFromOrigin(lines.r0s, lines.r0i);
12616 let r1 = distanceFromOrigin(lines.r1s, lines.r1i);
12617 let g0 = distanceFromOrigin(lines.g0s, lines.g0i);
12618 let g1 = distanceFromOrigin(lines.g1s, lines.g1i);
12619 let b0 = distanceFromOrigin(lines.b0s, lines.b0i);
12620 let b1 = distanceFromOrigin(lines.b1s, lines.b1i);
12621 return Math.min(r0, r1, g0, g1, b0, b1);
12622 }
12623 const HPLuv = new ColorSpace({
12624 id: "hpluv",
12625 name: "HPLuv",
12626 coords: {
12627 h: {
12628 refRange: [0, 360],
12629 type: "angle",
12630 name: "Hue"
12631 },
12632 s: {
12633 range: [0, 100],
12634 name: "Saturation"
12635 },
12636 l: {
12637 range: [0, 100],
12638 name: "Lightness"
12639 }
12640 },
12641 base: LCHuv,
12642 gamutSpace: "self",
12643 // Convert LCHuv to HPLuv
12644 fromBase(lch) {
12645 let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])];
12646 let s;
12647 if (l > 99.9999999) {
12648 s = 0;
12649 l = 100;
12650 } else if (l < 0.00000001) {
12651 s = 0;
12652 l = 0;
12653 } else {
12654 let lines = calculateBoundingLines(l);
12655 let max = calcMaxChromaHpluv(lines);
12656 s = c / max * 100;
12657 }
12658 return [h, s, l];
12659 },
12660 // Convert HPLuv to LCHuv
12661 toBase(hsl) {
12662 let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])];
12663 let c;
12664 if (l > 99.9999999) {
12665 l = 100;
12666 c = 0;
12667 } else if (l < 0.00000001) {
12668 l = 0;
12669 c = 0;
12670 } else {
12671 let lines = calculateBoundingLines(l);
12672 let max = calcMaxChromaHpluv(lines);
12673 c = max / 100 * s;
12674 }
12675 return [l, c, h];
12676 },
12677 formats: {
12678 color: {
12679 id: "--hpluv",
12680 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
12681 }
12682 }
12683 });
12684 HPLuv.rgbGamut = new RGBColorSpace({
12685 id: "hpluv-prism",
12686 cssId: "--hpluv-prism",
12687 name: "HPLuv Prism",
12688 base: HPLuv,
12689 fromBase(hsl) {
12690 return HSL.toBase(hsl);
12691 },
12692 toBase(rgb) {
12693 return HSL.fromBase(rgb);
12694 }
12695 });
12696
12697 /**
12698 * Helmlab GenSpace — generation-optimized color space for interpolation.
12699 *
12700 * Pipeline (v0.11.1, depressed cubic + chroma power + L-gated enrichment):
12701 * XYZ → M1 → depcubic(α=0.021) → M2 → chroma_power(0.978) →
12702 * PW_L → L-gated hue enrichment → Lab
12703 *
12704 * Optimized for perceptually uniform gradients, palette generation,
12705 * and color-mix. 59-8 vs OKLab in head-to-head benchmarks (83 metrics,
12706 * 3038 gradient pairs, sRGB/P3/Rec.2020). 360/360/360 cusps.
12707 *
12708 * Key properties:
12709 * - Depressed cubic: y³ + αy = x, finite derivative at zero
12710 * - Chroma power (0.978): improves gradient CV uniformity
12711 * - L-gated hue enrichment: fixes blue→white purple shift
12712 * - Structurally achromatic: a=b≈0 for all grays
12713 *
12714 * Note on blue-region gamut fold:
12715 * All M1→f→M2 spaces (OKLab, IPT, HelmGen) exhibit a tiny non-contiguous
12716 * gamut region near h≈260° in sRGB. This is a mathematical consequence of
12717 * mixing LMS channels before applying a power-like transfer: the inverse
12718 * creates a cubic polynomial that can have two positive roots in the blue
12719 * region. OKLab has 46 such holes; HelmGen has 5, each ~0.001 chroma wide
12720 * (sub-pixel, invisible). See: color.js#81, csswg-drafts#7071.
12721 *
12722 * Reference: arXiv:2602.23010
12723 * @see https://github.com/Grkmyldz148/helmlab
12724 */
12725
12726 /** @import { Matrix3x3 } from "../types.js" */
12727
12728 // ── Depressed cubic parameter ──────────────────────────────────────
12729 const ALPHA = 0.021;
12730 const S = Math.sqrt(ALPHA / 3);
12731 const S3 = S * S * S;
12732
12733 // ── Chroma power ───────────────────────────────────────────────────
12734 const CP = 0.978;
12735
12736 // ── L-gated hue enrichment parameters ──────────────────────────────
12737 const ENR_AMP = 0.058;
12738 const ENR_CENTER = 264.5 * Math.PI / 180; // radians
12739 const ENR_SIGMA = 0.7;
12740 const ENR_LLO = 0.37;
12741 const ENR_LHI = 1.0;
12742
12743 // ── Core matrices (v0.11.1) ────────────────────────────────────────
12744
12745 /**
12746 * Matrices used by this color space, also available as `HelmGen.M`
12747 * @type {Record<string, Matrix3x3>}
12748 */
12749 // prettier-ignore
12750 const M$1 = {
12751 // M1 = M1_orig @ CAT_TO_HELM (Bradford CAT baked in: Color.js D65 → Helmlab D65 → LMS)
12752 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]],
12753 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]],
12754 M2: [[0.21193779684470104, 0.7992121834263127, -0.00410075161564345], [2.4672018828033475, -2.9877348024830788, 0.520532919679731], [-0.11390787868068575, 1.3932982808117473, -1.279390402131062]],
12755 M2_INV: [[0.9930001151336143, 0.32599327253052285, 0.12945085631713921], [0.9930001151336139, -0.08708353111074627, -0.03861361743004929], [0.9930001151336136, -0.12386097008215022, -0.8351991365871061]]
12756 };
12757
12758 // ── Piecewise-linear L correction (21 breakpoints, v0.11.1) ───────
12759 // prettier-ignore
12760 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];
12761 // prettier-ignore
12762 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];
12763 const PW_N = PW_L_IN.length;
12764
12765 // ── Depressed cubic: y³ + αy = x ──────────────────────────────────
12766
12767 function depcubicFwd(x) {
12768 let t = x / (2 * S3);
12769 let y = 2 * S * Math.sinh(Math.asinh(t) / 3);
12770 // Halley refinement
12771 let f = y * y * y + ALPHA * y - x;
12772 let fp = 3 * y * y + ALPHA;
12773 let fpp = 6 * y;
12774 let denom = 2 * fp * fp - f * fpp;
12775 if (Math.abs(denom) > 1e-30) {
12776 y -= 2 * f * fp / denom;
12777 }
12778 return y;
12779 }
12780 function depcubicInv(y) {
12781 return y * y * y + ALPHA * y;
12782 }
12783
12784 // ── L-gated hue enrichment ─────────────────────────────────────────
12785
12786 function enrichGate(L) {
12787 let t = Math.max(0, Math.min(1, (L - ENR_LLO) / (ENR_LHI - ENR_LLO)));
12788 return Math.sin(Math.PI * t) ** 2;
12789 }
12790 function enrichFwd(L, a, b) {
12791 let C = Math.sqrt(a * a + b * b);
12792 if (C < 1e-12) {
12793 return [a, b];
12794 }
12795 let gate = enrichGate(L);
12796 if (gate < 1e-12) {
12797 return [a, b];
12798 }
12799 let h = Math.atan2(b, a);
12800 let dh = h - ENR_CENTER;
12801 dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI;
12802 let gauss = Math.exp(-0.5 * (dh / ENR_SIGMA) ** 2);
12803 let hNew = h + ENR_AMP * gate * gauss;
12804 return [C * Math.cos(hNew), C * Math.sin(hNew)];
12805 }
12806 function enrichInv(L, a, b) {
12807 let C = Math.sqrt(a * a + b * b);
12808 if (C < 1e-12) {
12809 return [a, b];
12810 }
12811 let gate = enrichGate(L);
12812 if (gate < 1e-12) {
12813 return [a, b];
12814 }
12815 let hTarget = Math.atan2(b, a);
12816 let sig2 = ENR_SIGMA * ENR_SIGMA;
12817 let ag = ENR_AMP * gate;
12818 let h = hTarget;
12819 for (let i = 0; i < 8; i++) {
12820 let dh = h - ENR_CENTER;
12821 dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI;
12822 let gauss = Math.exp(-0.5 * dh * dh / sig2);
12823 let F = h + ag * gauss - hTarget;
12824 let Fp = 1 + ag * gauss * (-dh / sig2);
12825 let Fpp = ag * gauss * (-1 / sig2 + dh * dh / (sig2 * sig2));
12826 let den = 2 * Fp * Fp - F * Fpp;
12827 if (Math.abs(den) > 1e-30) {
12828 h -= 2 * F * Fp / den;
12829 }
12830 }
12831 return [C * Math.cos(h), C * Math.sin(h)];
12832 }
12833
12834 // ── PW L correction ───────────────────────────────────────────────
12835
12836 function pwLForward(L) {
12837 if (L <= 0 || L >= 1) {
12838 return L;
12839 }
12840 let lo = 0,
12841 hi = PW_N - 1;
12842 while (hi - lo > 1) {
12843 let mid = lo + hi >> 1;
12844 if (PW_L_IN[mid] <= L) {
12845 lo = mid;
12846 } else {
12847 hi = mid;
12848 }
12849 }
12850 let t = (L - PW_L_IN[lo]) / (PW_L_IN[hi] - PW_L_IN[lo]);
12851 return PW_L_OUT[lo] + t * (PW_L_OUT[hi] - PW_L_OUT[lo]);
12852 }
12853 function pwLInverse(L) {
12854 if (L <= PW_L_OUT[0] || L >= PW_L_OUT[PW_N - 1]) {
12855 return L;
12856 }
12857 let lo = 0,
12858 hi = PW_N - 1;
12859 while (hi - lo > 1) {
12860 let mid = lo + hi >> 1;
12861 if (PW_L_OUT[mid] <= L) {
12862 lo = mid;
12863 } else {
12864 hi = mid;
12865 }
12866 }
12867 let t = (L - PW_L_OUT[lo]) / (PW_L_OUT[hi] - PW_L_OUT[lo]);
12868 return PW_L_IN[lo] + t * (PW_L_IN[hi] - PW_L_IN[lo]);
12869 }
12870
12871 // ── Color space definition ─────────────────────────────────────────
12872
12873 var HelmGen = new ColorSpace({
12874 id: "helmgen",
12875 name: "HelmGen",
12876 cssId: "--helmgen",
12877 coords: {
12878 l: {
12879 refRange: [0, 1],
12880 name: "Lightness"
12881 },
12882 a: {
12883 refRange: [-0.6, 0.6]
12884 },
12885 b: {
12886 refRange: [-0.6, 0.6]
12887 }
12888 },
12889 white: "D65",
12890 base: XYZ_D65,
12891 M: M$1,
12892 fromBase(xyz) {
12893 // Stage 1: XYZ → LMS (M1)
12894 let lms = multiply_v3_m3x3(xyz, M$1.M1);
12895
12896 // Stage 2: Depressed cubic transfer (y³ + αy = x)
12897 let c0 = depcubicFwd(Math.max(lms[0], 0));
12898 let c1 = depcubicFwd(Math.max(lms[1], 0));
12899 let c2 = depcubicFwd(Math.max(lms[2], 0));
12900
12901 // Stage 2.5: Smooth neutral blend (C∞ correction for achromatic precision)
12902 {
12903 let mean = (c0 + c1 + c2) / 3;
12904 let mx = Math.max(c0, c1, c2);
12905 let mn = Math.min(c0, c1, c2);
12906 let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30);
12907 let w = Math.exp(-((spread / 1e-5) ** 2));
12908 c0 += w * (mean - c0);
12909 c1 += w * (mean - c1);
12910 c2 += w * (mean - c2);
12911 }
12912
12913 // Stage 3: LMS_c → Lab (M2)
12914 let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M$1.M2);
12915
12916 // Stage 3.5: Chroma power (cp=0.978)
12917 {
12918 let C = Math.sqrt(a * a + b * b);
12919 if (C > 1e-12) {
12920 let Cnew = Math.pow(C, CP);
12921 let s = Cnew / C;
12922 a *= s;
12923 b *= s;
12924 }
12925 }
12926
12927 // Stage 4: Piecewise-linear L correction
12928 L = pwLForward(L);
12929
12930 // Stage 5: L-gated hue enrichment
12931 [a, b] = enrichFwd(L, a, b);
12932 return [L, a, b];
12933 },
12934 toBase(lab) {
12935 let [L, a, b] = lab;
12936
12937 // Undo Stage 5: L-gated hue enrichment
12938 [a, b] = enrichInv(L, a, b);
12939
12940 // Undo Stage 4: PW L correction
12941 L = pwLInverse(L);
12942
12943 // Undo Stage 3.5: Chroma power inverse (C^(1/cp))
12944 {
12945 let C = Math.sqrt(a * a + b * b);
12946 if (C > 1e-12) {
12947 let Corig = Math.pow(C, 1 / CP);
12948 let s = Corig / C;
12949 a *= s;
12950 b *= s;
12951 }
12952 }
12953
12954 // Undo Stage 3: Lab → LMS_c (M2_inv)
12955 let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M$1.M2_INV);
12956
12957 // Undo Stage 2.5: Smooth neutral blend
12958 {
12959 let mean = (lc0 + lc1 + lc2) / 3;
12960 let mx = Math.max(lc0, lc1, lc2);
12961 let mn = Math.min(lc0, lc1, lc2);
12962 let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30);
12963 let w = Math.exp(-((spread / 1e-5) ** 2));
12964 lc0 += w * (mean - lc0);
12965 lc1 += w * (mean - lc1);
12966 lc2 += w * (mean - lc2);
12967 }
12968
12969 // Undo Stage 2: Inverse depressed cubic (x = y³ + αy)
12970 let l0 = depcubicInv(lc0);
12971 let l1 = depcubicInv(lc1);
12972 let l2 = depcubicInv(lc2);
12973
12974 // Undo Stage 1: LMS → XYZ (M1_inv)
12975 return multiply_v3_m3x3([l0, l1, l2], M$1.M1_INV);
12976 }
12977 });
12978
12979 /**
12980 * HelmGenLCh — cylindrical form of Helmlab GenSpace.
12981 *
12982 * Converts GenSpace's rectangular (L, a, b) coordinates to
12983 * cylindrical (L, C, h). Ideal for CSS interpolation contexts
12984 * like gradients and color-mix where hue angle matters.
12985 *
12986 * @see https://github.com/Grkmyldz148/helmlab
12987 */
12988 var helmgenlch = new ColorSpace({
12989 id: "helmgenlch",
12990 name: "HelmGenLCh",
12991 cssId: "--helmgenlch",
12992 coords: {
12993 l: {
12994 refRange: [0, 1],
12995 name: "Lightness"
12996 },
12997 c: {
12998 refRange: [0, 0.65],
12999 name: "Chroma"
13000 },
13001 h: {
13002 refRange: [0, 360],
13003 type: "angle",
13004 name: "Hue"
13005 }
13006 },
13007 white: "D65",
13008 base: HelmGen,
13009 fromBase: lch.fromBase,
13010 toBase: lch.toBase
13011 });
13012
13013 var REC_2100_Linear = new RGBColorSpace({
13014 id: "rec2100-linear",
13015 name: "Linear REC.2100",
13016 white: "D65",
13017 M: M$8
13018 });
13019
13020 const Yw = 203; // absolute luminance of media white, cd/m²
13021 const n = 2610 / 2 ** 14;
13022 const ninv = 2 ** 14 / 2610;
13023 const m = 2523 / 2 ** 5;
13024 const minv = 2 ** 5 / 2523;
13025 const c1 = 3424 / 2 ** 12;
13026 const c2 = 2413 / 2 ** 7;
13027 const c3 = 2392 / 2 ** 7;
13028 var rec2100Pq = new RGBColorSpace({
13029 id: "rec2100pq",
13030 cssId: "rec2100-pq",
13031 name: "REC.2100-PQ",
13032 base: REC_2100_Linear,
13033 linearGamut: REC_2100_Linear,
13034 toBase(RGB) {
13035 // given PQ encoded component in range [0, 1]
13036 // return media-white relative linear-light
13037 return RGB.map(function (val) {
13038 let x = (Math.max(val ** minv - c1, 0) / (c2 - c3 * val ** minv)) ** ninv;
13039 return x * 10000 / Yw; // luminance relative to diffuse white, [0, 70 or so].
13040 });
13041 },
13042 fromBase(RGB) {
13043 // given media-white relative linear-light
13044 // returnPQ encoded component in range [0, 1]
13045 return RGB.map(function (val) {
13046 let x = Math.max(val * Yw / 10000, 0); // absolute luminance of peak white is 10,000 cd/m².
13047 let num = c1 + c2 * x ** n;
13048 let denom = 1 + c3 * x ** n;
13049 return (num / denom) ** m;
13050 });
13051 }
13052 });
13053
13054 const a = 0.17883277;
13055 const b = 0.28466892; // 1 - (4 * a)
13056 const c = 0.55991073; // 0.5 - a * Math.log(4 *a)
13057
13058 const scale = 3.7743; // Place 18% grey at HLG 0.38, so media white at 0.75
13059
13060 var rec2100Hlg = new RGBColorSpace({
13061 id: "rec2100hlg",
13062 cssId: "rec2100-hlg",
13063 name: "REC.2100-HLG",
13064 referred: "scene",
13065 base: REC_2100_Linear,
13066 linearGamut: REC_2100_Linear,
13067 toBase(RGB) {
13068 // given HLG encoded component in range [0, 1]
13069 // return media-white relative linear-light
13070 return RGB.map(function (val) {
13071 // first the HLG EOTF
13072 // ITU-R BT.2390-10 p.30 section
13073 // 6.3 The hybrid log-gamma electro-optical transfer function (EOTF)
13074 // Then scale by 3 so media white is 1.0
13075 if (val <= 0.5) {
13076 return val ** 2 / 3 * scale;
13077 }
13078 return (Math.exp((val - c) / a) + b) / 12 * scale;
13079 });
13080 },
13081 fromBase(RGB) {
13082 // given media-white relative linear-light
13083 // where diffuse white is 1.0,
13084 // return HLG encoded component in range [0, 1]
13085 return RGB.map(function (val) {
13086 // first scale to put linear-light media white at 1/3
13087 val /= scale;
13088 // now the HLG OETF
13089 // ITU-R BT.2390-10 p.23
13090 // 6.1 The hybrid log-gamma opto-electronic transfer function (OETF)
13091 if (val <= 1 / 12) {
13092 return spow(3 * val, 0.5);
13093 }
13094 return a * Math.log(12 * val - b) + c;
13095 });
13096 }
13097 });
13098
13099 /** @import { White } from "./types.js" */
13100
13101 // Type re-exports
13102 /** @typedef {import("./types.js").CAT} CAT */
13103
13104 /** @type {Record<string, CAT>} */
13105 const CATs = {};
13106 hooks.add("chromatic-adaptation-start", env => {
13107 if (env.options.method) {
13108 env.M = adapt(env.W1, env.W2, env.options.method);
13109 }
13110 });
13111 hooks.add("chromatic-adaptation-end", env => {
13112 if (!env.M) {
13113 env.M = adapt(env.W1, env.W2, env.options.method);
13114 }
13115 });
13116 function defineCAT(/** @type {CAT} */{
13117 id,
13118 toCone_M,
13119 fromCone_M
13120 }) {
13121 // Use id, toCone_M, fromCone_M like variables
13122 CATs[id] = arguments[0];
13123 }
13124
13125 /**
13126 *
13127 * @param {White} W1
13128 * @param {White} W2
13129 * @param {string} id
13130 * @returns {number[][]}
13131 */
13132 function adapt(W1, W2, id = "Bradford") {
13133 // adapt from a source whitepoint or illuminant W1
13134 // to a destination whitepoint or illuminant W2,
13135 // using the given chromatic adaptation transform (CAT)
13136 // debugger;
13137 let method = CATs[id];
13138 let [ρs, γs, βs] = multiplyMatrices(method.toCone_M, W1);
13139 let [ρd, γd, βd] = multiplyMatrices(method.toCone_M, W2);
13140
13141 // all practical illuminants have non-zero XYZ so no division by zero can occur below
13142 // prettier-ignore
13143 let scale = [[ρd / ρs, 0, 0], [0, γd / γs, 0], [0, 0, βd / βs]];
13144 // console.log({scale});
13145
13146 let scaled_cone_M = multiplyMatrices(scale, method.toCone_M);
13147 let adapt_M = multiplyMatrices(method.fromCone_M, scaled_cone_M);
13148 // console.log({scaled_cone_M, adapt_M});
13149 return adapt_M;
13150 }
13151
13152 // prettier-ignore
13153 defineCAT({
13154 id: "von Kries",
13155 toCone_M: [[0.4002400, 0.7076000, -0.0808100], [-0.2263000, 1.1653200, 0.0457000], [0.0000000, 0.0000000, 0.9182200]],
13156 fromCone_M: [[1.8599363874558397, -1.1293816185800916, 0.21989740959619328], [0.3611914362417676, 0.6388124632850422, -0.000006370596838649899], [0, 0, 1.0890636230968613]]
13157 });
13158
13159 // prettier-ignore
13160 defineCAT({
13161 id: "Bradford",
13162 // Convert an array of XYZ values in the range 0.0 - 1.0
13163 // to cone fundamentals
13164 toCone_M: [[0.8951000, 0.2664000, -0.1614000], [-0.7502000, 1.7135000, 0.0367000], [0.0389000, -0.0685000, 1.0296000]],
13165 // and back
13166 fromCone_M: [[0.9869929054667121, -0.14705425642099013, 0.15996265166373122], [0.4323052697233945, 0.5183602715367774, 0.049291228212855594], [-0.00852866457517732, 0.04004282165408486, 0.96848669578755]]
13167 });
13168
13169 // prettier-ignore
13170 defineCAT({
13171 id: "CAT02",
13172 // with complete chromatic adaptation to W2, so D = 1.0
13173 toCone_M: [[0.7328000, 0.4296000, -0.1624000], [-0.7036000, 1.6975000, 0.0061000], [0.0030000, 0.0136000, 0.9834000]],
13174 fromCone_M: [[1.0961238208355142, -0.27886900021828726, 0.18274517938277307], [0.4543690419753592, 0.4735331543074117, 0.07209780371722911], [-0.009627608738429355, -0.00569803121611342, 1.0153256399545427]]
13175 });
13176
13177 // prettier-ignore
13178 defineCAT({
13179 id: "CAT16",
13180 toCone_M: [[0.401288, 0.650173, -0.051461], [-0.250268, 1.204414, 0.045854], [-0.002079, 0.048952, 0.953127]],
13181 // the extra precision is needed to avoid roundtripping errors
13182 fromCone_M: [[1.862067855087233, -1.0112546305316845, 0.14918677544445172], [0.3875265432361372, 0.6214474419314753, -0.008973985167612521], [-0.01584149884933386, -0.03412293802851557, 1.0499644368778496]]
13183 });
13184
13185 // prettier-ignore
13186 Object.assign(WHITES, {
13187 // whitepoint values from ASTM E308-01 with 10nm spacing, 1931 2 degree observer
13188 // all normalized to Y (luminance) = 1.00000
13189 // Illuminant A is a tungsten electric light, giving a very warm, orange light.
13190 A: [1.09850, 1.00000, 0.35585],
13191 // Illuminant C was an early approximation to daylight: illuminant A with a blue filter.
13192 C: [0.98074, 1.000000, 1.18232],
13193 // The daylight series of illuminants simulate natural daylight.
13194 // The color temperature (in degrees Kelvin/100) ranges from
13195 // cool, overcast daylight (D50) to bright, direct sunlight (D65).
13196 D55: [0.95682, 1.00000, 0.92149],
13197 D75: [0.94972, 1.00000, 1.22638],
13198 // Equal-energy illuminant, used in two-stage CAT16
13199 E: [1.00000, 1.00000, 1.00000],
13200 // The F series of illuminants represent fluorescent lights
13201 F2: [0.99186, 1.00000, 0.67393],
13202 F7: [0.95041, 1.00000, 1.08747],
13203 F11: [1.00962, 1.00000, 0.64350]
13204 });
13205
13206 /** @import { Matrix3x3 } from "../types.js" */
13207
13208 // The ACES whitepoint
13209 // see TB-2018-001 Derivation of the ACES White Point CIE Chromaticity Coordinates
13210 // also https://github.com/ampas/aces-dev/blob/master/documents/python/TB-2018-001/aces_wp.py
13211 // Similar to D60
13212 WHITES.ACES = [0.32168 / 0.33767, 1.0, (1.0 - 0.32168 - 0.33767) / 0.33767];
13213
13214 /**
13215 * Matrices used by this color space, also available as `ACEScg.M`
13216 * @type {Record<string, Matrix3x3>}
13217 */
13218 // prettier-ignore
13219 const M = {
13220 // convert an array of linear-light ACEScg values to CIE XYZ
13221 toXYZ: [[0.6624541811085053, 0.13400420645643313, 0.1561876870049078], [0.27222871678091454, 0.6740817658111484, 0.05368951740793705], [-0.005574649490394108, 0.004060733528982826, 1.0103391003129971]],
13222 fromXYZ: [[1.6410233796943257, -0.32480329418479, -0.23642469523761225], [-0.6636628587229829, 1.6153315916573379, 0.016756347685530137], [0.011721894328375376, -0.008284441996237409, 0.9883948585390215]]
13223 };
13224 var ACEScg = new RGBColorSpace({
13225 id: "acescg",
13226 cssId: "--acescg",
13227 name: "ACEScg",
13228 // ACEScg – A scene-referred, linear-light encoding of ACES Data
13229 // https://docs.acescentral.com/specifications/acescg/
13230 // uses the AP1 primaries, see section 4.3.1 Color primaries
13231 coords: {
13232 r: {
13233 range: [0, 65504],
13234 name: "Red"
13235 },
13236 g: {
13237 range: [0, 65504],
13238 name: "Green"
13239 },
13240 b: {
13241 range: [0, 65504],
13242 name: "Blue"
13243 }
13244 },
13245 referred: "scene",
13246 white: WHITES.ACES,
13247 M
13248 });
13249
13250 // export default Color;
13251
13252 const ε = 2 ** -16;
13253
13254 // the smallest value which, in the 32bit IEEE 754 float encoding,
13255 // decodes as a non-negative value
13256 const ACES_min_nonzero = -0.35828683;
13257
13258 // brightest encoded value, decodes to 65504
13259 const ACES_cc_max = (Math.log2(65504) + 9.72) / 17.52; // 1.468
13260
13261 var acescc = new RGBColorSpace({
13262 id: "acescc",
13263 cssId: "--acescc",
13264 name: "ACEScc",
13265 // see S-2014-003 ACEScc – A Logarithmic Encoding of ACES Data
13266 // https://docs.acescentral.com/specifications/acescc/
13267 // uses the AP1 primaries, see section 4.3.1 Color primaries
13268
13269 // Appendix A: "Very small ACES scene referred values below 7 1/4 stops
13270 // below 18% middle gray are encoded as negative ACEScc values.
13271 // These values should be preserved per the encoding in Section 4.4
13272 // so that all positive ACES values are maintained."
13273 coords: {
13274 r: {
13275 range: [ACES_min_nonzero, ACES_cc_max],
13276 name: "Red"
13277 },
13278 g: {
13279 range: [ACES_min_nonzero, ACES_cc_max],
13280 name: "Green"
13281 },
13282 b: {
13283 range: [ACES_min_nonzero, ACES_cc_max],
13284 name: "Blue"
13285 }
13286 },
13287 referred: "scene",
13288 base: ACEScg,
13289 linearGamut: ACEScg,
13290 // from section 4.4.2 Decoding Function
13291 toBase(RGB) {
13292 const low = (9.72 - 15) / 17.52; // -0.3014
13293
13294 return RGB.map(function (val) {
13295 if (val <= low) {
13296 return (2 ** (val * 17.52 - 9.72) - ε) * 2; // very low values, below -0.3014
13297 } else if (val < ACES_cc_max) {
13298 return 2 ** (val * 17.52 - 9.72);
13299 } else {
13300 // val >= ACES_cc_max
13301 return 65504;
13302 }
13303 });
13304 },
13305 // Non-linear encoding function from S-2014-003, section 4.4.1 Encoding Function
13306 fromBase(RGB) {
13307 return RGB.map(function (val) {
13308 if (val <= 0) {
13309 return (Math.log2(ε) + 9.72) / 17.52; // -0.3584
13310 } else if (val < ε) {
13311 return (Math.log2(ε + val * 0.5) + 9.72) / 17.52;
13312 } else {
13313 // val >= ε
13314 return (Math.log2(val) + 9.72) / 17.52;
13315 }
13316 });
13317 }
13318 // encoded media white (rgb 1,1,1) => linear [ 222.861, 222.861, 222.861 ]
13319 // encoded media black (rgb 0,0,0) => linear [ 0.0011857, 0.0011857, 0.0011857]
13320 });
13321
13322 /**
13323 * @packageDocumentation
13324 * Re-exports all the spaces built into Color.js.
13325 */
13326
13327 var spaces = /*#__PURE__*/Object.freeze({
13328 __proto__: null,
13329 A98RGB: a98rgb,
13330 A98RGB_Linear: A98Linear,
13331 ACEScc: acescc,
13332 ACEScg: ACEScg,
13333 CAM16_JMh: cam16,
13334 HCT: hct,
13335 HPLuv: HPLuv,
13336 HSL: HSL,
13337 HSL_P3: hslP3,
13338 HSL_REC2020: hslRec2020,
13339 HSLuv: hsluv,
13340 HSV: HSV,
13341 HWB: hwb,
13342 HelmGen: HelmGen,
13343 HelmGenLCh: helmgenlch,
13344 Helmlab: helmlab,
13345 ICTCP: ictcp,
13346 JzCzHz: jzczhz,
13347 Jzazbz: Jzazbz,
13348 LCH: lch,
13349 LCH_P3: lchP3,
13350 LCH_REC_2020: lchRec2020,
13351 LCH_sRGB: lchSrgb,
13352 LCHuv: LCHuv,
13353 Lab: lab,
13354 Lab_D65: lab_d65,
13355 Luv: Luv,
13356 OKLCH: OKLCH,
13357 OKLCH_P3: oklchP3,
13358 OKLCH_REC_2020: oklchRec2020,
13359 OKLCH_sRGB: oklchSrgb,
13360 OKLab: Oklab,
13361 OKLrCH: oklrch,
13362 OKLrab: OKLrab,
13363 Okhsl: Okhsl,
13364 Okhsv: Okhsv,
13365 P3: P3,
13366 P3_Linear: P3Linear,
13367 ProPhoto: prophoto,
13368 ProPhoto_Linear: ProPhotoLinear,
13369 REC_2020: REC2020,
13370 REC_2020_Linear: REC2020Linear,
13371 REC_2020_Scene_Referred: rec2020Oetf,
13372 REC_2100_HLG: rec2100Hlg,
13373 REC_2100_Linear: REC_2100_Linear,
13374 REC_2100_PQ: rec2100Pq,
13375 XYZ_ABS_D65: XYZ_Abs_D65,
13376 XYZ_D50: XYZ_D50,
13377 XYZ_D65: XYZ_D65,
13378 sRGB: sRGB,
13379 sRGB_Linear: sRGBLinear
13380 });
13381
13382 class Color {
13383 /**
13384 * Creates an instance of Color.
13385 * Signatures:
13386 * - `new Color(stringToParse)`
13387 * - `new Color(otherColor)`
13388 * - `new Color({space, coords, alpha})`
13389 * - `new Color(space, coords, alpha)`
13390 * - `new Color(spaceId, coords, alpha)`
13391 */
13392 constructor(...args) {
13393 let color;
13394 if (args.length === 1) {
13395 let parseMeta = {};
13396 // Clone simple objects to avoid mutating original in getColor
13397 if (typeof args[0] === "object" && Object.getPrototypeOf(args[0]).constructor === Object) {
13398 args[0] = {
13399 ...args[0]
13400 };
13401 }
13402 color = getColor(args[0], {
13403 parseMeta
13404 });
13405 if (parseMeta.format) {
13406 // Color actually came from a string
13407 this.parseMeta = parseMeta;
13408 }
13409 }
13410 let space, coords, alpha;
13411 if (color) {
13412 space = color.space || color.spaceId;
13413 coords = color.coords;
13414 alpha = color.alpha;
13415 } else {
13416 // default signature new Color(ColorSpace, array [, alpha])
13417 [space, coords, alpha] = args;
13418 }
13419 Object.defineProperty(this, "space", {
13420 value: ColorSpace.get(space),
13421 writable: false,
13422 enumerable: true,
13423 configurable: true // see note in https://262.ecma-international.org/8.0/#sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver
13424 });
13425 this.coords = coords ? coords.slice() : [0, 0, 0];
13426
13427 // Clamp alpha to [0, 1]
13428 this.alpha = isNone(alpha) ? alpha : alpha === undefined ? 1 : clamp(0, alpha, 1);
13429
13430 // Define getters and setters for each coordinate
13431 for (let id in this.space.coords) {
13432 Object.defineProperty(this, id, {
13433 get: () => this.get(id),
13434 set: value => this.set(id, value)
13435 });
13436 }
13437 }
13438 get spaceId() {
13439 return this.space.id;
13440 }
13441 clone() {
13442 return new Color(this.space, this.coords, this.alpha);
13443 }
13444 toJSON() {
13445 return {
13446 spaceId: this.spaceId,
13447 coords: this.coords,
13448 alpha: this.alpha
13449 };
13450 }
13451 display(...args) {
13452 let ret = display(this, ...args);
13453
13454 // Convert color object to Color instance
13455 ret.color = new Color(ret.color);
13456 return ret;
13457 }
13458
13459 /**
13460 * Get a color from the argument(s) passed
13461 * Basically gets us the same result as new Color(color) but doesn't clone an existing color object
13462 */
13463 static get(color, ...args) {
13464 if (isInstance(color, this)) {
13465 return color;
13466 }
13467 return new Color(color, ...args);
13468 }
13469
13470 /**
13471 * Get a color instance from the argument passed or `null` if resolution fails (instead of throwing an error).
13472 * Additionally, it supports passing an element to resolve complex CSS colors through the DOM (slow).
13473 * @see {@link tryColor} for more details
13474 */
13475 static try(color, options) {
13476 if (isInstance(color, this)) {
13477 return color;
13478 }
13479 let ret = tryColor(color, options);
13480 if (ret) {
13481 return new Color(ret);
13482 }
13483 return null;
13484 }
13485 static defineFunction(name, code, o = code) {
13486 let {
13487 instance = true,
13488 returns
13489 } = o;
13490 let func = function (...args) {
13491 let ret = code(...args);
13492 if (returns === "color") {
13493 ret = Color.get(ret);
13494 } else if (returns === "function<color>") {
13495 let f = ret;
13496 ret = function (...args) {
13497 let ret = f(...args);
13498 return Color.get(ret);
13499 };
13500 // Copy any function metadata
13501 Object.assign(ret, f);
13502 } else if (returns === "array<color>") {
13503 ret = ret.map(c => Color.get(c));
13504 }
13505 return ret;
13506 };
13507 if (!(name in Color)) {
13508 Color[name] = func;
13509 }
13510 if (instance) {
13511 Color.prototype[name] = function (...args) {
13512 return func(this, ...args);
13513 };
13514 }
13515 }
13516 static defineFunctions(o) {
13517 for (let name in o) {
13518 Color.defineFunction(name, o[name], o[name]);
13519 }
13520 }
13521 static extend(exports) {
13522 if (exports.register) {
13523 exports.register(Color);
13524 } else {
13525 // No register method, just add the module's functions
13526 for (let name in exports) {
13527 Color.defineFunction(name, exports[name]);
13528 }
13529 }
13530 }
13531 }
13532 Color.defineFunctions({
13533 get,
13534 getAll,
13535 set,
13536 setAll,
13537 to,
13538 equals,
13539 inGamut,
13540 toGamut,
13541 distance,
13542 deltas,
13543 toString: serialize
13544 });
13545 Object.assign(Color, {
13546 util,
13547 hooks,
13548 WHITES,
13549 Space: ColorSpace,
13550 spaces: ColorSpace.registry,
13551 parse,
13552 // Global defaults one may want to configure
13553 defaults
13554 });
13555
13556 /**
13557 * @packageDocumentation
13558 * This module contains {@link spaces a namespace} with all the spaces built into Color.js.
13559 */
13560 for (let key of Object.keys(spaces)) {
13561 ColorSpace.register(spaces[key]);
13562 }
13563
13564 // Add space accessors to existing color spaces
13565 for (let id in ColorSpace.registry) {
13566 addSpaceAccessors(id, ColorSpace.registry[id]);
13567 }
13568
13569 // Add space accessors to color spaces not yet created
13570 hooks.add("colorspace-init-end", space => {
13571 var _space$aliases;
13572 addSpaceAccessors(space.id, space);
13573 (_space$aliases = space.aliases) === null || _space$aliases === void 0 || _space$aliases.forEach(alias => {
13574 addSpaceAccessors(alias, space);
13575 });
13576 });
13577 function addSpaceAccessors(id, space) {
13578 let propId = id.replace(/-/g, "_");
13579 Object.defineProperty(Color.prototype, propId, {
13580 // Convert coords to coords in another colorspace and return them
13581 // Source colorspace: this.spaceId
13582 // Target colorspace: id
13583 get() {
13584 let ret = this.getAll(id);
13585 if (typeof Proxy === "undefined") {
13586 // If proxies are not supported, just return a static array
13587 return ret;
13588 }
13589
13590 // Enable color.spaceId.coordName syntax
13591 let proxy = new Proxy(ret, {
13592 has: /** @param {string} property */(obj, property) => {
13593 try {
13594 ColorSpace.resolveCoord([space, property]);
13595 return true;
13596 } catch (e) {}
13597 return Reflect.has(obj, property);
13598 },
13599 get: (obj, property, receiver) => {
13600 if (property && typeof property !== "symbol" && !(property in obj) && property in proxy) {
13601 let {
13602 index
13603 } = ColorSpace.resolveCoord([space, property]);
13604 if (index >= 0) {
13605 return obj[index];
13606 }
13607 }
13608 return Reflect.get(obj, property, receiver);
13609 },
13610 set: (obj, property, value, receiver) => {
13611 if (property && typeof property !== "symbol" && !(property in obj) || Number(property) >= 0) {
13612 let {
13613 index
13614 } = ColorSpace.resolveCoord([space, (/** @type {string} */property)]);
13615 if (index >= 0) {
13616 obj[index] = value;
13617
13618 // Update color.coords
13619 this.setAll(id, obj);
13620 return true;
13621 }
13622 }
13623 return Reflect.set(obj, property, value, receiver);
13624 }
13625 });
13626 return proxy;
13627 },
13628 // Convert coords in another colorspace to internal coords and set them
13629 // Target colorspace: this.spaceId
13630 // Source colorspace: id
13631 set(coords) {
13632 this.setAll(id, coords);
13633 },
13634 configurable: true,
13635 enumerable: true
13636 });
13637 }
13638
13639 /**
13640 * Entry point for the OOP flavor of the API
13641 * Import as `colorjs.io`
13642 */
13643 Color.extend(deltaEMethods);
13644 Color.extend({
13645 deltaE
13646 });
13647 Object.assign(Color, {
13648 deltaEMethods
13649 });
13650 Color.extend(variations);
13651 Color.extend({
13652 contrast
13653 });
13654 Color.extend(chromaticity);
13655 Color.extend(luminance);
13656 Color.extend(interpolation);
13657 Color.extend(contrastMethods);
13658
13659 exports.default = Color;
13660 //# sourceMappingURL=color.legacy.cjs.map