mirror of
https://gitcode.com/gh_mirrors/hy/Hydro.git
synced 2026-10-17 17:36:08 +08:00
util: switch to pure module
This commit is contained in:
3 files changed
+47
-45
No files matched your search
@@ -39,7 +39,7 @@ String.prototype.format ||= function formatStr(...args) {
|
||||
}
|
||||
} else return this.formatFromArray(args);
|
||||
}
|
||||
return result;
|
||||
return result as string;
|
||||
};
|
||||
|
||||
String.prototype.formatFromArray = function formatStr(args) {
|
||||
@@ -50,7 +50,7 @@ String.prototype.formatFromArray = function formatStr(args) {
|
||||
result = result.replace(reg, args[i]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
return result as string;
|
||||
};
|
||||
|
||||
String.prototype.rawformat = function rawFormat(object) {
|
||||
@@ -73,26 +73,25 @@ try {
|
||||
Array.isDiff = diffArray;
|
||||
} catch (e) { } // Cannot add property isDiff, object is not extensible
|
||||
|
||||
// @ts-ignore
|
||||
Date.prototype.format = function formatDate(fmt = '%Y-%m-%d %H:%M:%S') {
|
||||
let m = this.getMonth() + 1;
|
||||
if (m < 10) m = `0${m}`;
|
||||
let d = this.getDate();
|
||||
if (d < 10) d = `0${d}`;
|
||||
let H = this.getHours();
|
||||
if (H < 10) H = `0${H}`;
|
||||
let M = this.getMinutes();
|
||||
if (M < 10) M = `0${M}`;
|
||||
let S = this.getSeconds();
|
||||
if (S < 10) S = `0${S}`;
|
||||
export function formatDate(date: Date, fmt = '%Y-%m-%d %H:%M:%S') {
|
||||
let m = (date.getMonth() + 1).toString();
|
||||
if (m.length < 2) m = `0${m}`;
|
||||
let d = date.getDate().toString();
|
||||
if (d.length < 2) d = `0${d}`;
|
||||
let H = date.getHours().toString();
|
||||
if (H.length < 2) H = `0${H}`;
|
||||
let M = date.getMinutes().toString();
|
||||
if (M.length < 2) M = `0${M}`;
|
||||
let S = date.getSeconds().toString();
|
||||
if (S.length < 2) S = `0${S}`;
|
||||
return fmt
|
||||
.replace('%Y', this.getFullYear())
|
||||
.replace('%Y', date.getFullYear().toString())
|
||||
.replace('%m', m)
|
||||
.replace('%d', d)
|
||||
.replace('%H', H)
|
||||
.replace('%M', M)
|
||||
.replace('%S', S);
|
||||
};
|
||||
}
|
||||
|
||||
Math.sum = function sum(...args) {
|
||||
let s = 0;
|
||||
@@ -129,7 +128,7 @@ Set.intersection = function Intersection<T>(A: Set<T> | Array<T> = [], B: Set<T>
|
||||
|
||||
export function sleep(timeout: number) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => resolve(true), timeout);
|
||||
setTimeout(resolve, timeout, true);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -137,11 +136,11 @@ function deepen(modifyString: (source: string) => string) {
|
||||
function modifyObject<T>(source: T): T {
|
||||
if (typeof source !== 'object' || !source) return source;
|
||||
if (Array.isArray(source)) return source.map(modifyObject) as any;
|
||||
const result = {} as T;
|
||||
const result = {} as any;
|
||||
for (const key in source) {
|
||||
result[modifyString(key)] = modifyObject(source[key]);
|
||||
}
|
||||
return result;
|
||||
return result as T;
|
||||
}
|
||||
|
||||
return function t<T>(source: T): T {
|
||||
@@ -157,9 +156,9 @@ export const paramCase = deepen((source) => source.replace(/_/g, '-').replace(/(
|
||||
export const snakeCase = deepen((source) => source.replace(/-/g, '_').replace(/(?<!^)[A-Z]/g, (str) => `_${str.toLowerCase()}`));
|
||||
|
||||
const TIME_RE = /^([0-9]+(?:\.[0-9]*)?)([mu]?)s?$/i;
|
||||
const TIME_UNITS = { '': 1000, m: 1, u: 0.001 };
|
||||
const TIME_UNITS = { '': 1000, m: 1, u: 0.001 } as Record<string, number>;
|
||||
const MEMORY_RE = /^([0-9]+(?:\.[0-9]*)?)([kmg])b?$/i;
|
||||
const MEMORY_UNITS = { k: 1 / 1024, m: 1, g: 1024 };
|
||||
const MEMORY_UNITS = { k: 1 / 1024, m: 1, g: 1024 } as Record<string, number>;
|
||||
|
||||
export function parseTimeMS(str: string | number, throwOnError = true) {
|
||||
if (typeof str === 'number' || Number.isSafeInteger(+str)) return +str;
|
||||
@@ -199,7 +198,7 @@ export function size(s: number, base = 1) {
|
||||
if (s < unit) return '{0} {1}'.format(Math.round(s * 10) / 10, unitName);
|
||||
s /= unit;
|
||||
}
|
||||
return `${Math.round(s * unit)} ${unitNames[unitNames.length - 1]}`;
|
||||
return `${Math.round(s * unit)} ${unitNames.at(-1)}`;
|
||||
}
|
||||
|
||||
export function randomPick<T>(arr: T[]): T {
|
||||
@@ -217,7 +216,7 @@ export function sortFiles(files: Record<string, any>[] | string[], key = '_id')
|
||||
if (!files?.length) return [];
|
||||
const isString = typeof files[0] === 'string';
|
||||
const result = files
|
||||
.map((i) => (isString ? { name: i, _weights: i.match(fSortR) } : { ...i, _weights: (i[key] || i.name).match(fSortR) }))
|
||||
.map((i: any) => (isString ? { name: i, _weights: i.match(fSortR) } : { ...i, _weights: (i[key] || i.name).match(fSortR) }))
|
||||
.sort((a, b) => {
|
||||
let pos = 0;
|
||||
const weightsA = a._weights;
|
||||
@@ -239,7 +238,7 @@ export function sortFiles(files: Record<string, any>[] | string[], key = '_id')
|
||||
|
||||
export const getAlphabeticId = (() => {
|
||||
// A...Z, AA...AZ, BA...BZ, ...
|
||||
const f = (a: number) => (a < 0 ? '' : f(a / 26 - 1) + String.fromCharCode((a % 26) + 65)) as string;
|
||||
const f: (a: number) => string = (a: number) => (a < 0 ? '' : f(a / 26 - 1) + String.fromCharCode((a % 26) + 65));
|
||||
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
const cache = alphabet.split('');
|
||||
for (const ch of alphabet) cache.push(...alphabet.split('').map((c) => ch + c));
|
||||
|
||||
@@ -9,7 +9,8 @@ import type { Moment } from 'moment';
|
||||
import { Exporter, Factory, Logger as Reggol } from 'reggol';
|
||||
import type * as superagent from 'superagent';
|
||||
|
||||
export * from '@hydrooj/utils/lib/common';
|
||||
// @ts-ignore
|
||||
export * from '@hydrooj/utils/lib/common.ts';
|
||||
export * as fs from 'fs-extra';
|
||||
|
||||
Factory.formatters['d'] = (value, exporter) => Reggol.color(exporter, 3, value);
|
||||
@@ -132,22 +133,23 @@ export function bufferToStream(buffer: Buffer): NodeJS.ReadableStream {
|
||||
let ObjectId: typeof import('bson').ObjectId; // eslint-disable-line
|
||||
let isMoment: (x: any) => x is Moment;
|
||||
|
||||
export namespace Time {
|
||||
export const second = 1000;
|
||||
export const minute = second * 60;
|
||||
export const hour = minute * 60;
|
||||
export const day = hour * 24;
|
||||
export const week = day * 7;
|
||||
export function formatTimeShort(ms: number) {
|
||||
const abs = Math.abs(ms);
|
||||
if (abs >= day - hour / 2) return `${Math.round(ms / day)}d`;
|
||||
if (abs >= hour - minute / 2) return `${Math.round(ms / hour)}h`;
|
||||
if (abs >= minute - second / 2) return `${Math.round(ms / minute)}m`;
|
||||
if (abs >= second) return `${Math.round(ms / second)}s`;
|
||||
return `${ms}ms`;
|
||||
}
|
||||
export const Time = {
|
||||
second: 1000,
|
||||
minute: 60 * 1000,
|
||||
hour: 60 * 60 * 1000,
|
||||
day: 24 * 60 * 60 * 1000,
|
||||
week: 7 * 24 * 60 * 60 * 1000,
|
||||
|
||||
export function getObjectID(timestamp: string | Date | Moment, allZero = true) {
|
||||
formatTimeShort(ms: number) {
|
||||
const abs = Math.abs(ms);
|
||||
if (abs >= Time.day - Time.hour / 2) return `${Math.round(ms / Time.day)}d`;
|
||||
if (abs >= Time.hour - Time.minute / 2) return `${Math.round(ms / Time.hour)}h`;
|
||||
if (abs >= Time.minute - Time.second / 2) return `${Math.round(ms / Time.minute)}m`;
|
||||
if (abs >= Time.second) return `${Math.round(ms / Time.second)}s`;
|
||||
return `${ms}ms`;
|
||||
},
|
||||
|
||||
getObjectID(timestamp: string | Date | Moment, allZero = true) {
|
||||
try {
|
||||
ObjectId ||= require('bson').ObjectId;
|
||||
} catch (e) {
|
||||
@@ -164,8 +166,8 @@ export namespace Time {
|
||||
else _timestamp = timestamp.getTime();
|
||||
const hexSeconds = Math.floor(_timestamp / 1000).toString(16);
|
||||
return new ObjectId(`${hexSeconds}${allZero ? '0000000000000000' : new ObjectId().toHexString().substring(8)}`);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export function errorMessage(err: Error | string) {
|
||||
const t = typeof err === 'string' ? err : err.stack;
|
||||
@@ -358,7 +360,7 @@ export async function pipeRequest(req: superagent.Request, w: fs.WriteStream, ti
|
||||
}
|
||||
}).catch(reject);
|
||||
});
|
||||
} catch (e) {
|
||||
} catch (e: any) {
|
||||
throw new Error(`Download${e.errno === 'ETIMEDOUT' ? 'Timedout' : 'Error'}(${name ? `${name}, ` : ''}${e.message})`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"name": "@hydrooj/utils",
|
||||
"version": "1.5.4",
|
||||
"description": "hydrooj utils",
|
||||
"type": "module",
|
||||
"main": "lib/utils.ts",
|
||||
"repository": "https://github.com/hydro-dev/Hydro.git",
|
||||
"author": "undefined <i@undefined.moe>",
|
||||
@@ -14,11 +15,11 @@
|
||||
"dependencies": {
|
||||
"@hydrooj/register": "workspace:^",
|
||||
"cac": "^6.7.14",
|
||||
"fs-extra": "^11.3.3",
|
||||
"fs-extra": "^11.3.4",
|
||||
"js-yaml": "^4.1.1",
|
||||
"reggol": "^2.1.0",
|
||||
"search-query-parser": "^1.6.0",
|
||||
"systeminformation": "^5.31.1"
|
||||
"systeminformation": "^5.31.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/fs-extra": "^11.0.4"
|
||||
|
||||
Reference in new issue
Block a user