molly-db 1.3.0 → 1.3.2

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,47 @@
1
+ /*--────────────────────────────────────────────────────────────────────────────────────────────--*/
2
+
3
+ const memory = require('./memory_handler');
4
+ const worker = require('worker_threads');
5
+ const init = require('./init_handler');
6
+ const {Buffer} = require('buffer');
7
+ const utils = require('./utils');
8
+ const path = require('path');
9
+
10
+ /*--────────────────────────────────────────────────────────────────────────────────────────────--*/
11
+
12
+ function Error(error){ console.log(`worker error: ${error}`); }
13
+ function Exit(code){ console.log(`worker exit code: ${code}`); }
14
+
15
+ /*--────────────────────────────────────────────────────────────────────────────────────────────--*/
16
+
17
+ function saveTimeout(data,db){
18
+ setTimeout(() => {
19
+ if( db._update_ ){
20
+ db._update_ = false;
21
+ utils.saveAll(data,db);
22
+ }
23
+ }, data.time * 3600 * 1000 );
24
+ }
25
+
26
+ /*--────────────────────────────────────────────────────────────────────────────────────────────--*/
27
+
28
+ module.exports = (args)=>{
29
+ init( args ).then((db)=>{ saveTimeout( args, db );
30
+ const dir = path.join(__dirname,'server_worker.js');
31
+ const srv = new worker.Worker(dir,{ workerData: args });
32
+ srv.on('error',Error); srv.on('exit',Exit); srv.on('message',(msg)=>{
33
+ const empty = '{ "status":"404", "message":"empty data" }';
34
+ const error = '{ "status":"404", "message":"error data" }';
35
+ try {
36
+ const raw = Buffer.from(msg).toString();
37
+ memory(args,JSON.parse(raw),db).then(x=>{
38
+ const out = JSON.stringify(x); srv.postMessage(out||empty);
39
+ }).catch(e=>{
40
+ const out = JSON.stringify(e); srv.postMessage(out||empty);
41
+ })
42
+ } catch(e) { console.log(e); srv.postMessage(error) }
43
+ });
44
+ }).catch((e)=>{ console.log(e) });
45
+ }
46
+
47
+ /*--────────────────────────────────────────────────────────────────────────────────────────────--*/
package/package.json CHANGED
@@ -1,12 +1,18 @@
1
1
  {
2
+ "scripts": {
3
+ "start": "node main"
4
+ },
5
+ "repository": "https://github.com/EDBC-REPO-NPM/Molly-db",
6
+ "dependencies": {
7
+ "crypto-js": "^4.1.1",
8
+ "molly-fetch": "^1.0.16",
9
+ "ws": "^8.11.0"
10
+ },
2
11
  "license": "MIT",
3
12
  "main": "main.js",
4
13
  "name": "molly-db",
5
- "version": "1.3.0",
14
+ "version": "1.3.2",
6
15
  "author": "bececrazy",
7
- "scripts": { "start": "node main" },
8
- "repository": "https://github.com/EDBC-REPO-NPM/Molly-db",
9
- "dependencies": { "crypto-js": "^4.1.1", "molly-fetch": "^1.0.16" },
10
16
  "description": "Molly-db is a free and open source library for nodejs that allow you create a lightweight encrypted database using Json files",
11
17
  "keywords": [
12
18
  "json",
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2022 Enmanuel D Becerra C
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/README.md DELETED
File without changes
package/module/_api_.js DELETED
@@ -1,212 +0,0 @@
1
- /* --------------------------------------------------------------------------------------- */
2
-
3
- function list( _params ){
4
- try{return parseData( db[_params.db][_params.table].slice(
5
- _params.offset, Number(_params.offset)+Number(_params.length)
6
- ).map(x=>JSON.parse(x)));
7
- } catch(e) { return parseError(e) }
8
- }
9
-
10
- function match( _params ){
11
- try{
12
- const result = new Array();
13
- db[_params.db][_params.table].map((x)=>{
14
- const reg = crypto.slugify(_params.target);
15
- const regex = new RegExp(reg,'gi');
16
- const target = crypto.slugify(x);
17
- if( regex.test(target) ) result.push(x);
18
- });
19
- return parseData( result.map(x=>JSON.parse(x)).slice(
20
- _params.offset, Number(_params.offset)+Number(_params.length)
21
- ), result.length);
22
- } catch(e) { return parseError(e) }
23
- }
24
-
25
- function hash( _params ){
26
- try{const result = new Array();
27
- db[_params.db][_params.table].map((x)=>{
28
- const regex = new RegExp(_params.target,'gi');
29
- if( regex.test(x) ) result.push(x);
30
- });
31
- return parseData( result.map(x=>JSON.parse(x)).slice(
32
- _params.offset, Number(_params.offset)+Number(_params.length)
33
- ), result.length);
34
- } catch(e) { return parseError(e) }
35
- }
36
-
37
- /* --------------------------------------------------------------------------------------- */
38
-
39
- async function unshift( _params ){ db._update_ = true;
40
- return parseData(db[_params.db][_params.table].unshift(...body))
41
- }
42
-
43
- async function push( _params ){ db._update_ = true;
44
- return parseData(db[_params.db][_params.table].push(...body))
45
- }
46
-
47
- async function shift( _params ){ db._update_ = true;
48
- return parseData(db[_params.db][_params.table].shift())
49
- }
50
-
51
- async function pop( _params ){ db._update_ = true;
52
- return parseData(db[_params.db][_params.table].pop())
53
- }
54
-
55
- /* --------------------------------------------------------------------------------------- */
56
-
57
- async function update( _params ){
58
- try{db._update_ = true;
59
- for( var i in db[_params.db][_params.table] ){
60
-
61
- const regex = new RegExp(_params.target,'gi');
62
- if( regex.test(db[_params.db][_params.table][i]) )
63
- return db[_params.db][_params.table].splice(i,1,...body);
64
-
65
- }
66
- } catch(e) { return parseError(e) }
67
- }
68
-
69
- async function remove( _params ){
70
- try{db._update_ = true;
71
- for( var i in db[_params.db][_params.table] ){
72
-
73
- const regex = new RegExp(_params.target,'gi');
74
- if( regex.test(db[_params.db][_params.table][i]) )
75
- return db[_params.db][_params.table].splice(i,1);
76
-
77
- }
78
- } catch(e) { return parseError(e) }
79
- }
80
-
81
- /* --------------------------------------------------------------------------------------- */
82
-
83
- async function addTable( _params ){
84
- try{db._update_ = true;
85
-
86
- if( db[_params.db][_params.table] ) return {
87
- status: 'table already exist',
88
- database: _params.db,
89
- table: _params.table,
90
- };
91
-
92
- for( var i in db._init_.DB ){
93
- if( db._init_.DB[i].name == _params.db ){
94
- db[_params.db][_params.table] = new Array();
95
- db._init_.DB[i].tables.push(_params.table);
96
- break;
97
- }
98
- }
99
-
100
- /*await save( _params )*/ return {
101
- status: 'table added',
102
- database: _params.db,
103
- table: _params.table,
104
- };
105
-
106
- } catch(e) { return parseError(e) }
107
- }
108
-
109
- async function removeTable( _params ){
110
- try{db._update_ = true;
111
-
112
- if( !db[_params.db][_params.table] ) return {
113
- status: 'table does not exist',
114
- database: _params.db,
115
- table: _params.table,
116
- };
117
-
118
- for( var i in db._init_.DB ){
119
- if( db._init_.DB[i].name == _params.db ){
120
- delete db[_params.db][_params.table];
121
- db._init_.DB[i].tables.splice(j,1);
122
- break;
123
- }
124
- }
125
-
126
- /*await save( _params )*/ return {
127
- status: 'table removed',
128
- database: _params.db,
129
- table: _params.table,
130
- };
131
-
132
- } catch(e) { return parseError(e) }
133
- }
134
-
135
- /* --------------------------------------------------------------------------------------- */
136
-
137
- async function addDB( _params ){
138
- try{db._update_ = true;
139
-
140
- if( db[_params.db] ) return {
141
- status: 'DB already exist',
142
- database: _params.db,
143
- table: _params.table,
144
- };
145
-
146
- db._init_.DB.push({
147
- tables: [], name: _params.db,
148
- }); db[_params.db] = new Array();
149
-
150
- /*await save( _params )*/ return {
151
- database: _params.db,
152
- status: 'DB added'
153
- };
154
-
155
- } catch(e) { return parseError(e) }
156
- }
157
-
158
- async function removeDB( _params ){
159
- try{
160
-
161
- if( !db[_params.db] ) return {
162
- status: 'DB does not exist',
163
- database: _params.db,
164
- table: _params.table,
165
- };
166
-
167
- for( var i in db._init_.DB ){
168
- if( db._init_.DB.name == _params.db ){
169
- db._init_.DB[i].tables.map(x=>{
170
- const path = `${query.path}/${x}.json`;
171
- fs.unlinkSync(path);
172
- }); db._init_.DB.splice(i,1);
173
- delete db[_params.db];
174
- break;
175
- }
176
- }
177
-
178
- /*await save( _params )*/ return {
179
- database: _params.db,
180
- table: _params.table,
181
- status: 'DB deleted'
182
- };
183
-
184
- } catch(e) { return parseError(e) }
185
- }
186
-
187
- async function modifyDB( _name, _table ){
188
- try{
189
-
190
- const init = `${query.path}/_init_.json`;
191
- const path = `${query.path}/${_table}.json`;
192
-
193
- fs.writeFileSync( init,JSON.stringify(db._init_) );
194
-
195
- try{const length = db[_name][_table].length;
196
- if( !(length>0) ) fs.writeFileSync(path,'');
197
- else await encryptDB( _name, _table, path );
198
- } catch(e) { fs.unlinkSync( path ); }
199
-
200
- } catch(e) { return parseError(e) }
201
- }
202
-
203
- /* --------------------------------------------------------------------------------------- */
204
-
205
- async function saveAll(){
206
- try{for( var i in db['_init_'] ){ for( var j in db['_init_'][i] ){
207
- const {name,tables} = db['_init_'][i][j];
208
- for( var k in tables )
209
- await modifyDB(name,tables[k])
210
- }} return { status: 'DB Saved' };
211
- } catch(e) { console.log(e); return parseError(e) }
212
- }
package/module/_app_.js DELETED
@@ -1,187 +0,0 @@
1
-
2
- const api = url.parse( req.url,true );
3
- const query = process.mollyDB;
4
- let params = api.query;
5
- let body = undefined;
6
- let parse = api;
7
-
8
- /* --------------------------------------------------------------------------------------- */
9
-
10
- function error( _error ){
11
- res.writeHead(404,{'contetn-type':'application/json'});
12
- res.end(JSON.stringify([{ status:'error', message:_error }]));
13
- console.log( _error,req.url );
14
- }
15
-
16
- function json( _data ){
17
- res.writeHead(200,{'content-type':'application/json'});
18
- res.end(JSON.stringify(_data));
19
- }
20
-
21
- function parseData( _data, _length ){
22
- const length = _length||db[params.db][params.table].length;
23
- const pagination = Math.ceil(length/_data.length)||1;
24
- return {
25
- pagination: pagination,
26
- database: params.db,
27
- table: params.table,
28
- length: length,
29
- status: 'OK',
30
- data: _data,
31
- }
32
- }
33
-
34
- function parseError( _e ){
35
- return {
36
- data: _e.message||_e,
37
- database: params.db,
38
- table: params.table,
39
- status: 'error',
40
- }
41
- }
42
-
43
- /* --------------------------------------------------------------------------------------- */
44
-
45
- function bodyParser( _data ){
46
- try{
47
- const date = Date.now(); _data = JSON.parse(_data);
48
- const result = _data.length ? _data : [_data];
49
- return result.map(x=>{ if( !x?.hash )
50
- x.hash = crypto.hash( date,Math.random() );
51
- return JSON.stringify(x);
52
- });
53
- } catch(e) { return false }
54
- }
55
-
56
- function getBody(){
57
- return new Promise((response,reject)=>{
58
- try{
59
- if( req.method == 'POST' || (/push|unshift|splice|update/).test(api.pathname) ){
60
- const data = new Array();
61
- req.on('data',(chunk)=>{ data.push(chunk); });
62
- req.on('close',()=>{ try{
63
- const buff = Buffer.concat(data);
64
- response( bodyParser(buff) );
65
- } catch(e) { response(false) } });
66
- } else { response(true) }
67
- } catch(e) { response(false) }
68
- });
69
- }
70
-
71
- function encryptDB( _db,_table, _path ){
72
- return new Promise((response,reject)=>{
73
- const writable = fs.createWriteStream( _path+'_tmp' );
74
- for( var i in db[_db][_table] ){
75
-
76
- const data = db[_db][_table][i];
77
- const ecrp = crypto.encrypt( data,query.pass );
78
-
79
- writable.write(`${ecrp}\n`);
80
- } writable.end();
81
-
82
- writable.on('close',()=>{
83
- fs.renameSync( _path+'_tmp', _path );
84
- response('done');
85
- });
86
-
87
- writable.on('error',(e)=>{
88
- reject(e);
89
- });
90
- });
91
- }
92
-
93
- function validate( _params ){
94
- return new Promise((response,reject)=>{
95
-
96
- let validator = false;
97
-
98
- const vdb = (key)=>{ return db._init_.DB.some(x=>{ return x.name == key; }) }
99
- const vtb = (key)=>{ return db._init_.DB.some(x=>{ return x.tables.join().match(key); }) }
100
-
101
- validator = [
102
- [ !_params?.offset, '_params.offset = 0' ],
103
- [ !_params?.target, '_params.target = ""' ],
104
- [ !_params?.length, '_params.length = 100' ],
105
- ].every(x=>{ if(x[0]) eval(x[1]); return true; });
106
-
107
- validator = [
108
- [!body, {status:'error',message:'invalid data'}],
109
- [!_params?.db, {status:'error',message:'no db name added'}],
110
- [!_params?.table, {status:'error',message:'no table name added'}]
111
- ].some(x=>{ if(x[0]) reject(x[1]); return x[0];}); if(validator) return 0;
112
-
113
- if( !(/table|db|all/gi).test(parse.pathname) ){
114
- validator = [
115
- [!vdb(_params?.db), {status:'error',message:`no db called ${_params.db} exist`}],
116
- [!vtb(_params?.table), {status:'error',message:`no table called ${_params.table} exist`}]
117
- ].some(x=>{ if(x[0]) reject(x[1]); return x[0];}); if(validator) return 0;
118
- }
119
-
120
- response(_params);
121
-
122
- });
123
- }
124
-
125
- /* --------------------------------------------------------------------------------------- */
126
-
127
- function refresh( _params ){
128
- return new Promise((response,reject)=>{
129
- _init_().then(()=>{ response([{status: 'done'}]) })
130
- .catch((e)=>{ reject([{status:'error',message:e.message}]) });
131
- });
132
- }
133
-
134
- async function save( _params ){
135
- await modifyDB( _params.db,_params.table );
136
- return [{
137
- database: _params.db,
138
- table: _params.table,
139
- status: 'saved'
140
- }];
141
- }
142
-
143
- /* --------------------------------------------------------------------------------------- */
144
-
145
- (async ()=>{
146
- try{
147
-
148
- body = await getBody();
149
- if( api.pathname == '/saveAll' )
150
- return json( await saveAll() );
151
- params = await validate(params);
152
-
153
- /* Find Api */
154
- switch( api.pathname ){
155
-
156
- case '/pop': return json( await pop(params) );
157
- case '/shift': return json( await shift(params) );
158
-
159
- case '/list': return json( await list(params) );
160
- case '/hash': return json( await hash(params) );
161
- case '/match': return json( await match(params) );
162
- case '/update': return json( await update(params) );
163
-
164
- case '/push': return json( await push(params) );
165
- case '/slice': return json( await splice(params) );
166
- case 'unshift': return json( await unshift(params) );
167
-
168
- case '/save': return json( await save(params) );
169
- case '/remove': return json( await remove(params) );
170
- case '/refresh': return json( await refresh(params) );
171
-
172
- case '/index': return json( await indexOf(params) );
173
- case '/length': return json( await lengthOf(params) );
174
-
175
- case '/addDB': return json( await addDB(params) );
176
- case '/removeDB': return json( await removeDB(params) );
177
- case '/addTable': return json( await addTable(params) );
178
- case '/removeTable':return json( await removeTable(params) );
179
-
180
- default: return error(parseError('Oops something went wrong'));
181
-
182
- }
183
-
184
- } catch(e) { error(parseError(e)); }
185
- })();
186
-
187
- /* --------------------------------------------------------------------------------------- */
@@ -1,158 +0,0 @@
1
- const crypto = require('crypto-js');
2
- const output = new Object();
3
-
4
- /* -------------------------------------------------------------------------------------------------------- */
5
-
6
- const JsonFormatter = {
7
-
8
- 'stringify': function(cipherParams) {
9
- var jsonObj = { ct: cipherParams.ciphertext.toString(crypto.enc.Base64) };
10
- if (cipherParams.salt) jsonObj.s = cipherParams.salt.toString();
11
- if (cipherParams.iv) jsonObj.iv = cipherParams.iv.toString();
12
- return new Buffer.from(JSON.stringify(jsonObj)).toString('base64');
13
- },
14
-
15
- 'parse': function(jsonStr) {
16
- var jsonObj = JSON.parse( new Buffer.from(jsonStr,'base64').toString());
17
- var cipherParams = crypto.lib.CipherParams.create({
18
- ciphertext: crypto.enc.Base64.parse(jsonObj.ct)
19
- });
20
- if (jsonObj.iv) cipherParams.iv = crypto.enc.Hex.parse(jsonObj.iv);
21
- if (jsonObj.s) cipherParams.salt = crypto.enc.Hex.parse(jsonObj.s);
22
- return cipherParams;
23
- }
24
-
25
- };
26
-
27
- /* --------------------------------------------------------------------------------------- */
28
-
29
- output.slugify = (str)=>{
30
- [
31
- ['c','ç'],
32
- ['n','ñ'],
33
- ['e','é|è|ê|ë'],
34
- ['i','í|ì|î|ï'],
35
- ['u','ú|ù|û|ü'],
36
- ['o','ó|ò|ô|õ|ö'],
37
- ['a','á|à|ã|â|ä'],
38
- ['' ,/\s+|\W+| /,]
39
- ].map(x=>{
40
- const regex = new RegExp(x[1],'gi');
41
- str = str.replace( regex,x[0] );
42
- }); return str.toLowerCase();
43
- }
44
-
45
- output.hash = (data,nonce)=>{
46
- return crypto.SHA256(Math.random+data+nonce).toString();
47
- }
48
-
49
- output.encrypt = ( _message,_password )=>{
50
- try{if( _password )
51
- return crypto.AES.encrypt( _message,_password,{
52
- format: JsonFormatter
53
- }).toString(); return _message;
54
- } catch(e) { return _message; }
55
- }
56
-
57
- output.decrypt = ( _message,_password )=>{
58
- try{if( _password )
59
- return crypto.AES.decrypt( _message,_password,{
60
- format: JsonFormatter
61
- }).toString( crypto.enc.Utf8 );
62
- return _message;
63
- } catch(e) { return _message; }
64
- }
65
-
66
- /* -------------------------------------------------------------------------------------------------------- */
67
-
68
- class State {
69
-
70
- state = new Object();
71
- events = new Array();
72
- update = new Array();
73
- active = true;
74
-
75
- constructor( state ){
76
- for( var i in state ){
77
- this.state[i] = state[i];
78
- }
79
- }
80
-
81
- set( state ){ let newState;
82
-
83
- const oldState = new Object();
84
- const keys = Object.keys(this.state);
85
- keys.map(x=>{ oldState[x]=this.state[x] });
86
-
87
- if( typeof state == 'function' ){
88
- newState = state( this.state ); const validator = [
89
- [!newState,'state is empty, please set a return state'],
90
- [typeof newState != 'object','state is not an object, please return a valid Object'],
91
- ]; if( validator.some(x=>{ if(x[0]) console.log(x[1]); return x[0] }) ) return 0;
92
- } else if( !state || typeof state != 'object' ) {
93
- return console.log('state is not an object, please return a valid Object')
94
- } else { newState = state; }
95
-
96
- this.active = this.shouldUpdate(null,[this.state,newState]);
97
- for( var i in newState ){ this.state[i] = newState[i];
98
- this.callback( i, oldState[i], newState[i] );
99
- }
100
-
101
- }
102
-
103
- get( item ){ return this.state[item] }
104
-
105
- shouldUpdate( callback,attr ){
106
- if( callback && typeof callback == 'function' )
107
- return this.update.push(callback);
108
- else if( callback && callback != 'function' )
109
- return console.log('callback should be a function');
110
- if( this.update.length == 0 ) return true;
111
- return this.update.some( x=>x(...attr) );
112
- }
113
-
114
- forceUpdate( item ){
115
- for( var i in this.events ){
116
- const field = this.events[i][0]
117
- this.events[i][1](
118
- this.state[field],
119
- this.state[field]
120
- );
121
- }
122
- }
123
-
124
- callback( item, prev, act ){
125
- if( !this.active ) return 0;
126
- for( var i in this.events ){
127
- if( this.events[i][0] == item )
128
- this.events[i][1]( prev,act );
129
- }
130
- }
131
-
132
- observeField( field,callback ){
133
- const id = this.eventID();
134
- const event = [field,callback,id];
135
- this.events.push(event); return id;
136
- }
137
-
138
- unObserveField( eventID ){
139
- for( var i in this.events ){
140
- if( this.events[i][2] == eventID ){
141
- this.events.splice(i,1);
142
- return true;
143
- }
144
- } return false;
145
- }
146
-
147
- eventID(){
148
- return crypto.SHA256(`
149
- ${Math.random()}
150
- ${Date.now()}
151
- `).toString();
152
- }
153
-
154
- }; output.state = State;
155
-
156
- /* -------------------------------------------------------------------------------------------------------- */
157
-
158
- module.exports = output;