colorino 0.13.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1015 +0,0 @@
1
- 'use strict';
2
-
3
- function hexToRgb(hex) {
4
- const match = hex.toString().match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
5
- if (!match) {
6
- return [0, 0, 0];
7
- }
8
- let colorString = match[0];
9
- if (match[0].length === 3) {
10
- colorString = [...colorString].map((char) => char + char).join("");
11
- }
12
- const integer = parseInt(colorString, 16);
13
- const r = integer >> 16 & 255;
14
- const g = integer >> 8 & 255;
15
- const b = integer & 255;
16
- return [r, g, b];
17
- }
18
- function rgbToAnsi256(rgb) {
19
- const [r, g, b] = rgb;
20
- if (r === g && g === b) {
21
- if (r < 8) return 16;
22
- if (r > 248) return 231;
23
- return Math.round((r - 8) / 247 * 24) + 232;
24
- }
25
- return 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
26
- }
27
- function rgbToHsvValue(rgb) {
28
- const r = rgb[0] / 255;
29
- const g = rgb[1] / 255;
30
- const b = rgb[2] / 255;
31
- const v = Math.max(r, g, b);
32
- return v * 100;
33
- }
34
- function rgbToAnsi16(rgb) {
35
- const [r, g, b] = rgb;
36
- const value = rgbToHsvValue(rgb);
37
- const roundedValue = Math.round(value / 50);
38
- if (roundedValue === 0) {
39
- return 30;
40
- }
41
- let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
42
- if (roundedValue === 2) {
43
- ansi += 60;
44
- }
45
- return ansi;
46
- }
47
- const colorConverter = {
48
- hex: {
49
- toRgb: hexToRgb,
50
- toAnsi16: (hex) => rgbToAnsi16(hexToRgb(hex)),
51
- toAnsi256: (hex) => rgbToAnsi256(hexToRgb(hex))
52
- }};
53
-
54
- var ColorLevel = /* @__PURE__ */ ((ColorLevel2) => {
55
- ColorLevel2[ColorLevel2["NO_COLOR"] = 0] = "NO_COLOR";
56
- ColorLevel2[ColorLevel2["ANSI"] = 1] = "ANSI";
57
- ColorLevel2[ColorLevel2["ANSI256"] = 2] = "ANSI256";
58
- ColorLevel2[ColorLevel2["TRUECOLOR"] = 3] = "TRUECOLOR";
59
- return ColorLevel2;
60
- })(ColorLevel || {});
61
-
62
- function isConsoleMethod(level) {
63
- return ["log", "info", "warn", "error", "trace", "debug"].includes(level);
64
- }
65
- const ColorinoBrowserColorized = Symbol("colorino.browserColorized");
66
- const ColorinoBrowserObject = Symbol("colorino.browserObject");
67
-
68
- const catppuccinMochaPalette = {
69
- log: "#cdd6f4",
70
- // Text
71
- info: "#89b4fa",
72
- // Blue
73
- warn: "#f9e2af",
74
- // Yellow
75
- error: "#f38ba8",
76
- // Red
77
- debug: "#a6adc8",
78
- // Subtext0
79
- trace: "#9399b2"
80
- // Subtext1
81
- };
82
- const catppuccinLattePalette = {
83
- log: "#4c4f69",
84
- // Text
85
- info: "#1e66f5",
86
- // Blue
87
- warn: "#df8e1d",
88
- // Yellow
89
- error: "#d20f39",
90
- // Red
91
- debug: "#7c7f93",
92
- // Subtext0
93
- trace: "#8c8fa1"
94
- // Subtext1
95
- };
96
- const draculaPalette = {
97
- log: "#f8f8f2",
98
- // Foreground
99
- info: "#8be9fd",
100
- // Cyan
101
- warn: "#f1fa8c",
102
- // Yellow
103
- error: "#ff5555",
104
- // Red
105
- debug: "#bd93f9",
106
- // Purple
107
- trace: "#6272a4"
108
- // Comment
109
- };
110
- const githubLightPalette = {
111
- log: "#24292e",
112
- // Text
113
- info: "#0366d6",
114
- // Blue
115
- warn: "#f9a002",
116
- // Yellow
117
- error: "#d73a49",
118
- // Red
119
- debug: "#586069",
120
- // Gray
121
- trace: "#6a737d"
122
- // Gray-light
123
- };
124
-
125
- const themePalettes = {
126
- "catppuccin-mocha": catppuccinMochaPalette,
127
- "catppuccin-latte": catppuccinLattePalette,
128
- dracula: draculaPalette,
129
- "github-light": githubLightPalette
130
- };
131
- const defaultDarkTheme = "dracula";
132
- const defaultLightTheme = "github-light";
133
- function isThemeName(theme) {
134
- return theme in themePalettes;
135
- }
136
-
137
- function determineBaseTheme(themeOpt, detectedBrowserTheme) {
138
- let baseThemeName;
139
- if (isThemeName(themeOpt)) {
140
- baseThemeName = themeOpt;
141
- } else if (themeOpt === "light") {
142
- baseThemeName = defaultLightTheme;
143
- } else if (themeOpt === "dark") {
144
- baseThemeName = defaultDarkTheme;
145
- } else {
146
- baseThemeName = detectedBrowserTheme === "light" ? defaultLightTheme : defaultDarkTheme;
147
- }
148
- return baseThemeName;
149
- }
150
-
151
- class TypeValidator {
152
- static isNull(value) {
153
- return value === null;
154
- }
155
- static isObject(value) {
156
- return typeof value === "object" && value !== null;
157
- }
158
- static isString(value) {
159
- return typeof value === "string";
160
- }
161
- static isError(value) {
162
- return value instanceof Error;
163
- }
164
- static isBrowserColorizedArg(value) {
165
- return typeof value === "object" && value !== null && ColorinoBrowserColorized in value;
166
- }
167
- static isBrowserObjectArg(value) {
168
- return typeof value === "object" && value !== null && ColorinoBrowserObject in value;
169
- }
170
- static isAnsiColoredString(value) {
171
- return TypeValidator.isString(value) && /\x1b\[[0-9;]*m/.test(value);
172
- }
173
- static isFormattableObject(value) {
174
- return TypeValidator.isObject(value) && !TypeValidator.isError(value) && !TypeValidator.isBrowserColorizedArg(value);
175
- }
176
- }
177
-
178
- class MyColorino {
179
- constructor(initialPalette, _userPalette, _validator, _browserColorSupportDetector, _nodeColorSupportDetector, _options = {}) {
180
- this._userPalette = _userPalette;
181
- this._validator = _validator;
182
- this._browserColorSupportDetector = _browserColorSupportDetector;
183
- this._nodeColorSupportDetector = _nodeColorSupportDetector;
184
- this._options = _options;
185
- this._palette = initialPalette;
186
- this.isBrowser = !!this._browserColorSupportDetector;
187
- this._colorLevel = this._detectColorSupport();
188
- const validatePaletteResult = this._validator.validatePalette(this._palette);
189
- if (validatePaletteResult.isErr()) throw validatePaletteResult.error;
190
- if (this._colorLevel !== ColorLevel.NO_COLOR && !this._options.disableWarnings && this._colorLevel === "UnknownEnv") {
191
- this._maybeWarnUser();
192
- }
193
- const themeOpt = this._options.theme ?? "auto";
194
- if (themeOpt === "auto" && this._nodeColorSupportDetector) {
195
- this._nodeColorSupportDetector.onTheme((resolvedTheme) => {
196
- this._applyResolvedTheme(resolvedTheme);
197
- });
198
- }
199
- }
200
- _alreadyWarned = false;
201
- _colorLevel;
202
- isBrowser;
203
- _palette;
204
- log(...args) {
205
- this._out("log", args);
206
- }
207
- info(...args) {
208
- this._out("info", args);
209
- }
210
- warn(...args) {
211
- this._out("warn", args);
212
- }
213
- error(...args) {
214
- this._out("error", args);
215
- }
216
- trace(...args) {
217
- this._out("trace", args);
218
- }
219
- debug(...args) {
220
- this._out("debug", args);
221
- }
222
- colorize(text, hex) {
223
- if (this._colorLevel === ColorLevel.NO_COLOR || this._colorLevel === "UnknownEnv") {
224
- return text;
225
- }
226
- if (this.isBrowser) {
227
- return {
228
- [ColorinoBrowserColorized]: true,
229
- text,
230
- hex
231
- };
232
- }
233
- const ansiPrefix = this._toAnsiPrefix(hex);
234
- if (!ansiPrefix) {
235
- return text;
236
- }
237
- return `${ansiPrefix}${text}\x1B[0m`;
238
- }
239
- _isAnsiColoredString(value) {
240
- return typeof value === "string" && /\x1b\[[0-9;]*m/.test(value);
241
- }
242
- _applyResolvedTheme(resolvedTheme) {
243
- const themeOpt = this._options.theme ?? "auto";
244
- const baseThemeName = determineBaseTheme(themeOpt, resolvedTheme);
245
- const basePalette = themePalettes[baseThemeName];
246
- this._palette = { ...basePalette, ...this._userPalette };
247
- }
248
- _detectColorSupport() {
249
- if (this.isBrowser) {
250
- return this._browserColorSupportDetector?.getColorLevel() ?? "UnknownEnv";
251
- }
252
- if (this._nodeColorSupportDetector?.isNodeEnv()) {
253
- return this._nodeColorSupportDetector?.getColorLevel() ?? "UnknownEnv";
254
- }
255
- return "UnknownEnv";
256
- }
257
- _maybeWarnUser() {
258
- if (this._alreadyWarned) return;
259
- this._alreadyWarned = true;
260
- console.warn(
261
- "No ANSI color support detected in this terminal. See [https://github.com/chalk/supports-color#support-matrix](https://github.com/chalk/supports-color#support-matrix) to learn how to enable terminal color."
262
- );
263
- }
264
- _formatValue(value, maxDepth = this._options.maxDepth ?? 5) {
265
- const seen = /* @__PURE__ */ new WeakSet();
266
- const sanitize = (val, currentDepth) => {
267
- if (val == null || typeof val !== "object") return val;
268
- if (seen.has(val)) return "[Circular]";
269
- seen.add(val);
270
- if (currentDepth >= maxDepth) return "[Object]";
271
- if (Array.isArray(val)) {
272
- return val.map((item) => sanitize(item, currentDepth + 1));
273
- }
274
- const result = {};
275
- for (const key in val) {
276
- result[key] = sanitize(
277
- val[key],
278
- currentDepth + 1
279
- );
280
- }
281
- return result;
282
- };
283
- return JSON.stringify(sanitize(value, 0), null, 2);
284
- }
285
- _normalizeString(value) {
286
- if (value instanceof String) return value.valueOf();
287
- return value;
288
- }
289
- _processArgs(args) {
290
- const processedArgs = [];
291
- let previousWasObject = false;
292
- for (const rawArg of args) {
293
- const arg = this._normalizeString(rawArg);
294
- if (TypeValidator.isBrowserColorizedArg(arg)) {
295
- processedArgs.push(arg);
296
- previousWasObject = false;
297
- continue;
298
- }
299
- if (TypeValidator.isFormattableObject(arg)) {
300
- if (this.isBrowser) {
301
- processedArgs.push({
302
- [ColorinoBrowserObject]: true,
303
- value: arg
304
- });
305
- } else {
306
- processedArgs.push(`
307
- ${this._formatValue(arg)}`);
308
- }
309
- previousWasObject = true;
310
- } else if (TypeValidator.isError(arg)) {
311
- processedArgs.push("\n", this._cleanErrorStack(arg));
312
- previousWasObject = true;
313
- } else {
314
- if (TypeValidator.isString(arg) && previousWasObject) {
315
- processedArgs.push(`
316
- ${arg}`);
317
- } else {
318
- processedArgs.push(arg);
319
- }
320
- previousWasObject = false;
321
- }
322
- }
323
- return processedArgs;
324
- }
325
- _applyBrowserColors(consoleMethod, args) {
326
- const formatParts = [];
327
- const cssArgs = [];
328
- const otherArgs = [];
329
- const paletteHex = this._palette[consoleMethod];
330
- for (const rawArg of args) {
331
- const arg = this._normalizeString(rawArg);
332
- if (TypeValidator.isBrowserColorizedArg(arg)) {
333
- formatParts.push(`%c${arg.text}`);
334
- cssArgs.push(`color:${arg.hex}`);
335
- continue;
336
- }
337
- if (TypeValidator.isBrowserObjectArg(arg)) {
338
- formatParts.push("%o");
339
- otherArgs.push(arg.value);
340
- continue;
341
- }
342
- if (TypeValidator.isString(arg)) {
343
- formatParts.push(`%c${arg}`);
344
- cssArgs.push(`color:${paletteHex}`);
345
- continue;
346
- }
347
- formatParts.push("%o");
348
- otherArgs.push(arg);
349
- }
350
- if (formatParts.length === 0) {
351
- return args;
352
- }
353
- return [formatParts.join(""), ...cssArgs, ...otherArgs];
354
- }
355
- _toAnsiPrefix(hex) {
356
- if (this._colorLevel === ColorLevel.NO_COLOR || this._colorLevel === "UnknownEnv") {
357
- return "";
358
- }
359
- switch (this._colorLevel) {
360
- case ColorLevel.TRUECOLOR: {
361
- const [r, g, b] = colorConverter.hex.toRgb(hex);
362
- return `\x1B[38;2;${r};${g};${b}m`;
363
- }
364
- case ColorLevel.ANSI256: {
365
- const code = colorConverter.hex.toAnsi256(hex);
366
- return `\x1B[38;5;${code}m`;
367
- }
368
- case ColorLevel.ANSI:
369
- default: {
370
- const code = colorConverter.hex.toAnsi16(hex);
371
- return `\x1B[${code}m`;
372
- }
373
- }
374
- }
375
- _applyNodeColors(consoleMethod, args) {
376
- const coloredArgs = [...args];
377
- const firstStringIndex = coloredArgs.findIndex(
378
- (arg) => typeof arg === "string"
379
- );
380
- if (firstStringIndex === -1) {
381
- return coloredArgs;
382
- }
383
- const first = coloredArgs[firstStringIndex];
384
- if (this._isAnsiColoredString(first)) {
385
- return coloredArgs;
386
- }
387
- const hex = this._palette[consoleMethod];
388
- const ansiPrefix = this._toAnsiPrefix(hex);
389
- if (!ansiPrefix) {
390
- return coloredArgs;
391
- }
392
- coloredArgs[firstStringIndex] = `${ansiPrefix}${String(first)}\x1B[0m`;
393
- return coloredArgs;
394
- }
395
- _output(consoleMethod, args) {
396
- if (consoleMethod === "trace") this._printCleanTrace(args);
397
- else console[consoleMethod](...args);
398
- }
399
- _out(level, args) {
400
- const consoleMethod = isConsoleMethod(level) ? level : "log";
401
- const processedArgs = this._processArgs(args);
402
- if (this._colorLevel === ColorLevel.NO_COLOR || this._colorLevel === "UnknownEnv") {
403
- this._output(consoleMethod, processedArgs);
404
- return;
405
- }
406
- if (this.isBrowser) {
407
- const coloredArgs2 = this._applyBrowserColors(consoleMethod, processedArgs);
408
- this._output(consoleMethod, coloredArgs2);
409
- return;
410
- }
411
- const coloredArgs = this._applyNodeColors(consoleMethod, processedArgs);
412
- this._output(consoleMethod, coloredArgs);
413
- }
414
- _filterStack(stack) {
415
- return stack.split("\n").filter((line) => !line.match(/.*colorino.*/gi)).join("\n");
416
- }
417
- _cleanErrorStack(error) {
418
- if (!error.stack) return error;
419
- const cleanStack = this._filterStack(error.stack);
420
- const cloned = Object.create(Object.getPrototypeOf(error));
421
- Object.assign(cloned, error);
422
- cloned.stack = cleanStack;
423
- return cloned;
424
- }
425
- _printCleanTrace(args) {
426
- const error = new Error();
427
- if (error.stack) {
428
- const cleanStack = this._filterStack(error.stack);
429
- console.log(...args, `
430
- ${cleanStack}`);
431
- } else {
432
- console.log(...args);
433
- }
434
- }
435
- }
436
-
437
- const defaultErrorConfig = {
438
- withStackTrace: false,
439
- };
440
- // Custom error object
441
- // Context / discussion: https://github.com/supermacro/neverthrow/pull/215
442
- const createNeverThrowError = (message, result, config = defaultErrorConfig) => {
443
- const data = result.isOk()
444
- ? { type: 'Ok', value: result.value }
445
- : { type: 'Err', value: result.error };
446
- const maybeStack = config.withStackTrace ? new Error().stack : undefined;
447
- return {
448
- data,
449
- message,
450
- stack: maybeStack,
451
- };
452
- };
453
-
454
- /******************************************************************************
455
- Copyright (c) Microsoft Corporation.
456
-
457
- Permission to use, copy, modify, and/or distribute this software for any
458
- purpose with or without fee is hereby granted.
459
-
460
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
461
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
462
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
463
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
464
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
465
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
466
- PERFORMANCE OF THIS SOFTWARE.
467
- ***************************************************************************** */
468
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
469
-
470
-
471
- function __awaiter(thisArg, _arguments, P, generator) {
472
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
473
- return new (P || (P = Promise))(function (resolve, reject) {
474
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
475
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
476
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
477
- step((generator = generator.apply(thisArg, [])).next());
478
- });
479
- }
480
-
481
- function __values(o) {
482
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
483
- if (m) return m.call(o);
484
- if (o && typeof o.length === "number") return {
485
- next: function () {
486
- if (o && i >= o.length) o = void 0;
487
- return { value: o && o[i++], done: !o };
488
- }
489
- };
490
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
491
- }
492
-
493
- function __await(v) {
494
- return this instanceof __await ? (this.v = v, this) : new __await(v);
495
- }
496
-
497
- function __asyncGenerator(thisArg, _arguments, generator) {
498
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
499
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
500
- return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
501
- function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
502
- function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
503
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
504
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
505
- function fulfill(value) { resume("next", value); }
506
- function reject(value) { resume("throw", value); }
507
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
508
- }
509
-
510
- function __asyncDelegator(o) {
511
- var i, p;
512
- return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
513
- function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
514
- }
515
-
516
- function __asyncValues(o) {
517
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
518
- var m = o[Symbol.asyncIterator], i;
519
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
520
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
521
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
522
- }
523
-
524
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
525
- var e = new Error(message);
526
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
527
- };
528
-
529
- class ResultAsync {
530
- constructor(res) {
531
- this._promise = res;
532
- }
533
- static fromSafePromise(promise) {
534
- const newPromise = promise.then((value) => new Ok(value));
535
- return new ResultAsync(newPromise);
536
- }
537
- static fromPromise(promise, errorFn) {
538
- const newPromise = promise
539
- .then((value) => new Ok(value))
540
- .catch((e) => new Err(errorFn(e)));
541
- return new ResultAsync(newPromise);
542
- }
543
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
544
- static fromThrowable(fn, errorFn) {
545
- return (...args) => {
546
- return new ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
547
- try {
548
- return new Ok(yield fn(...args));
549
- }
550
- catch (error) {
551
- return new Err(errorFn ? errorFn(error) : error);
552
- }
553
- }))());
554
- };
555
- }
556
- static combine(asyncResultList) {
557
- return combineResultAsyncList(asyncResultList);
558
- }
559
- static combineWithAllErrors(asyncResultList) {
560
- return combineResultAsyncListWithAllErrors(asyncResultList);
561
- }
562
- map(f) {
563
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
564
- if (res.isErr()) {
565
- return new Err(res.error);
566
- }
567
- return new Ok(yield f(res.value));
568
- })));
569
- }
570
- andThrough(f) {
571
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
572
- if (res.isErr()) {
573
- return new Err(res.error);
574
- }
575
- const newRes = yield f(res.value);
576
- if (newRes.isErr()) {
577
- return new Err(newRes.error);
578
- }
579
- return new Ok(res.value);
580
- })));
581
- }
582
- andTee(f) {
583
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
584
- if (res.isErr()) {
585
- return new Err(res.error);
586
- }
587
- try {
588
- yield f(res.value);
589
- }
590
- catch (e) {
591
- // Tee does not care about the error
592
- }
593
- return new Ok(res.value);
594
- })));
595
- }
596
- orTee(f) {
597
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
598
- if (res.isOk()) {
599
- return new Ok(res.value);
600
- }
601
- try {
602
- yield f(res.error);
603
- }
604
- catch (e) {
605
- // Tee does not care about the error
606
- }
607
- return new Err(res.error);
608
- })));
609
- }
610
- mapErr(f) {
611
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
612
- if (res.isOk()) {
613
- return new Ok(res.value);
614
- }
615
- return new Err(yield f(res.error));
616
- })));
617
- }
618
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
619
- andThen(f) {
620
- return new ResultAsync(this._promise.then((res) => {
621
- if (res.isErr()) {
622
- return new Err(res.error);
623
- }
624
- const newValue = f(res.value);
625
- return newValue instanceof ResultAsync ? newValue._promise : newValue;
626
- }));
627
- }
628
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
629
- orElse(f) {
630
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
631
- if (res.isErr()) {
632
- return f(res.error);
633
- }
634
- return new Ok(res.value);
635
- })));
636
- }
637
- match(ok, _err) {
638
- return this._promise.then((res) => res.match(ok, _err));
639
- }
640
- unwrapOr(t) {
641
- return this._promise.then((res) => res.unwrapOr(t));
642
- }
643
- /**
644
- * @deprecated will be removed in 9.0.0.
645
- *
646
- * You can use `safeTry` without this method.
647
- * @example
648
- * ```typescript
649
- * safeTry(async function* () {
650
- * const okValue = yield* yourResult
651
- * })
652
- * ```
653
- * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
654
- */
655
- safeUnwrap() {
656
- return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
657
- return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
658
- });
659
- }
660
- // Makes ResultAsync implement PromiseLike<Result>
661
- then(successCallback, failureCallback) {
662
- return this._promise.then(successCallback, failureCallback);
663
- }
664
- [Symbol.asyncIterator]() {
665
- return __asyncGenerator(this, arguments, function* _a() {
666
- const result = yield __await(this._promise);
667
- if (result.isErr()) {
668
- // @ts-expect-error -- This is structurally equivalent and safe
669
- yield yield __await(errAsync(result.error));
670
- }
671
- // @ts-expect-error -- This is structurally equivalent and safe
672
- return yield __await(result.value);
673
- });
674
- }
675
- }
676
- function errAsync(err) {
677
- return new ResultAsync(Promise.resolve(new Err(err)));
678
- }
679
-
680
- /**
681
- * Short circuits on the FIRST Err value that we find
682
- */
683
- const combineResultList = (resultList) => {
684
- let acc = ok([]);
685
- for (const result of resultList) {
686
- if (result.isErr()) {
687
- acc = err(result.error);
688
- break;
689
- }
690
- else {
691
- acc.map((list) => list.push(result.value));
692
- }
693
- }
694
- return acc;
695
- };
696
- /* This is the typesafe version of Promise.all
697
- *
698
- * Takes a list of ResultAsync<T, E> and success if all inner results are Ok values
699
- * or fails if one (or more) of the inner results are Err values
700
- */
701
- const combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
702
- /**
703
- * Give a list of all the errors we find
704
- */
705
- const combineResultListWithAllErrors = (resultList) => {
706
- let acc = ok([]);
707
- for (const result of resultList) {
708
- if (result.isErr() && acc.isErr()) {
709
- acc.error.push(result.error);
710
- }
711
- else if (result.isErr() && acc.isOk()) {
712
- acc = err([result.error]);
713
- }
714
- else if (result.isOk() && acc.isOk()) {
715
- acc.value.push(result.value);
716
- }
717
- // do nothing when result.isOk() && acc.isErr()
718
- }
719
- return acc;
720
- };
721
- const combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
722
-
723
- // eslint-disable-next-line @typescript-eslint/no-namespace
724
- var Result;
725
- (function (Result) {
726
- /**
727
- * Wraps a function with a try catch, creating a new function with the same
728
- * arguments but returning `Ok` if successful, `Err` if the function throws
729
- *
730
- * @param fn function to wrap with ok on success or err on failure
731
- * @param errorFn when an error is thrown, this will wrap the error result if provided
732
- */
733
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
734
- function fromThrowable(fn, errorFn) {
735
- return (...args) => {
736
- try {
737
- const result = fn(...args);
738
- return ok(result);
739
- }
740
- catch (e) {
741
- return err(errorFn ? errorFn(e) : e);
742
- }
743
- };
744
- }
745
- Result.fromThrowable = fromThrowable;
746
- function combine(resultList) {
747
- return combineResultList(resultList);
748
- }
749
- Result.combine = combine;
750
- function combineWithAllErrors(resultList) {
751
- return combineResultListWithAllErrors(resultList);
752
- }
753
- Result.combineWithAllErrors = combineWithAllErrors;
754
- })(Result || (Result = {}));
755
- function ok(value) {
756
- return new Ok(value);
757
- }
758
- function err(err) {
759
- return new Err(err);
760
- }
761
- class Ok {
762
- constructor(value) {
763
- this.value = value;
764
- }
765
- isOk() {
766
- return true;
767
- }
768
- isErr() {
769
- return !this.isOk();
770
- }
771
- map(f) {
772
- return ok(f(this.value));
773
- }
774
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
775
- mapErr(_f) {
776
- return ok(this.value);
777
- }
778
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
779
- andThen(f) {
780
- return f(this.value);
781
- }
782
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
783
- andThrough(f) {
784
- return f(this.value).map((_value) => this.value);
785
- }
786
- andTee(f) {
787
- try {
788
- f(this.value);
789
- }
790
- catch (e) {
791
- // Tee doesn't care about the error
792
- }
793
- return ok(this.value);
794
- }
795
- orTee(_f) {
796
- return ok(this.value);
797
- }
798
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
799
- orElse(_f) {
800
- return ok(this.value);
801
- }
802
- asyncAndThen(f) {
803
- return f(this.value);
804
- }
805
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
806
- asyncAndThrough(f) {
807
- return f(this.value).map(() => this.value);
808
- }
809
- asyncMap(f) {
810
- return ResultAsync.fromSafePromise(f(this.value));
811
- }
812
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
813
- unwrapOr(_v) {
814
- return this.value;
815
- }
816
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
817
- match(ok, _err) {
818
- return ok(this.value);
819
- }
820
- safeUnwrap() {
821
- const value = this.value;
822
- /* eslint-disable-next-line require-yield */
823
- return (function* () {
824
- return value;
825
- })();
826
- }
827
- _unsafeUnwrap(_) {
828
- return this.value;
829
- }
830
- _unsafeUnwrapErr(config) {
831
- throw createNeverThrowError('Called `_unsafeUnwrapErr` on an Ok', this, config);
832
- }
833
- // eslint-disable-next-line @typescript-eslint/no-this-alias, require-yield
834
- *[Symbol.iterator]() {
835
- return this.value;
836
- }
837
- }
838
- class Err {
839
- constructor(error) {
840
- this.error = error;
841
- }
842
- isOk() {
843
- return false;
844
- }
845
- isErr() {
846
- return !this.isOk();
847
- }
848
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
849
- map(_f) {
850
- return err(this.error);
851
- }
852
- mapErr(f) {
853
- return err(f(this.error));
854
- }
855
- andThrough(_f) {
856
- return err(this.error);
857
- }
858
- andTee(_f) {
859
- return err(this.error);
860
- }
861
- orTee(f) {
862
- try {
863
- f(this.error);
864
- }
865
- catch (e) {
866
- // Tee doesn't care about the error
867
- }
868
- return err(this.error);
869
- }
870
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
871
- andThen(_f) {
872
- return err(this.error);
873
- }
874
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
875
- orElse(f) {
876
- return f(this.error);
877
- }
878
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
879
- asyncAndThen(_f) {
880
- return errAsync(this.error);
881
- }
882
- asyncAndThrough(_f) {
883
- return errAsync(this.error);
884
- }
885
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
886
- asyncMap(_f) {
887
- return errAsync(this.error);
888
- }
889
- unwrapOr(v) {
890
- return v;
891
- }
892
- match(_ok, err) {
893
- return err(this.error);
894
- }
895
- safeUnwrap() {
896
- const error = this.error;
897
- return (function* () {
898
- yield err(error);
899
- throw new Error('Do not use this generator out of `safeTry`');
900
- })();
901
- }
902
- _unsafeUnwrap(config) {
903
- throw createNeverThrowError('Called `_unsafeUnwrap` on an Err', this, config);
904
- }
905
- _unsafeUnwrapErr(_) {
906
- return this.error;
907
- }
908
- *[Symbol.iterator]() {
909
- // eslint-disable-next-line @typescript-eslint/no-this-alias
910
- const self = this;
911
- // @ts-expect-error -- This is structurally equivalent and safe
912
- yield self;
913
- // @ts-expect-error -- This is structurally equivalent and safe
914
- return self;
915
- }
916
- }
917
- Result.fromThrowable;
918
-
919
- class InputValidationError extends Error {
920
- constructor(message) {
921
- super(message);
922
- this.name = "InputValidationError";
923
- Object.setPrototypeOf(this, InputValidationError.prototype);
924
- }
925
- }
926
-
927
- class InputValidator {
928
- validateHex(hex) {
929
- const trimmedHex = hex.trim();
930
- const isHexValid = /^#[0-9A-F]{6}$/i.test(trimmedHex);
931
- if (!isHexValid) {
932
- return err(new InputValidationError(`Invalid hex color: '${hex}'`));
933
- }
934
- return ok(true);
935
- }
936
- validatePalette(palette) {
937
- for (const level in palette) {
938
- const hex = palette[level];
939
- const result = this.validateHex(hex);
940
- if (result.isErr()) {
941
- return err(result.error);
942
- }
943
- }
944
- return ok(true);
945
- }
946
- }
947
-
948
- class BrowserColorSupportDetector {
949
- constructor(_window, _navigator, _overrideTheme) {
950
- this._window = _window;
951
- this._navigator = _navigator;
952
- this._overrideTheme = _overrideTheme;
953
- }
954
- isBrowserEnv() {
955
- return !!this._window && !!this._navigator?.userAgent;
956
- }
957
- getColorLevel() {
958
- if (!this.isBrowserEnv()) {
959
- return ColorLevel.NO_COLOR;
960
- }
961
- const userAgent = this._navigator.userAgent.toLowerCase();
962
- if (userAgent.includes("chrome")) return ColorLevel.ANSI256;
963
- if (userAgent.includes("firefox")) return ColorLevel.ANSI256;
964
- return ColorLevel.ANSI256;
965
- }
966
- getTheme() {
967
- if (this._overrideTheme) {
968
- return this._overrideTheme;
969
- }
970
- if (!this.isBrowserEnv() || typeof this._window.matchMedia !== "function") {
971
- return "unknown";
972
- }
973
- if (this._window.matchMedia("(prefers-color-scheme: dark)").matches) {
974
- return "dark";
975
- }
976
- if (this._window.matchMedia("(prefers-color-scheme: light)").matches) {
977
- return "light";
978
- }
979
- return "unknown";
980
- }
981
- }
982
-
983
- function createColorino(userPalette = {}, options = {}) {
984
- const validator = new InputValidator();
985
- let detectorThemeOverride;
986
- if (options.theme === "dark" || options.theme === "light") {
987
- detectorThemeOverride = options.theme;
988
- }
989
- const browserDetector = new BrowserColorSupportDetector(
990
- window,
991
- navigator,
992
- detectorThemeOverride
993
- );
994
- const detectedBrowserTheme = browserDetector.getTheme();
995
- const themeOpt = options.theme ?? "auto";
996
- const baseThemeName = determineBaseTheme(
997
- themeOpt,
998
- detectedBrowserTheme
999
- );
1000
- const basePalette = themePalettes[baseThemeName];
1001
- const finalPalette = { ...basePalette, ...userPalette };
1002
- return new MyColorino(
1003
- finalPalette,
1004
- userPalette,
1005
- validator,
1006
- browserDetector,
1007
- void 0,
1008
- options
1009
- );
1010
- }
1011
- const colorino = createColorino();
1012
-
1013
- exports.colorino = colorino;
1014
- exports.createColorino = createColorino;
1015
- exports.themePalettes = themePalettes;