-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.db.js
executable file
·2552 lines (2453 loc) · 69.5 KB
/
lib.db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/*
* lib.db.js (2019.8.20)
* https://github.com/kaizhu256/node-db-lite
* this zero-dependency package will provide a persistent, in-browser database, with a working web-demo
*
* browser example:
<script src="assets.db-lite.js"></script>
<script>
var dbTable1;
dbTable1 = window.dbTable1 = window.utility2_db.dbTableCreateOne({
name: "dbTable1"
});
dbTable1.idIndexCreate({ name: "field1" });
dbTable1.crudSetOneById({ field1: "hello", field2: "world" });
console.log(dbTable1.crudGetManyByQuery({
limit: Infinity,
query: { field1: "hello" },
skip: 0,
sort: [{ fieldName: 'field1', isDescending: false }]
}));
</script>
*
* node example:
var db, dbTable1;
utility2_db = require("./assets.db-lite.js");
dbTable1 = global.dbTable1 = utility2_db.dbTableCreateOne({
name: "dbTable1"
});
dbTable1.idIndexCreate({ name: "field1" });
dbTable1.crudSetOneById({ field1: "hello", field2: "world" });
console.log(dbTable1.crudGetManyByQuery({
limit: Infinity,
query: { field1: "hello" },
skip: 0,
sort: [{ fieldName: 'field1', isDescending: false }]
}));
*/
/* istanbul instrument in package db */
/* istanbul ignore next */
/* jslint utility2:true */
(function (globalThis) {
"use strict";
var consoleError;
var local;
// init globalThis
(function () {
try {
globalThis = Function("return this")(); // jslint ignore:line
} catch (ignore) {}
}());
globalThis.globalThis = globalThis;
// init debug_inline
if (!globalThis["debug\u0049nline"]) {
consoleError = console.error;
globalThis["debug\u0049nline"] = function () {
/*
* this function will both print <arguments> to stderr
* and return <arguments>[0]
*/
var argList;
argList = Array.from(arguments); // jslint ignore:line
// debug arguments
globalThis["debug\u0049nlineArguments"] = argList;
consoleError("\n\ndebug\u0049nline");
consoleError.apply(console, argList);
consoleError("\n");
// return arg0 for inspection
return argList[0];
};
}
// init local
local = {};
local.local = local;
globalThis.globalLocal = local;
// init isBrowser
local.isBrowser = (
typeof window === "object"
&& window === globalThis
&& typeof window.XMLHttpRequest === "function"
&& window.document
&& typeof window.document.querySelector === "function"
);
// init function
local.assertThrow = function (passed, message) {
/*
* this function will throw err.<message> if <passed> is falsy
*/
var err;
if (passed) {
return;
}
err = (
// ternary-operator
(
message
&& typeof message.message === "string"
&& typeof message.stack === "string"
)
// if message is errObj, then leave as is
? message
: new Error(
typeof message === "string"
// if message is a string, then leave as is
? message
// else JSON.stringify message
: JSON.stringify(message, null, 4)
)
);
throw err;
};
local.functionOrNop = function (fnc) {
/*
* this function will if <fnc> exists,
* them return <fnc>,
* else return <nop>
*/
return fnc || local.nop;
};
local.identity = function (value) {
/*
* this function will return <value>
*/
return value;
};
local.nop = function () {
/*
* this function will do nothing
*/
return;
};
local.objectAssignDefault = function (target, source) {
/*
* this function will if items from <target> are
* null, undefined, or empty-string,
* then overwrite them with items from <source>
*/
target = target || {};
Object.keys(source || {}).forEach(function (key) {
if (
target[key] === null
|| target[key] === undefined
|| target[key] === ""
) {
target[key] = target[key] || source[key];
}
});
return target;
};
// require builtin
if (!local.isBrowser) {
local.assert = require("assert");
local.buffer = require("buffer");
local.child_process = require("child_process");
local.cluster = require("cluster");
local.crypto = require("crypto");
local.dgram = require("dgram");
local.dns = require("dns");
local.domain = require("domain");
local.events = require("events");
local.fs = require("fs");
local.http = require("http");
local.https = require("https");
local.net = require("net");
local.os = require("os");
local.path = require("path");
local.querystring = require("querystring");
local.readline = require("readline");
local.repl = require("repl");
local.stream = require("stream");
local.string_decoder = require("string_decoder");
local.timers = require("timers");
local.tls = require("tls");
local.tty = require("tty");
local.url = require("url");
local.util = require("util");
local.vm = require("vm");
local.zlib = require("zlib");
}
}(this));
(function (local) {
"use strict";
/* istanbul ignore next */
// run shared js-env code - init-before
(function () {
// init local
local = (
globalThis.utility2_rollup
// || globalThis.utility2_rollup_old
// || require("./assets.utility2.rollup.js")
|| globalThis.globalLocal
);
// init exports
if (local.isBrowser) {
globalThis.utility2_db = local;
} else {
module.exports = local;
module.exports.__dirname = __dirname;
}
// init lib main
local.db = local;
/* validateLineSortedReset */
local.cliRun = function (opt) {
/*
* this function will run the cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict["--eval"] = local.cliDict["--eval"] || local.cliDict._eval;
local.cliDict["-e"] = local.cliDict["-e"] || local.cliDict._eval;
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
var commandList;
var file;
var packageJson;
var text;
var textDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
textDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
text = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
textDict[text] = textDict[text] || (ii + 2);
ii = textDict[text];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(text);
commandList[ii] = {
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
text = "";
text += packageJson.name + " (" + packageJson.version + ")\n\n";
text += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# "
+ elem.description
);
}
return (
elem.description + "\n " + file
+ (" " + elem.command.sort().join("|") + " ").replace((
/^\u0020{4}$/
), " ")
+ elem.argList.join(" ")
);
}).join("\n\n");
console.log(text);
};
local.cliDict["--help"] = local.cliDict["--help"] || local.cliDict._help;
local.cliDict["-h"] = local.cliDict["-h"] || local.cliDict._help;
local.cliDict._default = local.cliDict._default || local.cliDict._help;
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
local.cliDict["-i"] = local.cliDict["-i"] || local.cliDict._interactive;
local.cliDict._version = local.cliDict._version || function () {
/*
*
* will print version
*/
console.log(require(__dirname + "/package.json").version);
};
local.cliDict["--version"] = (
local.cliDict["--version"]
|| local.cliDict._version
);
local.cliDict["-v"] = local.cliDict["-v"] || local.cliDict._version;
// default to --help command if no arguments are given
if (process.argv.length <= 2) {
local.cliDict._help();
return;
}
if (local.cliDict[process.argv[2]]) {
local.cliDict[process.argv[2]]();
return;
}
local.cliDict._default();
};
local.jsonCopy = function (obj) {
/*
* this function will deep-copy obj
*/
return (
obj === undefined
? undefined
: JSON.parse(JSON.stringify(obj))
);
};
local.jsonStringifyOrdered = function (obj, replacer, space) {
/*
* this function will JSON.stringify <obj>,
* with object-keys sorted and circular-references removed
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax
*/
var circularSet;
var stringify;
var tmp;
stringify = function (obj) {
/*
* this function will recursively JSON.stringify obj,
* with object-keys sorted and circular-references removed
*/
// if obj is not an object or function, then JSON.stringify as normal
if (!(
obj
&& typeof obj === "object"
&& typeof obj.toJSON !== "function"
)) {
return JSON.stringify(obj);
}
// ignore circular-reference
if (circularSet.has(obj)) {
return;
}
circularSet.add(obj);
// if obj is an array, then recurse its items
if (Array.isArray(obj)) {
tmp = "[" + obj.map(function (obj) {
// recurse
tmp = stringify(obj);
return (
typeof tmp === "string"
? tmp
: "null"
);
}).join(",") + "]";
circularSet.delete(obj);
return tmp;
}
// if obj is not an array,
// then recurse its items with object-keys sorted
tmp = "{" + Object.keys(obj).sort().map(function (key) {
// recurse
tmp = stringify(obj[key]);
if (typeof tmp === "string") {
return JSON.stringify(key) + ":" + tmp;
}
}).filter(function (obj) {
return typeof obj === "string";
}).join(",") + "}";
circularSet.delete(obj);
return tmp;
};
circularSet = new Set();
return JSON.stringify((
(typeof obj === "object" && obj)
// recurse
? JSON.parse(stringify(obj))
: obj
), replacer, space);
};
local.listShuffle = function (list) {
/*
* this function will inplace shuffle <list> using fisher-yates algorithm
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
*/
var ii;
var random;
var swap;
ii = list.length;
while (ii > 1) {
ii -= 1;
random = Math.floor(Math.random() * (ii + 1));
swap = list[ii];
list[ii] = list[random];
list[random] = swap;
}
return list;
};
local.objectSetOverride = function (dict, overrides, depth, env) {
/*
* this function will recursively set overrides for items in dict
*/
dict = dict || {};
env = env || (typeof process === "object" && process.env) || {};
overrides = overrides || {};
Object.keys(overrides).forEach(function (key) {
var dict2;
var overrides2;
dict2 = dict[key];
overrides2 = overrides[key];
if (overrides2 === undefined) {
return;
}
// if both dict2 and overrides2 are non-null and non-array objects,
// then recurse with dict2 and overrides2
if (
depth > 1
// dict2 is a non-null and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// overrides2 is a non-null and non-array object
&& typeof overrides2 === "object" && overrides2
&& !Array.isArray(overrides2)
) {
local.objectSetOverride(dict2, overrides2, depth - 1, env);
return;
}
// else set dict[key] with overrides[key]
dict[key] = (
dict === env
// if dict is env, then overrides falsy-value with empty-string
? overrides2 || ""
: overrides2
);
});
return dict;
};
local.onErrorDefault = function (err) {
/*
* this function will if <err> exists, then print it to stderr
*/
if (err) {
console.error(err);
}
return err;
};
local.onErrorWithStack = function (onError) {
/*
* this function will create wrapper around <onError>
* that will append current-stack to err.stack
*/
var onError2;
var stack;
stack = new Error().stack.replace((
/(.*?)\n.*?$/m
), "$1");
onError2 = function (err, data, meta) {
// append current-stack to err.stack
if (
err
&& typeof err.stack === "string"
&& err !== local.errDefault
&& String(err.stack).indexOf(stack.split("\n")[2]) < 0
) {
err.stack += "\n" + stack;
}
onError(err, data, meta);
};
// debug onError
onError2.toString = function () {
return String(onError);
};
return onError2;
};
local.onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if counter === 0 or err occurred, then call onError(err)
*/
var onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement counter
onParallel.counter -= 1;
// validate counter
if (!(onParallel.counter >= 0 || err || onParallel.err)) {
err = new Error(
"invalid onParallel.counter = " + onParallel.counter
);
// ensure onError is run only once
} else if (onParallel.counter < 0) {
return;
}
// handle err
if (err) {
onParallel.err = err;
// ensure counter <= 0
onParallel.counter = -Math.abs(onParallel.counter);
}
// call onError when isDone
if (onParallel.counter <= 0) {
onError(err, data);
return;
}
onEach();
};
// init counter
onParallel.counter = 0;
// return callback
return onParallel;
};
local.replStart = function () {
/*
* this function will start the repl-debugger
*/
var that;
if (globalThis.utility2_repl1) {
return;
}
// start repl
that = require("repl").start({
useGlobal: true
});
globalThis.utility2_repl1 = that;
that.onError = function (err) {
/*
* this function will debug repl-err
*/
globalThis.utility2_debugReplError = err;
console.error(err);
};
// save eval-function
that.evalDefault = that.eval;
// hook custom-eval-function
that.eval = function (script, context, file, onError) {
var onError2;
onError2 = function (err, data) {
// debug err
globalThis.utility2_debugReplError = (
err || globalThis.utility2_debugReplError
);
onError(err, data);
};
script.replace((
/^(\S+)\u0020(.*?)\n/
), function (ignore, match1, match2) {
switch (match1) {
// syntax-sugar - run async shell-command
case "$":
switch (match2) {
// syntax-sugar - run git diff
case "git diff":
match2 = "git diff --color | cat";
break;
// syntax-sugar - run git log
case "git log":
match2 = "git log -n 4 | cat";
break;
// syntax-sugar - run git log
case "ll":
match2 = "ls -Fal";
break;
}
// source lib.utility2.sh
if (
process.platform !== "win32"
&& process.env.npm_config_dir_utility2 && (match2 !== ":")
) {
match2 = (
". " + process.env.npm_config_dir_utility2
+ "/lib.utility2.sh;" + match2
);
}
// run async shell-command
require("child_process").spawn(match2, {
shell: true,
stdio: [
"ignore", 1, 2
]
// on shell exit, print return prompt
}).on("exit", function (exitCode) {
console.error("exit-code " + exitCode);
that.evalDefault(
"\n",
context,
file,
onError2
);
});
script = "\n";
break;
// syntax-sugar - map text with charCodeAt
case "charCode":
console.error(
match2.split("").map(function (chr) {
return (
"\\u"
+ chr.charCodeAt(0).toString(16).padStart(4, 0)
);
}).join("")
);
script = "\n";
break;
// syntax-sugar - sort chr
case "charSort":
console.error(JSON.stringify(match2.split("").sort().join("")));
script = "\n";
break;
// syntax-sugar - grep current dir
case "grep":
// run async shell-command
require("child_process").spawn((
"find . -type f | grep -v -E "
/* jslint ignore:start */
+ '"\
/\\.|~\$|(\\b|_)(\\.\\d|\
archive|artifact|\
bower_component|build|\
coverage|\
doc|\
external|\
fixture|\
git_module|\
jquery|\
log|\
min|misc|mock|\
node_module|\
raw|\rollup|\
swp|\
tmp|\
vendor)s{0,1}(\\b|_)\
" '
/* jslint ignore:end */
+ "| tr \"\\n\" \"\\000\" | xargs -0 grep -HIin -E \""
+ match2 + "\""
), {
shell: true,
stdio: [
"ignore", 1, 2
]
// on shell exit, print return prompt
}).on("exit", function (exitCode) {
console.error("exit-code " + exitCode);
that.evalDefault(
"\n",
context,
file,
onError2
);
});
script = "\n";
break;
// syntax-sugar - list object's keys, sorted by item-type
// console.error(Object.keys(global).map(function(key){return(typeof global[key]==='object'&&global[key]&&global[key]===global[key]?'global':typeof global[key])+' '+key;}).sort().join('\n')) // jslint ignore:line
case "keys":
script = (
"console.error(Object.keys(" + match2
+ ").map(function(key){return("
+ "typeof " + match2 + "[key]==='object'&&"
+ match2 + "[key]&&"
+ match2 + "[key]===global[key]"
+ "?'global'"
+ ":typeof " + match2 + "[key]"
+ ")+' '+key;"
+ "}).sort().join('\\n'))\n"
);
break;
// syntax-sugar - print stringified arg
case "print":
script = "console.error(String(" + match2 + "))\n";
break;
// syntax-sugar - read file
case "readFile":
try {
console.error(JSON.stringify(
require("fs").readFileSync(match2, "utf8")
));
} catch (errCaught) {
console.error(errCaught);
}
script = "\n";
break;
}
});
// eval the script
that.evalDefault(script, context, file, onError2);
};
that.socket = {
end: local.nop,
on: local.nop,
write: local.nop
};
// init process.stdout
process.stdout._writeDefault = (
process.stdout._writeDefault
|| process.stdout._write
);
process.stdout._write = function (chunk, encoding, callback) {
process.stdout._writeDefault(chunk, encoding, callback);
// hack-istanbul - ignore else-statement
local.nop(that.socket.writable && (function () {
that.socket.write(chunk, encoding);
}()));
};
// start serverRepl1
globalThis.utility2_serverRepl1 = require("net").createServer(function (
socket
) {
// init socket
that.socket = socket;
that.socket.on("data", that.write.bind(that));
that.socket.on("error", that.onError);
that.socket.setKeepAlive(true);
});
// hack-istanbul - ignore else-statement
local.nop(process.env.PORT_REPL && (function () {
console.error(
"repl-server listening on port " + process.env.PORT_REPL
);
globalThis.utility2_serverRepl1.listen(process.env.PORT_REPL);
}()));
};
local.setTimeoutOnError = function (onError, timeout, err, data) {
/*
* this function will after timeout has passed,
* then call <onError>(<err>, <data>)
*/
if (typeof onError === "function") {
setTimeout(function () {
onError(err, data);
}, timeout);
}
return data;
};
}());
// run shared js-env code - lib.storage.js
(function (local) {
var child_process;
var clear;
var defer;
var deferList;
var fs;
var getItem;
var init;
var keys;
var length;
var os;
var removeItem;
var setItem;
var storage;
var storageDir;
storageDir = "tmp/storage." + (
local.isBrowser
? "undefined"
: process.env.NODE_ENV
);
if (!local.isBrowser) {
// require modules
child_process = require("child_process");
fs = require("fs");
os = require("os");
}
clear = function (onError) {
/*
* this function will clear storage
*/
defer({
action: "clear"
}, onError);
};
defer = function (opt, onError) {
/*
* this function will defer <opt>.action until storage is ready
*/
var data;
var isDone;
var objectStore;
var onError2;
var req;
var tmp;
onError = onError || function (err) {
// validate no err occurred
local.assertThrow(!err, err);
};
if (!storage) {
deferList.push(function () {
defer(opt, onError);
});
init();
return;
}
if (local.isBrowser) {
onError2 = function () {
/* istanbul ignore next */
if (isDone) {
return;
}
isDone = true;
onError(
req && (req.error || req.transaction.error),
data || req.result || ""
);
};
switch (opt.action) {
case "clear":
case "removeItem":
case "setItem":
objectStore = storage.transaction(
storageDir,
"readwrite"
).objectStore(storageDir);
break;
default:
objectStore = storage.transaction(
storageDir,
"readonly"
).objectStore(storageDir);
}
switch (opt.action) {
case "clear":
req = objectStore.clear();
break;
case "getItem":
req = objectStore.get(String(opt.key));
break;
case "keys":
data = [];
req = objectStore.openCursor();
req.onsuccess = function () {
if (!req.result) {
onError2();
return;
}
data.push(req.result.key);
req.result.continue();
};
break;
case "length":
req = objectStore.count();
break;
case "removeItem":
req = objectStore.delete(String(opt.key));
break;
case "setItem":
req = objectStore.put(opt.value, String(opt.key));
break;
}
[
"onabort", "onerror", "onsuccess"
].forEach(function (handler) {
req[handler] = req[handler] || onError2;
});
// debug req
local._debugStorageReq = req;
} else {
switch (opt.action) {
case "clear":
child_process.spawnSync("rm -f " + storage + "/*", {
shell: true,
stdio: [
"ignore", 1, 2
]
});
setTimeout(onError);
break;
case "getItem":
fs.readFile(
storage + "/" + encodeURIComponent(String(opt.key)),
"utf8",
function (ignore, data) {
onError(null, data || "");
}
);
break;
case "keys":
fs.readdir(storage, function (err, data) {
onError(err, data && data.map(decodeURIComponent));
});
break;
case "length":
fs.readdir(storage, function (err, data) {
onError(err, data && data.length);
});
break;
case "removeItem":
fs.unlink(
storage + "/" + encodeURIComponent(String(opt.key)),
// ignore err
function () {
onError();
}
);
break;
case "setItem":
tmp = os.tmpdir() + "/" + Date.now() + Math.random();
// save to tmp
fs.writeFile(tmp, opt.value, function (err) {
// validate no err occurred
local.assertThrow(!err, err);
// rename tmp to key
fs.rename(
tmp,
storage + "/" + encodeURIComponent(String(opt.key)),
onError
);
});
break;
}
}
};