@leofcoin/peernet 0.15.1 → 0.16.0

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.
@@ -1,3724 +0,0 @@
1
- (self["webpackChunk_leofcoin_peernet"] = self["webpackChunk_leofcoin_peernet"] || []).push([[851],{
2
-
3
- /***/ 110:
4
- /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
5
-
6
- __webpack_require__.r(__webpack_exports__);
7
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
8
- /* harmony export */ "default": function() { return /* binding */ LeofcoinStorage; }
9
- /* harmony export */ });
10
- /* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(764);
11
- /* harmony import */ var events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(187);
12
- /* harmony import */ var events__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(events__WEBPACK_IMPORTED_MODULE_1__);
13
- /* provided dependency */ var process = __webpack_require__(155);
14
-
15
-
16
-
17
- // import base32 from '@vandeurenglenn/base32'
18
- // import base58 from '@vandeurenglenn/base58'
19
-
20
- // export const encodings = {
21
- // base58,
22
- // base32
23
- // }
24
-
25
- const encode = (string, encoding = 'utf-8') => {
26
- if (typeof string === 'string') {
27
- let encoded;
28
-
29
- // if (encodings[encoding]) encoded = encodings[encoding].encode(encoded)
30
- encoded = new TextEncoder().encode(string);
31
- return encoded
32
- }
33
- throw Error(`expected typeof String instead got ${string}`)
34
- };
35
-
36
- const decode = (uint8Array, encoding) => {
37
- if (uint8Array instanceof Uint8Array) {
38
- let decoded;
39
- // if (encodings[encoding]) decoded = encodings[encoding].decode(decoded)
40
- decoded = new TextDecoder().decode(uint8Array);
41
-
42
- return decoded
43
- }
44
- throw Error(`expected typeof uint8Array instead got ${uint8Array}`)
45
- };
46
-
47
- const pathSepS = '/';
48
- class KeyPath {
49
-
50
- /**
51
- * @param {string | Uint8Array} input
52
- */
53
- constructor(input) {
54
- if (typeof input === 'string') {
55
- this.uint8Array = encode(input);
56
- } else if (input instanceof Uint8Array) {
57
- this.uint8Array = input;
58
- } else if (input instanceof KeyPath) {
59
- this.uint8Array = input.uint8Array;
60
- } else {
61
- throw new Error('Invalid keyPath, should be a String, Uint8Array or KeyPath')
62
- }
63
- }
64
-
65
- /**
66
- * Convert to the string representation
67
- *
68
- * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.
69
- * @returns {string}
70
- */
71
- toString (encoding = 'hex') {
72
- return decode(this.uint8Array)
73
- }
74
-
75
- /**
76
- * Returns the `list` representation of this path.
77
- *
78
- * @returns {Array<string>}
79
- *
80
- * @example
81
- * ```js
82
- * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()
83
- * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']
84
- * ```
85
- */
86
- list() {
87
- return this.toString().split(pathSepS).slice(1)
88
- }
89
-
90
- }
91
-
92
- class KeyValue {
93
-
94
- /**
95
- * @param {string | Uint8Array} input
96
- */
97
- constructor(input) {
98
- if (typeof input === 'string') {
99
- this.uint8Array = encode(input);
100
- } else if (input instanceof Uint8Array) {
101
- this.uint8Array = input;
102
- } else if (input instanceof KeyValue) {
103
- this.uint8Array = input.uint8Array;
104
- } else {
105
- throw new Error('Invalid KeyValue, should be a String, Uint8Array or KeyValue')
106
- }
107
- }
108
-
109
- /**
110
- * Convert to the string representation
111
- *
112
- * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.
113
- * @returns {string}
114
- */
115
- toString(encoding = 'utf8') {
116
- return decode(this.uint8Array)
117
- }
118
-
119
- }
120
-
121
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof self !== 'undefined' ? self : {};
122
-
123
- var abstractLevel$1 = {};
124
-
125
- var abstractLevel = {};
126
-
127
- var levelSupports = {};
128
-
129
- levelSupports.supports = function supports (...manifests) {
130
- const manifest = manifests.reduce((acc, m) => Object.assign(acc, m), {});
131
-
132
- return Object.assign(manifest, {
133
- snapshots: manifest.snapshots || false,
134
- permanence: manifest.permanence || false,
135
- seek: manifest.seek || false,
136
- clear: manifest.clear || false,
137
- getMany: manifest.getMany || false,
138
- keyIterator: manifest.keyIterator || false,
139
- valueIterator: manifest.valueIterator || false,
140
- iteratorNextv: manifest.iteratorNextv || false,
141
- iteratorAll: manifest.iteratorAll || false,
142
- status: manifest.status || false,
143
- createIfMissing: manifest.createIfMissing || false,
144
- errorIfExists: manifest.errorIfExists || false,
145
- deferredOpen: manifest.deferredOpen || false,
146
- promises: manifest.promises || false,
147
- streams: manifest.streams || false,
148
- encodings: Object.assign({}, manifest.encodings),
149
- events: Object.assign({}, manifest.events),
150
- additionalMethods: Object.assign({}, manifest.additionalMethods)
151
- })
152
- };
153
-
154
- var levelTranscoder = {};
155
-
156
- var moduleError = class ModuleError extends Error {
157
- /**
158
- * @param {string} message Error message
159
- * @param {{ code?: string, cause?: Error, expected?: boolean, transient?: boolean }} [options]
160
- */
161
- constructor (message, options) {
162
- super(message || '');
163
-
164
- if (typeof options === 'object' && options !== null) {
165
- if (options.code) this.code = String(options.code);
166
- if (options.expected) this.expected = true;
167
- if (options.transient) this.transient = true;
168
- if (options.cause) this.cause = options.cause;
169
- }
170
-
171
- if (Error.captureStackTrace) {
172
- Error.captureStackTrace(this, this.constructor);
173
- }
174
- }
175
- };
176
-
177
- var encodings$1 = {};
178
-
179
- /** @type {{ textEncoder: TextEncoder, textDecoder: TextDecoder }|null} */
180
- let lazy = null;
181
-
182
- /**
183
- * Get semi-global instances of TextEncoder and TextDecoder.
184
- * @returns {{ textEncoder: TextEncoder, textDecoder: TextDecoder }}
185
- */
186
- var textEndec$1 = function () {
187
- if (lazy === null) {
188
- lazy = {
189
- textEncoder: new TextEncoder(),
190
- textDecoder: new TextDecoder()
191
- };
192
- }
193
-
194
- return lazy
195
- };
196
-
197
- var formats$2 = {};
198
-
199
- var encoding = {};
200
-
201
- const ModuleError$8 = moduleError;
202
- const formats$1 = new Set(['buffer', 'view', 'utf8']);
203
-
204
- /**
205
- * @template TIn, TFormat, TOut
206
- * @abstract
207
- */
208
- class Encoding$2 {
209
- /**
210
- * @param {IEncoding<TIn,TFormat,TOut>} options
211
- */
212
- constructor (options) {
213
- /** @type {(data: TIn) => TFormat} */
214
- this.encode = options.encode || this.encode;
215
-
216
- /** @type {(data: TFormat) => TOut} */
217
- this.decode = options.decode || this.decode;
218
-
219
- /** @type {string} */
220
- this.name = options.name || this.name;
221
-
222
- /** @type {string} */
223
- this.format = options.format || this.format;
224
-
225
- if (typeof this.encode !== 'function') {
226
- throw new TypeError("The 'encode' property must be a function")
227
- }
228
-
229
- if (typeof this.decode !== 'function') {
230
- throw new TypeError("The 'decode' property must be a function")
231
- }
232
-
233
- this.encode = this.encode.bind(this);
234
- this.decode = this.decode.bind(this);
235
-
236
- if (typeof this.name !== 'string' || this.name === '') {
237
- throw new TypeError("The 'name' property must be a string")
238
- }
239
-
240
- if (typeof this.format !== 'string' || !formats$1.has(this.format)) {
241
- throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'")
242
- }
243
-
244
- if (options.createViewTranscoder) {
245
- this.createViewTranscoder = options.createViewTranscoder;
246
- }
247
-
248
- if (options.createBufferTranscoder) {
249
- this.createBufferTranscoder = options.createBufferTranscoder;
250
- }
251
-
252
- if (options.createUTF8Transcoder) {
253
- this.createUTF8Transcoder = options.createUTF8Transcoder;
254
- }
255
- }
256
-
257
- get commonName () {
258
- return /** @type {string} */ (this.name.split('+')[0])
259
- }
260
-
261
- /** @return {BufferFormat<TIn,TOut>} */
262
- createBufferTranscoder () {
263
- throw new ModuleError$8(`Encoding '${this.name}' cannot be transcoded to 'buffer'`, {
264
- code: 'LEVEL_ENCODING_NOT_SUPPORTED'
265
- })
266
- }
267
-
268
- /** @return {ViewFormat<TIn,TOut>} */
269
- createViewTranscoder () {
270
- throw new ModuleError$8(`Encoding '${this.name}' cannot be transcoded to 'view'`, {
271
- code: 'LEVEL_ENCODING_NOT_SUPPORTED'
272
- })
273
- }
274
-
275
- /** @return {UTF8Format<TIn,TOut>} */
276
- createUTF8Transcoder () {
277
- throw new ModuleError$8(`Encoding '${this.name}' cannot be transcoded to 'utf8'`, {
278
- code: 'LEVEL_ENCODING_NOT_SUPPORTED'
279
- })
280
- }
281
- }
282
-
283
- encoding.Encoding = Encoding$2;
284
-
285
- const { Buffer: Buffer$1 } = buffer__WEBPACK_IMPORTED_MODULE_0__ || {};
286
- const { Encoding: Encoding$1 } = encoding;
287
- const textEndec = textEndec$1;
288
-
289
- /**
290
- * @template TIn, TOut
291
- * @extends {Encoding<TIn,Buffer,TOut>}
292
- */
293
- class BufferFormat$2 extends Encoding$1 {
294
- /**
295
- * @param {Omit<IEncoding<TIn, Buffer, TOut>, 'format'>} options
296
- */
297
- constructor (options) {
298
- super({ ...options, format: 'buffer' });
299
- }
300
-
301
- /** @override */
302
- createViewTranscoder () {
303
- return new ViewFormat$2({
304
- encode: this.encode, // Buffer is a view (UInt8Array)
305
- decode: (data) => this.decode(
306
- Buffer$1.from(data.buffer, data.byteOffset, data.byteLength)
307
- ),
308
- name: `${this.name}+view`
309
- })
310
- }
311
-
312
- /** @override */
313
- createBufferTranscoder () {
314
- return this
315
- }
316
- }
317
-
318
- /**
319
- * @extends {Encoding<TIn,Uint8Array,TOut>}
320
- * @template TIn, TOut
321
- */
322
- class ViewFormat$2 extends Encoding$1 {
323
- /**
324
- * @param {Omit<IEncoding<TIn, Uint8Array, TOut>, 'format'>} options
325
- */
326
- constructor (options) {
327
- super({ ...options, format: 'view' });
328
- }
329
-
330
- /** @override */
331
- createBufferTranscoder () {
332
- return new BufferFormat$2({
333
- encode: (data) => {
334
- const view = this.encode(data);
335
- return Buffer$1.from(view.buffer, view.byteOffset, view.byteLength)
336
- },
337
- decode: this.decode, // Buffer is a view (UInt8Array)
338
- name: `${this.name}+buffer`
339
- })
340
- }
341
-
342
- /** @override */
343
- createViewTranscoder () {
344
- return this
345
- }
346
- }
347
-
348
- /**
349
- * @extends {Encoding<TIn,string,TOut>}
350
- * @template TIn, TOut
351
- */
352
- class UTF8Format$2 extends Encoding$1 {
353
- /**
354
- * @param {Omit<IEncoding<TIn, string, TOut>, 'format'>} options
355
- */
356
- constructor (options) {
357
- super({ ...options, format: 'utf8' });
358
- }
359
-
360
- /** @override */
361
- createBufferTranscoder () {
362
- return new BufferFormat$2({
363
- encode: (data) => Buffer$1.from(this.encode(data), 'utf8'),
364
- decode: (data) => this.decode(data.toString('utf8')),
365
- name: `${this.name}+buffer`
366
- })
367
- }
368
-
369
- /** @override */
370
- createViewTranscoder () {
371
- const { textEncoder, textDecoder } = textEndec();
372
-
373
- return new ViewFormat$2({
374
- encode: (data) => textEncoder.encode(this.encode(data)),
375
- decode: (data) => this.decode(textDecoder.decode(data)),
376
- name: `${this.name}+view`
377
- })
378
- }
379
-
380
- /** @override */
381
- createUTF8Transcoder () {
382
- return this
383
- }
384
- }
385
-
386
- formats$2.BufferFormat = BufferFormat$2;
387
- formats$2.ViewFormat = ViewFormat$2;
388
- formats$2.UTF8Format = UTF8Format$2;
389
-
390
- const { Buffer } = buffer__WEBPACK_IMPORTED_MODULE_0__ || { Buffer: { isBuffer: () => false } };
391
- const { textEncoder: textEncoder$1, textDecoder } = textEndec$1();
392
- const { BufferFormat: BufferFormat$1, ViewFormat: ViewFormat$1, UTF8Format: UTF8Format$1 } = formats$2;
393
-
394
- /** @type {<T>(v: T) => v} */
395
- const identity = (v) => v;
396
-
397
- /**
398
- * @type {typeof import('./encodings').utf8}
399
- */
400
- encodings$1.utf8 = new UTF8Format$1({
401
- encode: function (data) {
402
- // On node 16.9.1 buffer.toString() is 5x faster than TextDecoder
403
- return Buffer.isBuffer(data)
404
- ? data.toString('utf8')
405
- : ArrayBuffer.isView(data)
406
- ? textDecoder.decode(data)
407
- : String(data)
408
- },
409
- decode: identity,
410
- name: 'utf8',
411
- createViewTranscoder () {
412
- return new ViewFormat$1({
413
- encode: function (data) {
414
- return ArrayBuffer.isView(data) ? data : textEncoder$1.encode(data)
415
- },
416
- decode: function (data) {
417
- return textDecoder.decode(data)
418
- },
419
- name: `${this.name}+view`
420
- })
421
- },
422
- createBufferTranscoder () {
423
- return new BufferFormat$1({
424
- encode: function (data) {
425
- return Buffer.isBuffer(data)
426
- ? data
427
- : ArrayBuffer.isView(data)
428
- ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
429
- : Buffer.from(String(data), 'utf8')
430
- },
431
- decode: function (data) {
432
- return data.toString('utf8')
433
- },
434
- name: `${this.name}+buffer`
435
- })
436
- }
437
- });
438
-
439
- /**
440
- * @type {typeof import('./encodings').json}
441
- */
442
- encodings$1.json = new UTF8Format$1({
443
- encode: JSON.stringify,
444
- decode: JSON.parse,
445
- name: 'json'
446
- });
447
-
448
- /**
449
- * @type {typeof import('./encodings').buffer}
450
- */
451
- encodings$1.buffer = new BufferFormat$1({
452
- encode: function (data) {
453
- return Buffer.isBuffer(data)
454
- ? data
455
- : ArrayBuffer.isView(data)
456
- ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
457
- : Buffer.from(String(data), 'utf8')
458
- },
459
- decode: identity,
460
- name: 'buffer',
461
- createViewTranscoder () {
462
- return new ViewFormat$1({
463
- encode: function (data) {
464
- return ArrayBuffer.isView(data) ? data : Buffer.from(String(data), 'utf8')
465
- },
466
- decode: function (data) {
467
- return Buffer.from(data.buffer, data.byteOffset, data.byteLength)
468
- },
469
- name: `${this.name}+view`
470
- })
471
- }
472
- });
473
-
474
- /**
475
- * @type {typeof import('./encodings').view}
476
- */
477
- encodings$1.view = new ViewFormat$1({
478
- encode: function (data) {
479
- return ArrayBuffer.isView(data) ? data : textEncoder$1.encode(data)
480
- },
481
- decode: identity,
482
- name: 'view',
483
- createBufferTranscoder () {
484
- return new BufferFormat$1({
485
- encode: function (data) {
486
- return Buffer.isBuffer(data)
487
- ? data
488
- : ArrayBuffer.isView(data)
489
- ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
490
- : Buffer.from(String(data), 'utf8')
491
- },
492
- decode: identity,
493
- name: `${this.name}+buffer`
494
- })
495
- }
496
- });
497
-
498
- /**
499
- * @type {typeof import('./encodings').hex}
500
- */
501
- encodings$1.hex = new BufferFormat$1({
502
- encode: function (data) {
503
- return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'hex')
504
- },
505
- decode: function (buffer) {
506
- return buffer.toString('hex')
507
- },
508
- name: 'hex'
509
- });
510
-
511
- /**
512
- * @type {typeof import('./encodings').base64}
513
- */
514
- encodings$1.base64 = new BufferFormat$1({
515
- encode: function (data) {
516
- return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'base64')
517
- },
518
- decode: function (buffer) {
519
- return buffer.toString('base64')
520
- },
521
- name: 'base64'
522
- });
523
-
524
- const ModuleError$7 = moduleError;
525
- const encodings = encodings$1;
526
- const { Encoding } = encoding;
527
- const { BufferFormat, ViewFormat, UTF8Format } = formats$2;
528
-
529
- const kFormats = Symbol('formats');
530
- const kEncodings = Symbol('encodings');
531
- const validFormats = new Set(['buffer', 'view', 'utf8']);
532
-
533
- /** @template T */
534
- class Transcoder$1 {
535
- /**
536
- * @param {Array<'buffer'|'view'|'utf8'>} formats
537
- */
538
- constructor (formats) {
539
- if (!Array.isArray(formats)) {
540
- throw new TypeError("The first argument 'formats' must be an array")
541
- } else if (!formats.every(f => validFormats.has(f))) {
542
- // Note: we only only support aliases in key- and valueEncoding options (where we already did)
543
- throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")
544
- }
545
-
546
- /** @type {Map<string|MixedEncoding<any, any, any>, Encoding<any, any, any>>} */
547
- this[kEncodings] = new Map();
548
- this[kFormats] = new Set(formats);
549
-
550
- // Register encodings (done early in order to populate encodings())
551
- for (const k in encodings) {
552
- try {
553
- this.encoding(k);
554
- } catch (err) {
555
- /* istanbul ignore if: assertion */
556
- if (err.code !== 'LEVEL_ENCODING_NOT_SUPPORTED') throw err
557
- }
558
- }
559
- }
560
-
561
- /**
562
- * @returns {Array<Encoding<any,T,any>>}
563
- */
564
- encodings () {
565
- return Array.from(new Set(this[kEncodings].values()))
566
- }
567
-
568
- /**
569
- * @param {string|MixedEncoding<any, any, any>} encoding
570
- * @returns {Encoding<any, T, any>}
571
- */
572
- encoding (encoding) {
573
- let resolved = this[kEncodings].get(encoding);
574
-
575
- if (resolved === undefined) {
576
- if (typeof encoding === 'string' && encoding !== '') {
577
- resolved = lookup[encoding];
578
-
579
- if (!resolved) {
580
- throw new ModuleError$7(`Encoding '${encoding}' is not found`, {
581
- code: 'LEVEL_ENCODING_NOT_FOUND'
582
- })
583
- }
584
- } else if (typeof encoding !== 'object' || encoding === null) {
585
- throw new TypeError("First argument 'encoding' must be a string or object")
586
- } else {
587
- resolved = from(encoding);
588
- }
589
-
590
- const { name, format } = resolved;
591
-
592
- if (!this[kFormats].has(format)) {
593
- if (this[kFormats].has('view')) {
594
- resolved = resolved.createViewTranscoder();
595
- } else if (this[kFormats].has('buffer')) {
596
- resolved = resolved.createBufferTranscoder();
597
- } else if (this[kFormats].has('utf8')) {
598
- resolved = resolved.createUTF8Transcoder();
599
- } else {
600
- throw new ModuleError$7(`Encoding '${name}' cannot be transcoded`, {
601
- code: 'LEVEL_ENCODING_NOT_SUPPORTED'
602
- })
603
- }
604
- }
605
-
606
- for (const k of [encoding, name, resolved.name, resolved.commonName]) {
607
- this[kEncodings].set(k, resolved);
608
- }
609
- }
610
-
611
- return resolved
612
- }
613
- }
614
-
615
- levelTranscoder.Transcoder = Transcoder$1;
616
-
617
- /**
618
- * @param {MixedEncoding<any, any, any>} options
619
- * @returns {Encoding<any, any, any>}
620
- */
621
- function from (options) {
622
- if (options instanceof Encoding) {
623
- return options
624
- }
625
-
626
- // Loosely typed for ecosystem compatibility
627
- const maybeType = 'type' in options && typeof options.type === 'string' ? options.type : undefined;
628
- const name = options.name || maybeType || `anonymous-${anonymousCount++}`;
629
-
630
- switch (detectFormat(options)) {
631
- case 'view': return new ViewFormat({ ...options, name })
632
- case 'utf8': return new UTF8Format({ ...options, name })
633
- case 'buffer': return new BufferFormat({ ...options, name })
634
- default: {
635
- throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")
636
- }
637
- }
638
- }
639
-
640
- /**
641
- * If format is not provided, fallback to detecting `level-codec`
642
- * or `multiformats` encodings, else assume a format of buffer.
643
- * @param {MixedEncoding<any, any, any>} options
644
- * @returns {string}
645
- */
646
- function detectFormat (options) {
647
- if ('format' in options && options.format !== undefined) {
648
- return options.format
649
- } else if ('buffer' in options && typeof options.buffer === 'boolean') {
650
- return options.buffer ? 'buffer' : 'utf8' // level-codec
651
- } else if ('code' in options && Number.isInteger(options.code)) {
652
- return 'view' // multiformats
653
- } else {
654
- return 'buffer'
655
- }
656
- }
657
-
658
- /**
659
- * @typedef {import('./lib/encoding').MixedEncoding<TIn,TFormat,TOut>} MixedEncoding
660
- * @template TIn, TFormat, TOut
661
- */
662
-
663
- /**
664
- * @type {Object.<string, Encoding<any, any, any>>}
665
- */
666
- const aliases = {
667
- binary: encodings.buffer,
668
- 'utf-8': encodings.utf8
669
- };
670
-
671
- /**
672
- * @type {Object.<string, Encoding<any, any, any>>}
673
- */
674
- const lookup = {
675
- ...encodings,
676
- ...aliases
677
- };
678
-
679
- let anonymousCount = 0;
680
-
681
- var catering = {};
682
-
683
- var nextTick$2 = process.nextTick.bind(process);
684
-
685
- var nextTick$1 = nextTick$2;
686
-
687
- catering.fromCallback = function (callback, symbol) {
688
- if (callback === undefined) {
689
- var promise = new Promise(function (resolve, reject) {
690
- callback = function (err, res) {
691
- if (err) reject(err);
692
- else resolve(res);
693
- };
694
- });
695
-
696
- callback[symbol !== undefined ? symbol : 'promise'] = promise;
697
- } else if (typeof callback !== 'function') {
698
- throw new TypeError('Callback must be a function')
699
- }
700
-
701
- return callback
702
- };
703
-
704
- catering.fromPromise = function (promise, callback) {
705
- if (callback === undefined) return promise
706
-
707
- promise
708
- .then(function (res) { nextTick$1(() => callback(null, res)); })
709
- .catch(function (err) { nextTick$1(() => callback(err)); });
710
- };
711
-
712
- var abstractIterator = {};
713
-
714
- var common = {};
715
-
716
- common.getCallback = function (options, callback) {
717
- return typeof options === 'function' ? options : callback
718
- };
719
-
720
- common.getOptions = function (options, def) {
721
- if (typeof options === 'object' && options !== null) {
722
- return options
723
- }
724
-
725
- if (def !== undefined) {
726
- return def
727
- }
728
-
729
- return {}
730
- };
731
-
732
- const { fromCallback: fromCallback$3 } = catering;
733
- const ModuleError$6 = moduleError;
734
- const { getOptions: getOptions$2, getCallback: getCallback$2 } = common;
735
-
736
- const kPromise$3 = Symbol('promise');
737
- const kCallback$1 = Symbol('callback');
738
- const kWorking = Symbol('working');
739
- const kHandleOne$1 = Symbol('handleOne');
740
- const kHandleMany$1 = Symbol('handleMany');
741
- const kAutoClose = Symbol('autoClose');
742
- const kFinishWork = Symbol('finishWork');
743
- const kReturnMany = Symbol('returnMany');
744
- const kClosing = Symbol('closing');
745
- const kHandleClose = Symbol('handleClose');
746
- const kClosed = Symbol('closed');
747
- const kCloseCallbacks$1 = Symbol('closeCallbacks');
748
- const kKeyEncoding$1 = Symbol('keyEncoding');
749
- const kValueEncoding$1 = Symbol('valueEncoding');
750
- const kAbortOnClose = Symbol('abortOnClose');
751
- const kLegacy = Symbol('legacy');
752
- const kKeys = Symbol('keys');
753
- const kValues = Symbol('values');
754
- const kLimit = Symbol('limit');
755
- const kCount = Symbol('count');
756
-
757
- const emptyOptions$1 = Object.freeze({});
758
- const noop$1 = () => {};
759
- let warnedEnd = false;
760
-
761
- // This class is an internal utility for common functionality between AbstractIterator,
762
- // AbstractKeyIterator and AbstractValueIterator. It's not exported.
763
- class CommonIterator {
764
- constructor (db, options, legacy) {
765
- if (typeof db !== 'object' || db === null) {
766
- const hint = db === null ? 'null' : typeof db;
767
- throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)
768
- }
769
-
770
- if (typeof options !== 'object' || options === null) {
771
- throw new TypeError('The second argument must be an options object')
772
- }
773
-
774
- this[kClosed] = false;
775
- this[kCloseCallbacks$1] = [];
776
- this[kWorking] = false;
777
- this[kClosing] = false;
778
- this[kAutoClose] = false;
779
- this[kCallback$1] = null;
780
- this[kHandleOne$1] = this[kHandleOne$1].bind(this);
781
- this[kHandleMany$1] = this[kHandleMany$1].bind(this);
782
- this[kHandleClose] = this[kHandleClose].bind(this);
783
- this[kKeyEncoding$1] = options[kKeyEncoding$1];
784
- this[kValueEncoding$1] = options[kValueEncoding$1];
785
- this[kLegacy] = legacy;
786
- this[kLimit] = Number.isInteger(options.limit) && options.limit >= 0 ? options.limit : Infinity;
787
- this[kCount] = 0;
788
-
789
- // Undocumented option to abort pending work on close(). Used by the
790
- // many-level module as a temporary solution to a blocked close().
791
- // TODO (next major): consider making this the default behavior. Native
792
- // implementations should have their own logic to safely close iterators.
793
- this[kAbortOnClose] = !!options.abortOnClose;
794
-
795
- this.db = db;
796
- this.db.attachResource(this);
797
- this.nextTick = db.nextTick;
798
- }
799
-
800
- get count () {
801
- return this[kCount]
802
- }
803
-
804
- get limit () {
805
- return this[kLimit]
806
- }
807
-
808
- next (callback) {
809
- let promise;
810
-
811
- if (callback === undefined) {
812
- promise = new Promise((resolve, reject) => {
813
- callback = (err, key, value) => {
814
- if (err) reject(err);
815
- else if (!this[kLegacy]) resolve(key);
816
- else if (key === undefined && value === undefined) resolve();
817
- else resolve([key, value]);
818
- };
819
- });
820
- } else if (typeof callback !== 'function') {
821
- throw new TypeError('Callback must be a function')
822
- }
823
-
824
- if (this[kClosing]) {
825
- this.nextTick(callback, new ModuleError$6('Iterator is not open: cannot call next() after close()', {
826
- code: 'LEVEL_ITERATOR_NOT_OPEN'
827
- }));
828
- } else if (this[kWorking]) {
829
- this.nextTick(callback, new ModuleError$6('Iterator is busy: cannot call next() until previous call has completed', {
830
- code: 'LEVEL_ITERATOR_BUSY'
831
- }));
832
- } else {
833
- this[kWorking] = true;
834
- this[kCallback$1] = callback;
835
-
836
- if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleOne$1], null);
837
- else this._next(this[kHandleOne$1]);
838
- }
839
-
840
- return promise
841
- }
842
-
843
- _next (callback) {
844
- this.nextTick(callback);
845
- }
846
-
847
- nextv (size, options, callback) {
848
- callback = getCallback$2(options, callback);
849
- callback = fromCallback$3(callback, kPromise$3);
850
- options = getOptions$2(options, emptyOptions$1);
851
-
852
- if (!Number.isInteger(size)) {
853
- this.nextTick(callback, new TypeError("The first argument 'size' must be an integer"));
854
- return callback[kPromise$3]
855
- }
856
-
857
- if (this[kClosing]) {
858
- this.nextTick(callback, new ModuleError$6('Iterator is not open: cannot call nextv() after close()', {
859
- code: 'LEVEL_ITERATOR_NOT_OPEN'
860
- }));
861
- } else if (this[kWorking]) {
862
- this.nextTick(callback, new ModuleError$6('Iterator is busy: cannot call nextv() until previous call has completed', {
863
- code: 'LEVEL_ITERATOR_BUSY'
864
- }));
865
- } else {
866
- if (size < 1) size = 1;
867
- if (this[kLimit] < Infinity) size = Math.min(size, this[kLimit] - this[kCount]);
868
-
869
- this[kWorking] = true;
870
- this[kCallback$1] = callback;
871
-
872
- if (size <= 0) this.nextTick(this[kHandleMany$1], null, []);
873
- else this._nextv(size, options, this[kHandleMany$1]);
874
- }
875
-
876
- return callback[kPromise$3]
877
- }
878
-
879
- _nextv (size, options, callback) {
880
- const acc = [];
881
- const onnext = (err, key, value) => {
882
- if (err) {
883
- return callback(err)
884
- } else if (this[kLegacy] ? key === undefined && value === undefined : key === undefined) {
885
- return callback(null, acc)
886
- }
887
-
888
- acc.push(this[kLegacy] ? [key, value] : key);
889
-
890
- if (acc.length === size) {
891
- callback(null, acc);
892
- } else {
893
- this._next(onnext);
894
- }
895
- };
896
-
897
- this._next(onnext);
898
- }
899
-
900
- all (options, callback) {
901
- callback = getCallback$2(options, callback);
902
- callback = fromCallback$3(callback, kPromise$3);
903
- options = getOptions$2(options, emptyOptions$1);
904
-
905
- if (this[kClosing]) {
906
- this.nextTick(callback, new ModuleError$6('Iterator is not open: cannot call all() after close()', {
907
- code: 'LEVEL_ITERATOR_NOT_OPEN'
908
- }));
909
- } else if (this[kWorking]) {
910
- this.nextTick(callback, new ModuleError$6('Iterator is busy: cannot call all() until previous call has completed', {
911
- code: 'LEVEL_ITERATOR_BUSY'
912
- }));
913
- } else {
914
- this[kWorking] = true;
915
- this[kCallback$1] = callback;
916
- this[kAutoClose] = true;
917
-
918
- if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleMany$1], null, []);
919
- else this._all(options, this[kHandleMany$1]);
920
- }
921
-
922
- return callback[kPromise$3]
923
- }
924
-
925
- _all (options, callback) {
926
- // Must count here because we're directly calling _nextv()
927
- let count = this[kCount];
928
- const acc = [];
929
-
930
- const nextv = () => {
931
- // Not configurable, because implementations should optimize _all().
932
- const size = this[kLimit] < Infinity ? Math.min(1e3, this[kLimit] - count) : 1e3;
933
-
934
- if (size <= 0) {
935
- this.nextTick(callback, null, acc);
936
- } else {
937
- this._nextv(size, emptyOptions$1, onnextv);
938
- }
939
- };
940
-
941
- const onnextv = (err, items) => {
942
- if (err) {
943
- callback(err);
944
- } else if (items.length === 0) {
945
- callback(null, acc);
946
- } else {
947
- acc.push.apply(acc, items);
948
- count += items.length;
949
- nextv();
950
- }
951
- };
952
-
953
- nextv();
954
- }
955
-
956
- [kFinishWork] () {
957
- const cb = this[kCallback$1];
958
-
959
- // Callback will be null if work was aborted on close
960
- if (this[kAbortOnClose] && cb === null) return noop$1
961
-
962
- this[kWorking] = false;
963
- this[kCallback$1] = null;
964
-
965
- if (this[kClosing]) this._close(this[kHandleClose]);
966
-
967
- return cb
968
- }
969
-
970
- [kReturnMany] (cb, err, items) {
971
- if (this[kAutoClose]) {
972
- this.close(cb.bind(null, err, items));
973
- } else {
974
- cb(err, items);
975
- }
976
- }
977
-
978
- seek (target, options) {
979
- options = getOptions$2(options, emptyOptions$1);
980
-
981
- if (this[kClosing]) ; else if (this[kWorking]) {
982
- throw new ModuleError$6('Iterator is busy: cannot call seek() until next() has completed', {
983
- code: 'LEVEL_ITERATOR_BUSY'
984
- })
985
- } else {
986
- const keyEncoding = this.db.keyEncoding(options.keyEncoding || this[kKeyEncoding$1]);
987
- const keyFormat = keyEncoding.format;
988
-
989
- if (options.keyEncoding !== keyFormat) {
990
- options = { ...options, keyEncoding: keyFormat };
991
- }
992
-
993
- const mapped = this.db.prefixKey(keyEncoding.encode(target), keyFormat);
994
- this._seek(mapped, options);
995
- }
996
- }
997
-
998
- _seek (target, options) {
999
- throw new ModuleError$6('Iterator does not support seek()', {
1000
- code: 'LEVEL_NOT_SUPPORTED'
1001
- })
1002
- }
1003
-
1004
- close (callback) {
1005
- callback = fromCallback$3(callback, kPromise$3);
1006
-
1007
- if (this[kClosed]) {
1008
- this.nextTick(callback);
1009
- } else if (this[kClosing]) {
1010
- this[kCloseCallbacks$1].push(callback);
1011
- } else {
1012
- this[kClosing] = true;
1013
- this[kCloseCallbacks$1].push(callback);
1014
-
1015
- if (!this[kWorking]) {
1016
- this._close(this[kHandleClose]);
1017
- } else if (this[kAbortOnClose]) {
1018
- // Don't wait for work to finish. Subsequently ignore the result.
1019
- const cb = this[kFinishWork]();
1020
-
1021
- cb(new ModuleError$6('Aborted on iterator close()', {
1022
- code: 'LEVEL_ITERATOR_NOT_OPEN'
1023
- }));
1024
- }
1025
- }
1026
-
1027
- return callback[kPromise$3]
1028
- }
1029
-
1030
- _close (callback) {
1031
- this.nextTick(callback);
1032
- }
1033
-
1034
- [kHandleClose] () {
1035
- this[kClosed] = true;
1036
- this.db.detachResource(this);
1037
-
1038
- const callbacks = this[kCloseCallbacks$1];
1039
- this[kCloseCallbacks$1] = [];
1040
-
1041
- for (const cb of callbacks) {
1042
- cb();
1043
- }
1044
- }
1045
-
1046
- async * [Symbol.asyncIterator] () {
1047
- try {
1048
- let item;
1049
-
1050
- while ((item = (await this.next())) !== undefined) {
1051
- yield item;
1052
- }
1053
- } finally {
1054
- if (!this[kClosed]) await this.close();
1055
- }
1056
- }
1057
- }
1058
-
1059
- // For backwards compatibility this class is not (yet) called AbstractEntryIterator.
1060
- class AbstractIterator$3 extends CommonIterator {
1061
- constructor (db, options) {
1062
- super(db, options, true);
1063
- this[kKeys] = options.keys !== false;
1064
- this[kValues] = options.values !== false;
1065
- }
1066
-
1067
- [kHandleOne$1] (err, key, value) {
1068
- const cb = this[kFinishWork]();
1069
- if (err) return cb(err)
1070
-
1071
- try {
1072
- key = this[kKeys] && key !== undefined ? this[kKeyEncoding$1].decode(key) : undefined;
1073
- value = this[kValues] && value !== undefined ? this[kValueEncoding$1].decode(value) : undefined;
1074
- } catch (err) {
1075
- return cb(new IteratorDecodeError('entry', err))
1076
- }
1077
-
1078
- if (!(key === undefined && value === undefined)) {
1079
- this[kCount]++;
1080
- }
1081
-
1082
- cb(null, key, value);
1083
- }
1084
-
1085
- [kHandleMany$1] (err, entries) {
1086
- const cb = this[kFinishWork]();
1087
- if (err) return this[kReturnMany](cb, err)
1088
-
1089
- try {
1090
- for (const entry of entries) {
1091
- const key = entry[0];
1092
- const value = entry[1];
1093
-
1094
- entry[0] = this[kKeys] && key !== undefined ? this[kKeyEncoding$1].decode(key) : undefined;
1095
- entry[1] = this[kValues] && value !== undefined ? this[kValueEncoding$1].decode(value) : undefined;
1096
- }
1097
- } catch (err) {
1098
- return this[kReturnMany](cb, new IteratorDecodeError('entries', err))
1099
- }
1100
-
1101
- this[kCount] += entries.length;
1102
- this[kReturnMany](cb, null, entries);
1103
- }
1104
-
1105
- end (callback) {
1106
- if (!warnedEnd && typeof console !== 'undefined') {
1107
- warnedEnd = true;
1108
- console.warn(new ModuleError$6(
1109
- 'The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version',
1110
- { code: 'LEVEL_LEGACY' }
1111
- ));
1112
- }
1113
-
1114
- return this.close(callback)
1115
- }
1116
- }
1117
-
1118
- class AbstractKeyIterator$2 extends CommonIterator {
1119
- constructor (db, options) {
1120
- super(db, options, false);
1121
- }
1122
-
1123
- [kHandleOne$1] (err, key) {
1124
- const cb = this[kFinishWork]();
1125
- if (err) return cb(err)
1126
-
1127
- try {
1128
- key = key !== undefined ? this[kKeyEncoding$1].decode(key) : undefined;
1129
- } catch (err) {
1130
- return cb(new IteratorDecodeError('key', err))
1131
- }
1132
-
1133
- if (key !== undefined) this[kCount]++;
1134
- cb(null, key);
1135
- }
1136
-
1137
- [kHandleMany$1] (err, keys) {
1138
- const cb = this[kFinishWork]();
1139
- if (err) return this[kReturnMany](cb, err)
1140
-
1141
- try {
1142
- for (let i = 0; i < keys.length; i++) {
1143
- const key = keys[i];
1144
- keys[i] = key !== undefined ? this[kKeyEncoding$1].decode(key) : undefined;
1145
- }
1146
- } catch (err) {
1147
- return this[kReturnMany](cb, new IteratorDecodeError('keys', err))
1148
- }
1149
-
1150
- this[kCount] += keys.length;
1151
- this[kReturnMany](cb, null, keys);
1152
- }
1153
- }
1154
-
1155
- class AbstractValueIterator$2 extends CommonIterator {
1156
- constructor (db, options) {
1157
- super(db, options, false);
1158
- }
1159
-
1160
- [kHandleOne$1] (err, value) {
1161
- const cb = this[kFinishWork]();
1162
- if (err) return cb(err)
1163
-
1164
- try {
1165
- value = value !== undefined ? this[kValueEncoding$1].decode(value) : undefined;
1166
- } catch (err) {
1167
- return cb(new IteratorDecodeError('value', err))
1168
- }
1169
-
1170
- if (value !== undefined) this[kCount]++;
1171
- cb(null, value);
1172
- }
1173
-
1174
- [kHandleMany$1] (err, values) {
1175
- const cb = this[kFinishWork]();
1176
- if (err) return this[kReturnMany](cb, err)
1177
-
1178
- try {
1179
- for (let i = 0; i < values.length; i++) {
1180
- const value = values[i];
1181
- values[i] = value !== undefined ? this[kValueEncoding$1].decode(value) : undefined;
1182
- }
1183
- } catch (err) {
1184
- return this[kReturnMany](cb, new IteratorDecodeError('values', err))
1185
- }
1186
-
1187
- this[kCount] += values.length;
1188
- this[kReturnMany](cb, null, values);
1189
- }
1190
- }
1191
-
1192
- // Internal utility, not typed or exported
1193
- class IteratorDecodeError extends ModuleError$6 {
1194
- constructor (subject, cause) {
1195
- super(`Iterator could not decode ${subject}`, {
1196
- code: 'LEVEL_DECODE_ERROR',
1197
- cause
1198
- });
1199
- }
1200
- }
1201
-
1202
- // To help migrating to abstract-level
1203
- for (const k of ['_ended property', '_nexting property', '_end method']) {
1204
- Object.defineProperty(AbstractIterator$3.prototype, k.split(' ')[0], {
1205
- get () { throw new ModuleError$6(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) },
1206
- set () { throw new ModuleError$6(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) }
1207
- });
1208
- }
1209
-
1210
- // Exposed so that AbstractLevel can set these options
1211
- AbstractIterator$3.keyEncoding = kKeyEncoding$1;
1212
- AbstractIterator$3.valueEncoding = kValueEncoding$1;
1213
-
1214
- abstractIterator.AbstractIterator = AbstractIterator$3;
1215
- abstractIterator.AbstractKeyIterator = AbstractKeyIterator$2;
1216
- abstractIterator.AbstractValueIterator = AbstractValueIterator$2;
1217
-
1218
- var defaultKvIterator = {};
1219
-
1220
- const { AbstractKeyIterator: AbstractKeyIterator$1, AbstractValueIterator: AbstractValueIterator$1 } = abstractIterator;
1221
-
1222
- const kIterator = Symbol('iterator');
1223
- const kCallback = Symbol('callback');
1224
- const kHandleOne = Symbol('handleOne');
1225
- const kHandleMany = Symbol('handleMany');
1226
-
1227
- class DefaultKeyIterator$1 extends AbstractKeyIterator$1 {
1228
- constructor (db, options) {
1229
- super(db, options);
1230
-
1231
- this[kIterator] = db.iterator({ ...options, keys: true, values: false });
1232
- this[kHandleOne] = this[kHandleOne].bind(this);
1233
- this[kHandleMany] = this[kHandleMany].bind(this);
1234
- }
1235
- }
1236
-
1237
- class DefaultValueIterator$1 extends AbstractValueIterator$1 {
1238
- constructor (db, options) {
1239
- super(db, options);
1240
-
1241
- this[kIterator] = db.iterator({ ...options, keys: false, values: true });
1242
- this[kHandleOne] = this[kHandleOne].bind(this);
1243
- this[kHandleMany] = this[kHandleMany].bind(this);
1244
- }
1245
- }
1246
-
1247
- for (const Iterator of [DefaultKeyIterator$1, DefaultValueIterator$1]) {
1248
- const keys = Iterator === DefaultKeyIterator$1;
1249
- const mapEntry = keys ? (entry) => entry[0] : (entry) => entry[1];
1250
-
1251
- Iterator.prototype._next = function (callback) {
1252
- this[kCallback] = callback;
1253
- this[kIterator].next(this[kHandleOne]);
1254
- };
1255
-
1256
- Iterator.prototype[kHandleOne] = function (err, key, value) {
1257
- const callback = this[kCallback];
1258
- if (err) callback(err);
1259
- else callback(null, keys ? key : value);
1260
- };
1261
-
1262
- Iterator.prototype._nextv = function (size, options, callback) {
1263
- this[kCallback] = callback;
1264
- this[kIterator].nextv(size, options, this[kHandleMany]);
1265
- };
1266
-
1267
- Iterator.prototype._all = function (options, callback) {
1268
- this[kCallback] = callback;
1269
- this[kIterator].all(options, this[kHandleMany]);
1270
- };
1271
-
1272
- Iterator.prototype[kHandleMany] = function (err, entries) {
1273
- const callback = this[kCallback];
1274
- if (err) callback(err);
1275
- else callback(null, entries.map(mapEntry));
1276
- };
1277
-
1278
- Iterator.prototype._seek = function (target, options) {
1279
- this[kIterator].seek(target, options);
1280
- };
1281
-
1282
- Iterator.prototype._close = function (callback) {
1283
- this[kIterator].close(callback);
1284
- };
1285
- }
1286
-
1287
- // Internal utilities, should be typed as AbstractKeyIterator and AbstractValueIterator
1288
- defaultKvIterator.DefaultKeyIterator = DefaultKeyIterator$1;
1289
- defaultKvIterator.DefaultValueIterator = DefaultValueIterator$1;
1290
-
1291
- var deferredIterator = {};
1292
-
1293
- const { AbstractIterator: AbstractIterator$2, AbstractKeyIterator, AbstractValueIterator } = abstractIterator;
1294
- const ModuleError$5 = moduleError;
1295
-
1296
- const kNut = Symbol('nut');
1297
- const kUndefer$1 = Symbol('undefer');
1298
- const kFactory = Symbol('factory');
1299
-
1300
- class DeferredIterator$1 extends AbstractIterator$2 {
1301
- constructor (db, options) {
1302
- super(db, options);
1303
-
1304
- this[kNut] = null;
1305
- this[kFactory] = () => db.iterator(options);
1306
-
1307
- this.db.defer(() => this[kUndefer$1]());
1308
- }
1309
- }
1310
-
1311
- class DeferredKeyIterator$1 extends AbstractKeyIterator {
1312
- constructor (db, options) {
1313
- super(db, options);
1314
-
1315
- this[kNut] = null;
1316
- this[kFactory] = () => db.keys(options);
1317
-
1318
- this.db.defer(() => this[kUndefer$1]());
1319
- }
1320
- }
1321
-
1322
- class DeferredValueIterator$1 extends AbstractValueIterator {
1323
- constructor (db, options) {
1324
- super(db, options);
1325
-
1326
- this[kNut] = null;
1327
- this[kFactory] = () => db.values(options);
1328
-
1329
- this.db.defer(() => this[kUndefer$1]());
1330
- }
1331
- }
1332
-
1333
- for (const Iterator of [DeferredIterator$1, DeferredKeyIterator$1, DeferredValueIterator$1]) {
1334
- Iterator.prototype[kUndefer$1] = function () {
1335
- if (this.db.status === 'open') {
1336
- this[kNut] = this[kFactory]();
1337
- }
1338
- };
1339
-
1340
- Iterator.prototype._next = function (callback) {
1341
- if (this[kNut] !== null) {
1342
- this[kNut].next(callback);
1343
- } else if (this.db.status === 'opening') {
1344
- this.db.defer(() => this._next(callback));
1345
- } else {
1346
- this.nextTick(callback, new ModuleError$5('Iterator is not open: cannot call next() after close()', {
1347
- code: 'LEVEL_ITERATOR_NOT_OPEN'
1348
- }));
1349
- }
1350
- };
1351
-
1352
- Iterator.prototype._nextv = function (size, options, callback) {
1353
- if (this[kNut] !== null) {
1354
- this[kNut].nextv(size, options, callback);
1355
- } else if (this.db.status === 'opening') {
1356
- this.db.defer(() => this._nextv(size, options, callback));
1357
- } else {
1358
- this.nextTick(callback, new ModuleError$5('Iterator is not open: cannot call nextv() after close()', {
1359
- code: 'LEVEL_ITERATOR_NOT_OPEN'
1360
- }));
1361
- }
1362
- };
1363
-
1364
- Iterator.prototype._all = function (options, callback) {
1365
- if (this[kNut] !== null) {
1366
- this[kNut].all(callback);
1367
- } else if (this.db.status === 'opening') {
1368
- this.db.defer(() => this._all(options, callback));
1369
- } else {
1370
- this.nextTick(callback, new ModuleError$5('Iterator is not open: cannot call all() after close()', {
1371
- code: 'LEVEL_ITERATOR_NOT_OPEN'
1372
- }));
1373
- }
1374
- };
1375
-
1376
- Iterator.prototype._seek = function (target, options) {
1377
- if (this[kNut] !== null) {
1378
- // TODO: explain why we need _seek() rather than seek() here
1379
- this[kNut]._seek(target, options);
1380
- } else if (this.db.status === 'opening') {
1381
- this.db.defer(() => this._seek(target, options));
1382
- }
1383
- };
1384
-
1385
- Iterator.prototype._close = function (callback) {
1386
- if (this[kNut] !== null) {
1387
- this[kNut].close(callback);
1388
- } else if (this.db.status === 'opening') {
1389
- this.db.defer(() => this._close(callback));
1390
- } else {
1391
- this.nextTick(callback);
1392
- }
1393
- };
1394
- }
1395
-
1396
- deferredIterator.DeferredIterator = DeferredIterator$1;
1397
- deferredIterator.DeferredKeyIterator = DeferredKeyIterator$1;
1398
- deferredIterator.DeferredValueIterator = DeferredValueIterator$1;
1399
-
1400
- var defaultChainedBatch = {};
1401
-
1402
- var abstractChainedBatch = {};
1403
-
1404
- const { fromCallback: fromCallback$2 } = catering;
1405
- const ModuleError$4 = moduleError;
1406
- const { getCallback: getCallback$1, getOptions: getOptions$1 } = common;
1407
-
1408
- const kPromise$2 = Symbol('promise');
1409
- const kStatus$1 = Symbol('status');
1410
- const kOperations$1 = Symbol('operations');
1411
- const kFinishClose = Symbol('finishClose');
1412
- const kCloseCallbacks = Symbol('closeCallbacks');
1413
-
1414
- class AbstractChainedBatch$1 {
1415
- constructor (db) {
1416
- if (typeof db !== 'object' || db === null) {
1417
- const hint = db === null ? 'null' : typeof db;
1418
- throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)
1419
- }
1420
-
1421
- this[kOperations$1] = [];
1422
- this[kCloseCallbacks] = [];
1423
- this[kStatus$1] = 'open';
1424
- this[kFinishClose] = this[kFinishClose].bind(this);
1425
-
1426
- this.db = db;
1427
- this.db.attachResource(this);
1428
- this.nextTick = db.nextTick;
1429
- }
1430
-
1431
- get length () {
1432
- return this[kOperations$1].length
1433
- }
1434
-
1435
- put (key, value, options) {
1436
- if (this[kStatus$1] !== 'open') {
1437
- throw new ModuleError$4('Batch is not open: cannot call put() after write() or close()', {
1438
- code: 'LEVEL_BATCH_NOT_OPEN'
1439
- })
1440
- }
1441
-
1442
- const err = this.db._checkKey(key) || this.db._checkValue(value);
1443
- if (err) throw err
1444
-
1445
- const db = options && options.sublevel != null ? options.sublevel : this.db;
1446
- const original = options;
1447
- const keyEncoding = db.keyEncoding(options && options.keyEncoding);
1448
- const valueEncoding = db.valueEncoding(options && options.valueEncoding);
1449
- const keyFormat = keyEncoding.format;
1450
-
1451
- // Forward encoding options
1452
- options = { ...options, keyEncoding: keyFormat, valueEncoding: valueEncoding.format };
1453
-
1454
- // Prevent double prefixing
1455
- if (db !== this.db) {
1456
- options.sublevel = null;
1457
- }
1458
-
1459
- const mappedKey = db.prefixKey(keyEncoding.encode(key), keyFormat);
1460
- const mappedValue = valueEncoding.encode(value);
1461
-
1462
- this._put(mappedKey, mappedValue, options);
1463
- this[kOperations$1].push({ ...original, type: 'put', key, value });
1464
-
1465
- return this
1466
- }
1467
-
1468
- _put (key, value, options) {}
1469
-
1470
- del (key, options) {
1471
- if (this[kStatus$1] !== 'open') {
1472
- throw new ModuleError$4('Batch is not open: cannot call del() after write() or close()', {
1473
- code: 'LEVEL_BATCH_NOT_OPEN'
1474
- })
1475
- }
1476
-
1477
- const err = this.db._checkKey(key);
1478
- if (err) throw err
1479
-
1480
- const db = options && options.sublevel != null ? options.sublevel : this.db;
1481
- const original = options;
1482
- const keyEncoding = db.keyEncoding(options && options.keyEncoding);
1483
- const keyFormat = keyEncoding.format;
1484
-
1485
- // Forward encoding options
1486
- options = { ...options, keyEncoding: keyFormat };
1487
-
1488
- // Prevent double prefixing
1489
- if (db !== this.db) {
1490
- options.sublevel = null;
1491
- }
1492
-
1493
- this._del(db.prefixKey(keyEncoding.encode(key), keyFormat), options);
1494
- this[kOperations$1].push({ ...original, type: 'del', key });
1495
-
1496
- return this
1497
- }
1498
-
1499
- _del (key, options) {}
1500
-
1501
- clear () {
1502
- if (this[kStatus$1] !== 'open') {
1503
- throw new ModuleError$4('Batch is not open: cannot call clear() after write() or close()', {
1504
- code: 'LEVEL_BATCH_NOT_OPEN'
1505
- })
1506
- }
1507
-
1508
- this._clear();
1509
- this[kOperations$1] = [];
1510
-
1511
- return this
1512
- }
1513
-
1514
- _clear () {}
1515
-
1516
- write (options, callback) {
1517
- callback = getCallback$1(options, callback);
1518
- callback = fromCallback$2(callback, kPromise$2);
1519
- options = getOptions$1(options);
1520
-
1521
- if (this[kStatus$1] !== 'open') {
1522
- this.nextTick(callback, new ModuleError$4('Batch is not open: cannot call write() after write() or close()', {
1523
- code: 'LEVEL_BATCH_NOT_OPEN'
1524
- }));
1525
- } else if (this.length === 0) {
1526
- this.close(callback);
1527
- } else {
1528
- this[kStatus$1] = 'writing';
1529
- this._write(options, (err) => {
1530
- this[kStatus$1] = 'closing';
1531
- this[kCloseCallbacks].push(() => callback(err));
1532
-
1533
- // Emit after setting 'closing' status, because event may trigger a
1534
- // db close which in turn triggers (idempotently) closing this batch.
1535
- if (!err) this.db.emit('batch', this[kOperations$1]);
1536
-
1537
- this._close(this[kFinishClose]);
1538
- });
1539
- }
1540
-
1541
- return callback[kPromise$2]
1542
- }
1543
-
1544
- _write (options, callback) {}
1545
-
1546
- close (callback) {
1547
- callback = fromCallback$2(callback, kPromise$2);
1548
-
1549
- if (this[kStatus$1] === 'closing') {
1550
- this[kCloseCallbacks].push(callback);
1551
- } else if (this[kStatus$1] === 'closed') {
1552
- this.nextTick(callback);
1553
- } else {
1554
- this[kCloseCallbacks].push(callback);
1555
-
1556
- if (this[kStatus$1] !== 'writing') {
1557
- this[kStatus$1] = 'closing';
1558
- this._close(this[kFinishClose]);
1559
- }
1560
- }
1561
-
1562
- return callback[kPromise$2]
1563
- }
1564
-
1565
- _close (callback) {
1566
- this.nextTick(callback);
1567
- }
1568
-
1569
- [kFinishClose] () {
1570
- this[kStatus$1] = 'closed';
1571
- this.db.detachResource(this);
1572
-
1573
- const callbacks = this[kCloseCallbacks];
1574
- this[kCloseCallbacks] = [];
1575
-
1576
- for (const cb of callbacks) {
1577
- cb();
1578
- }
1579
- }
1580
- }
1581
-
1582
- abstractChainedBatch.AbstractChainedBatch = AbstractChainedBatch$1;
1583
-
1584
- const { AbstractChainedBatch } = abstractChainedBatch;
1585
- const ModuleError$3 = moduleError;
1586
- const kEncoded = Symbol('encoded');
1587
-
1588
- // Functional default for chained batch, with support of deferred open
1589
- class DefaultChainedBatch$1 extends AbstractChainedBatch {
1590
- constructor (db) {
1591
- super(db);
1592
- this[kEncoded] = [];
1593
- }
1594
-
1595
- _put (key, value, options) {
1596
- this[kEncoded].push({ ...options, type: 'put', key, value });
1597
- }
1598
-
1599
- _del (key, options) {
1600
- this[kEncoded].push({ ...options, type: 'del', key });
1601
- }
1602
-
1603
- _clear () {
1604
- this[kEncoded] = [];
1605
- }
1606
-
1607
- // Assumes this[kEncoded] cannot change after write()
1608
- _write (options, callback) {
1609
- if (this.db.status === 'opening') {
1610
- this.db.defer(() => this._write(options, callback));
1611
- } else if (this.db.status === 'open') {
1612
- if (this[kEncoded].length === 0) this.nextTick(callback);
1613
- else this.db._batch(this[kEncoded], options, callback);
1614
- } else {
1615
- this.nextTick(callback, new ModuleError$3('Batch is not open: cannot call write() after write() or close()', {
1616
- code: 'LEVEL_BATCH_NOT_OPEN'
1617
- }));
1618
- }
1619
- }
1620
- }
1621
-
1622
- defaultChainedBatch.DefaultChainedBatch = DefaultChainedBatch$1;
1623
-
1624
- const ModuleError$2 = moduleError;
1625
- const hasOwnProperty = Object.prototype.hasOwnProperty;
1626
- const rangeOptions$1 = new Set(['lt', 'lte', 'gt', 'gte']);
1627
-
1628
- var rangeOptions_1 = function (options, keyEncoding) {
1629
- const result = {};
1630
-
1631
- for (const k in options) {
1632
- if (!hasOwnProperty.call(options, k)) continue
1633
- if (k === 'keyEncoding' || k === 'valueEncoding') continue
1634
-
1635
- if (k === 'start' || k === 'end') {
1636
- throw new ModuleError$2(`The legacy range option '${k}' has been removed`, {
1637
- code: 'LEVEL_LEGACY'
1638
- })
1639
- } else if (k === 'encoding') {
1640
- // To help migrating to abstract-level
1641
- throw new ModuleError$2("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead", {
1642
- code: 'LEVEL_LEGACY'
1643
- })
1644
- }
1645
-
1646
- if (rangeOptions$1.has(k)) {
1647
- // Note that we don't reject nullish and empty options here. While
1648
- // those types are invalid as keys, they are valid as range options.
1649
- result[k] = keyEncoding.encode(options[k]);
1650
- } else {
1651
- result[k] = options[k];
1652
- }
1653
- }
1654
-
1655
- result.reverse = !!result.reverse;
1656
- result.limit = Number.isInteger(result.limit) && result.limit >= 0 ? result.limit : -1;
1657
-
1658
- return result
1659
- };
1660
-
1661
- var nextTick;
1662
- var hasRequiredNextTick;
1663
-
1664
- function requireNextTick () {
1665
- if (hasRequiredNextTick) return nextTick;
1666
- hasRequiredNextTick = 1;
1667
-
1668
- nextTick = process.nextTick;
1669
- return nextTick;
1670
- }
1671
-
1672
- var abstractSublevelIterator = {};
1673
-
1674
- var hasRequiredAbstractSublevelIterator;
1675
-
1676
- function requireAbstractSublevelIterator () {
1677
- if (hasRequiredAbstractSublevelIterator) return abstractSublevelIterator;
1678
- hasRequiredAbstractSublevelIterator = 1;
1679
-
1680
- const { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = abstractIterator;
1681
-
1682
- const kUnfix = Symbol('unfix');
1683
- const kIterator = Symbol('iterator');
1684
- const kHandleOne = Symbol('handleOne');
1685
- const kHandleMany = Symbol('handleMany');
1686
- const kCallback = Symbol('callback');
1687
-
1688
- // TODO: unfix natively if db supports it
1689
- class AbstractSublevelIterator extends AbstractIterator {
1690
- constructor (db, options, iterator, unfix) {
1691
- super(db, options);
1692
-
1693
- this[kIterator] = iterator;
1694
- this[kUnfix] = unfix;
1695
- this[kHandleOne] = this[kHandleOne].bind(this);
1696
- this[kHandleMany] = this[kHandleMany].bind(this);
1697
- this[kCallback] = null;
1698
- }
1699
-
1700
- [kHandleOne] (err, key, value) {
1701
- const callback = this[kCallback];
1702
- if (err) return callback(err)
1703
- if (key !== undefined) key = this[kUnfix](key);
1704
- callback(err, key, value);
1705
- }
1706
-
1707
- [kHandleMany] (err, entries) {
1708
- const callback = this[kCallback];
1709
- if (err) return callback(err)
1710
-
1711
- for (const entry of entries) {
1712
- const key = entry[0];
1713
- if (key !== undefined) entry[0] = this[kUnfix](key);
1714
- }
1715
-
1716
- callback(err, entries);
1717
- }
1718
- }
1719
-
1720
- class AbstractSublevelKeyIterator extends AbstractKeyIterator {
1721
- constructor (db, options, iterator, unfix) {
1722
- super(db, options);
1723
-
1724
- this[kIterator] = iterator;
1725
- this[kUnfix] = unfix;
1726
- this[kHandleOne] = this[kHandleOne].bind(this);
1727
- this[kHandleMany] = this[kHandleMany].bind(this);
1728
- this[kCallback] = null;
1729
- }
1730
-
1731
- [kHandleOne] (err, key) {
1732
- const callback = this[kCallback];
1733
- if (err) return callback(err)
1734
- if (key !== undefined) key = this[kUnfix](key);
1735
- callback(err, key);
1736
- }
1737
-
1738
- [kHandleMany] (err, keys) {
1739
- const callback = this[kCallback];
1740
- if (err) return callback(err)
1741
-
1742
- for (let i = 0; i < keys.length; i++) {
1743
- const key = keys[i];
1744
- if (key !== undefined) keys[i] = this[kUnfix](key);
1745
- }
1746
-
1747
- callback(err, keys);
1748
- }
1749
- }
1750
-
1751
- class AbstractSublevelValueIterator extends AbstractValueIterator {
1752
- constructor (db, options, iterator) {
1753
- super(db, options);
1754
- this[kIterator] = iterator;
1755
- }
1756
- }
1757
-
1758
- for (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator]) {
1759
- Iterator.prototype._next = function (callback) {
1760
- this[kCallback] = callback;
1761
- this[kIterator].next(this[kHandleOne]);
1762
- };
1763
-
1764
- Iterator.prototype._nextv = function (size, options, callback) {
1765
- this[kCallback] = callback;
1766
- this[kIterator].nextv(size, options, this[kHandleMany]);
1767
- };
1768
-
1769
- Iterator.prototype._all = function (options, callback) {
1770
- this[kCallback] = callback;
1771
- this[kIterator].all(options, this[kHandleMany]);
1772
- };
1773
- }
1774
-
1775
- for (const Iterator of [AbstractSublevelValueIterator]) {
1776
- Iterator.prototype._next = function (callback) {
1777
- this[kIterator].next(callback);
1778
- };
1779
-
1780
- Iterator.prototype._nextv = function (size, options, callback) {
1781
- this[kIterator].nextv(size, options, callback);
1782
- };
1783
-
1784
- Iterator.prototype._all = function (options, callback) {
1785
- this[kIterator].all(options, callback);
1786
- };
1787
- }
1788
-
1789
- for (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator, AbstractSublevelValueIterator]) {
1790
- Iterator.prototype._seek = function (target, options) {
1791
- this[kIterator].seek(target, options);
1792
- };
1793
-
1794
- Iterator.prototype._close = function (callback) {
1795
- this[kIterator].close(callback);
1796
- };
1797
- }
1798
-
1799
- abstractSublevelIterator.AbstractSublevelIterator = AbstractSublevelIterator;
1800
- abstractSublevelIterator.AbstractSublevelKeyIterator = AbstractSublevelKeyIterator;
1801
- abstractSublevelIterator.AbstractSublevelValueIterator = AbstractSublevelValueIterator;
1802
- return abstractSublevelIterator;
1803
- }
1804
-
1805
- var abstractSublevel;
1806
- var hasRequiredAbstractSublevel;
1807
-
1808
- function requireAbstractSublevel () {
1809
- if (hasRequiredAbstractSublevel) return abstractSublevel;
1810
- hasRequiredAbstractSublevel = 1;
1811
-
1812
- const ModuleError = moduleError;
1813
- const { Buffer } = buffer__WEBPACK_IMPORTED_MODULE_0__ || {};
1814
- const {
1815
- AbstractSublevelIterator,
1816
- AbstractSublevelKeyIterator,
1817
- AbstractSublevelValueIterator
1818
- } = requireAbstractSublevelIterator();
1819
-
1820
- const kPrefix = Symbol('prefix');
1821
- const kUpperBound = Symbol('upperBound');
1822
- const kPrefixRange = Symbol('prefixRange');
1823
- const kParent = Symbol('parent');
1824
- const kUnfix = Symbol('unfix');
1825
-
1826
- const textEncoder = new TextEncoder();
1827
- const defaults = { separator: '!' };
1828
-
1829
- // Wrapped to avoid circular dependency
1830
- abstractSublevel = function ({ AbstractLevel }) {
1831
- class AbstractSublevel extends AbstractLevel {
1832
- static defaults (options) {
1833
- // To help migrating from subleveldown to abstract-level
1834
- if (typeof options === 'string') {
1835
- throw new ModuleError('The subleveldown string shorthand for { separator } has been removed', {
1836
- code: 'LEVEL_LEGACY'
1837
- })
1838
- } else if (options && options.open) {
1839
- throw new ModuleError('The subleveldown open option has been removed', {
1840
- code: 'LEVEL_LEGACY'
1841
- })
1842
- }
1843
-
1844
- if (options == null) {
1845
- return defaults
1846
- } else if (!options.separator) {
1847
- return { ...options, separator: '!' }
1848
- } else {
1849
- return options
1850
- }
1851
- }
1852
-
1853
- // TODO: add autoClose option, which if true, does parent.attachResource(this)
1854
- constructor (db, name, options) {
1855
- // Don't forward AbstractSublevel options to AbstractLevel
1856
- const { separator, manifest, ...forward } = AbstractSublevel.defaults(options);
1857
- name = trim(name, separator);
1858
-
1859
- // Reserve one character between separator and name to give us an upper bound
1860
- const reserved = separator.charCodeAt(0) + 1;
1861
- const parent = db[kParent] || db;
1862
-
1863
- // Keys should sort like ['!a!', '!a!!a!', '!a"', '!aa!', '!b!'].
1864
- // Use ASCII for consistent length between string, Buffer and Uint8Array
1865
- if (!textEncoder.encode(name).every(x => x > reserved && x < 127)) {
1866
- throw new ModuleError(`Prefix must use bytes > ${reserved} < ${127}`, {
1867
- code: 'LEVEL_INVALID_PREFIX'
1868
- })
1869
- }
1870
-
1871
- super(mergeManifests(parent, manifest), forward);
1872
-
1873
- const prefix = (db.prefix || '') + separator + name + separator;
1874
- const upperBound = prefix.slice(0, -1) + String.fromCharCode(reserved);
1875
-
1876
- this[kParent] = parent;
1877
- this[kPrefix] = new MultiFormat(prefix);
1878
- this[kUpperBound] = new MultiFormat(upperBound);
1879
- this[kUnfix] = new Unfixer();
1880
-
1881
- this.nextTick = parent.nextTick;
1882
- }
1883
-
1884
- prefixKey (key, keyFormat) {
1885
- if (keyFormat === 'utf8') {
1886
- return this[kPrefix].utf8 + key
1887
- } else if (key.byteLength === 0) {
1888
- // Fast path for empty key (no copy)
1889
- return this[kPrefix][keyFormat]
1890
- } else if (keyFormat === 'view') {
1891
- const view = this[kPrefix].view;
1892
- const result = new Uint8Array(view.byteLength + key.byteLength);
1893
-
1894
- result.set(view, 0);
1895
- result.set(key, view.byteLength);
1896
-
1897
- return result
1898
- } else {
1899
- const buffer = this[kPrefix].buffer;
1900
- return Buffer.concat([buffer, key], buffer.byteLength + key.byteLength)
1901
- }
1902
- }
1903
-
1904
- // Not exposed for now.
1905
- [kPrefixRange] (range, keyFormat) {
1906
- if (range.gte !== undefined) {
1907
- range.gte = this.prefixKey(range.gte, keyFormat);
1908
- } else if (range.gt !== undefined) {
1909
- range.gt = this.prefixKey(range.gt, keyFormat);
1910
- } else {
1911
- range.gte = this[kPrefix][keyFormat];
1912
- }
1913
-
1914
- if (range.lte !== undefined) {
1915
- range.lte = this.prefixKey(range.lte, keyFormat);
1916
- } else if (range.lt !== undefined) {
1917
- range.lt = this.prefixKey(range.lt, keyFormat);
1918
- } else {
1919
- range.lte = this[kUpperBound][keyFormat];
1920
- }
1921
- }
1922
-
1923
- get prefix () {
1924
- return this[kPrefix].utf8
1925
- }
1926
-
1927
- get db () {
1928
- return this[kParent]
1929
- }
1930
-
1931
- _open (options, callback) {
1932
- // The parent db must open itself or be (re)opened by the user because
1933
- // a sublevel should not initiate state changes on the rest of the db.
1934
- this[kParent].open({ passive: true }, callback);
1935
- }
1936
-
1937
- _put (key, value, options, callback) {
1938
- this[kParent].put(key, value, options, callback);
1939
- }
1940
-
1941
- _get (key, options, callback) {
1942
- this[kParent].get(key, options, callback);
1943
- }
1944
-
1945
- _getMany (keys, options, callback) {
1946
- this[kParent].getMany(keys, options, callback);
1947
- }
1948
-
1949
- _del (key, options, callback) {
1950
- this[kParent].del(key, options, callback);
1951
- }
1952
-
1953
- _batch (operations, options, callback) {
1954
- this[kParent].batch(operations, options, callback);
1955
- }
1956
-
1957
- _clear (options, callback) {
1958
- // TODO (refactor): move to AbstractLevel
1959
- this[kPrefixRange](options, options.keyEncoding);
1960
- this[kParent].clear(options, callback);
1961
- }
1962
-
1963
- _iterator (options) {
1964
- // TODO (refactor): move to AbstractLevel
1965
- this[kPrefixRange](options, options.keyEncoding);
1966
- const iterator = this[kParent].iterator(options);
1967
- const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding);
1968
- return new AbstractSublevelIterator(this, options, iterator, unfix)
1969
- }
1970
-
1971
- _keys (options) {
1972
- this[kPrefixRange](options, options.keyEncoding);
1973
- const iterator = this[kParent].keys(options);
1974
- const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding);
1975
- return new AbstractSublevelKeyIterator(this, options, iterator, unfix)
1976
- }
1977
-
1978
- _values (options) {
1979
- this[kPrefixRange](options, options.keyEncoding);
1980
- const iterator = this[kParent].values(options);
1981
- return new AbstractSublevelValueIterator(this, options, iterator)
1982
- }
1983
- }
1984
-
1985
- return { AbstractSublevel }
1986
- };
1987
-
1988
- const mergeManifests = function (parent, manifest) {
1989
- return {
1990
- // Inherit manifest of parent db
1991
- ...parent.supports,
1992
-
1993
- // Disable unsupported features
1994
- createIfMissing: false,
1995
- errorIfExists: false,
1996
-
1997
- // Unset additional events because we're not forwarding them
1998
- events: {},
1999
-
2000
- // Unset additional methods (like approximateSize) which we can't support here unless
2001
- // the AbstractSublevel class is overridden by an implementation of `abstract-level`.
2002
- additionalMethods: {},
2003
-
2004
- // Inherit manifest of custom AbstractSublevel subclass. Such a class is not
2005
- // allowed to override encodings.
2006
- ...manifest,
2007
-
2008
- encodings: {
2009
- utf8: supportsEncoding(parent, 'utf8'),
2010
- buffer: supportsEncoding(parent, 'buffer'),
2011
- view: supportsEncoding(parent, 'view')
2012
- }
2013
- }
2014
- };
2015
-
2016
- const supportsEncoding = function (parent, encoding) {
2017
- // Prefer a non-transcoded encoding for optimal performance
2018
- return parent.supports.encodings[encoding]
2019
- ? parent.keyEncoding(encoding).name === encoding
2020
- : false
2021
- };
2022
-
2023
- class MultiFormat {
2024
- constructor (key) {
2025
- this.utf8 = key;
2026
- this.view = textEncoder.encode(key);
2027
- this.buffer = Buffer ? Buffer.from(this.view.buffer, 0, this.view.byteLength) : {};
2028
- }
2029
- }
2030
-
2031
- class Unfixer {
2032
- constructor () {
2033
- this.cache = new Map();
2034
- }
2035
-
2036
- get (prefixLength, keyFormat) {
2037
- let unfix = this.cache.get(keyFormat);
2038
-
2039
- if (unfix === undefined) {
2040
- if (keyFormat === 'view') {
2041
- unfix = function (prefixLength, key) {
2042
- // Avoid Uint8Array#slice() because it copies
2043
- return key.subarray(prefixLength)
2044
- }.bind(null, prefixLength);
2045
- } else {
2046
- unfix = function (prefixLength, key) {
2047
- // Avoid Buffer#subarray() because it's slow
2048
- return key.slice(prefixLength)
2049
- }.bind(null, prefixLength);
2050
- }
2051
-
2052
- this.cache.set(keyFormat, unfix);
2053
- }
2054
-
2055
- return unfix
2056
- }
2057
- }
2058
-
2059
- const trim = function (str, char) {
2060
- let start = 0;
2061
- let end = str.length;
2062
-
2063
- while (start < end && str[start] === char) start++;
2064
- while (end > start && str[end - 1] === char) end--;
2065
-
2066
- return str.slice(start, end)
2067
- };
2068
- return abstractSublevel;
2069
- }
2070
-
2071
- const { supports } = levelSupports;
2072
- const { Transcoder } = levelTranscoder;
2073
- const { EventEmitter } = (events__WEBPACK_IMPORTED_MODULE_1___default());
2074
- const { fromCallback: fromCallback$1 } = catering;
2075
- const ModuleError$1 = moduleError;
2076
- const { AbstractIterator: AbstractIterator$1 } = abstractIterator;
2077
- const { DefaultKeyIterator, DefaultValueIterator } = defaultKvIterator;
2078
- const { DeferredIterator, DeferredKeyIterator, DeferredValueIterator } = deferredIterator;
2079
- const { DefaultChainedBatch } = defaultChainedBatch;
2080
- const { getCallback, getOptions } = common;
2081
- const rangeOptions = rangeOptions_1;
2082
-
2083
- const kPromise$1 = Symbol('promise');
2084
- const kLanded = Symbol('landed');
2085
- const kResources = Symbol('resources');
2086
- const kCloseResources = Symbol('closeResources');
2087
- const kOperations = Symbol('operations');
2088
- const kUndefer = Symbol('undefer');
2089
- const kDeferOpen = Symbol('deferOpen');
2090
- const kOptions$1 = Symbol('options');
2091
- const kStatus = Symbol('status');
2092
- const kDefaultOptions = Symbol('defaultOptions');
2093
- const kTranscoder = Symbol('transcoder');
2094
- const kKeyEncoding = Symbol('keyEncoding');
2095
- const kValueEncoding = Symbol('valueEncoding');
2096
- const noop = () => {};
2097
-
2098
- class AbstractLevel$1 extends EventEmitter {
2099
- constructor (manifest, options) {
2100
- super();
2101
-
2102
- if (typeof manifest !== 'object' || manifest === null) {
2103
- throw new TypeError("The first argument 'manifest' must be an object")
2104
- }
2105
-
2106
- options = getOptions(options);
2107
- const { keyEncoding, valueEncoding, passive, ...forward } = options;
2108
-
2109
- this[kResources] = new Set();
2110
- this[kOperations] = [];
2111
- this[kDeferOpen] = true;
2112
- this[kOptions$1] = forward;
2113
- this[kStatus] = 'opening';
2114
-
2115
- this.supports = supports(manifest, {
2116
- status: true,
2117
- promises: true,
2118
- clear: true,
2119
- getMany: true,
2120
- deferredOpen: true,
2121
-
2122
- // TODO (next major): add seek
2123
- snapshots: manifest.snapshots !== false,
2124
- permanence: manifest.permanence !== false,
2125
-
2126
- // TODO: remove from level-supports because it's always supported
2127
- keyIterator: true,
2128
- valueIterator: true,
2129
- iteratorNextv: true,
2130
- iteratorAll: true,
2131
-
2132
- encodings: manifest.encodings || {},
2133
- events: Object.assign({}, manifest.events, {
2134
- opening: true,
2135
- open: true,
2136
- closing: true,
2137
- closed: true,
2138
- put: true,
2139
- del: true,
2140
- batch: true,
2141
- clear: true
2142
- })
2143
- });
2144
-
2145
- this[kTranscoder] = new Transcoder(formats(this));
2146
- this[kKeyEncoding] = this[kTranscoder].encoding(keyEncoding || 'utf8');
2147
- this[kValueEncoding] = this[kTranscoder].encoding(valueEncoding || 'utf8');
2148
-
2149
- // Add custom and transcoder encodings to manifest
2150
- for (const encoding of this[kTranscoder].encodings()) {
2151
- if (!this.supports.encodings[encoding.commonName]) {
2152
- this.supports.encodings[encoding.commonName] = true;
2153
- }
2154
- }
2155
-
2156
- this[kDefaultOptions] = {
2157
- empty: Object.freeze({}),
2158
- entry: Object.freeze({
2159
- keyEncoding: this[kKeyEncoding].commonName,
2160
- valueEncoding: this[kValueEncoding].commonName
2161
- }),
2162
- key: Object.freeze({
2163
- keyEncoding: this[kKeyEncoding].commonName
2164
- })
2165
- };
2166
-
2167
- // Let subclass finish its constructor
2168
- this.nextTick(() => {
2169
- if (this[kDeferOpen]) {
2170
- this.open({ passive: false }, noop);
2171
- }
2172
- });
2173
- }
2174
-
2175
- get status () {
2176
- return this[kStatus]
2177
- }
2178
-
2179
- keyEncoding (encoding) {
2180
- return this[kTranscoder].encoding(encoding != null ? encoding : this[kKeyEncoding])
2181
- }
2182
-
2183
- valueEncoding (encoding) {
2184
- return this[kTranscoder].encoding(encoding != null ? encoding : this[kValueEncoding])
2185
- }
2186
-
2187
- open (options, callback) {
2188
- callback = getCallback(options, callback);
2189
- callback = fromCallback$1(callback, kPromise$1);
2190
-
2191
- options = { ...this[kOptions$1], ...getOptions(options) };
2192
-
2193
- options.createIfMissing = options.createIfMissing !== false;
2194
- options.errorIfExists = !!options.errorIfExists;
2195
-
2196
- const maybeOpened = (err) => {
2197
- if (this[kStatus] === 'closing' || this[kStatus] === 'opening') {
2198
- // Wait until pending state changes are done
2199
- this.once(kLanded, err ? () => maybeOpened(err) : maybeOpened);
2200
- } else if (this[kStatus] !== 'open') {
2201
- callback(new ModuleError$1('Database is not open', {
2202
- code: 'LEVEL_DATABASE_NOT_OPEN',
2203
- cause: err
2204
- }));
2205
- } else {
2206
- callback();
2207
- }
2208
- };
2209
-
2210
- if (options.passive) {
2211
- if (this[kStatus] === 'opening') {
2212
- this.once(kLanded, maybeOpened);
2213
- } else {
2214
- this.nextTick(maybeOpened);
2215
- }
2216
- } else if (this[kStatus] === 'closed' || this[kDeferOpen]) {
2217
- this[kDeferOpen] = false;
2218
- this[kStatus] = 'opening';
2219
- this.emit('opening');
2220
-
2221
- this._open(options, (err) => {
2222
- if (err) {
2223
- this[kStatus] = 'closed';
2224
-
2225
- // Resources must be safe to close in any db state
2226
- this[kCloseResources](() => {
2227
- this.emit(kLanded);
2228
- maybeOpened(err);
2229
- });
2230
-
2231
- this[kUndefer]();
2232
- return
2233
- }
2234
-
2235
- this[kStatus] = 'open';
2236
- this[kUndefer]();
2237
- this.emit(kLanded);
2238
-
2239
- // Only emit public event if pending state changes are done
2240
- if (this[kStatus] === 'open') this.emit('open');
2241
-
2242
- // TODO (next major): remove this alias
2243
- if (this[kStatus] === 'open') this.emit('ready');
2244
-
2245
- maybeOpened();
2246
- });
2247
- } else if (this[kStatus] === 'open') {
2248
- this.nextTick(maybeOpened);
2249
- } else {
2250
- this.once(kLanded, () => this.open(options, callback));
2251
- }
2252
-
2253
- return callback[kPromise$1]
2254
- }
2255
-
2256
- _open (options, callback) {
2257
- this.nextTick(callback);
2258
- }
2259
-
2260
- close (callback) {
2261
- callback = fromCallback$1(callback, kPromise$1);
2262
-
2263
- const maybeClosed = (err) => {
2264
- if (this[kStatus] === 'opening' || this[kStatus] === 'closing') {
2265
- // Wait until pending state changes are done
2266
- this.once(kLanded, err ? maybeClosed(err) : maybeClosed);
2267
- } else if (this[kStatus] !== 'closed') {
2268
- callback(new ModuleError$1('Database is not closed', {
2269
- code: 'LEVEL_DATABASE_NOT_CLOSED',
2270
- cause: err
2271
- }));
2272
- } else {
2273
- callback();
2274
- }
2275
- };
2276
-
2277
- if (this[kStatus] === 'open') {
2278
- this[kStatus] = 'closing';
2279
- this.emit('closing');
2280
-
2281
- const cancel = (err) => {
2282
- this[kStatus] = 'open';
2283
- this[kUndefer]();
2284
- this.emit(kLanded);
2285
- maybeClosed(err);
2286
- };
2287
-
2288
- this[kCloseResources](() => {
2289
- this._close((err) => {
2290
- if (err) return cancel(err)
2291
-
2292
- this[kStatus] = 'closed';
2293
- this[kUndefer]();
2294
- this.emit(kLanded);
2295
-
2296
- // Only emit public event if pending state changes are done
2297
- if (this[kStatus] === 'closed') this.emit('closed');
2298
-
2299
- maybeClosed();
2300
- });
2301
- });
2302
- } else if (this[kStatus] === 'closed') {
2303
- this.nextTick(maybeClosed);
2304
- } else {
2305
- this.once(kLanded, () => this.close(callback));
2306
- }
2307
-
2308
- return callback[kPromise$1]
2309
- }
2310
-
2311
- [kCloseResources] (callback) {
2312
- if (this[kResources].size === 0) {
2313
- return this.nextTick(callback)
2314
- }
2315
-
2316
- let pending = this[kResources].size;
2317
- let sync = true;
2318
-
2319
- const next = () => {
2320
- if (--pending === 0) {
2321
- // We don't have tests for generic resources, so dezalgo
2322
- if (sync) this.nextTick(callback);
2323
- else callback();
2324
- }
2325
- };
2326
-
2327
- // In parallel so that all resources know they are closed
2328
- for (const resource of this[kResources]) {
2329
- resource.close(next);
2330
- }
2331
-
2332
- sync = false;
2333
- this[kResources].clear();
2334
- }
2335
-
2336
- _close (callback) {
2337
- this.nextTick(callback);
2338
- }
2339
-
2340
- get (key, options, callback) {
2341
- callback = getCallback(options, callback);
2342
- callback = fromCallback$1(callback, kPromise$1);
2343
- options = getOptions(options, this[kDefaultOptions].entry);
2344
-
2345
- if (this[kStatus] === 'opening') {
2346
- this.defer(() => this.get(key, options, callback));
2347
- return callback[kPromise$1]
2348
- }
2349
-
2350
- if (maybeError(this, callback)) {
2351
- return callback[kPromise$1]
2352
- }
2353
-
2354
- const err = this._checkKey(key);
2355
-
2356
- if (err) {
2357
- this.nextTick(callback, err);
2358
- return callback[kPromise$1]
2359
- }
2360
-
2361
- const keyEncoding = this.keyEncoding(options.keyEncoding);
2362
- const valueEncoding = this.valueEncoding(options.valueEncoding);
2363
- const keyFormat = keyEncoding.format;
2364
- const valueFormat = valueEncoding.format;
2365
-
2366
- // Forward encoding options to the underlying store
2367
- if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {
2368
- // Avoid spread operator because of https://bugs.chromium.org/p/chromium/issues/detail?id=1204540
2369
- options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat });
2370
- }
2371
-
2372
- this._get(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err, value) => {
2373
- if (err) {
2374
- // Normalize not found error for backwards compatibility with abstract-leveldown and level(up)
2375
- if (err.code === 'LEVEL_NOT_FOUND' || err.notFound || /NotFound/i.test(err)) {
2376
- if (!err.code) err.code = 'LEVEL_NOT_FOUND'; // Preferred way going forward
2377
- if (!err.notFound) err.notFound = true; // Same as level-errors
2378
- if (!err.status) err.status = 404; // Same as level-errors
2379
- }
2380
-
2381
- return callback(err)
2382
- }
2383
-
2384
- try {
2385
- value = valueEncoding.decode(value);
2386
- } catch (err) {
2387
- return callback(new ModuleError$1('Could not decode value', {
2388
- code: 'LEVEL_DECODE_ERROR',
2389
- cause: err
2390
- }))
2391
- }
2392
-
2393
- callback(null, value);
2394
- });
2395
-
2396
- return callback[kPromise$1]
2397
- }
2398
-
2399
- _get (key, options, callback) {
2400
- this.nextTick(callback, new Error('NotFound'));
2401
- }
2402
-
2403
- getMany (keys, options, callback) {
2404
- callback = getCallback(options, callback);
2405
- callback = fromCallback$1(callback, kPromise$1);
2406
- options = getOptions(options, this[kDefaultOptions].entry);
2407
-
2408
- if (this[kStatus] === 'opening') {
2409
- this.defer(() => this.getMany(keys, options, callback));
2410
- return callback[kPromise$1]
2411
- }
2412
-
2413
- if (maybeError(this, callback)) {
2414
- return callback[kPromise$1]
2415
- }
2416
-
2417
- if (!Array.isArray(keys)) {
2418
- this.nextTick(callback, new TypeError("The first argument 'keys' must be an array"));
2419
- return callback[kPromise$1]
2420
- }
2421
-
2422
- if (keys.length === 0) {
2423
- this.nextTick(callback, null, []);
2424
- return callback[kPromise$1]
2425
- }
2426
-
2427
- const keyEncoding = this.keyEncoding(options.keyEncoding);
2428
- const valueEncoding = this.valueEncoding(options.valueEncoding);
2429
- const keyFormat = keyEncoding.format;
2430
- const valueFormat = valueEncoding.format;
2431
-
2432
- // Forward encoding options
2433
- if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {
2434
- options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat });
2435
- }
2436
-
2437
- const mappedKeys = new Array(keys.length);
2438
-
2439
- for (let i = 0; i < keys.length; i++) {
2440
- const key = keys[i];
2441
- const err = this._checkKey(key);
2442
-
2443
- if (err) {
2444
- this.nextTick(callback, err);
2445
- return callback[kPromise$1]
2446
- }
2447
-
2448
- mappedKeys[i] = this.prefixKey(keyEncoding.encode(key), keyFormat);
2449
- }
2450
-
2451
- this._getMany(mappedKeys, options, (err, values) => {
2452
- if (err) return callback(err)
2453
-
2454
- try {
2455
- for (let i = 0; i < values.length; i++) {
2456
- if (values[i] !== undefined) {
2457
- values[i] = valueEncoding.decode(values[i]);
2458
- }
2459
- }
2460
- } catch (err) {
2461
- return callback(new ModuleError$1(`Could not decode one or more of ${values.length} value(s)`, {
2462
- code: 'LEVEL_DECODE_ERROR',
2463
- cause: err
2464
- }))
2465
- }
2466
-
2467
- callback(null, values);
2468
- });
2469
-
2470
- return callback[kPromise$1]
2471
- }
2472
-
2473
- _getMany (keys, options, callback) {
2474
- this.nextTick(callback, null, new Array(keys.length).fill(undefined));
2475
- }
2476
-
2477
- put (key, value, options, callback) {
2478
- callback = getCallback(options, callback);
2479
- callback = fromCallback$1(callback, kPromise$1);
2480
- options = getOptions(options, this[kDefaultOptions].entry);
2481
-
2482
- if (this[kStatus] === 'opening') {
2483
- this.defer(() => this.put(key, value, options, callback));
2484
- return callback[kPromise$1]
2485
- }
2486
-
2487
- if (maybeError(this, callback)) {
2488
- return callback[kPromise$1]
2489
- }
2490
-
2491
- const err = this._checkKey(key) || this._checkValue(value);
2492
-
2493
- if (err) {
2494
- this.nextTick(callback, err);
2495
- return callback[kPromise$1]
2496
- }
2497
-
2498
- const keyEncoding = this.keyEncoding(options.keyEncoding);
2499
- const valueEncoding = this.valueEncoding(options.valueEncoding);
2500
- const keyFormat = keyEncoding.format;
2501
- const valueFormat = valueEncoding.format;
2502
-
2503
- // Forward encoding options
2504
- if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {
2505
- options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat });
2506
- }
2507
-
2508
- const mappedKey = this.prefixKey(keyEncoding.encode(key), keyFormat);
2509
- const mappedValue = valueEncoding.encode(value);
2510
-
2511
- this._put(mappedKey, mappedValue, options, (err) => {
2512
- if (err) return callback(err)
2513
- this.emit('put', key, value);
2514
- callback();
2515
- });
2516
-
2517
- return callback[kPromise$1]
2518
- }
2519
-
2520
- _put (key, value, options, callback) {
2521
- this.nextTick(callback);
2522
- }
2523
-
2524
- del (key, options, callback) {
2525
- callback = getCallback(options, callback);
2526
- callback = fromCallback$1(callback, kPromise$1);
2527
- options = getOptions(options, this[kDefaultOptions].key);
2528
-
2529
- if (this[kStatus] === 'opening') {
2530
- this.defer(() => this.del(key, options, callback));
2531
- return callback[kPromise$1]
2532
- }
2533
-
2534
- if (maybeError(this, callback)) {
2535
- return callback[kPromise$1]
2536
- }
2537
-
2538
- const err = this._checkKey(key);
2539
-
2540
- if (err) {
2541
- this.nextTick(callback, err);
2542
- return callback[kPromise$1]
2543
- }
2544
-
2545
- const keyEncoding = this.keyEncoding(options.keyEncoding);
2546
- const keyFormat = keyEncoding.format;
2547
-
2548
- // Forward encoding options
2549
- if (options.keyEncoding !== keyFormat) {
2550
- options = Object.assign({}, options, { keyEncoding: keyFormat });
2551
- }
2552
-
2553
- this._del(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err) => {
2554
- if (err) return callback(err)
2555
- this.emit('del', key);
2556
- callback();
2557
- });
2558
-
2559
- return callback[kPromise$1]
2560
- }
2561
-
2562
- _del (key, options, callback) {
2563
- this.nextTick(callback);
2564
- }
2565
-
2566
- batch (operations, options, callback) {
2567
- if (!arguments.length) {
2568
- if (this[kStatus] === 'opening') return new DefaultChainedBatch(this)
2569
- if (this[kStatus] !== 'open') {
2570
- throw new ModuleError$1('Database is not open', {
2571
- code: 'LEVEL_DATABASE_NOT_OPEN'
2572
- })
2573
- }
2574
- return this._chainedBatch()
2575
- }
2576
-
2577
- if (typeof operations === 'function') callback = operations;
2578
- else callback = getCallback(options, callback);
2579
-
2580
- callback = fromCallback$1(callback, kPromise$1);
2581
- options = getOptions(options, this[kDefaultOptions].empty);
2582
-
2583
- if (this[kStatus] === 'opening') {
2584
- this.defer(() => this.batch(operations, options, callback));
2585
- return callback[kPromise$1]
2586
- }
2587
-
2588
- if (maybeError(this, callback)) {
2589
- return callback[kPromise$1]
2590
- }
2591
-
2592
- if (!Array.isArray(operations)) {
2593
- this.nextTick(callback, new TypeError("The first argument 'operations' must be an array"));
2594
- return callback[kPromise$1]
2595
- }
2596
-
2597
- if (operations.length === 0) {
2598
- this.nextTick(callback);
2599
- return callback[kPromise$1]
2600
- }
2601
-
2602
- const mapped = new Array(operations.length);
2603
- const { keyEncoding: ke, valueEncoding: ve, ...forward } = options;
2604
-
2605
- for (let i = 0; i < operations.length; i++) {
2606
- if (typeof operations[i] !== 'object' || operations[i] === null) {
2607
- this.nextTick(callback, new TypeError('A batch operation must be an object'));
2608
- return callback[kPromise$1]
2609
- }
2610
-
2611
- const op = Object.assign({}, operations[i]);
2612
-
2613
- if (op.type !== 'put' && op.type !== 'del') {
2614
- this.nextTick(callback, new TypeError("A batch operation must have a type property that is 'put' or 'del'"));
2615
- return callback[kPromise$1]
2616
- }
2617
-
2618
- const err = this._checkKey(op.key);
2619
-
2620
- if (err) {
2621
- this.nextTick(callback, err);
2622
- return callback[kPromise$1]
2623
- }
2624
-
2625
- const db = op.sublevel != null ? op.sublevel : this;
2626
- const keyEncoding = db.keyEncoding(op.keyEncoding || ke);
2627
- const keyFormat = keyEncoding.format;
2628
-
2629
- op.key = db.prefixKey(keyEncoding.encode(op.key), keyFormat);
2630
- op.keyEncoding = keyFormat;
2631
-
2632
- if (op.type === 'put') {
2633
- const valueErr = this._checkValue(op.value);
2634
-
2635
- if (valueErr) {
2636
- this.nextTick(callback, valueErr);
2637
- return callback[kPromise$1]
2638
- }
2639
-
2640
- const valueEncoding = db.valueEncoding(op.valueEncoding || ve);
2641
-
2642
- op.value = valueEncoding.encode(op.value);
2643
- op.valueEncoding = valueEncoding.format;
2644
- }
2645
-
2646
- // Prevent double prefixing
2647
- if (db !== this) {
2648
- op.sublevel = null;
2649
- }
2650
-
2651
- mapped[i] = op;
2652
- }
2653
-
2654
- this._batch(mapped, forward, (err) => {
2655
- if (err) return callback(err)
2656
- this.emit('batch', operations);
2657
- callback();
2658
- });
2659
-
2660
- return callback[kPromise$1]
2661
- }
2662
-
2663
- _batch (operations, options, callback) {
2664
- this.nextTick(callback);
2665
- }
2666
-
2667
- sublevel (name, options) {
2668
- return this._sublevel(name, AbstractSublevel.defaults(options))
2669
- }
2670
-
2671
- _sublevel (name, options) {
2672
- return new AbstractSublevel(this, name, options)
2673
- }
2674
-
2675
- prefixKey (key, keyFormat) {
2676
- return key
2677
- }
2678
-
2679
- clear (options, callback) {
2680
- callback = getCallback(options, callback);
2681
- callback = fromCallback$1(callback, kPromise$1);
2682
- options = getOptions(options, this[kDefaultOptions].empty);
2683
-
2684
- if (this[kStatus] === 'opening') {
2685
- this.defer(() => this.clear(options, callback));
2686
- return callback[kPromise$1]
2687
- }
2688
-
2689
- if (maybeError(this, callback)) {
2690
- return callback[kPromise$1]
2691
- }
2692
-
2693
- const original = options;
2694
- const keyEncoding = this.keyEncoding(options.keyEncoding);
2695
-
2696
- options = rangeOptions(options, keyEncoding);
2697
- options.keyEncoding = keyEncoding.format;
2698
-
2699
- if (options.limit === 0) {
2700
- this.nextTick(callback);
2701
- } else {
2702
- this._clear(options, (err) => {
2703
- if (err) return callback(err)
2704
- this.emit('clear', original);
2705
- callback();
2706
- });
2707
- }
2708
-
2709
- return callback[kPromise$1]
2710
- }
2711
-
2712
- _clear (options, callback) {
2713
- this.nextTick(callback);
2714
- }
2715
-
2716
- iterator (options) {
2717
- const keyEncoding = this.keyEncoding(options && options.keyEncoding);
2718
- const valueEncoding = this.valueEncoding(options && options.valueEncoding);
2719
-
2720
- options = rangeOptions(options, keyEncoding);
2721
- options.keys = options.keys !== false;
2722
- options.values = options.values !== false;
2723
-
2724
- // We need the original encoding options in AbstractIterator in order to decode data
2725
- options[AbstractIterator$1.keyEncoding] = keyEncoding;
2726
- options[AbstractIterator$1.valueEncoding] = valueEncoding;
2727
-
2728
- // Forward encoding options to private API
2729
- options.keyEncoding = keyEncoding.format;
2730
- options.valueEncoding = valueEncoding.format;
2731
-
2732
- if (this[kStatus] === 'opening') {
2733
- return new DeferredIterator(this, options)
2734
- } else if (this[kStatus] !== 'open') {
2735
- throw new ModuleError$1('Database is not open', {
2736
- code: 'LEVEL_DATABASE_NOT_OPEN'
2737
- })
2738
- }
2739
-
2740
- return this._iterator(options)
2741
- }
2742
-
2743
- _iterator (options) {
2744
- return new AbstractIterator$1(this, options)
2745
- }
2746
-
2747
- keys (options) {
2748
- // Also include valueEncoding (though unused) because we may fallback to _iterator()
2749
- const keyEncoding = this.keyEncoding(options && options.keyEncoding);
2750
- const valueEncoding = this.valueEncoding(options && options.valueEncoding);
2751
-
2752
- options = rangeOptions(options, keyEncoding);
2753
-
2754
- // We need the original encoding options in AbstractKeyIterator in order to decode data
2755
- options[AbstractIterator$1.keyEncoding] = keyEncoding;
2756
- options[AbstractIterator$1.valueEncoding] = valueEncoding;
2757
-
2758
- // Forward encoding options to private API
2759
- options.keyEncoding = keyEncoding.format;
2760
- options.valueEncoding = valueEncoding.format;
2761
-
2762
- if (this[kStatus] === 'opening') {
2763
- return new DeferredKeyIterator(this, options)
2764
- } else if (this[kStatus] !== 'open') {
2765
- throw new ModuleError$1('Database is not open', {
2766
- code: 'LEVEL_DATABASE_NOT_OPEN'
2767
- })
2768
- }
2769
-
2770
- return this._keys(options)
2771
- }
2772
-
2773
- _keys (options) {
2774
- return new DefaultKeyIterator(this, options)
2775
- }
2776
-
2777
- values (options) {
2778
- const keyEncoding = this.keyEncoding(options && options.keyEncoding);
2779
- const valueEncoding = this.valueEncoding(options && options.valueEncoding);
2780
-
2781
- options = rangeOptions(options, keyEncoding);
2782
-
2783
- // We need the original encoding options in AbstractValueIterator in order to decode data
2784
- options[AbstractIterator$1.keyEncoding] = keyEncoding;
2785
- options[AbstractIterator$1.valueEncoding] = valueEncoding;
2786
-
2787
- // Forward encoding options to private API
2788
- options.keyEncoding = keyEncoding.format;
2789
- options.valueEncoding = valueEncoding.format;
2790
-
2791
- if (this[kStatus] === 'opening') {
2792
- return new DeferredValueIterator(this, options)
2793
- } else if (this[kStatus] !== 'open') {
2794
- throw new ModuleError$1('Database is not open', {
2795
- code: 'LEVEL_DATABASE_NOT_OPEN'
2796
- })
2797
- }
2798
-
2799
- return this._values(options)
2800
- }
2801
-
2802
- _values (options) {
2803
- return new DefaultValueIterator(this, options)
2804
- }
2805
-
2806
- defer (fn) {
2807
- if (typeof fn !== 'function') {
2808
- throw new TypeError('The first argument must be a function')
2809
- }
2810
-
2811
- this[kOperations].push(fn);
2812
- }
2813
-
2814
- [kUndefer] () {
2815
- if (this[kOperations].length === 0) {
2816
- return
2817
- }
2818
-
2819
- const operations = this[kOperations];
2820
- this[kOperations] = [];
2821
-
2822
- for (const op of operations) {
2823
- op();
2824
- }
2825
- }
2826
-
2827
- // TODO: docs and types
2828
- attachResource (resource) {
2829
- if (typeof resource !== 'object' || resource === null ||
2830
- typeof resource.close !== 'function') {
2831
- throw new TypeError('The first argument must be a resource object')
2832
- }
2833
-
2834
- this[kResources].add(resource);
2835
- }
2836
-
2837
- // TODO: docs and types
2838
- detachResource (resource) {
2839
- this[kResources].delete(resource);
2840
- }
2841
-
2842
- _chainedBatch () {
2843
- return new DefaultChainedBatch(this)
2844
- }
2845
-
2846
- _checkKey (key) {
2847
- if (key === null || key === undefined) {
2848
- return new ModuleError$1('Key cannot be null or undefined', {
2849
- code: 'LEVEL_INVALID_KEY'
2850
- })
2851
- }
2852
- }
2853
-
2854
- _checkValue (value) {
2855
- if (value === null || value === undefined) {
2856
- return new ModuleError$1('Value cannot be null or undefined', {
2857
- code: 'LEVEL_INVALID_VALUE'
2858
- })
2859
- }
2860
- }
2861
- }
2862
-
2863
- // Expose browser-compatible nextTick for dependents
2864
- // TODO: after we drop node 10, also use queueMicrotask in node
2865
- AbstractLevel$1.prototype.nextTick = requireNextTick();
2866
-
2867
- const { AbstractSublevel } = requireAbstractSublevel()({ AbstractLevel: AbstractLevel$1 });
2868
-
2869
- abstractLevel.AbstractLevel = AbstractLevel$1;
2870
- abstractLevel.AbstractSublevel = AbstractSublevel;
2871
-
2872
- const maybeError = function (db, callback) {
2873
- if (db[kStatus] !== 'open') {
2874
- db.nextTick(callback, new ModuleError$1('Database is not open', {
2875
- code: 'LEVEL_DATABASE_NOT_OPEN'
2876
- }));
2877
- return true
2878
- }
2879
-
2880
- return false
2881
- };
2882
-
2883
- const formats = function (db) {
2884
- return Object.keys(db.supports.encodings)
2885
- .filter(k => !!db.supports.encodings[k])
2886
- };
2887
-
2888
- abstractLevel$1.AbstractLevel = abstractLevel.AbstractLevel;
2889
- abstractLevel$1.AbstractSublevel = abstractLevel.AbstractSublevel;
2890
- abstractLevel$1.AbstractIterator = abstractIterator.AbstractIterator;
2891
- abstractLevel$1.AbstractKeyIterator = abstractIterator.AbstractKeyIterator;
2892
- abstractLevel$1.AbstractValueIterator = abstractIterator.AbstractValueIterator;
2893
- abstractLevel$1.AbstractChainedBatch = abstractChainedBatch.AbstractChainedBatch;
2894
-
2895
- /*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
2896
-
2897
- let promise;
2898
-
2899
- var queueMicrotask_1 = typeof queueMicrotask === 'function'
2900
- ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal)
2901
- // reuse resolved promise, and allocate it lazily
2902
- : cb => (promise || (promise = Promise.resolve()))
2903
- .then(cb)
2904
- .catch(err => setTimeout(() => { throw err }, 0));
2905
-
2906
- /*! run-parallel-limit. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
2907
-
2908
- var runParallelLimit_1 = runParallelLimit;
2909
-
2910
- const queueMicrotask$1 = queueMicrotask_1;
2911
-
2912
- function runParallelLimit (tasks, limit, cb) {
2913
- if (typeof limit !== 'number') throw new Error('second argument must be a Number')
2914
- let results, len, pending, keys, isErrored;
2915
- let isSync = true;
2916
- let next;
2917
-
2918
- if (Array.isArray(tasks)) {
2919
- results = [];
2920
- pending = len = tasks.length;
2921
- } else {
2922
- keys = Object.keys(tasks);
2923
- results = {};
2924
- pending = len = keys.length;
2925
- }
2926
-
2927
- function done (err) {
2928
- function end () {
2929
- if (cb) cb(err, results);
2930
- cb = null;
2931
- }
2932
- if (isSync) queueMicrotask$1(end);
2933
- else end();
2934
- }
2935
-
2936
- function each (i, err, result) {
2937
- results[i] = result;
2938
- if (err) isErrored = true;
2939
- if (--pending === 0 || err) {
2940
- done(err);
2941
- } else if (!isErrored && next < len) {
2942
- let key;
2943
- if (keys) {
2944
- key = keys[next];
2945
- next += 1;
2946
- tasks[key](function (err, result) { each(key, err, result); });
2947
- } else {
2948
- key = next;
2949
- next += 1;
2950
- tasks[key](function (err, result) { each(key, err, result); });
2951
- }
2952
- }
2953
- }
2954
-
2955
- next = limit;
2956
- if (!pending) {
2957
- // empty
2958
- done(null);
2959
- } else if (keys) {
2960
- // object
2961
- keys.some(function (key, i) {
2962
- tasks[key](function (err, result) { each(key, err, result); });
2963
- if (i === limit - 1) return true // early return
2964
- return false
2965
- });
2966
- } else {
2967
- // array
2968
- tasks.some(function (task, i) {
2969
- task(function (err, result) { each(i, err, result); });
2970
- if (i === limit - 1) return true // early return
2971
- return false
2972
- });
2973
- }
2974
-
2975
- isSync = false;
2976
- }
2977
-
2978
- var iterator = {};
2979
-
2980
- /* global IDBKeyRange */
2981
-
2982
- var keyRange = function createKeyRange (options) {
2983
- const lower = options.gte !== undefined ? options.gte : options.gt !== undefined ? options.gt : undefined;
2984
- const upper = options.lte !== undefined ? options.lte : options.lt !== undefined ? options.lt : undefined;
2985
- const lowerExclusive = options.gte === undefined;
2986
- const upperExclusive = options.lte === undefined;
2987
-
2988
- if (lower !== undefined && upper !== undefined) {
2989
- return IDBKeyRange.bound(lower, upper, lowerExclusive, upperExclusive)
2990
- } else if (lower !== undefined) {
2991
- return IDBKeyRange.lowerBound(lower, lowerExclusive)
2992
- } else if (upper !== undefined) {
2993
- return IDBKeyRange.upperBound(upper, upperExclusive)
2994
- } else {
2995
- return null
2996
- }
2997
- };
2998
-
2999
- const textEncoder = new TextEncoder();
3000
-
3001
- var deserialize$2 = function (data) {
3002
- if (data instanceof Uint8Array) {
3003
- return data
3004
- } else if (data instanceof ArrayBuffer) {
3005
- return new Uint8Array(data)
3006
- } else {
3007
- // Non-binary data stored with an old version (level-js < 5.0.0)
3008
- return textEncoder.encode(data)
3009
- }
3010
- };
3011
-
3012
- const { AbstractIterator } = abstractLevel$1;
3013
- const createKeyRange$1 = keyRange;
3014
- const deserialize$1 = deserialize$2;
3015
-
3016
- const kCache = Symbol('cache');
3017
- const kFinished = Symbol('finished');
3018
- const kOptions = Symbol('options');
3019
- const kCurrentOptions = Symbol('currentOptions');
3020
- const kPosition = Symbol('position');
3021
- const kLocation$1 = Symbol('location');
3022
- const kFirst = Symbol('first');
3023
- const emptyOptions = {};
3024
-
3025
- class Iterator$1 extends AbstractIterator {
3026
- constructor (db, location, options) {
3027
- super(db, options);
3028
-
3029
- this[kCache] = [];
3030
- this[kFinished] = this.limit === 0;
3031
- this[kOptions] = options;
3032
- this[kCurrentOptions] = { ...options };
3033
- this[kPosition] = undefined;
3034
- this[kLocation$1] = location;
3035
- this[kFirst] = true;
3036
- }
3037
-
3038
- // Note: if called by _all() then size can be Infinity. This is an internal
3039
- // detail; by design AbstractIterator.nextv() does not support Infinity.
3040
- _nextv (size, options, callback) {
3041
- this[kFirst] = false;
3042
-
3043
- if (this[kFinished]) {
3044
- return this.nextTick(callback, null, [])
3045
- } else if (this[kCache].length > 0) {
3046
- // TODO: mixing next and nextv is not covered by test suite
3047
- size = Math.min(size, this[kCache].length);
3048
- return this.nextTick(callback, null, this[kCache].splice(0, size))
3049
- }
3050
-
3051
- // Adjust range by what we already visited
3052
- if (this[kPosition] !== undefined) {
3053
- if (this[kOptions].reverse) {
3054
- this[kCurrentOptions].lt = this[kPosition];
3055
- this[kCurrentOptions].lte = undefined;
3056
- } else {
3057
- this[kCurrentOptions].gt = this[kPosition];
3058
- this[kCurrentOptions].gte = undefined;
3059
- }
3060
- }
3061
-
3062
- let keyRange;
3063
-
3064
- try {
3065
- keyRange = createKeyRange$1(this[kCurrentOptions]);
3066
- } catch (_) {
3067
- // The lower key is greater than the upper key.
3068
- // IndexedDB throws an error, but we'll just return 0 results.
3069
- this[kFinished] = true;
3070
- return this.nextTick(callback, null, [])
3071
- }
3072
-
3073
- const transaction = this.db.db.transaction([this[kLocation$1]], 'readonly');
3074
- const store = transaction.objectStore(this[kLocation$1]);
3075
- const entries = [];
3076
-
3077
- if (!this[kOptions].reverse) {
3078
- let keys;
3079
- let values;
3080
-
3081
- const complete = () => {
3082
- // Wait for both requests to complete
3083
- if (keys === undefined || values === undefined) return
3084
-
3085
- const length = Math.max(keys.length, values.length);
3086
-
3087
- if (length === 0 || size === Infinity) {
3088
- this[kFinished] = true;
3089
- } else {
3090
- this[kPosition] = keys[length - 1];
3091
- }
3092
-
3093
- // Resize
3094
- entries.length = length;
3095
-
3096
- // Merge keys and values
3097
- for (let i = 0; i < length; i++) {
3098
- const key = keys[i];
3099
- const value = values[i];
3100
-
3101
- entries[i] = [
3102
- this[kOptions].keys && key !== undefined ? deserialize$1(key) : undefined,
3103
- this[kOptions].values && value !== undefined ? deserialize$1(value) : undefined
3104
- ];
3105
- }
3106
-
3107
- maybeCommit(transaction);
3108
- };
3109
-
3110
- // If keys were not requested and size is Infinity, we don't have to keep
3111
- // track of position and can thus skip getting keys.
3112
- if (this[kOptions].keys || size < Infinity) {
3113
- store.getAllKeys(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {
3114
- keys = ev.target.result;
3115
- complete();
3116
- };
3117
- } else {
3118
- keys = [];
3119
- this.nextTick(complete);
3120
- }
3121
-
3122
- if (this[kOptions].values) {
3123
- store.getAll(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {
3124
- values = ev.target.result;
3125
- complete();
3126
- };
3127
- } else {
3128
- values = [];
3129
- this.nextTick(complete);
3130
- }
3131
- } else {
3132
- // Can't use getAll() in reverse, so use a slower cursor that yields one item at a time
3133
- // TODO: test if all target browsers support openKeyCursor
3134
- const method = !this[kOptions].values && store.openKeyCursor ? 'openKeyCursor' : 'openCursor';
3135
-
3136
- store[method](keyRange, 'prev').onsuccess = (ev) => {
3137
- const cursor = ev.target.result;
3138
-
3139
- if (cursor) {
3140
- const { key, value } = cursor;
3141
- this[kPosition] = key;
3142
-
3143
- entries.push([
3144
- this[kOptions].keys && key !== undefined ? deserialize$1(key) : undefined,
3145
- this[kOptions].values && value !== undefined ? deserialize$1(value) : undefined
3146
- ]);
3147
-
3148
- if (entries.length < size) {
3149
- cursor.continue();
3150
- } else {
3151
- maybeCommit(transaction);
3152
- }
3153
- } else {
3154
- this[kFinished] = true;
3155
- }
3156
- };
3157
- }
3158
-
3159
- // If an error occurs (on the request), the transaction will abort.
3160
- transaction.onabort = () => {
3161
- callback(transaction.error || new Error('aborted by user'));
3162
- callback = null;
3163
- };
3164
-
3165
- transaction.oncomplete = () => {
3166
- callback(null, entries);
3167
- callback = null;
3168
- };
3169
- }
3170
-
3171
- _next (callback) {
3172
- if (this[kCache].length > 0) {
3173
- const [key, value] = this[kCache].shift();
3174
- this.nextTick(callback, null, key, value);
3175
- } else if (this[kFinished]) {
3176
- this.nextTick(callback);
3177
- } else {
3178
- let size = Math.min(100, this.limit - this.count);
3179
-
3180
- if (this[kFirst]) {
3181
- // It's common to only want one entry initially or after a seek()
3182
- this[kFirst] = false;
3183
- size = 1;
3184
- }
3185
-
3186
- this._nextv(size, emptyOptions, (err, entries) => {
3187
- if (err) return callback(err)
3188
- this[kCache] = entries;
3189
- this._next(callback);
3190
- });
3191
- }
3192
- }
3193
-
3194
- _all (options, callback) {
3195
- this[kFirst] = false;
3196
-
3197
- // TODO: mixing next and all is not covered by test suite
3198
- const cache = this[kCache].splice(0, this[kCache].length);
3199
- const size = this.limit - this.count - cache.length;
3200
-
3201
- if (size <= 0) {
3202
- return this.nextTick(callback, null, cache)
3203
- }
3204
-
3205
- this._nextv(size, emptyOptions, (err, entries) => {
3206
- if (err) return callback(err)
3207
- if (cache.length > 0) entries = cache.concat(entries);
3208
- callback(null, entries);
3209
- });
3210
- }
3211
-
3212
- _seek (target, options) {
3213
- this[kFirst] = true;
3214
- this[kCache] = [];
3215
- this[kFinished] = false;
3216
- this[kPosition] = undefined;
3217
-
3218
- // TODO: not covered by test suite
3219
- this[kCurrentOptions] = { ...this[kOptions] };
3220
-
3221
- let keyRange;
3222
-
3223
- try {
3224
- keyRange = createKeyRange$1(this[kOptions]);
3225
- } catch (_) {
3226
- this[kFinished] = true;
3227
- return
3228
- }
3229
-
3230
- if (keyRange !== null && !keyRange.includes(target)) {
3231
- this[kFinished] = true;
3232
- } else if (this[kOptions].reverse) {
3233
- this[kCurrentOptions].lte = target;
3234
- } else {
3235
- this[kCurrentOptions].gte = target;
3236
- }
3237
- }
3238
- }
3239
-
3240
- iterator.Iterator = Iterator$1;
3241
-
3242
- function maybeCommit (transaction) {
3243
- // Commit (meaning close) now instead of waiting for auto-commit
3244
- if (typeof transaction.commit === 'function') {
3245
- transaction.commit();
3246
- }
3247
- }
3248
-
3249
- var clear$1 = function clear (db, location, keyRange, options, callback) {
3250
- if (options.limit === 0) return db.nextTick(callback)
3251
-
3252
- const transaction = db.db.transaction([location], 'readwrite');
3253
- const store = transaction.objectStore(location);
3254
- let count = 0;
3255
-
3256
- transaction.oncomplete = function () {
3257
- callback();
3258
- };
3259
-
3260
- transaction.onabort = function () {
3261
- callback(transaction.error || new Error('aborted by user'));
3262
- };
3263
-
3264
- // A key cursor is faster (skips reading values) but not supported by IE
3265
- // TODO: we no longer support IE. Test others
3266
- const method = store.openKeyCursor ? 'openKeyCursor' : 'openCursor';
3267
- const direction = options.reverse ? 'prev' : 'next';
3268
-
3269
- store[method](keyRange, direction).onsuccess = function (ev) {
3270
- const cursor = ev.target.result;
3271
-
3272
- if (cursor) {
3273
- // Wait for a request to complete before continuing, saving CPU.
3274
- store.delete(cursor.key).onsuccess = function () {
3275
- if (options.limit <= 0 || ++count < options.limit) {
3276
- cursor.continue();
3277
- }
3278
- };
3279
- }
3280
- };
3281
- };
3282
-
3283
- /* global indexedDB */
3284
-
3285
- const { AbstractLevel } = abstractLevel$1;
3286
- const ModuleError = moduleError;
3287
- const parallel = runParallelLimit_1;
3288
- const { fromCallback } = catering;
3289
- const { Iterator } = iterator;
3290
- const deserialize = deserialize$2;
3291
- const clear = clear$1;
3292
- const createKeyRange = keyRange;
3293
-
3294
- // Keep as-is for compatibility with existing level-js databases
3295
- const DEFAULT_PREFIX = 'level-js-';
3296
-
3297
- const kIDB = Symbol('idb');
3298
- const kNamePrefix = Symbol('namePrefix');
3299
- const kLocation = Symbol('location');
3300
- const kVersion = Symbol('version');
3301
- const kStore = Symbol('store');
3302
- const kOnComplete = Symbol('onComplete');
3303
- const kPromise = Symbol('promise');
3304
-
3305
- class BrowserLevel extends AbstractLevel {
3306
- constructor (location, options, _) {
3307
- // To help migrating to abstract-level
3308
- if (typeof options === 'function' || typeof _ === 'function') {
3309
- throw new ModuleError('The levelup-style callback argument has been removed', {
3310
- code: 'LEVEL_LEGACY'
3311
- })
3312
- }
3313
-
3314
- const { prefix, version, ...forward } = options || {};
3315
-
3316
- super({
3317
- encodings: { view: true },
3318
- snapshots: false,
3319
- createIfMissing: false,
3320
- errorIfExists: false,
3321
- seek: true
3322
- }, forward);
3323
-
3324
- if (typeof location !== 'string') {
3325
- throw new Error('constructor requires a location string argument')
3326
- }
3327
-
3328
- // TODO (next major): remove default prefix
3329
- this[kLocation] = location;
3330
- this[kNamePrefix] = prefix == null ? DEFAULT_PREFIX : prefix;
3331
- this[kVersion] = parseInt(version || 1, 10);
3332
- this[kIDB] = null;
3333
- }
3334
-
3335
- get location () {
3336
- return this[kLocation]
3337
- }
3338
-
3339
- get namePrefix () {
3340
- return this[kNamePrefix]
3341
- }
3342
-
3343
- get version () {
3344
- return this[kVersion]
3345
- }
3346
-
3347
- // Exposed for backwards compat and unit tests
3348
- get db () {
3349
- return this[kIDB]
3350
- }
3351
-
3352
- get type () {
3353
- return 'browser-level'
3354
- }
3355
-
3356
- _open (options, callback) {
3357
- const req = indexedDB.open(this[kNamePrefix] + this[kLocation], this[kVersion]);
3358
-
3359
- req.onerror = function () {
3360
- callback(req.error || new Error('unknown error'));
3361
- };
3362
-
3363
- req.onsuccess = () => {
3364
- this[kIDB] = req.result;
3365
- callback();
3366
- };
3367
-
3368
- req.onupgradeneeded = (ev) => {
3369
- const db = ev.target.result;
3370
-
3371
- if (!db.objectStoreNames.contains(this[kLocation])) {
3372
- db.createObjectStore(this[kLocation]);
3373
- }
3374
- };
3375
- }
3376
-
3377
- [kStore] (mode) {
3378
- const transaction = this[kIDB].transaction([this[kLocation]], mode);
3379
- return transaction.objectStore(this[kLocation])
3380
- }
3381
-
3382
- [kOnComplete] (request, callback) {
3383
- const transaction = request.transaction;
3384
-
3385
- // Take advantage of the fact that a non-canceled request error aborts
3386
- // the transaction. I.e. no need to listen for "request.onerror".
3387
- transaction.onabort = function () {
3388
- callback(transaction.error || new Error('aborted by user'));
3389
- };
3390
-
3391
- transaction.oncomplete = function () {
3392
- callback(null, request.result);
3393
- };
3394
- }
3395
-
3396
- _get (key, options, callback) {
3397
- const store = this[kStore]('readonly');
3398
- let req;
3399
-
3400
- try {
3401
- req = store.get(key);
3402
- } catch (err) {
3403
- return this.nextTick(callback, err)
3404
- }
3405
-
3406
- this[kOnComplete](req, function (err, value) {
3407
- if (err) return callback(err)
3408
-
3409
- if (value === undefined) {
3410
- return callback(new ModuleError('Entry not found', {
3411
- code: 'LEVEL_NOT_FOUND'
3412
- }))
3413
- }
3414
-
3415
- callback(null, deserialize(value));
3416
- });
3417
- }
3418
-
3419
- _getMany (keys, options, callback) {
3420
- const store = this[kStore]('readonly');
3421
- const tasks = keys.map((key) => (next) => {
3422
- let request;
3423
-
3424
- try {
3425
- request = store.get(key);
3426
- } catch (err) {
3427
- return next(err)
3428
- }
3429
-
3430
- request.onsuccess = () => {
3431
- const value = request.result;
3432
- next(null, value === undefined ? value : deserialize(value));
3433
- };
3434
-
3435
- request.onerror = (ev) => {
3436
- ev.stopPropagation();
3437
- next(request.error);
3438
- };
3439
- });
3440
-
3441
- parallel(tasks, 16, callback);
3442
- }
3443
-
3444
- _del (key, options, callback) {
3445
- const store = this[kStore]('readwrite');
3446
- let req;
3447
-
3448
- try {
3449
- req = store.delete(key);
3450
- } catch (err) {
3451
- return this.nextTick(callback, err)
3452
- }
3453
-
3454
- this[kOnComplete](req, callback);
3455
- }
3456
-
3457
- _put (key, value, options, callback) {
3458
- const store = this[kStore]('readwrite');
3459
- let req;
3460
-
3461
- try {
3462
- // Will throw a DataError or DataCloneError if the environment
3463
- // does not support serializing the key or value respectively.
3464
- req = store.put(value, key);
3465
- } catch (err) {
3466
- return this.nextTick(callback, err)
3467
- }
3468
-
3469
- this[kOnComplete](req, callback);
3470
- }
3471
-
3472
- // TODO: implement key and value iterators
3473
- _iterator (options) {
3474
- return new Iterator(this, this[kLocation], options)
3475
- }
3476
-
3477
- _batch (operations, options, callback) {
3478
- const store = this[kStore]('readwrite');
3479
- const transaction = store.transaction;
3480
- let index = 0;
3481
- let error;
3482
-
3483
- transaction.onabort = function () {
3484
- callback(error || transaction.error || new Error('aborted by user'));
3485
- };
3486
-
3487
- transaction.oncomplete = function () {
3488
- callback();
3489
- };
3490
-
3491
- // Wait for a request to complete before making the next, saving CPU.
3492
- function loop () {
3493
- const op = operations[index++];
3494
- const key = op.key;
3495
-
3496
- let req;
3497
-
3498
- try {
3499
- req = op.type === 'del' ? store.delete(key) : store.put(op.value, key);
3500
- } catch (err) {
3501
- error = err;
3502
- transaction.abort();
3503
- return
3504
- }
3505
-
3506
- if (index < operations.length) {
3507
- req.onsuccess = loop;
3508
- } else if (typeof transaction.commit === 'function') {
3509
- // Commit now instead of waiting for auto-commit
3510
- transaction.commit();
3511
- }
3512
- }
3513
-
3514
- loop();
3515
- }
3516
-
3517
- _clear (options, callback) {
3518
- let keyRange;
3519
- let req;
3520
-
3521
- try {
3522
- keyRange = createKeyRange(options);
3523
- } catch (e) {
3524
- // The lower key is greater than the upper key.
3525
- // IndexedDB throws an error, but we'll just do nothing.
3526
- return this.nextTick(callback)
3527
- }
3528
-
3529
- if (options.limit >= 0) {
3530
- // IDBObjectStore#delete(range) doesn't have such an option.
3531
- // Fall back to cursor-based implementation.
3532
- return clear(this, this[kLocation], keyRange, options, callback)
3533
- }
3534
-
3535
- try {
3536
- const store = this[kStore]('readwrite');
3537
- req = keyRange ? store.delete(keyRange) : store.clear();
3538
- } catch (err) {
3539
- return this.nextTick(callback, err)
3540
- }
3541
-
3542
- this[kOnComplete](req, callback);
3543
- }
3544
-
3545
- _close (callback) {
3546
- this[kIDB].close();
3547
- this.nextTick(callback);
3548
- }
3549
- }
3550
-
3551
- BrowserLevel.destroy = function (location, prefix, callback) {
3552
- if (typeof prefix === 'function') {
3553
- callback = prefix;
3554
- prefix = DEFAULT_PREFIX;
3555
- }
3556
-
3557
- callback = fromCallback(callback, kPromise);
3558
- const request = indexedDB.deleteDatabase(prefix + location);
3559
-
3560
- request.onsuccess = function () {
3561
- callback();
3562
- };
3563
-
3564
- request.onerror = function (err) {
3565
- callback(err);
3566
- };
3567
-
3568
- return callback[kPromise]
3569
- };
3570
-
3571
- var BrowserLevel_1 = BrowserLevel;
3572
-
3573
- class Store {
3574
- constructor(name = 'storage', root, version = 'v1.0.0') {
3575
- this.name = name;
3576
- this.root = root;
3577
- this.version = version;
3578
-
3579
- this.db = new BrowserLevel_1(
3580
- this.name,
3581
- { valueEncoding: 'view'}
3582
- );
3583
- }
3584
-
3585
- toKeyPath(key) {
3586
- return key ? key.toString('base32') : key
3587
- }
3588
-
3589
- toKeyValue(value) {
3590
- return value.uint8Array
3591
- }
3592
-
3593
- async get(key) {
3594
- return this.db.get(this.toKeyPath(key))
3595
- }
3596
-
3597
- async put(key, value) {
3598
- return this.db.put(this.toKeyPath(key), this.toKeyValue(value))
3599
- }
3600
-
3601
- async delete(key) {
3602
- return this.db.del(this.toKeyPath(key))
3603
- }
3604
-
3605
- async clear() {
3606
- return this.db.clear()
3607
- }
3608
-
3609
- async values(limit = -1) {
3610
- const values = [];
3611
- for await (const value of this.db.values({limit})) {
3612
- values.push(value);
3613
- }
3614
- return values
3615
- }
3616
-
3617
- async keys(limit = -1) {
3618
- const keys = [];
3619
- for await (const key of this.db.keys({limit})) {
3620
- keys.push(key);
3621
- }
3622
- return keys
3623
- }
3624
-
3625
- }
3626
-
3627
- class LeofcoinStorage {
3628
-
3629
- constructor(name = 'storage', root = '.leofcoin') {
3630
- this.name = name;
3631
- this.db = new Store(name, root);
3632
- }
3633
-
3634
- async get(key) {
3635
- if (!key) return this.query()
3636
- if (typeof key === 'object') return this.many('get', key);
3637
- return this.db.get(new KeyPath(key))
3638
- }
3639
-
3640
- /**
3641
- *
3642
- * @param {*} key
3643
- * @param {*} value
3644
- * @returns Promise
3645
- */
3646
- put(key, value) {
3647
- if (typeof key === 'object') return this.many('put', key);
3648
- return this.db.put(new KeyPath(key), new KeyValue(value));
3649
- }
3650
-
3651
- async has(key) {
3652
- if (typeof key === 'object') return this.many('has', key);
3653
-
3654
- try {
3655
- const has = await this.db.get(new KeyPath(key));
3656
-
3657
- return Boolean(has);
3658
- } catch (e) {
3659
- return false
3660
- }
3661
- }
3662
-
3663
- async delete(key) {
3664
- return this.db.delete(new KeyPath(key))
3665
- }
3666
-
3667
- keys(limit = -1) {
3668
- return this.db.keys({limit})
3669
- }
3670
-
3671
- async #queryJob(key) {
3672
- const value = await this.db.get(key);
3673
- return { key, value }
3674
- }
3675
-
3676
- async query() {
3677
- const keys = await this.keys();
3678
- let promises = [];
3679
- for (const key of keys) {
3680
- promises.push(this.#queryJob(key));
3681
- }
3682
- return Promise.all(promises)
3683
- }
3684
-
3685
- async values(limit = -1) {
3686
- return this.db.values({limit})
3687
- }
3688
-
3689
- async many(type, _value) {
3690
- const jobs = [];
3691
-
3692
- for (const key of Object.keys(_value)) {
3693
- jobs.push(this[type](key, _value[key]));
3694
- }
3695
-
3696
- return Promise.all(jobs)
3697
- }
3698
-
3699
- async length() {
3700
- const keys = await this.keys();
3701
- return keys.length
3702
- }
3703
-
3704
- async size() {
3705
- let size = 0;
3706
- const query = await this.query();
3707
- for (const item of query) {
3708
- size += item.value.length;
3709
- }
3710
- return size
3711
- }
3712
-
3713
- async clear() {
3714
- return this.db.clear()
3715
- }
3716
-
3717
- }
3718
-
3719
-
3720
-
3721
-
3722
- /***/ })
3723
-
3724
- }])