@venizia/ignis-helpers 0.4.8-12 → 0.4.8-13
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/esm/common/types/field-mapping.d.ts +6 -6
- package/dist/esm/common/types/field-mapping.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.d.ts +1 -1
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +1 -1
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
- package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.d.ts +4 -4
- package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js +1 -1
- package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js.map +1 -1
- package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.d.ts +3 -3
- package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js.map +1 -1
- package/dist/esm/modules/socket/socket-io/client/browser-helper.js.map +1 -1
- package/dist/esm/modules/socket/socket-io/common/types/client.d.ts +2 -2
- package/dist/esm/modules/socket/socket-io/common/types/client.js.map +1 -1
- package/dist/esm/modules/socket/socket-io/common/types/server.d.ts +3 -1
- package/dist/esm/modules/socket/socket-io/common/types/server.js.map +1 -1
- package/dist/esm/modules/socket/socket-io/server/helper.d.ts +2 -2
- package/dist/esm/modules/socket/socket-io/server/helper.js.map +1 -1
- package/dist/esm/utilities/request.utility.d.ts +9 -11
- package/dist/esm/utilities/request.utility.js.map +1 -1
- package/package.json +1 -1
|
@@ -23,28 +23,28 @@ export type TFieldMappingNames<T extends Array<IFieldMapping>> = Extract<T[numbe
|
|
|
23
23
|
export type TObjectFromFieldMappings<T extends readonly {
|
|
24
24
|
name: string;
|
|
25
25
|
type: string;
|
|
26
|
-
[extra: string | symbol]:
|
|
26
|
+
[extra: string | symbol]: unknown;
|
|
27
27
|
}[]> = {
|
|
28
28
|
[K in T[number]['name']]: T extends {
|
|
29
29
|
name: K;
|
|
30
30
|
type: 'string';
|
|
31
|
-
[extra: string | symbol]:
|
|
31
|
+
[extra: string | symbol]: unknown;
|
|
32
32
|
} ? string : T extends {
|
|
33
33
|
name: K;
|
|
34
34
|
type: 'number';
|
|
35
|
-
[extra: string | symbol]:
|
|
35
|
+
[extra: string | symbol]: unknown;
|
|
36
36
|
} ? number : T extends {
|
|
37
37
|
name: K;
|
|
38
38
|
type: 'boolean';
|
|
39
|
-
[extra: string | symbol]:
|
|
39
|
+
[extra: string | symbol]: unknown;
|
|
40
40
|
} ? boolean : T extends {
|
|
41
41
|
name: K;
|
|
42
42
|
type: 'strings';
|
|
43
|
-
[extra: string | symbol]:
|
|
43
|
+
[extra: string | symbol]: unknown;
|
|
44
44
|
} ? string[] : T extends {
|
|
45
45
|
name: K;
|
|
46
46
|
type: 'numbers';
|
|
47
|
-
[extra: string | symbol]:
|
|
47
|
+
[extra: string | symbol]: unknown;
|
|
48
48
|
} ? number[] : never;
|
|
49
49
|
};
|
|
50
50
|
//# sourceMappingURL=field-mapping.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"field-mapping.js","sourceRoot":"","sources":["../../../../src/common/types/field-mapping.ts"],"names":[],"mappings":"AAEA,6CAA6C;AAC7C,MAAM,OAAO,qBAAqB;aAChB,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAClB,YAAO,GAAG,SAAS,CAAC;aACpB,YAAO,GAAG,SAAS,CAAC;aACpB,YAAO,GAAG,SAAS,CAAC","sourcesContent":["import type { TConstValue } from './const-value';\n\n/** The value kinds a field mapping reads. */\nexport class FieldMappingDataTypes {\n static readonly STRING = 'string';\n static readonly NUMBER = 'number';\n static readonly STRINGS = 'strings';\n static readonly NUMBERS = 'numbers';\n static readonly BOOLEAN = 'boolean';\n}\n\n/** Valid field mapping data type values. */\nexport type TFieldMappingDataType = TConstValue<typeof FieldMappingDataTypes>;\n\n/** Describes one field to read: its `name`, its value `type`, and an optional `default`. */\nexport interface IFieldMapping {\n name: string;\n type: TFieldMappingDataType;\n default?: string | number | Array<string> | Array<number> | boolean;\n}\n\n/** The union of `name` values in a list of field mappings. */\nexport type TFieldMappingNames<T extends Array<IFieldMapping>> = Extract<\n T[number],\n { type: Exclude<T[number]['type'], undefined> }\n>['name'];\n\n/** The object a list of field mappings yields: one key per `name`, typed from its `type` (`string`, `number`, `boolean`, `strings` or `numbers`). Needs the list typed as a literal (`as const`) to narrow. */\nexport type TObjectFromFieldMappings<\n T extends readonly {\n name: string;\n type: string;\n [extra: string | symbol]:
|
|
1
|
+
{"version":3,"file":"field-mapping.js","sourceRoot":"","sources":["../../../../src/common/types/field-mapping.ts"],"names":[],"mappings":"AAEA,6CAA6C;AAC7C,MAAM,OAAO,qBAAqB;aAChB,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAClB,YAAO,GAAG,SAAS,CAAC;aACpB,YAAO,GAAG,SAAS,CAAC;aACpB,YAAO,GAAG,SAAS,CAAC","sourcesContent":["import type { TConstValue } from './const-value';\n\n/** The value kinds a field mapping reads. */\nexport class FieldMappingDataTypes {\n static readonly STRING = 'string';\n static readonly NUMBER = 'number';\n static readonly STRINGS = 'strings';\n static readonly NUMBERS = 'numbers';\n static readonly BOOLEAN = 'boolean';\n}\n\n/** Valid field mapping data type values. */\nexport type TFieldMappingDataType = TConstValue<typeof FieldMappingDataTypes>;\n\n/** Describes one field to read: its `name`, its value `type`, and an optional `default`. */\nexport interface IFieldMapping {\n name: string;\n type: TFieldMappingDataType;\n default?: string | number | Array<string> | Array<number> | boolean;\n}\n\n/** The union of `name` values in a list of field mappings. */\nexport type TFieldMappingNames<T extends Array<IFieldMapping>> = Extract<\n T[number],\n { type: Exclude<T[number]['type'], undefined> }\n>['name'];\n\n/** The object a list of field mappings yields: one key per `name`, typed from its `type` (`string`, `number`, `boolean`, `strings` or `numbers`). Needs the list typed as a literal (`as const`) to narrow. */\nexport type TObjectFromFieldMappings<\n T extends readonly {\n name: string;\n type: string;\n [extra: string | symbol]: unknown;\n }[],\n> = {\n [K in T[number]['name']]: T extends {\n name: K;\n type: 'string';\n [extra: string | symbol]: unknown;\n }\n ? string\n : T extends { name: K; type: 'number'; [extra: string | symbol]: unknown }\n ? number\n : T extends { name: K; type: 'boolean'; [extra: string | symbol]: unknown }\n ? boolean\n : T extends { name: K; type: 'strings'; [extra: string | symbol]: unknown }\n ? string[]\n : T extends {\n name: K;\n type: 'numbers';\n [extra: string | symbol]: unknown;\n }\n ? number[]\n : never;\n};\n"]}
|
|
@@ -33,7 +33,7 @@ export declare class AxiosFetcher extends AbstractNetworkFetchableHelper<'axios'
|
|
|
33
33
|
*/
|
|
34
34
|
rejectUnauthorized?: boolean;
|
|
35
35
|
});
|
|
36
|
-
send<T =
|
|
36
|
+
send<T = unknown>(opts: IAxiosRequestOptions, logger?: ILogger): Promise<AxiosResponse<T, any, {}, any>>;
|
|
37
37
|
}
|
|
38
38
|
/** Options of `AxiosNetworkRequest`: an axios config with `baseUrl` in place of `baseURL`. */
|
|
39
39
|
export interface IAxiosNetworkRequestOptions {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"axios-fetcher.js","sourceRoot":"","sources":["../../../../../../src/modules/network/http-request/fetcher/axios-fetcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,IAAI,EAAoB,MAAM,UAAU,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,KAA0E,MAAM,OAAO,CAAC;AAC/F,OAAO,KAAK,MAAM,YAAY,CAAC;AAC/B,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAEpE,OAAO,EAAE,8BAA8B,EAAwB,MAAM,gBAAgB,CAAC;AAatF,4MAA4M;AAC5M,M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CAAC;QAED,MAAM;YACJ,EAAE,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;aACpB,IAAI,CAAC,qBAAqB,EAAE,GAAG,EAAE,aAAa,CAAC,aAAa,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QAEnF,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,CAAI,KAAK,CAAC,CAAC;IACvC,CAAC;CACF;AAUD,8JAA8J;AAC9J,MAAM,OAAO,mBAAoB,SAAQ,kBAA2B;IAClE,YAAY,IAAiC;QAC3C,MAAM,EAAE,IAAI,EAAE,cAAc,EAAE,GAAG,IAAI,CAAC;QACtC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,GAAG,cAAc,CAAC;QAE9D,MAAM,aAAa,GAAc;YAC/B,CAAC,cAAc,CAAC,EAAE,iCAAiC;YACnD,GAAG,OAAO;SACX,CAAC;QAEF,MAAM,cAAc,GAAuB;YACzC,eAAe,EAAE,IAAI;YACrB,cAAc,EAAE,CAAC,MAAc,EAAE,EAAE,CAAC,MAAM,GAAG,GAAG;YAChD,OAAO,EAAE,OAAO,IAAI,EAAE,GAAG,IAAI;YAC7B,GAAG,IAAI;YACP,OAAO,EAAE,OAAO;YAChB,OAAO,EAAE,aAAa;SACvB,CAAC;QAEF,KAAK,CAAC;YACJ,IAAI;YACJ,OAAO;YACP,OAAO,EAAE,IAAI,YAAY,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;SACpD,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { type AnyObject, HTTP, type THttpMethod } from '@/common';\nimport { RedactUtility } from '@/common/redact';\nimport axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios';\nimport https from 'node:https';\nimport { stringify } from 'node:querystring';\nimport { BaseNetworkRequest } from '../base-network-request.helper';\nimport type { ILogger } from '@/modules/logger/common/types';\nimport { AbstractNetworkFetchableHelper, type IRequestOptions } from './base-fetcher';\n\n/** Request accepted by `AxiosFetcher`: an axios config where `body` is sent as the axios `data`. `rejectUnauthorized` set here overrides the instance setting for this call. */\nexport interface IAxiosRequestOptions extends AxiosRequestConfig, IRequestOptions {\n url: string;\n method?: THttpMethod;\n params?: AnyObject;\n body?: AnyObject;\n headers?: AnyObject;\n /** Whether this call rejects an HTTPS server whose certificate fails verification; `false` turns verification off for this call. */\n rejectUnauthorized?: boolean;\n}\n\n/** Fetcher over an axios instance (`getWorker()`). HTTPS calls share one keep-alive agent that verifies certificates unless `rejectUnauthorized` is `false`; an `httpsAgent` passed in the request wins. */\nexport class AxiosFetcher extends AbstractNetworkFetchableHelper<\n 'axios',\n IAxiosRequestOptions,\n // The named type, not the `axios.` NAMESPACE: the namespace form resolves only under node16\n // module resolution, and this package also emits an ESM build under `bundler` resolution.\n AxiosResponse<any, any>['data'],\n AxiosInstance\n> {\n /**\n * One agent for the instance, not one per request. Built here so TLS verification is decided\n * ONCE, at construction, rather than per call - and so connections are actually reused: a fresh\n * agent per request forces a new TCP and TLS handshake every time (measured: 10 handshakes for 10\n * requests, versus 1).\n */\n private readonly httpsAgent: https.Agent;\n\n constructor(opts: {\n name: string;\n defaultConfigs: AxiosRequestConfig;\n logger?: ILogger;\n /**\n * Whether this instance rejects an HTTPS server whose certificate fails verification.\n * `false` turns verification off.\n * @default true\n */\n rejectUnauthorized?: boolean;\n }) {\n super({ name: opts.name, variant: 'axios' });\n const { defaultConfigs } = opts;\n opts?.logger?.info('Creating new network request worker instance! Name: %s', this.name);\n\n this.httpsAgent = new https.Agent({\n keepAlive: true,\n rejectUnauthorized: opts.rejectUnauthorized ?? true,\n });\n\n this.worker = axios.create({ ...defaultConfigs });\n }\n\n override send<T = unknown>(opts: IAxiosRequestOptions, logger?: ILogger) {\n const { url, method = HTTP.Methods.GET, params = {}, body: data, headers, ...rest } = opts;\n const props: AxiosRequestConfig = {\n url,\n method: method.toUpperCase(),\n params,\n data,\n headers,\n paramsSerializer: { serialize: (p) => stringify(p) },\n ...rest,\n };\n\n const protocol = this.getProtocol(url);\n\n if (protocol === HTTP.Protocols.HTTPS) {\n // A caller's own agent WINS. The previous code assigned after the `...rest` spread, so a\n // hardened agent - custom CA, pinning, mTLS - was overwritten and the secure path was\n // unreachable through the public seam.\n props.httpsAgent =\n rest.httpsAgent ??\n (opts.rejectUnauthorized === undefined\n ? this.httpsAgent\n : new https.Agent({ keepAlive: true, rejectUnauthorized: opts.rejectUnauthorized }));\n }\n\n logger\n ?.for(this.send.name)\n .info('URL: %s | Props: %s', url, RedactUtility.redactSecrets({ value: props }));\n\n return this.worker.request<T>(props);\n }\n}\n\n/** Options of `AxiosNetworkRequest`: an axios config with `baseUrl` in place of `baseURL`. */\nexport interface IAxiosNetworkRequestOptions {\n name: string;\n networkOptions: Omit<AxiosRequestConfig, 'baseURL'> & {\n baseUrl?: string;\n };\n}\n\n/** `BaseNetworkRequest` over an `AxiosFetcher`. Defaults: JSON content type, 60000 ms `timeout`, and no rejection for status below 500 (`validateStatus`). */\nexport class AxiosNetworkRequest extends BaseNetworkRequest<'axios'> {\n constructor(opts: IAxiosNetworkRequestOptions) {\n const { name, networkOptions } = opts;\n const { headers, baseUrl, timeout, ...rest } = networkOptions;\n\n const mergedHeaders: AnyObject = {\n ['content-type']: 'application/json; charset=utf-8',\n ...headers,\n };\n\n const defaultConfigs: AxiosRequestConfig = {\n withCredentials: true,\n validateStatus: (status: number) => status < 500,\n timeout: timeout ?? 60 * 1000,\n ...rest,\n baseURL: baseUrl,\n headers: mergedHeaders,\n };\n\n super({\n name,\n baseUrl,\n fetcher: new AxiosFetcher({ name, defaultConfigs }),\n });\n }\n}\n"]}
|
|
@@ -10,7 +10,7 @@ export interface IRequestOptions {
|
|
|
10
10
|
method?: THttpMethod;
|
|
11
11
|
params?: AnyObject;
|
|
12
12
|
timeout?: number;
|
|
13
|
-
[extra: symbol | string]:
|
|
13
|
+
[extra: symbol | string]: unknown;
|
|
14
14
|
}
|
|
15
15
|
/** Contract of an HTTP fetcher: `send` takes the method from the options, the verb methods fix it, and `getWorker` returns the underlying client (`W`). */
|
|
16
16
|
export interface IFetchable<V extends TFetcherVariant, RQ extends IRequestOptions, RS, W = unknown> {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-fetcher.js","sourceRoot":"","sources":["../../../../../../src/modules/network/http-request/fetcher/base-fetcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAoB,MAAM,yBAAyB,CAAC;AAsCjE,yNAAyN;AACzN,MAAM,OAAgB,8BAA8B;IAUlD,YAAY,IAA8C;QACxD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE5B,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;YAC9B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC5B,CAAC;IACH,CAAC;IAID,WAAW,CAAC,GAAW;QACrB,OAAO,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;IAC9E,CAAC;IAED,UAAU;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,GAAG,CAAC,IAAQ,EAAE,MAAuB;QACnC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,MAAM,CAAC,CAAC;IAClE,CAAC;IAED,IAAI,CAAC,IAAQ,EAAE,MAAuB;QACpC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,MAAM,CAAC,CAAC;IACnE,CAAC;IAED,GAAG,CAAC,IAAQ,EAAE,MAAuB;QACnC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,MAAM,CAAC,CAAC;IAClE,CAAC;IAED,KAAK,CAAC,IAAQ,EAAE,MAAuB;QACrC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,MAAM,CAAC,CAAC;IACpE,CAAC;IAED,MAAM,CAAC,IAAQ,EAAE,MAAuB;QACtC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,MAAM,CAAC,CAAC;IACrE,CAAC;IAED,KAAK,CAAC,IAAQ,EAAE,MAAuB;QACrC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,MAAM,CAAC,CAAC;IACpE,CAAC;CACF","sourcesContent":["import { HTTP, type THttpMethod } from '@/common/constants/http';\nimport { type AnyObject } from '@/common/types';\n// The leaf file, never the logger BARREL: that barrel reaches `node:module` and would drag this\n// browser-pure fetcher contract with it.\nimport type { ILogger } from '@/modules/logger/common/types';\nimport { type TFetcherVariant } from '../common';\n\n/** What a fetcher calls on the logger it is handed, so a host logger with only these two (a browser app's) is accepted as is. */\nexport type TFetcherLogger = Pick<ILogger, 'debug' | 'info'>;\n\n/** Options every fetcher accepts. `timeout` is in milliseconds; other keys pass through to the underlying client. */\nexport interface IRequestOptions {\n url: string;\n method?: THttpMethod;\n params?: AnyObject;\n timeout?: number;\n [extra: symbol | string]:
|
|
1
|
+
{"version":3,"file":"base-fetcher.js","sourceRoot":"","sources":["../../../../../../src/modules/network/http-request/fetcher/base-fetcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAoB,MAAM,yBAAyB,CAAC;AAsCjE,yNAAyN;AACzN,MAAM,OAAgB,8BAA8B;IAUlD,YAAY,IAA8C;QACxD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE5B,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;YAC9B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC5B,CAAC;IACH,CAAC;IAID,WAAW,CAAC,GAAW;QACrB,OAAO,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;IAC9E,CAAC;IAED,UAAU;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,GAAG,CAAC,IAAQ,EAAE,MAAuB;QACnC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,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,MAAM,CAAC,CAAC;IACpE,CAAC;CACF","sourcesContent":["import { HTTP, type THttpMethod } from '@/common/constants/http';\nimport { type AnyObject } from '@/common/types';\n// The leaf file, never the logger BARREL: that barrel reaches `node:module` and would drag this\n// browser-pure fetcher contract with it.\nimport type { ILogger } from '@/modules/logger/common/types';\nimport { type TFetcherVariant } from '../common';\n\n/** What a fetcher calls on the logger it is handed, so a host logger with only these two (a browser app's) is accepted as is. */\nexport type TFetcherLogger = Pick<ILogger, 'debug' | 'info'>;\n\n/** Options every fetcher accepts. `timeout` is in milliseconds; other keys pass through to the underlying client. */\nexport interface IRequestOptions {\n url: string;\n method?: THttpMethod;\n params?: AnyObject;\n timeout?: number;\n [extra: symbol | string]: unknown;\n}\n\n/** Contract of an HTTP fetcher: `send` takes the method from the options, the verb methods fix it, and `getWorker` returns the underlying client (`W`). */\nexport interface IFetchable<\n V extends TFetcherVariant,\n RQ extends IRequestOptions,\n RS,\n W = unknown,\n> {\n send(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n get(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n post(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n put(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n patch(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n delete(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n query(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n\n getVariant(): V;\n getWorker(): W;\n}\n\n/** `W` defaults to `unknown` so this stays free of `axios` - a concrete fetcher binds it to its real worker type (`AxiosInstance`, `typeof fetch`), which is then inherited on `this.worker` with no override needed. */\nexport abstract class AbstractNetworkFetchableHelper<\n V extends TFetcherVariant,\n RQ extends IRequestOptions,\n RS,\n W = unknown,\n> implements IFetchable<V, RQ, RS, W> {\n protected name: string;\n protected variant: V;\n protected worker: W;\n\n constructor(opts: { name: string; variant: V; worker?: W }) {\n this.name = opts.name;\n this.variant = opts.variant;\n\n if (opts.worker !== undefined) {\n this.worker = opts.worker;\n }\n }\n\n abstract send(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n\n getProtocol(url: string) {\n return url.startsWith('http:') ? HTTP.Protocols.HTTP : HTTP.Protocols.HTTPS;\n }\n\n getVariant() {\n return this.variant;\n }\n\n getWorker(): W {\n return this.worker;\n }\n\n get(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.GET }, logger);\n }\n\n post(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.POST }, logger);\n }\n\n put(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.PUT }, logger);\n }\n\n patch(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.PATCH }, logger);\n }\n\n delete(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.DELETE }, logger);\n }\n\n query(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.QUERY }, logger);\n }\n}\n"]}
|
|
@@ -30,7 +30,7 @@ export interface INetworkTcpClientProps<SocketClientOptions extends PlainConnect
|
|
|
30
30
|
onClosed?: (opts: {
|
|
31
31
|
client: SocketClientType;
|
|
32
32
|
}) => void;
|
|
33
|
-
onError?: (error:
|
|
33
|
+
onError?: (error: unknown) => void;
|
|
34
34
|
}
|
|
35
35
|
/** TCP or TLS client that opens its socket through `createClientFn`, reports connect, data, close and error to the `on*` callbacks, and reconnects when enabled. */
|
|
36
36
|
export declare class BaseNetworkTcpClient<SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions, SocketClientType extends PlainSocketClient | TlsSocketClient> extends BaseHelper {
|
|
@@ -41,7 +41,7 @@ export declare class BaseNetworkTcpClient<SocketClientOptions extends PlainConne
|
|
|
41
41
|
maxReconnect: number;
|
|
42
42
|
currentReconnect: number;
|
|
43
43
|
};
|
|
44
|
-
protected reconnectTimeout
|
|
44
|
+
protected reconnectTimeout?: ReturnType<typeof setTimeout> | null;
|
|
45
45
|
protected encoding?: BufferEncoding;
|
|
46
46
|
protected createClientFn: (options: SocketClientOptions, connectionListener?: () => void) => SocketClientType;
|
|
47
47
|
protected onConnected: (opts: {
|
|
@@ -54,7 +54,7 @@ export declare class BaseNetworkTcpClient<SocketClientOptions extends PlainConne
|
|
|
54
54
|
protected onClosed?: (opts: {
|
|
55
55
|
client: SocketClientType;
|
|
56
56
|
}) => void;
|
|
57
|
-
protected onError?: (error:
|
|
57
|
+
protected onError?: (error: unknown) => void;
|
|
58
58
|
constructor(opts: INetworkTcpClientProps<SocketClientOptions, SocketClientType>);
|
|
59
59
|
getClient(): SocketClientType | null | undefined;
|
|
60
60
|
/** Redacts before logging - a TLS client's options ARE its private key (`key`/`cert`/`passphrase`). */
|
|
@@ -65,7 +65,7 @@ export declare class BaseNetworkTcpClient<SocketClientOptions extends PlainConne
|
|
|
65
65
|
message: string | Buffer;
|
|
66
66
|
}): void;
|
|
67
67
|
handleClosed(): void;
|
|
68
|
-
handleError(error:
|
|
68
|
+
handleError(error: unknown): void;
|
|
69
69
|
connect(opts: {
|
|
70
70
|
resetReconnectCounter: boolean;
|
|
71
71
|
}): void;
|
|
@@ -119,7 +119,7 @@ export class BaseNetworkTcpClient extends BaseHelper {
|
|
|
119
119
|
}
|
|
120
120
|
this.client?.destroy();
|
|
121
121
|
this.client = null;
|
|
122
|
-
clearTimeout(this.reconnectTimeout);
|
|
122
|
+
clearTimeout(this.reconnectTimeout ?? undefined);
|
|
123
123
|
this.reconnectTimeout = null;
|
|
124
124
|
this.logger
|
|
125
125
|
.for(this.disconnect.name)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-tcp-client.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-client.helper.ts"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AO;QACT,CAAC;QAED,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;CACF","sourcesContent":["import { ObjectUtility } from '@venizia/ignis-inversion';\nimport { RedactUtility } from '@/common/redact';\nimport { BaseHelper } from '@/modules/base';\nimport { type ValueOrPromise } from '@/common';\nimport {\n type TcpSocketConnectOpts as PlainConnectionOptions,\n type Socket as PlainSocketClient,\n} from 'node:net';\nimport {\n type ConnectionOptions as TlsConnectionOptions,\n type TLSSocket as TlsSocketClient,\n} from 'node:tls';\n\nconst DEFAULT_MAX_RETRY = 5;\n\n/** Options of a TCP client. `createClientFn` opens the socket, so one client type serves plain and TLS. */\nexport interface INetworkTcpClientProps<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> {\n identifier: string;\n scope?: string;\n\n options: SocketClientOptions;\n /**\n * Retries after a close, up to `maxRetry` times.\n * @default false\n */\n reconnect?: boolean;\n /**\n * How many reconnects `reconnect` attempts.\n * @default 5\n */\n maxRetry?: number;\n /** When set, `onData` receives strings in this encoding instead of buffers. */\n encoding?: BufferEncoding;\n\n createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n onConnected?: (opts: { client: SocketClientType }) => ValueOrPromise<void>;\n onData?: (opts: { identifier: string; message: string | Buffer }) => ValueOrPromise<void>;\n onClosed?: (opts: { client: SocketClientType }) => void;\n onError?: (error: any) => void;\n}\n\n/** TCP or TLS client that opens its socket through `createClientFn`, reports connect, data, close and error to the `on*` callbacks, and reconnects when enabled. */\nexport class BaseNetworkTcpClient<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> extends BaseHelper {\n protected client?: SocketClientType | null;\n\n protected options: SocketClientOptions;\n protected reconnect?: boolean;\n protected retry: { maxReconnect: number; currentReconnect: number } = {\n maxReconnect: DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n protected reconnectTimeout: any;\n protected encoding?: BufferEncoding;\n\n protected createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n protected onConnected: (opts: { client: SocketClientType }) => void;\n protected onData: (opts: { identifier: string; message: string | Buffer }) => void;\n protected onClosed?: (opts: { client: SocketClientType }) => void;\n protected onError?: (error: any) => void;\n\n constructor(opts: INetworkTcpClientProps<SocketClientOptions, SocketClientType>) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpClient.name,\n identifier: opts.identifier,\n });\n this.options = opts.options;\n\n this.retry = {\n maxReconnect: opts.maxRetry ?? DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n this.createClientFn = opts.createClientFn;\n\n this.onConnected = opts?.onConnected ?? this.handleConnected;\n this.onData = opts?.onData ?? this.handleData;\n this.onClosed = opts?.onClosed ?? this.handleClosed;\n this.onError = opts?.onError ?? this.handleError;\n this.reconnect = opts?.reconnect ?? false;\n this.encoding = opts?.encoding;\n }\n\n getClient() {\n return this.client;\n }\n\n /** Redacts before logging - a TLS client's options ARE its private key (`key`/`cert`/`passphrase`). */\n protected getLoggableOptions(): unknown {\n return RedactUtility.redactSecrets({ value: this.options });\n }\n\n handleConnected() {\n this.logger\n .for(this.handleConnected.name)\n .info(\n '[%s] Connected to TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n this.retry.currentReconnect = 0;\n }\n\n handleData(_opts: { identifier: string; message: string | Buffer }) {}\n\n handleClosed() {\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Closed connection TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n }\n\n handleError(error: any) {\n this.logger\n .for(this.handleError.name)\n .error(\n '[%s] Connection error | Options: %j | Error: %s',\n this.identifier,\n this.getLoggableOptions(),\n error,\n );\n\n if (!this.reconnect || this.retry.currentReconnect >= this.retry.maxReconnect) {\n return;\n }\n\n const { currentReconnect, maxReconnect } = this.retry;\n\n if (maxReconnect > -1 && currentReconnect >= maxReconnect) {\n this.logger\n .for(this.handleData.name)\n .info(\n 'Exceeded max retry to reconnect! Max: %d | Current: %d',\n maxReconnect,\n currentReconnect,\n );\n\n return;\n }\n\n this.reconnectTimeout = setTimeout(() => {\n this.client?.destroy();\n this.client = null;\n\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Retrying to establish TCP Connection | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n this.connect({ resetReconnectCounter: false });\n this.retry.currentReconnect++;\n }, 5000);\n }\n\n connect(opts: { resetReconnectCounter: boolean }) {\n if (this.isConnected()) {\n this.logger\n .for(this.connect.name)\n .info('[%s] NetworkTcpClient is already initialized!', this.identifier);\n\n return;\n }\n\n if (ObjectUtility.isEmpty({ value: this.options })) {\n this.logger\n .for(this.connect.name)\n .info('[%s] Cannot init TCP Client with null options', this.identifier);\n\n return;\n }\n\n this.logger\n .for(this.connect.name)\n .info(\n '[%s] New network tcp client | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n if (opts?.resetReconnectCounter) {\n this.retry.currentReconnect = 0;\n }\n\n if (this.client !== null && this.client !== undefined) {\n this.client?.destroy();\n this.client = null;\n }\n\n // The listeners close over THIS socket: `this.client` is nulled by disconnect() and swapped by a reconnect, so reading it back would drop the close hook - or hand it the wrong socket.\n const client = this.createClientFn(this.options, () => {\n this.onConnected?.({ client });\n });\n\n this.client = client;\n\n if (this.encoding) {\n client.setEncoding(this.encoding);\n }\n\n client.on('data', (message: string | Buffer) => {\n this.onData({ identifier: this.identifier, message });\n });\n\n client.on('close', () => {\n this.onClosed?.({ client });\n });\n\n client.on('error', (error) => {\n this.onError?.(error);\n });\n }\n\n disconnect() {\n if (!this.client) {\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is not initialized yet!', this.identifier);\n\n return;\n }\n\n this.client?.destroy();\n this.client = null;\n\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is destroyed!', this.identifier);\n }\n\n forceReconnect() {\n this.disconnect();\n this.connect({ resetReconnectCounter: true });\n }\n\n isConnected() {\n return this.client && this.client.readyState !== 'closed';\n }\n\n emit(opts: { payload: Buffer | string }) {\n if (!this.client) {\n this.logger\n .for(this.emit.name)\n .info('[%s] TPC Client is not configured yet!', this.identifier);\n\n return;\n }\n\n const { payload } = opts;\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info('[%s] Invalid payload to write to TCP Socket!', this.identifier);\n\n return;\n }\n\n this.client.write(payload);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base-tcp-client.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-client.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAW5C,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAmC5B,oKAAoK;AACpK,MAAM,OAAO,oBAGX,SAAQ,UAAU;IAuBlB,YAAY,IAAmE;QAC7E,KAAK,CAAC;YACJ,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,UAAU,IAAI,oBAAoB,CAAC,IAAI;YACjE,UAAU,EAAE,IAAI,CAAC,UAAU;SAC5B,CAAC,CAAC;QAtBK,UAAK,GAAuD;YACpE,YAAY,EAAE,iBAAiB;YAC/B,gBAAgB,EAAE,CAAC;SACpB,CAAC;QAoBA,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE5B,IAAI,CAAC,KAAK,GAAG;YACX,YAAY,EAAE,IAAI,CAAC,QAAQ,IAAI,iBAAiB;YAChD,gBAAgB,EAAE,CAAC;SACpB,CAAC;QAEF,IAAI,CAAC,cAA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AK,QAAQ,CAAC;IAC5D,CAAC;IAED,IAAI,CAAC,IAAkC;QACrC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;iBACnB,IAAI,CAAC,wCAAwC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YAEnE,OAAO;QACT,CAAC;QAED,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAEzB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;iBACnB,IAAI,CAAC,8CAA8C,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YAEzE,OAAO;QACT,CAAC;QAED,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;CACF","sourcesContent":["import { ObjectUtility } from '@venizia/ignis-inversion';\nimport { RedactUtility } from '@/common/redact';\nimport { BaseHelper } from '@/modules/base';\nimport { type ValueOrPromise } from '@/common';\nimport {\n type TcpSocketConnectOpts as PlainConnectionOptions,\n type Socket as PlainSocketClient,\n} from 'node:net';\nimport {\n type ConnectionOptions as TlsConnectionOptions,\n type TLSSocket as TlsSocketClient,\n} from 'node:tls';\n\nconst DEFAULT_MAX_RETRY = 5;\n\n/** Options of a TCP client. `createClientFn` opens the socket, so one client type serves plain and TLS. */\nexport interface INetworkTcpClientProps<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> {\n identifier: string;\n scope?: string;\n\n options: SocketClientOptions;\n /**\n * Retries after a close, up to `maxRetry` times.\n * @default false\n */\n reconnect?: boolean;\n /**\n * How many reconnects `reconnect` attempts.\n * @default 5\n */\n maxRetry?: number;\n /** When set, `onData` receives strings in this encoding instead of buffers. */\n encoding?: BufferEncoding;\n\n createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n onConnected?: (opts: { client: SocketClientType }) => ValueOrPromise<void>;\n onData?: (opts: { identifier: string; message: string | Buffer }) => ValueOrPromise<void>;\n onClosed?: (opts: { client: SocketClientType }) => void;\n onError?: (error: unknown) => void;\n}\n\n/** TCP or TLS client that opens its socket through `createClientFn`, reports connect, data, close and error to the `on*` callbacks, and reconnects when enabled. */\nexport class BaseNetworkTcpClient<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> extends BaseHelper {\n protected client?: SocketClientType | null;\n\n protected options: SocketClientOptions;\n protected reconnect?: boolean;\n protected retry: { maxReconnect: number; currentReconnect: number } = {\n maxReconnect: DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n protected reconnectTimeout?: ReturnType<typeof setTimeout> | null;\n protected encoding?: BufferEncoding;\n\n protected createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n protected onConnected: (opts: { client: SocketClientType }) => void;\n protected onData: (opts: { identifier: string; message: string | Buffer }) => void;\n protected onClosed?: (opts: { client: SocketClientType }) => void;\n protected onError?: (error: unknown) => void;\n\n constructor(opts: INetworkTcpClientProps<SocketClientOptions, SocketClientType>) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpClient.name,\n identifier: opts.identifier,\n });\n this.options = opts.options;\n\n this.retry = {\n maxReconnect: opts.maxRetry ?? DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n this.createClientFn = opts.createClientFn;\n\n this.onConnected = opts?.onConnected ?? this.handleConnected;\n this.onData = opts?.onData ?? this.handleData;\n this.onClosed = opts?.onClosed ?? this.handleClosed;\n this.onError = opts?.onError ?? this.handleError;\n this.reconnect = opts?.reconnect ?? false;\n this.encoding = opts?.encoding;\n }\n\n getClient() {\n return this.client;\n }\n\n /** Redacts before logging - a TLS client's options ARE its private key (`key`/`cert`/`passphrase`). */\n protected getLoggableOptions(): unknown {\n return RedactUtility.redactSecrets({ value: this.options });\n }\n\n handleConnected() {\n this.logger\n .for(this.handleConnected.name)\n .info(\n '[%s] Connected to TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n this.retry.currentReconnect = 0;\n }\n\n handleData(_opts: { identifier: string; message: string | Buffer }) {}\n\n handleClosed() {\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Closed connection TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n }\n\n handleError(error: unknown) {\n this.logger\n .for(this.handleError.name)\n .error(\n '[%s] Connection error | Options: %j | Error: %s',\n this.identifier,\n this.getLoggableOptions(),\n error,\n );\n\n if (!this.reconnect || this.retry.currentReconnect >= this.retry.maxReconnect) {\n return;\n }\n\n const { currentReconnect, maxReconnect } = this.retry;\n\n if (maxReconnect > -1 && currentReconnect >= maxReconnect) {\n this.logger\n .for(this.handleData.name)\n .info(\n 'Exceeded max retry to reconnect! Max: %d | Current: %d',\n maxReconnect,\n currentReconnect,\n );\n\n return;\n }\n\n this.reconnectTimeout = setTimeout(() => {\n this.client?.destroy();\n this.client = null;\n\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Retrying to establish TCP Connection | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n this.connect({ resetReconnectCounter: false });\n this.retry.currentReconnect++;\n }, 5000);\n }\n\n connect(opts: { resetReconnectCounter: boolean }) {\n if (this.isConnected()) {\n this.logger\n .for(this.connect.name)\n .info('[%s] NetworkTcpClient is already initialized!', this.identifier);\n\n return;\n }\n\n if (ObjectUtility.isEmpty({ value: this.options })) {\n this.logger\n .for(this.connect.name)\n .info('[%s] Cannot init TCP Client with null options', this.identifier);\n\n return;\n }\n\n this.logger\n .for(this.connect.name)\n .info(\n '[%s] New network tcp client | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n if (opts?.resetReconnectCounter) {\n this.retry.currentReconnect = 0;\n }\n\n if (this.client !== null && this.client !== undefined) {\n this.client?.destroy();\n this.client = null;\n }\n\n // The listeners close over THIS socket: `this.client` is nulled by disconnect() and swapped by a reconnect, so reading it back would drop the close hook - or hand it the wrong socket.\n const client = this.createClientFn(this.options, () => {\n this.onConnected?.({ client });\n });\n\n this.client = client;\n\n if (this.encoding) {\n client.setEncoding(this.encoding);\n }\n\n client.on('data', (message: string | Buffer) => {\n this.onData({ identifier: this.identifier, message });\n });\n\n client.on('close', () => {\n this.onClosed?.({ client });\n });\n\n client.on('error', (error) => {\n this.onError?.(error);\n });\n }\n\n disconnect() {\n if (!this.client) {\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is not initialized yet!', this.identifier);\n\n return;\n }\n\n this.client?.destroy();\n this.client = null;\n\n clearTimeout(this.reconnectTimeout ?? undefined);\n this.reconnectTimeout = null;\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is destroyed!', this.identifier);\n }\n\n forceReconnect() {\n this.disconnect();\n this.connect({ resetReconnectCounter: true });\n }\n\n isConnected() {\n return this.client && this.client.readyState !== 'closed';\n }\n\n emit(opts: { payload: Buffer | string }) {\n if (!this.client) {\n this.logger\n .for(this.emit.name)\n .info('[%s] TPC Client is not configured yet!', this.identifier);\n\n return;\n }\n\n const { payload } = opts;\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info('[%s] Invalid payload to write to TCP Socket!', this.identifier);\n\n return;\n }\n\n this.client.write(payload);\n }\n}\n"]}
|
|
@@ -20,7 +20,7 @@ export interface ITcpSocketClient<SocketClientType> {
|
|
|
20
20
|
connectedAt: Date;
|
|
21
21
|
authenticatedAt: Date | null;
|
|
22
22
|
authenticateTimeout?: ReturnType<typeof setTimeout> | null;
|
|
23
|
-
[additionField: symbol | string]:
|
|
23
|
+
[additionField: symbol | string]: unknown;
|
|
24
24
|
};
|
|
25
25
|
}
|
|
26
26
|
/** Options of `BaseNetworkTcpServer`. With `authenticateOptions.required`, `duration` (milliseconds, greater than 0) is how long a client has to authenticate before its socket is ended; the constructor throws without it. `createServerFn` builds the server, so one class serves plain and TLS. */
|
|
@@ -36,7 +36,7 @@ export interface ITcpSocketServerOptions<SocketServerOptions extends ServerOpts
|
|
|
36
36
|
extraEvents?: Record<string, (opts: {
|
|
37
37
|
id: string;
|
|
38
38
|
socket: SocketClientType;
|
|
39
|
-
args:
|
|
39
|
+
args: unknown;
|
|
40
40
|
}) => ValueOrPromise<void>>;
|
|
41
41
|
createServerFn: (options: Partial<SocketServerOptions>, connectionListener: (socket: SocketClientType) => void) => SocketServerType;
|
|
42
42
|
onServerReady?: (opts: {
|
|
@@ -78,7 +78,7 @@ export declare class BaseNetworkTcpServer<SocketServerOptions extends ServerOpts
|
|
|
78
78
|
protected extraEvents: Record<string, (opts: {
|
|
79
79
|
id: string;
|
|
80
80
|
socket: SocketClientType;
|
|
81
|
-
args:
|
|
81
|
+
args: unknown;
|
|
82
82
|
}) => ValueOrPromise<void>>;
|
|
83
83
|
protected createServerFn: (options: Partial<SocketServerOptions>, connectionListener: (socket: SocketClientType) => void) => SocketServerType;
|
|
84
84
|
protected onServerReady?: (opts: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-tcp-server.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-server.helper.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAQ7D,6DAA6D;AAC7D,MAAM,OAAO,eAAe;aACV,iBAAY,GAAG,cAAc,CAAC;aAC9B,mBAAc,GAAG,gBAAgB,CAAC;aAClC,kBAAa,GAAG,eAAe,CAAC;;AAmDlD,iLAA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AED,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;CACF","sourcesContent":["import type { TConstValue } from '@/common/types';\nimport { type ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { ParseUtility } from '@/utilities/parse.utility';\nimport { PromiseUtility } from '@/utilities/promise.utility';\nimport {\n type ListenOptions,\n type ServerOpts,\n type Socket as SocketClient,\n type Server as SocketServer,\n} from 'node:net';\n\n/** Where a TCP client is in the authentication handshake. */\nexport class TcpClientStates {\n static readonly UNAUTHORIZED = 'unauthorized';\n static readonly AUTHENTICATING = 'authenticating';\n static readonly AUTHENTICATED = 'authenticated';\n}\n\n/** Valid TCP client state values. */\nexport type TTcpClientState = TConstValue<typeof TcpClientStates>;\n\n/** A client connected to `BaseNetworkTcpServer`: its `id`, `socket`, authentication `state`, `subscriptions` and `storage` (connect and authenticate times, the pending authenticate timer). */\nexport interface ITcpSocketClient<SocketClientType> {\n id: string;\n socket: SocketClientType;\n state: TTcpClientState;\n subscriptions: Set<string>;\n storage: {\n connectedAt: Date;\n authenticatedAt: Date | null;\n authenticateTimeout?: ReturnType<typeof setTimeout> | null;\n [additionField: symbol | string]: any;\n };\n}\n\n/** Options of `BaseNetworkTcpServer`. With `authenticateOptions.required`, `duration` (milliseconds, greater than 0) is how long a client has to authenticate before its socket is ended; the constructor throws without it. `createServerFn` builds the server, so one class serves plain and TLS. */\nexport interface ITcpSocketServerOptions<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> {\n scope?: string;\n identifier: string;\n\n serverOptions: Partial<SocketServerOptions>;\n listenOptions: Partial<ListenOptions>;\n authenticateOptions: { required: boolean; duration?: number };\n\n extraEvents?: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: any }) => ValueOrPromise<void>\n >;\n\n createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n onServerReady?: (opts: { server: SocketServerType }) => void;\n onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientData?: (opts: { id: string; socket: SocketClientType; data: Buffer | string }) => void;\n onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n}\n\n/** TCP or TLS server that tracks connected clients by id, with an optional authentication window, and reports connection events to the `onClient*` and `onServer*` callbacks. */\nexport class BaseNetworkTcpServer<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> extends BaseHelper {\n protected serverOptions: Partial<SocketServerOptions> = {};\n protected listenOptions: Partial<ListenOptions> = {};\n protected authenticateOptions: { required: boolean; duration?: number };\n\n protected clients: Record<string, ITcpSocketClient<SocketClientType>>;\n protected server: SocketServerType;\n\n protected extraEvents: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: any }) => ValueOrPromise<void>\n >;\n\n protected createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n protected onServerReady?: (opts: { server: SocketServerType }) => void;\n protected onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientData?: (opts: {\n id: string;\n socket: SocketClientType;\n data: Buffer | string;\n }) => void;\n\n protected onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n protected onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n\n constructor(\n opts: ITcpSocketServerOptions<SocketServerOptions, SocketServerType, SocketClientType>,\n ) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpServer.name,\n identifier: opts.identifier,\n });\n\n // No prototype: `getClient({ id: 'constructor' })` must find nothing, not `Object`.\n this.clients = Object.create(null);\n\n this.serverOptions = opts.serverOptions;\n this.listenOptions = opts.listenOptions;\n this.authenticateOptions = opts.authenticateOptions;\n\n if (\n this.authenticateOptions.required &&\n (!this.authenticateOptions.duration || this.authenticateOptions.duration < 0)\n ) {\n throw getError({\n message:\n 'TCP Server | Invalid authenticate duration | Required duration for authenticateOptions',\n });\n }\n\n this.extraEvents = opts.extraEvents ?? {};\n\n this.createServerFn = opts.createServerFn;\n\n this.onServerReady = opts.onServerReady;\n this.onClientConnected = opts.onClientConnected;\n this.onClientData = opts.onClientData;\n this.onClientClose = opts.onClientClose;\n this.onClientError = opts.onClientError;\n this.onServerError = opts.onServerError;\n\n this.configure();\n }\n\n // Hooks run inside socket event listeners: a synchronous throw there is an uncaught exception that kills the process and skips the client-registry cleanup that follows it.\n protected invokeHook(opts: { scope: string; execution: () => void }) {\n const { scope, execution } = opts;\n\n try {\n execution();\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n configure() {\n this.server = this.createServerFn(this.serverOptions, (socket) => {\n this.onNewConnection({ socket });\n });\n\n // Without this listener a failed listen - a port already in use is the commonest boot failure there is - emits an unhandled 'error' event, which takes the whole process down with it.\n this.server.on('error', (error: Error) => {\n this.logger\n .for(this.configure.name)\n .error('TCP Socket Server error | Options: %j | Error: %s', this.listenOptions, error);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerError?.({ server: this.server, error });\n },\n });\n });\n\n this.server.listen(this.listenOptions, () => {\n this.logger\n .for(this.configure.name)\n .info('TCP Socket Server is now listening | Options: %j', this.listenOptions);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerReady?.({ server: this.server });\n },\n });\n });\n }\n\n onNewConnection(opts: { socket: SocketClientType }) {\n const { socket } = opts;\n\n const id = ParseUtility.getUID();\n\n socket.on('data', (data: Buffer | string) => {\n this.invokeHook({\n scope: 'onClientData',\n execution: () => {\n this.onClientData?.({ id, socket, data });\n },\n });\n });\n\n socket.on('error', (error: Error) => {\n this.logger.for('onClientConnect').error('Socket Error | ID: %s | Error: %s', id, error);\n\n this.invokeHook({\n scope: 'onClientError',\n execution: () => {\n this.onClientError?.({ id, socket, error });\n },\n });\n\n socket.end();\n });\n\n socket.on('close', (hasError: boolean) => {\n this.logger\n .for('onClientConnect')\n .info('Socket Closed | ID: %s | hasError: %s', id, hasError);\n\n this.invokeHook({\n scope: 'onClientClose',\n execution: () => {\n this.onClientClose?.({ id, socket });\n },\n });\n\n const authenticateTimeout = this.getClient({ id })?.storage?.authenticateTimeout;\n\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n }\n\n // `delete`, not `omit`: omit rebuilds the WHOLE registry per disconnect, so a disconnect\n // storm is O(n^2) - measured at 5000 clients, 2.3s of drain with a 2.2s worst-case stall.\n delete this.clients[id];\n });\n\n for (const extraEvent in this.extraEvents) {\n socket.on(extraEvent, (args) => {\n PromiseUtility.voidExecution({\n logger: this.logger,\n scope: 'onClientConnect',\n // The async wrapper turns a SYNCHRONOUS throw from the handler into a rejection; calling it bare would throw out of this listener as an uncaught exception.\n execution: (async () => this.extraEvents[extraEvent]({ id, socket, args }))(),\n });\n });\n }\n\n this.clients[id] = {\n id,\n socket,\n state: this.authenticateOptions.required\n ? TcpClientStates.UNAUTHORIZED\n : TcpClientStates.AUTHENTICATED,\n subscriptions: new Set([]),\n storage: {\n connectedAt: new Date(),\n authenticatedAt: this.authenticateOptions.required ? null : new Date(),\n },\n };\n\n this.logger\n .for('onClientConnect')\n .info(\n 'New TCP SocketClient | Client: %s | authenticateOptions: %s %s',\n `${id} - ${socket.remoteAddress} - ${socket.remotePort} - ${socket.remoteFamily}`,\n this.authenticateOptions.required,\n this.authenticateOptions.duration,\n );\n\n this.invokeHook({\n scope: 'onClientConnected',\n execution: () => {\n this.onClientConnected?.({ id, socket });\n },\n });\n\n if (\n this.authenticateOptions.required &&\n this.authenticateOptions.duration &&\n this.authenticateOptions.duration > 0\n ) {\n const authenticateTimeout = setTimeout(() => {\n const client = this.getClient({ id });\n\n if (!client) {\n return;\n }\n\n client.storage.authenticateTimeout = null;\n\n if (client.state === TcpClientStates.AUTHENTICATED) {\n return;\n }\n\n this.emit({ clientId: id, payload: 'Unauthorized Client' });\n client.socket.end();\n }, this.authenticateOptions.duration);\n\n const client = this.getClient({ id });\n\n if (!client) {\n clearTimeout(authenticateTimeout);\n\n return;\n }\n\n client.storage.authenticateTimeout = authenticateTimeout;\n }\n }\n\n getClients() {\n return this.clients;\n }\n\n getClient(opts: { id: string }) {\n return this.clients?.[opts.id];\n }\n\n getServer() {\n return this.server;\n }\n\n /** Clears timers and destroys all client sockets before closing the listener - `server.close()` alone never settles while a socket stays attached. Idempotent; safe if never listened. */\n async shutdown(): Promise<void> {\n const clientsValues = Object.values(this.clients);\n\n for (const client of clientsValues) {\n const { authenticateTimeout } = client.storage;\n\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n client.socket.destroy();\n }\n\n this.clients = Object.create(null);\n\n const server = this.server;\n\n if (!server) {\n return;\n }\n\n // Not guarded on `listening`: listen() is async (DNS lookup), so a shutdown() racing startup could skip close() and leave the server bound forever; close() on a never-listened server just logs ERR_SERVER_NOT_RUNNING below.\n\n await new Promise<void>((resolve) => {\n server.close((error) => {\n if (error) {\n this.logger.for(this.shutdown.name).error('Failed to close server | Error: %s', error);\n }\n\n resolve();\n });\n });\n\n this.logger.for(this.shutdown.name).info('Server closed | Identifier: %s', this.identifier);\n }\n\n doAuthenticate(opts: { id: string; state: TTcpClientState }) {\n const { id, state } = opts;\n\n const client = this.getClient({ id });\n\n if (!client) {\n this.logger.for('authenticateClient').error('Client NOT FOUND | ID: %s', id);\n\n return;\n }\n\n client.state = state;\n\n switch (state) {\n case TcpClientStates.UNAUTHORIZED:\n case TcpClientStates.AUTHENTICATING: {\n client.storage.authenticatedAt = null;\n break;\n }\n case TcpClientStates.AUTHENTICATED: {\n client.storage.authenticatedAt = new Date();\n\n if (client.storage.authenticateTimeout) {\n clearTimeout(client.storage.authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n break;\n }\n default: {\n break;\n }\n }\n }\n\n emit(opts: { clientId: string; payload: Buffer | string }) {\n const { clientId, payload } = opts;\n const client = this.getClient({ id: clientId });\n\n if (!client) {\n this.logger.for(this.emit.name).error('Client NOT FOUND | ID: %s', clientId);\n\n return;\n }\n\n const { socket } = client;\n\n if (!socket.writable) {\n this.logger.for(this.emit.name).error('Client NOT WRITABLE | ID: %s', clientId);\n\n return;\n }\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info(\n '[%s] Client %s | Invalid payload to write to TCP Socket!',\n this.identifier,\n clientId,\n );\n\n return;\n }\n\n socket.write(payload);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base-tcp-server.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-server.helper.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAQ7D,6DAA6D;AAC7D,MAAM,OAAO,eAAe;aACV,iBAAY,GAAG,cAAc,CAAC;aAC9B,mBAAc,GAAG,gBAAgB,CAAC;aAClC,kBAAa,GAAG,eAAe,CAAC;;AAmDlD,iLAAiL;AACjL,MAAM,OAAO,oBAIX,SAAQ,UAAU;IA8BlB,YACE,IAAsF;QAEtF,KAAK,CAAC;YACJ,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,UAAU,IAAI,oBAAoB,CAAC,IAAI;YACjE,UAAU,EAAE,IAAI,CAAC,UAAU;SAC5B,CAAC,CAAC;QAnCK,kBAAa,GAAiC,EAAE,CAAC;QACjD,kBAAa,GAA2B,EAAE,CAAC;Q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gBAED,MAAM;YACR,CAAC;YACD,OAAO,CAAC,CAAC,CAAC;gBACR,MAAM;YACR,CAAC;QACH,CAAC;IACH,CAAC;IAED,IAAI,CAAC,IAAoD;QACvD,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QACnC,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;QAEhD,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,2BAA2B,EAAE,QAAQ,CAAC,CAAC;YAE7E,OAAO;QACT,CAAC;QAED,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;QAE1B,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,8BAA8B,EAAE,QAAQ,CAAC,CAAC;YAEhF,OAAO;QACT,CAAC;QAED,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;iBACnB,IAAI,CACH,0DAA0D,EAC1D,IAAI,CAAC,UAAU,EACf,QAAQ,CACT,CAAC;YAEJ,OAAO;QACT,CAAC;QAED,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;CACF","sourcesContent":["import type { TConstValue } from '@/common/types';\nimport { type ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { ParseUtility } from '@/utilities/parse.utility';\nimport { PromiseUtility } from '@/utilities/promise.utility';\nimport {\n type ListenOptions,\n type ServerOpts,\n type Socket as SocketClient,\n type Server as SocketServer,\n} from 'node:net';\n\n/** Where a TCP client is in the authentication handshake. */\nexport class TcpClientStates {\n static readonly UNAUTHORIZED = 'unauthorized';\n static readonly AUTHENTICATING = 'authenticating';\n static readonly AUTHENTICATED = 'authenticated';\n}\n\n/** Valid TCP client state values. */\nexport type TTcpClientState = TConstValue<typeof TcpClientStates>;\n\n/** A client connected to `BaseNetworkTcpServer`: its `id`, `socket`, authentication `state`, `subscriptions` and `storage` (connect and authenticate times, the pending authenticate timer). */\nexport interface ITcpSocketClient<SocketClientType> {\n id: string;\n socket: SocketClientType;\n state: TTcpClientState;\n subscriptions: Set<string>;\n storage: {\n connectedAt: Date;\n authenticatedAt: Date | null;\n authenticateTimeout?: ReturnType<typeof setTimeout> | null;\n [additionField: symbol | string]: unknown;\n };\n}\n\n/** Options of `BaseNetworkTcpServer`. With `authenticateOptions.required`, `duration` (milliseconds, greater than 0) is how long a client has to authenticate before its socket is ended; the constructor throws without it. `createServerFn` builds the server, so one class serves plain and TLS. */\nexport interface ITcpSocketServerOptions<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> {\n scope?: string;\n identifier: string;\n\n serverOptions: Partial<SocketServerOptions>;\n listenOptions: Partial<ListenOptions>;\n authenticateOptions: { required: boolean; duration?: number };\n\n extraEvents?: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: unknown }) => ValueOrPromise<void>\n >;\n\n createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n onServerReady?: (opts: { server: SocketServerType }) => void;\n onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientData?: (opts: { id: string; socket: SocketClientType; data: Buffer | string }) => void;\n onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n}\n\n/** TCP or TLS server that tracks connected clients by id, with an optional authentication window, and reports connection events to the `onClient*` and `onServer*` callbacks. */\nexport class BaseNetworkTcpServer<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> extends BaseHelper {\n protected serverOptions: Partial<SocketServerOptions> = {};\n protected listenOptions: Partial<ListenOptions> = {};\n protected authenticateOptions: { required: boolean; duration?: number };\n\n protected clients: Record<string, ITcpSocketClient<SocketClientType>>;\n protected server: SocketServerType;\n\n protected extraEvents: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: unknown }) => ValueOrPromise<void>\n >;\n\n protected createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n protected onServerReady?: (opts: { server: SocketServerType }) => void;\n protected onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientData?: (opts: {\n id: string;\n socket: SocketClientType;\n data: Buffer | string;\n }) => void;\n\n protected onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n protected onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n\n constructor(\n opts: ITcpSocketServerOptions<SocketServerOptions, SocketServerType, SocketClientType>,\n ) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpServer.name,\n identifier: opts.identifier,\n });\n\n // No prototype: `getClient({ id: 'constructor' })` must find nothing, not `Object`.\n this.clients = Object.create(null);\n\n this.serverOptions = opts.serverOptions;\n this.listenOptions = opts.listenOptions;\n this.authenticateOptions = opts.authenticateOptions;\n\n if (\n this.authenticateOptions.required &&\n (!this.authenticateOptions.duration || this.authenticateOptions.duration < 0)\n ) {\n throw getError({\n message:\n 'TCP Server | Invalid authenticate duration | Required duration for authenticateOptions',\n });\n }\n\n this.extraEvents = opts.extraEvents ?? {};\n\n this.createServerFn = opts.createServerFn;\n\n this.onServerReady = opts.onServerReady;\n this.onClientConnected = opts.onClientConnected;\n this.onClientData = opts.onClientData;\n this.onClientClose = opts.onClientClose;\n this.onClientError = opts.onClientError;\n this.onServerError = opts.onServerError;\n\n this.configure();\n }\n\n // Hooks run inside socket event listeners: a synchronous throw there is an uncaught exception that kills the process and skips the client-registry cleanup that follows it.\n protected invokeHook(opts: { scope: string; execution: () => void }) {\n const { scope, execution } = opts;\n\n try {\n execution();\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n configure() {\n this.server = this.createServerFn(this.serverOptions, (socket) => {\n this.onNewConnection({ socket });\n });\n\n // Without this listener a failed listen - a port already in use is the commonest boot failure there is - emits an unhandled 'error' event, which takes the whole process down with it.\n this.server.on('error', (error: Error) => {\n this.logger\n .for(this.configure.name)\n .error('TCP Socket Server error | Options: %j | Error: %s', this.listenOptions, error);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerError?.({ server: this.server, error });\n },\n });\n });\n\n this.server.listen(this.listenOptions, () => {\n this.logger\n .for(this.configure.name)\n .info('TCP Socket Server is now listening | Options: %j', this.listenOptions);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerReady?.({ server: this.server });\n },\n });\n });\n }\n\n onNewConnection(opts: { socket: SocketClientType }) {\n const { socket } = opts;\n\n const id = ParseUtility.getUID();\n\n socket.on('data', (data: Buffer | string) => {\n this.invokeHook({\n scope: 'onClientData',\n execution: () => {\n this.onClientData?.({ id, socket, data });\n },\n });\n });\n\n socket.on('error', (error: Error) => {\n this.logger.for('onClientConnect').error('Socket Error | ID: %s | Error: %s', id, error);\n\n this.invokeHook({\n scope: 'onClientError',\n execution: () => {\n this.onClientError?.({ id, socket, error });\n },\n });\n\n socket.end();\n });\n\n socket.on('close', (hasError: boolean) => {\n this.logger\n .for('onClientConnect')\n .info('Socket Closed | ID: %s | hasError: %s', id, hasError);\n\n this.invokeHook({\n scope: 'onClientClose',\n execution: () => {\n this.onClientClose?.({ id, socket });\n },\n });\n\n const authenticateTimeout = this.getClient({ id })?.storage?.authenticateTimeout;\n\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n }\n\n // `delete`, not `omit`: omit rebuilds the WHOLE registry per disconnect, so a disconnect\n // storm is O(n^2) - measured at 5000 clients, 2.3s of drain with a 2.2s worst-case stall.\n delete this.clients[id];\n });\n\n for (const extraEvent in this.extraEvents) {\n socket.on(extraEvent, (args) => {\n PromiseUtility.voidExecution({\n logger: this.logger,\n scope: 'onClientConnect',\n // The async wrapper turns a SYNCHRONOUS throw from the handler into a rejection; calling it bare would throw out of this listener as an uncaught exception.\n execution: (async () => this.extraEvents[extraEvent]({ id, socket, args }))(),\n });\n });\n }\n\n this.clients[id] = {\n id,\n socket,\n state: this.authenticateOptions.required\n ? TcpClientStates.UNAUTHORIZED\n : TcpClientStates.AUTHENTICATED,\n subscriptions: new Set([]),\n storage: {\n connectedAt: new Date(),\n authenticatedAt: this.authenticateOptions.required ? null : new Date(),\n },\n };\n\n this.logger\n .for('onClientConnect')\n .info(\n 'New TCP SocketClient | Client: %s | authenticateOptions: %s %s',\n `${id} - ${socket.remoteAddress} - ${socket.remotePort} - ${socket.remoteFamily}`,\n this.authenticateOptions.required,\n this.authenticateOptions.duration,\n );\n\n this.invokeHook({\n scope: 'onClientConnected',\n execution: () => {\n this.onClientConnected?.({ id, socket });\n },\n });\n\n if (\n this.authenticateOptions.required &&\n this.authenticateOptions.duration &&\n this.authenticateOptions.duration > 0\n ) {\n const authenticateTimeout = setTimeout(() => {\n const client = this.getClient({ id });\n\n if (!client) {\n return;\n }\n\n client.storage.authenticateTimeout = null;\n\n if (client.state === TcpClientStates.AUTHENTICATED) {\n return;\n }\n\n this.emit({ clientId: id, payload: 'Unauthorized Client' });\n client.socket.end();\n }, this.authenticateOptions.duration);\n\n const client = this.getClient({ id });\n\n if (!client) {\n clearTimeout(authenticateTimeout);\n\n return;\n }\n\n client.storage.authenticateTimeout = authenticateTimeout;\n }\n }\n\n getClients() {\n return this.clients;\n }\n\n getClient(opts: { id: string }) {\n return this.clients?.[opts.id];\n }\n\n getServer() {\n return this.server;\n }\n\n /** Clears timers and destroys all client sockets before closing the listener - `server.close()` alone never settles while a socket stays attached. Idempotent; safe if never listened. */\n async shutdown(): Promise<void> {\n const clientsValues = Object.values(this.clients);\n\n for (const client of clientsValues) {\n const { authenticateTimeout } = client.storage;\n\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n client.socket.destroy();\n }\n\n this.clients = Object.create(null);\n\n const server = this.server;\n\n if (!server) {\n return;\n }\n\n // Not guarded on `listening`: listen() is async (DNS lookup), so a shutdown() racing startup could skip close() and leave the server bound forever; close() on a never-listened server just logs ERR_SERVER_NOT_RUNNING below.\n\n await new Promise<void>((resolve) => {\n server.close((error) => {\n if (error) {\n this.logger.for(this.shutdown.name).error('Failed to close server | Error: %s', error);\n }\n\n resolve();\n });\n });\n\n this.logger.for(this.shutdown.name).info('Server closed | Identifier: %s', this.identifier);\n }\n\n doAuthenticate(opts: { id: string; state: TTcpClientState }) {\n const { id, state } = opts;\n\n const client = this.getClient({ id });\n\n if (!client) {\n this.logger.for('authenticateClient').error('Client NOT FOUND | ID: %s', id);\n\n return;\n }\n\n client.state = state;\n\n switch (state) {\n case TcpClientStates.UNAUTHORIZED:\n case TcpClientStates.AUTHENTICATING: {\n client.storage.authenticatedAt = null;\n break;\n }\n case TcpClientStates.AUTHENTICATED: {\n client.storage.authenticatedAt = new Date();\n\n if (client.storage.authenticateTimeout) {\n clearTimeout(client.storage.authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n break;\n }\n default: {\n break;\n }\n }\n }\n\n emit(opts: { clientId: string; payload: Buffer | string }) {\n const { clientId, payload } = opts;\n const client = this.getClient({ id: clientId });\n\n if (!client) {\n this.logger.for(this.emit.name).error('Client NOT FOUND | ID: %s', clientId);\n\n return;\n }\n\n const { socket } = client;\n\n if (!socket.writable) {\n this.logger.for(this.emit.name).error('Client NOT WRITABLE | ID: %s', clientId);\n\n return;\n }\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info(\n '[%s] Client %s | Invalid payload to write to TCP Socket!',\n this.identifier,\n clientId,\n );\n\n return;\n }\n\n socket.write(payload);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser-helper.js","sourceRoot":"","sources":["../../../../../../src/modules/socket/socket-io/client/browser-helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAE/C,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,sGAAsG;AACtG,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAQ9E;;;;GAIG;AACH,MAAM,OAAO,oBAAqB,SAAQ,UAAU;IAkBlD,YAAY,IAA4B;QACtC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;QAf5B,UAAK,GAAyB,oBAAoB,CAAC,YAAY,CAAC;QAExE,qKAAqK;QAC7J,oBAAe,GACrB,IAAI,GAAG,EAAE,CAAC;QAaV,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;QAClC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC5B,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC;QAEhC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC;QACpC,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;QAC1C,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC5B,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,e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AAC;YAChB,IAAI,CAAC,MAAM,CAAC,kBAAkB,EAAE,CAAC;YAEjC,IAAI,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;gBAC1B,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;YAC3B,CAAC;QACH,CAAC;QAED,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;QAC7B,IAAI,CAAC,KAAK,GAAG,oBAAoB,CAAC,YAAY,CAAC;QAC/C,MAAM,CAAC,IAAI,CAAC,4CAA4C,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAC7E,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport { type ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport type { Socket } from 'socket.io-client';\n// The leaf files, never the `../common` barrel: it reaches the server types, which name node modules.\nimport { SocketIOClientStates, SocketIOConstants } from '../common/constants';\nimport type {\n IOptions,\n ISocketIOClientOptions,\n TSocketIOClientState,\n} from '../common/types/client';\nimport type { TSocketIOEventHandler } from '../common/types/hooks';\n\n/**\n * The socket.io client with nothing node in its graph, so a browser bundle can hold it: `socket.io-client`\n * is handed in as `module` (`{ io }` from the app's own `import`) instead of being found on disk.\n * `@venizia/ignis-helpers/socket-io` extends it and finds the module itself when none is handed in.\n */\nexport class SocketIOClientHelper extends BaseHelper {\n private host: string;\n private options: IOptions;\n private client: Socket;\n private state: TSocketIOClientState = SocketIOClientStates.UNAUTHORIZED;\n\n // subscribe() registers a wrapper, never the caller handler: without this map unsubscribe() has nothing to hand to socket.off() and the listener stays bound forever\n private wrappedHandlers: Map<string, Map<TSocketIOEventHandler<any>, (data: any) => void>> =\n new Map();\n\n private onConnected?: () => ValueOrPromise<void>;\n private onDisconnected?: (reason: string) => ValueOrPromise<void>;\n private onError?: (error: Error) => ValueOrPromise<void>;\n private onAuthenticated?: () => ValueOrPromise<void>;\n private onUnauthenticated?: (message: string) => ValueOrPromise<void>;\n\n protected readonly clientModule?: typeof import('socket.io-client');\n\n constructor(opts: ISocketIOClientOptions) {\n super({ scope: opts.identifier });\n\n this.identifier = opts.identifier;\n this.host = opts.host;\n this.options = opts.options;\n this.clientModule = opts.module;\n\n this.onConnected = opts.onConnected;\n this.onDisconnected = opts.onDisconnected;\n this.onError = opts.onError;\n this.onAuthenticated = opts.onAuthenticated;\n this.onUnauthenticated = opts.onUnauthenticated;\n\n this.configure();\n }\n\n /** The `socket.io-client` module to connect with. Here only the one handed in; a subclass may find one. */\n protected resolveModule(): typeof import('socket.io-client') {\n if (!this.clientModule) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[SocketIOClientHelper][${this.identifier}] option 'module' is required: pass { io } from 'socket.io-client'`,\n });\n }\n\n return this.clientModule;\n }\n\n getState(): TSocketIOClientState {\n return this.state;\n }\n\n configure() {\n const logger = this.logger.for(this.configure.name);\n\n if (this.client) {\n logger.info('SocketIO Client already established | id: %s', this.identifier);\n\n return;\n }\n\n const { io } = this.resolveModule();\n this.client = io(this.host, this.options);\n\n // Socket.IO client fires 'connect', NOT 'connection' (server-side only)\n this.client.on('connect', () => {\n logger.info('Connected | id: %s', this.identifier);\n\n Promise.resolve(this.onConnected?.()).catch((error) => {\n logger.error('onConnected callback error | error: %s', error);\n });\n });\n\n this.client.on(SocketIOConstants.EVENT_DISCONNECT, (reason: string) => {\n logger.info('Disconnected | id: %s | reason: %s', this.identifier, reason);\n this.state = SocketIOClientStates.UNAUTHORIZED;\n\n Promise.resolve(this.onDisconnected?.(reason)).catch((error) => {\n logger.error('onDisconnected callback error | error: %s', error);\n });\n });\n\n this.client.on('connect_error', (error: Error) => {\n logger.error('Connection error | id: %s | error: %s', this.identifier, error);\n\n Promise.resolve(this.onError?.(error)).catch((err) => {\n logger.error('onError callback error | error: %s', err);\n });\n });\n\n this.client.on(SocketIOConstants.EVENT_AUTHENTICATED, (data: unknown) => {\n logger.info('Authenticated | id: %s | data: %j', this.identifier, data);\n this.state = SocketIOClientStates.AUTHENTICATED;\n\n Promise.resolve(this.onAuthenticated?.()).catch((error) => {\n logger.error('onAuthenticated callback error | error: %s', error);\n });\n });\n\n this.client.on(SocketIOConstants.EVENT_UNAUTHENTICATE, (data: { message?: string }) => {\n logger.warn('Unauthenticated | id: %s | data: %j', this.identifier, data);\n this.state = SocketIOClientStates.UNAUTHORIZED;\n\n Promise.resolve(this.onUnauthenticated?.(data?.message ?? '')).catch((error) => {\n logger.error('onUnauthenticated callback error | error: %s', error);\n });\n });\n\n this.client.on(SocketIOConstants.EVENT_PING, () => {\n logger.debug('Ping received | id: %s', this.identifier);\n });\n }\n\n getSocketClient(): Socket {\n return this.client;\n }\n\n authenticate() {\n const logger = this.logger.for(this.authenticate.name);\n\n if (!this.client?.connected) {\n logger.warn('Cannot authenticate | id: %s | reason: not connected', this.identifier);\n\n return;\n }\n\n if (this.state !== SocketIOClientStates.UNAUTHORIZED) {\n logger.warn('Cannot authenticate | id: %s | currentState: %s', this.identifier, this.state);\n\n return;\n }\n\n this.state = SocketIOClientStates.AUTHENTICATING;\n this.client.emit(SocketIOConstants.EVENT_AUTHENTICATE);\n logger.info('Authentication requested | id: %s', this.identifier);\n }\n\n subscribe<T = unknown>(opts: {\n event: string;\n handler: TSocketIOEventHandler<T>;\n ignoreDuplicate?: boolean;\n }) {\n const logger = this.logger.for(this.subscribe.name);\n const { event, handler, ignoreDuplicate = true } = opts;\n\n if (!handler) {\n logger.warn('No handler provided | event: %s', event);\n\n return;\n }\n\n if (ignoreDuplicate && this.client.hasListeners(event)) {\n logger.info('Handler already exists | event: %s', event);\n\n return;\n }\n\n // Wrap handler in try-catch for error safety (catches both sync throws and async rejections)\n const wrappedHandler = (data: T) => {\n try {\n Promise.resolve(handler(data)).catch((error) => {\n logger.error('Handler error | event: %s | error: %s', event, error);\n });\n } catch (error) {\n logger.error('Handler error | event: %s | error: %s', event, error);\n }\n };\n\n if (!this.wrappedHandlers.has(event)) {\n this.wrappedHandlers.set(event, new Map());\n }\n\n this.wrappedHandlers.get(event)!.set(handler, wrappedHandler);\n\n this.client.on(event, wrappedHandler);\n logger.info('Subscribed | event: %s', event);\n }\n\n subscribeMany(opts: {\n events: Record<string, TSocketIOEventHandler>;\n ignoreDuplicate?: boolean;\n }) {\n const { events, ignoreDuplicate } = opts;\n\n for (const event in events) {\n this.subscribe({\n event,\n handler: events[event],\n ignoreDuplicate,\n });\n }\n }\n\n unsubscribe(opts: { event: string; handler?: TSocketIOEventHandler }) {\n const logger = this.logger.for(this.unsubscribe.name);\n const { event, handler } = opts;\n\n if (!this.client?.hasListeners(event)) {\n logger.info('No listeners to remove | event: %s', event);\n\n return;\n }\n\n if (handler) {\n const wrappedHandler = this.wrappedHandlers.get(event)?.get(handler);\n\n if (!wrappedHandler) {\n logger.info('Handler was not subscribed through this helper | event: %s', event);\n\n return;\n }\n\n this.client.off(event, wrappedHandler);\n this.wrappedHandlers.get(event)?.delete(handler);\n\n if (!this.wrappedHandlers.get(event)?.size) {\n this.wrappedHandlers.delete(event);\n }\n\n logger.info('Removed specific handler | event: %s', event);\n\n return;\n }\n\n this.client.off(event);\n this.wrappedHandlers.delete(event);\n logger.info('Removed all handlers | event: %s', event);\n }\n\n unsubscribeMany(opts: { events: string[] }) {\n for (const event of opts.events) {\n this.unsubscribe({ event });\n }\n }\n\n connect() {\n const logger = this.logger.for(this.connect.name);\n\n if (!this.client) {\n logger.info('Invalid client to connect | id: %s', this.identifier);\n\n return;\n }\n\n this.client.connect();\n }\n\n disconnect() {\n const logger = this.logger.for(this.disconnect.name);\n\n if (!this.client) {\n logger.info('Invalid client to disconnect | id: %s', this.identifier);\n\n return;\n }\n\n this.client.disconnect();\n }\n\n emit<T = unknown>(opts: { topic: string; data: T; doLog?: boolean; callback?: () => void }) {\n const logger = this.logger.for(this.emit.name);\n const { topic, data, doLog = false, callback } = opts;\n\n if (!this.client?.connected) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: 'Invalid socket client state to emit',\n });\n }\n\n if (!topic) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: 'Topic is required to emit',\n });\n }\n\n this.client.emit(topic, data);\n\n if (callback) {\n setImmediate(callback);\n }\n\n if (doLog) {\n logger.info('Emitted | topic: %s | data: %j', topic, data);\n }\n }\n\n joinRooms(opts: { rooms: string[] }) {\n const logger = this.logger.for(this.joinRooms.name);\n const { rooms } = opts;\n\n if (!this.client?.connected) {\n logger.warn('Cannot join rooms | id: %s | reason: not connected', this.identifier);\n\n return;\n }\n\n this.client.emit(SocketIOConstants.EVENT_JOIN, { rooms });\n logger.info('Join rooms requested | id: %s | rooms: %j', this.identifier, rooms);\n }\n\n leaveRooms(opts: { rooms: string[] }) {\n const logger = this.logger.for(this.leaveRooms.name);\n const { rooms } = opts;\n\n if (!this.client?.connected) {\n logger.warn('Cannot leave rooms | id: %s | reason: not connected', this.identifier);\n\n return;\n }\n\n this.client.emit(SocketIOConstants.EVENT_LEAVE, { rooms });\n logger.info('Leave rooms requested | id: %s | rooms: %j', this.identifier, rooms);\n }\n\n shutdown() {\n const logger = this.logger.for(this.shutdown.name);\n logger.info('Shutting down SocketIO client | id: %s', this.identifier);\n\n if (this.client) {\n this.client.removeAllListeners();\n\n if (this.client.connected) {\n this.client.disconnect();\n }\n }\n\n this.wrappedHandlers.clear();\n this.state = SocketIOClientStates.UNAUTHORIZED;\n logger.info('SocketIO client shutdown complete | id: %s', this.identifier);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"browser-helper.js","sourceRoot":"","sources":["../../../../../../src/modules/socket/socket-io/client/browser-helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAE/C,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,sGAAsG;AACtG,OAAO,EAAE,oBAAoB,EAAE,iBA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,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QACrD,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAEvB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC;YAC5B,MAAM,CAAC,IAAI,CAAC,qDAAqD,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YAEpF,OAAO;QACT,CAAC;QAED,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,WAAW,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC3D,MAAM,CAAC,IAAI,CAAC,4CAA4C,EAAE,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACpF,CAAC;IAED,QAAQ;QACN,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACnD,MAAM,CAAC,IAAI,CAAC,wCAAwC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;QAEvE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,MAAM,CAAC,kBAAkB,EAAE,CAAC;YAEjC,IAAI,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;gBAC1B,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;YAC3B,CAAC;QACH,CAAC;QAED,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;QAC7B,IAAI,CAAC,KAAK,GAAG,oBAAoB,CAAC,YAAY,CAAC;QAC/C,MAAM,CAAC,IAAI,CAAC,4CAA4C,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAC7E,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport { type ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport type { Socket } from 'socket.io-client';\n// The leaf files, never the `../common` barrel: it reaches the server types, which name node modules.\nimport { SocketIOClientStates, SocketIOConstants } from '../common/constants';\nimport type {\n IOptions,\n ISocketIOClientOptions,\n TSocketIOClientState,\n} from '../common/types/client';\nimport type { TSocketIOEventHandler } from '../common/types/hooks';\n\n/** What `socket.off` takes back: the wrapper `subscribe` registered in place of the caller's handler. */\ntype TWrappedListener = NonNullable<Parameters<Socket['off']>[1]>;\n\n/**\n * The socket.io client with nothing node in its graph, so a browser bundle can hold it: `socket.io-client`\n * is handed in as `module` (`{ io }` from the app's own `import`) instead of being found on disk.\n * `@venizia/ignis-helpers/socket-io` extends it and finds the module itself when none is handed in.\n */\nexport class SocketIOClientHelper extends BaseHelper {\n private host: string;\n private options: IOptions;\n private client: Socket;\n private state: TSocketIOClientState = SocketIOClientStates.UNAUTHORIZED;\n\n // subscribe() registers a wrapper, never the caller handler: without this map unsubscribe() has nothing to hand to socket.off() and the listener stays bound forever\n private wrappedHandlers: Map<string, Map<TSocketIOEventHandler<never>, TWrappedListener>> =\n new Map();\n\n private onConnected?: () => ValueOrPromise<void>;\n private onDisconnected?: (reason: string) => ValueOrPromise<void>;\n private onError?: (error: Error) => ValueOrPromise<void>;\n private onAuthenticated?: () => ValueOrPromise<void>;\n private onUnauthenticated?: (message: string) => ValueOrPromise<void>;\n\n protected readonly clientModule?: typeof import('socket.io-client');\n\n constructor(opts: ISocketIOClientOptions) {\n super({ scope: opts.identifier });\n\n this.identifier = opts.identifier;\n this.host = opts.host;\n this.options = opts.options;\n this.clientModule = opts.module;\n\n this.onConnected = opts.onConnected;\n this.onDisconnected = opts.onDisconnected;\n this.onError = opts.onError;\n this.onAuthenticated = opts.onAuthenticated;\n this.onUnauthenticated = opts.onUnauthenticated;\n\n this.configure();\n }\n\n /** The `socket.io-client` module to connect with. Here only the one handed in; a subclass may find one. */\n protected resolveModule(): typeof import('socket.io-client') {\n if (!this.clientModule) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[SocketIOClientHelper][${this.identifier}] option 'module' is required: pass { io } from 'socket.io-client'`,\n });\n }\n\n return this.clientModule;\n }\n\n getState(): TSocketIOClientState {\n return this.state;\n }\n\n configure() {\n const logger = this.logger.for(this.configure.name);\n\n if (this.client) {\n logger.info('SocketIO Client already established | id: %s', this.identifier);\n\n return;\n }\n\n const { io } = this.resolveModule();\n this.client = io(this.host, this.options);\n\n // Socket.IO client fires 'connect', NOT 'connection' (server-side only)\n this.client.on('connect', () => {\n logger.info('Connected | id: %s', this.identifier);\n\n Promise.resolve(this.onConnected?.()).catch((error) => {\n logger.error('onConnected callback error | error: %s', error);\n });\n });\n\n this.client.on(SocketIOConstants.EVENT_DISCONNECT, (reason: string) => {\n logger.info('Disconnected | id: %s | reason: %s', this.identifier, reason);\n this.state = SocketIOClientStates.UNAUTHORIZED;\n\n Promise.resolve(this.onDisconnected?.(reason)).catch((error) => {\n logger.error('onDisconnected callback error | error: %s', error);\n });\n });\n\n this.client.on('connect_error', (error: Error) => {\n logger.error('Connection error | id: %s | error: %s', this.identifier, error);\n\n Promise.resolve(this.onError?.(error)).catch((err) => {\n logger.error('onError callback error | error: %s', err);\n });\n });\n\n this.client.on(SocketIOConstants.EVENT_AUTHENTICATED, (data: unknown) => {\n logger.info('Authenticated | id: %s | data: %j', this.identifier, data);\n this.state = SocketIOClientStates.AUTHENTICATED;\n\n Promise.resolve(this.onAuthenticated?.()).catch((error) => {\n logger.error('onAuthenticated callback error | error: %s', error);\n });\n });\n\n this.client.on(SocketIOConstants.EVENT_UNAUTHENTICATE, (data: { message?: string }) => {\n logger.warn('Unauthenticated | id: %s | data: %j', this.identifier, data);\n this.state = SocketIOClientStates.UNAUTHORIZED;\n\n Promise.resolve(this.onUnauthenticated?.(data?.message ?? '')).catch((error) => {\n logger.error('onUnauthenticated callback error | error: %s', error);\n });\n });\n\n this.client.on(SocketIOConstants.EVENT_PING, () => {\n logger.debug('Ping received | id: %s', this.identifier);\n });\n }\n\n getSocketClient(): Socket {\n return this.client;\n }\n\n authenticate() {\n const logger = this.logger.for(this.authenticate.name);\n\n if (!this.client?.connected) {\n logger.warn('Cannot authenticate | id: %s | reason: not connected', this.identifier);\n\n return;\n }\n\n if (this.state !== SocketIOClientStates.UNAUTHORIZED) {\n logger.warn('Cannot authenticate | id: %s | currentState: %s', this.identifier, this.state);\n\n return;\n }\n\n this.state = SocketIOClientStates.AUTHENTICATING;\n this.client.emit(SocketIOConstants.EVENT_AUTHENTICATE);\n logger.info('Authentication requested | id: %s', this.identifier);\n }\n\n subscribe<T = unknown>(opts: {\n event: string;\n handler: TSocketIOEventHandler<T>;\n ignoreDuplicate?: boolean;\n }) {\n const logger = this.logger.for(this.subscribe.name);\n const { event, handler, ignoreDuplicate = true } = opts;\n\n if (!handler) {\n logger.warn('No handler provided | event: %s', event);\n\n return;\n }\n\n if (ignoreDuplicate && this.client.hasListeners(event)) {\n logger.info('Handler already exists | event: %s', event);\n\n return;\n }\n\n // Wrap handler in try-catch for error safety (catches both sync throws and async rejections)\n const wrappedHandler = (data: T) => {\n try {\n Promise.resolve(handler(data)).catch((error) => {\n logger.error('Handler error | event: %s | error: %s', event, error);\n });\n } catch (error) {\n logger.error('Handler error | event: %s | error: %s', event, error);\n }\n };\n\n if (!this.wrappedHandlers.has(event)) {\n this.wrappedHandlers.set(event, new Map());\n }\n\n this.wrappedHandlers.get(event)!.set(handler, wrappedHandler);\n\n this.client.on(event, wrappedHandler);\n logger.info('Subscribed | event: %s', event);\n }\n\n subscribeMany(opts: {\n events: Record<string, TSocketIOEventHandler>;\n ignoreDuplicate?: boolean;\n }) {\n const { events, ignoreDuplicate } = opts;\n\n for (const event in events) {\n this.subscribe({\n event,\n handler: events[event],\n ignoreDuplicate,\n });\n }\n }\n\n unsubscribe(opts: { event: string; handler?: TSocketIOEventHandler }) {\n const logger = this.logger.for(this.unsubscribe.name);\n const { event, handler } = opts;\n\n if (!this.client?.hasListeners(event)) {\n logger.info('No listeners to remove | event: %s', event);\n\n return;\n }\n\n if (handler) {\n const wrappedHandler = this.wrappedHandlers.get(event)?.get(handler);\n\n if (!wrappedHandler) {\n logger.info('Handler was not subscribed through this helper | event: %s', event);\n\n return;\n }\n\n this.client.off(event, wrappedHandler);\n this.wrappedHandlers.get(event)?.delete(handler);\n\n if (!this.wrappedHandlers.get(event)?.size) {\n this.wrappedHandlers.delete(event);\n }\n\n logger.info('Removed specific handler | event: %s', event);\n\n return;\n }\n\n this.client.off(event);\n this.wrappedHandlers.delete(event);\n logger.info('Removed all handlers | event: %s', event);\n }\n\n unsubscribeMany(opts: { events: string[] }) {\n for (const event of opts.events) {\n this.unsubscribe({ event });\n }\n }\n\n connect() {\n const logger = this.logger.for(this.connect.name);\n\n if (!this.client) {\n logger.info('Invalid client to connect | id: %s', this.identifier);\n\n return;\n }\n\n this.client.connect();\n }\n\n disconnect() {\n const logger = this.logger.for(this.disconnect.name);\n\n if (!this.client) {\n logger.info('Invalid client to disconnect | id: %s', this.identifier);\n\n return;\n }\n\n this.client.disconnect();\n }\n\n emit<T = unknown>(opts: { topic: string; data: T; doLog?: boolean; callback?: () => void }) {\n const logger = this.logger.for(this.emit.name);\n const { topic, data, doLog = false, callback } = opts;\n\n if (!this.client?.connected) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: 'Invalid socket client state to emit',\n });\n }\n\n if (!topic) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: 'Topic is required to emit',\n });\n }\n\n this.client.emit(topic, data);\n\n if (callback) {\n setImmediate(callback);\n }\n\n if (doLog) {\n logger.info('Emitted | topic: %s | data: %j', topic, data);\n }\n }\n\n joinRooms(opts: { rooms: string[] }) {\n const logger = this.logger.for(this.joinRooms.name);\n const { rooms } = opts;\n\n if (!this.client?.connected) {\n logger.warn('Cannot join rooms | id: %s | reason: not connected', this.identifier);\n\n return;\n }\n\n this.client.emit(SocketIOConstants.EVENT_JOIN, { rooms });\n logger.info('Join rooms requested | id: %s | rooms: %j', this.identifier, rooms);\n }\n\n leaveRooms(opts: { rooms: string[] }) {\n const logger = this.logger.for(this.leaveRooms.name);\n const { rooms } = opts;\n\n if (!this.client?.connected) {\n logger.warn('Cannot leave rooms | id: %s | reason: not connected', this.identifier);\n\n return;\n }\n\n this.client.emit(SocketIOConstants.EVENT_LEAVE, { rooms });\n logger.info('Leave rooms requested | id: %s | rooms: %j', this.identifier, rooms);\n }\n\n shutdown() {\n const logger = this.logger.for(this.shutdown.name);\n logger.info('Shutting down SocketIO client | id: %s', this.identifier);\n\n if (this.client) {\n this.client.removeAllListeners();\n\n if (this.client.connected) {\n this.client.disconnect();\n }\n }\n\n this.wrappedHandlers.clear();\n this.state = SocketIOClientStates.UNAUTHORIZED;\n logger.info('SocketIO client shutdown complete | id: %s', this.identifier);\n }\n}\n"]}
|
|
@@ -15,7 +15,7 @@ export interface IHandshake {
|
|
|
15
15
|
url: string;
|
|
16
16
|
query: ParsedUrlQuery;
|
|
17
17
|
auth: {
|
|
18
|
-
[key: string]:
|
|
18
|
+
[key: string]: unknown;
|
|
19
19
|
};
|
|
20
20
|
}
|
|
21
21
|
/** One of the `SocketIOClientStates` values. */
|
|
@@ -31,7 +31,7 @@ export interface ISocketIOClient {
|
|
|
31
31
|
/** Connection options for the Socket.IO client helper: the `socket.io-client` options plus a required `path` and `extraHeaders`. */
|
|
32
32
|
export interface IOptions extends SocketOptions {
|
|
33
33
|
path: string;
|
|
34
|
-
extraHeaders: Record<string
|
|
34
|
+
extraHeaders: Record<string, string>;
|
|
35
35
|
}
|
|
36
36
|
/** Options for the Socket.IO client helper. The `on*` callbacks fire on the matching connection or authentication event. */
|
|
37
37
|
export interface ISocketIOClientOptions {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../../../../../src/modules/socket/socket-io/common/types/client.ts"],"names":[],"mappings":"","sourcesContent":["import { type TConstValue, type ValueOrPromise } from '@/common/types';\nimport { type IncomingHttpHeaders } from 'node:http';\nimport { type ParsedUrlQuery } from 'node:querystring';\nimport type { Socket as IOSocket } from 'socket.io';\nimport type { SocketOptions } from 'socket.io-client';\nimport { type SocketIOClientStates } from '../constants';\n\n/** Handshake data of a connecting Socket.IO client; passed to the authenticate hook. */\nexport interface IHandshake {\n headers: IncomingHttpHeaders;\n time: string;\n address: string;\n xdomain: boolean;\n secure: boolean;\n issued: number;\n url: string;\n query: ParsedUrlQuery;\n auth: {\n [key: string]:
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../../../../../src/modules/socket/socket-io/common/types/client.ts"],"names":[],"mappings":"","sourcesContent":["import { type TConstValue, type ValueOrPromise } from '@/common/types';\nimport { type IncomingHttpHeaders } from 'node:http';\nimport { type ParsedUrlQuery } from 'node:querystring';\nimport type { Socket as IOSocket } from 'socket.io';\nimport type { SocketOptions } from 'socket.io-client';\nimport { type SocketIOClientStates } from '../constants';\n\n/** Handshake data of a connecting Socket.IO client; passed to the authenticate hook. */\nexport interface IHandshake {\n headers: IncomingHttpHeaders;\n time: string;\n address: string;\n xdomain: boolean;\n secure: boolean;\n issued: number;\n url: string;\n query: ParsedUrlQuery;\n auth: {\n [key: string]: unknown;\n };\n}\n\n/** One of the `SocketIOClientStates` values. */\nexport type TSocketIOClientState = TConstValue<typeof SocketIOClientStates>;\n\n/** A connected Socket.IO client as tracked by the server helper, with its authentication state and timers. */\nexport interface ISocketIOClient {\n id: string;\n socket: IOSocket;\n state: TSocketIOClientState;\n interval?: NodeJS.Timeout;\n authenticateTimeout?: NodeJS.Timeout;\n}\n\n/** Connection options for the Socket.IO client helper: the `socket.io-client` options plus a required `path` and `extraHeaders`. */\nexport interface IOptions extends SocketOptions {\n path: string;\n extraHeaders: Record<string, string>;\n}\n\n/** Options for the Socket.IO client helper. The `on*` callbacks fire on the matching connection or authentication event. */\nexport interface ISocketIOClientOptions {\n identifier: string;\n host: string;\n options: IOptions;\n\n /** `socket.io-client` itself, for a `bun build --compile` binary that has no `node_modules` to load it from. Omitted, it is loaded on `configure()`. */\n module?: typeof import('socket.io-client');\n\n onConnected?: () => ValueOrPromise<void>;\n onDisconnected?: (reason: string) => ValueOrPromise<void>;\n onError?: (error: Error) => ValueOrPromise<void>;\n onAuthenticated?: () => ValueOrPromise<void>;\n onUnauthenticated?: (message: string) => ValueOrPromise<void>;\n}\n"]}
|
|
@@ -17,10 +17,12 @@ export interface ISocketIOServerBaseOptions {
|
|
|
17
17
|
validateRoomFn?: TSocketIOValidateRoomFn;
|
|
18
18
|
clientConnectedFn?: TSocketIOClientConnectedFn;
|
|
19
19
|
}
|
|
20
|
+
/** A `@socket.io/bun-engine` server. Socket.IO types what `io.bind` takes as `any` and the engine is an optional peer, so the helper names only that it is an object it passes on. */
|
|
21
|
+
export type TSocketIOBunEngine = object;
|
|
20
22
|
/** Socket.IO server options for the Bun runtime; `engine` is a `@socket.io/bun-engine` server instance. */
|
|
21
23
|
export interface ISocketIOServerBunOptions extends ISocketIOServerBaseOptions {
|
|
22
24
|
runtime: typeof RuntimeModules.BUN;
|
|
23
|
-
engine:
|
|
25
|
+
engine: TSocketIOBunEngine;
|
|
24
26
|
}
|
|
25
27
|
/** Options accepted by `SocketIOServerHelper`. */
|
|
26
28
|
export type TSocketIOServerOptions = ISocketIOServerBunOptions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../../../../../../src/modules/socket/socket-io/common/types/server.ts"],"names":[],"mappings":"","sourcesContent":["import { type RuntimeModules } from '@/common/constants';\nimport { type IRedisHelper } from '@/modules/redis';\nimport type { ServerOptions } from 'socket.io';\nimport {\n type TSocketIOAuthenticateFn,\n type TSocketIOClientConnectedFn,\n type TSocketIOValidateRoomFn,\n} from './hooks';\n\n/** Options shared by every Socket.IO server runtime. `authenticateTimeout` and `pingInterval` are milliseconds. */\nexport interface ISocketIOServerBaseOptions {\n identifier: string;\n serverOptions: Partial<ServerOptions>;\n redisConnection: IRedisHelper;\n /** @default [SocketIOConstants.ROOM_DEFAULT, SocketIOConstants.ROOM_NOTIFICATION] */\n defaultRooms?: string[];\n /** @default 10_000 */\n authenticateTimeout?: number;\n /** @default 30_000 */\n pingInterval?: number;\n\n authenticateFn: TSocketIOAuthenticateFn;\n validateRoomFn?: TSocketIOValidateRoomFn;\n clientConnectedFn?: TSocketIOClientConnectedFn;\n}\n\n/** Socket.IO server options for the Bun runtime; `engine` is a `@socket.io/bun-engine` server instance. */\nexport interface ISocketIOServerBunOptions extends ISocketIOServerBaseOptions {\n runtime: typeof RuntimeModules.BUN;\n engine:
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../../../../../../src/modules/socket/socket-io/common/types/server.ts"],"names":[],"mappings":"","sourcesContent":["import { type RuntimeModules } from '@/common/constants';\nimport { type IRedisHelper } from '@/modules/redis';\nimport type { ServerOptions } from 'socket.io';\nimport {\n type TSocketIOAuthenticateFn,\n type TSocketIOClientConnectedFn,\n type TSocketIOValidateRoomFn,\n} from './hooks';\n\n/** Options shared by every Socket.IO server runtime. `authenticateTimeout` and `pingInterval` are milliseconds. */\nexport interface ISocketIOServerBaseOptions {\n identifier: string;\n serverOptions: Partial<ServerOptions>;\n redisConnection: IRedisHelper;\n /** @default [SocketIOConstants.ROOM_DEFAULT, SocketIOConstants.ROOM_NOTIFICATION] */\n defaultRooms?: string[];\n /** @default 10_000 */\n authenticateTimeout?: number;\n /** @default 30_000 */\n pingInterval?: number;\n\n authenticateFn: TSocketIOAuthenticateFn;\n validateRoomFn?: TSocketIOValidateRoomFn;\n clientConnectedFn?: TSocketIOClientConnectedFn;\n}\n\n/** A `@socket.io/bun-engine` server. Socket.IO types what `io.bind` takes as `any` and the engine is an optional peer, so the helper names only that it is an object it passes on. */\nexport type TSocketIOBunEngine = object;\n\n/** Socket.IO server options for the Bun runtime; `engine` is a `@socket.io/bun-engine` server instance. */\nexport interface ISocketIOServerBunOptions extends ISocketIOServerBaseOptions {\n runtime: typeof RuntimeModules.BUN;\n engine: TSocketIOBunEngine;\n}\n\n/** Options accepted by `SocketIOServerHelper`. */\nexport type TSocketIOServerOptions = ISocketIOServerBunOptions;\n"]}
|
|
@@ -28,7 +28,7 @@ export declare class SocketIOServerHelper extends BaseHelper {
|
|
|
28
28
|
scope: string;
|
|
29
29
|
execution: () => ValueOrPromise<void>;
|
|
30
30
|
}): void;
|
|
31
|
-
getEngine():
|
|
31
|
+
getEngine(): object | undefined;
|
|
32
32
|
getClients(opts?: {
|
|
33
33
|
id?: string;
|
|
34
34
|
}): ISocketIOClient | Map<string, ISocketIOClient> | undefined;
|
|
@@ -68,7 +68,7 @@ export declare class SocketIOServerHelper extends BaseHelper {
|
|
|
68
68
|
destination?: string;
|
|
69
69
|
payload: {
|
|
70
70
|
topic: string;
|
|
71
|
-
data:
|
|
71
|
+
data: unknown;
|
|
72
72
|
};
|
|
73
73
|
doLog?: boolean;
|
|
74
74
|
callback?: () => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../../src/modules/socket/socket-io/server/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,cAAc,EAAuB,MAAM,oBAAoB,CAAC;AAEzE,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAqB,MAAM,iBAAiB,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAEnD,OAAO,EAAE,MAAM,IAAI,QAAQ,EAA+C,MAAM,WAAW,CAAC;AAC5F,OAAO,EAGL,oBAAoB,EACpB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,kCAAkC,CAAC,CAAC;QAEhD,KAAK,MAAM,CAAC,EAAE,MAAM,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACtC,IAAI,MAAM,CAAC,QAAQ,EAAE,CAAC;gBACpB,aAAa,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YACjC,CAAC;YAED,IAAI,MAAM,CAAC,mBAAmB,EAAE,CAAC;gBAC/B,YAAY,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC;YAC3C,CAAC;YAED,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;QAC7B,CAAC;QAED,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QAErB,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;QACrB,CAAC;gBAAS,CAAC;YACT,yLAAyL;YACzL,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,IAAI,CAAC,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QAC/F,CAAC;QAED,MAAM,CAAC,IAAI,CAAC,mCAAmC,CAAC,CAAC;IACnD,CAAC;CACF","sourcesContent":["import { ObjectUtility } from '@venizia/ignis-inversion';\nimport { HTTP } from '@/common';\nimport { RuntimeModules, type TRuntimeModule } from '@/common/constants';\nimport { type ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { RedisUtility, type TRedisClient } from '@/modules/redis';\nimport { PromiseUtility } from '@/utilities/promise.utility';\nimport { createAdapter } from '@socket.io/redis-adapter';\nimport { Emitter } from '@socket.io/redis-emitter';\nimport { type EventEmitter } from 'node:events';\nimport { Server as IOServer, type Socket as IOSocket, type ServerOptions } from 'socket.io';\nimport {\n type IHandshake,\n type ISocketIOClient,\n SocketIOClientStates,\n SocketIOConstants,\n type TSocketIOAuthenticateFn,\n type TSocketIOClientConnectedFn,\n type TSocketIOServerOptions,\n type TSocketIOValidateRoomFn,\n} from '../common';\n\nconst CLIENT_AUTHENTICATE_TIMEOUT = 10_000;\nconst CLIENT_PING_INTERVAL = 30_000;\n\n/** Socket.IO server over a Redis adapter. Clients must authenticate through `authenticateFn` within `authenticateTimeout` and are pinged every `pingInterval`. */\nexport class SocketIOServerHelper extends BaseHelper {\n private runtime: TRuntimeModule;\n private bunEngine?: any;\n private serverOptions: Partial<ServerOptions> = {};\n\n private io: IOServer;\n private emitter: Emitter;\n private clients: Map<string, ISocketIOClient> = new Map();\n\n private redisPub: TRedisClient;\n private redisSub: TRedisClient;\n private redisEmitter: TRedisClient;\n\n private authenticateFn: TSocketIOAuthenticateFn;\n private validateRoomFn?: TSocketIOValidateRoomFn;\n private onClientConnected?: TSocketIOClientConnectedFn;\n\n private authenticateTimeout: number;\n private pingInterval: number;\n private defaultRooms: string[];\n\n constructor(opts: TSocketIOServerOptions) {\n super({ scope: opts.identifier });\n\n this.identifier = opts.identifier;\n this.runtime = opts.runtime;\n this.serverOptions = opts?.serverOptions ?? {};\n\n this.authenticateFn = opts.authenticateFn;\n this.validateRoomFn = opts.validateRoomFn;\n this.onClientConnected = opts.clientConnectedFn;\n\n this.authenticateTimeout = opts.authenticateTimeout ?? CLIENT_AUTHENTICATE_TIMEOUT;\n this.pingInterval = opts.pingInterval ?? CLIENT_PING_INTERVAL;\n this.defaultRooms = opts.defaultRooms ?? [\n SocketIOConstants.ROOM_DEFAULT,\n SocketIOConstants.ROOM_NOTIFICATION,\n ];\n\n this.setRuntime(opts);\n this.initRedisClients(opts.redisConnection);\n }\n\n private setRuntime(opts: TSocketIOServerOptions) {\n switch (opts.runtime) {\n case RuntimeModules.BUN: {\n if (!opts.engine) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message:\n '[SocketIOServerHelper] Invalid @socket.io/bun-engine instance for Bun runtime!',\n });\n }\n\n this.bunEngine = opts.engine;\n break;\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[SocketIOServerHelper] Unsupported runtime!',\n });\n }\n }\n }\n\n private initRedisClients(redisConnection: TSocketIOServerOptions['redisConnection']) {\n if (!redisConnection) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: 'Invalid redis connection to config socket.io adapter!',\n });\n }\n\n this.redisPub = redisConnection.duplicateClient();\n this.redisSub = redisConnection.duplicateClient();\n this.redisEmitter = redisConnection.duplicateClient();\n }\n\n getIOServer(): IOServer {\n return this.io;\n }\n\n /** Handlers run inside socket.io event listeners - a sync throw there kills the process; voidExecution only catches promise rejections since its argument evaluates before the try/catch. */\n protected invokeHook(opts: { scope: string; execution: () => ValueOrPromise<void> }) {\n const { scope, execution } = opts;\n\n try {\n PromiseUtility.voidExecution({ logger: this.logger, scope, execution: execution() });\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n getEngine() {\n return this.bunEngine;\n }\n\n getClients(opts?: { id?: string }): ISocketIOClient | Map<string, ISocketIOClient> | undefined {\n const { id } = opts ?? {};\n\n if (id) {\n return this.clients.get(id);\n }\n\n return this.clients;\n }\n\n on<HandlerArgsType extends unknown[] = unknown[], HanderReturnType = void>(opts: {\n topic: string;\n handler: (...args: HandlerArgsType) => ValueOrPromise<HanderReturnType>;\n }) {\n const { topic, handler } = opts;\n\n if (!topic) {\n throw getError({ message: '[on] Invalid topic to start binding handler' });\n }\n\n if (!handler) {\n throw getError({ message: `[on] Invalid event handler | topic: ${topic}` });\n }\n\n if (!this.io) {\n throw getError({ message: '[on] IOServer is not initialized yet!' });\n }\n\n this.io.on(topic, handler);\n }\n\n async configure() {\n const logger = this.logger.for(this.configure.name);\n logger.info('Configuring IO Server | id: %s | runtime: %s', this.identifier, this.runtime);\n\n (this.redisPub as EventEmitter).on('error', (error: Error) => {\n logger.error('Redis adapter pub error | error: %s', error);\n });\n\n (this.redisSub as EventEmitter).on('error', (error: Error) => {\n logger.error('Redis adapter sub error | error: %s', error);\n });\n\n (this.redisEmitter as EventEmitter).on('error', (error: Error) => {\n logger.error('Redis emitter error | error: %s', error);\n });\n\n RedisUtility.ensureConnecting({\n clients: [this.redisPub, this.redisSub, this.redisEmitter],\n logger: this.logger,\n scope: this.configure.name,\n });\n\n await Promise.all([\n RedisUtility.waitForReady({ client: this.redisPub }),\n RedisUtility.waitForReady({ client: this.redisSub }),\n RedisUtility.waitForReady({ client: this.redisEmitter }),\n ]);\n logger.info('All Redis connections ready');\n\n this.initIOServer();\n\n this.io.adapter(createAdapter(this.redisPub, this.redisSub));\n logger.info('SocketIO Server initialized Redis Adapter');\n\n this.emitter = new Emitter(this.redisEmitter);\n logger.info('SocketIO Server initialized Redis Emitter');\n\n this.io.on(SocketIOConstants.EVENT_CONNECT, (socket: IOSocket) => {\n this.onClientConnect({ socket });\n });\n\n logger.info(\n 'SocketIO Server READY | path: %s | runtime: %s',\n this.serverOptions?.path ?? '',\n this.runtime,\n );\n }\n\n private initIOServer() {\n switch (this.runtime) {\n case RuntimeModules.BUN: {\n if (!this.bunEngine) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[DANGER] Invalid @socket.io/bun-engine instance to init Socket.io server!',\n });\n }\n\n this.io = new IOServer();\n this.io.bind(this.bunEngine);\n break;\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[configure] Unsupported runtime: ${this.runtime}`,\n });\n }\n }\n }\n\n onClientConnect(opts: { socket: IOSocket }) {\n const logger = this.logger.for(this.onClientConnect.name);\n const { socket } = opts;\n\n if (!socket) {\n logger.info('Invalid new socket connection!');\n\n return;\n }\n\n const { id, handshake } = socket;\n\n if (this.clients.has(id)) {\n logger.info('Socket client already existed | id: %s', id);\n\n return;\n }\n\n logger.info('New connection request | id: %s', id);\n\n const client: ISocketIOClient = {\n id,\n socket,\n state: SocketIOClientStates.UNAUTHORIZED,\n authenticateTimeout: setTimeout(() => {\n const currentClient = this.clients.get(id);\n\n if (currentClient?.state === SocketIOClientStates.AUTHENTICATED) {\n return;\n }\n\n this.disconnect({ socket });\n }, this.authenticateTimeout),\n };\n this.clients.set(id, client);\n\n socket.on(SocketIOConstants.EVENT_DISCONNECT, () => {\n this.disconnect({ socket });\n });\n\n this.registerAuthHandler({ socket, handshake, clientId: id });\n }\n\n private registerAuthHandler(opts: { socket: IOSocket; handshake: IHandshake; clientId: string }) {\n const { socket, handshake, clientId: id } = opts;\n const authLogger = this.logger.for('onClientAuthenticate');\n\n socket.on(SocketIOConstants.EVENT_AUTHENTICATE, () => {\n const currentClient = this.clients.get(id);\n\n if (!currentClient) {\n authLogger.warn('Client no longer exists during auth | id: %s', id);\n\n return;\n }\n\n if (currentClient.state !== SocketIOClientStates.UNAUTHORIZED) {\n authLogger.warn(\n 'Client attempted auth in invalid state | id: %s | currentState: %s',\n id,\n currentClient.state,\n );\n\n return;\n }\n\n currentClient.state = SocketIOClientStates.AUTHENTICATING;\n\n Promise.resolve()\n .then(() => this.authenticateFn(handshake))\n .then((rs: boolean) => {\n if (!this.clients.has(id)) {\n authLogger.info('Client disconnected during authentication | id: %s', id);\n\n return;\n }\n\n authLogger.info('Authentication completed | id: %s | result: %s', id, rs);\n\n if (rs) {\n this.onClientAuthenticated({ socket });\n\n return;\n }\n\n const failedClient = this.clients.get(id);\n\n if (failedClient) {\n failedClient.state = SocketIOClientStates.UNAUTHORIZED;\n }\n\n this.rejectClient({\n socket,\n message: 'Invalid token to authenticate! Please login again!',\n });\n })\n .catch((error: Error) => {\n const errorClient = this.clients.get(id);\n\n if (errorClient) {\n errorClient.state = SocketIOClientStates.UNAUTHORIZED;\n }\n\n authLogger.error('Failed to authenticate | id: %s | error: %s', id, error);\n\n this.rejectClient({\n socket,\n message: 'Failed to authenticate connection! Please login again!',\n });\n });\n });\n }\n\n // The socket is connected to this process, so the notice goes out on it directly: routed through the Redis emitter it arrives after the disconnect and is dropped.\n private rejectClient(opts: { socket: IOSocket; message: string }) {\n const { socket, message } = opts;\n\n socket.emit(SocketIOConstants.EVENT_UNAUTHENTICATE, {\n message,\n time: new Date().toISOString(),\n });\n this.disconnect({ socket });\n }\n\n onClientAuthenticated(opts: { socket: IOSocket }) {\n const logger = this.logger.for(this.onClientAuthenticated.name);\n const { socket } = opts;\n\n if (!socket) {\n logger.info('Invalid new socket connection!');\n\n return;\n }\n\n const { id } = socket;\n const client = this.clients.get(id);\n\n if (!client) {\n logger.info('Unknown client | id: %s', id);\n this.disconnect({ socket });\n\n return;\n }\n\n client.state = SocketIOClientStates.AUTHENTICATED;\n\n // The authenticate deadline is over: leaving it armed keeps a timer per client alive\n if (client.authenticateTimeout) {\n clearTimeout(client.authenticateTimeout);\n client.authenticateTimeout = undefined;\n }\n\n this.ping({ socket, doIgnoreAuth: true });\n\n logger.info(\n 'Client connected | id: %s | identifier: %s | time: %s',\n id,\n this.identifier,\n new Date().toISOString(),\n );\n\n // The authenticated room first, and whatever `defaultRooms` the application configured: a broadcast must reach an\n // authenticated socket even when the application replaced the defaults.\n const rooms = [...new Set([SocketIOConstants.ROOM_AUTHENTICATED, ...this.defaultRooms])];\n\n Promise.all(rooms.map((room: string) => Promise.resolve(socket.join(room))))\n .then(() => {\n logger.info('Joined default rooms | id: %s | rooms: %s', id, rooms);\n })\n .catch((error) => {\n logger.error(\n 'Failed to join default rooms | id: %s | rooms: %s | error: %s',\n id,\n rooms,\n error,\n );\n });\n\n this.registerRoomHandlers({ socket, clientId: id });\n\n client.interval = setInterval(() => {\n this.ping({ socket, doIgnoreAuth: true });\n }, this.pingInterval);\n\n this.send({\n destination: socket.id,\n payload: {\n topic: SocketIOConstants.EVENT_AUTHENTICATED,\n data: {\n id: socket.id,\n time: new Date().toISOString(),\n },\n },\n });\n\n this.invokeHook({\n scope: 'clientConnectedFn',\n execution: () => this.onClientConnected?.({ socket }),\n });\n }\n\n /**\n * Narrows an untrusted room payload to the strings it actually contains.\n *\n * The listeners below run on data any authenticated client sends. Destructuring `{ rooms = [] }`\n * out of an `any` and testing `rooms?.length` accepts a STRING - `{\"rooms\":\"lobby\"}` has a\n * length of 5 - and the next line calls `rooms.map`, which a string does not have. socket.io\n * dispatches on `process.nextTick` with no try/catch around the handler, so that TypeError\n * escapes as an uncaught exception and takes the process with it.\n */\n private static toRoomList(payload: unknown): string[] {\n const rooms = (payload as { rooms?: unknown } | null | undefined)?.rooms;\n\n return Array.isArray(rooms)\n ? rooms.filter((room): room is string => typeof room === 'string')\n : [];\n }\n\n private registerRoomHandlers(opts: { socket: IOSocket; clientId: string }) {\n const { socket, clientId: id } = opts;\n\n const joinLogger = this.logger.for(SocketIOConstants.EVENT_JOIN);\n socket.on(SocketIOConstants.EVENT_JOIN, (payload: any) => {\n const rooms = SocketIOServerHelper.toRoomList(payload);\n\n if (!rooms.length) {\n return;\n }\n\n const validateRoomFn = this.validateRoomFn;\n\n if (!validateRoomFn) {\n joinLogger.warn(\n 'Join rejected | id: %s | rooms: %j | reason: no validateRoomFn configured',\n id,\n rooms,\n );\n\n return;\n }\n\n Promise.resolve()\n .then(() => validateRoomFn({ socket, rooms }))\n .then((allowedRooms: string[]) => {\n if (!allowedRooms?.length) {\n joinLogger.warn(\n 'Join rejected | id: %s | rooms: %j | reason: no rooms allowed',\n id,\n rooms,\n );\n\n return;\n }\n\n joinLogger.info('Joining rooms | id: %s | rooms: %j', id, allowedRooms);\n\n for (const room of allowedRooms) {\n PromiseUtility.voidExecution({\n logger: this.logger,\n scope: SocketIOConstants.EVENT_JOIN,\n execution: socket.join(room),\n });\n }\n\n joinLogger.info('Joined rooms | id: %s | rooms: %s', id, allowedRooms);\n })\n .catch((error) => {\n joinLogger.error(\n 'Failed to join rooms | id: %s | rooms: %s | error: %s',\n id,\n rooms,\n error,\n );\n });\n });\n\n const leaveLogger = this.logger.for(SocketIOConstants.EVENT_LEAVE);\n socket.on(SocketIOConstants.EVENT_LEAVE, (payload: any) => {\n const rooms = SocketIOServerHelper.toRoomList(payload);\n\n if (!rooms.length) {\n return;\n }\n\n leaveLogger.info('Leaving rooms | id: %s | rooms: %j', id, rooms);\n\n // `Promise.resolve` per room: socket.io declares `leave(room): Promise<void> | void` - the\n // default adapter is synchronous, a clustered one is not - and `Promise.all` over a mixed\n // iterable is what the previous `any`-typed payload was hiding.\n Promise.all(rooms.map((room) => Promise.resolve(socket.leave(room))))\n .then(() => {\n leaveLogger.info('Left rooms | id: %s | rooms: %s', id, rooms);\n })\n .catch((error) => {\n leaveLogger.error(\n 'Failed to leave rooms | id: %s | rooms: %s | error: %s',\n id,\n rooms,\n error,\n );\n });\n });\n }\n\n ping(opts: { socket: IOSocket; doIgnoreAuth: boolean }) {\n const logger = this.logger.for(this.ping.name);\n const { socket, doIgnoreAuth } = opts;\n\n if (!socket) {\n logger.info('Socket is undefined to PING!');\n\n return;\n }\n\n const client = this.clients.get(socket.id);\n\n if (!client) {\n logger.info('Client not found | socketId: %s', socket.id);\n\n return;\n }\n\n if (!doIgnoreAuth && client.state !== SocketIOClientStates.AUTHENTICATED) {\n logger.info('Socket client is not authenticated | state: %s', client.state);\n this.disconnect({ socket });\n\n return;\n }\n\n socket.emit(SocketIOConstants.EVENT_PING, { time: new Date().toISOString() });\n }\n\n disconnect(opts: { socket: IOSocket }) {\n const logger = this.logger.for(this.disconnect.name);\n const { socket } = opts;\n\n if (!socket) {\n return;\n }\n\n const { id } = socket;\n\n if (this.clients.has(id)) {\n const client = this.clients.get(id)!;\n\n if (client.interval) {\n clearInterval(client.interval);\n }\n\n if (client.authenticateTimeout) {\n clearTimeout(client.authenticateTimeout);\n }\n\n this.clients.delete(id);\n }\n\n logger.info('Client disconnected | id: %s | time: %s', id, new Date().toISOString());\n socket.disconnect();\n }\n\n send(opts: {\n destination?: string;\n payload: { topic: string; data: any };\n doLog?: boolean;\n callback?: () => void;\n }) {\n const logger = this.logger.for(this.send.name);\n const { destination, payload, doLog, callback } = opts;\n\n if (!payload) {\n return;\n }\n\n const { topic, data } = payload;\n\n if (!topic || !data) {\n return;\n }\n\n if (!this.emitter) {\n logger.error(\n 'Cannot emit | Redis emitter is not initialized | call configure() first | topic: %s',\n topic,\n );\n\n return;\n }\n\n const sender = this.emitter.compress(true);\n\n if (destination && !ObjectUtility.isEmpty({ value: destination })) {\n sender.to(destination).emit(topic, data);\n } else {\n // Not `sender.emit`: that reaches every connected socket, the ones that have not authenticated included.\n sender.to(SocketIOConstants.ROOM_AUTHENTICATED).emit(topic, data);\n }\n\n if (callback) {\n setImmediate(callback);\n }\n\n if (doLog) {\n logger.info(\n 'Message emitted | destination: %s | topic: %s | data: %j',\n destination ?? SocketIOConstants.ROOM_AUTHENTICATED,\n topic,\n data,\n );\n }\n }\n\n private close() {\n return new Promise<void>((resolve, reject) => {\n // configure() may never have run (or may have failed): there is nothing to close, but the redis clients still have to be released by the caller\n if (!this.io) {\n this.logger.for('close').info('SKIP close | IOServer was never initialized');\n resolve();\n\n return;\n }\n\n PromiseUtility.voidExecution({\n logger: this.logger,\n scope: 'close',\n execution: this.io.close((error) => {\n if (error) {\n reject(error);\n\n return;\n }\n\n resolve();\n }),\n });\n });\n }\n\n async shutdown() {\n const logger = this.logger.for(this.shutdown.name);\n logger.info('Shutting down SocketIO server...');\n\n for (const [, client] of this.clients) {\n if (client.interval) {\n clearInterval(client.interval);\n }\n\n if (client.authenticateTimeout) {\n clearTimeout(client.authenticateTimeout);\n }\n\n client.socket.disconnect();\n }\n\n this.clients.clear();\n\n try {\n await this.close();\n } finally {\n // close() rejects when io.close() reports a lingering handle. Skipping the quits there leaves three live Redis sockets holding the event loop open, and a SIGTERM handler never returns.\n await Promise.all([this.redisPub?.quit(), this.redisSub?.quit(), this.redisEmitter?.quit()]);\n }\n\n logger.info('SocketIO server shutdown complete');\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../../src/modules/socket/socket-io/server/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MA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;QAC/F,CAAC;QAED,MAAM,CAAC,IAAI,CAAC,mCAAmC,CAAC,CAAC;IACnD,CAAC;CACF","sourcesContent":["import { ObjectUtility } from '@venizia/ignis-inversion';\nimport { HTTP } from '@/common';\nimport { RuntimeModules, type TRuntimeModule } from '@/common/constants';\nimport { type ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { RedisUtility, type TRedisClient } from '@/modules/redis';\nimport { PromiseUtility } from '@/utilities/promise.utility';\nimport { createAdapter } from '@socket.io/redis-adapter';\nimport { Emitter } from '@socket.io/redis-emitter';\nimport { type EventEmitter } from 'node:events';\nimport { Server as IOServer, type Socket as IOSocket, type ServerOptions } from 'socket.io';\nimport {\n type IHandshake,\n type ISocketIOClient,\n SocketIOClientStates,\n SocketIOConstants,\n type TSocketIOAuthenticateFn,\n type TSocketIOClientConnectedFn,\n type TSocketIOBunEngine,\n type TSocketIOServerOptions,\n type TSocketIOValidateRoomFn,\n} from '../common';\n\nconst CLIENT_AUTHENTICATE_TIMEOUT = 10_000;\nconst CLIENT_PING_INTERVAL = 30_000;\n\n/** Socket.IO server over a Redis adapter. Clients must authenticate through `authenticateFn` within `authenticateTimeout` and are pinged every `pingInterval`. */\nexport class SocketIOServerHelper extends BaseHelper {\n private runtime: TRuntimeModule;\n private bunEngine?: TSocketIOBunEngine;\n private serverOptions: Partial<ServerOptions> = {};\n\n private io: IOServer;\n private emitter: Emitter;\n private clients: Map<string, ISocketIOClient> = new Map();\n\n private redisPub: TRedisClient;\n private redisSub: TRedisClient;\n private redisEmitter: TRedisClient;\n\n private authenticateFn: TSocketIOAuthenticateFn;\n private validateRoomFn?: TSocketIOValidateRoomFn;\n private onClientConnected?: TSocketIOClientConnectedFn;\n\n private authenticateTimeout: number;\n private pingInterval: number;\n private defaultRooms: string[];\n\n constructor(opts: TSocketIOServerOptions) {\n super({ scope: opts.identifier });\n\n this.identifier = opts.identifier;\n this.runtime = opts.runtime;\n this.serverOptions = opts?.serverOptions ?? {};\n\n this.authenticateFn = opts.authenticateFn;\n this.validateRoomFn = opts.validateRoomFn;\n this.onClientConnected = opts.clientConnectedFn;\n\n this.authenticateTimeout = opts.authenticateTimeout ?? CLIENT_AUTHENTICATE_TIMEOUT;\n this.pingInterval = opts.pingInterval ?? CLIENT_PING_INTERVAL;\n this.defaultRooms = opts.defaultRooms ?? [\n SocketIOConstants.ROOM_DEFAULT,\n SocketIOConstants.ROOM_NOTIFICATION,\n ];\n\n this.setRuntime(opts);\n this.initRedisClients(opts.redisConnection);\n }\n\n private setRuntime(opts: TSocketIOServerOptions) {\n switch (opts.runtime) {\n case RuntimeModules.BUN: {\n if (!opts.engine) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message:\n '[SocketIOServerHelper] Invalid @socket.io/bun-engine instance for Bun runtime!',\n });\n }\n\n this.bunEngine = opts.engine;\n break;\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[SocketIOServerHelper] Unsupported runtime!',\n });\n }\n }\n }\n\n private initRedisClients(redisConnection: TSocketIOServerOptions['redisConnection']) {\n if (!redisConnection) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: 'Invalid redis connection to config socket.io adapter!',\n });\n }\n\n this.redisPub = redisConnection.duplicateClient();\n this.redisSub = redisConnection.duplicateClient();\n this.redisEmitter = redisConnection.duplicateClient();\n }\n\n getIOServer(): IOServer {\n return this.io;\n }\n\n /** Handlers run inside socket.io event listeners - a sync throw there kills the process; voidExecution only catches promise rejections since its argument evaluates before the try/catch. */\n protected invokeHook(opts: { scope: string; execution: () => ValueOrPromise<void> }) {\n const { scope, execution } = opts;\n\n try {\n PromiseUtility.voidExecution({ logger: this.logger, scope, execution: execution() });\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n getEngine() {\n return this.bunEngine;\n }\n\n getClients(opts?: { id?: string }): ISocketIOClient | Map<string, ISocketIOClient> | undefined {\n const { id } = opts ?? {};\n\n if (id) {\n return this.clients.get(id);\n }\n\n return this.clients;\n }\n\n on<HandlerArgsType extends unknown[] = unknown[], HanderReturnType = void>(opts: {\n topic: string;\n handler: (...args: HandlerArgsType) => ValueOrPromise<HanderReturnType>;\n }) {\n const { topic, handler } = opts;\n\n if (!topic) {\n throw getError({ message: '[on] Invalid topic to start binding handler' });\n }\n\n if (!handler) {\n throw getError({ message: `[on] Invalid event handler | topic: ${topic}` });\n }\n\n if (!this.io) {\n throw getError({ message: '[on] IOServer is not initialized yet!' });\n }\n\n this.io.on(topic, handler);\n }\n\n async configure() {\n const logger = this.logger.for(this.configure.name);\n logger.info('Configuring IO Server | id: %s | runtime: %s', this.identifier, this.runtime);\n\n (this.redisPub as EventEmitter).on('error', (error: Error) => {\n logger.error('Redis adapter pub error | error: %s', error);\n });\n\n (this.redisSub as EventEmitter).on('error', (error: Error) => {\n logger.error('Redis adapter sub error | error: %s', error);\n });\n\n (this.redisEmitter as EventEmitter).on('error', (error: Error) => {\n logger.error('Redis emitter error | error: %s', error);\n });\n\n RedisUtility.ensureConnecting({\n clients: [this.redisPub, this.redisSub, this.redisEmitter],\n logger: this.logger,\n scope: this.configure.name,\n });\n\n await Promise.all([\n RedisUtility.waitForReady({ client: this.redisPub }),\n RedisUtility.waitForReady({ client: this.redisSub }),\n RedisUtility.waitForReady({ client: this.redisEmitter }),\n ]);\n logger.info('All Redis connections ready');\n\n this.initIOServer();\n\n this.io.adapter(createAdapter(this.redisPub, this.redisSub));\n logger.info('SocketIO Server initialized Redis Adapter');\n\n this.emitter = new Emitter(this.redisEmitter);\n logger.info('SocketIO Server initialized Redis Emitter');\n\n this.io.on(SocketIOConstants.EVENT_CONNECT, (socket: IOSocket) => {\n this.onClientConnect({ socket });\n });\n\n logger.info(\n 'SocketIO Server READY | path: %s | runtime: %s',\n this.serverOptions?.path ?? '',\n this.runtime,\n );\n }\n\n private initIOServer() {\n switch (this.runtime) {\n case RuntimeModules.BUN: {\n if (!this.bunEngine) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[DANGER] Invalid @socket.io/bun-engine instance to init Socket.io server!',\n });\n }\n\n this.io = new IOServer();\n this.io.bind(this.bunEngine);\n break;\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[configure] Unsupported runtime: ${this.runtime}`,\n });\n }\n }\n }\n\n onClientConnect(opts: { socket: IOSocket }) {\n const logger = this.logger.for(this.onClientConnect.name);\n const { socket } = opts;\n\n if (!socket) {\n logger.info('Invalid new socket connection!');\n\n return;\n }\n\n const { id, handshake } = socket;\n\n if (this.clients.has(id)) {\n logger.info('Socket client already existed | id: %s', id);\n\n return;\n }\n\n logger.info('New connection request | id: %s', id);\n\n const client: ISocketIOClient = {\n id,\n socket,\n state: SocketIOClientStates.UNAUTHORIZED,\n authenticateTimeout: setTimeout(() => {\n const currentClient = this.clients.get(id);\n\n if (currentClient?.state === SocketIOClientStates.AUTHENTICATED) {\n return;\n }\n\n this.disconnect({ socket });\n }, this.authenticateTimeout),\n };\n this.clients.set(id, client);\n\n socket.on(SocketIOConstants.EVENT_DISCONNECT, () => {\n this.disconnect({ socket });\n });\n\n this.registerAuthHandler({ socket, handshake, clientId: id });\n }\n\n private registerAuthHandler(opts: { socket: IOSocket; handshake: IHandshake; clientId: string }) {\n const { socket, handshake, clientId: id } = opts;\n const authLogger = this.logger.for('onClientAuthenticate');\n\n socket.on(SocketIOConstants.EVENT_AUTHENTICATE, () => {\n const currentClient = this.clients.get(id);\n\n if (!currentClient) {\n authLogger.warn('Client no longer exists during auth | id: %s', id);\n\n return;\n }\n\n if (currentClient.state !== SocketIOClientStates.UNAUTHORIZED) {\n authLogger.warn(\n 'Client attempted auth in invalid state | id: %s | currentState: %s',\n id,\n currentClient.state,\n );\n\n return;\n }\n\n currentClient.state = SocketIOClientStates.AUTHENTICATING;\n\n Promise.resolve()\n .then(() => this.authenticateFn(handshake))\n .then((rs: boolean) => {\n if (!this.clients.has(id)) {\n authLogger.info('Client disconnected during authentication | id: %s', id);\n\n return;\n }\n\n authLogger.info('Authentication completed | id: %s | result: %s', id, rs);\n\n if (rs) {\n this.onClientAuthenticated({ socket });\n\n return;\n }\n\n const failedClient = this.clients.get(id);\n\n if (failedClient) {\n failedClient.state = SocketIOClientStates.UNAUTHORIZED;\n }\n\n this.rejectClient({\n socket,\n message: 'Invalid token to authenticate! Please login again!',\n });\n })\n .catch((error: Error) => {\n const errorClient = this.clients.get(id);\n\n if (errorClient) {\n errorClient.state = SocketIOClientStates.UNAUTHORIZED;\n }\n\n authLogger.error('Failed to authenticate | id: %s | error: %s', id, error);\n\n this.rejectClient({\n socket,\n message: 'Failed to authenticate connection! Please login again!',\n });\n });\n });\n }\n\n // The socket is connected to this process, so the notice goes out on it directly: routed through the Redis emitter it arrives after the disconnect and is dropped.\n private rejectClient(opts: { socket: IOSocket; message: string }) {\n const { socket, message } = opts;\n\n socket.emit(SocketIOConstants.EVENT_UNAUTHENTICATE, {\n message,\n time: new Date().toISOString(),\n });\n this.disconnect({ socket });\n }\n\n onClientAuthenticated(opts: { socket: IOSocket }) {\n const logger = this.logger.for(this.onClientAuthenticated.name);\n const { socket } = opts;\n\n if (!socket) {\n logger.info('Invalid new socket connection!');\n\n return;\n }\n\n const { id } = socket;\n const client = this.clients.get(id);\n\n if (!client) {\n logger.info('Unknown client | id: %s', id);\n this.disconnect({ socket });\n\n return;\n }\n\n client.state = SocketIOClientStates.AUTHENTICATED;\n\n // The authenticate deadline is over: leaving it armed keeps a timer per client alive\n if (client.authenticateTimeout) {\n clearTimeout(client.authenticateTimeout);\n client.authenticateTimeout = undefined;\n }\n\n this.ping({ socket, doIgnoreAuth: true });\n\n logger.info(\n 'Client connected | id: %s | identifier: %s | time: %s',\n id,\n this.identifier,\n new Date().toISOString(),\n );\n\n // The authenticated room first, and whatever `defaultRooms` the application configured: a broadcast must reach an\n // authenticated socket even when the application replaced the defaults.\n const rooms = [...new Set([SocketIOConstants.ROOM_AUTHENTICATED, ...this.defaultRooms])];\n\n Promise.all(rooms.map((room: string) => Promise.resolve(socket.join(room))))\n .then(() => {\n logger.info('Joined default rooms | id: %s | rooms: %s', id, rooms);\n })\n .catch((error) => {\n logger.error(\n 'Failed to join default rooms | id: %s | rooms: %s | error: %s',\n id,\n rooms,\n error,\n );\n });\n\n this.registerRoomHandlers({ socket, clientId: id });\n\n client.interval = setInterval(() => {\n this.ping({ socket, doIgnoreAuth: true });\n }, this.pingInterval);\n\n this.send({\n destination: socket.id,\n payload: {\n topic: SocketIOConstants.EVENT_AUTHENTICATED,\n data: {\n id: socket.id,\n time: new Date().toISOString(),\n },\n },\n });\n\n this.invokeHook({\n scope: 'clientConnectedFn',\n execution: () => this.onClientConnected?.({ socket }),\n });\n }\n\n /**\n * Narrows an untrusted room payload to the strings it actually contains.\n *\n * The listeners below run on data any authenticated client sends. Destructuring `{ rooms = [] }`\n * out of an `any` and testing `rooms?.length` accepts a STRING - `{\"rooms\":\"lobby\"}` has a\n * length of 5 - and the next line calls `rooms.map`, which a string does not have. socket.io\n * dispatches on `process.nextTick` with no try/catch around the handler, so that TypeError\n * escapes as an uncaught exception and takes the process with it.\n */\n private static toRoomList(payload: unknown): string[] {\n const rooms = (payload as { rooms?: unknown } | null | undefined)?.rooms;\n\n return Array.isArray(rooms)\n ? rooms.filter((room): room is string => typeof room === 'string')\n : [];\n }\n\n private registerRoomHandlers(opts: { socket: IOSocket; clientId: string }) {\n const { socket, clientId: id } = opts;\n\n const joinLogger = this.logger.for(SocketIOConstants.EVENT_JOIN);\n socket.on(SocketIOConstants.EVENT_JOIN, (payload: unknown) => {\n const rooms = SocketIOServerHelper.toRoomList(payload);\n\n if (!rooms.length) {\n return;\n }\n\n const validateRoomFn = this.validateRoomFn;\n\n if (!validateRoomFn) {\n joinLogger.warn(\n 'Join rejected | id: %s | rooms: %j | reason: no validateRoomFn configured',\n id,\n rooms,\n );\n\n return;\n }\n\n Promise.resolve()\n .then(() => validateRoomFn({ socket, rooms }))\n .then((allowedRooms: string[]) => {\n if (!allowedRooms?.length) {\n joinLogger.warn(\n 'Join rejected | id: %s | rooms: %j | reason: no rooms allowed',\n id,\n rooms,\n );\n\n return;\n }\n\n joinLogger.info('Joining rooms | id: %s | rooms: %j', id, allowedRooms);\n\n for (const room of allowedRooms) {\n PromiseUtility.voidExecution({\n logger: this.logger,\n scope: SocketIOConstants.EVENT_JOIN,\n execution: socket.join(room),\n });\n }\n\n joinLogger.info('Joined rooms | id: %s | rooms: %s', id, allowedRooms);\n })\n .catch((error) => {\n joinLogger.error(\n 'Failed to join rooms | id: %s | rooms: %s | error: %s',\n id,\n rooms,\n error,\n );\n });\n });\n\n const leaveLogger = this.logger.for(SocketIOConstants.EVENT_LEAVE);\n socket.on(SocketIOConstants.EVENT_LEAVE, (payload: unknown) => {\n const rooms = SocketIOServerHelper.toRoomList(payload);\n\n if (!rooms.length) {\n return;\n }\n\n leaveLogger.info('Leaving rooms | id: %s | rooms: %j', id, rooms);\n\n // `Promise.resolve` per room: socket.io declares `leave(room): Promise<void> | void` - the\n // default adapter is synchronous, a clustered one is not - and `Promise.all` over a mixed\n // iterable is what the previous `any`-typed payload was hiding.\n Promise.all(rooms.map((room) => Promise.resolve(socket.leave(room))))\n .then(() => {\n leaveLogger.info('Left rooms | id: %s | rooms: %s', id, rooms);\n })\n .catch((error) => {\n leaveLogger.error(\n 'Failed to leave rooms | id: %s | rooms: %s | error: %s',\n id,\n rooms,\n error,\n );\n });\n });\n }\n\n ping(opts: { socket: IOSocket; doIgnoreAuth: boolean }) {\n const logger = this.logger.for(this.ping.name);\n const { socket, doIgnoreAuth } = opts;\n\n if (!socket) {\n logger.info('Socket is undefined to PING!');\n\n return;\n }\n\n const client = this.clients.get(socket.id);\n\n if (!client) {\n logger.info('Client not found | socketId: %s', socket.id);\n\n return;\n }\n\n if (!doIgnoreAuth && client.state !== SocketIOClientStates.AUTHENTICATED) {\n logger.info('Socket client is not authenticated | state: %s', client.state);\n this.disconnect({ socket });\n\n return;\n }\n\n socket.emit(SocketIOConstants.EVENT_PING, { time: new Date().toISOString() });\n }\n\n disconnect(opts: { socket: IOSocket }) {\n const logger = this.logger.for(this.disconnect.name);\n const { socket } = opts;\n\n if (!socket) {\n return;\n }\n\n const { id } = socket;\n\n if (this.clients.has(id)) {\n const client = this.clients.get(id)!;\n\n if (client.interval) {\n clearInterval(client.interval);\n }\n\n if (client.authenticateTimeout) {\n clearTimeout(client.authenticateTimeout);\n }\n\n this.clients.delete(id);\n }\n\n logger.info('Client disconnected | id: %s | time: %s', id, new Date().toISOString());\n socket.disconnect();\n }\n\n send(opts: {\n destination?: string;\n payload: { topic: string; data: unknown };\n doLog?: boolean;\n callback?: () => void;\n }) {\n const logger = this.logger.for(this.send.name);\n const { destination, payload, doLog, callback } = opts;\n\n if (!payload) {\n return;\n }\n\n const { topic, data } = payload;\n\n if (!topic || !data) {\n return;\n }\n\n if (!this.emitter) {\n logger.error(\n 'Cannot emit | Redis emitter is not initialized | call configure() first | topic: %s',\n topic,\n );\n\n return;\n }\n\n const sender = this.emitter.compress(true);\n\n if (destination && !ObjectUtility.isEmpty({ value: destination })) {\n sender.to(destination).emit(topic, data);\n } else {\n // Not `sender.emit`: that reaches every connected socket, the ones that have not authenticated included.\n sender.to(SocketIOConstants.ROOM_AUTHENTICATED).emit(topic, data);\n }\n\n if (callback) {\n setImmediate(callback);\n }\n\n if (doLog) {\n logger.info(\n 'Message emitted | destination: %s | topic: %s | data: %j',\n destination ?? SocketIOConstants.ROOM_AUTHENTICATED,\n topic,\n data,\n );\n }\n }\n\n private close() {\n return new Promise<void>((resolve, reject) => {\n // configure() may never have run (or may have failed): there is nothing to close, but the redis clients still have to be released by the caller\n if (!this.io) {\n this.logger.for('close').info('SKIP close | IOServer was never initialized');\n resolve();\n\n return;\n }\n\n PromiseUtility.voidExecution({\n logger: this.logger,\n scope: 'close',\n execution: this.io.close((error) => {\n if (error) {\n reject(error);\n\n return;\n }\n\n resolve();\n }),\n });\n });\n }\n\n async shutdown() {\n const logger = this.logger.for(this.shutdown.name);\n logger.info('Shutting down SocketIO server...');\n\n for (const [, client] of this.clients) {\n if (client.interval) {\n clearInterval(client.interval);\n }\n\n if (client.authenticateTimeout) {\n clearTimeout(client.authenticateTimeout);\n }\n\n client.socket.disconnect();\n }\n\n this.clients.clear();\n\n try {\n await this.close();\n } finally {\n // close() rejects when io.close() reports a lingering handle. Skipping the quits there leaves three live Redis sockets holding the event loop open, and a SIGTERM handler never returns.\n await Promise.all([this.redisPub?.quit(), this.redisSub?.quit(), this.redisEmitter?.quit()]);\n }\n\n logger.info('SocketIO server shutdown complete');\n }\n}\n"]}
|
|
@@ -4,7 +4,7 @@ export interface IRequestedRemark {
|
|
|
4
4
|
id: string;
|
|
5
5
|
url: string;
|
|
6
6
|
method: string;
|
|
7
|
-
[extra: string | symbol]:
|
|
7
|
+
[extra: string | symbol]: unknown;
|
|
8
8
|
}
|
|
9
9
|
/** Where `RequestUtility.parseMultipartBody` keeps an uploaded file: MEMORY (a buffer) or DISK (spooled to `uploadDir`). */
|
|
10
10
|
export declare class MultipartStorages {
|
|
@@ -15,11 +15,13 @@ export declare class MultipartStorages {
|
|
|
15
15
|
}
|
|
16
16
|
/** Valid multipart storage values. */
|
|
17
17
|
export type TMultipartStorage = TConstValue<typeof MultipartStorages>;
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
}
|
|
18
|
+
/** The part of a request context a multipart body is read from: its `formData()`. A Hono context satisfies it. */
|
|
19
|
+
interface IMultipartContext {
|
|
20
|
+
req: {
|
|
21
|
+
formData: () => Promise<FormData>;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
interface IParseMultipartOptions<C extends IMultipartContext = IMultipartContext> {
|
|
23
25
|
storage?: TMultipartStorage;
|
|
24
26
|
uploadDir?: string;
|
|
25
27
|
/** The most file parts one request may carry; more is refused (413) before anything is spooled. Unset: no limit. */
|
|
@@ -56,11 +58,7 @@ export declare class RequestUtility {
|
|
|
56
58
|
private static uploadTokens?;
|
|
57
59
|
/** Uniqueness for a spooled filename, not a secret; the helper's 16-byte floor is the shortest it makes. */
|
|
58
60
|
private static getUploadTokens;
|
|
59
|
-
static parseMultipartBody<C extends
|
|
60
|
-
req: any;
|
|
61
|
-
} = {
|
|
62
|
-
req: any;
|
|
63
|
-
}>(opts: IParseMultipartOptions<C>): Promise<IParsedMultipartBody>;
|
|
61
|
+
static parseMultipartBody<C extends IMultipartContext = IMultipartContext>(opts: IParseMultipartOptions<C>): Promise<IParsedMultipartBody>;
|
|
64
62
|
private static removeSpooled;
|
|
65
63
|
private static readParts;
|
|
66
64
|
/** Sanitizes a filename by removing path components and dangerous characters. The result is printable ASCII. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.utility.js","sourceRoot":"","sources":["../../../src/utilities/request.utility.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACzE,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAU7B,4HAA4H;AAC5H,MAAM,OAAO,iBAAiB;aACZ,WAAM,GAAG,QAAQ,CAAC;aAClB,SAAI,GAAG,MAAM,CAAC;aAEd,eAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAEvE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AA+BH,8SAA8S;AAC9S,MAAM,+BAA+B,GAAG,gCAA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M,EAAE,GAAG,IAAI,CAAC;QAExB,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,SAAS,CAAC;QAEvD,0FAA0F;QAC1F,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC,2BAA2B,CAAC,CAAC;QAE3D,IAAI,QAAQ,EAAE,CAAC;YACb,MAAM,KAAK,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACjC,8FAA8F;YAC9F,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;YAExD,IAAI,CAAC;gBACH,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,kBAAkB,CAAC,OAAO,CAAC,EAAE,CAAC;gBACvD,8JAA8J;YAChK,CAAC;YAAC,MAAM,CAAC;gBACP,0FAA0F;YAC5F,CAAC;QACH,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,2BAA2B,CAAC,CAAC;QAEzD,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;QACvC,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,yBAAyB,CAAC,CAAC;QAErD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC;IAC/D,CAAC;CACF","sourcesContent":["import type { TConstValue } from '@/common/types';\nimport { getError } from '@/modules/error';\nimport { MIN_TOKEN_BYTES, TokenUidHelper, UidTokenEncodings } from '@/modules/uid';\nimport { FormBodyUtility, RequestBodyErrors } from './form-body.utility';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/** A request remark: `id`, `url` and `method`, plus any extra keys. */\nexport interface IRequestedRemark {\n id: string;\n url: string;\n method: string;\n [extra: string | symbol]: any;\n}\n\n/** Where `RequestUtility.parseMultipartBody` keeps an uploaded file: MEMORY (a buffer) or DISK (spooled to `uploadDir`). */\nexport class MultipartStorages {\n static readonly MEMORY = 'memory';\n static readonly DISK = 'disk';\n\n static readonly SCHEME_SET = new Set<string>([this.MEMORY, this.DISK]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid multipart storage values. */\nexport type TMultipartStorage = TConstValue<typeof MultipartStorages>;\n\ninterface IParseMultipartOptions<C extends { req: any } = { req: any }> {\n storage?: TMultipartStorage;\n uploadDir?: string;\n /** The most file parts one request may carry; more is refused (413) before anything is spooled. Unset: no limit. */\n maxFiles?: number;\n context: C;\n}\n\ninterface IParsedFile {\n fieldname: string;\n originalname: string;\n encoding: string;\n mimetype: string;\n size: number;\n buffer?: Buffer;\n filename?: string;\n path?: string;\n}\n\n/** Files and the text fields posted beside them - dropping the second silently loses what the client sent. */\nexport interface IParsedMultipartBody {\n files: IParsedFile[];\n fields: Record<string, string>;\n}\n\n/** Control, format (bidi overrides, zero-width space) and lone surrogate characters: a format character reorders the name a client shows, a lone surrogate makes `encodeURIComponent` throw. The zero-width joiner and non-joiner stay: they build emoji sequences and Persian words, and reorder nothing. */\nconst UNENCODABLE_FILENAME_CHARACTERS = /(?![])[\\p{Cc}\\p{Cf}\\p{Cs}]/gu;\nconst LEADING_DOTS = /^\\.+/;\n\n/** How a client treats a download: ATTACHMENT saves it, INLINE shows it. */\nexport class ContentDispositionTypes {\n static readonly ATTACHMENT = 'attachment';\n static readonly INLINE = 'inline';\n\n static readonly SCHEME_SET = new Set<string>([this.ATTACHMENT, this.INLINE]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid Content-Disposition type values. */\nexport type TContentDispositionType = TConstValue<typeof ContentDispositionTypes>;\n\n/** Multipart body parsing and `Content-Disposition` header building and parsing for requests and uploads. */\nexport class RequestUtility {\n /** Built on first use: a helper opens a logger, which is work an import alone should not do. */\n private static uploadTokens?: TokenUidHelper;\n\n /** Uniqueness for a spooled filename, not a secret; the helper's 16-byte floor is the shortest it makes. */\n private static getUploadTokens(): TokenUidHelper {\n RequestUtility.uploadTokens ??= new TokenUidHelper({\n bytes: MIN_TOKEN_BYTES,\n encoding: UidTokenEncodings.HEX,\n });\n\n return RequestUtility.uploadTokens;\n }\n\n static async parseMultipartBody<C extends { req: any } = { req: any }>(\n opts: IParseMultipartOptions<C>,\n ): Promise<IParsedMultipartBody> {\n const { storage = MultipartStorages.MEMORY, uploadDir = './uploads', context, maxFiles } = opts;\n\n if (storage === MultipartStorages.DISK && !fs.existsSync(uploadDir)) {\n fs.mkdirSync(uploadDir, { recursive: true });\n }\n\n const formData = await FormBodyUtility.readFormBody({ req: context.req });\n const files: IParsedFile[] = [];\n const fields: Record<string, string> = {};\n\n if (maxFiles !== undefined) {\n if (!Number.isInteger(maxFiles) || maxFiles < 0) {\n throw getError({\n message: `[parseMultipartBody] maxFiles must be a non-negative integer | received: ${maxFiles}`,\n });\n }\n\n let fileParts = 0;\n\n for (const [, value] of formData.entries()) {\n if (typeof value !== 'string') {\n fileParts += 1;\n }\n }\n\n if (fileParts > maxFiles) {\n throw getError({\n error: RequestBodyErrors.TOO_MANY_FILES,\n message: `[parseMultipartBody] Too many files in one request | received: ${fileParts} | max: ${maxFiles}`,\n });\n }\n }\n\n try {\n await RequestUtility.readParts({ formData, storage, uploadDir, files, fields });\n } catch (error) {\n // Files already written to disk belong to a request that failed; nothing else knows their names.\n RequestUtility.removeSpooled({ files });\n\n throw error;\n }\n\n return { files, fields };\n }\n\n private static removeSpooled(opts: { files: IParsedFile[] }): void {\n for (const file of opts.files) {\n if (!file.path) {\n continue;\n }\n\n try {\n fs.rmSync(file.path, { force: true });\n // eslint-disable-next-line venizia/no-silent-catch -- cleanup of a failed request: one file that will not go must not hide the original error or stop the others\n } catch {\n continue;\n }\n }\n }\n\n private static async readParts(opts: {\n formData: FormData;\n storage: TMultipartStorage;\n uploadDir: string;\n files: IParsedFile[];\n fields: Record<string, string>;\n }): Promise<void> {\n const { formData, storage, uploadDir, files, fields } = opts;\n const entries = formData.entries();\n\n for (const [fieldname, value] of entries) {\n if (typeof value === 'string') {\n // Last one wins, like a repeated query parameter.\n fields[fieldname] = value;\n continue;\n }\n\n const file = value as File;\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n const parsedFile: IParsedFile = {\n fieldname,\n originalname: file.name,\n encoding: 'utf8',\n mimetype: file.type,\n size: file.size,\n };\n\n switch (storage) {\n case MultipartStorages.MEMORY: {\n parsedFile.buffer = buffer;\n break;\n }\n case MultipartStorages.DISK: {\n const timestamp = Date.now();\n const randomString = RequestUtility.getUploadTokens().nextId();\n // Sanitize filename to prevent path traversal\n const sanitizedName = path.basename(file.name).replace(/[^a-zA-Z0-9._-]/g, '_');\n const filename = `${timestamp}-${randomString}-${sanitizedName}`;\n const filepath = path.join(uploadDir, filename);\n\n try {\n fs.writeFileSync(filepath, buffer);\n } catch (error) {\n // A write that dies midway (a full disk) leaves a partial file this part never got to list.\n RequestUtility.removeSpooled({ files: [{ ...parsedFile, path: filepath }] });\n\n throw error;\n }\n\n parsedFile.filename = filename;\n parsedFile.path = filepath;\n break;\n }\n default: {\n throw getError({\n message: `[parseMultipartBody] storage: ${storage} | Invalid storage type | Valids: ['memory', 'disk']`,\n });\n }\n }\n\n files.push(parsedFile);\n }\n }\n\n /** Sanitizes a filename by removing path components and dangerous characters. The result is printable ASCII. */\n static sanitizeFilename(opts: { filename: string }): string {\n const basename = path.basename(opts.filename);\n let sanitized = basename.replace(/[^\\w .-]/g, '_');\n sanitized = sanitized.replace(/^\\.+/, '');\n sanitized = sanitized.replace(/\\.{2,}/g, '.');\n sanitized = sanitized.replace(/\\.\\./g, '.');\n\n if (!sanitized || sanitized === '.' || sanitized.includes('..')) {\n sanitized = 'download';\n }\n\n return sanitized;\n }\n\n static encodeRfc5987(opts: { filename: string }): string {\n return encodeURIComponent(opts.filename)\n .replace(/['()]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase())\n .replace(/\\*/g, '%2A');\n }\n\n static buildContentDispositionHeader(opts: {\n filename: string;\n type: TContentDispositionType;\n }): string {\n const { filename, type } = opts;\n const sanitized = RequestUtility.sanitizeFilename({ filename });\n const extendedName = path\n .basename(filename)\n .replace(UNENCODABLE_FILENAME_CHARACTERS, '_')\n .replace(LEADING_DOTS, '');\n const encoded = RequestUtility.encodeRfc5987({ filename: extendedName || sanitized });\n\n // filename= is the ASCII fallback for old browsers, filename*= the UTF-8 form for modern ones.\n return `${type}; filename=\"${sanitized}\"; filename*=UTF-8''${encoded}`;\n }\n\n /**\n * Reads a filename out of a `Content-Disposition` value.\n *\n * Three forms, in the order the RFC gives them precedence: `filename*=UTF-8''...` (percent-encoded,\n * and the one hand-rolled parsers miss), a quoted `filename=\"...\"`, and a bare `filename=...`.\n * Splitting on `filename=` alone returns the percent-encoded bytes for any non-ASCII name, which in\n * a product with non-English filenames is most of them.\n *\n * The pair of {@link RequestUtility.buildContentDispositionHeader}: one writes the header, this one reads it.\n */\n static parseContentDisposition(opts: { header: string | null | undefined }): {\n type?: string;\n filename?: string;\n } {\n const { header } = opts;\n\n if (!header) {\n return {};\n }\n\n const type = header.split(';')[0]?.trim() || undefined;\n\n // `filename*` wins when both are present - it is the one that can carry a non-ASCII name.\n const extended = header.match(/filename\\*\\s*=\\s*([^;]+)/i);\n\n if (extended) {\n const value = extended[1].trim();\n // `UTF-8''name` or `UTF-8'lang'name`; anything before the last quote is charset and language.\n const encoded = value.slice(value.lastIndexOf(\"'\") + 1);\n\n try {\n return { type, filename: decodeURIComponent(encoded) };\n // eslint-disable-next-line venizia/no-silent-catch -- a malformed `filename*` falls through to the plain `filename` parameter; only the extended name is lost\n } catch {\n // A malformed sequence is not worth failing a download over - fall through to `filename`.\n }\n }\n\n const quoted = header.match(/filename\\s*=\\s*\"([^\"]*)\"/i);\n\n if (quoted) {\n return { type, filename: quoted[1] };\n }\n\n const bare = header.match(/filename\\s*=\\s*([^;]+)/i);\n\n return { type, filename: bare ? bare[1].trim() : undefined };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"request.utility.js","sourceRoot":"","sources":["../../../src/utilities/request.utility.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACzE,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAU7B,4HAA4H;AAC5H,MAAM,OAAO,iBAAiB;aACZ,WAAM,GAAG,QAAQ,CAAC;aAClB,SAAI,GAAG,MAAM,CAAC;aAEd,eAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAEvE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAoCH,8SAA8S;AAC9S,MAAM,+BAA+B,GAAG,gCAAgC,CAAC;AACzE,MAAM,YAAY,GAAG,MAAM,CAAC;AAE5B,4EAA4E;AAC5E,MAAM,OAAO,uBAAuB;aAClB,eAAU,GAAG,YAAY,CAAC;aAC1B,WAAM,GAAG,QAAQ,CAAC;aAElB,eAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,CA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Q,GAAG,MAAM,CAAC,KAAK,CAAC,2BAA2B,CAAC,CAAC;QAE3D,IAAI,QAAQ,EAAE,CAAC;YACb,MAAM,KAAK,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YACjC,8FAA8F;YAC9F,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;YAExD,IAAI,CAAC;gBACH,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,kBAAkB,CAAC,OAAO,CAAC,EAAE,CAAC;gBACvD,8JAA8J;YAChK,CAAC;YAAC,MAAM,CAAC;gBACP,0FAA0F;YAC5F,CAAC;QACH,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,2BAA2B,CAAC,CAAC;QAEzD,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;QACvC,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,yBAAyB,CAAC,CAAC;QAErD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC;IAC/D,CAAC;CACF","sourcesContent":["import type { TConstValue } from '@/common/types';\nimport { getError } from '@/modules/error';\nimport { MIN_TOKEN_BYTES, TokenUidHelper, UidTokenEncodings } from '@/modules/uid';\nimport { FormBodyUtility, RequestBodyErrors } from './form-body.utility';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/** A request remark: `id`, `url` and `method`, plus any extra keys. */\nexport interface IRequestedRemark {\n id: string;\n url: string;\n method: string;\n [extra: string | symbol]: unknown;\n}\n\n/** Where `RequestUtility.parseMultipartBody` keeps an uploaded file: MEMORY (a buffer) or DISK (spooled to `uploadDir`). */\nexport class MultipartStorages {\n static readonly MEMORY = 'memory';\n static readonly DISK = 'disk';\n\n static readonly SCHEME_SET = new Set<string>([this.MEMORY, this.DISK]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid multipart storage values. */\nexport type TMultipartStorage = TConstValue<typeof MultipartStorages>;\n\n/** The part of a request context a multipart body is read from: its `formData()`. A Hono context satisfies it. */\ninterface IMultipartContext {\n req: { formData: () => Promise<FormData> };\n}\n\ninterface IParseMultipartOptions<C extends IMultipartContext = IMultipartContext> {\n storage?: TMultipartStorage;\n uploadDir?: string;\n /** The most file parts one request may carry; more is refused (413) before anything is spooled. Unset: no limit. */\n maxFiles?: number;\n context: C;\n}\n\ninterface IParsedFile {\n fieldname: string;\n originalname: string;\n encoding: string;\n mimetype: string;\n size: number;\n buffer?: Buffer;\n filename?: string;\n path?: string;\n}\n\n/** Files and the text fields posted beside them - dropping the second silently loses what the client sent. */\nexport interface IParsedMultipartBody {\n files: IParsedFile[];\n fields: Record<string, string>;\n}\n\n/** Control, format (bidi overrides, zero-width space) and lone surrogate characters: a format character reorders the name a client shows, a lone surrogate makes `encodeURIComponent` throw. The zero-width joiner and non-joiner stay: they build emoji sequences and Persian words, and reorder nothing. */\nconst UNENCODABLE_FILENAME_CHARACTERS = /(?![])[\\p{Cc}\\p{Cf}\\p{Cs}]/gu;\nconst LEADING_DOTS = /^\\.+/;\n\n/** How a client treats a download: ATTACHMENT saves it, INLINE shows it. */\nexport class ContentDispositionTypes {\n static readonly ATTACHMENT = 'attachment';\n static readonly INLINE = 'inline';\n\n static readonly SCHEME_SET = new Set<string>([this.ATTACHMENT, this.INLINE]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid Content-Disposition type values. */\nexport type TContentDispositionType = TConstValue<typeof ContentDispositionTypes>;\n\n/** Multipart body parsing and `Content-Disposition` header building and parsing for requests and uploads. */\nexport class RequestUtility {\n /** Built on first use: a helper opens a logger, which is work an import alone should not do. */\n private static uploadTokens?: TokenUidHelper;\n\n /** Uniqueness for a spooled filename, not a secret; the helper's 16-byte floor is the shortest it makes. */\n private static getUploadTokens(): TokenUidHelper {\n RequestUtility.uploadTokens ??= new TokenUidHelper({\n bytes: MIN_TOKEN_BYTES,\n encoding: UidTokenEncodings.HEX,\n });\n\n return RequestUtility.uploadTokens;\n }\n\n static async parseMultipartBody<C extends IMultipartContext = IMultipartContext>(\n opts: IParseMultipartOptions<C>,\n ): Promise<IParsedMultipartBody> {\n const { storage = MultipartStorages.MEMORY, uploadDir = './uploads', context, maxFiles } = opts;\n\n if (storage === MultipartStorages.DISK && !fs.existsSync(uploadDir)) {\n fs.mkdirSync(uploadDir, { recursive: true });\n }\n\n const formData = await FormBodyUtility.readFormBody({ req: context.req });\n const files: IParsedFile[] = [];\n const fields: Record<string, string> = {};\n\n if (maxFiles !== undefined) {\n if (!Number.isInteger(maxFiles) || maxFiles < 0) {\n throw getError({\n message: `[parseMultipartBody] maxFiles must be a non-negative integer | received: ${maxFiles}`,\n });\n }\n\n let fileParts = 0;\n\n for (const [, value] of formData.entries()) {\n if (typeof value !== 'string') {\n fileParts += 1;\n }\n }\n\n if (fileParts > maxFiles) {\n throw getError({\n error: RequestBodyErrors.TOO_MANY_FILES,\n message: `[parseMultipartBody] Too many files in one request | received: ${fileParts} | max: ${maxFiles}`,\n });\n }\n }\n\n try {\n await RequestUtility.readParts({ formData, storage, uploadDir, files, fields });\n } catch (error) {\n // Files already written to disk belong to a request that failed; nothing else knows their names.\n RequestUtility.removeSpooled({ files });\n\n throw error;\n }\n\n return { files, fields };\n }\n\n private static removeSpooled(opts: { files: IParsedFile[] }): void {\n for (const file of opts.files) {\n if (!file.path) {\n continue;\n }\n\n try {\n fs.rmSync(file.path, { force: true });\n // eslint-disable-next-line venizia/no-silent-catch -- cleanup of a failed request: one file that will not go must not hide the original error or stop the others\n } catch {\n continue;\n }\n }\n }\n\n private static async readParts(opts: {\n formData: FormData;\n storage: TMultipartStorage;\n uploadDir: string;\n files: IParsedFile[];\n fields: Record<string, string>;\n }): Promise<void> {\n const { formData, storage, uploadDir, files, fields } = opts;\n const entries = formData.entries();\n\n for (const [fieldname, value] of entries) {\n if (typeof value === 'string') {\n // Last one wins, like a repeated query parameter.\n fields[fieldname] = value;\n continue;\n }\n\n const file = value as File;\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n const parsedFile: IParsedFile = {\n fieldname,\n originalname: file.name,\n encoding: 'utf8',\n mimetype: file.type,\n size: file.size,\n };\n\n switch (storage) {\n case MultipartStorages.MEMORY: {\n parsedFile.buffer = buffer;\n break;\n }\n case MultipartStorages.DISK: {\n const timestamp = Date.now();\n const randomString = RequestUtility.getUploadTokens().nextId();\n // Sanitize filename to prevent path traversal\n const sanitizedName = path.basename(file.name).replace(/[^a-zA-Z0-9._-]/g, '_');\n const filename = `${timestamp}-${randomString}-${sanitizedName}`;\n const filepath = path.join(uploadDir, filename);\n\n try {\n fs.writeFileSync(filepath, buffer);\n } catch (error) {\n // A write that dies midway (a full disk) leaves a partial file this part never got to list.\n RequestUtility.removeSpooled({ files: [{ ...parsedFile, path: filepath }] });\n\n throw error;\n }\n\n parsedFile.filename = filename;\n parsedFile.path = filepath;\n break;\n }\n default: {\n throw getError({\n message: `[parseMultipartBody] storage: ${storage} | Invalid storage type | Valids: ['memory', 'disk']`,\n });\n }\n }\n\n files.push(parsedFile);\n }\n }\n\n /** Sanitizes a filename by removing path components and dangerous characters. The result is printable ASCII. */\n static sanitizeFilename(opts: { filename: string }): string {\n const basename = path.basename(opts.filename);\n let sanitized = basename.replace(/[^\\w .-]/g, '_');\n sanitized = sanitized.replace(/^\\.+/, '');\n sanitized = sanitized.replace(/\\.{2,}/g, '.');\n sanitized = sanitized.replace(/\\.\\./g, '.');\n\n if (!sanitized || sanitized === '.' || sanitized.includes('..')) {\n sanitized = 'download';\n }\n\n return sanitized;\n }\n\n static encodeRfc5987(opts: { filename: string }): string {\n return encodeURIComponent(opts.filename)\n .replace(/['()]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase())\n .replace(/\\*/g, '%2A');\n }\n\n static buildContentDispositionHeader(opts: {\n filename: string;\n type: TContentDispositionType;\n }): string {\n const { filename, type } = opts;\n const sanitized = RequestUtility.sanitizeFilename({ filename });\n const extendedName = path\n .basename(filename)\n .replace(UNENCODABLE_FILENAME_CHARACTERS, '_')\n .replace(LEADING_DOTS, '');\n const encoded = RequestUtility.encodeRfc5987({ filename: extendedName || sanitized });\n\n // filename= is the ASCII fallback for old browsers, filename*= the UTF-8 form for modern ones.\n return `${type}; filename=\"${sanitized}\"; filename*=UTF-8''${encoded}`;\n }\n\n /**\n * Reads a filename out of a `Content-Disposition` value.\n *\n * Three forms, in the order the RFC gives them precedence: `filename*=UTF-8''...` (percent-encoded,\n * and the one hand-rolled parsers miss), a quoted `filename=\"...\"`, and a bare `filename=...`.\n * Splitting on `filename=` alone returns the percent-encoded bytes for any non-ASCII name, which in\n * a product with non-English filenames is most of them.\n *\n * The pair of {@link RequestUtility.buildContentDispositionHeader}: one writes the header, this one reads it.\n */\n static parseContentDisposition(opts: { header: string | null | undefined }): {\n type?: string;\n filename?: string;\n } {\n const { header } = opts;\n\n if (!header) {\n return {};\n }\n\n const type = header.split(';')[0]?.trim() || undefined;\n\n // `filename*` wins when both are present - it is the one that can carry a non-ASCII name.\n const extended = header.match(/filename\\*\\s*=\\s*([^;]+)/i);\n\n if (extended) {\n const value = extended[1].trim();\n // `UTF-8''name` or `UTF-8'lang'name`; anything before the last quote is charset and language.\n const encoded = value.slice(value.lastIndexOf(\"'\") + 1);\n\n try {\n return { type, filename: decodeURIComponent(encoded) };\n // eslint-disable-next-line venizia/no-silent-catch -- a malformed `filename*` falls through to the plain `filename` parameter; only the extended name is lost\n } catch {\n // A malformed sequence is not worth failing a download over - fall through to `filename`.\n }\n }\n\n const quoted = header.match(/filename\\s*=\\s*\"([^\"]*)\"/i);\n\n if (quoted) {\n return { type, filename: quoted[1] };\n }\n\n const bare = header.match(/filename\\s*=\\s*([^;]+)/i);\n\n return { type, filename: bare ? bare[1].trim() : undefined };\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@venizia/ignis-helpers",
|
|
3
|
-
"version": "0.4.8-
|
|
3
|
+
"version": "0.4.8-13",
|
|
4
4
|
"description": "Production-ready TypeScript utility library: pluggable logging (winston or pino behind one ILogger contract), Redis single/cluster/sentinel with pub/sub, BullMQ/MQTT/Kafka message queues, MinIO/Disk/Bun-S3 object storage, AES-256/RSA/ECDH cryptography, Snowflake UID generation, cron scheduling, Socket.IO/WebSocket, TCP/TLS/UDP networking, HTTP clients, secrets/Vault, worker thread pools, and environment management. Sub-path imports isolate optional peer dependencies so the root barrel never forces a peer into your bundle.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"aes",
|