0.6.0 • Published 5 years ago

cpuabuse-system v0.6.0

Weekly downloads
53
License
UNLICENSED
Repository
github
Last release
5 years ago

Build Status npm version Coverage Status Maintainability Inline docs

Files & Data

  • Default file extension is added, if missing
  • For empty value in key/value pair, value equal to key is assumed
  • In absent key/value child pairs, default values for missing keys are assumed

JSDoc - Member Declaration

TypeSelectorDeclaration
static.Default
inner~@inner@memberof module:myModule~myMember
instance#@instance

Structure

Structure

system

System is intended more than anything, for centralized managment.

system.System ⇐ Loader

Provides wide range of functionality for file loading and event exchange. Throws standard error if failed to perform basic initializations, or system failure that cannot be reported otherwise has occured.

Kind: static class of system
Extends: Loader
Emits: systemLoad

new System(options, behaviors)

The constructor will perform necessary preparations, so that failures can be processed with system events. Up until these preparations are complete, the failure will result in thrown standard Error.

Throws:

  • Error - loader_failed - Loader did not construct the mandatory properties
ParamTypeDescription
optionsoptionsSystem options.
behaviorsArray.<behavior>Optional Behaviors to add.

system.events : Object

Events to be populated by the loader. System by itself does not deal with events, it only confirms that the events were initialized. Although, if the events are fired, and failure to fire event is set to throw, or undocumented events encountered, it would throw errors.

Kind: instance abstract property of System

"errorExists"

Error could not be added, because error with same code already exists.

Kind: event emitted by events
Default: error_exists

"systemLoad"

System load event. Fires at the end of system load, so it is safe to execute code in the then() directive of behavior associated.

Kind: event emitted by events
Default: system_load

"behaviorAttach"

Behavior has been attached.

Kind: event emitted by events
Default: behavior_attach

"behaviorAttachFail"

Behavior could not be attached.

Kind: event emitted by events
Default: behavior_attach_fail

"behaviorAttachRequestFail"

Incorrect behavior attach request.

Kind: event emitted by events
Default: behavior_attach_request_fail

"typeError"

Type error has been encountered.

Kind: event emitted by events
Default: type_error

"eventFail"

Failed to fire an event.

Kind: event emitted by events
Default: event_fail

system.behaviors : Object

Behavior describtions initialized by loader.

Kind: instance abstract property of System

system.system : options

Contains system info.

Kind: instance property of System
Read only: true
Properties

NameTypeDescription
behaviorBehaviorEvent emitter for the behaviors. Generally should use the public system instance methods instead.

system.behavior : Behavior

Actual behaviors are located here.

Kind: static property of system

system.error : Object

Actual errors are located here.

Kind: static abstract property of system

system.file : Object

File system methods.

Kind: static property of system

file.filter : Object

File level filters.

Kind: static property of file

filter.isFile(filterContext) ⇒ Promise

Check if argument is a file (relative to system root directory).

Kind: static method of filter
Returns: Promise - Promise, containing boolean result.

ParamTypeDescription
filterContextfilterContextInformation on the item to be filtered.

filter.isDir(filterContext) ⇒ Promise

Check if argument is a folder (relative to system root directory).

Kind: static method of filter
Returns: Promise - Promise, containing boolean result.

ParamTypeDescription
filterContextfilterContextInformation on the item to be filtered

file.toRelative(rootDir, target) ⇒ Promise

Converts absolute path to relative path.

Kind: static method of file
Returns: Promise - Promise, containing string relative path.

ParamTypeDescription
rootDirstringRelative directory.
targetstringAbsolute file/folder path.

file.join(rootDir, target) ⇒ Promise

Joins two paths.

Kind: static method of file
Returns: Promise - Promise, containing string path.

ParamTypeDescription
rootDirstringRelative directory.
targetstringFile/folder path to rootDir.

file.getFile(dir, file) ⇒ Promise

Get file contents relative to system root directory.

Kind: static method of file
Returns: Promise - Promise, containing string with file contents..

ParamTypeDescription
dirstringDirectory, relative to system root.
filestringFilename.

file.getYaml(dir, file) ⇒ Promise

Get contents of yaml file relative to system root directory.

Kind: static method of file
Returns: Promise - Promise, containing string with file contents..

ParamTypeDescription
dirstringDirectory, relative to system root.
filestringFilename.

file.list(dir, file) ⇒ Promise

List the contents of the folder, relative to system root directory.

Kind: static method of file
Returns: Promise - Promise, containing an array of filtered strings - files/folders relative to system root.

ParamTypeDescription
dirstringFolder relative to system root.
filestringFilename.

Example (List folders)

systemInstance.system.file.list("css", systemInstance.system.file.filter.isDir);

system.addError(code, message)

Adds an error to the System dynamically

Kind: instance method of System
Emits: errorExists

ParamTypeDescription
codestringError code
messagestringError description

Example (Usage)

code = "no_beakers"
message = "Beakers out of stock."
var options = {
  id: "lab_inventory",
  rootDir: "labs",
  relativeInitDir: "black_mesa",
  initFilename: "inventory.yml",
  notMute: true
};
var labInventory = new System(options);

labInventory.addError(code, message);

system.addBehaviors(behaviors)

Adds behaviors to the system, and fires post-addtion events. Firstly, this function attempts to add the behaviors. When the behavior addition has been processed, the function will attempt to fire post-addition events, depending on success/failure of behavior additions.

Kind: instance method of System
Emits: behaviorAttach, behaviorAttachFail, behaviorAttachRequestFail

ParamType
behaviorsArray.<behavior>

Example (Usage)

var options = {
  id: "lab_inventory",
  rootDir: "labs",
  relativeInitDir: "black_mesa",
  initFilename: "inventory.yml",
  notMute: true
};
var behavior = {
  "check_inventory": () => {
    // Behavior functionality
    // ...
  }
}

var labInventory = new System(options);
labInventory.addBehaviors([behavior]).then(function(){
  console.log("Behavior added.");
});

system.log(text)

Log message from the System context

Kind: instance method of System
Emits: module:system.System~event:type_error

ParamTypeDescription
textstringMessage

Example (Usage)

var options = {
  id: "lab_inventory",
  rootDir: "labs",
  relativeInitDir: "black_mesa",
  initFilename: "inventory.yml",
  notMute: true
};
var text = "Lab Inventory working.";

var labInventory = new System(options);
labInventory.log(text);

system.error(text)

Log an error message from the System context

Kind: instance method of System
Emits: module:system.System~event:type_error

ParamTypeDescription
textstringMessage

Example (Usage)

var options = {
  id: "lab_inventory",
  rootDir: "labs",
  relativeInitDir: "black_mesa",
  initFilename: "inventory.yml",
  notMute: true
};
var text = "Testing Lab Inventory error log.";

var labInventory = new System(options);
labInventory.error(text);

system.fire(name, message)

Fires a system event

Kind: instance method of System
Throws:

  • Error Will throw error_hell. The inability to process error - if eventFail event fails.

Emits: eventFail

ParamTypeDescription
namestringEvent name, as specified in events.
messagestringOptional Message is not strictly required, but preferred. If not specified, will assume value of the name

Example (Usage)

var options = {
  id: "lab_inventory",
  rootDir: "labs",
  relativeInitDir: "black_mesa",
  initFilename: "inventory.yml",
  notMute: true
};

var labInventory = new System(options);
labInventory.fire("system_load_aux", "Auxiliary system loaded.");

system.behave(event)

Emit an event as a behavior.

Kind: instance method of System

ParamTypeDescription
eventstringBehavior name.

Example (Usage)

// From the lab inventory system context
{
  // ...

  this.behave("system_load_aux");

  // ...
}

system.on(event, callback)

Adds a behavior bound to "this".

Kind: instance method of System

ParamTypeDescription
eventstringBehavior name.
callbackfunctionBehavior.

Example (Usage)

var options = {
  id: "lab_inventory",
  rootDir: "labs",
  relativeInitDir: "black_mesa",
  initFilename: "inventory.yml",
  notMute: true
};

var labInventory = new System(options);
labInventory.on("system_load_aux", function(that){
  console.log("Auxiliary system loaded - " + that.system.id);
});

System.checkOptionsFailure(options) ⇒ boolean

Checks options argument for missing incorrect property types

Kind: static method of System
Returns: boolean - Returns true if the arguments is corrupt; false if OK

ParamTypeDescription
optionsmodule:system~System~optionsSystem options argument

Example (Usage)

var options = {
  id: "stars",
  rootDir: "test",
  relativeInitDir: "stars",
  initFilename: "stars.yml",
  notMute: true
};

if (System.checkOptionsFailure(options)){
  throw new Error ("Options inconsistent.");
}

System.error(text)

Access stderr

Kind: static method of System

ParamType
textstring

Example (Usage)

system.System.error("Not enough resources.");

System.log(text)

Access stdout

Kind: static method of System

ParamType
textstring

Example (Usage)

system.System.log("Resources loaded.");

System~options : Object

System options

Kind: inner typedef of System
Properties

NameTypeDescription
idstringSystem instace internal ID.
rootDirstringThe root directory for the System instance.
relativeInitDirstringThe relative directory to root of the location of the initialization file.
initFilenamestringInitialization file filename.
notMutebooleanWhether the system logs or not.

System~filterContext : Object

System options

Kind: inner typedef of System
Properties

NameTypeDescription
dirstringParent directory of the filtered item
itemNamestringName of the filtered item
itemstringPath to the filtered item

System~behavior : Object

System behavior - an object, with a property where key is the name of the behavior, and value is the function, taking a system context as an argument.

Kind: inner typedef of System
Properties

Type
function

Example (Behavior - argument outline)

amazing_behavior: (that) => {
  // Process system instance on "amazing_behavior"
  amazingProcessor(that);
}

system.AtomicLock

Creates an instance of AtomicLock. It is not intended to be actually used for parallel processing, and mutual exlusion. It is intended for abstraction of atomic logic more than anything.

Note: To be eventually split into a primitive lock to objectify the functionality of a lock, and a lock with timout and a queue.

Kind: static class of system

new AtomicLock()

Creates an instance of AtomicLock. Does not take any arguments or return any values.

atomicLock.locked : boolean

Indicates the locked/unlocked state.

Kind: instance property of AtomicLock
Access: private

atomicLock.lock() ⇒ Promise

Lock an atomic lock.

Kind: instance method of AtomicLock
Returns: Promise - Resolves when lock succeeds
Example (Usage)

// Lock
exampleAtomicLock.lock();

atomicLock.release()

Release atomic lock

Kind: instance method of AtomicLock
Example (Usage)

// Release
exampleAtomicLock.release();

system~Loader

Required by system to perform file initialization.

Kind: inner class of system

new Loader(rootDir, relativeInitDir, initFilename, callback)

ParamTypeDescription
rootDirstringAbsolute root directory.
relativeInitDirstringRelative path to root.
initFilenamestringFilename.
callbackfunctionCallback to call with Promise of completion.

Loader.getFile(rootDir, relativeDir, file) ⇒ external.Promise

Gets file contents.

Kind: static method of Loader
Returns: external.Promise - File contents.

ParamTypeDescription
rootDirstringAbsolute root directory.
relativeDirstringDirectory relative to root.
filestringFull file name.

Example (Usage)

// Load files
var grapefruitJuicer = Loader.getFile("c:\machines", "appliances", "grapefruitJuicer.txt");

// Output the result
grapefruitJuicer.then(function(result){ // grapefruitJuicer - on resolve
  console.log(result);
}, function(error){ // grapefruitJuicer - on reject
  console.error("Could not load a file.");
});

// Input - grapefruitJuicer.txt
// 1000W powerful juicer

// Output
// 1000W powerful juicer

Loader.toRelative(dir, target) ⇒ string | Array.<string>

Extracts relative path from rootDir to target.

Kind: static method of Loader
Returns: string | Array.<string> - Relative path|paths.

ParamTypeDescription
dirstringSource folder.
targetstring | Array.<string>File/folder namenames.

Example (Usage)

// Convert path and output the result
console.log(Loader.toRelative("c:\machines\refrigerators", "c:\machines\appliances"));

// Output
// ..\appliances

Loader.join(rootDir, target) ⇒ string | Array.<string>

Join a root directory with a file/folder or an array of files/folders to absolute path.

Kind: static method of Loader
Returns: string | Array.<string> - Absolute path|paths.

ParamTypeDescription
rootDirstringRoot folder.
targetstring | Array.<string>File/folder namenames.

Example (Usage)

// Join and log result
console.log(Loader.join("c:\machines", "appliances"))

// Output
// c:\machines\appliances

Loader.isFile(rootDir, relativeDir, filename) ⇒ boolean

Checks if is a file

Kind: static method of Loader
Returns: boolean - Returns true if a file, false if not.

ParamTypeDescription
rootDirstringAbsolute root directory.
relativeDirstringRelative directory to root.
filenamestringFull filename.

Example (Usage)

// Verify file
Loader.isFile("c:\machines","appliances","grapefruitJuicer.txt").then(function(result){
  console.log(result);
});

// Input - grapefruitJuicer.txt
// 1000W powerful juicer

// Output
// true

Loader.isDir(rootDir, relativeDir) ⇒ boolean

Checks if is a directory.

Kind: static method of Loader
Returns: boolean - Returns true if a directory, false if not.

ParamTypeDescription
rootDirstringAbsolute root directory.
relativeDirstringRelative directory to root.

Example (Usage)

// Verify directory
Loader.isDir("c:\machines\appliances","grapefruitJuicer.txt").then(function(result){
  console.log(result);
});

// Input - grapefruitJuicer.txt
// 1000W powerful juicer

// Output
// false

Loader.list(rootDir, relativeDir) ⇒ Promise

Returns an array of strings, representing the contents of a folder.

Kind: static method of Loader
Returns: Promise - Array with contents; Rejects with errors from fs.readdir.

ParamTypeDescription
rootDirstringRoot directory.
relativeDirstringRelative directory.

Example (Usage)

// List directory contents
Loader.list("c:","machines").then(function(result){
  console.log(result);
}, function(error){
  console.error("Folder not found.");
});

// Output
// ["machines", "appliances"]

Loader.yamlToObject(string) ⇒ Object

Converts YAML string to a JS object.

Kind: static method of Loader
Returns: Object - Javascript object.

ParamTypeDescription
stringstringYAML string.

Example (Usage)

// Ouput conversion of YAML to JSON
console.log(Loader.yamlToObject("Wine: Red"));

// Output
// {"Wine": "Red"}

Loader~initRecursion(rootDir, relativePath, initFilename, targetObject, extend) ⇒ Promise

System loader recursion.

Note:

  • Default values are assumed for unspecified or empty values.
  • Extension means recursive loading of data into variable, as if loading a new file into the current variable as new system.
  • Relative path is relative to the directory location of current file.

Kind: inner method of Loader
Throws:

  • Will throw an error if the directive is not an allowed one (folder, file, path, extend).
ParamTypeDescription
rootDirstringRoot directory.
relativePathObjectRelative path.
initFilenamestringFilename for settings.
targetObjectObjectObject to be filled.
extendbooleanExtend the children objects or not.

Example (Default filename - null)

# Variable settings to be populated with data from "system_root_dir/settings.yml"
settings: # Defaults to "settings"

Example (Default filename - empty string)

# Variable settings to be populated with data from "system_root_dir/settings.yml"
settings: "" # Defaults to "settings"

Example (Specified filename)

# Variable settings to be populated with data from "system_root_dir/xxx.yml"
settings: "xxx"

Example (Default values)

# Variable settings to be populated with data from "system_root_dir/settings.yml"
settings:
  folder: # Defaults to "./"
  file: # Defaults to "settings"
  path: # Defaults to "absolute"
  extend: # Defaults to "false"

Example (Specified values)

# Variable settings to be populated with data from "current_dir/hello/xxx.yml"
settings:
  folder: "hello"
  file: xxx
  path: relative
  extend: false

Example (Extension)

# Variable settings to be populated **recursively** with data from "current_dir/hello/xxx.yml"
settings:
  folder: "hello"
  file: xxx
  path: relative
  extend: true

Example (Usage)

// Input - ./settings/init.yml
// settings:
//   path: relative

// Input - ./settings/settings.yml
// apples: red
// bananas: yellow

// Target object to fill
var targetObject = {};

initRecursion("./", "settings", "init.yml", targetObject, true));

Loader~initSettings(rootDir, initPath, filename) ⇒ Object

Init and populate globalspace with settings - specific global object member per file. Semantically this function has broader purpose than loadYaml.

Kind: inner method of Loader
Returns: Object - Javascript object with settings.

ParamTypeDescription
rootDirstringRoot directory.
initPathstringRelative directory to root.
filenamestringFilename.

Example (Usage)

var settings = await initSettings("./", "settings", "settings");

Loader~loadYaml(rootDir, relativeDir, filename) ⇒ Promise

Parses YAML file, and returns and object; Adds extension if absent.

Kind: inner method of Loader
Returns: Promise - Javascript object.

ParamTypeDescription
rootDirstringAbsolute directory path.
relativeDirstringRelative directory to root.
filenamestringFilename, with or without extension.

Example (Usage)

var settings = await loadYaml("./", "settings", "settings");

system~SystemError ⇐ Error

Extended system error class.

Kind: inner class of system
Extends: Error

new SystemError(code, message)

Creates an instance of SystemError.

ParamTypeDescription
codestringError code
messagestringError message

systemError.code : string

Error code.

Kind: instance property of SystemError
Access: private

SystemError.isSystemError(error) ⇒ boolean

Check if an object is indeed a functional SystemError.

Note:

  • Not checking for presence of code property, or for it being a string, as assuming that the object of SystemError type would have it initialized.
  • Empty code errors will return false, due to the ambiguity.

Kind: static method of SystemError
Returns: boolean - Returns true if is is a SystemError, false if not.

ParamTypeDescription
errormodule:system.SystemErrorError to check

Example (Usage)

// Try to load JSON
try{
  loadJson();
} catch(error) {
  if (SystemError.isSystemError(error)){
    // If error is something that we have defined, throw a more generic error
    throw new SystemError("json_load_fail", "Failed to load JSON file.");
  } else {
    // Rethrow the original error
    throw error;
  }
}

system~Behavior ⇐ EventEmitter

System behavior class

Kind: inner class of system
Extends: EventEmitter

new Behavior()

Initializes system behavior

behavior.atomicLock : AtomicLock

Atomic lock to perform counter increments

Kind: instance property of Behavior
Access: private

behavior.behaviorId : Object

IDs to use as actual event identifiers

Kind: instance property of Behavior
Access: private

behavior.behaviorIndex : Array.<string>

Index to link id's back to behavior names

Kind: instance property of Behavior
Access: private

behavior.nextBehaviorCounter : number

Counter to use to generate IDs

Kind: instance property of Behavior
Access: private

behavior.addBehavior(name, callback) ⇒ number

Adds a behavior to the behavior class instance.

Note:

Does not check for inconsistencies within ID and index arrays, as if it is internally managed by this class, inconsistencies should not happen.

Kind: instance method of Behavior
Returns: number - ID of the behavior; -1 if creation failed

ParamTypeDescription
namestringName of the bahavior
callbackfunctionBehavior callback function

Example (Usage)

// Create a new instance of Behavior
var behavior = new Behavior();

// Add a behavior
behavior.addBehavior("hello_behavior", () => console.log("Hello World"));

behavior.behave(name)

Triggers behaviors registered for name

Kind: instance method of Behavior

ParamTypeDescription
namestringBehavior name

Example (Usage)

// Create a new instance of Behavior
var behavior = new Behavior();

// Add a behavior
behavior.addBehavior("hello_behavior", () => console.log("Hello World"));

// Call a behavior
behavior.behave("hello_behavior");

// Output:
// "Hello World"

system~test

Series of tests for the system.

Kind: inner property of system

test.Loader

Tests for the Loader class.

Kind: static property of test

Loader.toRelative

Tests the toRelative function.

Kind: static property of Loader

Loader.join

Tests the join function.

Kind: static property of Loader

Loader.isFile

Tests the isFile function.

Kind: static property of Loader

0.6.2

5 years ago

0.6.1

5 years ago

0.6.0

5 years ago

0.5.0

5 years ago

0.4.1

5 years ago

0.4.0

5 years ago

0.3.3

5 years ago

0.3.2

5 years ago

0.3.1

5 years ago

0.3.0

5 years ago

0.2.4

5 years ago

0.2.3

5 years ago

0.2.2

5 years ago

0.2.1

6 years ago

0.2.0

6 years ago

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago