Socket
Socket
Sign inDemoInstall

@zenflux/core

Package Overview
Dependencies
0
Maintainers
1
Versions
49
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.0.0-devlopment.0 to 0.0.0-devlopment.2

dist/es/clients/http.d.ts

64

package.json
{
"name": "@zenflux/core",
"version": "0.0.0-devlopment.0",
"version": "0.0.0-devlopment.2",
"description": "ZenFlux core",
"author": "Leonid Vinikov <leonidvinikov@gmail.com> (https://github.com/iNewLegend)",
"scripts": {
"test": "export flow_modules_logger=off && jest",
"build": "rollup --config rollup.config.ts --configPlugin typescript"
},
"repository": {
"type": "git",
"url": "git+https://github.com/zenflux/core.git"
},
"keywords": [

@@ -20,4 +11,16 @@ "zenflux",

"manager",
"commands manager"
"commands manager",
"core",
"zenflux-core"
],
"repository": {
"type": "git",
"url": "git+https://github.com/zenflux/core.git"
},
"license": "MIT",
"author": "Leonid Vinikov <leonidvinikov@gmail.com> (https://github.com/iNewLegend)",
"main": "dist/cjs/zenflux-core.js",
"unpkg": "dist/umd/zenflux-core.js",
"module": "dist/es/zenflux-core.js",
"types": "types/index.d.ts",
"files": [

@@ -28,30 +31,21 @@ "dist",

],
"license": "MIT",
"main": "dist/cjs/zenflux-core.js",
"unpkg": "dist/umd/zenflux-core.js",
"module": "dist/es/zenflux-core.js",
"types": "types/index.d.ts",
"scripts": {
"test": "export flow_modules_logger=off && jest",
"toolkit-build": "node_modules/@zenflux/rollup-toolkit/bin/run @build",
"toolkit-build-dev": "node_modules/@zenflux/rollup-toolkit/bin/dev @build",
"toolkit-watch": "node_modules/@zenflux/rollup-toolkit/bin/run @watch",
"toolkit-watch-dev": "node_modules/@zenflux/rollup-toolkit/bin/dev @watch"
},
"devDependencies": {
"@babel/core": "^7.20.7",
"@babel/plugin-transform-runtime": "^7.19.6",
"@babel/plugin-syntax-import-assertions": "^7.20.0",
"@babel/preset-env": "^7.20.2",
"@babel/preset-typescript": "^7.18.6",
"@babel/runtime": "^7.20.7",
"@rollup/plugin-babel": "^6.0.3",
"@rollup/plugin-json": "^6.0.0",
"@rollup/plugin-node-resolve": "^15.0.1",
"@rollup/plugin-replace": "^5.0.2",
"@rollup/plugin-terser": "^0.2.1",
"@rollup/plugin-typescript": "^10.0.1",
"@types/jest": "^29.2.5",
"@typescript-eslint/eslint-plugin": "^5.48.0",
"@typescript-eslint/parser": "^5.48.0",
"babel-jest": "^29.3.1",
"rollup": "^3.9.1",
"ts-jest": "^29.0.3",
"tslib": "^2.4.1"
},
"dependencies": {
"@babel/runtime": "^7.19.0"
"@types/jest": "^29.4.0",
"@typescript-eslint/eslint-plugin": "^5.50.0",
"@typescript-eslint/parser": "^5.50.0",
"@zenflux/rollup-toolkit": "^0.0.0-alpha.15",
"babel-jest": "^29.4.1",
"ts-jest": "^29.0.5",
"tslib": "^2.5.0"
}
}

@@ -9,4 +9,11 @@ /**

import { HTTPMethodEnum } from "../enums/http";
import {
E_HTTP_METHOD_TYPE,
TErrorHandlerCallbackType,
TResponseFilterCallbackType,
TResponseHandlerCallbackType,
} from "../interfaces/";
// noinspection ExceptionCaughtLocallyJS
export class Http extends ObjectBase {

@@ -17,2 +24,6 @@ private readonly logger: Logger;

private errorHandler?: TErrorHandlerCallbackType = undefined;
private responseFilter?: TResponseFilterCallbackType = undefined;
private responseHandler?: TResponseHandlerCallbackType = undefined;
static getName() {

@@ -38,3 +49,3 @@ return 'Core/Clients/Http';

*/
async fetch( path: string, method: HTTPMethodEnum, body: {} | null = null ) {
async fetch( path: string, method: E_HTTP_METHOD_TYPE, body: any = {} ) {
this.logger.startWith( { path, method, body } );

@@ -45,7 +56,5 @@

if ( [
HTTPMethodEnum.POST,
HTTPMethodEnum.PUT,
HTTPMethodEnum.PATCH,
].includes( method ) ) {
if ( method === E_HTTP_METHOD_TYPE.GET ) {
Object.assign( params, { headers } );
} else {
Object.assign( headers, { 'Content-Type': 'application/json' } );

@@ -57,5 +66,2 @@ Object.assign( params, {

} );
} else {
Object.assign( params, { headers } );
}

@@ -68,14 +74,28 @@

try {
data = await response.json();
if ( ! response.ok ) {
throw response;
}
let responseText = await response.text();
responseText = this.applyResponseFilter( responseText );
// TODO: Currently support JSON and plain text.
if ( response.headers?.get( 'Content-Type' )?.includes( 'application/json' ) ) {
data = JSON.parse( responseText );
} else {
data = responseText;
}
if ( this.applyResponseHandler( data ) ) {
return false;
}
} catch ( e ) {
console.error( e );
if ( this.applyErrorHandler( e ) ) {
return false;
}
return false;
await Promise.reject( e );
}
// TODO: This is part should be modular and not hard coded.
if ( data?.error && data?.global && data?.message ) {
throw new Error( data.message );
}
this.logger.drop( { path }, data );

@@ -85,4 +105,40 @@

}
public setErrorHandler( callback: TErrorHandlerCallbackType ) {
if ( this.errorHandler ) {
throw new Error( 'Error handler already set.' );
}
this.errorHandler = callback;
}
public setResponseFilter( callback: TResponseFilterCallbackType ) {
if ( this.responseFilter ) {
throw new Error( 'Response filter already set.' );
}
this.responseFilter = callback;
}
public setResponseHandler( callback: TResponseHandlerCallbackType ) {
if ( this.responseHandler ) {
throw new Error( 'Response handler already set.' );
}
this.responseHandler = callback;
}
private applyErrorHandler( error: any ) {
return this.errorHandler && this.errorHandler( error );
}
private applyResponseFilter( text: string ) {
return ( this.responseFilter && this.responseFilter( text ) ) || text;
}
private applyResponseHandler( text: string ) {
return this.responseHandler && this.responseHandler( text );
}
}
export default Http;

@@ -8,2 +8,3 @@ /**

import ObjectBase from "../core/object-base";
import Controller from "../core/controller";

@@ -14,5 +15,9 @@ import ForceMethod from "../errors/force-method";

import { ICommandArgsInterface, ICommandOptionsInterface } from "../interfaces/commands";
import { ControllerAlreadySet } from "../errors";
import { ICommandArgsInterface, ICommandOptionsInterface } from "../interfaces/";
export abstract class CommandBase extends ObjectBase {
private static controller: Controller;
protected args: ICommandArgsInterface = {};

@@ -23,2 +28,14 @@ protected options: ICommandOptionsInterface = {};

public static setController( controller: Controller ) {
if ( this.controller ) {
throw new ControllerAlreadySet();
}
this.controller = controller;
}
public static getController() {
return this.controller;
}
constructor( args: ICommandArgsInterface = {}, options = {} ) {

@@ -38,3 +55,3 @@ super();

initialize( args: ICommandArgsInterface, options: ICommandOptionsInterface ) {
public initialize( args: ICommandArgsInterface, options: ICommandOptionsInterface ) {
this.args = args;

@@ -44,7 +61,7 @@ this.options = options;

apply( args = this.args, options = this.options ): any {// eslint-disable-line @typescript-eslint/no-unused-vars
public apply( args = this.args, options = this.options ): any {// eslint-disable-line @typescript-eslint/no-unused-vars
throw new ForceMethod( this, "apply" );
}
async run() {
public async run() {
this.onBeforeApply && this.onBeforeApply();

@@ -59,15 +76,15 @@

getArgs() {
public getArgs() {
return this.args;
}
getOptions() {
public getOptions() {
return this.options;
}
onBeforeApply?():void;
public onBeforeApply?():void;
onAfterApply?():void;
public onAfterApply?():void;
}
export default CommandBase;

@@ -8,3 +8,3 @@ /**

import { data } from '../managers/';
import * as managers from '../managers';

@@ -32,4 +32,4 @@ export abstract class CommandData extends CommandBase {

return data.getClient().fetch(
endpoint, data.currentHttpMethod, args || null
return managers.data.getClient().fetch(
endpoint, managers.data.currentHttpMethod, args || null
);

@@ -36,0 +36,0 @@ }

@@ -7,3 +7,3 @@ /**

import { IObjectBaseInterface } from "../interfaces/object-base";
import { IObjectBaseInterface } from "../interfaces/";

@@ -10,0 +10,0 @@ let IdCounter = 0;

export { CommandAlreadyRegistered } from "./command-already-registered";
export { CommandNotFound } from "./command-not-found";
export { ControllerAlreadyRegistered } from "./controller-already-registered";
export { ControllerAlreadySet } from './controller-already-set';
export { ForceMethod } from "./force-method";

@@ -7,2 +7,3 @@ /**

export * as errors from "./errors";
export * as interfaces from "./interfaces";
export * as managers from "./managers";

@@ -12,2 +13,1 @@ export * as managerBases from "./manager-bases";

export * as utils from "./utils";
/**
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
*/
export { CoreAPI as default } from "./initializer";
export * from './exports';
export { CoreAPI as default } from "./initializer";

@@ -1,15 +0,17 @@

import pkg from "../package.json";
// @ts-ignore
import * as pkg from "../package.json" assert { type: "json" };
import { IAPIConfig } from "./interfaces/config";
import { destroy, initialize, afterInitializeCallbacks } from "./managers";
import * as exported from './exports';
import { IAPIConfig } from "./interfaces/config";
declare global {
var ZenCore: any;
var __ZEN_CORE__IS_INITIALIZED__: boolean;
}
let isInitialized = false;
function errorInitTwice() {
if ( isInitialized ) {
if ( 'undefined' !== typeof __ZEN_CORE__IS_INITIALIZED__ && __ZEN_CORE__IS_INITIALIZED__) {
throw new Error( 'ZenCore is already initialized.' );

@@ -23,6 +25,4 @@ }

version: pkg.version,
}
};
const afterInitializeCallbacks: ( () => void )[] = [];
export const CoreAPI = {

@@ -34,19 +34,12 @@ initialize: ( configuration?: IAPIConfig ) => {

exported.managers.commands = new exported.managerBases.Commands();
exported.managers.controllers = new exported.managerBases.Controllers();
exported.managers.data = new exported.managerBases.Data( config );
exported.managers.internal = new exported.managerBases.Internal();
initialize( config );
isInitialized = true;
globalThis.__ZEN_CORE__IS_INITIALIZED__ = true;
afterInitializeCallbacks.forEach( ( callback ) => callback() );
},
destroy: () => {
isInitialized = false;
destroy();
exported.managers.commands = {} as exported.managerBases.Commands;
exported.managers.controllers = {} as exported.managerBases.Controllers
exported.managers.data = {} as exported.managerBases.Data;
exported.managers.internal = {} as exported.managerBases.Internal;
globalThis.__ZEN_CORE__IS_INITIALIZED__ = false;
},

@@ -61,3 +54,3 @@

...exported,
}
};

@@ -64,0 +57,0 @@ // TODO: Make it available only for development.

@@ -7,11 +7,14 @@ /**

import { CommandBase } from "../command-bases";
import { Controller, ObjectBase } from "../core";
import { CommandAlreadyRegistered, CommandNotFound } from "../errors/";
import ObjectBase from "../core/object-base";
import Controller from "../core/controller";
import {
CommandCallbackType,
ICommandArgsInterface,
CommandCallbackType,
IOnHookAffectInterface,
IOnHookInterface, ICommandOptionsInterface,
} from "../interfaces/commands";
IOnHookInterface,
ICommandOptionsInterface,
} from "../interfaces/";

@@ -96,2 +99,4 @@ export class Commands extends ObjectBase {

command.setController( controller );
this.commands[ commandName ] = command;

@@ -98,0 +103,0 @@

@@ -5,3 +5,4 @@ /**

*/
import { Controller, ObjectBase } from "../core";
import ObjectBase from "../core/object-base";
import Controller from "../core/controller";

@@ -8,0 +9,0 @@ import { ControllerAlreadyRegistered } from "../errors/controller-already-registered";

@@ -11,6 +11,14 @@ /**

import { HTTPMethodEnum } from "../enums/http";
import {
IAPIConfig,
ICommandArgsInterface,
ICommandOptionsInterface,
TErrorHandlerCallbackType,
TPossibleHandlersType,
TResponseFilterCallbackType,
TResponseHandlerCallbackType,
import { IAPIConfig } from "../interfaces/config";
import { ICommandArgsInterface, ICommandOptionsInterface } from '../interfaces/commands';
E_RESPONSE_HANDLER_TYPE,
E_HTTP_METHOD_TYPE
} from "../interfaces/";

@@ -20,3 +28,3 @@ export class Data extends Commands {

public currentHttpMethod: HTTPMethodEnum;
public currentHttpMethod: E_HTTP_METHOD_TYPE;

@@ -30,3 +38,2 @@ static getName() {

// @ts-ignore
Data.client = new Http( Config.baseURL );

@@ -40,3 +47,3 @@ }

public get( command: string, args: ICommandArgsInterface = {}, options: ICommandOptionsInterface = {} ) {
this.currentHttpMethod = HTTPMethodEnum.GET;
this.currentHttpMethod = E_HTTP_METHOD_TYPE.GET;

@@ -47,3 +54,3 @@ return super.run( command, args, options );

public update( command: string, args: ICommandArgsInterface = {}, options: {} = {} ) {
this.currentHttpMethod = HTTPMethodEnum.PATCH;
this.currentHttpMethod = E_HTTP_METHOD_TYPE.PATCH;

@@ -54,3 +61,3 @@ return super.run( command, args, options );

public delete( command: string, args: ICommandArgsInterface = {}, options: {} = {} ) {
this.currentHttpMethod = HTTPMethodEnum.DELETE;
this.currentHttpMethod = E_HTTP_METHOD_TYPE.DELETE;

@@ -61,3 +68,3 @@ return super.run( command, args, options );

public create( command: string, args: ICommandArgsInterface = {}, options: {} = {} ) {
this.currentHttpMethod = HTTPMethodEnum.POST;
this.currentHttpMethod = E_HTTP_METHOD_TYPE.POST;

@@ -81,3 +88,3 @@ return super.run( command, args, options );

if ( HTTPMethodEnum.GET === this.currentHttpMethod ) {
if ( E_HTTP_METHOD_TYPE.GET === this.currentHttpMethod ) {
newArgs.args.query = args;

@@ -88,11 +95,31 @@ } else {

args.result = await super.runInstance( command, newArgs, options )
args.result = await super.runInstance( command, newArgs, options );
// Clear method type.
this.currentHttpMethod = HTTPMethodEnum.__EMPTY__;
this.currentHttpMethod = E_HTTP_METHOD_TYPE.__EMPTY__;
return args.result;
}
/**
* Handlers on return true will swallow the request.
*/
public setHandler( type: E_RESPONSE_HANDLER_TYPE, callback: TPossibleHandlersType ) {
switch ( type ) {
case E_RESPONSE_HANDLER_TYPE.ERROR_HANDLER:
Data.client.setErrorHandler( callback as TErrorHandlerCallbackType );
break;
case E_RESPONSE_HANDLER_TYPE.RESPONSE_FILTER:
Data.client.setResponseFilter( callback as TResponseFilterCallbackType );
break;
case E_RESPONSE_HANDLER_TYPE.RESPONSE_HANDLER:
Data.client.setResponseHandler( callback as TResponseHandlerCallbackType );
break;
default:
throw new Error( `Unknown handler type: '${ type }'` );
}
}
}
export default Data;
/**
* @author: Leonid Vinikov <leonidvinikov@gmail.com>
*/
import * as managersBases from "../manager-bases";
import Commands from "../manager-bases/commands";
import Controllers from "../manager-bases/controllers";
import Data from "../manager-bases/data";
import Internal from "../manager-bases/internal";
export let commands = {} as managersBases.Commands;
export let controllers = {} as managersBases.Controllers;
export let data = {} as managersBases.Data;
export let internal = {} as managersBases.Internal;
import { IAPIConfig } from "../interfaces/";
export const afterInitializeCallbacks: ( () => void )[] = [];
export function initialize( config: IAPIConfig ) {
commands = new Commands();
controllers = new Controllers();
data = new Data( config );
internal = new Internal();
}
export function destroy() {
commands = {} as Commands;
controllers = {} as Controllers;
data = {} as Data;
internal = {} as Internal;
}
export var commands = {} as Commands;
export var controllers = {} as Controllers;
export var data = {} as Data;
export var internal = {} as Internal;

@@ -11,4 +11,17 @@ /**

// TODO: Should by dynamic/configure-able.
const MAX_WRAPPING_RECURSIVE_DEPTH = 4;
const MAX_WRAPPING_RECURSIVE_DEPTH = 4,
STACK_BACKWARD_CALLER_INDEX = 3,
UNKNOWN_CALLER_NAME = 'anonymous function',
BABEL_EXCLUDE_FUNCTIONS_NAMES = [
'_callee',
'tryCatch',
'<anonymous>',
'Generator.next',
'asyncGeneratorStep',
'_next',
];
// TODO: Should by dynamic/configure-able.
Error.stackTraceLimit = 50;
export class Logger {

@@ -57,3 +70,2 @@ static wrappers = {};

Logger.wrappers[ classType.name ].push( { classType, callback } );
}

@@ -66,3 +78,4 @@

const error = new Error(),
caller = error.stack ? error.stack.split( "\n" )[ 3 ].trim() : '_UNKNOWN_CALLER_NAME_'
errorsPerLine = error.stack?.split( "\n" ) || [],
caller = errorsPerLine.length ? errorsPerLine[ STACK_BACKWARD_CALLER_INDEX ].trim() : UNKNOWN_CALLER_NAME;

@@ -73,3 +86,36 @@ if ( caller.startsWith( "at new" ) ) {

return caller.split( "." )[ 1 ].split( " " )[ 0 ];
let extractName = caller.split( "." )[ 1 ].split( " " )[ 0 ],
isBabelAsyncRuntime = false;
// Babel compatibility.
if ( extractName.includes( '_callee' ) ) {
// Run till find reliable function name.
for ( let i = STACK_BACKWARD_CALLER_INDEX; i < errorsPerLine.length; i++ ) {
const line = errorsPerLine[ i ];
const isExcluded = BABEL_EXCLUDE_FUNCTIONS_NAMES.some( ( excludeName ) => {
return line.includes( excludeName );
} );
if ( ! isExcluded ) {
const format = line.trim().split(' ');
if ( format.length <= 2 ) {
continue;
}
extractName = format[ 1 ].split( "." )[ 1 ];
isBabelAsyncRuntime = true;
break;
}
}
if ( ! isBabelAsyncRuntime ) {
extractName = UNKNOWN_CALLER_NAME;
}
}
return extractName;
}

@@ -81,3 +127,3 @@

private static getFunctionView( fn: string | Function ): ( string | Function ) {
let fReturn = "anonymous function()";
let fReturn = UNKNOWN_CALLER_NAME;

@@ -165,3 +211,3 @@ // TODO: Check if works.

// Result will lose classType (instanceOf will not work), now based on obj.
let result = { ... obj };
let result = { ...obj };

@@ -414,3 +460,3 @@ // @ts-ignore

*/
private out( ... args: any ) {
private out( ...args: any ) {
this.outputHandler.apply( this, args );

@@ -417,0 +463,0 @@ }

@@ -1,2 +0,6 @@

export * from '../dist/es/src/exports';
export { initialize, destroy, onAfterInitialize } from "../dist/es/src/initializer";
export { initialize, destroy, onAfterInitialize } from "../dist/es/initializer";
export * from '../dist/es/exports';
export * as managers from "../dist/es/managers";

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc