@fireproof/core 0.6.3-dev2 → 0.6.4

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,8 +1,5 @@
1
1
  'use strict';
2
2
 
3
- var node_fs = require('node:fs');
4
- var promises = require('node:fs/promises');
5
-
6
3
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
7
4
 
8
5
  function getDefaultExportFromCjs (x) {
@@ -8146,6 +8143,267 @@ var raw = /*#__PURE__*/Object.freeze({
8146
8143
  name: name$2
8147
8144
  });
8148
8145
 
8146
+ const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);
8147
+
8148
+ let idbProxyableTypes;
8149
+ let cursorAdvanceMethods;
8150
+ // This is a function to prevent it throwing up in node environments.
8151
+ function getIdbProxyableTypes() {
8152
+ return (idbProxyableTypes ||
8153
+ (idbProxyableTypes = [
8154
+ IDBDatabase,
8155
+ IDBObjectStore,
8156
+ IDBIndex,
8157
+ IDBCursor,
8158
+ IDBTransaction,
8159
+ ]));
8160
+ }
8161
+ // This is a function to prevent it throwing up in node environments.
8162
+ function getCursorAdvanceMethods() {
8163
+ return (cursorAdvanceMethods ||
8164
+ (cursorAdvanceMethods = [
8165
+ IDBCursor.prototype.advance,
8166
+ IDBCursor.prototype.continue,
8167
+ IDBCursor.prototype.continuePrimaryKey,
8168
+ ]));
8169
+ }
8170
+ const cursorRequestMap = new WeakMap();
8171
+ const transactionDoneMap = new WeakMap();
8172
+ const transactionStoreNamesMap = new WeakMap();
8173
+ const transformCache = new WeakMap();
8174
+ const reverseTransformCache = new WeakMap();
8175
+ function promisifyRequest(request) {
8176
+ const promise = new Promise((resolve, reject) => {
8177
+ const unlisten = () => {
8178
+ request.removeEventListener('success', success);
8179
+ request.removeEventListener('error', error);
8180
+ };
8181
+ const success = () => {
8182
+ resolve(wrap$1(request.result));
8183
+ unlisten();
8184
+ };
8185
+ const error = () => {
8186
+ reject(request.error);
8187
+ unlisten();
8188
+ };
8189
+ request.addEventListener('success', success);
8190
+ request.addEventListener('error', error);
8191
+ });
8192
+ promise
8193
+ .then((value) => {
8194
+ // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval
8195
+ // (see wrapFunction).
8196
+ if (value instanceof IDBCursor) {
8197
+ cursorRequestMap.set(value, request);
8198
+ }
8199
+ // Catching to avoid "Uncaught Promise exceptions"
8200
+ })
8201
+ .catch(() => { });
8202
+ // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
8203
+ // is because we create many promises from a single IDBRequest.
8204
+ reverseTransformCache.set(promise, request);
8205
+ return promise;
8206
+ }
8207
+ function cacheDonePromiseForTransaction(tx) {
8208
+ // Early bail if we've already created a done promise for this transaction.
8209
+ if (transactionDoneMap.has(tx))
8210
+ return;
8211
+ const done = new Promise((resolve, reject) => {
8212
+ const unlisten = () => {
8213
+ tx.removeEventListener('complete', complete);
8214
+ tx.removeEventListener('error', error);
8215
+ tx.removeEventListener('abort', error);
8216
+ };
8217
+ const complete = () => {
8218
+ resolve();
8219
+ unlisten();
8220
+ };
8221
+ const error = () => {
8222
+ reject(tx.error || new DOMException('AbortError', 'AbortError'));
8223
+ unlisten();
8224
+ };
8225
+ tx.addEventListener('complete', complete);
8226
+ tx.addEventListener('error', error);
8227
+ tx.addEventListener('abort', error);
8228
+ });
8229
+ // Cache it for later retrieval.
8230
+ transactionDoneMap.set(tx, done);
8231
+ }
8232
+ let idbProxyTraps = {
8233
+ get(target, prop, receiver) {
8234
+ if (target instanceof IDBTransaction) {
8235
+ // Special handling for transaction.done.
8236
+ if (prop === 'done')
8237
+ return transactionDoneMap.get(target);
8238
+ // Polyfill for objectStoreNames because of Edge.
8239
+ if (prop === 'objectStoreNames') {
8240
+ return target.objectStoreNames || transactionStoreNamesMap.get(target);
8241
+ }
8242
+ // Make tx.store return the only store in the transaction, or undefined if there are many.
8243
+ if (prop === 'store') {
8244
+ return receiver.objectStoreNames[1]
8245
+ ? undefined
8246
+ : receiver.objectStore(receiver.objectStoreNames[0]);
8247
+ }
8248
+ }
8249
+ // Else transform whatever we get back.
8250
+ return wrap$1(target[prop]);
8251
+ },
8252
+ set(target, prop, value) {
8253
+ target[prop] = value;
8254
+ return true;
8255
+ },
8256
+ has(target, prop) {
8257
+ if (target instanceof IDBTransaction &&
8258
+ (prop === 'done' || prop === 'store')) {
8259
+ return true;
8260
+ }
8261
+ return prop in target;
8262
+ },
8263
+ };
8264
+ function replaceTraps(callback) {
8265
+ idbProxyTraps = callback(idbProxyTraps);
8266
+ }
8267
+ function wrapFunction(func) {
8268
+ // Due to expected object equality (which is enforced by the caching in `wrap`), we
8269
+ // only create one new func per func.
8270
+ // Edge doesn't support objectStoreNames (booo), so we polyfill it here.
8271
+ if (func === IDBDatabase.prototype.transaction &&
8272
+ !('objectStoreNames' in IDBTransaction.prototype)) {
8273
+ return function (storeNames, ...args) {
8274
+ const tx = func.call(unwrap(this), storeNames, ...args);
8275
+ transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
8276
+ return wrap$1(tx);
8277
+ };
8278
+ }
8279
+ // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
8280
+ // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
8281
+ // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
8282
+ // with real promises, so each advance methods returns a new promise for the cursor object, or
8283
+ // undefined if the end of the cursor has been reached.
8284
+ if (getCursorAdvanceMethods().includes(func)) {
8285
+ return function (...args) {
8286
+ // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
8287
+ // the original object.
8288
+ func.apply(unwrap(this), args);
8289
+ return wrap$1(cursorRequestMap.get(this));
8290
+ };
8291
+ }
8292
+ return function (...args) {
8293
+ // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
8294
+ // the original object.
8295
+ return wrap$1(func.apply(unwrap(this), args));
8296
+ };
8297
+ }
8298
+ function transformCachableValue(value) {
8299
+ if (typeof value === 'function')
8300
+ return wrapFunction(value);
8301
+ // This doesn't return, it just creates a 'done' promise for the transaction,
8302
+ // which is later returned for transaction.done (see idbObjectHandler).
8303
+ if (value instanceof IDBTransaction)
8304
+ cacheDonePromiseForTransaction(value);
8305
+ if (instanceOfAny(value, getIdbProxyableTypes()))
8306
+ return new Proxy(value, idbProxyTraps);
8307
+ // Return the same value back if we're not going to transform it.
8308
+ return value;
8309
+ }
8310
+ function wrap$1(value) {
8311
+ // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
8312
+ // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
8313
+ if (value instanceof IDBRequest)
8314
+ return promisifyRequest(value);
8315
+ // If we've already transformed this value before, reuse the transformed value.
8316
+ // This is faster, but it also provides object equality.
8317
+ if (transformCache.has(value))
8318
+ return transformCache.get(value);
8319
+ const newValue = transformCachableValue(value);
8320
+ // Not all types are transformed.
8321
+ // These may be primitive types, so they can't be WeakMap keys.
8322
+ if (newValue !== value) {
8323
+ transformCache.set(value, newValue);
8324
+ reverseTransformCache.set(newValue, value);
8325
+ }
8326
+ return newValue;
8327
+ }
8328
+ const unwrap = (value) => reverseTransformCache.get(value);
8329
+
8330
+ /**
8331
+ * Open a database.
8332
+ *
8333
+ * @param name Name of the database.
8334
+ * @param version Schema version.
8335
+ * @param callbacks Additional callbacks.
8336
+ */
8337
+ function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {
8338
+ const request = indexedDB.open(name, version);
8339
+ const openPromise = wrap$1(request);
8340
+ if (upgrade) {
8341
+ request.addEventListener('upgradeneeded', (event) => {
8342
+ upgrade(wrap$1(request.result), event.oldVersion, event.newVersion, wrap$1(request.transaction), event);
8343
+ });
8344
+ }
8345
+ if (blocked) {
8346
+ request.addEventListener('blocked', (event) => blocked(
8347
+ // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
8348
+ event.oldVersion, event.newVersion, event));
8349
+ }
8350
+ openPromise
8351
+ .then((db) => {
8352
+ if (terminated)
8353
+ db.addEventListener('close', () => terminated());
8354
+ if (blocking) {
8355
+ db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));
8356
+ }
8357
+ })
8358
+ .catch(() => { });
8359
+ return openPromise;
8360
+ }
8361
+
8362
+ const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
8363
+ const writeMethods = ['put', 'add', 'delete', 'clear'];
8364
+ const cachedMethods = new Map();
8365
+ function getMethod(target, prop) {
8366
+ if (!(target instanceof IDBDatabase &&
8367
+ !(prop in target) &&
8368
+ typeof prop === 'string')) {
8369
+ return;
8370
+ }
8371
+ if (cachedMethods.get(prop))
8372
+ return cachedMethods.get(prop);
8373
+ const targetFuncName = prop.replace(/FromIndex$/, '');
8374
+ const useIndex = prop !== targetFuncName;
8375
+ const isWrite = writeMethods.includes(targetFuncName);
8376
+ if (
8377
+ // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
8378
+ !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||
8379
+ !(isWrite || readMethods.includes(targetFuncName))) {
8380
+ return;
8381
+ }
8382
+ const method = async function (storeName, ...args) {
8383
+ // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
8384
+ const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
8385
+ let target = tx.store;
8386
+ if (useIndex)
8387
+ target = target.index(args.shift());
8388
+ // Must reject if op rejects.
8389
+ // If it's a write operation, must reject if tx.done rejects.
8390
+ // Must reject with op rejection first.
8391
+ // Must resolve with op value.
8392
+ // Must handle both promises (no unhandled rejections)
8393
+ return (await Promise.all([
8394
+ target[targetFuncName](...args),
8395
+ isWrite && tx.done,
8396
+ ]))[0];
8397
+ };
8398
+ cachedMethods.set(prop, method);
8399
+ return method;
8400
+ }
8401
+ replaceTraps((oldTraps) => ({
8402
+ ...oldTraps,
8403
+ get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
8404
+ has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),
8405
+ }));
8406
+
8149
8407
  var cargoQueueExports = {};
8150
8408
  var cargoQueue$1 = {
8151
8409
  get exports(){ return cargoQueueExports; },
@@ -8187,7 +8445,7 @@ Object.defineProperty(setImmediate$1, "__esModule", {
8187
8445
  value: true
8188
8446
  });
8189
8447
  setImmediate$1.fallback = fallback;
8190
- setImmediate$1.wrap = wrap$1;
8448
+ setImmediate$1.wrap = wrap;
8191
8449
  /* istanbul ignore file */
8192
8450
 
8193
8451
  var hasQueueMicrotask = setImmediate$1.hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask;
@@ -8198,7 +8456,7 @@ function fallback(fn) {
8198
8456
  setTimeout(fn, 0);
8199
8457
  }
8200
8458
 
8201
- function wrap$1(defer) {
8459
+ function wrap(defer) {
8202
8460
  return (fn, ...args) => defer(() => fn(...args));
8203
8461
  }
8204
8462
 
@@ -8214,7 +8472,7 @@ if (hasQueueMicrotask) {
8214
8472
  _defer = fallback;
8215
8473
  }
8216
8474
 
8217
- setImmediate$1.default = wrap$1(_defer);
8475
+ setImmediate$1.default = wrap(_defer);
8218
8476
 
8219
8477
  var DoublyLinkedListExports = {};
8220
8478
  var DoublyLinkedList = {
@@ -8885,559 +9143,6 @@ function requireWrapAsync () {
8885
9143
 
8886
9144
  var cargoQueue = /*@__PURE__*/getDefaultExportFromCjs(cargoQueueExports);
8887
9145
 
8888
- const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);
8889
-
8890
- let idbProxyableTypes;
8891
- let cursorAdvanceMethods;
8892
- // This is a function to prevent it throwing up in node environments.
8893
- function getIdbProxyableTypes() {
8894
- return (idbProxyableTypes ||
8895
- (idbProxyableTypes = [
8896
- IDBDatabase,
8897
- IDBObjectStore,
8898
- IDBIndex,
8899
- IDBCursor,
8900
- IDBTransaction,
8901
- ]));
8902
- }
8903
- // This is a function to prevent it throwing up in node environments.
8904
- function getCursorAdvanceMethods() {
8905
- return (cursorAdvanceMethods ||
8906
- (cursorAdvanceMethods = [
8907
- IDBCursor.prototype.advance,
8908
- IDBCursor.prototype.continue,
8909
- IDBCursor.prototype.continuePrimaryKey,
8910
- ]));
8911
- }
8912
- const cursorRequestMap = new WeakMap();
8913
- const transactionDoneMap = new WeakMap();
8914
- const transactionStoreNamesMap = new WeakMap();
8915
- const transformCache = new WeakMap();
8916
- const reverseTransformCache = new WeakMap();
8917
- function promisifyRequest(request) {
8918
- const promise = new Promise((resolve, reject) => {
8919
- const unlisten = () => {
8920
- request.removeEventListener('success', success);
8921
- request.removeEventListener('error', error);
8922
- };
8923
- const success = () => {
8924
- resolve(wrap(request.result));
8925
- unlisten();
8926
- };
8927
- const error = () => {
8928
- reject(request.error);
8929
- unlisten();
8930
- };
8931
- request.addEventListener('success', success);
8932
- request.addEventListener('error', error);
8933
- });
8934
- promise
8935
- .then((value) => {
8936
- // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval
8937
- // (see wrapFunction).
8938
- if (value instanceof IDBCursor) {
8939
- cursorRequestMap.set(value, request);
8940
- }
8941
- // Catching to avoid "Uncaught Promise exceptions"
8942
- })
8943
- .catch(() => { });
8944
- // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
8945
- // is because we create many promises from a single IDBRequest.
8946
- reverseTransformCache.set(promise, request);
8947
- return promise;
8948
- }
8949
- function cacheDonePromiseForTransaction(tx) {
8950
- // Early bail if we've already created a done promise for this transaction.
8951
- if (transactionDoneMap.has(tx))
8952
- return;
8953
- const done = new Promise((resolve, reject) => {
8954
- const unlisten = () => {
8955
- tx.removeEventListener('complete', complete);
8956
- tx.removeEventListener('error', error);
8957
- tx.removeEventListener('abort', error);
8958
- };
8959
- const complete = () => {
8960
- resolve();
8961
- unlisten();
8962
- };
8963
- const error = () => {
8964
- reject(tx.error || new DOMException('AbortError', 'AbortError'));
8965
- unlisten();
8966
- };
8967
- tx.addEventListener('complete', complete);
8968
- tx.addEventListener('error', error);
8969
- tx.addEventListener('abort', error);
8970
- });
8971
- // Cache it for later retrieval.
8972
- transactionDoneMap.set(tx, done);
8973
- }
8974
- let idbProxyTraps = {
8975
- get(target, prop, receiver) {
8976
- if (target instanceof IDBTransaction) {
8977
- // Special handling for transaction.done.
8978
- if (prop === 'done')
8979
- return transactionDoneMap.get(target);
8980
- // Polyfill for objectStoreNames because of Edge.
8981
- if (prop === 'objectStoreNames') {
8982
- return target.objectStoreNames || transactionStoreNamesMap.get(target);
8983
- }
8984
- // Make tx.store return the only store in the transaction, or undefined if there are many.
8985
- if (prop === 'store') {
8986
- return receiver.objectStoreNames[1]
8987
- ? undefined
8988
- : receiver.objectStore(receiver.objectStoreNames[0]);
8989
- }
8990
- }
8991
- // Else transform whatever we get back.
8992
- return wrap(target[prop]);
8993
- },
8994
- set(target, prop, value) {
8995
- target[prop] = value;
8996
- return true;
8997
- },
8998
- has(target, prop) {
8999
- if (target instanceof IDBTransaction &&
9000
- (prop === 'done' || prop === 'store')) {
9001
- return true;
9002
- }
9003
- return prop in target;
9004
- },
9005
- };
9006
- function replaceTraps(callback) {
9007
- idbProxyTraps = callback(idbProxyTraps);
9008
- }
9009
- function wrapFunction(func) {
9010
- // Due to expected object equality (which is enforced by the caching in `wrap`), we
9011
- // only create one new func per func.
9012
- // Edge doesn't support objectStoreNames (booo), so we polyfill it here.
9013
- if (func === IDBDatabase.prototype.transaction &&
9014
- !('objectStoreNames' in IDBTransaction.prototype)) {
9015
- return function (storeNames, ...args) {
9016
- const tx = func.call(unwrap(this), storeNames, ...args);
9017
- transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
9018
- return wrap(tx);
9019
- };
9020
- }
9021
- // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
9022
- // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
9023
- // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
9024
- // with real promises, so each advance methods returns a new promise for the cursor object, or
9025
- // undefined if the end of the cursor has been reached.
9026
- if (getCursorAdvanceMethods().includes(func)) {
9027
- return function (...args) {
9028
- // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
9029
- // the original object.
9030
- func.apply(unwrap(this), args);
9031
- return wrap(cursorRequestMap.get(this));
9032
- };
9033
- }
9034
- return function (...args) {
9035
- // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
9036
- // the original object.
9037
- return wrap(func.apply(unwrap(this), args));
9038
- };
9039
- }
9040
- function transformCachableValue(value) {
9041
- if (typeof value === 'function')
9042
- return wrapFunction(value);
9043
- // This doesn't return, it just creates a 'done' promise for the transaction,
9044
- // which is later returned for transaction.done (see idbObjectHandler).
9045
- if (value instanceof IDBTransaction)
9046
- cacheDonePromiseForTransaction(value);
9047
- if (instanceOfAny(value, getIdbProxyableTypes()))
9048
- return new Proxy(value, idbProxyTraps);
9049
- // Return the same value back if we're not going to transform it.
9050
- return value;
9051
- }
9052
- function wrap(value) {
9053
- // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
9054
- // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
9055
- if (value instanceof IDBRequest)
9056
- return promisifyRequest(value);
9057
- // If we've already transformed this value before, reuse the transformed value.
9058
- // This is faster, but it also provides object equality.
9059
- if (transformCache.has(value))
9060
- return transformCache.get(value);
9061
- const newValue = transformCachableValue(value);
9062
- // Not all types are transformed.
9063
- // These may be primitive types, so they can't be WeakMap keys.
9064
- if (newValue !== value) {
9065
- transformCache.set(value, newValue);
9066
- reverseTransformCache.set(newValue, value);
9067
- }
9068
- return newValue;
9069
- }
9070
- const unwrap = (value) => reverseTransformCache.get(value);
9071
-
9072
- /**
9073
- * Open a database.
9074
- *
9075
- * @param name Name of the database.
9076
- * @param version Schema version.
9077
- * @param callbacks Additional callbacks.
9078
- */
9079
- function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {
9080
- const request = indexedDB.open(name, version);
9081
- const openPromise = wrap(request);
9082
- if (upgrade) {
9083
- request.addEventListener('upgradeneeded', (event) => {
9084
- upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
9085
- });
9086
- }
9087
- if (blocked) {
9088
- request.addEventListener('blocked', (event) => blocked(
9089
- // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
9090
- event.oldVersion, event.newVersion, event));
9091
- }
9092
- openPromise
9093
- .then((db) => {
9094
- if (terminated)
9095
- db.addEventListener('close', () => terminated());
9096
- if (blocking) {
9097
- db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));
9098
- }
9099
- })
9100
- .catch(() => { });
9101
- return openPromise;
9102
- }
9103
-
9104
- const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
9105
- const writeMethods = ['put', 'add', 'delete', 'clear'];
9106
- const cachedMethods = new Map();
9107
- function getMethod(target, prop) {
9108
- if (!(target instanceof IDBDatabase &&
9109
- !(prop in target) &&
9110
- typeof prop === 'string')) {
9111
- return;
9112
- }
9113
- if (cachedMethods.get(prop))
9114
- return cachedMethods.get(prop);
9115
- const targetFuncName = prop.replace(/FromIndex$/, '');
9116
- const useIndex = prop !== targetFuncName;
9117
- const isWrite = writeMethods.includes(targetFuncName);
9118
- if (
9119
- // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
9120
- !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||
9121
- !(isWrite || readMethods.includes(targetFuncName))) {
9122
- return;
9123
- }
9124
- const method = async function (storeName, ...args) {
9125
- // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
9126
- const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
9127
- let target = tx.store;
9128
- if (useIndex)
9129
- target = target.index(args.shift());
9130
- // Must reject if op rejects.
9131
- // If it's a write operation, must reject if tx.done rejects.
9132
- // Must reject with op rejection first.
9133
- // Must resolve with op value.
9134
- // Must handle both promises (no unhandled rejections)
9135
- return (await Promise.all([
9136
- target[targetFuncName](...args),
9137
- isWrite && tx.done,
9138
- ]))[0];
9139
- };
9140
- cachedMethods.set(prop, method);
9141
- return method;
9142
- }
9143
- replaceTraps((oldTraps) => ({
9144
- ...oldTraps,
9145
- get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
9146
- has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),
9147
- }));
9148
-
9149
- // Copyright Joyent, Inc. and other Node contributors.
9150
- //
9151
- // Permission is hereby granted, free of charge, to any person obtaining a
9152
- // copy of this software and associated documentation files (the
9153
- // "Software"), to deal in the Software without restriction, including
9154
- // without limitation the rights to use, copy, modify, merge, publish,
9155
- // distribute, sublicense, and/or sell copies of the Software, and to permit
9156
- // persons to whom the Software is furnished to do so, subject to the
9157
- // following conditions:
9158
- //
9159
- // The above copyright notice and this permission notice shall be included
9160
- // in all copies or substantial portions of the Software.
9161
- //
9162
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
9163
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
9164
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
9165
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
9166
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
9167
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
9168
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
9169
-
9170
- // resolves . and .. elements in a path array with directory names there
9171
- // must be no slashes, empty elements, or device names (c:\) in the array
9172
- // (so also no leading and trailing slashes - it does not distinguish
9173
- // relative and absolute paths)
9174
- function normalizeArray(parts, allowAboveRoot) {
9175
- // if the path tries to go above the root, `up` ends up > 0
9176
- var up = 0;
9177
- for (var i = parts.length - 1; i >= 0; i--) {
9178
- var last = parts[i];
9179
- if (last === '.') {
9180
- parts.splice(i, 1);
9181
- } else if (last === '..') {
9182
- parts.splice(i, 1);
9183
- up++;
9184
- } else if (up) {
9185
- parts.splice(i, 1);
9186
- up--;
9187
- }
9188
- }
9189
-
9190
- // if the path is allowed to go above the root, restore leading ..s
9191
- if (allowAboveRoot) {
9192
- for (; up--; up) {
9193
- parts.unshift('..');
9194
- }
9195
- }
9196
-
9197
- return parts;
9198
- }
9199
-
9200
- // Split a filename into [root, dir, basename, ext], unix version
9201
- // 'root' is just a slash, or nothing.
9202
- var splitPathRe =
9203
- /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
9204
- var splitPath = function(filename) {
9205
- return splitPathRe.exec(filename).slice(1);
9206
- };
9207
-
9208
- // path.normalize(path)
9209
- // posix version
9210
- function normalize(path) {
9211
- var isPathAbsolute = isAbsolute(path),
9212
- trailingSlash = substr(path, -1) === '/';
9213
-
9214
- // Normalize the path
9215
- path = normalizeArray(filter(path.split('/'), function(p) {
9216
- return !!p;
9217
- }), !isPathAbsolute).join('/');
9218
-
9219
- if (!path && !isPathAbsolute) {
9220
- path = '.';
9221
- }
9222
- if (path && trailingSlash) {
9223
- path += '/';
9224
- }
9225
-
9226
- return (isPathAbsolute ? '/' : '') + path;
9227
- }
9228
- // posix version
9229
- function isAbsolute(path) {
9230
- return path.charAt(0) === '/';
9231
- }
9232
-
9233
- // posix version
9234
- function join() {
9235
- var paths = Array.prototype.slice.call(arguments, 0);
9236
- return normalize(filter(paths, function(p, index) {
9237
- if (typeof p !== 'string') {
9238
- throw new TypeError('Arguments to path.join must be strings');
9239
- }
9240
- return p;
9241
- }).join('/'));
9242
- }
9243
-
9244
- function dirname(path) {
9245
- var result = splitPath(path),
9246
- root = result[0],
9247
- dir = result[1];
9248
-
9249
- if (!root && !dir) {
9250
- // No dirname whatsoever
9251
- return '.';
9252
- }
9253
-
9254
- if (dir) {
9255
- // It has a dirname, strip trailing slash
9256
- dir = dir.substr(0, dir.length - 1);
9257
- }
9258
-
9259
- return root + dir;
9260
- }
9261
- function filter (xs, f) {
9262
- if (xs.filter) return xs.filter(f);
9263
- var res = [];
9264
- for (var i = 0; i < xs.length; i++) {
9265
- if (f(xs[i], i, xs)) res.push(xs[i]);
9266
- }
9267
- return res;
9268
- }
9269
-
9270
- // String.prototype.substr - negative index don't work in IE8
9271
- var substr = 'ab'.substr(-1) === 'b' ?
9272
- function (str, start, len) { return str.substr(start, len) } :
9273
- function (str, start, len) {
9274
- if (start < 0) start = str.length + start;
9275
- return str.substr(start, len);
9276
- }
9277
- ;
9278
-
9279
- function homedir(){
9280
- return '$HOME'
9281
- }
9282
-
9283
- const defaultConfig = {
9284
- dataDir: join(homedir(), '.fireproof'),
9285
- headerKeyPrefix: 'fp.'
9286
- };
9287
-
9288
- const FORCE_IDB = typeof process !== 'undefined' && !!process.env?.FORCE_IDB;
9289
-
9290
- /* global localStorage */
9291
-
9292
- class Loader {
9293
- constructor (name, keyId, config = defaultConfig) {
9294
- this.name = name;
9295
- this.keyId = keyId;
9296
- this.config = config;
9297
- this.isBrowser = false;
9298
- try {
9299
- this.isBrowser = window.localStorage && true;
9300
- } catch (e) {}
9301
- }
9302
-
9303
- withDB = async (dbWorkFun) => {
9304
- if (!this.idb) {
9305
- this.idb = await openDB(`fp.${this.keyId}.${this.name}.valet`, 3, {
9306
- upgrade (db, oldVersion, newVersion, transaction) {
9307
- if (oldVersion < 1) {
9308
- db.createObjectStore('cars');
9309
- }
9310
- }
9311
- });
9312
- }
9313
- return await dbWorkFun(this.idb)
9314
- }
9315
-
9316
- async writeCars (cars) {
9317
- // console.log('writeCars', this.config.dataDir, this.name, cars.map(c => c.cid.toString()))
9318
- // console.log('writeCars', cars.length)
9319
-
9320
- if (FORCE_IDB || this.isBrowser) {
9321
- await this.writeCarsIDB(cars);
9322
- } else {
9323
- const writes = [];
9324
- for (const { cid, bytes } of cars) {
9325
- const carFilename = join(this.config.dataDir, this.name, `${cid.toString()}.car`);
9326
- // console.log('writeCars', carFilename)
9327
- writes.push(writeSync(carFilename, bytes));
9328
- }
9329
- await Promise.all(writes);
9330
- }
9331
- }
9332
-
9333
- async writeCarsIDB (cars) {
9334
- return await this.withDB(async db => {
9335
- const tx = db.transaction(['cars'], 'readwrite');
9336
- for (const { cid, bytes, replaces } of cars) {
9337
- await tx.objectStore('cars').put(bytes, cid.toString());
9338
- // todo remove old maps
9339
- if (replaces) {
9340
- await tx.objectStore('cars').delete(replaces.toString());
9341
- }
9342
- }
9343
- return await tx.done
9344
- })
9345
- }
9346
-
9347
- async readCar (carCid) {
9348
- if (FORCE_IDB || this.isBrowser) {
9349
- return await this.readCarIDB(carCid)
9350
- } else {
9351
- const carFilename = join(this.config.dataDir, this.name, `${carCid.toString()}.car`);
9352
- const got = node_fs.readFileSync(carFilename);
9353
- // console.log('readCar', carFilename, got.constructor.name)
9354
- return got
9355
- }
9356
- }
9357
-
9358
- async readCarIDB (carCid) {
9359
- return await this.withDB(async db => {
9360
- const tx = db.transaction(['cars'], 'readonly');
9361
- // console.log('getCarReader', carCid)
9362
- return await tx.objectStore('cars').get(carCid)
9363
- })
9364
- }
9365
-
9366
- getHeader () {
9367
- if (this.isBrowser) {
9368
- return localStorage.getItem(this.config.headerKeyPrefix + this.name)
9369
- } else {
9370
- return loadSync(this.headerFilename())
9371
- // return null
9372
- }
9373
- }
9374
-
9375
- async saveHeader (stringValue) {
9376
- // console.log('saveHeader', this.isBrowser)
9377
- if (this.isBrowser) {
9378
- // console.log('localStorage!', this.config.headerKeyPrefix)
9379
- return localStorage.setItem(this.config.headerKeyPrefix + this.name, stringValue)
9380
- } else {
9381
- // console.log('no localStorage', this.config.dataDir, this.name)
9382
- // console.log('saving clock to', this.headerFilename(), stringValue)
9383
-
9384
- try {
9385
- await writeSync(this.headerFilename(), stringValue);
9386
- } catch (error) {
9387
- console.log('error', error);
9388
- }
9389
-
9390
- // console.log('saved clock to', this.headerFilename())
9391
- }
9392
- }
9393
-
9394
- headerFilename () {
9395
- // console.log('headerFilename', this.config.dataDir, this.name)
9396
- return join(this.config.dataDir, this.name, 'header.json')
9397
- }
9398
-
9399
- // async loadData (database, filename) {
9400
- // const fullFilePath = join(process.cwd(), filename)
9401
- // const readableStream = createReadStream(fullFilePath)
9402
- // const parseStream = parse()
9403
- // readableStream.pipe(parseStream)
9404
-
9405
- // const saveQueue = cargoQueue(async (tasks, callback) => {
9406
- // for (const t of tasks) {
9407
- // await database.put(t)
9408
- // }
9409
- // callback()
9410
- // })
9411
-
9412
- // parseStream.on('data', async (data) => {
9413
- // saveQueue.push(data)
9414
- // })
9415
- // let res
9416
- // const p = new Promise((resolve, reject) => {
9417
- // res = resolve
9418
- // })
9419
- // saveQueue.drain(async (x) => {
9420
- // res()
9421
- // })
9422
- // return p
9423
- // }
9424
- }
9425
-
9426
- function loadSync (filename) {
9427
- try {
9428
- return node_fs.readFileSync(filename, 'utf8').toString()
9429
- } catch (error) {
9430
- // console.log('error', error)
9431
- return null
9432
- }
9433
- }
9434
-
9435
- async function writeSync (fullpath, stringValue) {
9436
- await promises.mkdir(dirname(fullpath), { recursive: true });
9437
- // writeFileSync(fullpath, stringValue)
9438
- await promises.writeFile(fullpath, stringValue);
9439
- }
9440
-
9441
9146
  var cryptoBrowserify = {};
9442
9147
 
9443
9148
  var inherits$x;
@@ -9958,7 +9663,15 @@ var _polyfillNode_events = /*#__PURE__*/Object.freeze({
9958
9663
 
9959
9664
  var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_events);
9960
9665
 
9961
- var streamBrowser = require$$0$1.EventEmitter;
9666
+ var streamBrowser;
9667
+ var hasRequiredStreamBrowser;
9668
+
9669
+ function requireStreamBrowser () {
9670
+ if (hasRequiredStreamBrowser) return streamBrowser;
9671
+ hasRequiredStreamBrowser = 1;
9672
+ streamBrowser = require$$0$1.EventEmitter;
9673
+ return streamBrowser;
9674
+ }
9962
9675
 
9963
9676
  // shim for using process in browser
9964
9677
  // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
@@ -10101,7 +9814,7 @@ var argv = [];
10101
9814
  var version$2 = ''; // empty string to avoid regexp issues
10102
9815
  var versions = {};
10103
9816
  var release = {};
10104
- var config$1 = {};
9817
+ var config = {};
10105
9818
 
10106
9819
  function noop$3() {}
10107
9820
 
@@ -10178,7 +9891,7 @@ var browser$1$1 = {
10178
9891
  hrtime: hrtime,
10179
9892
  platform: platform,
10180
9893
  release: release,
10181
- config: config$1,
9894
+ config: config,
10182
9895
  uptime: uptime
10183
9896
  };
10184
9897
 
@@ -10259,11 +9972,11 @@ function format(f) {
10259
9972
  // Mark that a method should not be used.
10260
9973
  // Returns a modified function which warns once by default.
10261
9974
  // If --no-deprecation is set, then it is a no-op.
10262
- function deprecate$2(fn, msg) {
9975
+ function deprecate$1(fn, msg) {
10263
9976
  // Allow for deprecating things in the process of starting up.
10264
9977
  if (isUndefined(global$1.process)) {
10265
9978
  return function() {
10266
- return deprecate$2(fn, msg).apply(this, arguments);
9979
+ return deprecate$1(fn, msg).apply(this, arguments);
10267
9980
  };
10268
9981
  }
10269
9982
 
@@ -10872,7 +10585,7 @@ var _polyfillNode_util = {
10872
10585
  isBoolean: isBoolean,
10873
10586
  isArray: isArray,
10874
10587
  inspect: inspect,
10875
- deprecate: deprecate$2,
10588
+ deprecate: deprecate$1,
10876
10589
  format: format,
10877
10590
  debuglog: debuglog,
10878
10591
  promisify: promisify,
@@ -10885,7 +10598,7 @@ var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({
10885
10598
  callbackify: callbackify,
10886
10599
  debuglog: debuglog,
10887
10600
  default: _polyfillNode_util,
10888
- deprecate: deprecate$2,
10601
+ deprecate: deprecate$1,
10889
10602
  format: format,
10890
10603
  inherits: inherits$w,
10891
10604
  inspect: inspect,
@@ -11073,99 +10786,108 @@ function requireBuffer_list () {
11073
10786
  return buffer_list;
11074
10787
  }
11075
10788
 
11076
- // undocumented cb() API, needed for core, not for public API
11077
- function destroy(err, cb) {
11078
- const readableDestroyed = this._readableState && this._readableState.destroyed;
11079
- const writableDestroyed = this._writableState && this._writableState.destroyed;
11080
- if (readableDestroyed || writableDestroyed) {
11081
- if (cb) {
11082
- cb(err);
11083
- } else if (err) {
11084
- if (!this._writableState) {
11085
- process.nextTick(emitErrorNT, this, err);
11086
- } else if (!this._writableState.errorEmitted) {
11087
- this._writableState.errorEmitted = true;
11088
- process.nextTick(emitErrorNT, this, err);
11089
- }
11090
- }
11091
- return this;
11092
- }
11093
-
11094
- // we set destroyed to true before firing error callbacks in order
11095
- // to make it re-entrance safe in case destroy() is called within callbacks
10789
+ var destroy_1;
10790
+ var hasRequiredDestroy;
10791
+
10792
+ function requireDestroy () {
10793
+ if (hasRequiredDestroy) return destroy_1;
10794
+ hasRequiredDestroy = 1;
10795
+
10796
+ // undocumented cb() API, needed for core, not for public API
10797
+ function destroy(err, cb) {
10798
+ const readableDestroyed = this._readableState && this._readableState.destroyed;
10799
+ const writableDestroyed = this._writableState && this._writableState.destroyed;
10800
+ if (readableDestroyed || writableDestroyed) {
10801
+ if (cb) {
10802
+ cb(err);
10803
+ } else if (err) {
10804
+ if (!this._writableState) {
10805
+ process.nextTick(emitErrorNT, this, err);
10806
+ } else if (!this._writableState.errorEmitted) {
10807
+ this._writableState.errorEmitted = true;
10808
+ process.nextTick(emitErrorNT, this, err);
10809
+ }
10810
+ }
10811
+ return this;
10812
+ }
11096
10813
 
11097
- if (this._readableState) {
11098
- this._readableState.destroyed = true;
11099
- }
10814
+ // we set destroyed to true before firing error callbacks in order
10815
+ // to make it re-entrance safe in case destroy() is called within callbacks
11100
10816
 
11101
- // if this is a duplex stream mark the writable part as destroyed as well
11102
- if (this._writableState) {
11103
- this._writableState.destroyed = true;
11104
- }
11105
- this._destroy(err || null, err => {
11106
- if (!cb && err) {
11107
- if (!this._writableState) {
11108
- process.nextTick(emitErrorAndCloseNT, this, err);
11109
- } else if (!this._writableState.errorEmitted) {
11110
- this._writableState.errorEmitted = true;
11111
- process.nextTick(emitErrorAndCloseNT, this, err);
11112
- } else {
11113
- process.nextTick(emitCloseNT, this);
11114
- }
11115
- } else if (cb) {
11116
- process.nextTick(emitCloseNT, this);
11117
- cb(err);
11118
- } else {
11119
- process.nextTick(emitCloseNT, this);
11120
- }
11121
- });
11122
- return this;
11123
- }
11124
- function emitErrorAndCloseNT(self, err) {
11125
- emitErrorNT(self, err);
11126
- emitCloseNT(self);
11127
- }
11128
- function emitCloseNT(self) {
11129
- if (self._writableState && !self._writableState.emitClose) return;
11130
- if (self._readableState && !self._readableState.emitClose) return;
11131
- self.emit('close');
11132
- }
11133
- function undestroy() {
11134
- if (this._readableState) {
11135
- this._readableState.destroyed = false;
11136
- this._readableState.reading = false;
11137
- this._readableState.ended = false;
11138
- this._readableState.endEmitted = false;
11139
- }
11140
- if (this._writableState) {
11141
- this._writableState.destroyed = false;
11142
- this._writableState.ended = false;
11143
- this._writableState.ending = false;
11144
- this._writableState.finalCalled = false;
11145
- this._writableState.prefinished = false;
11146
- this._writableState.finished = false;
11147
- this._writableState.errorEmitted = false;
11148
- }
11149
- }
11150
- function emitErrorNT(self, err) {
11151
- self.emit('error', err);
11152
- }
11153
- function errorOrDestroy(stream, err) {
11154
- // We have tests that rely on errors being emitted
11155
- // in the same tick, so changing this is semver major.
11156
- // For now when you opt-in to autoDestroy we allow
11157
- // the error to be emitted nextTick. In a future
11158
- // semver major update we should change the default to this.
10817
+ if (this._readableState) {
10818
+ this._readableState.destroyed = true;
10819
+ }
11159
10820
 
11160
- const rState = stream._readableState;
11161
- const wState = stream._writableState;
11162
- if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
10821
+ // if this is a duplex stream mark the writable part as destroyed as well
10822
+ if (this._writableState) {
10823
+ this._writableState.destroyed = true;
10824
+ }
10825
+ this._destroy(err || null, err => {
10826
+ if (!cb && err) {
10827
+ if (!this._writableState) {
10828
+ process.nextTick(emitErrorAndCloseNT, this, err);
10829
+ } else if (!this._writableState.errorEmitted) {
10830
+ this._writableState.errorEmitted = true;
10831
+ process.nextTick(emitErrorAndCloseNT, this, err);
10832
+ } else {
10833
+ process.nextTick(emitCloseNT, this);
10834
+ }
10835
+ } else if (cb) {
10836
+ process.nextTick(emitCloseNT, this);
10837
+ cb(err);
10838
+ } else {
10839
+ process.nextTick(emitCloseNT, this);
10840
+ }
10841
+ });
10842
+ return this;
10843
+ }
10844
+ function emitErrorAndCloseNT(self, err) {
10845
+ emitErrorNT(self, err);
10846
+ emitCloseNT(self);
10847
+ }
10848
+ function emitCloseNT(self) {
10849
+ if (self._writableState && !self._writableState.emitClose) return;
10850
+ if (self._readableState && !self._readableState.emitClose) return;
10851
+ self.emit('close');
10852
+ }
10853
+ function undestroy() {
10854
+ if (this._readableState) {
10855
+ this._readableState.destroyed = false;
10856
+ this._readableState.reading = false;
10857
+ this._readableState.ended = false;
10858
+ this._readableState.endEmitted = false;
10859
+ }
10860
+ if (this._writableState) {
10861
+ this._writableState.destroyed = false;
10862
+ this._writableState.ended = false;
10863
+ this._writableState.ending = false;
10864
+ this._writableState.finalCalled = false;
10865
+ this._writableState.prefinished = false;
10866
+ this._writableState.finished = false;
10867
+ this._writableState.errorEmitted = false;
10868
+ }
10869
+ }
10870
+ function emitErrorNT(self, err) {
10871
+ self.emit('error', err);
10872
+ }
10873
+ function errorOrDestroy(stream, err) {
10874
+ // We have tests that rely on errors being emitted
10875
+ // in the same tick, so changing this is semver major.
10876
+ // For now when you opt-in to autoDestroy we allow
10877
+ // the error to be emitted nextTick. In a future
10878
+ // semver major update we should change the default to this.
10879
+
10880
+ const rState = stream._readableState;
10881
+ const wState = stream._writableState;
10882
+ if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
10883
+ }
10884
+ destroy_1 = {
10885
+ destroy,
10886
+ undestroy,
10887
+ errorOrDestroy
10888
+ };
10889
+ return destroy_1;
11163
10890
  }
11164
- var destroy_1 = {
11165
- destroy,
11166
- undestroy,
11167
- errorOrDestroy
11168
- };
11169
10891
 
11170
10892
  var errorsBrowser = {};
11171
10893
 
@@ -11295,92 +11017,109 @@ createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
11295
11017
  createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
11296
11018
  errorsBrowser.codes = codes;
11297
11019
 
11298
- const ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE;
11299
- function highWaterMarkFrom(options, isDuplex, duplexKey) {
11300
- return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
11301
- }
11302
- function getHighWaterMark(state, options, duplexKey, isDuplex) {
11303
- const hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
11304
- if (hwm != null) {
11305
- if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
11306
- const name = isDuplex ? duplexKey : 'highWaterMark';
11307
- throw new ERR_INVALID_OPT_VALUE(name, hwm);
11308
- }
11309
- return Math.floor(hwm);
11310
- }
11020
+ var state;
11021
+ var hasRequiredState;
11022
+
11023
+ function requireState () {
11024
+ if (hasRequiredState) return state;
11025
+ hasRequiredState = 1;
11026
+
11027
+ const ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE;
11028
+ function highWaterMarkFrom(options, isDuplex, duplexKey) {
11029
+ return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
11030
+ }
11031
+ function getHighWaterMark(state, options, duplexKey, isDuplex) {
11032
+ const hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
11033
+ if (hwm != null) {
11034
+ if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
11035
+ const name = isDuplex ? duplexKey : 'highWaterMark';
11036
+ throw new ERR_INVALID_OPT_VALUE(name, hwm);
11037
+ }
11038
+ return Math.floor(hwm);
11039
+ }
11311
11040
 
11312
- // Default value
11313
- return state.objectMode ? 16 : 16 * 1024;
11041
+ // Default value
11042
+ return state.objectMode ? 16 : 16 * 1024;
11043
+ }
11044
+ state = {
11045
+ getHighWaterMark
11046
+ };
11047
+ return state;
11314
11048
  }
11315
- var state = {
11316
- getHighWaterMark
11317
- };
11318
11049
 
11319
- /**
11320
- * Module exports.
11321
- */
11050
+ var browser$b;
11051
+ var hasRequiredBrowser$3;
11322
11052
 
11323
- var browser$b = deprecate$1;
11053
+ function requireBrowser$3 () {
11054
+ if (hasRequiredBrowser$3) return browser$b;
11055
+ hasRequiredBrowser$3 = 1;
11056
+ /**
11057
+ * Module exports.
11058
+ */
11324
11059
 
11325
- /**
11326
- * Mark that a method should not be used.
11327
- * Returns a modified function which warns once by default.
11328
- *
11329
- * If `localStorage.noDeprecation = true` is set, then it is a no-op.
11330
- *
11331
- * If `localStorage.throwDeprecation = true` is set, then deprecated functions
11332
- * will throw an Error when invoked.
11333
- *
11334
- * If `localStorage.traceDeprecation = true` is set, then deprecated functions
11335
- * will invoke `console.trace()` instead of `console.error()`.
11336
- *
11337
- * @param {Function} fn - the function to deprecate
11338
- * @param {String} msg - the string to print to the console when `fn` is invoked
11339
- * @returns {Function} a new "deprecated" version of `fn`
11340
- * @api public
11341
- */
11060
+ browser$b = deprecate;
11342
11061
 
11343
- function deprecate$1 (fn, msg) {
11344
- if (config('noDeprecation')) {
11345
- return fn;
11346
- }
11062
+ /**
11063
+ * Mark that a method should not be used.
11064
+ * Returns a modified function which warns once by default.
11065
+ *
11066
+ * If `localStorage.noDeprecation = true` is set, then it is a no-op.
11067
+ *
11068
+ * If `localStorage.throwDeprecation = true` is set, then deprecated functions
11069
+ * will throw an Error when invoked.
11070
+ *
11071
+ * If `localStorage.traceDeprecation = true` is set, then deprecated functions
11072
+ * will invoke `console.trace()` instead of `console.error()`.
11073
+ *
11074
+ * @param {Function} fn - the function to deprecate
11075
+ * @param {String} msg - the string to print to the console when `fn` is invoked
11076
+ * @returns {Function} a new "deprecated" version of `fn`
11077
+ * @api public
11078
+ */
11347
11079
 
11348
- var warned = false;
11349
- function deprecated() {
11350
- if (!warned) {
11351
- if (config('throwDeprecation')) {
11352
- throw new Error(msg);
11353
- } else if (config('traceDeprecation')) {
11354
- console.trace(msg);
11355
- } else {
11356
- console.warn(msg);
11357
- }
11358
- warned = true;
11359
- }
11360
- return fn.apply(this, arguments);
11361
- }
11080
+ function deprecate (fn, msg) {
11081
+ if (config('noDeprecation')) {
11082
+ return fn;
11083
+ }
11362
11084
 
11363
- return deprecated;
11364
- }
11085
+ var warned = false;
11086
+ function deprecated() {
11087
+ if (!warned) {
11088
+ if (config('throwDeprecation')) {
11089
+ throw new Error(msg);
11090
+ } else if (config('traceDeprecation')) {
11091
+ console.trace(msg);
11092
+ } else {
11093
+ console.warn(msg);
11094
+ }
11095
+ warned = true;
11096
+ }
11097
+ return fn.apply(this, arguments);
11098
+ }
11365
11099
 
11366
- /**
11367
- * Checks `localStorage` for boolean values for the given `name`.
11368
- *
11369
- * @param {String} name
11370
- * @returns {Boolean}
11371
- * @api private
11372
- */
11100
+ return deprecated;
11101
+ }
11373
11102
 
11374
- function config (name) {
11375
- // accessing global.localStorage can trigger a DOMException in sandboxed iframes
11376
- try {
11377
- if (!commonjsGlobal.localStorage) return false;
11378
- } catch (_) {
11379
- return false;
11380
- }
11381
- var val = commonjsGlobal.localStorage[name];
11382
- if (null == val) return false;
11383
- return String(val).toLowerCase() === 'true';
11103
+ /**
11104
+ * Checks `localStorage` for boolean values for the given `name`.
11105
+ *
11106
+ * @param {String} name
11107
+ * @returns {Boolean}
11108
+ * @api private
11109
+ */
11110
+
11111
+ function config (name) {
11112
+ // accessing global.localStorage can trigger a DOMException in sandboxed iframes
11113
+ try {
11114
+ if (!commonjsGlobal.localStorage) return false;
11115
+ } catch (_) {
11116
+ return false;
11117
+ }
11118
+ var val = commonjsGlobal.localStorage[name];
11119
+ if (null == val) return false;
11120
+ return String(val).toLowerCase() === 'true';
11121
+ }
11122
+ return browser$b;
11384
11123
  }
11385
11124
 
11386
11125
  var _stream_writable;
@@ -11411,12 +11150,12 @@ function require_stream_writable () {
11411
11150
 
11412
11151
  /*<replacement>*/
11413
11152
  const internalUtil = {
11414
- deprecate: browser$b
11153
+ deprecate: requireBrowser$3()
11415
11154
  };
11416
11155
  /*</replacement>*/
11417
11156
 
11418
11157
  /*<replacement>*/
11419
- var Stream = streamBrowser;
11158
+ var Stream = requireStreamBrowser();
11420
11159
  /*</replacement>*/
11421
11160
 
11422
11161
  const Buffer = require$$6$1.Buffer;
@@ -11427,8 +11166,8 @@ function require_stream_writable () {
11427
11166
  function _isUint8Array(obj) {
11428
11167
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
11429
11168
  }
11430
- const destroyImpl = destroy_1;
11431
- const _require = state,
11169
+ const destroyImpl = requireDestroy();
11170
+ const _require = requireState(),
11432
11171
  getHighWaterMark = _require.getHighWaterMark;
11433
11172
  const _require$codes = errorsBrowser.codes,
11434
11173
  ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
@@ -12622,7 +12361,7 @@ function require_stream_readable () {
12622
12361
  /*</replacement>*/
12623
12362
 
12624
12363
  /*<replacement>*/
12625
- var Stream = streamBrowser;
12364
+ var Stream = requireStreamBrowser();
12626
12365
  /*</replacement>*/
12627
12366
 
12628
12367
  const Buffer = require$$6$1.Buffer;
@@ -12645,8 +12384,8 @@ function require_stream_readable () {
12645
12384
  /*</replacement>*/
12646
12385
 
12647
12386
  const BufferList = requireBuffer_list();
12648
- const destroyImpl = destroy_1;
12649
- const _require = state,
12387
+ const destroyImpl = requireDestroy();
12388
+ const _require = requireState(),
12650
12389
  getHighWaterMark = _require.getHighWaterMark;
12651
12390
  const _require$codes = errorsBrowser.codes,
12652
12391
  ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
@@ -16012,7 +15751,7 @@ function WriteReq(chunk, encoding, cb) {
16012
15751
 
16013
15752
  function WritableState(options, stream) {
16014
15753
  Object.defineProperty(this, 'buffer', {
16015
- get: deprecate$2(function () {
15754
+ get: deprecate$1(function () {
16016
15755
  return this.getBuffer();
16017
15756
  }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
16018
15757
  });
@@ -39807,7 +39546,6 @@ class Valet {
39807
39546
  constructor (name = 'default', keyMaterial) {
39808
39547
  this.name = name;
39809
39548
  this.setKeyMaterial(keyMaterial);
39810
- this.loader = new Loader(name, this.keyId); // todo send this config.loader, if we ever need it
39811
39549
  this.uploadQueue = cargoQueue(async (tasks, callback) => {
39812
39550
  // console.log(
39813
39551
  // 'queue worker',
@@ -39842,10 +39580,6 @@ class Valet {
39842
39580
  });
39843
39581
  }
39844
39582
 
39845
- saveHeader (header) {
39846
- return this.loader.saveHeader(header)
39847
- }
39848
-
39849
39583
  getKeyMaterial () {
39850
39584
  return this.keyMaterial
39851
39585
  }
@@ -39886,6 +39620,19 @@ class Valet {
39886
39620
  }
39887
39621
  }
39888
39622
 
39623
+ withDB = async dbWorkFun => {
39624
+ if (!this.idb) {
39625
+ this.idb = await openDB(`fp.${this.keyId}.${this.name}.valet`, 3, {
39626
+ upgrade (db, oldVersion, newVersion, transaction) {
39627
+ if (oldVersion < 1) {
39628
+ db.createObjectStore('cars');
39629
+ }
39630
+ }
39631
+ });
39632
+ }
39633
+ return await dbWorkFun(this.idb)
39634
+ }
39635
+
39889
39636
  /**
39890
39637
  * Iterate over all blocks in the store.
39891
39638
  *
@@ -39926,7 +39673,6 @@ class Valet {
39926
39673
  blockHasher: blockOpts$1.hasher,
39927
39674
  blockCodec: blockOpts$1.codec
39928
39675
  });
39929
- this.valetRoot = indexNode;
39930
39676
  }
39931
39677
 
39932
39678
  const got = await indexNode.get(cid);
@@ -39973,7 +39719,6 @@ class Valet {
39973
39719
  * @param {*} value
39974
39720
  */
39975
39721
  async parkCar (carCid, value, cids) {
39976
- // const callId = Math.random().toString(36).substring(7)
39977
39722
  // console.log('parkCar', this.instanceId, this.name, carCid, cids)
39978
39723
  const combinedReader = await this.getCombinedReader(carCid);
39979
39724
  const mapNode = await addCidsToCarIndex(
@@ -39986,7 +39731,7 @@ class Valet {
39986
39731
  this.valetRoot = mapNode;
39987
39732
  this.valetRootCid = mapNode.cid;
39988
39733
  // make a block set with all the cids of the map
39989
- const saveValetBlocks = new VMemoryBlockstore();
39734
+ const saveValetBlocks = new VMemoryBlockstore(); // todo this blockstore should read from the last valetCid car also
39990
39735
 
39991
39736
  for await (const cidx of mapNode.cids()) {
39992
39737
  const bytes = await combinedReader.get(cidx);
@@ -39999,8 +39744,7 @@ class Valet {
39999
39744
  newValetCidCar = await blocksToCarBlock(this.valetRootCid, saveValetBlocks);
40000
39745
  }
40001
39746
  // console.log('newValetCidCar', this.name, Math.floor(newValetCidCar.bytes.length / 1024))
40002
- // console.log('writeCars', callId, carCid.toString(), newValetCidCar.cid.toString())
40003
- await this.loader.writeCars([
39747
+ await this.writeCars([
40004
39748
  {
40005
39749
  cid: carCid,
40006
39750
  bytes: value,
@@ -40016,8 +39760,6 @@ class Valet {
40016
39760
 
40017
39761
  this.valetRootCarCid = newValetCidCar.cid; // goes to clock
40018
39762
 
40019
- // console.log('wroteCars', callId, carCid.toString(), newValetCidCar.cid.toString())
40020
-
40021
39763
  // console.log('parked car', carCid, value.length, Array.from(cids))
40022
39764
  // upload to web3.storage if we have credentials
40023
39765
  if (this.uploadFunction) {
@@ -40032,13 +39774,29 @@ class Valet {
40032
39774
  }
40033
39775
  }
40034
39776
 
39777
+ async writeCars (cars) {
39778
+ return await this.withDB(async db => {
39779
+ const tx = db.transaction(['cars'], 'readwrite');
39780
+ for (const { cid, bytes, replaces } of cars) {
39781
+ await tx.objectStore('cars').put(bytes, cid.toString());
39782
+ // todo remove old maps
39783
+ if (replaces) {
39784
+ await tx.objectStore('cars').delete(replaces.toString());
39785
+ }
39786
+ }
39787
+ return await tx.done
39788
+ })
39789
+ }
39790
+
40035
39791
  remoteBlockFunction = null
40036
39792
 
40037
39793
  async getCarReader (carCid) {
40038
39794
  carCid = carCid.toString();
40039
- const carBytes = await this.loader.readCar(carCid);
40040
- // const callID = Math.random().toString(36).substring(7)
40041
- // console.log('getCarReader', callID, carCid)
39795
+ const carBytes = await this.withDB(async db => {
39796
+ const tx = db.transaction(['cars'], 'readonly');
39797
+ // console.log('getCarReader', carCid)
39798
+ return await tx.objectStore('cars').get(carCid)
39799
+ });
40042
39800
  const reader = await CarReader.fromBytes(carBytes);
40043
39801
  if (this.keyMaterial) {
40044
39802
  const roots = await reader.getRoots();
@@ -40062,7 +39820,7 @@ class Valet {
40062
39820
 
40063
39821
  // last block is the root ??? todo
40064
39822
  const rootBlock = blocks[blocks.length - 1];
40065
- // console.log('got reader', callID, carCid)
39823
+
40066
39824
  return {
40067
39825
  root: rootBlock,
40068
39826
  get: async dataCID => {
@@ -40189,8 +39947,6 @@ const blocksFromEncryptedCarBlock = async (cid, get, keyMaterial) => {
40189
39947
 
40190
39948
  const addCidsToCarIndex = async (blockstore, valetRoot, valetRootCid, bulkOperations) => {
40191
39949
  let indexNode;
40192
- // const callID = Math.random().toString(32).substring(2, 8)
40193
- // console.log('addCidsToCarIndex', callID, valetRootCid, bulkOperations.length)
40194
39950
  if (valetRootCid) {
40195
39951
  if (valetRoot) {
40196
39952
  indexNode = valetRoot;
@@ -40210,7 +39966,6 @@ const addCidsToCarIndex = async (blockstore, valetRoot, valetRootCid, bulkOperat
40210
39966
  // console.log('adding', key, value)
40211
39967
  await indexNode.set(key, value);
40212
39968
  }
40213
- // console.log('newCidsToCarIndex', callID, indexNode.cid, bulkOperations.length)
40214
39969
  return indexNode
40215
39970
  };
40216
39971
 
@@ -41163,6 +40918,22 @@ object.factory = function (codec) {
41163
40918
  exports.type = 'charwise';
41164
40919
  } (charwise));
41165
40920
 
40921
+ /* global localStorage */
40922
+ let storageSupported = false;
40923
+ try {
40924
+ storageSupported = window.localStorage && true;
40925
+ } catch (e) {}
40926
+ function localGet (key) {
40927
+ if (storageSupported) {
40928
+ return localStorage && localStorage.getItem(key)
40929
+ }
40930
+ }
40931
+ function localSet (key, value) {
40932
+ if (storageSupported) {
40933
+ return localStorage && localStorage.setItem(key, value)
40934
+ }
40935
+ }
40936
+
41166
40937
  // @ts-nocheck
41167
40938
  const parseCID = cid => (typeof cid === 'string' ? CID$1.parse(cid) : cid);
41168
40939
 
@@ -41187,7 +40958,7 @@ class Database {
41187
40958
  this.name = name;
41188
40959
  this.instanceId = `fp.${this.name}.${Math.random().toString(36).substring(2, 7)}`;
41189
40960
  this.blocks = new TransactionBlockstore(name, config.key);
41190
- this.indexBlocks = new TransactionBlockstore(name ? name + '.indexes' : null, config.key);
40961
+ this.indexBlocks = new TransactionBlockstore(name + '.indexes', config.key);
41191
40962
  this.clock = clock;
41192
40963
  this.config = config;
41193
40964
  }
@@ -41231,7 +41002,7 @@ class Database {
41231
41002
 
41232
41003
  maybeSaveClock () {
41233
41004
  if (this.name && this.blocks.valet) {
41234
- this.blocks.valet.saveHeader(JSON.stringify(this));
41005
+ localSet('fp.' + this.name, JSON.stringify(this));
41235
41006
  }
41236
41007
  }
41237
41008
 
@@ -41467,7 +41238,6 @@ class Database {
41467
41238
  console.error('failed', event);
41468
41239
  throw new Error('failed to put at storage layer')
41469
41240
  }
41470
- // await new Promise(resolve => setTimeout(resolve, 10)) // makes concurrent tests work
41471
41241
  this.applyClock(prevClock, result.head);
41472
41242
  await this.notifyListeners([decodedEvent]); // this type is odd
41473
41243
  return {
@@ -44329,8 +44099,8 @@ class Fireproof {
44329
44099
  static storage = (name = null, opts = {}) => {
44330
44100
  if (name) {
44331
44101
  opts.name = name;
44332
- const loader = new Loader(name, opts.loader);
44333
- const existing = loader.getHeader();
44102
+ // todo this can come from a registry also eg remote database / config, etc
44103
+ const existing = localGet('fp.' + name);
44334
44104
  if (existing) {
44335
44105
  const existingConfig = JSON.parse(existing);
44336
44106
  return Fireproof.fromConfig(name, existingConfig, opts)