@grandlinex/base-con 1.0.0

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.
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = ConMerger;
4
+ function ConMerger(conA, conB) {
5
+ const prop = Object.getPrototypeOf(conB);
6
+ const propertyNames = Object.getOwnPropertyNames(prop);
7
+ for (const key of propertyNames) {
8
+ if (key !== 'constructor' && !conA[key]) {
9
+ conA[key] = prop[key];
10
+ }
11
+ }
12
+ return conA;
13
+ }
@@ -0,0 +1,3 @@
1
+ import { ConHandle } from './BaseCon.js';
2
+ declare const FetchCon: ConHandle;
3
+ export default FetchCon;
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ async function fcTransform(r) {
4
+ const res = await r;
5
+ const head = {};
6
+ res.headers.forEach((val, key) => {
7
+ head[key] = val;
8
+ });
9
+ let data = null;
10
+ if (head['content-type']?.includes('application/json')) {
11
+ data = await res.json();
12
+ }
13
+ else if (head['content-type']?.includes('form-data')) {
14
+ data = await res.formData();
15
+ }
16
+ else if (head['content-type']?.includes('octet-stream')) {
17
+ data = await res.arrayBuffer();
18
+ }
19
+ else if (head['content-type']?.includes('text/plain')) {
20
+ data = await res.text();
21
+ }
22
+ return {
23
+ code: res.status,
24
+ data,
25
+ headers: head,
26
+ };
27
+ }
28
+ function bodyTransform(r, headers) {
29
+ if (!r) {
30
+ return {
31
+ headers,
32
+ };
33
+ }
34
+ if (r instanceof FormData) {
35
+ return {
36
+ body: r,
37
+ headers: {
38
+ ...headers,
39
+ },
40
+ };
41
+ }
42
+ return {
43
+ body: JSON.stringify(r),
44
+ headers: {
45
+ ...headers,
46
+ 'content-type': 'application/json',
47
+ },
48
+ };
49
+ }
50
+ const FetchCon = {
51
+ get: async (url, config) => {
52
+ return fcTransform(fetch(url, {
53
+ method: 'GET',
54
+ headers: {
55
+ accept: 'application/json, text/plain, */*',
56
+ ...config?.headers,
57
+ },
58
+ }));
59
+ },
60
+ post: async (url, body, config) => {
61
+ return fcTransform(fetch(url, {
62
+ method: 'POST',
63
+ ...bodyTransform(body, config?.headers),
64
+ }));
65
+ },
66
+ patch: async (url, body, config) => {
67
+ return fcTransform(fetch(url, {
68
+ method: 'PATCH',
69
+ ...bodyTransform(body, config?.headers),
70
+ }));
71
+ },
72
+ delete: async (url, config) => {
73
+ return fcTransform(fetch(url, {
74
+ method: 'DELETE',
75
+ headers: config?.headers,
76
+ }));
77
+ },
78
+ };
79
+ exports.default = FetchCon;
@@ -0,0 +1,3 @@
1
+ import { ConHandle } from './BaseCon.js';
2
+ declare const NodeCon: ConHandle;
3
+ export default NodeCon;
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ const form_data_1 = __importDefault(require("form-data"));
40
+ const http = __importStar(require("http"));
41
+ const https = __importStar(require("https"));
42
+ function selectClient(url) {
43
+ if (url.startsWith('https')) {
44
+ return https;
45
+ }
46
+ return http;
47
+ }
48
+ async function fcTransform(message, raw) {
49
+ let data = null;
50
+ if (message.headers['content-type']?.includes('application/json')) {
51
+ data = JSON.parse(raw);
52
+ }
53
+ else if (message.headers['content-type']?.includes('form-data')) {
54
+ data = null; // await res.formData()
55
+ }
56
+ else if (message.headers['content-type']?.includes('octet-stream')) {
57
+ data = Buffer.from(raw);
58
+ }
59
+ else if (message.headers['content-type']?.startsWith('text/')) {
60
+ data = Buffer.from(raw).toString('utf8');
61
+ }
62
+ return {
63
+ code: message.statusCode || -1,
64
+ data,
65
+ headers: message.headers,
66
+ };
67
+ }
68
+ function bodyTransform(r, headers) {
69
+ if (!r) {
70
+ return {
71
+ headers: headers || {},
72
+ body: undefined,
73
+ };
74
+ }
75
+ if (r instanceof form_data_1.default) {
76
+ return {
77
+ body: r,
78
+ headers: {
79
+ ...headers,
80
+ 'content-type': 'multipart/form-data',
81
+ },
82
+ };
83
+ }
84
+ return {
85
+ body: JSON.stringify(r),
86
+ headers: {
87
+ ...headers,
88
+ 'content-type': 'application/json',
89
+ },
90
+ };
91
+ }
92
+ async function makeRequest(url, option, body, config) {
93
+ return new Promise((resolve) => {
94
+ let headers = config?.headers || {};
95
+ let transForm = null;
96
+ if (body) {
97
+ let safeHeaders;
98
+ if (option.headers &&
99
+ typeof option.headers === 'object' &&
100
+ !Array.isArray(option.headers)) {
101
+ safeHeaders = option.headers;
102
+ }
103
+ transForm = bodyTransform(body, safeHeaders);
104
+ headers = {
105
+ ...headers,
106
+ ...transForm.headers,
107
+ };
108
+ }
109
+ const req = selectClient(url)
110
+ .request(url, {
111
+ headers,
112
+ ...option,
113
+ }, (res) => {
114
+ let data = '';
115
+ // A chunk of data has been received.
116
+ res.on('data', (chunk) => {
117
+ data += chunk;
118
+ });
119
+ // The whole response has been received. Print out the result.
120
+ res.on('end', () => {
121
+ resolve(fcTransform(res, data));
122
+ });
123
+ })
124
+ .on('error', (err) => {
125
+ console.log(`Error: ${err.message}`);
126
+ resolve({
127
+ code: -1,
128
+ data: null,
129
+ headers: {},
130
+ });
131
+ });
132
+ if (transForm && transForm.body) {
133
+ req.write(transForm.body);
134
+ }
135
+ req.end();
136
+ });
137
+ }
138
+ const NodeCon = {
139
+ get: async (url, config) => {
140
+ return makeRequest(url, {}, undefined, config);
141
+ },
142
+ post: async (url, body, config) => {
143
+ return makeRequest(url, {
144
+ method: 'POST',
145
+ }, body, config);
146
+ },
147
+ patch: async (url, body, config) => {
148
+ return makeRequest(url, {
149
+ method: 'PATCH',
150
+ }, body, config);
151
+ },
152
+ delete: async (url, config) => {
153
+ return makeRequest(url, {
154
+ method: 'DELETE',
155
+ }, undefined, config);
156
+ },
157
+ };
158
+ exports.default = NodeCon;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * THIS FILE IS AUTOMATICALLY GENERATED
3
+ * DO NOT EDIT THIS FILE
4
+ */
5
+ import FormData from 'form-data';
6
+ import BaseCon from './BaseCon.js';
7
+ import ConMerger from './ConMerger.js';
8
+ export * from './BaseCon.js';
9
+ import FetchCon from './FetchCon.js';
10
+ import AxiosCon from './AxiosCon.js';
11
+ export { BaseCon, FormData, FetchCon, AxiosCon, ConMerger };
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ var __importDefault = (this && this.__importDefault) || function (mod) {
17
+ return (mod && mod.__esModule) ? mod : { "default": mod };
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.ConMerger = exports.AxiosCon = exports.FetchCon = exports.FormData = exports.BaseCon = void 0;
21
+ /**
22
+ * THIS FILE IS AUTOMATICALLY GENERATED
23
+ * DO NOT EDIT THIS FILE
24
+ */
25
+ const form_data_1 = __importDefault(require("form-data"));
26
+ exports.FormData = form_data_1.default;
27
+ const BaseCon_js_1 = __importDefault(require("./BaseCon.js"));
28
+ exports.BaseCon = BaseCon_js_1.default;
29
+ const ConMerger_js_1 = __importDefault(require("./ConMerger.js"));
30
+ exports.ConMerger = ConMerger_js_1.default;
31
+ __exportStar(require("./BaseCon.js"), exports);
32
+ const FetchCon_js_1 = __importDefault(require("./FetchCon.js"));
33
+ exports.FetchCon = FetchCon_js_1.default;
34
+ const AxiosCon_js_1 = __importDefault(require("./AxiosCon.js"));
35
+ exports.AxiosCon = AxiosCon_js_1.default;
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,3 @@
1
+ import { ConHandle } from './BaseCon.js';
2
+ declare const AxiosCon: ConHandle;
3
+ export default AxiosCon;
@@ -0,0 +1,36 @@
1
+ import axios from 'axios';
2
+ async function acTransform(r) {
3
+ const res = await r;
4
+ return {
5
+ code: res.status,
6
+ data: res.data,
7
+ headers: res.headers,
8
+ };
9
+ }
10
+ const AxiosCon = {
11
+ get: async (url, config) => {
12
+ return acTransform(axios.get(url, {
13
+ headers: config?.headers,
14
+ validateStatus: (status) => true,
15
+ }));
16
+ },
17
+ post: async (url, body, config) => {
18
+ return acTransform(axios.post(url, body, {
19
+ headers: config?.headers,
20
+ validateStatus: (status) => true,
21
+ }));
22
+ },
23
+ patch: async (url, body, config) => {
24
+ return acTransform(axios.patch(url, body, {
25
+ headers: config?.headers,
26
+ validateStatus: (status) => true,
27
+ }));
28
+ },
29
+ delete: async (url, config) => {
30
+ return acTransform(axios.delete(url, {
31
+ headers: config?.headers,
32
+ validateStatus: (status) => true,
33
+ }));
34
+ },
35
+ };
36
+ export default AxiosCon;
@@ -0,0 +1,182 @@
1
+ /**
2
+ * THIS FILE IS AUTOMATICALLY GENERATED
3
+ * DO NOT EDIT THIS FILE
4
+ */
5
+ export type ErrorType = {
6
+ type: string;
7
+ global?: string[];
8
+ field?: {
9
+ key: string;
10
+ message: string;
11
+ }[];
12
+ };
13
+ export type HeaderType = string | string[] | number | undefined;
14
+ export type HandleRes<T> = {
15
+ success: boolean;
16
+ data: T | null;
17
+ code?: number;
18
+ error?: ErrorType;
19
+ headers?: Record<string, HeaderType>;
20
+ };
21
+ export type PathParam = {
22
+ [key: string]: string | number | undefined;
23
+ };
24
+ export declare function isErrorType(x: any): x is ErrorType;
25
+ export interface ConHandleConfig {
26
+ headers?: Record<string, string>;
27
+ param?: PathParam;
28
+ query?: PathParam;
29
+ }
30
+ export interface ConHandleResponse<T> {
31
+ code: number;
32
+ data: T | null;
33
+ headers: Record<string, HeaderType>;
34
+ }
35
+ export interface ConHandle {
36
+ get<T>(url: string, config?: ConHandleConfig): Promise<ConHandleResponse<T>>;
37
+ post<T, J>(url: string, body?: J, config?: ConHandleConfig): Promise<ConHandleResponse<T>>;
38
+ patch<T, J>(url: string, body?: J, config?: ConHandleConfig): Promise<ConHandleResponse<T>>;
39
+ delete<T>(url: string, config?: ConHandleConfig): Promise<ConHandleResponse<T>>;
40
+ }
41
+ /**
42
+ * BaseCon provides a minimal client for interacting with an HTTP backend.
43
+ * It manages connection state, authentication tokens, and reconnection
44
+ * logic while delegating actual HTTP requests to a supplied {@link ConHandle}.
45
+ *
46
+ * @class
47
+ */
48
+ export default class BaseCon {
49
+ private api;
50
+ private permanentHeader;
51
+ private authorization;
52
+ private noAuth;
53
+ private disconnected;
54
+ private readonly logger;
55
+ con: ConHandle;
56
+ reconnect: () => Promise<boolean>;
57
+ onReconnect: (con: BaseCon) => Promise<boolean>;
58
+ constructor(conf: {
59
+ con: ConHandle;
60
+ endpoint: string;
61
+ logger?: (arg: any) => void;
62
+ permanentHeader?: Record<string, string>;
63
+ });
64
+ /**
65
+ * Retrieves the API endpoint.
66
+ *
67
+ * @return {string} The API endpoint string.
68
+ */
69
+ getApiEndpoint(): string;
70
+ /**
71
+ * Sets the API endpoint URL used by the client.
72
+ *
73
+ * @param {string} endpoint - The full URL of the API endpoint.
74
+ * @returns {void}
75
+ */
76
+ setApiEndpoint(endpoint: string): void;
77
+ /**
78
+ * Indicates whether the instance is considered connected.
79
+ *
80
+ * The instance is regarded as connected when it either does not require authentication
81
+ * (`noAuth` is true) or it has an authorization token set (`authorization` is not null),
82
+ * and it is not currently marked as disconnected.
83
+ *
84
+ * @return {boolean} `true` if the instance is connected, `false` otherwise.
85
+ */
86
+ isConnected(): boolean;
87
+ /**
88
+ * Returns the current authorization token.
89
+ *
90
+ * @return {string} The authorization token or an empty string if none is set.
91
+ */
92
+ token(): string | null;
93
+ /**
94
+ * Returns the current authorization token.
95
+ *
96
+ * @return {string} The authorization token or an empty string if none is set.
97
+ */
98
+ getBearer(): string | null;
99
+ private p;
100
+ /**
101
+ * Sends a ping request to the API to verify connectivity and version availability.
102
+ *
103
+ * @return {boolean} `true` if the API responded with a 200 status code and a valid version object; `false` otherwise.
104
+ */
105
+ ping(): Promise<boolean>;
106
+ private tokenHeader;
107
+ setPermanentHeader(header: Record<string, string>): void;
108
+ /**
109
+ * Validates the current authentication token by performing a ping and a test request
110
+ * to the backend. The method first ensures connectivity via {@link ping}. If the ping
111
+ * succeeds, it attempts to retrieve a token from the `/test/auth` endpoint using the
112
+ * current token in the `Authorization` header. The operation is considered successful
113
+ * if the response status code is 200 or 201.
114
+ *
115
+ * If any step fails, an error is logged and the method returns {@code false}. On
116
+ * success, it returns {@code true}.
117
+ *
118
+ * @return {Promise<boolean>} A promise that resolves to {@code true} if the token
119
+ * test succeeds, otherwise {@code false}.
120
+ */
121
+ testToken(): Promise<boolean>;
122
+ /**
123
+ * Attempts to establish a connection to the backend without authentication.
124
+ *
125
+ * This method sends a ping request. If the ping succeeds, it clears any
126
+ * existing authorization data, marks the instance as connected,
127
+ * enables the no‑authentication mode, and returns `true`. If the ping
128
+ * fails, it logs a warning, clears authorization, marks the instance
129
+ * as disconnected, and returns `false`.
130
+ *
131
+ * @return {Promise<boolean>} `true` when a connection is successfully
132
+ * established without authentication, otherwise `false`.
133
+ */
134
+ connectNoAuth(): Promise<boolean>;
135
+ /**
136
+ * Forces a connection using the provided bearer token.
137
+ *
138
+ * @param {string|null} token The token to be used for authentication.
139
+ * @returns {void}
140
+ */
141
+ forceConnect(token: string | null): void;
142
+ coppyFrom(con: BaseCon): void;
143
+ /**
144
+ * Establishes a connection to the backend using the supplied credentials.
145
+ * Performs a health‑check ping first; if successful, it requests an authentication
146
+ * token from the `/token` endpoint. When the token is obtained, the method
147
+ * updates internal state (authorization header, connection flags) and, unless
148
+ * a dry run is requested, sets up a reconnection routine. Any errors are
149
+ * logged and the method resolves to `false`.
150
+ *
151
+ * @param {string} email - The user's email address for authentication.
152
+ * @param {string} pw - The password (or token) for the specified user.
153
+ * @param {boolean} [dry=false] - If `true`, the method performs a dry run
154
+ * without persisting credentials or configuring reconnection logic.
155
+ *
156
+ * @returns Promise<boolean> `true` if the connection was successfully
157
+ * established, otherwise `false`.
158
+ */
159
+ connect(email: string, pw: string, dry?: boolean): Promise<boolean>;
160
+ /**
161
+ * Performs an HTTP request using the client’s internal connection.
162
+ *
163
+ * The method verifies that the client is connected before attempting a request.
164
+ * It automatically injects the authorization token, permanent headers, and any
165
+ * headers supplied in `config`. If the request body is a `FormData` instance
166
+ * (or provides a `getHeaders` method), the appropriate form headers are added.
167
+ *
168
+ * Response handling:
169
+ * - `200` or `201`: returns `success: true` with the received data.
170
+ * - `498`: attempts to reconnect and retries the request once.
171
+ * - `401`: logs an authentication error, marks the client as disconnected.
172
+ * - `403` and other status codes: return `success: false` with the status code.
173
+ *
174
+ * @param {'POST'|'GET'|'PATCH'|'DELETE'} type The HTTP method to use.
175
+ * @param {string} path The endpoint path relative to the base URL.
176
+ * @param {J} [body] Optional request payload. May be `FormData` or a plain object.
177
+ * @param {ConHandleConfig} [config] Optional Axios-like configuration for the request.
178
+ * @returns {Promise<HandleRes<T>>} A promise that resolves to a `HandleRes` object
179
+ * containing the response data, status code, any error information, and headers.
180
+ */
181
+ handle<T, J>(type: 'POST' | 'GET' | 'PATCH' | 'DELETE', path: string, body?: J, config?: ConHandleConfig): Promise<HandleRes<T>>;
182
+ }