mirror of
https://github.com/Alfresco/alfresco-ng2-components.git
synced 2026-09-09 18:03:21 +00:00
AAE-30882 Remove superagent for fetch (#11856)
* [AAE-30882] - Remove superagent for fetch * [AAE-30882] - Fixing comments * [AAE-30882] - fixde failing unit tests * [AAE-30882] - fixde failing unit tests * [AAE-30882] - fixd sonarcloud comment
This commit is contained in:
@@ -18,7 +18,7 @@
|
||||
import { EventEmitter } from 'eventemitter3';
|
||||
import { AlfrescoApiConfig } from './alfrescoApiConfig';
|
||||
import { Authentication } from './authentication/authentication';
|
||||
import { SuperagentHttpClient } from './superagentHttpClient';
|
||||
import { FetchHttpClient } from './fetchHttpClient';
|
||||
import { Emitters, HttpClient, LegacyHttpClient, RequestOptions, SecurityOptions } from './api-clients/http-client.interface';
|
||||
import { paramToString } from './utils';
|
||||
import { Storage } from './storage';
|
||||
@@ -105,7 +105,7 @@ export class AlfrescoApiClient implements LegacyHttpClient {
|
||||
this.host = host;
|
||||
this.storage = Storage.getInstance();
|
||||
// fallback for backward compatibility
|
||||
this.httpClient = httpClient || new SuperagentHttpClient();
|
||||
this.httpClient = httpClient || new FetchHttpClient();
|
||||
}
|
||||
|
||||
// EventEmitter delegation methods
|
||||
|
||||
@@ -24,6 +24,7 @@ import { AlfrescoApi } from '../alfrescoApi';
|
||||
import { Storage } from '../storage';
|
||||
import { HttpClient } from '../api-clients/http-client.interface';
|
||||
import { PathMatcher } from '../utils/path-matcher';
|
||||
import { isBrowser } from '../utils';
|
||||
|
||||
declare const Buffer: any;
|
||||
|
||||
@@ -355,7 +356,7 @@ export class Oauth2Auth extends AlfrescoApiClient {
|
||||
}
|
||||
|
||||
isRedirectionUrl() {
|
||||
return window.location.hash && window.location.hash.split('&')[0].indexOf('session_state') === -1;
|
||||
return window.location.hash?.split('&')[0].indexOf('session_state') === -1;
|
||||
}
|
||||
|
||||
genNonce(): string {
|
||||
@@ -500,7 +501,7 @@ export class Oauth2Auth extends AlfrescoApiClient {
|
||||
}
|
||||
|
||||
silentRefresh(): void {
|
||||
if (typeof document === 'undefined') {
|
||||
if (!isBrowser()) {
|
||||
this.pollingRefreshToken();
|
||||
return;
|
||||
}
|
||||
@@ -591,7 +592,7 @@ export class Oauth2Auth extends AlfrescoApiClient {
|
||||
resolve(data);
|
||||
},
|
||||
(error) => {
|
||||
if ((error.error && error.error.status === 401) || error.status === 401) {
|
||||
if (error.error?.status === 401 || error.status === 401) {
|
||||
this.emit('unauthorized');
|
||||
}
|
||||
this.emit('error');
|
||||
@@ -640,7 +641,7 @@ export class Oauth2Auth extends AlfrescoApiClient {
|
||||
resolve(data);
|
||||
},
|
||||
(error) => {
|
||||
if (error.error && error.error.status === 401) {
|
||||
if (error.error?.status === 401) {
|
||||
this.emit('unauthorized');
|
||||
}
|
||||
this.emit('error');
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2025 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { Authentication } from './authentication/authentication';
|
||||
import { RequestOptions, HttpClient, SecurityOptions, Emitters } from './api-clients/http-client.interface';
|
||||
import { Oauth2 } from './authentication/oauth2';
|
||||
import { BasicAuth } from './authentication/basicAuth';
|
||||
import { isBrowser, paramToString } from './utils';
|
||||
|
||||
declare const Blob: any;
|
||||
declare const Buffer: any;
|
||||
declare const process: any;
|
||||
declare const XMLHttpRequest: any;
|
||||
|
||||
export class FetchHttpClient implements HttpClient {
|
||||
timeout: number | { deadline?: number; response?: number } = undefined;
|
||||
private readonly customFetch?: typeof fetch;
|
||||
|
||||
constructor(customFetch?: typeof fetch) {
|
||||
this.customFetch = customFetch;
|
||||
}
|
||||
|
||||
private getFetch(): typeof fetch {
|
||||
// eslint-disable-next-line no-underscore-dangle
|
||||
return this.customFetch || (typeof process !== 'undefined' && (process as any).__test_fetch__) || globalThis.fetch;
|
||||
}
|
||||
|
||||
private hasNativeXhr(): boolean {
|
||||
// eslint-disable-next-line no-underscore-dangle
|
||||
if (this.customFetch || (typeof process !== 'undefined' && (process as any).__test_fetch__)) {
|
||||
return false;
|
||||
}
|
||||
return typeof XMLHttpRequest !== 'undefined';
|
||||
}
|
||||
|
||||
post<T = any>(url: string, options: RequestOptions, securityOptions: SecurityOptions, emitters: Emitters): Promise<T> {
|
||||
return this.request<T>(url, { ...options, httpMethod: 'POST' }, securityOptions, emitters);
|
||||
}
|
||||
|
||||
put<T = any>(url: string, options: RequestOptions, securityOptions: SecurityOptions, emitters: Emitters): Promise<T> {
|
||||
return this.request<T>(url, { ...options, httpMethod: 'PUT' }, securityOptions, emitters);
|
||||
}
|
||||
|
||||
get<T = any>(url: string, options: RequestOptions, securityOptions: SecurityOptions, emitters: Emitters): Promise<T> {
|
||||
return this.request<T>(url, { ...options, httpMethod: 'GET' }, securityOptions, emitters);
|
||||
}
|
||||
|
||||
delete<T = void>(url: string, options: RequestOptions, securityOptions: SecurityOptions, emitters: Emitters): Promise<T> {
|
||||
return this.request<T>(url, { ...options, httpMethod: 'DELETE' }, securityOptions, emitters);
|
||||
}
|
||||
|
||||
request<T = any>(url: string, options: RequestOptions, securityOptions: SecurityOptions, emitters: Emitters): Promise<T> {
|
||||
const { httpMethod, queryParams, headerParams, formParams, bodyParam, contentType, accept, responseType, returnType } = options;
|
||||
|
||||
const headers = this.buildHeaders(headerParams, securityOptions, contentType, accept);
|
||||
const queryString = FetchHttpClient.buildQueryString(queryParams);
|
||||
const fullUrl = queryString ? `${url}${url.includes('?') ? '&' : '?'}${queryString}` : url;
|
||||
const body = this.buildBody(contentType, formParams, bodyParam);
|
||||
const hasBody = body !== undefined && httpMethod !== 'GET' && httpMethod !== 'HEAD';
|
||||
const withCredentials = securityOptions.withCredentials || securityOptions.isBpmRequest;
|
||||
|
||||
if (hasBody && this.hasNativeXhr()) {
|
||||
return this.requestWithXhr<T>(fullUrl, httpMethod, headers, body, withCredentials, returnType, responseType, securityOptions, emitters);
|
||||
}
|
||||
|
||||
return this.requestWithFetch<T>(
|
||||
fullUrl,
|
||||
httpMethod,
|
||||
headers,
|
||||
hasBody ? body : undefined,
|
||||
withCredentials,
|
||||
returnType,
|
||||
responseType,
|
||||
securityOptions,
|
||||
emitters
|
||||
);
|
||||
}
|
||||
|
||||
private requestWithFetch<T>(
|
||||
url: string,
|
||||
method: string,
|
||||
headers: Record<string, string>,
|
||||
body: any,
|
||||
withCredentials: boolean,
|
||||
returnType: string,
|
||||
responseType: string,
|
||||
securityOptions: SecurityOptions,
|
||||
emitters: Emitters
|
||||
): Promise<T> {
|
||||
const { eventEmitter } = emitters;
|
||||
const controller = new AbortController();
|
||||
const timeoutMs = typeof this.timeout === 'number' ? this.timeout : this.timeout?.deadline;
|
||||
|
||||
if (timeoutMs) {
|
||||
if (typeof AbortSignal.timeout === 'function') {
|
||||
AbortSignal.timeout(timeoutMs).addEventListener('abort', () => controller.abort());
|
||||
} else {
|
||||
setTimeout(() => controller.abort(), timeoutMs);
|
||||
}
|
||||
}
|
||||
|
||||
const init: RequestInit = {
|
||||
method,
|
||||
headers,
|
||||
signal: controller.signal,
|
||||
credentials: withCredentials ? 'include' : 'same-origin'
|
||||
};
|
||||
|
||||
if (body !== undefined) {
|
||||
init.body = body;
|
||||
}
|
||||
|
||||
const fn = this.getFetch();
|
||||
|
||||
const promise: any = new Promise<T>((resolve, reject) => {
|
||||
const execute = async () => {
|
||||
const response = await fn(url, init);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => '');
|
||||
const error: any = new Error(errorText || response.statusText);
|
||||
error.status = response.status;
|
||||
error.response = response;
|
||||
|
||||
FetchHttpClient.emitErrorEvents(error, response.status, emitters);
|
||||
// eslint-disable-next-line prefer-promise-reject-errors
|
||||
reject({ error, status: response.status, message: errorText || response.statusText });
|
||||
return;
|
||||
}
|
||||
|
||||
if (securityOptions.isBpmRequest) {
|
||||
const setCookie = response.headers.get('set-cookie');
|
||||
if (setCookie) {
|
||||
securityOptions.authentications.cookie = setCookie;
|
||||
}
|
||||
}
|
||||
|
||||
const data = await this.deserializeResponse(response, returnType, responseType);
|
||||
eventEmitter.emit('success', data);
|
||||
resolve(data as T);
|
||||
};
|
||||
|
||||
execute().catch((error: any) => {
|
||||
if (error.name === 'AbortError') {
|
||||
eventEmitter.emit('abort');
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
if (!error.status) {
|
||||
FetchHttpClient.emitErrorEvents(error, 0, emitters);
|
||||
}
|
||||
// eslint-disable-next-line prefer-promise-reject-errors
|
||||
reject(error.status ? { error, status: error.status, message: error.message } : { error });
|
||||
});
|
||||
});
|
||||
|
||||
promise.abort = () => {
|
||||
controller.abort();
|
||||
return promise;
|
||||
};
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
private requestWithXhr<T>(
|
||||
url: string,
|
||||
method: string,
|
||||
headers: Record<string, string>,
|
||||
body: any,
|
||||
withCredentials: boolean,
|
||||
returnType: string,
|
||||
responseType: string,
|
||||
securityOptions: SecurityOptions,
|
||||
emitters: Emitters
|
||||
): Promise<T> {
|
||||
const { eventEmitter } = emitters;
|
||||
const timeoutMs = typeof this.timeout === 'number' ? this.timeout : this.timeout?.deadline;
|
||||
let xhr: any;
|
||||
|
||||
const promise: any = new Promise<T>((resolve, reject) => {
|
||||
xhr = new XMLHttpRequest();
|
||||
xhr.open(method, url, true);
|
||||
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
xhr.setRequestHeader(key, value);
|
||||
}
|
||||
|
||||
if (withCredentials) {
|
||||
xhr.withCredentials = true;
|
||||
}
|
||||
|
||||
if (timeoutMs) {
|
||||
xhr.timeout = timeoutMs;
|
||||
}
|
||||
|
||||
if (returnType === 'blob' || returnType === 'Blob' || responseType === 'blob' || responseType === 'Blob' || returnType === 'Binary') {
|
||||
xhr.responseType = 'blob';
|
||||
}
|
||||
|
||||
xhr.upload.onprogress = (event: any) => {
|
||||
if (event.lengthComputable) {
|
||||
const percent = Math.round((event.loaded / event.total) * 100);
|
||||
eventEmitter.emit('progress', { total: event.total, loaded: event.loaded, percent });
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
if (securityOptions.isBpmRequest) {
|
||||
const setCookie = xhr.getResponseHeader('set-cookie');
|
||||
if (setCookie) {
|
||||
securityOptions.authentications.cookie = setCookie;
|
||||
}
|
||||
}
|
||||
|
||||
const data = this.deserializeXhrResponse(xhr, returnType, responseType);
|
||||
eventEmitter.emit('success', data);
|
||||
resolve(data as T);
|
||||
} else {
|
||||
const errorText = xhr.responseText || xhr.statusText;
|
||||
const error: any = new Error(errorText);
|
||||
error.status = xhr.status;
|
||||
error.message = errorText;
|
||||
|
||||
FetchHttpClient.emitErrorEvents(error, xhr.status, emitters);
|
||||
// eslint-disable-next-line prefer-promise-reject-errors
|
||||
reject({ error, status: xhr.status, message: errorText });
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onerror = () => {
|
||||
const error = new Error('Network request failed');
|
||||
FetchHttpClient.emitErrorEvents(error, 0, emitters);
|
||||
// eslint-disable-next-line prefer-promise-reject-errors
|
||||
reject({ error });
|
||||
};
|
||||
|
||||
xhr.onabort = () => {
|
||||
eventEmitter.emit('abort');
|
||||
reject(new DOMException('The operation was aborted.', 'AbortError'));
|
||||
};
|
||||
|
||||
xhr.ontimeout = () => {
|
||||
const error = new Error('Request timed out');
|
||||
FetchHttpClient.emitErrorEvents(error, 0, emitters);
|
||||
// eslint-disable-next-line prefer-promise-reject-errors
|
||||
reject({ error });
|
||||
};
|
||||
|
||||
xhr.send(body);
|
||||
});
|
||||
|
||||
promise.abort = () => {
|
||||
if (xhr) {
|
||||
xhr.abort();
|
||||
}
|
||||
return promise;
|
||||
};
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
private deserializeXhrResponse(xhr: any, returnType: string, responseType: string): any {
|
||||
if (returnType === 'blob' || returnType === 'Blob' || responseType === 'blob' || responseType === 'Blob' || returnType === 'Binary') {
|
||||
return xhr.response;
|
||||
}
|
||||
|
||||
if (returnType === 'String') {
|
||||
return xhr.responseText;
|
||||
}
|
||||
|
||||
const contentType = xhr.getResponseHeader('content-type') || '';
|
||||
if (contentType.includes('text/html')) {
|
||||
return xhr.responseText;
|
||||
}
|
||||
|
||||
try {
|
||||
const text = xhr.responseText;
|
||||
if (!text) {
|
||||
return {};
|
||||
}
|
||||
const data = JSON.parse(text);
|
||||
if (returnType && Array.isArray(data)) {
|
||||
return data.map((element: any) => new (returnType as any)(element));
|
||||
}
|
||||
if (returnType && typeof returnType === 'function') {
|
||||
return new (returnType as any)(data);
|
||||
}
|
||||
return data;
|
||||
} catch {
|
||||
return xhr.responseText || '';
|
||||
}
|
||||
}
|
||||
|
||||
setCsrfToken(headers: Record<string, string>): void {
|
||||
const token = FetchHttpClient.createCSRFToken();
|
||||
headers['X-CSRF-TOKEN'] = token;
|
||||
|
||||
if (!isBrowser()) {
|
||||
headers['Cookie'] = 'CSRF-TOKEN=' + token + ';path=/';
|
||||
}
|
||||
|
||||
try {
|
||||
document.cookie = 'CSRF-TOKEN=' + token + ';path=/';
|
||||
} catch {
|
||||
/* continue regardless of error */
|
||||
}
|
||||
}
|
||||
|
||||
private buildHeaders(
|
||||
headerParams: Record<string, any>,
|
||||
securityOptions: SecurityOptions,
|
||||
contentType: string,
|
||||
accept: string
|
||||
): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
...securityOptions.defaultHeaders,
|
||||
...FetchHttpClient.normalizeParams(headerParams)
|
||||
};
|
||||
|
||||
this.applyAuthHeaders(headers, securityOptions.authentications);
|
||||
|
||||
if (securityOptions.isBpmRequest && securityOptions.enableCsrf) {
|
||||
this.setCsrfToken(headers);
|
||||
}
|
||||
|
||||
if (securityOptions.isBpmRequest && securityOptions.authentications.cookie && !isBrowser()) {
|
||||
headers['Cookie'] = headers['Cookie']
|
||||
? headers['Cookie'] + '; ' + securityOptions.authentications.cookie
|
||||
: securityOptions.authentications.cookie;
|
||||
}
|
||||
|
||||
if (contentType && contentType !== 'multipart/form-data') {
|
||||
headers['Content-Type'] = contentType;
|
||||
} else if (contentType !== 'multipart/form-data' && !headers['Content-Type']) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
|
||||
if (accept) {
|
||||
headers['Accept'] = accept;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
private buildBody(contentType: string, formParams: Record<string, any>, bodyParam: string | object): any {
|
||||
if (contentType === 'application/x-www-form-urlencoded') {
|
||||
const params = FetchHttpClient.normalizeParams(formParams);
|
||||
return new URLSearchParams(params).toString();
|
||||
}
|
||||
|
||||
if (contentType === 'multipart/form-data') {
|
||||
const normalizedParams = FetchHttpClient.normalizeParams(formParams);
|
||||
const formData = new FormData();
|
||||
for (const [key, value] of Object.entries(normalizedParams)) {
|
||||
formData.append(key, value as any);
|
||||
}
|
||||
return formData;
|
||||
}
|
||||
|
||||
if (bodyParam) {
|
||||
return typeof bodyParam === 'string' ? bodyParam : JSON.stringify(bodyParam);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private static emitErrorEvents(error: any, status: number, emitters: Emitters): void {
|
||||
const { eventEmitter, apiClientEmitter } = emitters;
|
||||
|
||||
apiClientEmitter.emit('error', error);
|
||||
eventEmitter.emit('error', error);
|
||||
|
||||
if (status === 401) {
|
||||
apiClientEmitter.emit('unauthorized');
|
||||
eventEmitter.emit('unauthorized');
|
||||
}
|
||||
|
||||
if (status === 403) {
|
||||
apiClientEmitter.emit('forbidden');
|
||||
eventEmitter.emit('forbidden');
|
||||
}
|
||||
}
|
||||
|
||||
private applyAuthHeaders(headers: Record<string, string>, authentications: Authentication): void {
|
||||
if (!authentications) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (authentications.type) {
|
||||
case 'basic': {
|
||||
const basicAuth: BasicAuth = authentications.basicAuth;
|
||||
if (basicAuth.username || basicAuth.password) {
|
||||
const encoded =
|
||||
typeof btoa === 'function'
|
||||
? btoa((basicAuth.username || '') + ':' + (basicAuth.password || ''))
|
||||
: Buffer.from((basicAuth.username || '') + ':' + (basicAuth.password || '')).toString('base64');
|
||||
headers['Authorization'] = 'Basic ' + encoded;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'activiti': {
|
||||
if (authentications.basicAuth.ticket) {
|
||||
headers['Authorization'] = authentications.basicAuth.ticket;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'oauth2': {
|
||||
const oauth2: Oauth2 = authentications.oauth2;
|
||||
if (oauth2.accessToken) {
|
||||
headers['Authorization'] = 'Bearer ' + oauth2.accessToken;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new Error('Unknown authentication type: ' + authentications.type);
|
||||
}
|
||||
}
|
||||
|
||||
private async deserializeResponse(response: Response, returnType: string, responseType: string): Promise<any> {
|
||||
if (returnType === 'blob' || returnType === 'Blob' || responseType === 'blob' || responseType === 'Blob' || returnType === 'Binary') {
|
||||
const blob = await response.blob();
|
||||
if (isBrowser()) {
|
||||
return blob;
|
||||
}
|
||||
const arrayBuffer = await blob.arrayBuffer();
|
||||
return Buffer.from(arrayBuffer);
|
||||
}
|
||||
|
||||
if (returnType === 'String') {
|
||||
return response.text();
|
||||
}
|
||||
|
||||
const contentTypeHeader = response.headers.get('content-type') || '';
|
||||
if (contentTypeHeader.includes('text/html')) {
|
||||
return response.text();
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
if (!text) {
|
||||
return {};
|
||||
}
|
||||
try {
|
||||
const data = JSON.parse(text);
|
||||
if (returnType && Array.isArray(data)) {
|
||||
return data.map((element: any) => new (returnType as any)(element));
|
||||
}
|
||||
if (returnType && typeof returnType === 'function') {
|
||||
return new (returnType as any)(data);
|
||||
}
|
||||
return data;
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
private static createCSRFToken(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
const bytes = new Uint8Array(16);
|
||||
crypto.getRandomValues(bytes);
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
|
||||
private static buildQueryString(params: Record<string, any>): string {
|
||||
if (!params) {
|
||||
return '';
|
||||
}
|
||||
const normalized = FetchHttpClient.normalizeParams(params);
|
||||
const searchParams = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(normalized)) {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((v: any) => searchParams.append(key, v));
|
||||
} else {
|
||||
searchParams.append(key, value);
|
||||
}
|
||||
}
|
||||
return searchParams.toString();
|
||||
}
|
||||
|
||||
private static normalizeParams(params: Record<string, any>): Record<string, any> {
|
||||
if (!params) {
|
||||
return {};
|
||||
}
|
||||
const newParams: Record<string, any> = {};
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value != null) {
|
||||
newParams[key] = FetchHttpClient.isFileParam(value) || Array.isArray(value) ? value : paramToString(value);
|
||||
}
|
||||
}
|
||||
return newParams;
|
||||
}
|
||||
|
||||
private static isFileParam(param: any): boolean {
|
||||
if (typeof Buffer === 'function' && (param instanceof Buffer || param?.path)) {
|
||||
return true;
|
||||
}
|
||||
if (typeof Blob === 'function' && param instanceof Blob) {
|
||||
return true;
|
||||
}
|
||||
if (typeof File === 'function' && param instanceof File) {
|
||||
return true;
|
||||
}
|
||||
if (typeof File === 'object' && param instanceof File) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,376 +0,0 @@
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2025 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import superagent, { Response, SuperAgentRequest } from 'superagent';
|
||||
import { Authentication } from './authentication/authentication';
|
||||
import { RequestOptions, HttpClient, SecurityOptions, Emitters } from './api-clients/http-client.interface';
|
||||
import { Oauth2 } from './authentication/oauth2';
|
||||
import { BasicAuth } from './authentication/basicAuth';
|
||||
import { isBrowser, paramToString } from './utils';
|
||||
import { EventEmitterInstance } from './types';
|
||||
|
||||
declare const Blob: any;
|
||||
declare const Buffer: any;
|
||||
|
||||
const isProgressEvent = (event: ProgressEvent | unknown): event is ProgressEvent => (event as ProgressEvent)?.lengthComputable;
|
||||
|
||||
export class SuperagentHttpClient implements HttpClient {
|
||||
/**
|
||||
* The default HTTP timeout for all API calls.
|
||||
*/
|
||||
timeout: number | { deadline?: number; response?: number } = undefined;
|
||||
|
||||
post<T = any>(url: string, options: RequestOptions, securityOptions: SecurityOptions, emitters: Emitters): Promise<T> {
|
||||
return this.request<T>(url, { ...options, httpMethod: 'POST' }, securityOptions, emitters);
|
||||
}
|
||||
|
||||
put<T = any>(url: string, options: RequestOptions, securityOptions: SecurityOptions, emitters: Emitters): Promise<T> {
|
||||
return this.request<T>(url, { ...options, httpMethod: 'PUT' }, securityOptions, emitters);
|
||||
}
|
||||
|
||||
get<T = any>(url: string, options: RequestOptions, securityOptions: SecurityOptions, emitters: Emitters): Promise<T> {
|
||||
return this.request<T>(url, { ...options, httpMethod: 'GET' }, securityOptions, emitters);
|
||||
}
|
||||
|
||||
delete<T = void>(url: string, options: RequestOptions, securityOptions: SecurityOptions, emitters: Emitters): Promise<T> {
|
||||
return this.request<T>(url, { ...options, httpMethod: 'DELETE' }, securityOptions, emitters);
|
||||
}
|
||||
|
||||
request<T = any>(url: string, options: RequestOptions, securityOptions: SecurityOptions, emitters: Emitters): Promise<T> {
|
||||
const { httpMethod, queryParams, headerParams, formParams, bodyParam, contentType, accept, responseType, returnType } = options;
|
||||
const { eventEmitter, apiClientEmitter } = emitters;
|
||||
|
||||
let request = this.buildRequest(
|
||||
httpMethod,
|
||||
url,
|
||||
queryParams,
|
||||
headerParams,
|
||||
formParams,
|
||||
bodyParam,
|
||||
contentType,
|
||||
accept,
|
||||
responseType,
|
||||
eventEmitter,
|
||||
returnType,
|
||||
securityOptions
|
||||
);
|
||||
|
||||
if (returnType === 'Binary') {
|
||||
request = request.buffer(true).parse(superagent.parse['application/octet-stream']);
|
||||
}
|
||||
|
||||
const promise: any = new Promise((resolve, reject) => {
|
||||
request.on('abort', () => {
|
||||
eventEmitter.emit('abort');
|
||||
});
|
||||
request.end((error: any, response: Response) => {
|
||||
if (error) {
|
||||
apiClientEmitter.emit('error', error);
|
||||
eventEmitter.emit('error', error);
|
||||
|
||||
if (error.status === 401) {
|
||||
apiClientEmitter.emit('unauthorized');
|
||||
eventEmitter.emit('unauthorized');
|
||||
}
|
||||
|
||||
if (response?.text) {
|
||||
error = error || {};
|
||||
reject(Object.assign(error, { message: response.text }));
|
||||
} else {
|
||||
// eslint-disable-next-line prefer-promise-reject-errors
|
||||
reject({ error });
|
||||
}
|
||||
} else {
|
||||
if (securityOptions.isBpmRequest) {
|
||||
const hasSetCookie = Object.prototype.hasOwnProperty.call(response.header, 'set-cookie');
|
||||
if (response.header && hasSetCookie) {
|
||||
// mutate the passed value from AlfrescoApiClient class for backward compatibility
|
||||
securityOptions.authentications.cookie = response.header['set-cookie'][0];
|
||||
}
|
||||
}
|
||||
let data = {};
|
||||
if (response.type === 'text/html') {
|
||||
data = SuperagentHttpClient.deserialize(response);
|
||||
} else {
|
||||
data = SuperagentHttpClient.deserialize(response, returnType);
|
||||
}
|
||||
|
||||
eventEmitter.emit('success', data);
|
||||
resolve(data);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
promise.abort = function () {
|
||||
request.abort();
|
||||
return this;
|
||||
};
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
private buildRequest(
|
||||
httpMethod: string,
|
||||
url: string,
|
||||
queryParams: { [key: string]: any },
|
||||
headerParams: { [key: string]: any },
|
||||
formParams: { [key: string]: any },
|
||||
bodyParam: string | object,
|
||||
contentType: string,
|
||||
accept: string,
|
||||
responseType: string,
|
||||
eventEmitter: EventEmitterInstance,
|
||||
returnType: string,
|
||||
securityOptions: SecurityOptions
|
||||
) {
|
||||
const request = superagent(httpMethod, url);
|
||||
|
||||
const { isBpmRequest, authentications, defaultHeaders = {}, enableCsrf, withCredentials = false } = securityOptions;
|
||||
|
||||
// apply authentications
|
||||
this.applyAuthToRequest(request, authentications);
|
||||
|
||||
// set query parameters
|
||||
request.query(SuperagentHttpClient.normalizeParams(queryParams));
|
||||
|
||||
// set header parameters
|
||||
request.set(defaultHeaders).set(SuperagentHttpClient.normalizeParams(headerParams));
|
||||
|
||||
if (isBpmRequest && enableCsrf) {
|
||||
this.setCsrfToken(request);
|
||||
}
|
||||
|
||||
if (withCredentials) {
|
||||
request.withCredentials();
|
||||
}
|
||||
|
||||
// add cookie for activiti
|
||||
if (isBpmRequest) {
|
||||
request.withCredentials();
|
||||
if (securityOptions.authentications.cookie) {
|
||||
if (!isBrowser()) {
|
||||
request.set('Cookie', securityOptions.authentications.cookie);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// set request timeout
|
||||
request.timeout(this.timeout);
|
||||
|
||||
if (contentType && contentType !== 'multipart/form-data') {
|
||||
request.type(contentType);
|
||||
} else if (!(request as any).header['Content-Type'] && contentType !== 'multipart/form-data') {
|
||||
request.type('application/json');
|
||||
}
|
||||
|
||||
if (contentType === 'application/x-www-form-urlencoded') {
|
||||
request.send(SuperagentHttpClient.normalizeParams(formParams)).on('progress', (event: any) => {
|
||||
this.progress(event, eventEmitter);
|
||||
});
|
||||
} else if (contentType === 'multipart/form-data') {
|
||||
const _formParams = SuperagentHttpClient.normalizeParams(formParams);
|
||||
for (const key in _formParams) {
|
||||
if (Object.prototype.hasOwnProperty.call(_formParams, key)) {
|
||||
if (SuperagentHttpClient.isFileParam(_formParams[key])) {
|
||||
// file field
|
||||
request.attach(key, _formParams[key]).on('progress', (event: ProgressEvent) => {
|
||||
// jshint ignore:line
|
||||
this.progress(event, eventEmitter);
|
||||
});
|
||||
} else {
|
||||
request.field(key, _formParams[key]).on('progress', (event: ProgressEvent) => {
|
||||
// jshint ignore:line
|
||||
this.progress(event, eventEmitter);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (bodyParam) {
|
||||
request.send(bodyParam).on('progress', (event: any) => {
|
||||
this.progress(event, eventEmitter);
|
||||
});
|
||||
}
|
||||
|
||||
if (accept) {
|
||||
request.accept(accept);
|
||||
}
|
||||
|
||||
if (returnType === 'blob' || returnType === 'Blob' || responseType === 'blob' || responseType === 'Blob') {
|
||||
request.responseType('blob');
|
||||
} else if (returnType === 'String') {
|
||||
request.responseType('string');
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
setCsrfToken(request: SuperAgentRequest): void {
|
||||
const token = SuperagentHttpClient.createCSRFToken();
|
||||
request.set('X-CSRF-TOKEN', token);
|
||||
|
||||
if (!isBrowser()) {
|
||||
request.set('Cookie', 'CSRF-TOKEN=' + token + ';path=/');
|
||||
}
|
||||
|
||||
try {
|
||||
document.cookie = 'CSRF-TOKEN=' + token + ';path=/';
|
||||
} catch {
|
||||
/* continue regardless of error */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies authentication headers to the request.
|
||||
* @param request The request object created by a <code>superagent()</code> call.
|
||||
* @param authentications authentications
|
||||
*/
|
||||
private applyAuthToRequest(request: SuperAgentRequest, authentications: Authentication) {
|
||||
if (authentications) {
|
||||
switch (authentications.type) {
|
||||
case 'basic': {
|
||||
const basicAuth: BasicAuth = authentications.basicAuth;
|
||||
if (basicAuth.username || basicAuth.password) {
|
||||
request.auth(basicAuth.username || '', basicAuth.password || '');
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'activiti': {
|
||||
if (authentications.basicAuth.ticket) {
|
||||
request.set({ Authorization: authentications.basicAuth.ticket });
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'oauth2': {
|
||||
const oauth2: Oauth2 = authentications.oauth2;
|
||||
if (oauth2.accessToken) {
|
||||
request.set({ Authorization: 'Bearer ' + oauth2.accessToken });
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new Error('Unknown authentication type: ' + authentications.type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private progress(event: ProgressEvent | unknown, eventEmitter: EventEmitterInstance): void {
|
||||
if (isProgressEvent(event)) {
|
||||
const percent = Math.round((event.loaded / event.total) * 100);
|
||||
|
||||
const progress = {
|
||||
total: event.total,
|
||||
loaded: event.loaded,
|
||||
percent
|
||||
};
|
||||
|
||||
eventEmitter.emit('progress', progress);
|
||||
}
|
||||
}
|
||||
|
||||
private static createCSRFToken(a?: any): string {
|
||||
return a
|
||||
? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16)
|
||||
: ([1e16] + (1e16).toString()).replace(/[01]/g, SuperagentHttpClient.createCSRFToken);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserializes an HTTP response body into a value of the specified type.
|
||||
* @param response A SuperAgent response object.
|
||||
* @param returnType The type to return. Pass a string for simple types
|
||||
* or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To
|
||||
* return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type:
|
||||
* all properties on <code>data<code> will be converted to this type.
|
||||
* @returns A value of the specified type.
|
||||
*/
|
||||
private static deserialize(response: Response, returnType?: any): any {
|
||||
if (response === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let data = response.body;
|
||||
|
||||
if (data === null) {
|
||||
data = response.text;
|
||||
}
|
||||
|
||||
if (returnType) {
|
||||
if (returnType === 'blob' && isBrowser()) {
|
||||
data = new Blob([data], { type: response.header['content-type'] });
|
||||
} else if (returnType === 'blob' && !isBrowser()) {
|
||||
data = new Buffer.from(data, 'binary');
|
||||
} else if (Array.isArray(data)) {
|
||||
data = data.map((element) => new returnType(element));
|
||||
} else {
|
||||
data = new returnType(data);
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes parameter values:
|
||||
* <ul>
|
||||
* <li>remove nils</li>
|
||||
* <li>keep files and arrays</li>
|
||||
* <li>format to string with `paramToString` for other cases</li>
|
||||
* </ul>
|
||||
* @param params The parameters as object properties.
|
||||
* @returns normalized parameters.
|
||||
*/
|
||||
private static normalizeParams(params: { [key: string]: any }): { [key: string]: any } {
|
||||
const newParams: { [key: string]: any } = {};
|
||||
|
||||
for (const key in params) {
|
||||
if (Object.prototype.hasOwnProperty.call(params, key) && params[key] != null) {
|
||||
const value = params[key];
|
||||
if (SuperagentHttpClient.isFileParam(value) || Array.isArray(value)) {
|
||||
newParams[key] = value;
|
||||
} else {
|
||||
newParams[key] = paramToString(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return newParams;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given parameter value represents file-like content.
|
||||
* @param param The parameter to check.
|
||||
* @returns <code>true</code> if <code>param</code> represents a file.
|
||||
*/
|
||||
private static isFileParam(param: any): boolean {
|
||||
// Buffer in Node.js
|
||||
if (typeof Buffer === 'function' && (param instanceof Buffer || param.path)) {
|
||||
return true;
|
||||
}
|
||||
// Blob in browser
|
||||
if (typeof Blob === 'function' && param instanceof Blob) {
|
||||
return true;
|
||||
}
|
||||
// File in browser (it seems File object is also instance of Blob, but keep this for safe)
|
||||
if (typeof File === 'function' && param instanceof File) {
|
||||
return true;
|
||||
}
|
||||
// Safari fix
|
||||
if (typeof File === 'object' && param instanceof File) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2025 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { getGlobalMockAgent } from '../test/mockObjects/base.mock';
|
||||
|
||||
getGlobalMockAgent();
|
||||
Reference in New Issue
Block a user