@peerbit/indexer-sqlite3 1.0.7 → 1.1.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.
@@ -5587,9 +5587,6 @@ var FixedArrayKind = class extends WrappedType {
5587
5587
  this.length = length;
5588
5588
  }
5589
5589
  };
5590
- var fixedArray = (type, length) => {
5591
- return new FixedArrayKind(type, length);
5592
- };
5593
5590
  var StructKind = class {
5594
5591
  constructor(properties) {
5595
5592
  if (properties) {
@@ -6668,6 +6665,273 @@ var resize = (arr, newSize, defaultValue) => {
6668
6665
  arr.length = newSize;
6669
6666
  };
6670
6667
 
6668
+ // ../../../../node_modules/multiformats/dist/src/bytes.js
6669
+ var empty = new Uint8Array(0);
6670
+ function coerce(o) {
6671
+ if (o instanceof Uint8Array && o.constructor.name === "Uint8Array")
6672
+ return o;
6673
+ if (o instanceof ArrayBuffer)
6674
+ return new Uint8Array(o);
6675
+ if (ArrayBuffer.isView(o)) {
6676
+ return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
6677
+ }
6678
+ throw new Error("Unknown type, must be binary type");
6679
+ }
6680
+
6681
+ // ../../../../node_modules/multiformats/dist/src/vendor/base-x.js
6682
+ function base(ALPHABET, name) {
6683
+ if (ALPHABET.length >= 255) {
6684
+ throw new TypeError("Alphabet too long");
6685
+ }
6686
+ var BASE_MAP = new Uint8Array(256);
6687
+ for (var j = 0; j < BASE_MAP.length; j++) {
6688
+ BASE_MAP[j] = 255;
6689
+ }
6690
+ for (var i = 0; i < ALPHABET.length; i++) {
6691
+ var x = ALPHABET.charAt(i);
6692
+ var xc = x.charCodeAt(0);
6693
+ if (BASE_MAP[xc] !== 255) {
6694
+ throw new TypeError(x + " is ambiguous");
6695
+ }
6696
+ BASE_MAP[xc] = i;
6697
+ }
6698
+ var BASE = ALPHABET.length;
6699
+ var LEADER = ALPHABET.charAt(0);
6700
+ var FACTOR = Math.log(BASE) / Math.log(256);
6701
+ var iFACTOR = Math.log(256) / Math.log(BASE);
6702
+ function encode(source) {
6703
+ if (source instanceof Uint8Array)
6704
+ ;
6705
+ else if (ArrayBuffer.isView(source)) {
6706
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
6707
+ } else if (Array.isArray(source)) {
6708
+ source = Uint8Array.from(source);
6709
+ }
6710
+ if (!(source instanceof Uint8Array)) {
6711
+ throw new TypeError("Expected Uint8Array");
6712
+ }
6713
+ if (source.length === 0) {
6714
+ return "";
6715
+ }
6716
+ var zeroes = 0;
6717
+ var length = 0;
6718
+ var pbegin = 0;
6719
+ var pend = source.length;
6720
+ while (pbegin !== pend && source[pbegin] === 0) {
6721
+ pbegin++;
6722
+ zeroes++;
6723
+ }
6724
+ var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
6725
+ var b58 = new Uint8Array(size);
6726
+ while (pbegin !== pend) {
6727
+ var carry = source[pbegin];
6728
+ var i2 = 0;
6729
+ for (var it1 = size - 1; (carry !== 0 || i2 < length) && it1 !== -1; it1--, i2++) {
6730
+ carry += 256 * b58[it1] >>> 0;
6731
+ b58[it1] = carry % BASE >>> 0;
6732
+ carry = carry / BASE >>> 0;
6733
+ }
6734
+ if (carry !== 0) {
6735
+ throw new Error("Non-zero carry");
6736
+ }
6737
+ length = i2;
6738
+ pbegin++;
6739
+ }
6740
+ var it2 = size - length;
6741
+ while (it2 !== size && b58[it2] === 0) {
6742
+ it2++;
6743
+ }
6744
+ var str = LEADER.repeat(zeroes);
6745
+ for (; it2 < size; ++it2) {
6746
+ str += ALPHABET.charAt(b58[it2]);
6747
+ }
6748
+ return str;
6749
+ }
6750
+ function decodeUnsafe(source) {
6751
+ if (typeof source !== "string") {
6752
+ throw new TypeError("Expected String");
6753
+ }
6754
+ if (source.length === 0) {
6755
+ return new Uint8Array();
6756
+ }
6757
+ var psz = 0;
6758
+ if (source[psz] === " ") {
6759
+ return;
6760
+ }
6761
+ var zeroes = 0;
6762
+ var length = 0;
6763
+ while (source[psz] === LEADER) {
6764
+ zeroes++;
6765
+ psz++;
6766
+ }
6767
+ var size = (source.length - psz) * FACTOR + 1 >>> 0;
6768
+ var b256 = new Uint8Array(size);
6769
+ while (source[psz]) {
6770
+ var carry = BASE_MAP[source.charCodeAt(psz)];
6771
+ if (carry === 255) {
6772
+ return;
6773
+ }
6774
+ var i2 = 0;
6775
+ for (var it3 = size - 1; (carry !== 0 || i2 < length) && it3 !== -1; it3--, i2++) {
6776
+ carry += BASE * b256[it3] >>> 0;
6777
+ b256[it3] = carry % 256 >>> 0;
6778
+ carry = carry / 256 >>> 0;
6779
+ }
6780
+ if (carry !== 0) {
6781
+ throw new Error("Non-zero carry");
6782
+ }
6783
+ length = i2;
6784
+ psz++;
6785
+ }
6786
+ if (source[psz] === " ") {
6787
+ return;
6788
+ }
6789
+ var it4 = size - length;
6790
+ while (it4 !== size && b256[it4] === 0) {
6791
+ it4++;
6792
+ }
6793
+ var vch = new Uint8Array(zeroes + (size - it4));
6794
+ var j2 = zeroes;
6795
+ while (it4 !== size) {
6796
+ vch[j2++] = b256[it4++];
6797
+ }
6798
+ return vch;
6799
+ }
6800
+ function decode(string) {
6801
+ var buffer = decodeUnsafe(string);
6802
+ if (buffer) {
6803
+ return buffer;
6804
+ }
6805
+ throw new Error(`Non-${name} character`);
6806
+ }
6807
+ return {
6808
+ encode,
6809
+ decodeUnsafe,
6810
+ decode
6811
+ };
6812
+ }
6813
+ var src = base;
6814
+ var _brrp__multiformats_scope_baseX = src;
6815
+ var base_x_default = _brrp__multiformats_scope_baseX;
6816
+
6817
+ // ../../../../node_modules/multiformats/dist/src/bases/base.js
6818
+ var Encoder = class {
6819
+ name;
6820
+ prefix;
6821
+ baseEncode;
6822
+ constructor(name, prefix, baseEncode) {
6823
+ this.name = name;
6824
+ this.prefix = prefix;
6825
+ this.baseEncode = baseEncode;
6826
+ }
6827
+ encode(bytes) {
6828
+ if (bytes instanceof Uint8Array) {
6829
+ return `${this.prefix}${this.baseEncode(bytes)}`;
6830
+ } else {
6831
+ throw Error("Unknown type, must be binary type");
6832
+ }
6833
+ }
6834
+ };
6835
+ var Decoder = class {
6836
+ name;
6837
+ prefix;
6838
+ baseDecode;
6839
+ prefixCodePoint;
6840
+ constructor(name, prefix, baseDecode) {
6841
+ this.name = name;
6842
+ this.prefix = prefix;
6843
+ const prefixCodePoint = prefix.codePointAt(0);
6844
+ if (prefixCodePoint === void 0) {
6845
+ throw new Error("Invalid prefix character");
6846
+ }
6847
+ this.prefixCodePoint = prefixCodePoint;
6848
+ this.baseDecode = baseDecode;
6849
+ }
6850
+ decode(text) {
6851
+ if (typeof text === "string") {
6852
+ if (text.codePointAt(0) !== this.prefixCodePoint) {
6853
+ throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
6854
+ }
6855
+ return this.baseDecode(text.slice(this.prefix.length));
6856
+ } else {
6857
+ throw Error("Can only multibase decode strings");
6858
+ }
6859
+ }
6860
+ or(decoder) {
6861
+ return or(this, decoder);
6862
+ }
6863
+ };
6864
+ var ComposedDecoder = class {
6865
+ decoders;
6866
+ constructor(decoders) {
6867
+ this.decoders = decoders;
6868
+ }
6869
+ or(decoder) {
6870
+ return or(this, decoder);
6871
+ }
6872
+ decode(input) {
6873
+ const prefix = input[0];
6874
+ const decoder = this.decoders[prefix];
6875
+ if (decoder != null) {
6876
+ return decoder.decode(input);
6877
+ } else {
6878
+ throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
6879
+ }
6880
+ }
6881
+ };
6882
+ function or(left, right) {
6883
+ return new ComposedDecoder({
6884
+ ...left.decoders ?? { [left.prefix]: left },
6885
+ ...right.decoders ?? { [right.prefix]: right }
6886
+ });
6887
+ }
6888
+ var Codec = class {
6889
+ name;
6890
+ prefix;
6891
+ baseEncode;
6892
+ baseDecode;
6893
+ encoder;
6894
+ decoder;
6895
+ constructor(name, prefix, baseEncode, baseDecode) {
6896
+ this.name = name;
6897
+ this.prefix = prefix;
6898
+ this.baseEncode = baseEncode;
6899
+ this.baseDecode = baseDecode;
6900
+ this.encoder = new Encoder(name, prefix, baseEncode);
6901
+ this.decoder = new Decoder(name, prefix, baseDecode);
6902
+ }
6903
+ encode(input) {
6904
+ return this.encoder.encode(input);
6905
+ }
6906
+ decode(input) {
6907
+ return this.decoder.decode(input);
6908
+ }
6909
+ };
6910
+ function from({ name, prefix, encode, decode }) {
6911
+ return new Codec(name, prefix, encode, decode);
6912
+ }
6913
+ function baseX({ name, prefix, alphabet }) {
6914
+ const { encode, decode } = base_x_default(alphabet, name);
6915
+ return from({
6916
+ prefix,
6917
+ name,
6918
+ encode,
6919
+ decode: (text) => coerce(decode(text))
6920
+ });
6921
+ }
6922
+
6923
+ // ../../../../node_modules/multiformats/dist/src/bases/base58.js
6924
+ var base58btc = baseX({
6925
+ name: "base58btc",
6926
+ prefix: "z",
6927
+ alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
6928
+ });
6929
+ var base58flickr = baseX({
6930
+ name: "base58flickr",
6931
+ prefix: "Z",
6932
+ alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
6933
+ });
6934
+
6671
6935
  // ../../../../node_modules/@stablelib/int/lib/int.js
6672
6936
  var isInteger = Number.isInteger;
6673
6937
  var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
@@ -6685,7 +6949,7 @@ function writeUint32BE(value, out = new Uint8Array(4), offset = 0) {
6685
6949
  return out;
6686
6950
  }
6687
6951
 
6688
- // ../../../../node_modules/@stablelib/sha256/node_modules/@stablelib/wipe/lib/wipe.js
6952
+ // ../../../../node_modules/@stablelib/wipe/lib/wipe.js
6689
6953
  function wipe(array) {
6690
6954
  for (let i = 0; i < array.length; i++) {
6691
6955
  array[i] = 0;
@@ -6933,311 +7197,43 @@ function hashBlocks(w, v2, p, pos, len) {
6933
7197
  let h = v2[7];
6934
7198
  for (let i = 0; i < 16; i++) {
6935
7199
  let j = pos + i * 4;
6936
- w[i] = readUint32BE(p, j);
6937
- }
6938
- for (let i = 16; i < 64; i++) {
6939
- let u = w[i - 2];
6940
- let t1 = (u >>> 17 | u << 32 - 17) ^ (u >>> 19 | u << 32 - 19) ^ u >>> 10;
6941
- u = w[i - 15];
6942
- let t2 = (u >>> 7 | u << 32 - 7) ^ (u >>> 18 | u << 32 - 18) ^ u >>> 3;
6943
- w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);
6944
- }
6945
- for (let i = 0; i < 64; i++) {
6946
- let t1 = (((e >>> 6 | e << 32 - 6) ^ (e >>> 11 | e << 32 - 11) ^ (e >>> 25 | e << 32 - 25)) + (e & f ^ ~e & g) | 0) + (h + (K[i] + w[i] | 0) | 0) | 0;
6947
- let t2 = ((a >>> 2 | a << 32 - 2) ^ (a >>> 13 | a << 32 - 13) ^ (a >>> 22 | a << 32 - 22)) + (a & b ^ a & c ^ b & c) | 0;
6948
- h = g;
6949
- g = f;
6950
- f = e;
6951
- e = d + t1 | 0;
6952
- d = c;
6953
- c = b;
6954
- b = a;
6955
- a = t1 + t2 | 0;
6956
- }
6957
- v2[0] += a;
6958
- v2[1] += b;
6959
- v2[2] += c;
6960
- v2[3] += d;
6961
- v2[4] += e;
6962
- v2[5] += f;
6963
- v2[6] += g;
6964
- v2[7] += h;
6965
- pos += 64;
6966
- len -= 64;
6967
- }
6968
- return pos;
6969
- }
6970
-
6971
- // ../../crypto/dist/src/utils.js
6972
- var import_libsodium_wrappers = __toESM(require_libsodium_wrappers(), 1);
6973
-
6974
- // ../../../../node_modules/multiformats/dist/src/bytes.js
6975
- var empty = new Uint8Array(0);
6976
- function coerce(o) {
6977
- if (o instanceof Uint8Array && o.constructor.name === "Uint8Array")
6978
- return o;
6979
- if (o instanceof ArrayBuffer)
6980
- return new Uint8Array(o);
6981
- if (ArrayBuffer.isView(o)) {
6982
- return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
6983
- }
6984
- throw new Error("Unknown type, must be binary type");
6985
- }
6986
-
6987
- // ../../../../node_modules/multiformats/dist/src/vendor/base-x.js
6988
- function base(ALPHABET, name) {
6989
- if (ALPHABET.length >= 255) {
6990
- throw new TypeError("Alphabet too long");
6991
- }
6992
- var BASE_MAP = new Uint8Array(256);
6993
- for (var j = 0; j < BASE_MAP.length; j++) {
6994
- BASE_MAP[j] = 255;
6995
- }
6996
- for (var i = 0; i < ALPHABET.length; i++) {
6997
- var x = ALPHABET.charAt(i);
6998
- var xc = x.charCodeAt(0);
6999
- if (BASE_MAP[xc] !== 255) {
7000
- throw new TypeError(x + " is ambiguous");
7001
- }
7002
- BASE_MAP[xc] = i;
7003
- }
7004
- var BASE = ALPHABET.length;
7005
- var LEADER = ALPHABET.charAt(0);
7006
- var FACTOR = Math.log(BASE) / Math.log(256);
7007
- var iFACTOR = Math.log(256) / Math.log(BASE);
7008
- function encode(source) {
7009
- if (source instanceof Uint8Array)
7010
- ;
7011
- else if (ArrayBuffer.isView(source)) {
7012
- source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
7013
- } else if (Array.isArray(source)) {
7014
- source = Uint8Array.from(source);
7015
- }
7016
- if (!(source instanceof Uint8Array)) {
7017
- throw new TypeError("Expected Uint8Array");
7018
- }
7019
- if (source.length === 0) {
7020
- return "";
7021
- }
7022
- var zeroes = 0;
7023
- var length = 0;
7024
- var pbegin = 0;
7025
- var pend = source.length;
7026
- while (pbegin !== pend && source[pbegin] === 0) {
7027
- pbegin++;
7028
- zeroes++;
7029
- }
7030
- var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
7031
- var b58 = new Uint8Array(size);
7032
- while (pbegin !== pend) {
7033
- var carry = source[pbegin];
7034
- var i2 = 0;
7035
- for (var it1 = size - 1; (carry !== 0 || i2 < length) && it1 !== -1; it1--, i2++) {
7036
- carry += 256 * b58[it1] >>> 0;
7037
- b58[it1] = carry % BASE >>> 0;
7038
- carry = carry / BASE >>> 0;
7039
- }
7040
- if (carry !== 0) {
7041
- throw new Error("Non-zero carry");
7042
- }
7043
- length = i2;
7044
- pbegin++;
7045
- }
7046
- var it2 = size - length;
7047
- while (it2 !== size && b58[it2] === 0) {
7048
- it2++;
7049
- }
7050
- var str = LEADER.repeat(zeroes);
7051
- for (; it2 < size; ++it2) {
7052
- str += ALPHABET.charAt(b58[it2]);
7053
- }
7054
- return str;
7055
- }
7056
- function decodeUnsafe(source) {
7057
- if (typeof source !== "string") {
7058
- throw new TypeError("Expected String");
7059
- }
7060
- if (source.length === 0) {
7061
- return new Uint8Array();
7062
- }
7063
- var psz = 0;
7064
- if (source[psz] === " ") {
7065
- return;
7066
- }
7067
- var zeroes = 0;
7068
- var length = 0;
7069
- while (source[psz] === LEADER) {
7070
- zeroes++;
7071
- psz++;
7072
- }
7073
- var size = (source.length - psz) * FACTOR + 1 >>> 0;
7074
- var b256 = new Uint8Array(size);
7075
- while (source[psz]) {
7076
- var carry = BASE_MAP[source.charCodeAt(psz)];
7077
- if (carry === 255) {
7078
- return;
7079
- }
7080
- var i2 = 0;
7081
- for (var it3 = size - 1; (carry !== 0 || i2 < length) && it3 !== -1; it3--, i2++) {
7082
- carry += BASE * b256[it3] >>> 0;
7083
- b256[it3] = carry % 256 >>> 0;
7084
- carry = carry / 256 >>> 0;
7085
- }
7086
- if (carry !== 0) {
7087
- throw new Error("Non-zero carry");
7088
- }
7089
- length = i2;
7090
- psz++;
7091
- }
7092
- if (source[psz] === " ") {
7093
- return;
7094
- }
7095
- var it4 = size - length;
7096
- while (it4 !== size && b256[it4] === 0) {
7097
- it4++;
7098
- }
7099
- var vch = new Uint8Array(zeroes + (size - it4));
7100
- var j2 = zeroes;
7101
- while (it4 !== size) {
7102
- vch[j2++] = b256[it4++];
7103
- }
7104
- return vch;
7105
- }
7106
- function decode(string) {
7107
- var buffer = decodeUnsafe(string);
7108
- if (buffer) {
7109
- return buffer;
7110
- }
7111
- throw new Error(`Non-${name} character`);
7112
- }
7113
- return {
7114
- encode,
7115
- decodeUnsafe,
7116
- decode
7117
- };
7118
- }
7119
- var src = base;
7120
- var _brrp__multiformats_scope_baseX = src;
7121
- var base_x_default = _brrp__multiformats_scope_baseX;
7122
-
7123
- // ../../../../node_modules/multiformats/dist/src/bases/base.js
7124
- var Encoder = class {
7125
- name;
7126
- prefix;
7127
- baseEncode;
7128
- constructor(name, prefix, baseEncode) {
7129
- this.name = name;
7130
- this.prefix = prefix;
7131
- this.baseEncode = baseEncode;
7132
- }
7133
- encode(bytes) {
7134
- if (bytes instanceof Uint8Array) {
7135
- return `${this.prefix}${this.baseEncode(bytes)}`;
7136
- } else {
7137
- throw Error("Unknown type, must be binary type");
7138
- }
7139
- }
7140
- };
7141
- var Decoder = class {
7142
- name;
7143
- prefix;
7144
- baseDecode;
7145
- prefixCodePoint;
7146
- constructor(name, prefix, baseDecode) {
7147
- this.name = name;
7148
- this.prefix = prefix;
7149
- if (prefix.codePointAt(0) === void 0) {
7150
- throw new Error("Invalid prefix character");
7151
- }
7152
- this.prefixCodePoint = prefix.codePointAt(0);
7153
- this.baseDecode = baseDecode;
7154
- }
7155
- decode(text) {
7156
- if (typeof text === "string") {
7157
- if (text.codePointAt(0) !== this.prefixCodePoint) {
7158
- throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
7159
- }
7160
- return this.baseDecode(text.slice(this.prefix.length));
7161
- } else {
7162
- throw Error("Can only multibase decode strings");
7163
- }
7164
- }
7165
- or(decoder) {
7166
- return or(this, decoder);
7167
- }
7168
- };
7169
- var ComposedDecoder = class {
7170
- decoders;
7171
- constructor(decoders) {
7172
- this.decoders = decoders;
7173
- }
7174
- or(decoder) {
7175
- return or(this, decoder);
7176
- }
7177
- decode(input) {
7178
- const prefix = input[0];
7179
- const decoder = this.decoders[prefix];
7180
- if (decoder != null) {
7181
- return decoder.decode(input);
7182
- } else {
7183
- throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
7200
+ w[i] = readUint32BE(p, j);
7184
7201
  }
7202
+ for (let i = 16; i < 64; i++) {
7203
+ let u = w[i - 2];
7204
+ let t1 = (u >>> 17 | u << 32 - 17) ^ (u >>> 19 | u << 32 - 19) ^ u >>> 10;
7205
+ u = w[i - 15];
7206
+ let t2 = (u >>> 7 | u << 32 - 7) ^ (u >>> 18 | u << 32 - 18) ^ u >>> 3;
7207
+ w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);
7208
+ }
7209
+ for (let i = 0; i < 64; i++) {
7210
+ let t1 = (((e >>> 6 | e << 32 - 6) ^ (e >>> 11 | e << 32 - 11) ^ (e >>> 25 | e << 32 - 25)) + (e & f ^ ~e & g) | 0) + (h + (K[i] + w[i] | 0) | 0) | 0;
7211
+ let t2 = ((a >>> 2 | a << 32 - 2) ^ (a >>> 13 | a << 32 - 13) ^ (a >>> 22 | a << 32 - 22)) + (a & b ^ a & c ^ b & c) | 0;
7212
+ h = g;
7213
+ g = f;
7214
+ f = e;
7215
+ e = d + t1 | 0;
7216
+ d = c;
7217
+ c = b;
7218
+ b = a;
7219
+ a = t1 + t2 | 0;
7220
+ }
7221
+ v2[0] += a;
7222
+ v2[1] += b;
7223
+ v2[2] += c;
7224
+ v2[3] += d;
7225
+ v2[4] += e;
7226
+ v2[5] += f;
7227
+ v2[6] += g;
7228
+ v2[7] += h;
7229
+ pos += 64;
7230
+ len -= 64;
7185
7231
  }
7186
- };
7187
- function or(left, right) {
7188
- return new ComposedDecoder({
7189
- ...left.decoders ?? { [left.prefix]: left },
7190
- ...right.decoders ?? { [right.prefix]: right }
7191
- });
7192
- }
7193
- var Codec = class {
7194
- name;
7195
- prefix;
7196
- baseEncode;
7197
- baseDecode;
7198
- encoder;
7199
- decoder;
7200
- constructor(name, prefix, baseEncode, baseDecode) {
7201
- this.name = name;
7202
- this.prefix = prefix;
7203
- this.baseEncode = baseEncode;
7204
- this.baseDecode = baseDecode;
7205
- this.encoder = new Encoder(name, prefix, baseEncode);
7206
- this.decoder = new Decoder(name, prefix, baseDecode);
7207
- }
7208
- encode(input) {
7209
- return this.encoder.encode(input);
7210
- }
7211
- decode(input) {
7212
- return this.decoder.decode(input);
7213
- }
7214
- };
7215
- function from({ name, prefix, encode, decode }) {
7216
- return new Codec(name, prefix, encode, decode);
7217
- }
7218
- function baseX({ name, prefix, alphabet }) {
7219
- const { encode, decode } = base_x_default(alphabet, name);
7220
- return from({
7221
- prefix,
7222
- name,
7223
- encode,
7224
- decode: (text) => coerce(decode(text))
7225
- });
7232
+ return pos;
7226
7233
  }
7227
7234
 
7228
- // ../../../../node_modules/multiformats/dist/src/bases/base58.js
7229
- var base58btc = baseX({
7230
- name: "base58btc",
7231
- prefix: "z",
7232
- alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
7233
- });
7234
- var base58flickr = baseX({
7235
- name: "base58flickr",
7236
- prefix: "Z",
7237
- alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
7238
- });
7239
-
7240
7235
  // ../../crypto/dist/src/utils.js
7236
+ var import_libsodium_wrappers = __toESM(require_libsodium_wrappers(), 1);
7241
7237
  var toHexString = (bytes) => import_libsodium_wrappers.default.to_hex(bytes);
7242
7238
  var toBase64 = (arr) => {
7243
7239
  return import_libsodium_wrappers.default.to_base64(arr, import_libsodium_wrappers.default.base64_variants.ORIGINAL);
@@ -7247,7 +7243,6 @@ var toBase58 = (arr) => {
7247
7243
  };
7248
7244
 
7249
7245
  // ../../crypto/dist/src/hash.browser.js
7250
- var sha256Base64Sync = (bytes) => toBase64(new SHA256().update(bytes).digest());
7251
7246
  var sha256Sync = (bytes) => new SHA256().update(bytes).digest();
7252
7247
 
7253
7248
  // ../../../../node_modules/uint8-varint/dist/src/index.js
@@ -7372,9 +7367,6 @@ function decodeUint8Array(buf, offset) {
7372
7367
  throw new RangeError("Could not decode varint");
7373
7368
  }
7374
7369
 
7375
- // ../../crypto/dist/src/random.browser.js
7376
- var randomBytes = (len) => globalThis.crypto.getRandomValues(new Uint8Array(len));
7377
-
7378
7370
  // ../interface/dist/src/id.js
7379
7371
  var __decorate = function(decorators, target, key, desc) {
7380
7372
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -7543,6 +7535,16 @@ var toId = (obj) => {
7543
7535
  throw new Error("Unexpected index key: " + typeof obj + ", expected: string, number, bigint or Uint8Array");
7544
7536
  };
7545
7537
 
7538
+ // ../../../../node_modules/uuid/dist/esm-browser/stringify.js
7539
+ var byteToHex = [];
7540
+ for (i = 0; i < 256; ++i) {
7541
+ byteToHex.push((i + 256).toString(16).slice(1));
7542
+ }
7543
+ var i;
7544
+ function unsafeStringify(arr, offset = 0) {
7545
+ return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
7546
+ }
7547
+
7546
7548
  // ../../../../node_modules/uuid/dist/esm-browser/rng.js
7547
7549
  var getRandomValues;
7548
7550
  var rnds8 = new Uint8Array(16);
@@ -7556,15 +7558,6 @@ function rng() {
7556
7558
  return getRandomValues(rnds8);
7557
7559
  }
7558
7560
 
7559
- // ../../../../node_modules/uuid/dist/esm-browser/stringify.js
7560
- var byteToHex = [];
7561
- for (let i = 0; i < 256; ++i) {
7562
- byteToHex.push((i + 256).toString(16).slice(1));
7563
- }
7564
- function unsafeStringify(arr, offset = 0) {
7565
- return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
7566
- }
7567
-
7568
7561
  // ../../../../node_modules/uuid/dist/esm-browser/native.js
7569
7562
  var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
7570
7563
  var native_default = {
@@ -7577,12 +7570,12 @@ function v4(options, buf, offset) {
7577
7570
  return native_default.randomUUID();
7578
7571
  }
7579
7572
  options = options || {};
7580
- const rnds = options.random || (options.rng || rng)();
7573
+ var rnds = options.random || (options.rng || rng)();
7581
7574
  rnds[6] = rnds[6] & 15 | 64;
7582
7575
  rnds[8] = rnds[8] & 63 | 128;
7583
7576
  if (buf) {
7584
7577
  offset = offset || 0;
7585
- for (let i = 0; i < 16; ++i) {
7578
+ for (var i = 0; i < 16; ++i) {
7586
7579
  buf[offset + i] = rnds[i];
7587
7580
  }
7588
7581
  return buf;
@@ -7649,94 +7642,6 @@ Sort = __decorate2([
7649
7642
  variant(0),
7650
7643
  __metadata2("design:paramtypes", [Object])
7651
7644
  ], Sort);
7652
- var AbstractSearchRequest = class {
7653
- };
7654
- var toArray = (arr) => (arr ? Array.isArray(arr) ? arr : [arr] : void 0) || [];
7655
- var SearchRequest = class SearchRequest2 extends AbstractSearchRequest {
7656
- id;
7657
- // Session id
7658
- query;
7659
- sort;
7660
- fetch;
7661
- constructor(props) {
7662
- super();
7663
- this.id = randomBytes(32);
7664
- this.query = props?.query ? toQuery(props.query) : [];
7665
- this.sort = toArray(props?.sort);
7666
- this.fetch = props?.fetch ?? 10;
7667
- }
7668
- _idString;
7669
- get idString() {
7670
- return this._idString || (this._idString = sha256Base64Sync(this.id));
7671
- }
7672
- };
7673
- __decorate2([
7674
- field({ type: fixedArray("u8", 32) }),
7675
- __metadata2("design:type", Uint8Array)
7676
- ], SearchRequest.prototype, "id", void 0);
7677
- __decorate2([
7678
- field({ type: vec(Query) }),
7679
- __metadata2("design:type", Array)
7680
- ], SearchRequest.prototype, "query", void 0);
7681
- __decorate2([
7682
- field({ type: vec(Sort) }),
7683
- __metadata2("design:type", Array)
7684
- ], SearchRequest.prototype, "sort", void 0);
7685
- __decorate2([
7686
- field({ type: "u32" }),
7687
- __metadata2("design:type", Number)
7688
- ], SearchRequest.prototype, "fetch", void 0);
7689
- SearchRequest = __decorate2([
7690
- variant(0),
7691
- __metadata2("design:paramtypes", [Object])
7692
- ], SearchRequest);
7693
- var CollectNextRequest = class CollectNextRequest2 extends AbstractSearchRequest {
7694
- id;
7695
- // collect with id
7696
- amount;
7697
- // number of documents to ask for
7698
- constructor(properties) {
7699
- super();
7700
- this.id = properties.id;
7701
- this.amount = properties.amount;
7702
- }
7703
- _idString;
7704
- get idString() {
7705
- return this._idString || (this._idString = sha256Base64Sync(this.id));
7706
- }
7707
- };
7708
- __decorate2([
7709
- field({ type: fixedArray("u8", 32) }),
7710
- __metadata2("design:type", Uint8Array)
7711
- ], CollectNextRequest.prototype, "id", void 0);
7712
- __decorate2([
7713
- field({ type: "u32" }),
7714
- __metadata2("design:type", Number)
7715
- ], CollectNextRequest.prototype, "amount", void 0);
7716
- CollectNextRequest = __decorate2([
7717
- variant(2),
7718
- __metadata2("design:paramtypes", [Object])
7719
- ], CollectNextRequest);
7720
- var CloseIteratorRequest = class CloseIteratorRequest2 extends AbstractSearchRequest {
7721
- id;
7722
- // collect with id
7723
- constructor(properties) {
7724
- super();
7725
- this.id = properties.id;
7726
- }
7727
- _idString;
7728
- get idString() {
7729
- return this._idString || (this._idString = sha256Base64Sync(this.id));
7730
- }
7731
- };
7732
- __decorate2([
7733
- field({ type: fixedArray("u8", 32) }),
7734
- __metadata2("design:type", Uint8Array)
7735
- ], CloseIteratorRequest.prototype, "id", void 0);
7736
- CloseIteratorRequest = __decorate2([
7737
- variant(3),
7738
- __metadata2("design:paramtypes", [Object])
7739
- ], CloseIteratorRequest);
7740
7645
  var LogicalQuery = class LogicalQuery2 extends Query {
7741
7646
  };
7742
7647
  LogicalQuery = __decorate2([
@@ -7967,84 +7872,10 @@ Nested = __decorate2([
7967
7872
  variant(2),
7968
7873
  __metadata2("design:paramtypes", [Object])
7969
7874
  ], Nested);
7970
- var AbstractAggregationRequest = class {
7971
- };
7972
- var SumRequest = class SumRequest2 extends AbstractAggregationRequest {
7973
- id;
7974
- query;
7975
- key;
7976
- constructor(props) {
7977
- super();
7978
- this.id = randomBytes(32);
7979
- this.query = props.query ? toQuery(props.query) : [];
7980
- this.key = Array.isArray(props.key) ? props.key : [props.key];
7981
- }
7982
- };
7983
- __decorate2([
7984
- field({ type: fixedArray("u8", 32) }),
7985
- __metadata2("design:type", Uint8Array)
7986
- ], SumRequest.prototype, "id", void 0);
7987
- __decorate2([
7988
- field({ type: vec(Query) }),
7989
- __metadata2("design:type", Array)
7990
- ], SumRequest.prototype, "query", void 0);
7991
- __decorate2([
7992
- field({ type: vec("string") }),
7993
- __metadata2("design:type", Array)
7994
- ], SumRequest.prototype, "key", void 0);
7995
- SumRequest = __decorate2([
7996
- variant(0),
7997
- __metadata2("design:paramtypes", [Object])
7998
- ], SumRequest);
7999
- var AbstractCountRequest = class {
8000
- };
8001
- var CountRequest = class CountRequest2 extends AbstractCountRequest {
8002
- id;
8003
- // Session id
8004
- query;
8005
- constructor(props = { query: [] }) {
8006
- super();
8007
- this.id = randomBytes(32);
8008
- this.query = toQuery(props.query);
8009
- }
8010
- };
8011
- __decorate2([
8012
- field({ type: fixedArray("u8", 32) }),
8013
- __metadata2("design:type", Uint8Array)
8014
- ], CountRequest.prototype, "id", void 0);
8015
- __decorate2([
8016
- field({ type: vec(Query) }),
8017
- __metadata2("design:type", Array)
8018
- ], CountRequest.prototype, "query", void 0);
8019
- CountRequest = __decorate2([
8020
- variant(0),
8021
- __metadata2("design:paramtypes", [Object])
8022
- ], CountRequest);
8023
- var AbstractDeleteRequest = class {
8024
- };
8025
- var DeleteRequest = class DeleteRequest2 extends AbstractDeleteRequest {
8026
- id;
8027
- // Session id
8028
- query;
8029
- constructor(props) {
8030
- super();
8031
- this.id = randomBytes(32);
8032
- this.query = toQuery(props.query);
8033
- }
8034
- };
8035
- __decorate2([
8036
- field({ type: fixedArray("u8", 32) }),
8037
- __metadata2("design:type", Uint8Array)
8038
- ], DeleteRequest.prototype, "id", void 0);
8039
- __decorate2([
8040
- field({ type: vec(Query) }),
8041
- __metadata2("design:type", Array)
8042
- ], DeleteRequest.prototype, "query", void 0);
8043
- DeleteRequest = __decorate2([
8044
- variant(0),
8045
- __metadata2("design:paramtypes", [Object])
8046
- ], DeleteRequest);
8047
7875
  var toQuery = (query) => {
7876
+ if (!query) {
7877
+ return [];
7878
+ }
8048
7879
  if (Array.isArray(query)) {
8049
7880
  return query;
8050
7881
  }
@@ -8608,8 +8439,17 @@ var insert = async (insertFn, obj, tables, table, fields, handleNestedCallback,
8608
8439
  var getTablePrefixedField = (table, key, skipPrefix = false) => `${skipPrefix ? "" : table.name + "#"}${getInlineTableFieldName(table.path.slice(1), key)}`;
8609
8440
  var getInlineTableFieldName = (path, key) => {
8610
8441
  if (key) {
8611
- return path && path.length > 0 ? `${path.join("_")}__${key}` : key;
8442
+ if (Array.isArray(path)) {
8443
+ return path && path.length > 0 ? `${path.join("_")}__${key}` : key;
8444
+ }
8445
+ return path + "__" + key;
8612
8446
  } else {
8447
+ if (!Array.isArray(path)) {
8448
+ if (!path) {
8449
+ throw new Error("Unexpected missing path");
8450
+ }
8451
+ return path;
8452
+ }
8613
8453
  return path.length > 2 ? `${path.slice(0, -1).join("_")}__${path[path.length - 1]}` : path.join("__");
8614
8454
  }
8615
8455
  };
@@ -8630,7 +8470,11 @@ var matchFieldInShape = (shape, path, field2) => {
8630
8470
  if (nextShape === true) {
8631
8471
  return true;
8632
8472
  }
8633
- currentShape = nextShape;
8473
+ if (Array.isArray(nextShape)) {
8474
+ currentShape = nextShape[0];
8475
+ } else {
8476
+ currentShape = nextShape;
8477
+ }
8634
8478
  }
8635
8479
  }
8636
8480
  throw new Error("Unexpected");
@@ -8690,7 +8534,7 @@ var selectAllFieldsFromTable = (table, shape) => {
8690
8534
  if (!maybeShape) {
8691
8535
  continue;
8692
8536
  }
8693
- childShape = maybeShape === true ? void 0 : maybeShape;
8537
+ childShape = maybeShape === true ? void 0 : Array.isArray(maybeShape) ? maybeShape[0] : maybeShape;
8694
8538
  }
8695
8539
  stack.push({ table: child, shape: childShape });
8696
8540
  if (!child.inline) {
@@ -8723,7 +8567,11 @@ var resolveInstanceFromValue = async (fromTablePrefixedValues, tables, table, re
8723
8567
  const handleNested = async (field2, isOptional, isArray) => {
8724
8568
  const subTables = getTableFromField(table, tables, field2);
8725
8569
  let maybeShape = shape?.[field2.key];
8726
- let subshape = maybeShape === true ? void 0 : maybeShape;
8570
+ const subshapeIsArray = Array.isArray(maybeShape);
8571
+ if (isArray && maybeShape && !subshapeIsArray && maybeShape !== true) {
8572
+ throw new Error("Shape is not matching the array field type: " + field2.key + ". Shape: " + JSON.stringify(shape));
8573
+ }
8574
+ let subshape = maybeShape === true ? void 0 : subshapeIsArray ? maybeShape[0] : maybeShape;
8727
8575
  if (isArray) {
8728
8576
  let once = false;
8729
8577
  let resolvedArr = [];
@@ -8808,13 +8656,25 @@ var resolveInstanceFromValue = async (fromTablePrefixedValues, tables, table, re
8808
8656
  return Object.assign(Object.create(table.ctor.prototype), obj);
8809
8657
  };
8810
8658
  var convertDeleteRequestToQuery = (request, tables, table) => {
8811
- return `DELETE FROM ${table.name} WHERE ${table.primary} IN (SELECT ${table.primary} from ${table.name} ${convertRequestToQuery(request, tables, table).query}) returning ${table.primary}`;
8659
+ const { query, bindable } = convertRequestToQuery("delete", request, tables, table);
8660
+ return {
8661
+ sql: `DELETE FROM ${table.name} WHERE ${table.primary} IN (SELECT ${table.primary} from ${table.name} ${query}) returning ${table.primary}`,
8662
+ bindable
8663
+ };
8812
8664
  };
8813
8665
  var convertSumRequestToQuery = (request, tables, table) => {
8814
- return `SELECT SUM(${table.name}.${getInlineTableFieldName(request.key)}) as sum FROM ${table.name} ${convertRequestToQuery(request, tables, table).query}`;
8666
+ const { query, bindable } = convertRequestToQuery("sum", request, tables, table);
8667
+ return {
8668
+ sql: `SELECT SUM(${table.name}.${getInlineTableFieldName(request.key)}) as sum FROM ${table.name} ${query}`,
8669
+ bindable
8670
+ };
8815
8671
  };
8816
8672
  var convertCountRequestToQuery = (request, tables, table) => {
8817
- return `SELECT count(*) as count FROM ${table.name} ${convertRequestToQuery(request, tables, table).query}`;
8673
+ const { query, bindable } = convertRequestToQuery("count", request, tables, table);
8674
+ return {
8675
+ sql: `SELECT count(*) as count FROM ${table.name} ${query}`,
8676
+ bindable
8677
+ };
8818
8678
  };
8819
8679
  var convertSearchRequestToQuery = (request, tables, rootTables, shape) => {
8820
8680
  let unionBuilder = "";
@@ -8822,14 +8682,16 @@ var convertSearchRequestToQuery = (request, tables, rootTables, shape) => {
8822
8682
  let matchedOnce = false;
8823
8683
  let lastError = void 0;
8824
8684
  const selectsPerTable = selectAllFieldsFromTables(rootTables, shape);
8685
+ let bindableBuilder = [];
8825
8686
  for (const [i, table] of rootTables.entries()) {
8826
8687
  const { selects, joins: joinFromSelect } = selectsPerTable[i];
8827
8688
  const selectQuery = generateSelectQuery(table, selects);
8828
8689
  try {
8829
- const { orderBy, query } = convertRequestToQuery(request, tables, table, joinFromSelect);
8690
+ const { orderBy, query, bindable } = convertRequestToQuery("iterate", request, tables, table, joinFromSelect);
8830
8691
  unionBuilder += `${unionBuilder.length > 0 ? " UNION ALL " : ""} ${selectQuery} ${query}`;
8831
8692
  orderByClause = orderBy?.length > 0 ? orderByClause.length > 0 ? orderByClause + ", " + orderBy : orderBy : orderByClause;
8832
8693
  matchedOnce = true;
8694
+ bindableBuilder.push(...bindable);
8833
8695
  } catch (error2) {
8834
8696
  if (error2 instanceof MissingFieldError) {
8835
8697
  lastError = error2;
@@ -8841,31 +8703,44 @@ var convertSearchRequestToQuery = (request, tables, rootTables, shape) => {
8841
8703
  if (!matchedOnce) {
8842
8704
  throw lastError;
8843
8705
  }
8844
- return `${unionBuilder} ${orderByClause ? "ORDER BY " + orderByClause : ""} limit ? offset ?`;
8706
+ return {
8707
+ sql: `${unionBuilder} ${orderByClause ? "ORDER BY " + orderByClause : ""} limit ? offset ?`,
8708
+ bindable: bindableBuilder
8709
+ };
8845
8710
  };
8846
- var convertRequestToQuery = (request, tables, table, extraJoin, path = []) => {
8711
+ function isIterateRequest(request, type) {
8712
+ return type === "iterate";
8713
+ }
8714
+ var convertRequestToQuery = (type, request, tables, table, extraJoin, path = []) => {
8847
8715
  let whereBuilder = "";
8716
+ let bindableBuilder = [];
8848
8717
  let orderByBuilder = void 0;
8849
8718
  let joinBuilder = extraJoin || /* @__PURE__ */ new Map();
8850
- if (request.query.length === 1) {
8851
- const { where: where2 } = convertQueryToSQLQuery(request.query[0], tables, table, joinBuilder, path);
8719
+ const coercedQuery = toQuery(request?.query);
8720
+ if (coercedQuery.length === 1) {
8721
+ const { where: where2, bindable } = convertQueryToSQLQuery(coercedQuery[0], tables, table, joinBuilder, path);
8852
8722
  whereBuilder += where2;
8853
- } else if (request.query.length > 1) {
8854
- const { where: where2 } = convertQueryToSQLQuery(new And(request.query), tables, table, joinBuilder, path);
8723
+ bindableBuilder.push(...bindable);
8724
+ } else if (coercedQuery.length > 1) {
8725
+ const { where: where2, bindable } = convertQueryToSQLQuery(new And(coercedQuery), tables, table, joinBuilder, path);
8855
8726
  whereBuilder += where2;
8856
- }
8857
- if (request instanceof SearchRequest) {
8858
- if (request.sort.length > 0) {
8859
- orderByBuilder = "";
8860
- let once = false;
8861
- for (const sort of request.sort) {
8862
- const { foreignTables, queryKey } = resolveTableToQuery(table, tables, joinBuilder, [...path, ...sort.key], void 0, true);
8863
- for (const table2 of foreignTables) {
8864
- if (once) {
8865
- orderByBuilder += ", ";
8727
+ bindableBuilder.push(...bindable);
8728
+ }
8729
+ if (isIterateRequest(request, type)) {
8730
+ if (request?.sort) {
8731
+ let sortArr = Array.isArray(request.sort) ? request.sort : [request.sort];
8732
+ if (sortArr.length > 0) {
8733
+ orderByBuilder = "";
8734
+ let once = false;
8735
+ for (const sort of sortArr) {
8736
+ const { foreignTables, queryKey } = resolveTableToQuery(table, tables, joinBuilder, [...path, ...sort.key], void 0, true);
8737
+ for (const table2 of foreignTables) {
8738
+ if (once) {
8739
+ orderByBuilder += ", ";
8740
+ }
8741
+ once = true;
8742
+ orderByBuilder += `${table2.as}.${queryKey} ${sort.direction === SortDirection.ASC ? "ASC" : "DESC"}`;
8866
8743
  }
8867
- once = true;
8868
- orderByBuilder += `${table2.as}.${queryKey} ${sort.direction === SortDirection.ASC ? "ASC" : "DESC"}`;
8869
8744
  }
8870
8745
  }
8871
8746
  }
@@ -8874,11 +8749,12 @@ var convertRequestToQuery = (request, tables, table, extraJoin, path = []) => {
8874
8749
  if (extraJoin && extraJoin.size > 0) {
8875
8750
  insertMapIntoMap(joinBuilder, extraJoin);
8876
8751
  }
8877
- let join = buildJoin(joinBuilder, request instanceof SearchRequest ? true : false);
8752
+ let join = buildJoin(joinBuilder, type === "iterate" ? true : false);
8878
8753
  const query = `${join ? join : ""} ${where ? where : ""}`;
8879
8754
  return {
8880
8755
  query,
8881
- orderBy: orderByBuilder
8756
+ orderBy: orderByBuilder,
8757
+ bindable: bindableBuilder
8882
8758
  };
8883
8759
  };
8884
8760
  var buildJoin = (joinBuilder, resolveAllColumns) => {
@@ -8907,15 +8783,18 @@ var insertMapIntoMap = (map, insert2) => {
8907
8783
  };
8908
8784
  var convertQueryToSQLQuery = (query, tables, table, joinBuilder, path = [], tableAlias = void 0) => {
8909
8785
  let whereBuilder = "";
8786
+ let bindableBuilder = [];
8910
8787
  const handleAnd = (queries, path2, tableAlias2) => {
8911
8788
  for (const query2 of queries) {
8912
- const { where } = convertQueryToSQLQuery(query2, tables, table, joinBuilder, path2, tableAlias2);
8789
+ const { where, bindable } = convertQueryToSQLQuery(query2, tables, table, joinBuilder, path2, tableAlias2);
8913
8790
  whereBuilder = whereBuilder.length > 0 ? `(${whereBuilder}) AND (${where})` : where;
8791
+ bindableBuilder.push(...bindable);
8914
8792
  }
8915
8793
  };
8916
8794
  if (query instanceof StateFieldQuery) {
8917
- const { where } = convertStateFieldQuery(query, tables, table, joinBuilder, path, tableAlias);
8795
+ const { where, bindable } = convertStateFieldQuery(query, tables, table, joinBuilder, path, tableAlias);
8918
8796
  whereBuilder += where;
8797
+ bindableBuilder.push(...bindable);
8919
8798
  } else if (query instanceof Nested) {
8920
8799
  let joinPrefix = "__" + String(tables.size);
8921
8800
  path = [...path, query.path];
@@ -8925,12 +8804,14 @@ var convertQueryToSQLQuery = (query, tables, table, joinBuilder, path = [], tabl
8925
8804
  handleAnd(query.and, path, tableAlias);
8926
8805
  } else if (query instanceof Or) {
8927
8806
  for (const subquery of query.or) {
8928
- const { where } = convertQueryToSQLQuery(subquery, tables, table, joinBuilder, path, tableAlias);
8807
+ const { where, bindable } = convertQueryToSQLQuery(subquery, tables, table, joinBuilder, path, tableAlias);
8929
8808
  whereBuilder = whereBuilder.length > 0 ? `(${whereBuilder}) OR (${where})` : where;
8809
+ bindableBuilder.push(...bindable);
8930
8810
  }
8931
8811
  } else if (query instanceof Not) {
8932
- const { where } = convertQueryToSQLQuery(query.not, tables, table, joinBuilder, path, tableAlias);
8812
+ const { where, bindable } = convertQueryToSQLQuery(query.not, tables, table, joinBuilder, path, tableAlias);
8933
8813
  whereBuilder = `NOT (${where})`;
8814
+ bindableBuilder.push(...bindable);
8934
8815
  } else {
8935
8816
  throw new Error("Unsupported query type: " + query.constructor.name);
8936
8817
  }
@@ -8938,7 +8819,8 @@ var convertQueryToSQLQuery = (query, tables, table, joinBuilder, path = [], tabl
8938
8819
  throw new Error("Unsupported query type: " + query.constructor.name);
8939
8820
  }
8940
8821
  return {
8941
- where: whereBuilder
8822
+ where: whereBuilder,
8823
+ bindable: bindableBuilder
8942
8824
  };
8943
8825
  };
8944
8826
  var cloneQuery = (query) => {
@@ -9026,70 +8908,85 @@ var convertStateFieldQuery = (query, tables, table, join, path, tableAlias = voi
9026
8908
  query = cloneQuery(query);
9027
8909
  query.key = [queryKey];
9028
8910
  let whereBuilder = [];
8911
+ let bindableBuilder = [];
9029
8912
  for (const ftable of foreignTables) {
9030
8913
  if (ftable.table === table) {
9031
8914
  throw new Error("Unexpected");
9032
8915
  }
9033
- const { where: where2 } = convertQueryToSQLQuery(query, tables, ftable.table, join, path, ftable.as);
8916
+ const { where: where2, bindable: bindable2 } = convertQueryToSQLQuery(query, tables, ftable.table, join, path, ftable.as);
9034
8917
  whereBuilder.push(where2);
8918
+ bindableBuilder.push(bindable2);
9035
8919
  }
9036
- return { where: whereBuilder.join(" OR ") };
8920
+ return {
8921
+ where: whereBuilder.join(" OR "),
8922
+ bindable: bindableBuilder.flat()
8923
+ };
9037
8924
  }
8925
+ let bindable = [];
9038
8926
  const keyWithTable = (tableAlias || table.name) + "." + escapeColumnName(inlinedName);
9039
8927
  let where;
9040
8928
  if (query instanceof StringMatch) {
9041
8929
  let statement = "";
9042
8930
  if (query.method === StringMatchMethod.contains) {
9043
- statement = `${keyWithTable} LIKE '%${query.value}%'`;
8931
+ statement = `${keyWithTable} LIKE ?`;
8932
+ bindable.push(`%${query.value}%`);
9044
8933
  } else if (query.method === StringMatchMethod.prefix) {
9045
- statement = `${keyWithTable} LIKE '${query.value}%'`;
8934
+ statement = `${keyWithTable} LIKE ?`;
8935
+ bindable.push(`${query.value}%`);
9046
8936
  } else if (query.method === StringMatchMethod.exact) {
9047
- statement = `${keyWithTable} = '${query.value}'`;
8937
+ statement = `${keyWithTable} = ?`;
8938
+ bindable.push(`${query.value}`);
9048
8939
  }
9049
8940
  if (query.caseInsensitive) {
9050
8941
  statement += " COLLATE NOCASE";
9051
8942
  }
9052
8943
  where = statement;
9053
8944
  } else if (query instanceof ByteMatchQuery) {
9054
- const statement = `${keyWithTable} = x'${toHexString(query.value)}'`;
8945
+ const statement = `${keyWithTable} = ?`;
8946
+ bindable.push(query.value);
9055
8947
  where = statement;
9056
8948
  } else if (query instanceof IntegerCompare) {
9057
8949
  if (tableField.type === "BLOB") {
9058
- where = `hex(${keyWithTable}) LIKE '%${toHexString(new Uint8Array([Number(query.value.value)]))}%'`;
9059
- } else if (query.compare === Compare.Equal) {
9060
- where = `${keyWithTable} = ${query.value.value}`;
9061
- } else if (query.compare === Compare.Greater) {
9062
- where = `${keyWithTable} > ${query.value.value}`;
9063
- } else if (query.compare === Compare.Less) {
9064
- where = `${keyWithTable} < ${query.value.value}`;
9065
- } else if (query.compare === Compare.GreaterOrEqual) {
9066
- where = `${keyWithTable} >= ${query.value.value}`;
9067
- } else if (query.compare === Compare.LessOrEqual) {
9068
- where = `${keyWithTable} <= ${query.value.value}`;
8950
+ where = `hex(${keyWithTable}) LIKE ?`;
8951
+ bindable.push(`%${toHexString(new Uint8Array([Number(query.value.value)]))}%`);
9069
8952
  } else {
9070
- throw new Error(`Unsupported compare type: ${query.compare}`);
8953
+ if (query.compare === Compare.Equal) {
8954
+ where = `${keyWithTable} = ?`;
8955
+ } else if (query.compare === Compare.Greater) {
8956
+ where = `${keyWithTable} > ?`;
8957
+ } else if (query.compare === Compare.Less) {
8958
+ where = `${keyWithTable} < ?`;
8959
+ } else if (query.compare === Compare.GreaterOrEqual) {
8960
+ where = `${keyWithTable} >= ?`;
8961
+ } else if (query.compare === Compare.LessOrEqual) {
8962
+ where = `${keyWithTable} <= ?`;
8963
+ } else {
8964
+ throw new Error(`Unsupported compare type: ${query.compare}`);
8965
+ }
8966
+ bindable.push(query.value.value);
9071
8967
  }
9072
8968
  } else if (query instanceof IsNull) {
9073
8969
  where = `${keyWithTable} IS NULL`;
9074
8970
  } else if (query instanceof BoolQuery) {
9075
- where = `${keyWithTable} = ${query.value}`;
8971
+ where = `${keyWithTable} = ?`;
8972
+ bindable.push(query.value ? 1 : 0);
9076
8973
  } else {
9077
8974
  throw new Error("Unsupported query type: " + query.constructor.name);
9078
8975
  }
9079
- return { where };
8976
+ return { where, bindable };
9080
8977
  };
9081
8978
 
9082
8979
  // dist/src/engine.js
9083
8980
  var escapePathToSQLName = (path) => {
9084
8981
  return path.map((x) => x.replace(/[^a-zA-Z0-9]/g, "_"));
9085
8982
  };
8983
+ var putStatementKey = (table) => table.name + "_put";
8984
+ var replaceStatementKey = (table) => table.name + "_replicate";
8985
+ var resolveChildrenStatement = (table) => table.name + "_resolve_children";
9086
8986
  var SQLLiteIndex = class {
9087
8987
  properties;
9088
8988
  primaryKeyArr;
9089
8989
  primaryKeyString;
9090
- putStatement;
9091
- replaceStatement;
9092
- resolveChildrenStatement;
9093
8990
  scopeString;
9094
8991
  _rootTables;
9095
8992
  _tables;
@@ -9147,9 +9044,6 @@ var SQLLiteIndex = class {
9147
9044
  throw new Error("Not initialized");
9148
9045
  }
9149
9046
  await this.properties.start?.();
9150
- this.putStatement = /* @__PURE__ */ new Map();
9151
- this.replaceStatement = /* @__PURE__ */ new Map();
9152
- this.resolveChildrenStatement = /* @__PURE__ */ new Map();
9153
9047
  this._tables = /* @__PURE__ */ new Map();
9154
9048
  this._cursor = /* @__PURE__ */ new Map();
9155
9049
  const tables = getSQLTable(
@@ -9177,10 +9071,10 @@ var SQLLiteIndex = class {
9177
9071
  this.properties.db.exec(sqlCreateIndex);
9178
9072
  let sqlPut = `insert into ${table.name} (${table.fields.map((field2) => escapeColumnName(field2.name)).join(", ")}) VALUES (${table.fields.map((_x) => "?").join(", ")}) RETURNING ${table.primary};`;
9179
9073
  let sqlReplace = `insert or replace into ${table.name} (${table.fields.map((field2) => escapeColumnName(field2.name)).join(", ")}) VALUES (${table.fields.map((_x) => "?").join(", ")});`;
9180
- this.putStatement.set(table.name, await this.properties.db.prepare(sqlPut));
9181
- this.replaceStatement.set(table.name, await this.properties.db.prepare(sqlReplace));
9074
+ await this.properties.db.prepare(sqlPut, putStatementKey(table));
9075
+ await this.properties.db.prepare(sqlReplace, replaceStatementKey(table));
9182
9076
  if (table.parent) {
9183
- this.resolveChildrenStatement.set(table.name, await this.properties.db.prepare(selectChildren(table)));
9077
+ await this.properties.db.prepare(selectChildren(table), resolveChildrenStatement(table));
9184
9078
  }
9185
9079
  }
9186
9080
  this.closed = false;
@@ -9189,18 +9083,6 @@ var SQLLiteIndex = class {
9189
9083
  if (await this.properties.db.status() === "closed") {
9190
9084
  return;
9191
9085
  }
9192
- for (const [_k, v2] of this.putStatement) {
9193
- await v2.finalize?.();
9194
- }
9195
- for (const [_k, v2] of this.replaceStatement) {
9196
- await v2.finalize?.();
9197
- }
9198
- for (const [_k, v2] of this.resolveChildrenStatement) {
9199
- await v2.finalize?.();
9200
- }
9201
- this.putStatement.clear();
9202
- this.replaceStatement.clear();
9203
- this.resolveChildrenStatement.clear();
9204
9086
  }
9205
9087
  async stop() {
9206
9088
  if (this.closed) {
@@ -9225,7 +9107,7 @@ var SQLLiteIndex = class {
9225
9107
  }
9226
9108
  }
9227
9109
  async resolveDependencies(parentId, table) {
9228
- const stmt = this.resolveChildrenStatement.get(table.name);
9110
+ const stmt = this.properties.db.statements.get(resolveChildrenStatement(table));
9229
9111
  const results = await stmt.all([parentId]);
9230
9112
  await stmt.reset?.();
9231
9113
  return results;
@@ -9234,9 +9116,8 @@ var SQLLiteIndex = class {
9234
9116
  for (const table of this._rootTables) {
9235
9117
  const { join: joinMap, selects } = selectAllFieldsFromTable(table, options?.shape);
9236
9118
  const sql = `${generateSelectQuery(table, selects)} ${buildJoin(joinMap, true)} where ${this.primaryKeyString} = ? `;
9237
- const stmt = await this.properties.db.prepare(sql);
9119
+ const stmt = await this.properties.db.prepare(sql, sql);
9238
9120
  const rows = await stmt.get([id.key]);
9239
- await stmt.finalize?.();
9240
9121
  if (!rows) {
9241
9122
  continue;
9242
9123
  }
@@ -9252,34 +9133,42 @@ var SQLLiteIndex = class {
9252
9133
  return insert(async (values, table) => {
9253
9134
  const preId = values[table.primaryIndex];
9254
9135
  if (preId != null) {
9255
- const statement = this.replaceStatement.get(table.name);
9136
+ const statement = this.properties.db.statements.get(replaceStatementKey(table));
9256
9137
  await statement.run(values.map((x) => typeof x === "boolean" ? x ? 1 : 0 : x));
9257
9138
  await statement.reset?.();
9258
9139
  return preId;
9259
9140
  } else {
9260
- const statement = this.putStatement.get(table.name);
9141
+ const statement = this.properties.db.statements.get(putStatementKey(table));
9261
9142
  const out = await statement.get(values.map((x) => typeof x === "boolean" ? x ? 1 : 0 : x));
9262
9143
  await statement.reset?.();
9144
+ if (out == null) {
9145
+ return void 0;
9146
+ }
9263
9147
  return out[table.primary];
9264
9148
  }
9265
9149
  }, value, this.tables, resolveTable(this.scopeString ? [this.scopeString] : [], this.tables, classOfValue, true), getSchema(classOfValue).fields, (_fn) => {
9266
9150
  throw new Error("Unexpected");
9267
9151
  });
9268
9152
  }
9269
- async query(request, options) {
9270
- let sqlFetch = convertSearchRequestToQuery(request, this.tables, this._rootTables, options?.shape);
9271
- const stmt = await this.properties.db.prepare(sqlFetch);
9153
+ iterate(request, options) {
9154
+ let { sql: sqlFetch, bindable } = convertSearchRequestToQuery(request, this.tables, this._rootTables, options?.shape);
9272
9155
  let offset = 0;
9273
- let first = false;
9156
+ let once = false;
9157
+ let requestId = v4_default();
9158
+ let hasMore = true;
9159
+ let stmt;
9160
+ let kept = void 0;
9274
9161
  const fetch2 = async (amount) => {
9275
- if (!first) {
9276
- stmt.reset?.();
9162
+ kept = void 0;
9163
+ if (!once) {
9164
+ stmt = await this.properties.db.prepare(sqlFetch, sqlFetch);
9277
9165
  clearTimeout(iterator.timeout);
9278
- iterator.timeout = setTimeout(() => this.clearupIterator(request.idString), this.iteratorTimeout);
9166
+ iterator.timeout = setTimeout(() => this.clearupIterator(requestId), this.iteratorTimeout);
9279
9167
  }
9280
- first = true;
9168
+ once = true;
9281
9169
  const offsetStart = offset;
9282
9170
  const allResults = await stmt.all([
9171
+ ...bindable,
9283
9172
  amount,
9284
9173
  offsetStart
9285
9174
  ]);
@@ -9291,38 +9180,53 @@ var SQLLiteIndex = class {
9291
9180
  id: toId(row[getTablePrefixedField(selectedTable, this.primaryKeyString)])
9292
9181
  };
9293
9182
  }));
9294
- offset += amount;
9295
- if (results.length > 0) {
9296
- const totalCount = await this.count(new CountRequest({ query: request.query }));
9297
- iterator.kept = totalCount - results.length - offsetStart;
9298
- } else {
9299
- iterator.kept = 0;
9300
- }
9301
- if (iterator.kept === 0) {
9302
- await this.clearupIterator(request.idString);
9183
+ offset += results.length;
9184
+ if (results.length < amount) {
9185
+ hasMore = false;
9186
+ await this.clearupIterator(requestId);
9303
9187
  clearTimeout(iterator.timeout);
9304
9188
  }
9305
- return { results, kept: iterator.kept };
9189
+ return results;
9306
9190
  };
9307
9191
  const iterator = {
9308
- kept: 0,
9309
9192
  fetch: fetch2,
9310
- fetchStatement: stmt,
9311
9193
  /* countStatement: countStmt, */
9312
- timeout: setTimeout(() => this.clearupIterator(request.idString), this.iteratorTimeout)
9194
+ timeout: setTimeout(() => this.clearupIterator(requestId), this.iteratorTimeout)
9195
+ };
9196
+ this.cursor.set(requestId, iterator);
9197
+ let totalCount = void 0;
9198
+ return {
9199
+ all: async () => {
9200
+ const results = [];
9201
+ while (true) {
9202
+ const res = await fetch2(100);
9203
+ results.push(...res);
9204
+ if (res.length === 0) {
9205
+ break;
9206
+ }
9207
+ }
9208
+ return results;
9209
+ },
9210
+ close: () => {
9211
+ hasMore = false;
9212
+ kept = 0;
9213
+ this.clearupIterator(requestId);
9214
+ },
9215
+ next: (amount) => fetch2(amount),
9216
+ pending: async () => {
9217
+ if (!hasMore) {
9218
+ return 0;
9219
+ }
9220
+ if (kept != null) {
9221
+ return kept;
9222
+ }
9223
+ totalCount = totalCount ?? await this.count(request);
9224
+ kept = totalCount - offset;
9225
+ hasMore = kept > 0;
9226
+ return kept;
9227
+ },
9228
+ done: () => once ? !hasMore : void 0
9313
9229
  };
9314
- this.cursor.set(request.idString, iterator);
9315
- return fetch2(request.fetch);
9316
- }
9317
- next(query) {
9318
- const cache = this.cursor.get(query.idString);
9319
- if (!cache) {
9320
- throw new Error("No cursor found with id: " + query.idString);
9321
- }
9322
- return cache.fetch(query.amount);
9323
- }
9324
- close(query) {
9325
- return this.clearupIterator(query.idString);
9326
9230
  }
9327
9231
  async clearupIterator(id) {
9328
9232
  const cache = this._cursor.get(id);
@@ -9330,14 +9234,13 @@ var SQLLiteIndex = class {
9330
9234
  return;
9331
9235
  }
9332
9236
  clearTimeout(cache.timeout);
9333
- await cache.fetchStatement.finalize?.();
9334
9237
  this._cursor.delete(id);
9335
9238
  }
9336
9239
  async getSize() {
9337
9240
  if (this.tables.size === 0) {
9338
9241
  return 0;
9339
9242
  }
9340
- return this.count(new CountRequest({ query: {} }));
9243
+ return this.count();
9341
9244
  }
9342
9245
  async del(query) {
9343
9246
  let ret = [];
@@ -9345,9 +9248,9 @@ var SQLLiteIndex = class {
9345
9248
  let lastError = void 0;
9346
9249
  for (const table of this._rootTables) {
9347
9250
  try {
9348
- const stmt = await this.properties.db.prepare(convertDeleteRequestToQuery(query, this.tables, table));
9349
- const results = await stmt.all([]);
9350
- await stmt.finalize?.();
9251
+ const { sql, bindable } = convertDeleteRequestToQuery(query, this.tables, table);
9252
+ const stmt = await this.properties.db.prepare(sql, sql);
9253
+ const results = await stmt.all(bindable);
9351
9254
  for (const result of results) {
9352
9255
  ret.push(toId(result[table.primary]));
9353
9256
  }
@@ -9373,18 +9276,20 @@ var SQLLiteIndex = class {
9373
9276
  for (const table of this._rootTables) {
9374
9277
  try {
9375
9278
  if (table.fields.find((x) => x.name === inlinedName) == null) {
9376
- lastError = new MissingFieldError("Missing field: " + query.key.join("."));
9279
+ lastError = new MissingFieldError("Missing field: " + (Array.isArray(query.key) ? query.key : [query.key]).join("."));
9377
9280
  continue;
9378
9281
  }
9379
- const stmt = await this.properties.db.prepare(convertSumRequestToQuery(query, this.tables, table));
9380
- const result = await stmt.get();
9381
- await stmt.finalize?.();
9382
- if (ret == null) {
9383
- ret = result.sum;
9384
- } else {
9385
- ret += result.sum;
9282
+ const { sql, bindable } = convertSumRequestToQuery(query, this.tables, table);
9283
+ const stmt = await this.properties.db.prepare(sql, sql);
9284
+ const result = await stmt.get(bindable);
9285
+ if (result != null) {
9286
+ if (ret == null) {
9287
+ ret = result.sum;
9288
+ } else {
9289
+ ret += result.sum;
9290
+ }
9291
+ once = true;
9386
9292
  }
9387
- once = true;
9388
9293
  } catch (error2) {
9389
9294
  if (error2 instanceof MissingFieldError) {
9390
9295
  lastError = error2;
@@ -9404,11 +9309,13 @@ var SQLLiteIndex = class {
9404
9309
  let lastError = void 0;
9405
9310
  for (const table of this._rootTables) {
9406
9311
  try {
9407
- const stmt = await this.properties.db.prepare(convertCountRequestToQuery(request, this.tables, table));
9408
- const result = await stmt.get();
9409
- await stmt.finalize?.();
9410
- ret += Number(result.count);
9411
- once = true;
9312
+ const { sql, bindable } = convertCountRequestToQuery(request, this.tables, table);
9313
+ const stmt = await this.properties.db.prepare(sql, sql);
9314
+ const result = await stmt.get(bindable);
9315
+ if (result != null) {
9316
+ ret += Number(result.count);
9317
+ once = true;
9318
+ }
9412
9319
  } catch (error2) {
9413
9320
  if (error2 instanceof MissingFieldError) {
9414
9321
  lastError = error2;
@@ -9422,13 +9329,6 @@ var SQLLiteIndex = class {
9422
9329
  }
9423
9330
  return ret;
9424
9331
  }
9425
- getPending(cursorId) {
9426
- const cursor = this.cursor.get(cursorId);
9427
- if (!cursor) {
9428
- return;
9429
- }
9430
- return cursor.kept;
9431
- }
9432
9332
  get cursorCount() {
9433
9333
  return this.cursor.size;
9434
9334
  }
@@ -21522,12 +21422,13 @@ var Statement = class {
21522
21422
  return this;
21523
21423
  }
21524
21424
  async finalize() {
21525
- if (await this.statement.finalize() > 0) {
21425
+ const out = await this.statement.finalize();
21426
+ if (out != null && out > 0) {
21526
21427
  throw new Error("Error finalizing statement");
21527
21428
  }
21528
21429
  }
21529
21430
  get(values) {
21530
- if (values) {
21431
+ if (values && values?.length > 0) {
21531
21432
  this.statement.bind(values);
21532
21433
  }
21533
21434
  let step = this.statement.step();
@@ -21601,10 +21502,15 @@ var create = async (directory) => {
21601
21502
  return sqliteDb.exec(sql);
21602
21503
  },
21603
21504
  open,
21604
- prepare: (sql, id) => {
21505
+ prepare: async (sql, id) => {
21605
21506
  if (id == null) {
21606
21507
  id = v4_default();
21607
21508
  }
21509
+ let prev = statements.get(id);
21510
+ if (prev) {
21511
+ await prev.reset();
21512
+ return prev;
21513
+ }
21608
21514
  const statement = sqliteDb.prepare(sql);
21609
21515
  const wrappedStatement = new Statement(statement, id);
21610
21516
  statements.set(id, wrappedStatement);
@@ -21716,7 +21622,14 @@ var ProxyDatabase = class {
21716
21622
  databaseId: this.databaseId
21717
21623
  });
21718
21624
  }
21719
- async prepare(sql) {
21625
+ async prepare(sql, id) {
21626
+ if (id != null) {
21627
+ const prev = this.statements.get(id);
21628
+ if (prev) {
21629
+ await prev.reset();
21630
+ return prev;
21631
+ }
21632
+ }
21720
21633
  const statementId = await this.send({
21721
21634
  type: "prepare",
21722
21635
  sql,
@@ -21725,6 +21638,9 @@ var ProxyDatabase = class {
21725
21638
  });
21726
21639
  const statement = new ProxyStatement(this.send, this.databaseId, statementId);
21727
21640
  this.statements.set(statementId, statement);
21641
+ if (id != null) {
21642
+ this.statements.set(id, statement);
21643
+ }
21728
21644
  return statement;
21729
21645
  }
21730
21646
  async open() {