This commit is contained in:
Ubuntu
2026-07-03 16:58:28 +08:00
commit 32b43f85bd
6240 changed files with 1987678 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
export { byOrder };
function byOrder({ order }: { order: 'asc' | 'desc' | null | undefined }) {
return (a: string, b: string) => {
return order === 'asc' ? a.localeCompare(b) : b.localeCompare(a);
};
}
+86
View File
@@ -0,0 +1,86 @@
import { describe, expect, it } from 'vitest';
import { base64ToText, isValidBase64, removePotentialDataAndMimePrefix, textToBase64 } from './base64';
describe('base64 utils', () => {
describe('textToBase64', () => {
it('should convert string into base64', () => {
expect(textToBase64('')).to.eql('');
expect(textToBase64('a')).to.eql('YQ==');
expect(textToBase64('lorem ipsum')).to.eql('bG9yZW0gaXBzdW0=');
expect(textToBase64('-1')).to.eql('LTE=');
expect(textToBase64('<<<????????>>>', { makeUrlSafe: false })).to.eql('PDw8Pz8/Pz8/Pz8+Pj4=');
});
it('should convert string into url safe base64', () => {
expect(textToBase64('', { makeUrlSafe: true })).to.eql('');
expect(textToBase64('a', { makeUrlSafe: true })).to.eql('YQ');
expect(textToBase64('lorem ipsum', { makeUrlSafe: true })).to.eql('bG9yZW0gaXBzdW0');
expect(textToBase64('<<<????????>>>', { makeUrlSafe: true })).to.eql('PDw8Pz8_Pz8_Pz8-Pj4');
});
});
describe('base64ToText', () => {
it('should convert base64 into text', () => {
expect(base64ToText('')).to.eql('');
expect(base64ToText('YQ==', { makeUrlSafe: false })).to.eql('a');
expect(base64ToText('bG9yZW0gaXBzdW0=')).to.eql('lorem ipsum');
expect(base64ToText('data:text/plain;base64,bG9yZW0gaXBzdW0=')).to.eql('lorem ipsum');
expect(base64ToText('LTE=')).to.eql('-1');
});
it('should convert url safe base64 into text', () => {
expect(base64ToText('', { makeUrlSafe: true })).to.eql('');
expect(base64ToText('YQ', { makeUrlSafe: true })).to.eql('a');
expect(base64ToText('bG9yZW0gaXBzdW0', { makeUrlSafe: true })).to.eql('lorem ipsum');
expect(base64ToText('data:text/plain;base64,bG9yZW0gaXBzdW0', { makeUrlSafe: true })).to.eql('lorem ipsum');
expect(base64ToText('LTE', { makeUrlSafe: true })).to.eql('-1');
expect(base64ToText('PDw8Pz8_Pz8_Pz8-Pj4', { makeUrlSafe: true })).to.eql('<<<????????>>>');
});
it('should throw for incorrect base64 string', () => {
expect(() => base64ToText('a')).to.throw('Incorrect base64 string');
// should not really be false because trimming of space is now implied
// expect(() => base64ToText(' ')).to.throw('Incorrect base64 string');
expect(() => base64ToText('é')).to.throw('Incorrect base64 string');
// missing final '='
expect(() => base64ToText('bG9yZW0gaXBzdW0')).to.throw('Incorrect base64 string');
});
});
describe('isValidBase64', () => {
it('should return true for correct base64 string', () => {
expect(isValidBase64('')).to.eql(true);
expect(isValidBase64('bG9yZW0gaXBzdW0=')).to.eql(true);
expect(isValidBase64('LTE=')).to.eql(true);
expect(isValidBase64('YQ==')).to.eql(true);
expect(isValidBase64('data:text/plain;base64,YQ==')).to.eql(true);
});
it('should return false for incorrect base64 string', () => {
expect(isValidBase64('a')).to.eql(false);
expect(isValidBase64('é')).to.eql(false);
expect(isValidBase64('data:text/plain;notbase64,YQ==')).to.eql(false);
// missing final '='
expect(isValidBase64('bG9yZW0gaXBzdW0')).to.eql(false);
});
it('should return true for untrimmed correct base64 string', () => {
expect(isValidBase64('bG9yZW0gaXBzdW0= ')).to.eql(true);
expect(isValidBase64(' LTE=')).to.eql(true);
expect(isValidBase64(' YQ== ')).to.eql(true);
expect(isValidBase64(' ')).to.eql(true);
});
});
describe('removePotentialDataAndMimePrefix', () => {
it('should remove data prefix of string', () => {
expect(removePotentialDataAndMimePrefix('')).to.eql('');
expect(removePotentialDataAndMimePrefix('lorem ipsum')).to.eql('lorem ipsum');
expect(removePotentialDataAndMimePrefix('bG9yZW0gaXBzdW0=')).to.eql('bG9yZW0gaXBzdW0=');
expect(removePotentialDataAndMimePrefix('data:image/jpeg;base64,lorem')).to.eql('lorem');
expect(removePotentialDataAndMimePrefix('data:image/jpeg;notbase64,lorem')).to.eql(
'data:image/jpeg;notbase64,lorem',
);
expect(removePotentialDataAndMimePrefix('data:unknownmime;base64,lorem')).to.eql('lorem');
});
});
});
+63
View File
@@ -0,0 +1,63 @@
import { Base64 } from 'js-base64';
export { textToBase64, base64ToText, isValidBase64, removePotentialDataAndMimePrefix };
function textToBase64(str: string, { makeUrlSafe = false }: { makeUrlSafe?: boolean } = {}) {
const encoded = Base64.encode(str);
return makeUrlSafe ? makeUriSafe(encoded) : encoded;
}
function base64ToText(str: string, { makeUrlSafe = false }: { makeUrlSafe?: boolean } = {}) {
if (!isValidBase64(str, { makeUrlSafe })) {
throw new Error('Incorrect base64 string');
}
let cleanStr = removePotentialDataAndMimePrefix(str);
if (makeUrlSafe) {
cleanStr = unURI(cleanStr);
}
try {
return Base64.decode(cleanStr);
}
catch (_) {
throw new Error('Incorrect base64 string');
}
}
function removePotentialDataAndMimePrefix(str: string) {
return str.replace(/^data:.*?;base64,/, '');
}
function isValidBase64(str: string, { makeUrlSafe = false }: { makeUrlSafe?: boolean } = {}) {
let cleanStr = removePotentialDataAndMimePrefix(str);
if (makeUrlSafe) {
cleanStr = unURI(cleanStr);
}
try {
const reEncodedBase64 = Base64.fromUint8Array(Base64.toUint8Array(cleanStr));
if (makeUrlSafe) {
return removePotentialPadding(reEncodedBase64) === cleanStr;
}
return reEncodedBase64 === cleanStr.replace(/\s/g, '');
}
catch (err) {
return false;
}
}
function makeUriSafe(encoded: string) {
return encoded.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}
function unURI(encoded: string): string {
return encoded
.replace(/-/g, '+')
.replace(/_/g, '/')
.replace(/[^A-Za-z0-9+/]/g, '');
}
function removePotentialPadding(str: string) {
return str.replace(/=/g, '');
}
+23
View File
@@ -0,0 +1,23 @@
import _ from 'lodash';
import { describe, expect, it } from 'vitest';
import { booleanToHumanReadable, isNotThrowing } from './boolean';
describe('boolean utils', () => {
describe('isNotThrowing', () => {
it('should return if the call throws or false otherwise', () => {
expect(isNotThrowing(_.noop)).to.eql(true);
expect(
isNotThrowing(() => {
throw new Error('message');
}),
).to.eql(false);
});
});
describe('booleanToHumanReadable', () => {
it('should return "Yes" if the value is true and "No" otherwise', () => {
expect(booleanToHumanReadable(true)).to.eql('Yes');
expect(booleanToHumanReadable(false)).to.eql('No');
});
});
});
+15
View File
@@ -0,0 +1,15 @@
export { isNotThrowing, booleanToHumanReadable };
function isNotThrowing(cb: () => unknown): boolean {
try {
cb();
return true;
}
catch (_) {
return false;
}
}
function booleanToHumanReadable(value: boolean): string {
return value ? 'Yes' : 'No';
}
+11
View File
@@ -0,0 +1,11 @@
export function formatBytes(bytes: number, decimals = 2) {
if (bytes === 0) {
return '0 Bytes';
}
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${Number.parseFloat((bytes / k ** i).toFixed(decimals))} ${sizes[i]}`;
}
+16
View File
@@ -0,0 +1,16 @@
import { describe, expect, it } from 'vitest';
import { withDefaultOnError } from './defaults';
describe('defaults util', () => {
describe('withDefaultOnError', () => {
it('should return the callback or the default one if the callback throws', () => {
expect(withDefaultOnError(() => 'original', 'default')).to.eql('original');
});
expect(
withDefaultOnError(() => {
throw new Error('message');
}, 'default'),
).to.eql('default');
});
});
+19
View File
@@ -0,0 +1,19 @@
export { withDefaultOnError, withDefaultOnErrorAsync };
function withDefaultOnError<A, B>(cb: () => A, defaultValue: B): A | B {
try {
return cb();
}
catch (_) {
return defaultValue;
}
}
async function withDefaultOnErrorAsync<A, B>(cb: () => A, defaultValue: B): Promise<Awaited<A> | B> {
try {
return await cb();
}
catch (_) {
return defaultValue;
}
}
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest';
import { getErrorMessageIfThrows } from './error';
describe('error util', () => {
describe('getErrorMessageIfThrows', () => {
it('get an error message if the callback throws, undefined instead', () => {
expect(
getErrorMessageIfThrows(() => {
// eslint-disable-next-line no-throw-literal
throw 'message';
}),
).to.equal('message');
expect(
getErrorMessageIfThrows(() => {
throw new Error('message');
}),
).to.equal('message');
expect(
getErrorMessageIfThrows(() => {
// eslint-disable-next-line no-throw-literal
throw { message: 'message' };
}),
).to.equal('message');
expect(getErrorMessageIfThrows(() => {})).to.equal(undefined);
});
});
});
+25
View File
@@ -0,0 +1,25 @@
import _ from 'lodash';
export { getErrorMessageIfThrows };
function getErrorMessageIfThrows(cb: () => unknown) {
try {
cb();
return undefined;
}
catch (err) {
if (_.isString(err)) {
return err;
}
if (_.isError(err)) {
return err.message;
}
if (_.isObject(err) && _.has(err, 'message')) {
return (err as { message: string }).message;
}
return 'An error as occurred.';
}
}
+32
View File
@@ -0,0 +1,32 @@
import type { Ref } from 'vue';
import { useValidation } from '@/composable/validation';
const macAddressValidationRules = [
{
message: 'Invalid MAC address',
validator: (value: string) => value.trim().match(/^([0-9A-Fa-f]{2}[:-]){2,5}([0-9A-Fa-f]{2})$/),
},
];
function macAddressValidation(value: Ref) {
return useValidation({
source: value,
rules: macAddressValidationRules,
});
}
const partialMacAddressValidationRules = [
{
message: 'Invalid partial MAC address',
validator: (value: string) => value.trim().match(/^([0-9a-f]{2}[:\-. ]){0,5}([0-9a-f]{0,2})$/i),
},
];
function usePartialMacAddressValidation(value: Ref) {
return useValidation({
source: value,
rules: partialMacAddressValidationRules,
});
}
export { macAddressValidation, macAddressValidationRules, usePartialMacAddressValidation, partialMacAddressValidationRules };
+31
View File
@@ -0,0 +1,31 @@
const random = () => Math.random();
const randFromArray = (array: unknown[]) => array[Math.floor(random() * array.length)];
const randIntFromInterval = (min: number, max: number) => Math.floor(random() * (max - min) + min);
// Durstenfeld shuffle
function shuffleArrayMutate<T>(array: T[]): T[] {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const shuffleArray = <T>(array: T[]): T[] => shuffleArrayMutate([...array]);
const shuffleString = (str: string, delimiter = ''): string => shuffleArrayMutate(str.split(delimiter)).join(delimiter);
const generateRandomId = () => `id-${random().toString(36).substring(2, 12)}`;
export {
randFromArray,
randIntFromInterval,
random,
shuffleArray,
shuffleArrayMutate,
shuffleString,
generateRandomId,
};