@isikk/core 0.1.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.
@@ -0,0 +1,79 @@
1
+ declare const getKeys: <T extends object>(obj: T) => Array<keyof T>;
2
+ type RecursivePartial<T> = {
3
+ [P in keyof T]?: RecursivePartial<T[P]>;
4
+ };
5
+ type RecursiveRecord = {
6
+ [key: string]: string | number | boolean | RecursiveRecord | Array<RecursiveRecord>;
7
+ };
8
+ declare function forcedType<T>(obj: unknown): T;
9
+
10
+ declare function notNone<T>(value: T | null | undefined): value is T;
11
+ declare function allCombinations<T>(options: T[]): T[][];
12
+
13
+ declare function withAttributes<Fn extends (...args: never[]) => unknown, Attrs extends Record<string, unknown>>(fn: Fn, attributes: Attrs): Fn & Attrs;
14
+ declare function makeCallable<T, R>(originalCallable: (arg: T) => R): (data: T) => () => R;
15
+ declare function getLazyValue<T>(input: T | (() => T)): T;
16
+ declare function getLazyValueAsync<T>(input: T | (() => Promise<T>) | (() => T)): Promise<T>;
17
+ declare function suppress<T, ERT>(exceptions: Array<new (message?: string) => Error>, fn: () => T, onError?: (error: unknown) => ERT): T | ERT | undefined;
18
+ declare function preventDefault<E extends Event, R>(callable: (event: E) => R): (event: E) => Promise<Awaited<R>>;
19
+ declare function isPathMatched(pathname: string, pattern: RegExp, exemptPatterns?: RegExp[]): boolean;
20
+ declare function raises(error: Error): (...args: unknown[]) => never;
21
+ declare function cloned<Fn extends (...args: never[]) => unknown>(fn: Fn): Fn;
22
+ declare function enabledIf<R>(condition: boolean | (() => boolean), options: {
23
+ ifNotEnabledReturnValue: R;
24
+ }): <Fn extends (...args: never[]) => R>(fn: Fn) => Fn;
25
+ declare function transformExceptions<E extends Error>(exceptionTypes: Array<new (...args: never[]) => E>, transform: (error: E) => Error, options?: {
26
+ keepOriginal?: boolean;
27
+ }): <Fn extends (...args: never[]) => unknown>(fn: Fn) => Fn;
28
+
29
+ declare function checkRequiredKeys<T extends Record<string, unknown>, C extends Record<string, Array<keyof T>>>(obj: T, conditions: C): keyof C;
30
+ declare function requireExclusiveKeys<T extends Record<string, unknown>, C extends Record<string, Array<keyof T>>>(conditions: C, options?: {
31
+ allowEmpty?: boolean;
32
+ }): <Fn extends (arg: T) => unknown>(fn: Fn) => Fn;
33
+ declare function setKeyValueToObjectIfValue(key: string, value: unknown, object: Record<string, unknown>): void;
34
+
35
+ declare function slugify(value: string, allowUnicode?: boolean): string;
36
+
37
+ declare const LONG_DATE_FORMAT = "EEEE, MMMM dd, yyyy 'at' hh:mm a";
38
+ declare const SHORT_DATE_FORMAT = "dd.MM.yyyy";
39
+ declare const SHORT_DATETIME_FORMAT = "dd.MM.yyyy HH:mm a";
40
+ declare function formattedDate(pattern: string, date?: Date): string;
41
+ declare function longFormattedDate(date?: Date): string;
42
+ declare function shortFormattedDate(date?: Date): string;
43
+ declare function shortFormattedDateTime(date?: Date): string;
44
+ declare function optionalDate(date?: string): Date | undefined;
45
+
46
+ type MimeType = 'image/png' | 'image/jpeg' | 'image/webp';
47
+ declare function guessImageMimeType(filename: string): MimeType;
48
+ declare function isImageMimeType(mimeType: string): mimeType is MimeType;
49
+ declare function escapeName(name: string): string;
50
+ declare function safeFileName(filename: string, maxLength?: number): string;
51
+ declare function downloadAndFormatImage(src: string, name?: string, mimeType?: MimeType, quality?: number): Promise<void>;
52
+ declare function fileToBase64Native(file: File): Promise<string>;
53
+ declare function fileToBase64(file: File, quality?: number): Promise<string>;
54
+
55
+ declare function getCookie(name: string): string | undefined;
56
+
57
+ type WindowLike = Window & typeof globalThis;
58
+ declare function createConsoleDebugSwitch(targetWindow: WindowLike, options: {
59
+ namespace: string;
60
+ }): void;
61
+
62
+ type TailwindShade = 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 950;
63
+ type TailwindColorScale = Record<TailwindShade, string>;
64
+ /**
65
+ * Generates a Tailwind-style 50-950 color scale from a single base hex color, treated as the 500 shade.
66
+ */
67
+ declare function generateTailwindColorScale(baseColor: string): TailwindColorScale;
68
+ /**
69
+ * Like {@link generateTailwindColorScale}, but prefixes each shade with `name` (e.g. `primary500`)
70
+ * so multiple scales can be spread into one flat palette object.
71
+ */
72
+ declare function generateNamedTailwindColorScale<T extends string>(baseColor: string, name: T): Record<`${T}${TailwindShade}`, string>;
73
+ /**
74
+ * Formats a hex color as the "H S% L%" triplet shadcn/Tailwind CSS variable themes expect,
75
+ * e.g. for `--primary: 240 5.9% 10%;` consumed as `hsl(var(--primary))`.
76
+ */
77
+ declare function hexToHslTriplet(hex: string, precision?: number): string;
78
+
79
+ export { LONG_DATE_FORMAT, type RecursivePartial, type RecursiveRecord, SHORT_DATETIME_FORMAT, SHORT_DATE_FORMAT, type TailwindColorScale, type TailwindShade, allCombinations, checkRequiredKeys, cloned, createConsoleDebugSwitch, downloadAndFormatImage, enabledIf, escapeName, fileToBase64, fileToBase64Native, forcedType, formattedDate, generateNamedTailwindColorScale, generateTailwindColorScale, getCookie, getKeys, getLazyValue, getLazyValueAsync, guessImageMimeType, hexToHslTriplet, isImageMimeType, isPathMatched, longFormattedDate, makeCallable, notNone, optionalDate, preventDefault, raises, requireExclusiveKeys, safeFileName, setKeyValueToObjectIfValue, shortFormattedDate, shortFormattedDateTime, slugify, suppress, transformExceptions, withAttributes };
@@ -0,0 +1,79 @@
1
+ declare const getKeys: <T extends object>(obj: T) => Array<keyof T>;
2
+ type RecursivePartial<T> = {
3
+ [P in keyof T]?: RecursivePartial<T[P]>;
4
+ };
5
+ type RecursiveRecord = {
6
+ [key: string]: string | number | boolean | RecursiveRecord | Array<RecursiveRecord>;
7
+ };
8
+ declare function forcedType<T>(obj: unknown): T;
9
+
10
+ declare function notNone<T>(value: T | null | undefined): value is T;
11
+ declare function allCombinations<T>(options: T[]): T[][];
12
+
13
+ declare function withAttributes<Fn extends (...args: never[]) => unknown, Attrs extends Record<string, unknown>>(fn: Fn, attributes: Attrs): Fn & Attrs;
14
+ declare function makeCallable<T, R>(originalCallable: (arg: T) => R): (data: T) => () => R;
15
+ declare function getLazyValue<T>(input: T | (() => T)): T;
16
+ declare function getLazyValueAsync<T>(input: T | (() => Promise<T>) | (() => T)): Promise<T>;
17
+ declare function suppress<T, ERT>(exceptions: Array<new (message?: string) => Error>, fn: () => T, onError?: (error: unknown) => ERT): T | ERT | undefined;
18
+ declare function preventDefault<E extends Event, R>(callable: (event: E) => R): (event: E) => Promise<Awaited<R>>;
19
+ declare function isPathMatched(pathname: string, pattern: RegExp, exemptPatterns?: RegExp[]): boolean;
20
+ declare function raises(error: Error): (...args: unknown[]) => never;
21
+ declare function cloned<Fn extends (...args: never[]) => unknown>(fn: Fn): Fn;
22
+ declare function enabledIf<R>(condition: boolean | (() => boolean), options: {
23
+ ifNotEnabledReturnValue: R;
24
+ }): <Fn extends (...args: never[]) => R>(fn: Fn) => Fn;
25
+ declare function transformExceptions<E extends Error>(exceptionTypes: Array<new (...args: never[]) => E>, transform: (error: E) => Error, options?: {
26
+ keepOriginal?: boolean;
27
+ }): <Fn extends (...args: never[]) => unknown>(fn: Fn) => Fn;
28
+
29
+ declare function checkRequiredKeys<T extends Record<string, unknown>, C extends Record<string, Array<keyof T>>>(obj: T, conditions: C): keyof C;
30
+ declare function requireExclusiveKeys<T extends Record<string, unknown>, C extends Record<string, Array<keyof T>>>(conditions: C, options?: {
31
+ allowEmpty?: boolean;
32
+ }): <Fn extends (arg: T) => unknown>(fn: Fn) => Fn;
33
+ declare function setKeyValueToObjectIfValue(key: string, value: unknown, object: Record<string, unknown>): void;
34
+
35
+ declare function slugify(value: string, allowUnicode?: boolean): string;
36
+
37
+ declare const LONG_DATE_FORMAT = "EEEE, MMMM dd, yyyy 'at' hh:mm a";
38
+ declare const SHORT_DATE_FORMAT = "dd.MM.yyyy";
39
+ declare const SHORT_DATETIME_FORMAT = "dd.MM.yyyy HH:mm a";
40
+ declare function formattedDate(pattern: string, date?: Date): string;
41
+ declare function longFormattedDate(date?: Date): string;
42
+ declare function shortFormattedDate(date?: Date): string;
43
+ declare function shortFormattedDateTime(date?: Date): string;
44
+ declare function optionalDate(date?: string): Date | undefined;
45
+
46
+ type MimeType = 'image/png' | 'image/jpeg' | 'image/webp';
47
+ declare function guessImageMimeType(filename: string): MimeType;
48
+ declare function isImageMimeType(mimeType: string): mimeType is MimeType;
49
+ declare function escapeName(name: string): string;
50
+ declare function safeFileName(filename: string, maxLength?: number): string;
51
+ declare function downloadAndFormatImage(src: string, name?: string, mimeType?: MimeType, quality?: number): Promise<void>;
52
+ declare function fileToBase64Native(file: File): Promise<string>;
53
+ declare function fileToBase64(file: File, quality?: number): Promise<string>;
54
+
55
+ declare function getCookie(name: string): string | undefined;
56
+
57
+ type WindowLike = Window & typeof globalThis;
58
+ declare function createConsoleDebugSwitch(targetWindow: WindowLike, options: {
59
+ namespace: string;
60
+ }): void;
61
+
62
+ type TailwindShade = 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 950;
63
+ type TailwindColorScale = Record<TailwindShade, string>;
64
+ /**
65
+ * Generates a Tailwind-style 50-950 color scale from a single base hex color, treated as the 500 shade.
66
+ */
67
+ declare function generateTailwindColorScale(baseColor: string): TailwindColorScale;
68
+ /**
69
+ * Like {@link generateTailwindColorScale}, but prefixes each shade with `name` (e.g. `primary500`)
70
+ * so multiple scales can be spread into one flat palette object.
71
+ */
72
+ declare function generateNamedTailwindColorScale<T extends string>(baseColor: string, name: T): Record<`${T}${TailwindShade}`, string>;
73
+ /**
74
+ * Formats a hex color as the "H S% L%" triplet shadcn/Tailwind CSS variable themes expect,
75
+ * e.g. for `--primary: 240 5.9% 10%;` consumed as `hsl(var(--primary))`.
76
+ */
77
+ declare function hexToHslTriplet(hex: string, precision?: number): string;
78
+
79
+ export { LONG_DATE_FORMAT, type RecursivePartial, type RecursiveRecord, SHORT_DATETIME_FORMAT, SHORT_DATE_FORMAT, type TailwindColorScale, type TailwindShade, allCombinations, checkRequiredKeys, cloned, createConsoleDebugSwitch, downloadAndFormatImage, enabledIf, escapeName, fileToBase64, fileToBase64Native, forcedType, formattedDate, generateNamedTailwindColorScale, generateTailwindColorScale, getCookie, getKeys, getLazyValue, getLazyValueAsync, guessImageMimeType, hexToHslTriplet, isImageMimeType, isPathMatched, longFormattedDate, makeCallable, notNone, optionalDate, preventDefault, raises, requireExclusiveKeys, safeFileName, setKeyValueToObjectIfValue, shortFormattedDate, shortFormattedDateTime, slugify, suppress, transformExceptions, withAttributes };
package/dist/index.js ADDED
@@ -0,0 +1,490 @@
1
+ // src/types/index.ts
2
+ var getKeys = Object.keys;
3
+ function forcedType(obj) {
4
+ return obj;
5
+ }
6
+
7
+ // src/arrays/index.ts
8
+ function notNone(value) {
9
+ return value !== null && value !== void 0;
10
+ }
11
+ function combinationsOfSize(items, size) {
12
+ if (size === 0) {
13
+ return [[]];
14
+ }
15
+ if (size > items.length) {
16
+ return [];
17
+ }
18
+ const [first, ...rest] = items;
19
+ const withFirst = combinationsOfSize(rest, size - 1).map((combination) => [first, ...combination]);
20
+ const withoutFirst = combinationsOfSize(rest, size);
21
+ return [...withFirst, ...withoutFirst];
22
+ }
23
+ function allCombinations(options) {
24
+ const result = [];
25
+ for (let size = 1; size <= options.length; size++) {
26
+ result.push(...combinationsOfSize(options, size));
27
+ }
28
+ return result;
29
+ }
30
+
31
+ // src/functions/index.ts
32
+ function withAttributes(fn, attributes) {
33
+ for (const key of Object.keys(attributes)) {
34
+ Object.defineProperty(fn, key, {
35
+ value: attributes[key],
36
+ writable: true,
37
+ configurable: true,
38
+ enumerable: true
39
+ });
40
+ }
41
+ return fn;
42
+ }
43
+ function makeCallable(originalCallable) {
44
+ return (data) => () => originalCallable(data);
45
+ }
46
+ function getLazyValue(input) {
47
+ if (typeof input === "function") {
48
+ return input();
49
+ }
50
+ return input;
51
+ }
52
+ async function getLazyValueAsync(input) {
53
+ if (typeof input === "function") {
54
+ const result = input();
55
+ if (result instanceof Promise) {
56
+ return await result;
57
+ }
58
+ return result;
59
+ }
60
+ return input;
61
+ }
62
+ function suppress(exceptions, fn, onError) {
63
+ try {
64
+ return fn();
65
+ } catch (error) {
66
+ if (exceptions.some((exception) => error instanceof exception)) {
67
+ return onError ? onError(error) : void 0;
68
+ }
69
+ throw error;
70
+ }
71
+ }
72
+ function preventDefault(callable) {
73
+ return async function(event) {
74
+ event.preventDefault();
75
+ return await callable(event);
76
+ };
77
+ }
78
+ function isPathMatched(pathname, pattern, exemptPatterns = []) {
79
+ if (exemptPatterns.some((exempt) => exempt.test(pathname))) {
80
+ return false;
81
+ }
82
+ return pattern.test(pathname);
83
+ }
84
+ function raises(error) {
85
+ return () => {
86
+ throw error;
87
+ };
88
+ }
89
+ function cloned(fn) {
90
+ return ((...args) => fn(...args));
91
+ }
92
+ function enabledIf(condition, options) {
93
+ const enabled = typeof condition === "function" ? condition() : condition;
94
+ return function(fn) {
95
+ if (!enabled) {
96
+ return cloned((() => options.ifNotEnabledReturnValue));
97
+ }
98
+ return cloned(fn);
99
+ };
100
+ }
101
+ function transformExceptions(exceptionTypes, transform, options = {}) {
102
+ const { keepOriginal = true } = options;
103
+ return function(fn) {
104
+ return ((...args) => {
105
+ try {
106
+ return fn(...args);
107
+ } catch (error) {
108
+ if (!exceptionTypes.some((ExceptionType) => error instanceof ExceptionType)) {
109
+ throw error;
110
+ }
111
+ const newError = transform(error);
112
+ if (keepOriginal) {
113
+ newError.cause = error;
114
+ }
115
+ throw newError;
116
+ }
117
+ });
118
+ };
119
+ }
120
+
121
+ // src/objects/index.ts
122
+ function checkRequiredKeys(obj, conditions) {
123
+ const matchingConditions = Object.entries(conditions).filter(
124
+ ([, keys]) => keys.every((key) => obj[key] !== void 0) && Object.keys(obj).every((key) => keys.includes(key) || obj[key] === void 0)
125
+ );
126
+ if (matchingConditions.length !== 1) {
127
+ throw new Error(`Object keys do not match exactly one required condition. ${JSON.stringify(conditions)}`);
128
+ }
129
+ return matchingConditions[0][0];
130
+ }
131
+ function requireExclusiveKeys(conditions, options = {}) {
132
+ const conditionEntries = Object.entries(conditions);
133
+ if (conditionEntries.length === 0) {
134
+ throw new Error("At least one condition must be provided.");
135
+ }
136
+ const { allowEmpty = false } = options;
137
+ const governedKeys = new Set(conditionEntries.flatMap(([, keys]) => keys));
138
+ return function(fn) {
139
+ return ((arg) => {
140
+ const provided = new Set(
141
+ Object.keys(arg).filter((key) => governedKeys.has(key) && arg[key] !== void 0)
142
+ );
143
+ if (allowEmpty && provided.size === 0) {
144
+ return fn(arg);
145
+ }
146
+ const matches = conditionEntries.filter(
147
+ ([, keys]) => keys.length === provided.size && keys.every((key) => provided.has(key))
148
+ );
149
+ if (matches.length !== 1) {
150
+ throw new Error(`Object keys do not match exactly one required condition. ${JSON.stringify(conditions)}`);
151
+ }
152
+ return fn(arg);
153
+ });
154
+ };
155
+ }
156
+ function setKeyValueToObjectIfValue(key, value, object) {
157
+ if (value) {
158
+ Object.defineProperty(object, key, { value, writable: true, configurable: true, enumerable: true });
159
+ }
160
+ }
161
+
162
+ // src/strings/index.ts
163
+ function slugify(value, allowUnicode = false) {
164
+ if (allowUnicode) {
165
+ value = value.normalize("NFKC").replace(/[^\p{L}\p{N}_\s-]/gu, "");
166
+ } else {
167
+ value = value.normalize("NFKD").replace(/[^\x00-\x7F]/g, "").replace(/[\r\n]+/g, " ").trim().replace(/[^\w\s-]/g, "");
168
+ }
169
+ value = value.toLowerCase();
170
+ return value.replace(/[-\s]+/g, "-").replace(/^[-_]+|[-_]+$/g, "");
171
+ }
172
+
173
+ // src/dates/_format.ts
174
+ import { format } from "date-fns";
175
+ function formatDate(date, pattern) {
176
+ return format(date, pattern);
177
+ }
178
+
179
+ // src/dates/index.ts
180
+ var LONG_DATE_FORMAT = "EEEE, MMMM dd, yyyy 'at' hh:mm a";
181
+ var SHORT_DATE_FORMAT = "dd.MM.yyyy";
182
+ var SHORT_DATETIME_FORMAT = "dd.MM.yyyy HH:mm a";
183
+ function formattedDate(pattern, date = /* @__PURE__ */ new Date()) {
184
+ return formatDate(date, pattern);
185
+ }
186
+ function longFormattedDate(date = /* @__PURE__ */ new Date()) {
187
+ return formattedDate(LONG_DATE_FORMAT, date);
188
+ }
189
+ function shortFormattedDate(date = /* @__PURE__ */ new Date()) {
190
+ return formattedDate(SHORT_DATE_FORMAT, date);
191
+ }
192
+ function shortFormattedDateTime(date = /* @__PURE__ */ new Date()) {
193
+ return formattedDate(SHORT_DATETIME_FORMAT, date);
194
+ }
195
+ function optionalDate(date) {
196
+ return date ? new Date(date) : void 0;
197
+ }
198
+
199
+ // src/files/index.ts
200
+ function guessImageMimeType(filename) {
201
+ const withoutQueryOrHash = filename.split(/[?#]/)[0];
202
+ const extension = withoutQueryOrHash.split(".").pop()?.toLowerCase();
203
+ switch (extension) {
204
+ case "png":
205
+ return "image/png";
206
+ case "jfif":
207
+ case "jpg":
208
+ case "jpeg":
209
+ return "image/jpeg";
210
+ case "webp":
211
+ return "image/webp";
212
+ default:
213
+ return "image/png";
214
+ }
215
+ }
216
+ function isImageMimeType(mimeType) {
217
+ return mimeType === "image/png" || mimeType === "image/jpeg" || mimeType === "image/webp";
218
+ }
219
+ function escapeName(name) {
220
+ return name.replace(/[^a-zA-Z0-9-_.]/g, "_");
221
+ }
222
+ function safeFileName(filename, maxLength = 255) {
223
+ if (filename.length <= maxLength) return filename;
224
+ const dotIndex = filename.lastIndexOf(".");
225
+ const hasExtension = dotIndex > 0;
226
+ const extension = escapeName(hasExtension ? filename.slice(dotIndex) : "");
227
+ const name = escapeName(hasExtension ? filename.slice(0, dotIndex) : filename);
228
+ return name.slice(0, Math.max(0, maxLength - extension.length)) + extension;
229
+ }
230
+ async function downloadAndFormatImage(src, name = "image.png", mimeType = guessImageMimeType(name), quality = 1) {
231
+ name = safeFileName(name);
232
+ try {
233
+ const img = new Image();
234
+ img.crossOrigin = "anonymous";
235
+ await new Promise((resolve, reject) => {
236
+ img.onload = resolve;
237
+ img.onerror = reject;
238
+ img.src = src;
239
+ });
240
+ const canvas = document.createElement("canvas");
241
+ canvas.width = img.width;
242
+ canvas.height = img.height;
243
+ const ctx = canvas.getContext("2d");
244
+ if (!ctx) {
245
+ throw new Error("Could not get canvas context");
246
+ }
247
+ ctx.drawImage(img, 0, 0);
248
+ const blob = await new Promise((resolve) => {
249
+ canvas.toBlob(resolve, mimeType, quality);
250
+ });
251
+ if (!blob) {
252
+ throw new Error("Could not generate blob");
253
+ }
254
+ const link = document.createElement("a");
255
+ const downloadUrl = URL.createObjectURL(blob);
256
+ try {
257
+ link.href = downloadUrl;
258
+ link.download = name;
259
+ document.body.appendChild(link);
260
+ link.click();
261
+ } finally {
262
+ document.body.removeChild(link);
263
+ URL.revokeObjectURL(downloadUrl);
264
+ }
265
+ } catch (error) {
266
+ console.error("Failed to download image:", error);
267
+ }
268
+ }
269
+ async function fileToBase64Native(file) {
270
+ const result = await new Promise((resolve, reject) => {
271
+ const reader = new FileReader();
272
+ reader.readAsDataURL(file);
273
+ reader.onload = () => resolve(reader.result);
274
+ reader.onerror = (error) => reject(error);
275
+ });
276
+ if (typeof result === "string") {
277
+ return result;
278
+ } else {
279
+ throw new Error("Failed to read file as Data URL");
280
+ }
281
+ }
282
+ async function fileToBase64(file, quality = 1) {
283
+ if (isImageMimeType(file.type)) {
284
+ const img = new Image();
285
+ const url = URL.createObjectURL(file);
286
+ try {
287
+ await new Promise((resolve, reject) => {
288
+ img.onload = () => resolve();
289
+ img.onerror = () => reject(new Error("Failed to load image for metadata removal"));
290
+ img.src = url;
291
+ });
292
+ const canvas = document.createElement("canvas");
293
+ canvas.width = img.width;
294
+ canvas.height = img.height;
295
+ const ctx = canvas.getContext("2d");
296
+ if (!ctx) {
297
+ throw new Error("Failed to get canvas context");
298
+ }
299
+ ctx.drawImage(img, 0, 0);
300
+ const cleanDataUrl = canvas.toDataURL(file.type, quality);
301
+ if (cleanDataUrl === "data:,") {
302
+ return await fileToBase64Native(file);
303
+ }
304
+ return cleanDataUrl;
305
+ } finally {
306
+ URL.revokeObjectURL(url);
307
+ }
308
+ } else {
309
+ return await fileToBase64Native(file);
310
+ }
311
+ }
312
+
313
+ // src/cookies/index.ts
314
+ function getCookie(name) {
315
+ for (const pair of document.cookie.split("; ")) {
316
+ const separatorIndex = pair.indexOf("=");
317
+ if (separatorIndex === -1) {
318
+ continue;
319
+ }
320
+ if (pair.slice(0, separatorIndex) === name) {
321
+ return pair.slice(separatorIndex + 1);
322
+ }
323
+ }
324
+ return void 0;
325
+ }
326
+
327
+ // src/console/index.ts
328
+ var patchedWindows = /* @__PURE__ */ new WeakMap();
329
+ function createConsoleDebugSwitch(targetWindow, options) {
330
+ if (!targetWindow) {
331
+ return;
332
+ }
333
+ const { namespace } = options;
334
+ let enabledNamespaces = patchedWindows.get(targetWindow);
335
+ if (!enabledNamespaces) {
336
+ enabledNamespaces = /* @__PURE__ */ new Set();
337
+ patchedWindows.set(targetWindow, enabledNamespaces);
338
+ const original = {
339
+ log: targetWindow.console.log.bind(targetWindow.console),
340
+ info: targetWindow.console.info.bind(targetWindow.console),
341
+ warn: targetWindow.console.warn.bind(targetWindow.console),
342
+ error: targetWindow.console.error.bind(targetWindow.console)
343
+ };
344
+ const conditional = (method) => (...args) => {
345
+ if (enabledNamespaces.size > 0) {
346
+ method(...args);
347
+ }
348
+ };
349
+ targetWindow.console.log = conditional(original.log);
350
+ targetWindow.console.info = conditional(original.info);
351
+ targetWindow.console.warn = conditional(original.warn);
352
+ targetWindow.console.error = conditional(original.error);
353
+ }
354
+ const globals = targetWindow;
355
+ const existing = Object.prototype.hasOwnProperty.call(globals, namespace) ? Object.getOwnPropertyDescriptor(globals, namespace)?.value : void 0;
356
+ const target = existing ?? {};
357
+ target.debug = (flag) => {
358
+ if (flag) {
359
+ enabledNamespaces.add(namespace);
360
+ } else {
361
+ enabledNamespaces.delete(namespace);
362
+ }
363
+ };
364
+ Object.defineProperty(globals, namespace, { value: target, writable: true, configurable: true, enumerable: true });
365
+ }
366
+
367
+ // src/colors/index.ts
368
+ var HEX_PATTERN = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;
369
+ function hexToRgb(hex) {
370
+ const match = HEX_PATTERN.exec(hex.trim());
371
+ if (!match) {
372
+ throw new Error(`Invalid hex color: "${hex}"`);
373
+ }
374
+ const digits = match[1];
375
+ const normalized = digits.length === 3 ? digits.split("").map((char) => char + char).join("") : digits;
376
+ return {
377
+ r: parseInt(normalized.slice(0, 2), 16),
378
+ g: parseInt(normalized.slice(2, 4), 16),
379
+ b: parseInt(normalized.slice(4, 6), 16)
380
+ };
381
+ }
382
+ function rgbToHex({ r, g, b }) {
383
+ return `#${[r, g, b].map((channel) => Math.round(channel).toString(16).padStart(2, "0")).join("")}`;
384
+ }
385
+ function mixRgb(base, target, weight) {
386
+ return {
387
+ r: base.r + (target.r - base.r) * weight,
388
+ g: base.g + (target.g - base.g) * weight,
389
+ b: base.b + (target.b - base.b) * weight
390
+ };
391
+ }
392
+ var WHITE = { r: 255, g: 255, b: 255 };
393
+ var BLACK = { r: 0, g: 0, b: 0 };
394
+ var TINT_WEIGHTS = { 50: 0.95, 100: 0.9, 200: 0.75, 300: 0.6, 400: 0.3 };
395
+ var SHADE_WEIGHTS = {
396
+ 600: 0.15,
397
+ 700: 0.3,
398
+ 800: 0.45,
399
+ 900: 0.6,
400
+ 950: 0.8
401
+ };
402
+ function generateTailwindColorScale(baseColor) {
403
+ const base = hexToRgb(baseColor);
404
+ return {
405
+ 50: rgbToHex(mixRgb(base, WHITE, TINT_WEIGHTS[50])),
406
+ 100: rgbToHex(mixRgb(base, WHITE, TINT_WEIGHTS[100])),
407
+ 200: rgbToHex(mixRgb(base, WHITE, TINT_WEIGHTS[200])),
408
+ 300: rgbToHex(mixRgb(base, WHITE, TINT_WEIGHTS[300])),
409
+ 400: rgbToHex(mixRgb(base, WHITE, TINT_WEIGHTS[400])),
410
+ 500: rgbToHex(base),
411
+ 600: rgbToHex(mixRgb(base, BLACK, SHADE_WEIGHTS[600])),
412
+ 700: rgbToHex(mixRgb(base, BLACK, SHADE_WEIGHTS[700])),
413
+ 800: rgbToHex(mixRgb(base, BLACK, SHADE_WEIGHTS[800])),
414
+ 900: rgbToHex(mixRgb(base, BLACK, SHADE_WEIGHTS[900])),
415
+ 950: rgbToHex(mixRgb(base, BLACK, SHADE_WEIGHTS[950]))
416
+ };
417
+ }
418
+ function generateNamedTailwindColorScale(baseColor, name) {
419
+ const scale = generateTailwindColorScale(baseColor);
420
+ return Object.fromEntries(Object.entries(scale).map(([shade, hex]) => [`${name}${shade}`, hex]));
421
+ }
422
+ function rgbToHsl({ r, g, b }) {
423
+ const rN = r / 255;
424
+ const gN = g / 255;
425
+ const bN = b / 255;
426
+ const max = Math.max(rN, gN, bN);
427
+ const min = Math.min(rN, gN, bN);
428
+ const l = (max + min) / 2;
429
+ if (max === min) {
430
+ return { h: 0, s: 0, l: l * 100 };
431
+ }
432
+ const delta = max - min;
433
+ const s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min);
434
+ let h;
435
+ if (max === rN) {
436
+ h = ((gN - bN) / delta + (gN < bN ? 6 : 0)) * 60;
437
+ } else if (max === gN) {
438
+ h = ((bN - rN) / delta + 2) * 60;
439
+ } else {
440
+ h = ((rN - gN) / delta + 4) * 60;
441
+ }
442
+ return { h, s: s * 100, l: l * 100 };
443
+ }
444
+ function hexToHslTriplet(hex, precision = 1) {
445
+ const { h, s, l } = rgbToHsl(hexToRgb(hex));
446
+ const round = (value) => Number(value.toFixed(precision));
447
+ return `${round(h)} ${round(s)}% ${round(l)}%`;
448
+ }
449
+ export {
450
+ LONG_DATE_FORMAT,
451
+ SHORT_DATETIME_FORMAT,
452
+ SHORT_DATE_FORMAT,
453
+ allCombinations,
454
+ checkRequiredKeys,
455
+ cloned,
456
+ createConsoleDebugSwitch,
457
+ downloadAndFormatImage,
458
+ enabledIf,
459
+ escapeName,
460
+ fileToBase64,
461
+ fileToBase64Native,
462
+ forcedType,
463
+ formattedDate,
464
+ generateNamedTailwindColorScale,
465
+ generateTailwindColorScale,
466
+ getCookie,
467
+ getKeys,
468
+ getLazyValue,
469
+ getLazyValueAsync,
470
+ guessImageMimeType,
471
+ hexToHslTriplet,
472
+ isImageMimeType,
473
+ isPathMatched,
474
+ longFormattedDate,
475
+ makeCallable,
476
+ notNone,
477
+ optionalDate,
478
+ preventDefault,
479
+ raises,
480
+ requireExclusiveKeys,
481
+ safeFileName,
482
+ setKeyValueToObjectIfValue,
483
+ shortFormattedDate,
484
+ shortFormattedDateTime,
485
+ slugify,
486
+ suppress,
487
+ transformExceptions,
488
+ withAttributes
489
+ };
490
+ //# sourceMappingURL=index.js.map