xjs-node 1.0.0 → 1.0.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.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export * from "./func/u";
2
2
  export * from "./func/u-file";
3
- export { HttpResolver } from "./prcs/http/http-resolver";
3
+ export { HttpResolver, ClientMode } from "./prcs/http/http-resolver";
4
4
  export { s_clientMode } from "./prcs/http/http-resolver-context";
5
5
  export { IHttpClient } from "./prcs/http/i-http-client";
@@ -64,7 +64,7 @@ const s_mode2headers = new Map([
64
64
  "Accept-Language": "en-US,en;q=0.9",
65
65
  "Sec-Ch-Ua": uad,
66
66
  "Sec-Ch-Ua-Mobile": "?0",
67
- "Sec-Ch-Ua-Platform": "Windows",
67
+ "Sec-Ch-Ua-Platform": '"Windows"',
68
68
  "Sec-Fetch-Dest": "document",
69
69
  "Sec-Fetch-Mode": "navigate",
70
70
  "Sec-Fetch-Site": "none",
@@ -4,7 +4,7 @@ exports.HttpResolver = void 0;
4
4
  const xjs_common_1 = require("xjs-common");
5
5
  const http_resolver_context_1 = require("./http-resolver-context");
6
6
  const s_cmvRange = 5;
7
- const s_defaultCmv = 137;
7
+ const s_defaultCmv = 138;
8
8
  class HttpResolver {
9
9
  _baseCmv;
10
10
  _l;
@@ -34,7 +34,7 @@ export interface HttpResponse {
34
34
  export interface IHttpClient {
35
35
  /**
36
36
  * request GET to the url with new context.
37
- * @param url target url.
37
+ * @param url target url. (currently https only)
38
38
  * @param op.headers http headers.
39
39
  * @param op.mode {@link s_clientMode} that is imitated. default is random between chrome or firefox.
40
40
  * @param op.proxy proxy configuration.
@@ -49,7 +49,7 @@ export interface IHttpClient {
49
49
  }): Promise<HttpResponse>;
50
50
  /**
51
51
  * request POST to the url with new context.
52
- * @param url target url.
52
+ * @param url target url. (currently https only)
53
53
  * @param payload request payload. if this is an object, it is treated as json.
54
54
  * @param op.headers http headers.
55
55
  * @param op.mode {@link s_clientMode} that is imitated. default is random between chrome or firefox.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xjs-node",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "library modules for nodejs + typescript that bundled general-purpose implementations.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,6 +29,6 @@
29
29
  "typescript": "^4.9.5"
30
30
  },
31
31
  "dependencies": {
32
- "xjs-common": "^10.0.0"
32
+ "xjs-common": "^10.1.0"
33
33
  }
34
34
  }
@@ -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,20 +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
- /** decorators to be validated by {@link UType.validate} */
13
- export declare namespace DValidate {
14
- function string(target: Object, propKey: string): void;
15
- function number(target: Object, propKey: string): void;
16
- function boolean(target: Object, propKey: string): void;
17
- function required(target: Object, propKey: string): void;
18
- function array(elmDesc?: TypeDesc): (target: Object, propKey: string) => void;
19
- function recursive(target: Object, propKey: string): void;
20
- }
@@ -1,64 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DValidate = 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("typeMap");
8
- /** decorators to be validated by {@link UType.validate} */
9
- var DValidate;
10
- (function (DValidate) {
11
- function string(target, propKey) {
12
- setTypeDesc(target, propKey, types_1.Type.string);
13
- }
14
- DValidate.string = string;
15
- function number(target, propKey) {
16
- setTypeDesc(target, propKey, types_1.Type.number);
17
- }
18
- DValidate.number = number;
19
- function boolean(target, propKey) {
20
- setTypeDesc(target, propKey, types_1.Type.boolean);
21
- }
22
- DValidate.boolean = boolean;
23
- function setTypeDesc(target, propKey, t) {
24
- setDesc(target, propKey, (td) => {
25
- if (td.t)
26
- throw new xjs_err_1.XjsErr(s_errCode, "decorator to express type is duplicate.");
27
- td.t = t;
28
- });
29
- }
30
- function required(target, propKey) {
31
- setDesc(target, propKey, (td) => td.req = true);
32
- }
33
- DValidate.required = required;
34
- function array(elmDesc = {}) {
35
- return (target, propKey) => setDesc(target, propKey, (td) => td.ary = elmDesc);
36
- }
37
- DValidate.array = array;
38
- function recursive(target, propKey) {
39
- setDesc(target, propKey, (td) => td.rec = true);
40
- }
41
- DValidate.recursive = recursive;
42
- function setDesc(target, propKey, setter) {
43
- const map = target[exports.smbl_tm] ?? {};
44
- map[propKey] ??= { t: null, req: false, rec: false, ary: null };
45
- const td = map[propKey];
46
- setter(td);
47
- let ex1 = null, ex2 = null;
48
- if (td.t && td.rec) {
49
- ex1 = "type";
50
- ex2 = "recursive flag";
51
- }
52
- if (td.t && td.ary) {
53
- ex1 = "type";
54
- ex2 = "array";
55
- }
56
- if (td.ary && td.rec) {
57
- ex1 = "array";
58
- ex2 = "recursive flag";
59
- }
60
- if (ex1 && ex2)
61
- throw new xjs_err_1.XjsErr(s_errCode, `decorator to express ${ex1} and ${ex2} are exclusive.`);
62
- Object.defineProperty(target, exports.smbl_tm, { value: map });
63
- }
64
- })(DValidate = exports.DValidate || (exports.DValidate = {}));
@@ -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,7 +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
- }
@@ -1,25 +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
- })(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,24 +0,0 @@
1
- import { TimeUnit } from "../const/time-unit";
2
- export declare namespace UString {
3
- function eq(s1: string, s2: string): boolean;
4
- /**
5
- * generate date time number as fixed length (depends on `unit`) string without separator charactor.
6
- * For example, `2025-06-08T10:15:06.366Z` is to be `20250608101506366`.
7
- * @param op.date Date object refered by this. default is `new Date()`.
8
- * @param op.unit time unit. default is secound.
9
- */
10
- function simpleTime(op?: {
11
- date?: Date;
12
- unit?: TimeUnit;
13
- }): string;
14
- function trimProps(obj: any): void;
15
- function generateRandomString(len: number): string;
16
- function idx2az(idx: number): string;
17
- function az2idx(az: string): number;
18
- function is_yyyy(v: string): boolean;
19
- function is_yyyyMM(v: string): boolean;
20
- function is_yyyyMMdd(v: string): boolean;
21
- function is_yyyyMMddhh(v: string): boolean;
22
- function is_yyyyMMddhhmm(v: string): boolean;
23
- function is_yyyyMMddhhmmss(v: string): boolean;
24
- }
@@ -1,86 +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
- /**
16
- * generate date time number as fixed length (depends on `unit`) string without separator charactor.
17
- * For example, `2025-06-08T10:15:06.366Z` is to be `20250608101506366`.
18
- * @param op.date Date object refered by this. default is `new Date()`.
19
- * @param op.unit time unit. default is secound.
20
- */
21
- function simpleTime(op) {
22
- const t = (op?.date ?? new Date()).toISOString().split(".")[0].replace(/[-T:]/g, "");
23
- if (op?.unit === time_unit_1.TimeUnit.Msec)
24
- return t;
25
- return t.substring(0, 14 - (6 - (op?.unit ?? time_unit_1.TimeUnit.Sec)) * 2);
26
- }
27
- UString.simpleTime = simpleTime;
28
- function trimProps(obj) {
29
- Object.keys(obj)
30
- .filter(k => typeof obj[k] === "string")
31
- .forEach(k => obj[k] = obj[k]?.trim());
32
- }
33
- UString.trimProps = trimProps;
34
- function generateRandomString(len) {
35
- return (0, u_1.int2array)(len).map(_ => {
36
- let rnd = Math.floor(62 * Math.random());
37
- const remain = rnd - 52;
38
- if (remain >= 0)
39
- return remain.toString();
40
- if (rnd > 26)
41
- rnd += 6;
42
- return String.fromCharCode(rnd + 65);
43
- }).join("");
44
- }
45
- UString.generateRandomString = generateRandomString;
46
- function idx2az(idx) {
47
- let az = "", num = idx;
48
- while (num >= 0) {
49
- az = String.fromCharCode(num % 26 + 97) + az;
50
- num = Math.floor(num / 26) - 1;
51
- }
52
- return az.toUpperCase();
53
- }
54
- UString.idx2az = idx2az;
55
- function az2idx(az) {
56
- if (!az?.match(/^[a-zA-Z]+$/))
57
- throw new xjs_err_1.XjsErr(s_errCode, "the parameter isn't az(AZ) format.");
58
- return az.toLowerCase().split("").map(c => c.charCodeAt(0) - 97).reverse()
59
- .map((idx, i) => (idx + 1) * (26 ** i)).reduce((v1, v2) => v1 + v2) - 1;
60
- }
61
- UString.az2idx = az2idx;
62
- function is_yyyy(v) {
63
- return !!v?.match(/^[1-9]\d{3}$/);
64
- }
65
- UString.is_yyyy = is_yyyy;
66
- function is_yyyyMM(v) {
67
- return !!v?.match(/^[1-9]\d{3}(0[1-9]|1[0-2])$/);
68
- }
69
- UString.is_yyyyMM = is_yyyyMM;
70
- function is_yyyyMMdd(v) {
71
- return !!v?.match(/^[1-9]\d{3}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|[3][0-1])$/);
72
- }
73
- UString.is_yyyyMMdd = is_yyyyMMdd;
74
- function is_yyyyMMddhh(v) {
75
- 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])$/);
76
- }
77
- UString.is_yyyyMMddhh = is_yyyyMMddhh;
78
- function is_yyyyMMddhhmm(v) {
79
- 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$/);
80
- }
81
- UString.is_yyyyMMddhhmm = is_yyyyMMddhhmm;
82
- function is_yyyyMMddhhmmss(v) {
83
- 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$/);
84
- }
85
- UString.is_yyyyMMddhhmmss = is_yyyyMMddhhmmss;
86
- })(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 = {}));
@@ -1,8 +0,0 @@
1
- import { Type } from "../const/types";
2
- export declare class TypeExp<T> {
3
- private t;
4
- private readonly _m;
5
- constructor(t: Type.string | Type.number | Type.bigint | Type.null | Type.symbol | Type.undefined);
6
- constructor(t: Type.object, model: any);
7
- match(o: any): o is T;
8
- }
@@ -1,23 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TypeExp = void 0;
4
- const types_1 = require("../const/types");
5
- class TypeExp {
6
- t;
7
- _m;
8
- constructor(t, model) {
9
- this.t = t;
10
- this._m = model;
11
- }
12
- match(o) {
13
- if (typeof o !== this.t)
14
- return false;
15
- if (this.t !== types_1.Type.object)
16
- return true;
17
- const isArray = Array.isArray(o);
18
- if (isArray !== Array.isArray(this._m))
19
- return false;
20
- return true;
21
- }
22
- }
23
- exports.TypeExp = TypeExp;
@@ -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;
@@ -1,53 +0,0 @@
1
- export declare const s_clientMode: Record<string, ClientMode>;
2
- interface ClientMode {
3
- id: number;
4
- cipherOrder: number[];
5
- }
6
- interface ProxyConfig {
7
- server: string;
8
- port: number;
9
- auth?: {
10
- name: string;
11
- pass: string;
12
- };
13
- }
14
- export declare class HttpResolver {
15
- private _baseCmv;
16
- private _l;
17
- private readonly _als;
18
- private readonly _mode2headers;
19
- /**
20
- * @param _baseCmv chrome major version refered when construct a user agent, and the version will be randomized between `n` to `n-4`.
21
- * @param _l custom logger. default is `console`.
22
- */
23
- constructor(_baseCmv: number, _l?: {
24
- log: (msg: any) => void;
25
- warn: (msg: any) => void;
26
- });
27
- /**
28
- * request to the url with GET.
29
- * @param url target url.
30
- * @param op.mode {@link s_clientMode} that is imitated. default is random between chrome or firefox.
31
- * @param op.proxy proxy configuration.
32
- * @param op.ignoreQuery if true, query part in the `url` is ignored.
33
- * @param op.redirectAsNewRequest handle redirect as new request. this may be efficient when using proxy which is implemented reverse proxy.
34
- * @returns string encoded by utf-8 as response payload.
35
- */
36
- get(url: string, op?: {
37
- mode?: ClientMode;
38
- ignoreQuery?: boolean;
39
- proxy?: ProxyConfig;
40
- redirectAsNewRequest?: boolean;
41
- }): Promise<any>;
42
- private fixCmv;
43
- private createProxyAgent;
44
- private getIn;
45
- private reqHttps;
46
- private handleRedirect;
47
- private createCiphers;
48
- private setCookies;
49
- private storeCookies;
50
- private log;
51
- private warn;
52
- }
53
- export {};
@@ -1,255 +0,0 @@
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.HttpResolver = exports.s_clientMode = void 0;
27
- const tls = __importStar(require("tls"));
28
- const zlib = __importStar(require("zlib"));
29
- const url_1 = require("url");
30
- const https_1 = require("https");
31
- const http_1 = require("http");
32
- const async_hooks_1 = require("async_hooks");
33
- const xjs_err_1 = require("../obj/xjs-err");
34
- const u_http_1 = require("../func/u-http");
35
- const u_array_1 = require("../func/u-array");
36
- exports.s_clientMode = {
37
- nodejs: { id: 0, cipherOrder: null },
38
- chrome: { id: 1, cipherOrder: [2, 0, 1] },
39
- firefox: { id: 2, cipherOrder: [2, 1, 0] }
40
- };
41
- const s_cmvRange = 5;
42
- const s_timeout = 1000 * 20;
43
- const s_errCode = 200;
44
- class HttpResolver {
45
- _baseCmv;
46
- _l;
47
- _als = new async_hooks_1.AsyncLocalStorage();
48
- _mode2headers = new Map([
49
- [exports.s_clientMode.firefox, (cmv) => ({
50
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
51
- "Accept-Encoding": "gzip, deflate, br",
52
- "Accept-Language": "en-US,en;q=0.5",
53
- "Sec-Fetch-Dest": "document",
54
- "Sec-Fetch-Mode": "navigate",
55
- "Sec-Fetch-Site": "none",
56
- "Sec-Fetch-User": "?1",
57
- "Upgrade-Insecure-Requests": "1",
58
- "User-Agent": `Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:${cmv}.0) Gecko/20100101 Firefox/${cmv}.0`
59
- })],
60
- [exports.s_clientMode.chrome, (cmv) => {
61
- const uad = cmv < 130
62
- ? `"Not/A)Brand";v="8", "Chromium";v="${cmv}", "Google Chrome";v="${cmv}"`
63
- : `"Chromium";v="${cmv}", "Not:A-Brand";v="24", "Google Chrome";v="${cmv}"`;
64
- const ch = {
65
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
66
- "Accept-Encoding": "gzip, deflate, br, zstd",
67
- "Accept-Language": "en-US,en;q=0.9",
68
- "Sec-Ch-Ua": uad,
69
- "Sec-Ch-Ua-Mobile": "?0",
70
- "Sec-Ch-Ua-Platform": "Windows",
71
- "Sec-Fetch-Dest": "document",
72
- "Sec-Fetch-Mode": "navigate",
73
- "Sec-Fetch-Site": "none",
74
- "Sec-Fetch-User": "?1",
75
- "Upgrade-Insecure-Requests": "1",
76
- "User-Agent": `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${cmv}.0.0.0 Safari/537.36`
77
- };
78
- if (cmv >= 124)
79
- ch["Priority"] = "u=0, i";
80
- return ch;
81
- }]
82
- ]);
83
- /**
84
- * @param _baseCmv chrome major version refered when construct a user agent, and the version will be randomized between `n` to `n-4`.
85
- * @param _l custom logger. default is `console`.
86
- */
87
- constructor(_baseCmv, _l = console) {
88
- this._baseCmv = _baseCmv;
89
- this._l = _l;
90
- }
91
- /**
92
- * request to the url with GET.
93
- * @param url target url.
94
- * @param op.mode {@link s_clientMode} that is imitated. default is random between chrome or firefox.
95
- * @param op.proxy proxy configuration.
96
- * @param op.ignoreQuery if true, query part in the `url` is ignored.
97
- * @param op.redirectAsNewRequest handle redirect as new request. this may be efficient when using proxy which is implemented reverse proxy.
98
- * @returns string encoded by utf-8 as response payload.
99
- */
100
- async get(url, op) {
101
- const cmv = this.fixCmv();
102
- const m = op?.mode ?? u_array_1.UArray.randomPick([exports.s_clientMode.chrome, exports.s_clientMode.firefox]);
103
- const ciphers = this.createCiphers(m);
104
- const u = new url_1.URL(url);
105
- const proxyAgent = op?.proxy && await this.createProxyAgent(u, op.proxy);
106
- this._l.log(`Starts to request with ${Object.keys(exports.s_clientMode).find((_, i) => i === m.id)}:${cmv}.`);
107
- const rc = {
108
- mode: m, cmv, ciphers,
109
- ignoreQuery: !!op?.ignoreQuery,
110
- redirectCount: 0, redirectAsNewRequest: !!op?.redirectAsNewRequest,
111
- proxyAgent, proxyConfig: op?.proxy
112
- };
113
- return await this._als.run(rc, this.getIn, u).finally(() => proxyAgent?.destroy());
114
- }
115
- fixCmv() {
116
- return this._baseCmv - Math.floor(Math.random() * s_cmvRange);
117
- }
118
- createProxyAgent(u, conf) {
119
- return new Promise((resolve, reject) => {
120
- const headers = {};
121
- if (conf.auth)
122
- headers['Proxy-Authorization'] = `Basic ${Buffer.from(conf.auth.name + ':' + conf.auth.pass).toString('base64')}`;
123
- const req = (0, http_1.request)({
124
- host: conf.server,
125
- port: conf.port,
126
- method: 'CONNECT',
127
- path: `${u.hostname}:443`,
128
- headers
129
- }).on('connect', (res, socket) => {
130
- if (res.statusCode === 200)
131
- resolve(new https_1.Agent({ socket, keepAlive: true }));
132
- else
133
- reject(new xjs_err_1.XjsErr(s_errCode, "Could not connect to proxy."));
134
- });
135
- req.on('error', reject);
136
- req.on('timeout', () => {
137
- req.destroy();
138
- reject(new xjs_err_1.XjsErr(s_errCode, "The http request timeout, maybe server did not respond."));
139
- });
140
- req.end();
141
- });
142
- }
143
- getIn = async (u) => {
144
- const params = {};
145
- const rc = this._als.getStore();
146
- const toRefresh = rc.redirectCount > 0 && rc.redirectAsNewRequest;
147
- params.method = "GET";
148
- params.protocol = u.protocol;
149
- params.host = u.host;
150
- params.path = (rc.ignoreQuery || !u.search) ? u.pathname : `${u.pathname}${u.search}`;
151
- params.agent = toRefresh ? await this.createProxyAgent(u, rc.proxyConfig) : rc.proxyAgent;
152
- if (toRefresh) {
153
- rc.cmv = this.fixCmv();
154
- rc.ciphers = this.createCiphers(rc.mode);
155
- }
156
- return await this.reqHttps(params, null);
157
- };
158
- reqHttps(params, postData) {
159
- params.timeout = s_timeout;
160
- const rc = this._als.getStore();
161
- if (rc.mode.id > 0) {
162
- params.ciphers = rc.ciphers;
163
- const chHeaders = this._mode2headers.get(rc.mode)(rc.cmv);
164
- params.headers = params.headers ? Object.assign(params.headers, chHeaders) : chHeaders;
165
- }
166
- if (rc.cookies && !rc.redirectAsNewRequest)
167
- this.setCookies(params.headers);
168
- return new Promise((resolve, reject) => {
169
- const req = (0, https_1.request)(params, (res) => {
170
- const sc = u_http_1.UHttp.statusCategoryOf(res.statusCode);
171
- if (sc === 3) {
172
- this.handleRedirect(res, params.host).then(resolve).catch(reject).finally(() => res.destroy());
173
- return;
174
- }
175
- const bfs = [];
176
- const contentEncofing = res.headers["content-encoding"]?.toLocaleLowerCase();
177
- res.on('data', chunk => bfs.push(chunk));
178
- res.on('end', () => {
179
- try {
180
- let retBuf = Buffer.concat(bfs);
181
- if (contentEncofing == "gzip")
182
- retBuf = zlib.gunzipSync(retBuf);
183
- else if (contentEncofing == "br")
184
- retBuf = zlib.brotliDecompressSync(retBuf);
185
- const data = retBuf.toString("utf8");
186
- if (sc !== 2) {
187
- if (data.trim())
188
- this.warn(data);
189
- reject(new xjs_err_1.XjsErr(s_errCode, `Https received a error status ${res.statusCode}`));
190
- }
191
- else
192
- resolve(data);
193
- }
194
- catch (e) {
195
- reject(e);
196
- }
197
- });
198
- });
199
- req.on('error', reject);
200
- req.on('timeout', () => {
201
- req.destroy();
202
- reject(new xjs_err_1.XjsErr(s_errCode, "The http request timeout, maybe server did not respond."));
203
- });
204
- if (postData)
205
- req.write(postData);
206
- req.end();
207
- });
208
- }
209
- handleRedirect(res, host) {
210
- const rc = this._als.getStore();
211
- if (!res.headers.location)
212
- throw new xjs_err_1.XjsErr(s_errCode, "Received http redirection, but no location header found.");
213
- if (rc.redirectCount++ > 2)
214
- throw new xjs_err_1.XjsErr(s_errCode, "Count of http redirection exceeds limit.");
215
- if (res.headers["set-cookie"] && !rc.redirectAsNewRequest)
216
- this.storeCookies(res.headers["set-cookie"]);
217
- this.log(`Redirect to ${res.headers.location}. (count is ${rc.redirectCount})`);
218
- const dest = res.headers.location.startsWith("http") ? res.headers.location : `https://${host}${res.headers.location}`;
219
- if (rc.redirectAsNewRequest)
220
- rc.proxyAgent?.destroy();
221
- return this.getIn(new url_1.URL(dest));
222
- }
223
- createCiphers(mode) {
224
- const defaultCiphers = tls.DEFAULT_CIPHERS.split(':');
225
- return [
226
- defaultCiphers[mode.cipherOrder[0]],
227
- defaultCiphers[mode.cipherOrder[1]],
228
- defaultCiphers[mode.cipherOrder[2]],
229
- ...u_array_1.UArray.shuffle(defaultCiphers.slice(3))
230
- ].join(':');
231
- }
232
- setCookies(headers) {
233
- const cks = this._als.getStore().cookies;
234
- headers.cookie = Object.keys(cks).map(ckk => `${ckk}=${cks[ckk]};`).join(" ");
235
- }
236
- storeCookies(cookies) {
237
- this._als.getStore().cookies ??= {};
238
- cookies.filter(c => c).flatMap(c => c.split(";"))
239
- .map(c => {
240
- const idx = c.indexOf("=");
241
- return idx !== -1 && [c.substring(0, idx).toLowerCase().trim(), c.substring(idx + 1)];
242
- })
243
- .filter(cp => cp && cp[0] && !["secure", "path", "domain", "samesite"].includes(cp[0]))
244
- .forEach(cp => this._als.getStore().cookies[cp[0]] = cp[1]);
245
- this.log("Store cookies from set-cookie headers.");
246
- this.log(JSON.stringify(this._als.getStore().cookies));
247
- }
248
- log(msg) {
249
- this._l.log(`[http-resolver] ${msg}`);
250
- }
251
- warn(msg) {
252
- this._l.warn(`[http-resolver] ${msg}`);
253
- }
254
- }
255
- exports.HttpResolver = HttpResolver;