xjs-common 10.1.3 → 11.0.0-alpha.2

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.
package/dist/index.js CHANGED
@@ -1,32 +1 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.DType = void 0;
18
- __exportStar(require("./const/types"), exports);
19
- __exportStar(require("./const/time-unit"), exports);
20
- __exportStar(require("./const/gender"), exports);
21
- __exportStar(require("./const/http-method"), exports);
22
- __exportStar(require("./const/ccy"), exports);
23
- __exportStar(require("./func/u"), exports);
24
- __exportStar(require("./func/u-obj"), exports);
25
- __exportStar(require("./func/u-string"), exports);
26
- __exportStar(require("./func/u-array"), exports);
27
- __exportStar(require("./func/u-http"), exports);
28
- __exportStar(require("./func/u-type"), exports);
29
- __exportStar(require("./func/decorator/transaction"), exports);
30
- var d_type_1 = require("./func/decorator/d-type");
31
- Object.defineProperty(exports, "DType", { enumerable: true, get: function () { return d_type_1.DType; } });
32
- __exportStar(require("./obj/xjs-err"), exports);
1
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports["xjs-common"]=e():t["xjs-common"]=e()}(this,()=>(()=>{"use strict";var t,e,n,r,o={d:(t,e)=>{for(var n in e)o.o(e,n)&&!o.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},i={};o.r(i),o.d(i,{DType:()=>g,Gender:()=>n,HttpMethod:()=>r,TimeUnit:()=>e,Type:()=>t,UArray:()=>O,UHttp:()=>S,UObj:()=>M,UString:()=>w,UType:()=>j,XjsErr:()=>a,array2map:()=>p,bitor:()=>m,delay:()=>y,getJSTDate:()=>l,int2array:()=>d,resolveCcy:()=>u,retry:()=>h,s_ccy:()=>c,transaction:()=>P}),function(t){t.string="string",t.number="number",t.bigint="bigint",t.boolean="boolean",t.symbol="symbol",t.object="object",t[void 0]="undefined",t.null="null"}(t||(t={})),function(t){t[t.Year=1]="Year",t[t.Month=2]="Month",t[t.Day=3]="Day",t[t.Hour=4]="Hour",t[t.Min=5]="Min",t[t.Sec=6]="Sec",t[t.Msec=7]="Msec"}(e||(e={})),function(t){t[t.Male=0]="Male",t[t.Female=1]="Female"}(n||(n={})),function(t){t.Get="GET",t.Put="PUT",t.Post="POST",t.Delete="DELETE",t.Patch="PATCH",t.Connect="CONNECT"}(r||(r={}));const s={jpy:{crossUsd:"usd/jpy"},usd:{crossUsd:null},gbp:{crossUsd:"gbp/usd"},eur:{crossUsd:"eur/usd"},cad:{crossUsd:"cad/usd"},aud:{crossUsd:"aud/usd"}},c=(Object.entries(s).forEach(t=>{t[1].symbol=t[0],s[t[0]]=Object.freeze(t[1])}),Object.freeze(s));function u(t){const e=Object.keys(c).find(e=>t?.toLowerCase()==e);return e&&c[e]}class a extends Error{code;origin;constructor(t,e,n){super(`[XJS] ${e}`),this.code=t,this.origin=n}}const f=10;function l(t){return new Date((t?t.getTime():Date.now())+324e5)}function y(t){return new Promise(e=>setTimeout(e,1e3*t))}function d(t){const e=Number(t);if(Number.isNaN(e))throw new a(f,"size of the argument is not number.");return Array.from(Array(e).keys())}function p(t,e){const n=new Map;for(const r of t){const t=e(r);n.has(t)?n.get(t).push(r):n.set(t,[r])}return n}function m(...t){return t.reduce((t,e)=>t|e)}function h(t,e){const n=e?.logger??console,r=e?.count??1,o=t=>!(e?.errorCriterion&&!e.errorCriterion(t)||(n.warn(t),0)),i=n=>{if(n<0)throw new a(f,"failure exceeds retryable count.");let s=null;const c=()=>{try{s=t()}catch(t){if(!o(t))throw t;s=i(n-1)}return s instanceof Promise?new Promise((t,e)=>s.then(t).catch(r=>{o(r)?t(i(n-1)):e(r)})):s};return n<r&&e?.intervalPredicate&&(s=e?.intervalPredicate()),s instanceof Promise?s.then(()=>c()):c()};return i(r)}const b=Symbol.for("xjs:typeMap");var g,j,M,w,O,S;!function(e){function n(t,e,n){r(t,e,t=>{if(t.t)throw new a(30,"decorator to express type is duplicate.");t.t=n})}function r(t,e,n){const r=t[b]?Object.assign({},t[b]):{};r[e]??={t:null,req:!1,rec:!1,ary:null};const o=r[e];n(o);let i=null,s=null;if(o.t&&o.rec&&(i="type",s="recursive flag"),o.t&&o.ary&&(i="type",s="array"),o.ary&&o.rec&&(i="array",s="recursive flag"),i&&s)throw new a(30,`decorator to express ${i} and ${s} are exclusive.`);Object.defineProperty(t,b,{value:r,configurable:!0})}e.string=function(e,r){n(e,r,t.string)},e.number=function(e,r){n(e,r,t.number)},e.boolean=function(e,r){n(e,r,t.boolean)},e.required=function(t,e){r(t,e,t=>t.req=!0)},e.array=function(t={}){return(e,n)=>r(e,n,e=>e.ary=t)},e.recursive=function(t,e){r(t,e,t=>t.rec=!0)},e.keep=function(t,e){r(t,e,t=>{})}}(g||(g={})),function(e){function n(e){return null===e||typeof e===t.undefined}function r(t){return t[b]?Object.entries(t[b]).flatMap(e=>o(e[0],t[e[0]],e[1])):[]}function o(t,e,i){return n(e)?i.req?[t]:[]:i.t&&typeof e!==i.t?[t]:i.ary?Array.isArray(e)?e.flatMap(e=>o(t,e,i.ary)):[t]:i.rec?r(e).flatMap(e=>`${t}.${e}`):[]}e.isDefined=function(e){return typeof e!==t.undefined},e.isEmpty=n,e.isString=function(e){return typeof e===t.string},e.isNumber=function(e){return typeof e===t.number},e.isBigint=function(e){return typeof e===t.bigint},e.isBoolean=function(e){return typeof e===t.boolean},e.isSymbol=function(e){return typeof e===t.symbol},e.isObject=function(e){return typeof e===t.object},e.isArray=function(t,e){return Array.isArray(t)&&(!e||t.every(t=>typeof t===e))},e.validate=r,e.takeAsArray=function(t){return Array.isArray(t)?t:[t]}}(j||(j={})),function(t){t.assignProperties=function t(e,n,r,o){for(const i of r??Object.keys(n))j.isDefined(n[i])&&(o&&j.isObject(e[i])&&j.isObject(n[i])&&e[i]?.[b]?t(e[i],n[i],null,!0):e[i]=n[i]);return e},t.crop=function t(e,n,r){if(!n&&!e[b])return{};const o=n??Object.keys(e[b]);return Object.keys(e).filter(i=>(!n&&e[b]?.[i]?.rec&&e[i]&&t(e[i]),!!r===o.includes(i))).forEach(t=>delete e[t]),e}}(M||(M={})),function(t){function n(t,e){const n=t.toString().split("."),r=n[0].split("").reverse().join("");let o="";const i=Math.ceil(r.length/3);for(let t=0;t<i;t++)o+=t===i-1?r.substring(3*t):r.substring(3*t,3*(t+1))+",";const s=e+o.split("").reverse().join("");return 1===n.length?s:s+"."+n[1]}t.eq=function(t,e){return j.isString(t)&&j.isString(e)?t.trim()===e.trim():t===e},t.repeat=function(t,e){return d(e).map(e=>t).join("")},t.simpleTime=function(t){const n=(t?.date??new Date).toISOString().split(".")[0].replace(/[-T:]/g,"");return t?.unit===e.Msec?n:n.substring(0,14-2*(6-(t?.unit??e.Sec)))},t.generateRandomString=function(t){return d(t).map(t=>{let e=Math.floor(62*Math.random());const n=e-52;return n>=0?n.toString():(e>26&&(e+=6),String.fromCharCode(e+65))}).join("")},t.idx2az=function(t){let e="",n=t;for(;n>=0;)e=String.fromCharCode(n%26+97)+e,n=Math.floor(n/26)-1;return e.toUpperCase()},t.az2idx=function(t){if(!t?.match(/^[a-zA-Z]+$/))throw new a(20,"the parameter isn't az(AZ) format.");return t.toLowerCase().split("").map(t=>t.charCodeAt(0)-97).reverse().map((t,e)=>(t+1)*26**e).reduce((t,e)=>t+e)-1},t.asJpy=function(t){return j.isEmpty(t)?"":n(Math.floor(t),"¥")},t.asUsd=function(t){return j.isEmpty(t)?"":n(Number(t.toFixed(2)),"$")},t.asPercentage=function(t){if(j.isEmpty(t))return"";let e=(100*t).toFixed(2);for(;e.endsWith("0");)e=e.substring(0,e.length-1);return e.endsWith(".")&&(e=e.substring(0,e.length-1)),e+"%"},t.is_yyyy=function(t){return!!t?.match(/^[1-9]\d{3}$/)},t.is_yyyyMM=function(t){return!!t?.match(/^[1-9]\d{3}(0[1-9]|1[0-2])$/)},t.is_yyyyMMdd=function(t){return!!t?.match(/^[1-9]\d{3}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|[3][0-1])$/)},t.is_yyyyMMddhh=function(t){return!!t?.match(/^[1-9]\d{3}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|[3][0-1])([01]\d|2[0-3])$/)},t.is_yyyyMMddhhmm=function(t){return!!t?.match(/^[1-9]\d{3}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|[3][0-1])([01]\d|2[0-3])[0-5]\d$/)},t.is_yyyyMMddhhmmss=function(t){return!!t?.match(/^[1-9]\d{3}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|[3][0-1])([01]\d|2[0-3])[0-5]\d[0-5]\d$/)}}(w||(w={})),function(t){function e(t,e=!0){const n=Math.floor(t.length*Math.random()),r=t[n];return e&&t.splice(n,1),r}t.eq=function(t,e,n={}){const{sort:r,useStrictEqual:o}=Object.assign({sort:!0,useStrictEqual:!0},n);if(t&&!e||!t&&e)return!1;if(!t)return!0;if(t.length!==e.length)return!1;const i=r?[...t].sort():t,s=r?[...e].sort():e;return i.every((t,e)=>o?t===s[e]:t==s[e])},t.distinct=function(t,e){if(!t||0===t.length)return[];if(e?.k)return Array.from(p(t,t=>t[e.k]).values()).map(t=>e?.takeLast?t.pop():t.shift());const n=e?.takeLast?[...t].reverse():[...t],r=e?.predicate??((t,e)=>t==e),o=[n.shift()];return n.forEach(t=>o.some(e=>r(t,e))?{}:o.push(t)),o},t.chop=function(t,e){return[...Array(Math.ceil(t.length/e)).keys()].map(n=>{let r=(n+1)*e;return r>t.length&&(r=t.length),t.slice(n*e,r)})},t.remove=function(t,e){const n=t.indexOf(e);-1!==n&&t.splice(n,1)},t.randomPick=e,t.shuffle=function(t){const n=[...t];return d(t.length).map(t=>e(n))},t.takeOut=function(t,e){const n=[];for(let r=t.length-1;r>=0;r--)e(t[r],r)&&(n.unshift(t[r]),t.splice(r,1));return n}}(O||(O={})),function(t){function e(t){return Math.floor(t/100)}t.isHttpSuccess=function(t){return 2===e(t)},t.statusCategoryOf=e,t.concatParamsWithEncoding=function(t,e){if(!e||0===Object.keys(e).length)return t;const n=Object.entries(e).flatMap(t=>Array.isArray(t[1])?t[1].map(e=>[t[0],e]):[t]);let r=t?t+"?":"";for(var o of n)r+=o[0]+"="+encodeURIComponent(o[1])+"&";return r.substring(0,r.length-1)},t.normalizeHeaders=function(t){return t?Object.entries(t).reduce((t,e)=>(t[e[0].toLowerCase()]=e[1],t),{}):{}}}(S||(S={}));const v=100;function P(t){let e=0;const n=t?.timeoutSec??30;return(t,r,o)=>{const i=o.value;o.value=async function(...t){const r=Date.now()+1e3*n;for(;e>0;){if(r<=Date.now())throw new a(v,"An exclusive process to execute was already running by other request.");await y(1)}try{e++;const n=i.apply(this,t);return n instanceof Promise?await n:n}finally{e--}}}}return i})());
@@ -0,0 +1,285 @@
1
+ declare module "const/types" {
2
+ export type IndexSignature = string | number | symbol;
3
+ export type NormalRecord = Record<IndexSignature, any>;
4
+ export type MaybeArray<T> = T | T[];
5
+ export type Loggable = {
6
+ log: (msg: any) => void;
7
+ warn: (msg: any) => void;
8
+ error: (msg: any) => void;
9
+ };
10
+ export type Unique<T = number> = {
11
+ id: T;
12
+ };
13
+ export type IdName<T = number> = {
14
+ name: string;
15
+ } & Unique<T>;
16
+ export enum Type {
17
+ string = "string",
18
+ number = "number",
19
+ bigint = "bigint",
20
+ boolean = "boolean",
21
+ symbol = "symbol",
22
+ object = "object",
23
+ undefined = "undefined",
24
+ null = "null"
25
+ }
26
+ }
27
+ declare module "const/time-unit" {
28
+ export enum TimeUnit {
29
+ Year = 1,
30
+ Month = 2,
31
+ Day = 3,
32
+ Hour = 4,
33
+ Min = 5,
34
+ Sec = 6,
35
+ Msec = 7
36
+ }
37
+ }
38
+ declare module "const/gender" {
39
+ export enum Gender {
40
+ Male = 0,
41
+ Female = 1
42
+ }
43
+ }
44
+ declare module "const/http-method" {
45
+ export enum HttpMethod {
46
+ Get = "GET",
47
+ Put = "PUT",
48
+ Post = "POST",
49
+ Delete = "DELETE",
50
+ Patch = "PATCH",
51
+ Connect = "CONNECT"
52
+ }
53
+ }
54
+ declare module "const/ccy" {
55
+ export interface Ccy {
56
+ symbol: t_ccySymbol;
57
+ crossUsd: string;
58
+ }
59
+ export type t_ccySymbol = keyof (typeof currencies);
60
+ const currencies: {
61
+ jpy: Ccy;
62
+ usd: Ccy;
63
+ gbp: Ccy;
64
+ eur: Ccy;
65
+ cad: Ccy;
66
+ aud: Ccy;
67
+ };
68
+ export const s_ccy: {
69
+ [k in t_ccySymbol]: Readonly<Ccy>;
70
+ };
71
+ export function resolveCcy(str: string): Ccy;
72
+ }
73
+ declare module "obj/xjs-err" {
74
+ export class XjsErr extends Error {
75
+ code: number;
76
+ origin?: any;
77
+ constructor(code: number, msg: string, origin?: any);
78
+ }
79
+ }
80
+ declare module "func/u" {
81
+ import { Loggable } from "const/types";
82
+ export function getJSTDate(d?: Date): Date;
83
+ export function delay(sec: number): Promise<void>;
84
+ export function int2array(size: number): number[];
85
+ export function array2map<K, T>(array: T[], keyGen: (e: T) => K): Map<K, T[]>;
86
+ export function bitor(...bit: number[]): number;
87
+ export interface RetryOption<T = void | Promise<void>> {
88
+ count?: number;
89
+ logger?: Loggable;
90
+ errorCriterion?: (e: any) => boolean;
91
+ intervalPredicate?: () => T;
92
+ }
93
+ /**
94
+ * runs callback with customizable retry.
95
+ * @param cb callback to be retried.
96
+ * @param op.count number of retries. default is 1.
97
+ * @param op.logger logger used for exceptions while retrying the process. default is `console` object.
98
+ * @param op.errorCriterion distinguish whether retry is required form exceptions. default is none. (i.e. allways required.)
99
+ * @param op.intervalPredicate predicate that runs between callbacks when retrying.
100
+ */
101
+ export function retry<T>(cb: () => T, op?: RetryOption<void>): T;
102
+ export function retry<T>(cb: () => T, op?: RetryOption<Promise<void>>): Promise<T>;
103
+ export function retry<T>(cb: () => Promise<T>, op?: RetryOption<void>): Promise<T>;
104
+ export function retry<T>(cb: () => Promise<T>, op?: RetryOption<Promise<void>>): Promise<T>;
105
+ }
106
+ declare module "func/u-type" {
107
+ import { MaybeArray, Type } from "const/types";
108
+ export namespace UType {
109
+ function isDefined(v: any): boolean;
110
+ function isEmpty(v: any): boolean;
111
+ function isString(v: any): v is string;
112
+ function isNumber(v: any): v is number;
113
+ function isBigint(v: any): v is bigint;
114
+ function isBoolean(v: any): v is boolean;
115
+ function isSymbol(v: any): v is symbol;
116
+ function isObject(v: any): v is object;
117
+ function isArray(v: any, t: Type.string): v is string[];
118
+ function isArray(v: any, t: Type.number): v is number[];
119
+ function isArray(v: any, t: Type.bigint): v is bigint[];
120
+ function isArray(v: any, t: Type.boolean): v is boolean[];
121
+ function isArray(v: any, t: Type.symbol): v is symbol[];
122
+ function isArray(v: any, t: Type.object): v is object[];
123
+ function isArray(v: any): v is any[];
124
+ /**
125
+ * validate properties which attached decorators in {@link DType}.
126
+ * @param o object to be validated.
127
+ * @returns invalid property keys. returns an empty array if `o` is valid.
128
+ */
129
+ function validate(o: any): string[];
130
+ function takeAsArray<T>(v: MaybeArray<T>): T[];
131
+ }
132
+ }
133
+ declare module "func/decorator/d-type" {
134
+ import { Type } from "const/types";
135
+ export const smbl_tm: unique symbol;
136
+ export interface TypeDesc {
137
+ t?: Type;
138
+ req?: boolean;
139
+ ary?: TypeDesc;
140
+ rec?: boolean;
141
+ }
142
+ export interface TypeMap {
143
+ [k: string]: TypeDesc;
144
+ }
145
+ /**
146
+ * decorators to be validated by {@link UType.validate},
147
+ * and to be cropped by {@link UObj.crop}.
148
+ */
149
+ export namespace DType {
150
+ function string(target: Object, propKey: string): void;
151
+ function number(target: Object, propKey: string): void;
152
+ function boolean(target: Object, propKey: string): void;
153
+ function required(target: Object, propKey: string): void;
154
+ function array(elmDesc?: TypeDesc): (target: Object, propKey: string) => void;
155
+ function recursive(target: Object, propKey: string): void;
156
+ function keep(target: Object, propKey: string): void;
157
+ }
158
+ }
159
+ declare module "func/u-obj" {
160
+ import { NormalRecord } from "const/types";
161
+ export namespace UObj {
162
+ /**
163
+ * assign properties to the object with specified property keys.
164
+ * @param t target object.
165
+ * @param s source object.
166
+ * @param keys property keys which are copied from source object. if omit this, all keys in source object is applied.
167
+ * @param keepDtypeClass if true, class which has properties decorated with {@link DType} in target object is kept and that is assigned properties recursively.
168
+ */
169
+ function assignProperties<T extends NormalRecord, S extends NormalRecord>(t: T, s: S, keys?: (keyof S)[], keepDtypeClass?: boolean): T & Partial<S>;
170
+ /**
171
+ * crop properties of the object. the properties is removed with `delete` operator.
172
+ * @param o object which properties is removed.
173
+ * @param keys property names to be remained. if omit this, it removes the properties other than properties decorated {@link DType}.
174
+ * @param exclusive if true, it removes `keys` instead of remaining it.
175
+ */
176
+ function crop<T extends NormalRecord>(o: T, keys?: (keyof T)[], exclusive?: boolean): Partial<T>;
177
+ }
178
+ }
179
+ declare module "func/u-string" {
180
+ import { TimeUnit } from "const/time-unit";
181
+ export namespace UString {
182
+ function eq(s1: string, s2: string): boolean;
183
+ function repeat(token: string, mlt: number): string;
184
+ /**
185
+ * generate date time number as fixed length (depends on `unit`) string without separator charactor.
186
+ * For example, `2025-06-08T10:15:06.366Z` is to be `20250608101506366`.
187
+ * @param op.date Date object refered by this. default is `new Date()`.
188
+ * @param op.unit time unit. default is secound.
189
+ */
190
+ function simpleTime(op?: {
191
+ date?: Date;
192
+ unit?: TimeUnit;
193
+ }): string;
194
+ function generateRandomString(len: number): string;
195
+ function idx2az(idx: number): string;
196
+ function az2idx(az: string): number;
197
+ function asJpy(amount: number): string;
198
+ function asUsd(amount: number): string;
199
+ function asPercentage(amount: number): string;
200
+ function is_yyyy(v: string): boolean;
201
+ function is_yyyyMM(v: string): boolean;
202
+ function is_yyyyMMdd(v: string): boolean;
203
+ function is_yyyyMMddhh(v: string): boolean;
204
+ function is_yyyyMMddhhmm(v: string): boolean;
205
+ function is_yyyyMMddhhmmss(v: string): boolean;
206
+ }
207
+ }
208
+ declare module "func/u-array" {
209
+ export namespace UArray {
210
+ /**
211
+ * compares two arrays to valuate equality.
212
+ * if one side is null or undefined, it returns true when other side is the same.
213
+ * @param v1 it uses equal operator for comparing elements, so applying object element is not recommended.
214
+ * @param v2 same as v1.
215
+ * @param sort it uses {@link Array#sort} on v1 and v2 if true. default is true.
216
+ * @param useStrictEqual it uses `===` operator for compareing elements if true, otherwise using `==` operator. default is true.
217
+ */
218
+ function eq(v1: any[], v2: any[], op: {
219
+ sort?: boolean;
220
+ useStrictEqual: false;
221
+ }): boolean;
222
+ function eq<T>(v1: T[], v2: T[], op: {
223
+ sort?: boolean;
224
+ useStrictEqual: true;
225
+ }): boolean;
226
+ function eq<T>(v1: T[], v2: T[], op: {
227
+ sort?: boolean;
228
+ }): boolean;
229
+ function eq<T>(v1: T[], v2: T[]): boolean;
230
+ /**
231
+ * returns array which is removed duplicate of elements.
232
+ * this doesn't mutate the param.
233
+ */
234
+ function distinct<T>(array: T[]): T[];
235
+ function distinct<T>(array: T[], op: {
236
+ k: keyof T;
237
+ takeLast?: boolean;
238
+ }): T[];
239
+ function distinct<T>(array: T[], op: {
240
+ predicate: (v1: T, v2: T) => boolean;
241
+ takeLast?: boolean;
242
+ }): T[];
243
+ function chop<T>(array: T[], len: number): T[][];
244
+ function remove<T>(array: T[], v: T): void;
245
+ function randomPick<T>(array: T[], takeout?: boolean): T;
246
+ function shuffle<T>(array: T[]): T[];
247
+ function takeOut<T>(array: T[], filter: (v: T, i?: number) => boolean): T[];
248
+ }
249
+ }
250
+ declare module "func/u-http" {
251
+ export namespace UHttp {
252
+ function isHttpSuccess(statusCode: number): boolean;
253
+ function statusCategoryOf(statusCode: number): number;
254
+ function concatParamsWithEncoding(end: string, params: {
255
+ [k: string]: string | string[];
256
+ }): string;
257
+ /** normalize object keys to lower case. */
258
+ function normalizeHeaders(headers: Record<string, any>): Record<string, any>;
259
+ }
260
+ }
261
+ declare module "func/decorator/transaction" {
262
+ /**
263
+ * applies transation to the method. note that the method must return a Promise.
264
+ * @param op.timeoutSec default is `30`.
265
+ */
266
+ export function transaction(op?: {
267
+ timeoutSec?: number;
268
+ }): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => void;
269
+ }
270
+ declare module "xjs-common" {
271
+ export * from "const/types";
272
+ export * from "const/time-unit";
273
+ export * from "const/gender";
274
+ export * from "const/http-method";
275
+ export * from "const/ccy";
276
+ export * from "func/u";
277
+ export * from "func/u-obj";
278
+ export * from "func/u-string";
279
+ export * from "func/u-array";
280
+ export * from "func/u-http";
281
+ export * from "func/u-type";
282
+ export * from "func/decorator/transaction";
283
+ export { DType } from "func/decorator/d-type";
284
+ export * from "obj/xjs-err";
285
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xjs-common",
3
- "version": "10.1.3",
3
+ "version": "11.0.0-alpha.2",
4
4
  "description": "library modules for typescript that bundled general-purpose implementations.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -12,8 +12,9 @@
12
12
  "utility"
13
13
  ],
14
14
  "scripts": {
15
- "build": "tsc",
16
- "test": "node ./dist/test/test.js"
15
+ "build": "tsc && webpack && npm run build:types",
16
+ "build:types": "sh ./build-types.sh",
17
+ "test": "tsc -p ./tsconfig-test.json && node ./compiled/test/test.js"
17
18
  },
18
19
  "author": "begyyal",
19
20
  "license": "Apache-2.0",
@@ -22,9 +23,11 @@
22
23
  "!/dist/test*"
23
24
  ],
24
25
  "main": "./dist/index",
25
- "types": "./dist/index.d.ts",
26
+ "types": "./dist/types.d.ts",
26
27
  "devDependencies": {
27
- "ts-node": "^10.9.1",
28
- "typescript": "^4.9.5"
28
+ "tsx": "^4.20.3",
29
+ "typescript": "^5.9.2",
30
+ "webpack": "^5.101.0",
31
+ "webpack-cli": "^6.0.1"
29
32
  }
30
- }
33
+ }
@@ -1,18 +0,0 @@
1
- export interface Ccy {
2
- symbol: t_ccySymbol;
3
- crossUsd: string;
4
- }
5
- export type t_ccySymbol = keyof (typeof currencies);
6
- declare const currencies: {
7
- jpy: Ccy;
8
- usd: Ccy;
9
- gbp: Ccy;
10
- eur: Ccy;
11
- cad: Ccy;
12
- aud: Ccy;
13
- };
14
- export declare const s_ccy: {
15
- [k in t_ccySymbol]: Readonly<Ccy>;
16
- };
17
- export declare function resolveCcy(str: string): Ccy;
18
- export {};
package/dist/const/ccy.js DELETED
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveCcy = exports.s_ccy = void 0;
4
- const currencies = {
5
- jpy: { crossUsd: "usd/jpy" },
6
- usd: { crossUsd: null },
7
- gbp: { crossUsd: "gbp/usd" },
8
- eur: { crossUsd: "eur/usd" },
9
- cad: { crossUsd: "cad/usd" },
10
- aud: { crossUsd: "aud/usd" }
11
- };
12
- exports.s_ccy = (() => {
13
- Object.entries(currencies).forEach(kv => { kv[1].symbol = kv[0]; currencies[kv[0]] = Object.freeze(kv[1]); });
14
- return Object.freeze(currencies);
15
- })();
16
- function resolveCcy(str) {
17
- const ccyKey = Object.keys(exports.s_ccy).find(k => str?.toLowerCase() == k);
18
- return ccyKey && exports.s_ccy[ccyKey];
19
- }
20
- exports.resolveCcy = resolveCcy;
@@ -1,4 +0,0 @@
1
- export declare enum Gender {
2
- Male = 0,
3
- Female = 1
4
- }
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Gender = void 0;
4
- var Gender;
5
- (function (Gender) {
6
- Gender[Gender["Male"] = 0] = "Male";
7
- Gender[Gender["Female"] = 1] = "Female";
8
- })(Gender = exports.Gender || (exports.Gender = {}));
@@ -1,8 +0,0 @@
1
- export declare enum HttpMethod {
2
- Get = "GET",
3
- Put = "PUT",
4
- Post = "POST",
5
- Delete = "DELETE",
6
- Patch = "PATCH",
7
- Connect = "CONNECT"
8
- }
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpMethod = void 0;
4
- var HttpMethod;
5
- (function (HttpMethod) {
6
- HttpMethod["Get"] = "GET";
7
- HttpMethod["Put"] = "PUT";
8
- HttpMethod["Post"] = "POST";
9
- HttpMethod["Delete"] = "DELETE";
10
- HttpMethod["Patch"] = "PATCH";
11
- HttpMethod["Connect"] = "CONNECT";
12
- })(HttpMethod = exports.HttpMethod || (exports.HttpMethod = {}));
@@ -1,9 +0,0 @@
1
- export declare enum TimeUnit {
2
- Year = 1,
3
- Month = 2,
4
- Day = 3,
5
- Hour = 4,
6
- Min = 5,
7
- Sec = 6,
8
- Msec = 7
9
- }
@@ -1,13 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TimeUnit = void 0;
4
- var TimeUnit;
5
- (function (TimeUnit) {
6
- TimeUnit[TimeUnit["Year"] = 1] = "Year";
7
- TimeUnit[TimeUnit["Month"] = 2] = "Month";
8
- TimeUnit[TimeUnit["Day"] = 3] = "Day";
9
- TimeUnit[TimeUnit["Hour"] = 4] = "Hour";
10
- TimeUnit[TimeUnit["Min"] = 5] = "Min";
11
- TimeUnit[TimeUnit["Sec"] = 6] = "Sec";
12
- TimeUnit[TimeUnit["Msec"] = 7] = "Msec";
13
- })(TimeUnit = exports.TimeUnit || (exports.TimeUnit = {}));
@@ -1,24 +0,0 @@
1
- export type IndexSignature = string | number | symbol;
2
- export type NormalRecord = Record<IndexSignature, any>;
3
- export type MaybeArray<T> = T | T[];
4
- export type Loggable = {
5
- log: (msg: any) => void;
6
- warn: (msg: any) => void;
7
- error: (msg: any) => void;
8
- };
9
- export type Unique<T = number> = {
10
- id: T;
11
- };
12
- export type IdName<T = number> = {
13
- name: string;
14
- } & Unique<T>;
15
- export declare enum Type {
16
- string = "string",
17
- number = "number",
18
- bigint = "bigint",
19
- boolean = "boolean",
20
- symbol = "symbol",
21
- object = "object",
22
- undefined = "undefined",
23
- null = "null"
24
- }
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Type = void 0;
4
- var Type;
5
- (function (Type) {
6
- Type["string"] = "string";
7
- Type["number"] = "number";
8
- Type["bigint"] = "bigint";
9
- Type["boolean"] = "boolean";
10
- Type["symbol"] = "symbol";
11
- Type["object"] = "object";
12
- Type["undefined"] = "undefined";
13
- Type["null"] = "null";
14
- })(Type = exports.Type || (exports.Type = {}));
@@ -1,24 +0,0 @@
1
- import { Type } from "../../const/types";
2
- export declare const smbl_tm: unique symbol;
3
- export interface TypeDesc {
4
- t?: Type;
5
- req?: boolean;
6
- ary?: TypeDesc;
7
- rec?: boolean;
8
- }
9
- export interface TypeMap {
10
- [k: string]: TypeDesc;
11
- }
12
- /**
13
- * decorators to be validated by {@link UType.validate},
14
- * and to be cropped by {@link UObj.crop}.
15
- */
16
- export declare namespace DType {
17
- function string(target: Object, propKey: string): void;
18
- function number(target: Object, propKey: string): void;
19
- function boolean(target: Object, propKey: string): void;
20
- function required(target: Object, propKey: string): void;
21
- function array(elmDesc?: TypeDesc): (target: Object, propKey: string) => void;
22
- function recursive(target: Object, propKey: string): void;
23
- function keep(target: Object, propKey: string): void;
24
- }
@@ -1,71 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DType = exports.smbl_tm = void 0;
4
- const types_1 = require("../../const/types");
5
- const xjs_err_1 = require("../../obj/xjs-err");
6
- const s_errCode = 30;
7
- exports.smbl_tm = Symbol.for("xjs:typeMap");
8
- /**
9
- * decorators to be validated by {@link UType.validate},
10
- * and to be cropped by {@link UObj.crop}.
11
- */
12
- var DType;
13
- (function (DType) {
14
- function string(target, propKey) {
15
- setTypeDesc(target, propKey, types_1.Type.string);
16
- }
17
- DType.string = string;
18
- function number(target, propKey) {
19
- setTypeDesc(target, propKey, types_1.Type.number);
20
- }
21
- DType.number = number;
22
- function boolean(target, propKey) {
23
- setTypeDesc(target, propKey, types_1.Type.boolean);
24
- }
25
- DType.boolean = boolean;
26
- function setTypeDesc(target, propKey, t) {
27
- setDesc(target, propKey, (td) => {
28
- if (td.t)
29
- throw new xjs_err_1.XjsErr(s_errCode, "decorator to express type is duplicate.");
30
- td.t = t;
31
- });
32
- }
33
- function required(target, propKey) {
34
- setDesc(target, propKey, (td) => td.req = true);
35
- }
36
- DType.required = required;
37
- function array(elmDesc = {}) {
38
- return (target, propKey) => setDesc(target, propKey, (td) => td.ary = elmDesc);
39
- }
40
- DType.array = array;
41
- function recursive(target, propKey) {
42
- setDesc(target, propKey, (td) => td.rec = true);
43
- }
44
- DType.recursive = recursive;
45
- function keep(target, propKey) {
46
- setDesc(target, propKey, (_) => { });
47
- }
48
- DType.keep = keep;
49
- function setDesc(target, propKey, setter) {
50
- const map = target[exports.smbl_tm] ? Object.assign({}, target[exports.smbl_tm]) : {};
51
- map[propKey] ??= { t: null, req: false, rec: false, ary: null };
52
- const td = map[propKey];
53
- setter(td);
54
- let ex1 = null, ex2 = null;
55
- if (td.t && td.rec) {
56
- ex1 = "type";
57
- ex2 = "recursive flag";
58
- }
59
- if (td.t && td.ary) {
60
- ex1 = "type";
61
- ex2 = "array";
62
- }
63
- if (td.ary && td.rec) {
64
- ex1 = "array";
65
- ex2 = "recursive flag";
66
- }
67
- if (ex1 && ex2)
68
- throw new xjs_err_1.XjsErr(s_errCode, `decorator to express ${ex1} and ${ex2} are exclusive.`);
69
- Object.defineProperty(target, exports.smbl_tm, { value: map, configurable: true });
70
- }
71
- })(DType = exports.DType || (exports.DType = {}));
@@ -1,7 +0,0 @@
1
- /**
2
- * applies transation to the method. note that the method must return a Promise.
3
- * @param op.timeoutSec default is `30`.
4
- */
5
- export declare function transaction(op?: {
6
- timeoutSec?: number;
7
- }): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => void;
@@ -1,36 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.transaction = void 0;
4
- const xjs_err_1 = require("../../obj/xjs-err");
5
- const u_1 = require("../u");
6
- const s_errCode = 100;
7
- /**
8
- * applies transation to the method. note that the method must return a Promise.
9
- * @param op.timeoutSec default is `30`.
10
- */
11
- function transaction(op) {
12
- let lock = 0;
13
- const timeoutSec = op?.timeoutSec ?? 30;
14
- return (target, propertyKey, descriptor) => {
15
- const method = descriptor.value;
16
- async function exe(...p) {
17
- const timelimit = Date.now() + timeoutSec * 1000;
18
- while (lock > 0) {
19
- if (timelimit <= Date.now())
20
- throw new xjs_err_1.XjsErr(s_errCode, "An exclusive process to execute was already running by other request.");
21
- await (0, u_1.delay)(1);
22
- }
23
- try {
24
- lock++;
25
- const ret = method.apply(this, p);
26
- return ret instanceof Promise ? await ret : ret;
27
- }
28
- finally {
29
- lock--;
30
- }
31
- }
32
- ;
33
- descriptor.value = exe;
34
- };
35
- }
36
- exports.transaction = transaction;
@@ -1,40 +0,0 @@
1
- export declare namespace UArray {
2
- /**
3
- * compares two arrays to valuate equality.
4
- * if one side is null or undefined, it returns true when other side is the same.
5
- * @param v1 it uses equal operator for comparing elements, so applying object element is not recommended.
6
- * @param v2 same as v1.
7
- * @param sort it uses {@link Array#sort} on v1 and v2 if true. default is true.
8
- * @param useStrictEqual it uses `===` operator for compareing elements if true, otherwise using `==` operator. default is true.
9
- */
10
- function eq(v1: any[], v2: any[], op: {
11
- sort?: boolean;
12
- useStrictEqual: false;
13
- }): boolean;
14
- function eq<T>(v1: T[], v2: T[], op: {
15
- sort?: boolean;
16
- useStrictEqual: true;
17
- }): boolean;
18
- function eq<T>(v1: T[], v2: T[], op: {
19
- sort?: boolean;
20
- }): boolean;
21
- function eq<T>(v1: T[], v2: T[]): boolean;
22
- /**
23
- * returns array which is removed duplicate of elements.
24
- * this doesn't mutate the param.
25
- */
26
- function distinct<T>(array: T[]): T[];
27
- function distinct<T>(array: T[], op: {
28
- k: keyof T;
29
- takeLast?: boolean;
30
- }): T[];
31
- function distinct<T>(array: T[], op: {
32
- predicate: (v1: T, v2: T) => boolean;
33
- takeLast?: boolean;
34
- }): T[];
35
- function chop<T>(array: T[], len: number): T[][];
36
- function remove<T>(array: T[], v: T): void;
37
- function randomPick<T>(array: T[], takeout?: boolean): T;
38
- function shuffle<T>(array: T[]): T[];
39
- function takeOut<T>(array: T[], filter: (v: T, i?: number) => boolean): T[];
40
- }
@@ -1,70 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UArray = void 0;
4
- const u_1 = require("./u");
5
- var UArray;
6
- (function (UArray) {
7
- function eq(v1, v2, op = {}) {
8
- const { sort, useStrictEqual } = Object.assign({ sort: true, useStrictEqual: true }, op);
9
- if (v1 && !v2 || !v1 && v2)
10
- return false;
11
- if (!v1)
12
- return true;
13
- if (v1.length !== v2.length)
14
- return false;
15
- const a = sort ? [...v1].sort() : v1, b = sort ? [...v2].sort() : v2;
16
- return a.every((v, i) => useStrictEqual ? v === b[i] : v == b[i]);
17
- }
18
- UArray.eq = eq;
19
- function distinct(array, op) {
20
- if (!array || array.length === 0)
21
- return [];
22
- if (op?.k)
23
- return Array.from((0, u_1.array2map)(array, e => e[op.k]).values()).map(a => op?.takeLast ? a.pop() : a.shift());
24
- const a = op?.takeLast ? [...array].reverse() : [...array];
25
- const p = op?.predicate ?? ((v1, v2) => v1 == v2);
26
- const result = [a.shift()];
27
- a.forEach(v => result.some(v2 => p(v, v2)) ? {} : result.push(v));
28
- return result;
29
- }
30
- UArray.distinct = distinct;
31
- function chop(array, len) {
32
- return [...Array(Math.ceil(array.length / len)).keys()]
33
- .map(i => {
34
- let endIdx = (i + 1) * len;
35
- if (endIdx > array.length)
36
- endIdx = array.length;
37
- return array.slice(i * len, endIdx);
38
- });
39
- }
40
- UArray.chop = chop;
41
- function remove(array, v) {
42
- const idx = array.indexOf(v);
43
- if (idx !== -1)
44
- array.splice(idx, 1);
45
- }
46
- UArray.remove = remove;
47
- function randomPick(array, takeout = true) {
48
- const i = Math.floor(array.length * Math.random());
49
- const r = array[i];
50
- if (takeout)
51
- array.splice(i, 1);
52
- return r;
53
- }
54
- UArray.randomPick = randomPick;
55
- function shuffle(array) {
56
- const cp = [...array];
57
- return (0, u_1.int2array)(array.length).map(_ => randomPick(cp));
58
- }
59
- UArray.shuffle = shuffle;
60
- function takeOut(array, filter) {
61
- const result = [];
62
- for (let i = array.length - 1; i >= 0; i--)
63
- if (filter(array[i], i)) {
64
- result.unshift(array[i]);
65
- array.splice(i, 1);
66
- }
67
- return result;
68
- }
69
- UArray.takeOut = takeOut;
70
- })(UArray = exports.UArray || (exports.UArray = {}));
@@ -1,9 +0,0 @@
1
- export declare namespace UHttp {
2
- function isHttpSuccess(statusCode: number): boolean;
3
- function statusCategoryOf(statusCode: number): number;
4
- function concatParamsWithEncoding(end: string, params: {
5
- [k: string]: string | string[];
6
- }): string;
7
- /** normalize object keys to lower case. */
8
- function normalizeHeaders(headers: Record<string, any>): Record<string, any>;
9
- }
@@ -1,32 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UHttp = void 0;
4
- var UHttp;
5
- (function (UHttp) {
6
- function isHttpSuccess(statusCode) {
7
- return statusCategoryOf(statusCode) === 2;
8
- }
9
- UHttp.isHttpSuccess = isHttpSuccess;
10
- function statusCategoryOf(statusCode) {
11
- return Math.floor(statusCode / 100);
12
- }
13
- UHttp.statusCategoryOf = statusCategoryOf;
14
- function concatParamsWithEncoding(end, params) {
15
- if (!params || Object.keys(params).length === 0)
16
- return end;
17
- const paramsFlatten = Object.entries(params)
18
- .flatMap(kv => Array.isArray(kv[1]) ? kv[1].map(v => [kv[0], v]) : [kv]);
19
- let result = end ? end + "?" : "";
20
- for (var kv of paramsFlatten)
21
- result += kv[0] + "=" + encodeURIComponent(kv[1]) + "&";
22
- return result.substring(0, result.length - 1);
23
- }
24
- UHttp.concatParamsWithEncoding = concatParamsWithEncoding;
25
- /** normalize object keys to lower case. */
26
- function normalizeHeaders(headers) {
27
- if (!headers)
28
- return {};
29
- return Object.entries(headers).reduce((a, b) => { a[b[0].toLowerCase()] = b[1]; return a; }, {});
30
- }
31
- UHttp.normalizeHeaders = normalizeHeaders;
32
- })(UHttp = exports.UHttp || (exports.UHttp = {}));
@@ -1,18 +0,0 @@
1
- import { NormalRecord } from "../const/types";
2
- export declare namespace UObj {
3
- /**
4
- * assign properties to the object with specified property keys.
5
- * @param t target object.
6
- * @param s source object.
7
- * @param keys property keys which are copied from source object. if omit this, all keys in source object is applied.
8
- * @param keepDtypeClass if true, class which has properties decorated with {@link DType} in target object is kept and that is assigned properties recursively.
9
- */
10
- function assignProperties<T extends NormalRecord, S extends NormalRecord>(t: T, s: S, keys?: (keyof S)[], keepDtypeClass?: boolean): T & Partial<S>;
11
- /**
12
- * crop properties of the object. the properties is removed with `delete` operator.
13
- * @param o object which properties is removed.
14
- * @param keys property names to be remained. if omit this, it removes the properties other than properties decorated {@link DType}.
15
- * @param exclusive if true, it removes `keys` instead of remaining it.
16
- */
17
- function crop<T extends NormalRecord>(o: T, keys?: (keyof T)[], exclusive?: boolean): Partial<T>;
18
- }
@@ -1,44 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UObj = void 0;
4
- const d_type_1 = require("./decorator/d-type");
5
- const u_type_1 = require("./u-type");
6
- var UObj;
7
- (function (UObj) {
8
- /**
9
- * assign properties to the object with specified property keys.
10
- * @param t target object.
11
- * @param s source object.
12
- * @param keys property keys which are copied from source object. if omit this, all keys in source object is applied.
13
- * @param keepDtypeClass if true, class which has properties decorated with {@link DType} in target object is kept and that is assigned properties recursively.
14
- */
15
- function assignProperties(t, s, keys, keepDtypeClass) {
16
- for (const k of keys ?? Object.keys(s))
17
- if (u_type_1.UType.isDefined(s[k]))
18
- if (keepDtypeClass && u_type_1.UType.isObject(t[k]) && u_type_1.UType.isObject(s[k]) && t[k]?.[d_type_1.smbl_tm]) {
19
- assignProperties(t[k], s[k], null, true);
20
- }
21
- else
22
- t[k] = s[k];
23
- return t;
24
- }
25
- UObj.assignProperties = assignProperties;
26
- /**
27
- * crop properties of the object. the properties is removed with `delete` operator.
28
- * @param o object which properties is removed.
29
- * @param keys property names to be remained. if omit this, it removes the properties other than properties decorated {@link DType}.
30
- * @param exclusive if true, it removes `keys` instead of remaining it.
31
- */
32
- function crop(o, keys, exclusive) {
33
- if (!keys && !o[d_type_1.smbl_tm])
34
- return {};
35
- const _keys = keys ?? Object.keys(o[d_type_1.smbl_tm]);
36
- Object.keys(o).filter(k => {
37
- if (!keys && o[d_type_1.smbl_tm]?.[k]?.rec && o[k])
38
- crop(o[k]);
39
- return !!exclusive === _keys.includes(k);
40
- }).forEach(k => delete o[k]);
41
- return o;
42
- }
43
- UObj.crop = crop;
44
- })(UObj = exports.UObj || (exports.UObj = {}));
@@ -1,27 +0,0 @@
1
- import { TimeUnit } from "../const/time-unit";
2
- export declare namespace UString {
3
- function eq(s1: string, s2: string): boolean;
4
- function repeat(token: string, mlt: number): string;
5
- /**
6
- * generate date time number as fixed length (depends on `unit`) string without separator charactor.
7
- * For example, `2025-06-08T10:15:06.366Z` is to be `20250608101506366`.
8
- * @param op.date Date object refered by this. default is `new Date()`.
9
- * @param op.unit time unit. default is secound.
10
- */
11
- function simpleTime(op?: {
12
- date?: Date;
13
- unit?: TimeUnit;
14
- }): string;
15
- function generateRandomString(len: number): string;
16
- function idx2az(idx: number): string;
17
- function az2idx(az: string): number;
18
- function asJpy(amount: number): string;
19
- function asUsd(amount: number): string;
20
- function asPercentage(amount: number): string;
21
- function is_yyyy(v: string): boolean;
22
- function is_yyyyMM(v: string): boolean;
23
- function is_yyyyMMdd(v: string): boolean;
24
- function is_yyyyMMddhh(v: string): boolean;
25
- function is_yyyyMMddhhmm(v: string): boolean;
26
- function is_yyyyMMddhhmmss(v: string): boolean;
27
- }
@@ -1,120 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UString = void 0;
4
- const time_unit_1 = require("../const/time-unit");
5
- const xjs_err_1 = require("../obj/xjs-err");
6
- const u_1 = require("./u");
7
- const u_type_1 = require("./u-type");
8
- const s_errCode = 20;
9
- var UString;
10
- (function (UString) {
11
- function eq(s1, s2) {
12
- return !u_type_1.UType.isString(s1) || !u_type_1.UType.isString(s2) ? s1 === s2 : s1.trim() === s2.trim();
13
- }
14
- UString.eq = eq;
15
- function repeat(token, mlt) {
16
- return (0, u_1.int2array)(mlt).map(_ => token).join("");
17
- }
18
- UString.repeat = repeat;
19
- /**
20
- * generate date time number as fixed length (depends on `unit`) string without separator charactor.
21
- * For example, `2025-06-08T10:15:06.366Z` is to be `20250608101506366`.
22
- * @param op.date Date object refered by this. default is `new Date()`.
23
- * @param op.unit time unit. default is secound.
24
- */
25
- function simpleTime(op) {
26
- const t = (op?.date ?? new Date()).toISOString().split(".")[0].replace(/[-T:]/g, "");
27
- if (op?.unit === time_unit_1.TimeUnit.Msec)
28
- return t;
29
- return t.substring(0, 14 - (6 - (op?.unit ?? time_unit_1.TimeUnit.Sec)) * 2);
30
- }
31
- UString.simpleTime = simpleTime;
32
- function generateRandomString(len) {
33
- return (0, u_1.int2array)(len).map(_ => {
34
- let rnd = Math.floor(62 * Math.random());
35
- const remain = rnd - 52;
36
- if (remain >= 0)
37
- return remain.toString();
38
- if (rnd > 26)
39
- rnd += 6;
40
- return String.fromCharCode(rnd + 65);
41
- }).join("");
42
- }
43
- UString.generateRandomString = generateRandomString;
44
- function idx2az(idx) {
45
- let az = "", num = idx;
46
- while (num >= 0) {
47
- az = String.fromCharCode(num % 26 + 97) + az;
48
- num = Math.floor(num / 26) - 1;
49
- }
50
- return az.toUpperCase();
51
- }
52
- UString.idx2az = idx2az;
53
- function az2idx(az) {
54
- if (!az?.match(/^[a-zA-Z]+$/))
55
- throw new xjs_err_1.XjsErr(s_errCode, "the parameter isn't az(AZ) format.");
56
- return az.toLowerCase().split("").map(c => c.charCodeAt(0) - 97).reverse()
57
- .map((idx, i) => (idx + 1) * (26 ** i)).reduce((v1, v2) => v1 + v2) - 1;
58
- }
59
- UString.az2idx = az2idx;
60
- function asAmount(amount, unit) {
61
- const int2dec = amount.toString().split(".");
62
- const etni = int2dec[0].split("").reverse().join("");
63
- let fetni = "";
64
- const max = Math.ceil(etni.length / 3);
65
- for (let i = 0; i < max; i++) {
66
- if (i === max - 1)
67
- fetni += etni.substring(i * 3);
68
- else
69
- fetni += (etni.substring(i * 3, (i + 1) * 3) + ",");
70
- }
71
- const finte = unit + fetni.split("").reverse().join("");
72
- if (int2dec.length === 1)
73
- return finte;
74
- else
75
- return finte + "." + int2dec[1];
76
- }
77
- function asJpy(amount) {
78
- return u_type_1.UType.isEmpty(amount) ? "" : asAmount(Math.floor(amount), "¥");
79
- }
80
- UString.asJpy = asJpy;
81
- function asUsd(amount) {
82
- return u_type_1.UType.isEmpty(amount) ? "" : asAmount(Number(amount.toFixed(2)), "$");
83
- }
84
- UString.asUsd = asUsd;
85
- function asPercentage(amount) {
86
- if (u_type_1.UType.isEmpty(amount))
87
- return "";
88
- let percent = (amount * 100).toFixed(2);
89
- while (percent.endsWith("0"))
90
- percent = percent.substring(0, percent.length - 1);
91
- if (percent.endsWith("."))
92
- percent = percent.substring(0, percent.length - 1);
93
- return percent + "%";
94
- }
95
- UString.asPercentage = asPercentage;
96
- function is_yyyy(v) {
97
- return !!v?.match(/^[1-9]\d{3}$/);
98
- }
99
- UString.is_yyyy = is_yyyy;
100
- function is_yyyyMM(v) {
101
- return !!v?.match(/^[1-9]\d{3}(0[1-9]|1[0-2])$/);
102
- }
103
- UString.is_yyyyMM = is_yyyyMM;
104
- function is_yyyyMMdd(v) {
105
- return !!v?.match(/^[1-9]\d{3}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|[3][0-1])$/);
106
- }
107
- UString.is_yyyyMMdd = is_yyyyMMdd;
108
- function is_yyyyMMddhh(v) {
109
- return !!v?.match(/^[1-9]\d{3}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|[3][0-1])([01]\d|2[0-3])$/);
110
- }
111
- UString.is_yyyyMMddhh = is_yyyyMMddhh;
112
- function is_yyyyMMddhhmm(v) {
113
- return !!v?.match(/^[1-9]\d{3}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|[3][0-1])([01]\d|2[0-3])[0-5]\d$/);
114
- }
115
- UString.is_yyyyMMddhhmm = is_yyyyMMddhhmm;
116
- function is_yyyyMMddhhmmss(v) {
117
- return !!v?.match(/^[1-9]\d{3}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|[3][0-1])([01]\d|2[0-3])[0-5]\d[0-5]\d$/);
118
- }
119
- UString.is_yyyyMMddhhmmss = is_yyyyMMddhhmmss;
120
- })(UString = exports.UString || (exports.UString = {}));
@@ -1,25 +0,0 @@
1
- import { MaybeArray, Type } from "../const/types";
2
- export declare namespace UType {
3
- function isDefined(v: any): boolean;
4
- function isEmpty(v: any): boolean;
5
- function isString(v: any): v is string;
6
- function isNumber(v: any): v is number;
7
- function isBigint(v: any): v is bigint;
8
- function isBoolean(v: any): v is boolean;
9
- function isSymbol(v: any): v is symbol;
10
- function isObject(v: any): v is object;
11
- function isArray(v: any, t: Type.string): v is string[];
12
- function isArray(v: any, t: Type.number): v is number[];
13
- function isArray(v: any, t: Type.bigint): v is bigint[];
14
- function isArray(v: any, t: Type.boolean): v is boolean[];
15
- function isArray(v: any, t: Type.symbol): v is symbol[];
16
- function isArray(v: any, t: Type.object): v is object[];
17
- function isArray(v: any): v is any[];
18
- /**
19
- * validate properties which attached decorators in {@link DType}.
20
- * @param o object to be validated.
21
- * @returns invalid property keys. returns an empty array if `o` is valid.
22
- */
23
- function validate(o: any): string[];
24
- function takeAsArray<T>(v: MaybeArray<T>): T[];
25
- }
@@ -1,58 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UType = void 0;
4
- const types_1 = require("../const/types");
5
- const d_type_1 = require("./decorator/d-type");
6
- var UType;
7
- (function (UType) {
8
- function isDefined(v) {
9
- return typeof v !== types_1.Type.undefined;
10
- }
11
- UType.isDefined = isDefined;
12
- function isEmpty(v) {
13
- return v === null || typeof v === types_1.Type.undefined;
14
- }
15
- UType.isEmpty = isEmpty;
16
- function isString(v) { return typeof v === types_1.Type.string; }
17
- UType.isString = isString;
18
- function isNumber(v) { return typeof v === types_1.Type.number; }
19
- UType.isNumber = isNumber;
20
- function isBigint(v) { return typeof v === types_1.Type.bigint; }
21
- UType.isBigint = isBigint;
22
- function isBoolean(v) { return typeof v === types_1.Type.boolean; }
23
- UType.isBoolean = isBoolean;
24
- function isSymbol(v) { return typeof v === types_1.Type.symbol; }
25
- UType.isSymbol = isSymbol;
26
- function isObject(v) { return typeof v === types_1.Type.object; }
27
- UType.isObject = isObject;
28
- function isArray(v, t) {
29
- return Array.isArray(v) && (!t || v.every(e => typeof e === t));
30
- }
31
- UType.isArray = isArray;
32
- /**
33
- * validate properties which attached decorators in {@link DType}.
34
- * @param o object to be validated.
35
- * @returns invalid property keys. returns an empty array if `o` is valid.
36
- */
37
- function validate(o) {
38
- if (!o[d_type_1.smbl_tm])
39
- return [];
40
- return Object.entries(o[d_type_1.smbl_tm]).flatMap(e => validateProp(e[0], o[e[0]], e[1]));
41
- }
42
- UType.validate = validate;
43
- function validateProp(k, prop, td) {
44
- if (isEmpty(prop))
45
- return td.req ? [k] : [];
46
- if (td.t && typeof prop !== td.t)
47
- return [k];
48
- if (td.ary)
49
- return Array.isArray(prop) ? prop.flatMap(e => validateProp(k, e, td.ary)) : [k];
50
- if (td.rec)
51
- return validate(prop).flatMap(k2 => `${k}.${k2}`);
52
- return [];
53
- }
54
- function takeAsArray(v) {
55
- return Array.isArray(v) ? v : [v];
56
- }
57
- UType.takeAsArray = takeAsArray;
58
- })(UType = exports.UType || (exports.UType = {}));
package/dist/func/u.d.ts DELETED
@@ -1,24 +0,0 @@
1
- import { Loggable } from "../const/types";
2
- export declare function getJSTDate(d?: Date): Date;
3
- export declare function delay(sec: number): Promise<void>;
4
- export declare function int2array(size: number): number[];
5
- export declare function array2map<K, T>(array: T[], keyGen: (e: T) => K): Map<K, T[]>;
6
- export declare function bitor(...bit: number[]): number;
7
- export interface RetryOption<T = void | Promise<void>> {
8
- count?: number;
9
- logger?: Loggable;
10
- errorCriterion?: (e: any) => boolean;
11
- intervalPredicate?: () => T;
12
- }
13
- /**
14
- * runs callback with customizable retry.
15
- * @param cb callback to be retried.
16
- * @param op.count number of retries. default is 1.
17
- * @param op.logger logger used for exceptions while retrying the process. default is `console` object.
18
- * @param op.errorCriterion distinguish whether retry is required form exceptions. default is none. (i.e. allways required.)
19
- * @param op.intervalPredicate predicate that runs between callbacks when retrying.
20
- */
21
- export declare function retry<T>(cb: () => T, op?: RetryOption<void>): T;
22
- export declare function retry<T>(cb: () => T, op?: RetryOption<Promise<void>>): Promise<T>;
23
- export declare function retry<T>(cb: () => Promise<T>, op?: RetryOption<void>): Promise<T>;
24
- export declare function retry<T>(cb: () => Promise<T>, op?: RetryOption<Promise<void>>): Promise<T>;
package/dist/func/u.js DELETED
@@ -1,76 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.retry = exports.bitor = exports.array2map = exports.int2array = exports.delay = exports.getJSTDate = void 0;
4
- const xjs_err_1 = require("../obj/xjs-err");
5
- const s_errCode = 10;
6
- function getJSTDate(d) {
7
- return new Date((d ? d.getTime() : Date.now()) + 9 * 60 * 60 * 1000);
8
- }
9
- exports.getJSTDate = getJSTDate;
10
- function delay(sec) {
11
- return new Promise(resolve => setTimeout(resolve, 1000 * sec));
12
- }
13
- exports.delay = delay;
14
- function int2array(size) {
15
- const s = Number(size);
16
- if (Number.isNaN(s))
17
- throw new xjs_err_1.XjsErr(s_errCode, "size of the argument is not number.");
18
- return Array.from(Array(s).keys());
19
- }
20
- exports.int2array = int2array;
21
- function array2map(array, keyGen) {
22
- const map = new Map();
23
- for (const e of array) {
24
- const k = keyGen(e);
25
- if (map.has(k))
26
- map.get(k).push(e);
27
- else
28
- map.set(k, [e]);
29
- }
30
- return map;
31
- }
32
- exports.array2map = array2map;
33
- function bitor(...bit) {
34
- return bit.reduce((a, b) => a | b);
35
- }
36
- exports.bitor = bitor;
37
- ;
38
- function retry(cb, op) {
39
- const l = op?.logger ?? console;
40
- const initialCount = op?.count ?? 1;
41
- const handleError = (e) => {
42
- if (op?.errorCriterion && !op.errorCriterion(e))
43
- return false;
44
- l.warn(e);
45
- return true;
46
- };
47
- const prcs = (c) => {
48
- if (c < 0)
49
- throw new xjs_err_1.XjsErr(s_errCode, "failure exceeds retryable count.");
50
- let ret = null;
51
- const innerPrcs = () => {
52
- try {
53
- ret = cb();
54
- }
55
- catch (e) {
56
- if (handleError(e))
57
- ret = prcs(c - 1);
58
- else
59
- throw e;
60
- }
61
- if (ret instanceof Promise) {
62
- return new Promise((resolve, reject) => ret.then(resolve).catch((e) => { if (handleError(e))
63
- resolve(prcs(c - 1));
64
- else
65
- reject(e); }));
66
- }
67
- else
68
- return ret;
69
- };
70
- if (c < initialCount && op?.intervalPredicate)
71
- ret = op?.intervalPredicate();
72
- return ret instanceof Promise ? ret.then(() => innerPrcs()) : innerPrcs();
73
- };
74
- return prcs(initialCount);
75
- }
76
- exports.retry = retry;
package/dist/index.d.ts DELETED
@@ -1,14 +0,0 @@
1
- export * from "./const/types";
2
- export * from "./const/time-unit";
3
- export * from "./const/gender";
4
- export * from "./const/http-method";
5
- export * from "./const/ccy";
6
- export * from "./func/u";
7
- export * from "./func/u-obj";
8
- export * from "./func/u-string";
9
- export * from "./func/u-array";
10
- export * from "./func/u-http";
11
- export * from "./func/u-type";
12
- export * from "./func/decorator/transaction";
13
- export { DType } from "./func/decorator/d-type";
14
- export * from "./obj/xjs-err";
@@ -1,5 +0,0 @@
1
- export declare class XjsErr extends Error {
2
- code: number;
3
- origin?: any;
4
- constructor(code: number, msg: string, origin?: any);
5
- }
@@ -1,13 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.XjsErr = void 0;
4
- class XjsErr extends Error {
5
- code;
6
- origin;
7
- constructor(code, msg, origin) {
8
- super(`[XJS] ${msg}`);
9
- this.code = code;
10
- this.origin = origin;
11
- }
12
- }
13
- exports.XjsErr = XjsErr;