s3db.js 12.2.1 → 12.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/s3db.es.js CHANGED
@@ -10622,6 +10622,605 @@ class FullTextPlugin extends Plugin {
10622
10622
  }
10623
10623
  }
10624
10624
 
10625
+ class GeoPlugin extends Plugin {
10626
+ constructor(config = {}) {
10627
+ super(config);
10628
+ this.resources = config.resources || {};
10629
+ this.verbose = config.verbose !== void 0 ? config.verbose : false;
10630
+ this.base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
10631
+ }
10632
+ /**
10633
+ * Install the plugin
10634
+ */
10635
+ async install(database) {
10636
+ await super.install(database);
10637
+ for (const [resourceName, config] of Object.entries(this.resources)) {
10638
+ await this._setupResource(resourceName, config);
10639
+ }
10640
+ this.database.addHook("afterCreateResource", async (context) => {
10641
+ const { resource, config: resourceConfig } = context;
10642
+ const geoConfig = this.resources[resource.name];
10643
+ if (geoConfig) {
10644
+ await this._setupResource(resource.name, geoConfig);
10645
+ }
10646
+ });
10647
+ if (this.verbose) {
10648
+ console.log(`[GeoPlugin] Installed with ${Object.keys(this.resources).length} resources`);
10649
+ }
10650
+ this.emit("installed", {
10651
+ plugin: "GeoPlugin",
10652
+ resources: Object.keys(this.resources)
10653
+ });
10654
+ }
10655
+ /**
10656
+ * Setup a resource with geo capabilities
10657
+ */
10658
+ async _setupResource(resourceName, config) {
10659
+ if (!this.database.resources[resourceName]) {
10660
+ if (this.verbose) {
10661
+ console.warn(`[GeoPlugin] Resource "${resourceName}" not found, will setup when created`);
10662
+ }
10663
+ return;
10664
+ }
10665
+ const resource = this.database.resources[resourceName];
10666
+ if (!resource || typeof resource.addHook !== "function") {
10667
+ if (this.verbose) {
10668
+ console.warn(`[GeoPlugin] Resource "${resourceName}" not found or invalid`);
10669
+ }
10670
+ return;
10671
+ }
10672
+ if (!config.latField || !config.lonField) {
10673
+ throw new Error(
10674
+ `[GeoPlugin] Resource "${resourceName}" must have "latField" and "lonField" configured`
10675
+ );
10676
+ }
10677
+ if (!config.precision || config.precision < 1 || config.precision > 12) {
10678
+ config.precision = 5;
10679
+ }
10680
+ resource._geoConfig = config;
10681
+ const latField = resource.attributes[config.latField];
10682
+ const lonField = resource.attributes[config.lonField];
10683
+ const isLatOptional = typeof latField === "object" && latField.optional === true;
10684
+ const isLonOptional = typeof lonField === "object" && lonField.optional === true;
10685
+ const areCoordinatesOptional = isLatOptional || isLonOptional;
10686
+ const geohashType = areCoordinatesOptional ? "string|optional" : "string";
10687
+ let needsUpdate = false;
10688
+ const newAttributes = { ...resource.attributes };
10689
+ if (config.addGeohash && !newAttributes.geohash) {
10690
+ newAttributes.geohash = geohashType;
10691
+ needsUpdate = true;
10692
+ }
10693
+ if (!newAttributes._geohash) {
10694
+ newAttributes._geohash = geohashType;
10695
+ needsUpdate = true;
10696
+ }
10697
+ if (config.zoomLevels && Array.isArray(config.zoomLevels)) {
10698
+ for (const zoom of config.zoomLevels) {
10699
+ const fieldName = `_geohash_zoom${zoom}`;
10700
+ if (!newAttributes[fieldName]) {
10701
+ newAttributes[fieldName] = geohashType;
10702
+ needsUpdate = true;
10703
+ }
10704
+ }
10705
+ }
10706
+ if (needsUpdate) {
10707
+ resource.updateAttributes(newAttributes);
10708
+ if (this.database.uploadMetadataFile) {
10709
+ await this.database.uploadMetadataFile();
10710
+ }
10711
+ }
10712
+ if (config.usePartitions) {
10713
+ await this._setupPartitions(resource, config);
10714
+ }
10715
+ this._addHooks(resource, config);
10716
+ this._addHelperMethods(resource, config);
10717
+ if (this.verbose) {
10718
+ console.log(
10719
+ `[GeoPlugin] Setup resource "${resourceName}" with precision ${config.precision} (~${this._getPrecisionDistance(config.precision)}km cells)` + (config.usePartitions ? " [Partitions enabled]" : "")
10720
+ );
10721
+ }
10722
+ }
10723
+ /**
10724
+ * Setup geohash partitions for efficient spatial queries
10725
+ * Creates multiple zoom-level partitions if zoomLevels configured
10726
+ */
10727
+ async _setupPartitions(resource, config) {
10728
+ const updatedConfig = { ...resource.config };
10729
+ updatedConfig.partitions = updatedConfig.partitions || {};
10730
+ let partitionsCreated = 0;
10731
+ if (config.zoomLevels && Array.isArray(config.zoomLevels)) {
10732
+ for (const zoom of config.zoomLevels) {
10733
+ const partitionName = `byGeohashZoom${zoom}`;
10734
+ const fieldName = `_geohash_zoom${zoom}`;
10735
+ if (!updatedConfig.partitions[partitionName]) {
10736
+ updatedConfig.partitions[partitionName] = {
10737
+ fields: {
10738
+ [fieldName]: "string"
10739
+ }
10740
+ };
10741
+ partitionsCreated++;
10742
+ if (this.verbose) {
10743
+ console.log(
10744
+ `[GeoPlugin] Created ${partitionName} partition for "${resource.name}" (precision ${zoom}, ~${this._getPrecisionDistance(zoom)}km cells)`
10745
+ );
10746
+ }
10747
+ }
10748
+ }
10749
+ } else {
10750
+ const hasGeohashPartition = resource.config.partitions && resource.config.partitions.byGeohash;
10751
+ if (!hasGeohashPartition) {
10752
+ updatedConfig.partitions.byGeohash = {
10753
+ fields: {
10754
+ _geohash: "string"
10755
+ }
10756
+ };
10757
+ partitionsCreated++;
10758
+ if (this.verbose) {
10759
+ console.log(`[GeoPlugin] Created byGeohash partition for "${resource.name}"`);
10760
+ }
10761
+ }
10762
+ }
10763
+ if (partitionsCreated > 0) {
10764
+ resource.config = updatedConfig;
10765
+ resource.setupPartitionHooks();
10766
+ if (this.database.uploadMetadataFile) {
10767
+ await this.database.uploadMetadataFile();
10768
+ }
10769
+ }
10770
+ }
10771
+ /**
10772
+ * Add hooks to automatically calculate geohash at all zoom levels
10773
+ */
10774
+ _addHooks(resource, config) {
10775
+ const calculateGeohash = async (data) => {
10776
+ const lat = data[config.latField];
10777
+ const lon = data[config.lonField];
10778
+ if (lat !== void 0 && lon !== void 0) {
10779
+ const geohash = this.encodeGeohash(lat, lon, config.precision);
10780
+ if (config.addGeohash) {
10781
+ data.geohash = geohash;
10782
+ }
10783
+ data._geohash = geohash;
10784
+ if (config.zoomLevels && Array.isArray(config.zoomLevels)) {
10785
+ for (const zoom of config.zoomLevels) {
10786
+ const zoomGeohash = this.encodeGeohash(lat, lon, zoom);
10787
+ data[`_geohash_zoom${zoom}`] = zoomGeohash;
10788
+ }
10789
+ }
10790
+ }
10791
+ return data;
10792
+ };
10793
+ resource.addHook("beforeInsert", calculateGeohash);
10794
+ resource.addHook("beforeUpdate", calculateGeohash);
10795
+ }
10796
+ /**
10797
+ * Add helper methods to resource
10798
+ */
10799
+ _addHelperMethods(resource, config) {
10800
+ const plugin = this;
10801
+ resource.findNearby = async function({ lat, lon, radius = 10, limit = 100 }) {
10802
+ if (lat === void 0 || lon === void 0) {
10803
+ throw new Error("lat and lon are required for findNearby");
10804
+ }
10805
+ const longitude = lon;
10806
+ let allRecords = [];
10807
+ if (config.usePartitions) {
10808
+ let partitionName, fieldName, precision;
10809
+ if (config.zoomLevels && config.zoomLevels.length > 0) {
10810
+ const optimalZoom = plugin._selectOptimalZoom(config.zoomLevels, radius);
10811
+ partitionName = `byGeohashZoom${optimalZoom}`;
10812
+ fieldName = `_geohash_zoom${optimalZoom}`;
10813
+ precision = optimalZoom;
10814
+ if (plugin.verbose) {
10815
+ console.log(
10816
+ `[GeoPlugin] Auto-selected zoom${optimalZoom} (${plugin._getPrecisionDistance(optimalZoom)}km cells) for ${radius}km radius query`
10817
+ );
10818
+ }
10819
+ } else {
10820
+ partitionName = "byGeohash";
10821
+ fieldName = "_geohash";
10822
+ precision = config.precision;
10823
+ }
10824
+ if (this.config.partitions?.[partitionName]) {
10825
+ const centerGeohash = plugin.encodeGeohash(lat, longitude, precision);
10826
+ const neighbors = plugin.getNeighbors(centerGeohash);
10827
+ const geohashesToSearch = [centerGeohash, ...neighbors];
10828
+ const partitionResults = await Promise.all(
10829
+ geohashesToSearch.map(async (geohash) => {
10830
+ const [ok, err, records] = await tryFn(async () => {
10831
+ return await this.listPartition({
10832
+ partition: partitionName,
10833
+ partitionValues: { [fieldName]: geohash },
10834
+ limit: limit * 2
10835
+ });
10836
+ });
10837
+ return ok ? records : [];
10838
+ })
10839
+ );
10840
+ allRecords = partitionResults.flat();
10841
+ if (plugin.verbose) {
10842
+ console.log(
10843
+ `[GeoPlugin] findNearby searched ${geohashesToSearch.length} ${partitionName} partitions, found ${allRecords.length} candidates`
10844
+ );
10845
+ }
10846
+ } else {
10847
+ allRecords = await this.list({ limit: limit * 10 });
10848
+ }
10849
+ } else {
10850
+ allRecords = await this.list({ limit: limit * 10 });
10851
+ }
10852
+ const withDistances = allRecords.map((record) => {
10853
+ const recordLat = record[config.latField];
10854
+ const recordLon = record[config.lonField];
10855
+ if (recordLat === void 0 || recordLon === void 0) {
10856
+ return null;
10857
+ }
10858
+ const distance = plugin.calculateDistance(lat, longitude, recordLat, recordLon);
10859
+ return {
10860
+ ...record,
10861
+ _distance: distance
10862
+ };
10863
+ }).filter((record) => record !== null && record._distance <= radius).sort((a, b) => a._distance - b._distance).slice(0, limit);
10864
+ return withDistances;
10865
+ };
10866
+ resource.findInBounds = async function({ north, south, east, west, limit = 100 }) {
10867
+ if (north === void 0 || south === void 0 || east === void 0 || west === void 0) {
10868
+ throw new Error("north, south, east, west are required for findInBounds");
10869
+ }
10870
+ let allRecords = [];
10871
+ if (config.usePartitions) {
10872
+ let partitionName, precision;
10873
+ if (config.zoomLevels && config.zoomLevels.length > 0) {
10874
+ const centerLat = (north + south) / 2;
10875
+ const centerLon = (east + west) / 2;
10876
+ const latRadius = plugin.calculateDistance(centerLat, centerLon, north, centerLon);
10877
+ const lonRadius = plugin.calculateDistance(centerLat, centerLon, centerLat, east);
10878
+ const approximateRadius = Math.max(latRadius, lonRadius);
10879
+ const optimalZoom = plugin._selectOptimalZoom(config.zoomLevels, approximateRadius);
10880
+ partitionName = `byGeohashZoom${optimalZoom}`;
10881
+ precision = optimalZoom;
10882
+ if (plugin.verbose) {
10883
+ console.log(
10884
+ `[GeoPlugin] Auto-selected zoom${optimalZoom} (${plugin._getPrecisionDistance(optimalZoom)}km cells) for ${approximateRadius.toFixed(1)}km bounding box`
10885
+ );
10886
+ }
10887
+ } else {
10888
+ partitionName = "byGeohash";
10889
+ precision = config.precision;
10890
+ }
10891
+ if (this.config.partitions?.[partitionName]) {
10892
+ const geohashesToSearch = plugin._getGeohashesInBounds({
10893
+ north,
10894
+ south,
10895
+ east,
10896
+ west,
10897
+ precision
10898
+ });
10899
+ const partitionResults = await Promise.all(
10900
+ geohashesToSearch.map(async (geohash) => {
10901
+ const [ok, err, records] = await tryFn(async () => {
10902
+ const fieldName = config.zoomLevels ? `_geohash_zoom${precision}` : "_geohash";
10903
+ return await this.listPartition({
10904
+ partition: partitionName,
10905
+ partitionValues: { [fieldName]: geohash },
10906
+ limit: limit * 2
10907
+ });
10908
+ });
10909
+ return ok ? records : [];
10910
+ })
10911
+ );
10912
+ allRecords = partitionResults.flat();
10913
+ if (plugin.verbose) {
10914
+ console.log(
10915
+ `[GeoPlugin] findInBounds searched ${geohashesToSearch.length} ${partitionName} partitions, found ${allRecords.length} candidates`
10916
+ );
10917
+ }
10918
+ } else {
10919
+ allRecords = await this.list({ limit: limit * 10 });
10920
+ }
10921
+ } else {
10922
+ allRecords = await this.list({ limit: limit * 10 });
10923
+ }
10924
+ const inBounds = allRecords.filter((record) => {
10925
+ const lat = record[config.latField];
10926
+ const lon = record[config.lonField];
10927
+ if (lat === void 0 || lon === void 0) {
10928
+ return false;
10929
+ }
10930
+ return lat <= north && lat >= south && lon <= east && lon >= west;
10931
+ }).slice(0, limit);
10932
+ return inBounds;
10933
+ };
10934
+ resource.getDistance = async function(id1, id2) {
10935
+ let record1, record2;
10936
+ try {
10937
+ [record1, record2] = await Promise.all([
10938
+ this.get(id1),
10939
+ this.get(id2)
10940
+ ]);
10941
+ } catch (err) {
10942
+ if (err.name === "NoSuchKey" || err.message?.includes("No such key")) {
10943
+ throw new Error("One or both records not found");
10944
+ }
10945
+ throw err;
10946
+ }
10947
+ if (!record1 || !record2) {
10948
+ throw new Error("One or both records not found");
10949
+ }
10950
+ const lat1 = record1[config.latField];
10951
+ const lon1 = record1[config.lonField];
10952
+ const lat2 = record2[config.latField];
10953
+ const lon2 = record2[config.lonField];
10954
+ if (lat1 === void 0 || lon1 === void 0 || lat2 === void 0 || lon2 === void 0) {
10955
+ throw new Error("One or both records missing coordinates");
10956
+ }
10957
+ const distance = plugin.calculateDistance(lat1, lon1, lat2, lon2);
10958
+ return {
10959
+ distance,
10960
+ unit: "km",
10961
+ from: id1,
10962
+ to: id2
10963
+ };
10964
+ };
10965
+ }
10966
+ /**
10967
+ * Encode coordinates to geohash
10968
+ * @param {number} latitude - Latitude (-90 to 90)
10969
+ * @param {number} longitude - Longitude (-180 to 180)
10970
+ * @param {number} precision - Number of characters in geohash
10971
+ * @returns {string} Geohash string
10972
+ */
10973
+ encodeGeohash(latitude, longitude, precision = 5) {
10974
+ let idx = 0;
10975
+ let bit = 0;
10976
+ let evenBit = true;
10977
+ let geohash = "";
10978
+ let latMin = -90;
10979
+ let latMax = 90;
10980
+ let lonMin = -180;
10981
+ let lonMax = 180;
10982
+ while (geohash.length < precision) {
10983
+ if (evenBit) {
10984
+ const lonMid = (lonMin + lonMax) / 2;
10985
+ if (longitude > lonMid) {
10986
+ idx |= 1 << 4 - bit;
10987
+ lonMin = lonMid;
10988
+ } else {
10989
+ lonMax = lonMid;
10990
+ }
10991
+ } else {
10992
+ const latMid = (latMin + latMax) / 2;
10993
+ if (latitude > latMid) {
10994
+ idx |= 1 << 4 - bit;
10995
+ latMin = latMid;
10996
+ } else {
10997
+ latMax = latMid;
10998
+ }
10999
+ }
11000
+ evenBit = !evenBit;
11001
+ if (bit < 4) {
11002
+ bit++;
11003
+ } else {
11004
+ geohash += this.base32[idx];
11005
+ bit = 0;
11006
+ idx = 0;
11007
+ }
11008
+ }
11009
+ return geohash;
11010
+ }
11011
+ /**
11012
+ * Decode geohash to coordinates
11013
+ * @param {string} geohash - Geohash string
11014
+ * @returns {Object} { latitude, longitude, error }
11015
+ */
11016
+ decodeGeohash(geohash) {
11017
+ let evenBit = true;
11018
+ let latMin = -90;
11019
+ let latMax = 90;
11020
+ let lonMin = -180;
11021
+ let lonMax = 180;
11022
+ for (let i = 0; i < geohash.length; i++) {
11023
+ const chr = geohash[i];
11024
+ const idx = this.base32.indexOf(chr);
11025
+ if (idx === -1) {
11026
+ throw new Error(`Invalid geohash character: ${chr}`);
11027
+ }
11028
+ for (let n = 4; n >= 0; n--) {
11029
+ const bitN = idx >> n & 1;
11030
+ if (evenBit) {
11031
+ const lonMid = (lonMin + lonMax) / 2;
11032
+ if (bitN === 1) {
11033
+ lonMin = lonMid;
11034
+ } else {
11035
+ lonMax = lonMid;
11036
+ }
11037
+ } else {
11038
+ const latMid = (latMin + latMax) / 2;
11039
+ if (bitN === 1) {
11040
+ latMin = latMid;
11041
+ } else {
11042
+ latMax = latMid;
11043
+ }
11044
+ }
11045
+ evenBit = !evenBit;
11046
+ }
11047
+ }
11048
+ const latitude = (latMin + latMax) / 2;
11049
+ const longitude = (lonMin + lonMax) / 2;
11050
+ return {
11051
+ latitude,
11052
+ longitude,
11053
+ error: {
11054
+ latitude: latMax - latMin,
11055
+ longitude: lonMax - lonMin
11056
+ }
11057
+ };
11058
+ }
11059
+ /**
11060
+ * Calculate distance between two coordinates using Haversine formula
11061
+ * @param {number} lat1 - Latitude of point 1
11062
+ * @param {number} lon1 - Longitude of point 1
11063
+ * @param {number} lat2 - Latitude of point 2
11064
+ * @param {number} lon2 - Longitude of point 2
11065
+ * @returns {number} Distance in kilometers
11066
+ */
11067
+ calculateDistance(lat1, lon1, lat2, lon2) {
11068
+ const R = 6371;
11069
+ const dLat = this._toRadians(lat2 - lat1);
11070
+ const dLon = this._toRadians(lon2 - lon1);
11071
+ const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(this._toRadians(lat1)) * Math.cos(this._toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
11072
+ const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
11073
+ return R * c;
11074
+ }
11075
+ /**
11076
+ * Get geohash neighbors (8 surrounding cells)
11077
+ * @param {string} geohash - Center geohash
11078
+ * @returns {Array<string>} Array of 8 neighboring geohashes
11079
+ */
11080
+ getNeighbors(geohash) {
11081
+ const decoded = this.decodeGeohash(geohash);
11082
+ const { latitude, longitude, error } = decoded;
11083
+ const latStep = error.latitude;
11084
+ const lonStep = error.longitude;
11085
+ const neighbors = [];
11086
+ const directions = [
11087
+ [-latStep, -lonStep],
11088
+ // SW
11089
+ [-latStep, 0],
11090
+ // S
11091
+ [-latStep, lonStep],
11092
+ // SE
11093
+ [0, -lonStep],
11094
+ // W
11095
+ [0, lonStep],
11096
+ // E
11097
+ [latStep, -lonStep],
11098
+ // NW
11099
+ [latStep, 0],
11100
+ // N
11101
+ [latStep, lonStep]
11102
+ // NE
11103
+ ];
11104
+ for (const [latDelta, lonDelta] of directions) {
11105
+ const neighborHash = this.encodeGeohash(
11106
+ latitude + latDelta,
11107
+ longitude + lonDelta,
11108
+ geohash.length
11109
+ );
11110
+ neighbors.push(neighborHash);
11111
+ }
11112
+ return neighbors;
11113
+ }
11114
+ /**
11115
+ * Get all geohashes that cover a bounding box
11116
+ * @param {Object} bounds - Bounding box { north, south, east, west, precision }
11117
+ * @returns {Array<string>} Array of unique geohashes covering the area
11118
+ */
11119
+ _getGeohashesInBounds({ north, south, east, west, precision }) {
11120
+ const geohashes = /* @__PURE__ */ new Set();
11121
+ const cellSize = this._getPrecisionDistance(precision);
11122
+ const latStep = cellSize / 111;
11123
+ const lonStep = cellSize / (111 * Math.cos(this._toRadians((north + south) / 2)));
11124
+ for (let lat = south; lat <= north; lat += latStep) {
11125
+ for (let lon = west; lon <= east; lon += lonStep) {
11126
+ const geohash = this.encodeGeohash(lat, lon, precision);
11127
+ geohashes.add(geohash);
11128
+ }
11129
+ }
11130
+ const corners = [
11131
+ [north, west],
11132
+ [north, east],
11133
+ [south, west],
11134
+ [south, east],
11135
+ [(north + south) / 2, west],
11136
+ [(north + south) / 2, east],
11137
+ [north, (east + west) / 2],
11138
+ [south, (east + west) / 2]
11139
+ ];
11140
+ for (const [lat, lon] of corners) {
11141
+ const geohash = this.encodeGeohash(lat, lon, precision);
11142
+ geohashes.add(geohash);
11143
+ }
11144
+ return Array.from(geohashes);
11145
+ }
11146
+ /**
11147
+ * Convert degrees to radians
11148
+ */
11149
+ _toRadians(degrees) {
11150
+ return degrees * (Math.PI / 180);
11151
+ }
11152
+ /**
11153
+ * Get approximate cell size for precision level
11154
+ */
11155
+ _getPrecisionDistance(precision) {
11156
+ const distances = {
11157
+ 1: 5e3,
11158
+ 2: 1250,
11159
+ 3: 156,
11160
+ 4: 39,
11161
+ 5: 4.9,
11162
+ 6: 1.2,
11163
+ 7: 0.15,
11164
+ 8: 0.038,
11165
+ 9: 47e-4,
11166
+ 10: 12e-4,
11167
+ 11: 15e-5,
11168
+ 12: 37e-6
11169
+ };
11170
+ return distances[precision] || 5;
11171
+ }
11172
+ /**
11173
+ * Select optimal zoom level based on search radius
11174
+ * @param {Array<number>} zoomLevels - Available zoom levels
11175
+ * @param {number} radiusKm - Search radius in kilometers
11176
+ * @returns {number} Optimal zoom precision
11177
+ */
11178
+ _selectOptimalZoom(zoomLevels, radiusKm) {
11179
+ if (!zoomLevels || zoomLevels.length === 0) {
11180
+ return null;
11181
+ }
11182
+ const targetCellSize = radiusKm / 2.5;
11183
+ let bestZoom = zoomLevels[0];
11184
+ let bestDiff = Math.abs(this._getPrecisionDistance(bestZoom) - targetCellSize);
11185
+ for (const zoom of zoomLevels) {
11186
+ const cellSize = this._getPrecisionDistance(zoom);
11187
+ const diff = Math.abs(cellSize - targetCellSize);
11188
+ if (diff < bestDiff) {
11189
+ bestDiff = diff;
11190
+ bestZoom = zoom;
11191
+ }
11192
+ }
11193
+ return bestZoom;
11194
+ }
11195
+ /**
11196
+ * Get plugin statistics
11197
+ */
11198
+ getStats() {
11199
+ return {
11200
+ resources: Object.keys(this.resources).length,
11201
+ configurations: Object.entries(this.resources).map(([name, config]) => ({
11202
+ resource: name,
11203
+ latField: config.latField,
11204
+ lonField: config.lonField,
11205
+ precision: config.precision,
11206
+ cellSize: `~${this._getPrecisionDistance(config.precision)}km`
11207
+ }))
11208
+ };
11209
+ }
11210
+ /**
11211
+ * Uninstall the plugin
11212
+ */
11213
+ async uninstall() {
11214
+ if (this.verbose) {
11215
+ console.log("[GeoPlugin] Uninstalled");
11216
+ }
11217
+ this.emit("uninstalled", {
11218
+ plugin: "GeoPlugin"
11219
+ });
11220
+ await super.uninstall();
11221
+ }
11222
+ }
11223
+
10625
11224
  class MetricsPlugin extends Plugin {
10626
11225
  constructor(options = {}) {
10627
11226
  super();
@@ -20431,7 +21030,7 @@ class Database extends EventEmitter {
20431
21030
  this.id = idGenerator(7);
20432
21031
  this.version = "1";
20433
21032
  this.s3dbVersion = (() => {
20434
- const [ok, err, version] = tryFn(() => true ? "12.2.1" : "latest");
21033
+ const [ok, err, version] = tryFn(() => true ? "12.2.2" : "latest");
20435
21034
  return ok ? version : "latest";
20436
21035
  })();
20437
21036
  this._resourcesMap = {};
@@ -35346,6 +35945,532 @@ class TfStatePlugin extends Plugin {
35346
35945
  }
35347
35946
  }
35348
35947
 
35948
+ const GRANULARITIES = {
35949
+ minute: {
35950
+ threshold: 3600,
35951
+ // TTL < 1 hour
35952
+ interval: 1e4,
35953
+ // Check every 10 seconds
35954
+ cohortsToCheck: 3,
35955
+ // Check last 3 minutes
35956
+ cohortFormat: (date) => date.toISOString().substring(0, 16)
35957
+ // '2024-10-25T14:30'
35958
+ },
35959
+ hour: {
35960
+ threshold: 86400,
35961
+ // TTL < 24 hours
35962
+ interval: 6e5,
35963
+ // Check every 10 minutes
35964
+ cohortsToCheck: 2,
35965
+ // Check last 2 hours
35966
+ cohortFormat: (date) => date.toISOString().substring(0, 13)
35967
+ // '2024-10-25T14'
35968
+ },
35969
+ day: {
35970
+ threshold: 2592e3,
35971
+ // TTL < 30 days
35972
+ interval: 36e5,
35973
+ // Check every 1 hour
35974
+ cohortsToCheck: 2,
35975
+ // Check last 2 days
35976
+ cohortFormat: (date) => date.toISOString().substring(0, 10)
35977
+ // '2024-10-25'
35978
+ },
35979
+ week: {
35980
+ threshold: Infinity,
35981
+ // TTL >= 30 days
35982
+ interval: 864e5,
35983
+ // Check every 24 hours
35984
+ cohortsToCheck: 2,
35985
+ // Check last 2 weeks
35986
+ cohortFormat: (date) => {
35987
+ const year = date.getUTCFullYear();
35988
+ const week = getWeekNumber(date);
35989
+ return `${year}-W${String(week).padStart(2, "0")}`;
35990
+ }
35991
+ }
35992
+ };
35993
+ function getWeekNumber(date) {
35994
+ const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
35995
+ const dayNum = d.getUTCDay() || 7;
35996
+ d.setUTCDate(d.getUTCDate() + 4 - dayNum);
35997
+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
35998
+ return Math.ceil(((d - yearStart) / 864e5 + 1) / 7);
35999
+ }
36000
+ function detectGranularity(ttl) {
36001
+ if (!ttl) return "day";
36002
+ if (ttl < GRANULARITIES.minute.threshold) return "minute";
36003
+ if (ttl < GRANULARITIES.hour.threshold) return "hour";
36004
+ if (ttl < GRANULARITIES.day.threshold) return "day";
36005
+ return "week";
36006
+ }
36007
+ function getExpiredCohorts(granularity, count) {
36008
+ const config = GRANULARITIES[granularity];
36009
+ const cohorts = [];
36010
+ const now = /* @__PURE__ */ new Date();
36011
+ for (let i = 0; i < count; i++) {
36012
+ let checkDate;
36013
+ switch (granularity) {
36014
+ case "minute":
36015
+ checkDate = new Date(now.getTime() - i * 6e4);
36016
+ break;
36017
+ case "hour":
36018
+ checkDate = new Date(now.getTime() - i * 36e5);
36019
+ break;
36020
+ case "day":
36021
+ checkDate = new Date(now.getTime() - i * 864e5);
36022
+ break;
36023
+ case "week":
36024
+ checkDate = new Date(now.getTime() - i * 6048e5);
36025
+ break;
36026
+ }
36027
+ cohorts.push(config.cohortFormat(checkDate));
36028
+ }
36029
+ return cohorts;
36030
+ }
36031
+ class TTLPlugin extends Plugin {
36032
+ constructor(config = {}) {
36033
+ super(config);
36034
+ this.verbose = config.verbose !== void 0 ? config.verbose : false;
36035
+ this.resources = config.resources || {};
36036
+ this.batchSize = config.batchSize || 100;
36037
+ this.stats = {
36038
+ totalScans: 0,
36039
+ totalExpired: 0,
36040
+ totalDeleted: 0,
36041
+ totalArchived: 0,
36042
+ totalSoftDeleted: 0,
36043
+ totalCallbacks: 0,
36044
+ totalErrors: 0,
36045
+ lastScanAt: null,
36046
+ lastScanDuration: 0
36047
+ };
36048
+ this.intervals = [];
36049
+ this.isRunning = false;
36050
+ this.expirationIndex = null;
36051
+ }
36052
+ /**
36053
+ * Install the plugin
36054
+ */
36055
+ async install(database) {
36056
+ await super.install(database);
36057
+ for (const [resourceName, config] of Object.entries(this.resources)) {
36058
+ this._validateResourceConfig(resourceName, config);
36059
+ }
36060
+ await this._createExpirationIndex();
36061
+ for (const [resourceName, config] of Object.entries(this.resources)) {
36062
+ this._setupResourceHooks(resourceName, config);
36063
+ }
36064
+ this._startIntervals();
36065
+ if (this.verbose) {
36066
+ console.log(`[TTLPlugin] Installed with ${Object.keys(this.resources).length} resources`);
36067
+ }
36068
+ this.emit("installed", {
36069
+ plugin: "TTLPlugin",
36070
+ resources: Object.keys(this.resources)
36071
+ });
36072
+ }
36073
+ /**
36074
+ * Validate resource configuration
36075
+ */
36076
+ _validateResourceConfig(resourceName, config) {
36077
+ if (!config.ttl && !config.field) {
36078
+ throw new Error(
36079
+ `[TTLPlugin] Resource "${resourceName}" must have either "ttl" (seconds) or "field" (timestamp field name)`
36080
+ );
36081
+ }
36082
+ const validStrategies = ["soft-delete", "hard-delete", "archive", "callback"];
36083
+ if (!config.onExpire || !validStrategies.includes(config.onExpire)) {
36084
+ throw new Error(
36085
+ `[TTLPlugin] Resource "${resourceName}" must have an "onExpire" value. Valid options: ${validStrategies.join(", ")}`
36086
+ );
36087
+ }
36088
+ if (config.onExpire === "soft-delete" && !config.deleteField) {
36089
+ config.deleteField = "deletedat";
36090
+ }
36091
+ if (config.onExpire === "archive" && !config.archiveResource) {
36092
+ throw new Error(
36093
+ `[TTLPlugin] Resource "${resourceName}" with onExpire="archive" must have an "archiveResource" specified`
36094
+ );
36095
+ }
36096
+ if (config.onExpire === "callback" && typeof config.callback !== "function") {
36097
+ throw new Error(
36098
+ `[TTLPlugin] Resource "${resourceName}" with onExpire="callback" must have a "callback" function`
36099
+ );
36100
+ }
36101
+ if (!config.field) {
36102
+ config.field = "_createdAt";
36103
+ }
36104
+ if (config.field === "_createdAt" && this.database) {
36105
+ const resource = this.database.resources[resourceName];
36106
+ if (resource && resource.config && resource.config.timestamps === false) {
36107
+ console.warn(
36108
+ `[TTLPlugin] WARNING: Resource "${resourceName}" uses TTL with field "_createdAt" but timestamps are disabled. TTL will be calculated from indexing time, not creation time.`
36109
+ );
36110
+ }
36111
+ }
36112
+ config.granularity = detectGranularity(config.ttl);
36113
+ }
36114
+ /**
36115
+ * Create expiration index (plugin resource)
36116
+ */
36117
+ async _createExpirationIndex() {
36118
+ this.expirationIndex = await this.database.createResource({
36119
+ name: "plg_ttl_expiration_index",
36120
+ attributes: {
36121
+ resourceName: "string|required",
36122
+ recordId: "string|required",
36123
+ expiresAtCohort: "string|required",
36124
+ expiresAtTimestamp: "number|required",
36125
+ // Exact expiration timestamp for precise checking
36126
+ granularity: "string|required",
36127
+ createdAt: "number"
36128
+ },
36129
+ partitions: {
36130
+ byExpiresAtCohort: {
36131
+ fields: { expiresAtCohort: "string" }
36132
+ }
36133
+ },
36134
+ asyncPartitions: false
36135
+ // Sync partitions for deterministic behavior
36136
+ });
36137
+ if (this.verbose) {
36138
+ console.log("[TTLPlugin] Created expiration index with partition");
36139
+ }
36140
+ }
36141
+ /**
36142
+ * Setup hooks for a resource
36143
+ */
36144
+ _setupResourceHooks(resourceName, config) {
36145
+ if (!this.database.resources[resourceName]) {
36146
+ if (this.verbose) {
36147
+ console.warn(`[TTLPlugin] Resource "${resourceName}" not found, skipping hooks`);
36148
+ }
36149
+ return;
36150
+ }
36151
+ const resource = this.database.resources[resourceName];
36152
+ if (typeof resource.insert !== "function" || typeof resource.delete !== "function") {
36153
+ if (this.verbose) {
36154
+ console.warn(`[TTLPlugin] Resource "${resourceName}" missing insert/delete methods, skipping hooks`);
36155
+ }
36156
+ return;
36157
+ }
36158
+ this.addMiddleware(resource, "insert", async (next, data, options) => {
36159
+ const result = await next(data, options);
36160
+ await this._addToIndex(resourceName, result, config);
36161
+ return result;
36162
+ });
36163
+ this.addMiddleware(resource, "delete", async (next, id, options) => {
36164
+ const result = await next(id, options);
36165
+ await this._removeFromIndex(resourceName, id);
36166
+ return result;
36167
+ });
36168
+ if (this.verbose) {
36169
+ console.log(`[TTLPlugin] Setup hooks for resource "${resourceName}"`);
36170
+ }
36171
+ }
36172
+ /**
36173
+ * Add record to expiration index
36174
+ */
36175
+ async _addToIndex(resourceName, record, config) {
36176
+ try {
36177
+ let baseTime = record[config.field];
36178
+ if (!baseTime && config.field === "_createdAt") {
36179
+ baseTime = Date.now();
36180
+ }
36181
+ if (!baseTime) {
36182
+ if (this.verbose) {
36183
+ console.warn(
36184
+ `[TTLPlugin] Record ${record.id} in ${resourceName} missing field "${config.field}", skipping index`
36185
+ );
36186
+ }
36187
+ return;
36188
+ }
36189
+ const baseTimestamp = typeof baseTime === "number" ? baseTime : new Date(baseTime).getTime();
36190
+ const expiresAt = config.ttl ? new Date(baseTimestamp + config.ttl * 1e3) : new Date(baseTimestamp);
36191
+ const cohortConfig = GRANULARITIES[config.granularity];
36192
+ const cohort = cohortConfig.cohortFormat(expiresAt);
36193
+ const indexId = `${resourceName}:${record.id}`;
36194
+ await this.expirationIndex.insert({
36195
+ id: indexId,
36196
+ resourceName,
36197
+ recordId: record.id,
36198
+ expiresAtCohort: cohort,
36199
+ expiresAtTimestamp: expiresAt.getTime(),
36200
+ // Store exact timestamp for precise checking
36201
+ granularity: config.granularity,
36202
+ createdAt: Date.now()
36203
+ });
36204
+ if (this.verbose) {
36205
+ console.log(
36206
+ `[TTLPlugin] Added ${resourceName}:${record.id} to index (cohort: ${cohort}, granularity: ${config.granularity})`
36207
+ );
36208
+ }
36209
+ } catch (error) {
36210
+ console.error(`[TTLPlugin] Error adding to index:`, error);
36211
+ this.stats.totalErrors++;
36212
+ }
36213
+ }
36214
+ /**
36215
+ * Remove record from expiration index (O(1) using deterministic ID)
36216
+ */
36217
+ async _removeFromIndex(resourceName, recordId) {
36218
+ try {
36219
+ const indexId = `${resourceName}:${recordId}`;
36220
+ const [ok, err] = await tryFn(() => this.expirationIndex.delete(indexId));
36221
+ if (this.verbose && ok) {
36222
+ console.log(`[TTLPlugin] Removed index entry for ${resourceName}:${recordId}`);
36223
+ }
36224
+ if (!ok && err?.code !== "NoSuchKey") {
36225
+ throw err;
36226
+ }
36227
+ } catch (error) {
36228
+ console.error(`[TTLPlugin] Error removing from index:`, error);
36229
+ }
36230
+ }
36231
+ /**
36232
+ * Start interval-based cleanup for each granularity
36233
+ */
36234
+ _startIntervals() {
36235
+ const byGranularity = {
36236
+ minute: [],
36237
+ hour: [],
36238
+ day: [],
36239
+ week: []
36240
+ };
36241
+ for (const [name, config] of Object.entries(this.resources)) {
36242
+ byGranularity[config.granularity].push({ name, config });
36243
+ }
36244
+ for (const [granularity, resources] of Object.entries(byGranularity)) {
36245
+ if (resources.length === 0) continue;
36246
+ const granularityConfig = GRANULARITIES[granularity];
36247
+ const handle = setInterval(
36248
+ () => this._cleanupGranularity(granularity, resources),
36249
+ granularityConfig.interval
36250
+ );
36251
+ this.intervals.push(handle);
36252
+ if (this.verbose) {
36253
+ console.log(
36254
+ `[TTLPlugin] Started ${granularity} interval (${granularityConfig.interval}ms) for ${resources.length} resources`
36255
+ );
36256
+ }
36257
+ }
36258
+ this.isRunning = true;
36259
+ }
36260
+ /**
36261
+ * Stop all intervals
36262
+ */
36263
+ _stopIntervals() {
36264
+ for (const handle of this.intervals) {
36265
+ clearInterval(handle);
36266
+ }
36267
+ this.intervals = [];
36268
+ this.isRunning = false;
36269
+ if (this.verbose) {
36270
+ console.log("[TTLPlugin] Stopped all intervals");
36271
+ }
36272
+ }
36273
+ /**
36274
+ * Cleanup expired records for a specific granularity
36275
+ */
36276
+ async _cleanupGranularity(granularity, resources) {
36277
+ const startTime = Date.now();
36278
+ this.stats.totalScans++;
36279
+ try {
36280
+ const granularityConfig = GRANULARITIES[granularity];
36281
+ const cohorts = getExpiredCohorts(granularity, granularityConfig.cohortsToCheck);
36282
+ if (this.verbose) {
36283
+ console.log(`[TTLPlugin] Cleaning ${granularity} granularity, checking cohorts:`, cohorts);
36284
+ }
36285
+ for (const cohort of cohorts) {
36286
+ const expired = await this.expirationIndex.listPartition({
36287
+ partition: "byExpiresAtCohort",
36288
+ partitionValues: { expiresAtCohort: cohort }
36289
+ });
36290
+ const resourceNames = new Set(resources.map((r) => r.name));
36291
+ const filtered = expired.filter((e) => resourceNames.has(e.resourceName));
36292
+ if (this.verbose && filtered.length > 0) {
36293
+ console.log(`[TTLPlugin] Found ${filtered.length} expired records in cohort ${cohort}`);
36294
+ }
36295
+ for (let i = 0; i < filtered.length; i += this.batchSize) {
36296
+ const batch = filtered.slice(i, i + this.batchSize);
36297
+ for (const entry of batch) {
36298
+ const config = this.resources[entry.resourceName];
36299
+ await this._processExpiredEntry(entry, config);
36300
+ }
36301
+ }
36302
+ }
36303
+ this.stats.lastScanAt = (/* @__PURE__ */ new Date()).toISOString();
36304
+ this.stats.lastScanDuration = Date.now() - startTime;
36305
+ this.emit("scanCompleted", {
36306
+ granularity,
36307
+ duration: this.stats.lastScanDuration,
36308
+ cohorts
36309
+ });
36310
+ } catch (error) {
36311
+ console.error(`[TTLPlugin] Error in ${granularity} cleanup:`, error);
36312
+ this.stats.totalErrors++;
36313
+ this.emit("cleanupError", { granularity, error });
36314
+ }
36315
+ }
36316
+ /**
36317
+ * Process a single expired index entry
36318
+ */
36319
+ async _processExpiredEntry(entry, config) {
36320
+ try {
36321
+ if (!this.database.resources[entry.resourceName]) {
36322
+ if (this.verbose) {
36323
+ console.warn(`[TTLPlugin] Resource "${entry.resourceName}" not found during cleanup, skipping`);
36324
+ }
36325
+ return;
36326
+ }
36327
+ const resource = this.database.resources[entry.resourceName];
36328
+ const [ok, err, record] = await tryFn(() => resource.get(entry.recordId));
36329
+ if (!ok || !record) {
36330
+ await this.expirationIndex.delete(entry.id);
36331
+ return;
36332
+ }
36333
+ if (entry.expiresAtTimestamp && Date.now() < entry.expiresAtTimestamp) {
36334
+ return;
36335
+ }
36336
+ switch (config.onExpire) {
36337
+ case "soft-delete":
36338
+ await this._softDelete(resource, record, config);
36339
+ this.stats.totalSoftDeleted++;
36340
+ break;
36341
+ case "hard-delete":
36342
+ await this._hardDelete(resource, record);
36343
+ this.stats.totalDeleted++;
36344
+ break;
36345
+ case "archive":
36346
+ await this._archive(resource, record, config);
36347
+ this.stats.totalArchived++;
36348
+ this.stats.totalDeleted++;
36349
+ break;
36350
+ case "callback":
36351
+ const shouldDelete = await config.callback(record, resource);
36352
+ this.stats.totalCallbacks++;
36353
+ if (shouldDelete) {
36354
+ await this._hardDelete(resource, record);
36355
+ this.stats.totalDeleted++;
36356
+ }
36357
+ break;
36358
+ }
36359
+ await this.expirationIndex.delete(entry.id);
36360
+ this.stats.totalExpired++;
36361
+ this.emit("recordExpired", { resource: entry.resourceName, record });
36362
+ } catch (error) {
36363
+ console.error(`[TTLPlugin] Error processing expired entry:`, error);
36364
+ this.stats.totalErrors++;
36365
+ }
36366
+ }
36367
+ /**
36368
+ * Soft delete: Mark record as deleted
36369
+ */
36370
+ async _softDelete(resource, record, config) {
36371
+ const deleteField = config.deleteField || "deletedat";
36372
+ const updates = {
36373
+ [deleteField]: (/* @__PURE__ */ new Date()).toISOString(),
36374
+ isdeleted: "true"
36375
+ // Add isdeleted field for partition compatibility
36376
+ };
36377
+ await resource.update(record.id, updates);
36378
+ if (this.verbose) {
36379
+ console.log(`[TTLPlugin] Soft-deleted record ${record.id} in ${resource.name}`);
36380
+ }
36381
+ }
36382
+ /**
36383
+ * Hard delete: Remove record from S3
36384
+ */
36385
+ async _hardDelete(resource, record) {
36386
+ await resource.delete(record.id);
36387
+ if (this.verbose) {
36388
+ console.log(`[TTLPlugin] Hard-deleted record ${record.id} in ${resource.name}`);
36389
+ }
36390
+ }
36391
+ /**
36392
+ * Archive: Copy to another resource then delete
36393
+ */
36394
+ async _archive(resource, record, config) {
36395
+ if (!this.database.resources[config.archiveResource]) {
36396
+ throw new Error(`Archive resource "${config.archiveResource}" not found`);
36397
+ }
36398
+ const archiveResource = this.database.resources[config.archiveResource];
36399
+ const archiveData = {};
36400
+ for (const [key, value] of Object.entries(record)) {
36401
+ if (!key.startsWith("_")) {
36402
+ archiveData[key] = value;
36403
+ }
36404
+ }
36405
+ archiveData.archivedAt = (/* @__PURE__ */ new Date()).toISOString();
36406
+ archiveData.archivedFrom = resource.name;
36407
+ archiveData.originalId = record.id;
36408
+ if (!config.keepOriginalId) {
36409
+ delete archiveData.id;
36410
+ }
36411
+ await archiveResource.insert(archiveData);
36412
+ await resource.delete(record.id);
36413
+ if (this.verbose) {
36414
+ console.log(`[TTLPlugin] Archived record ${record.id} from ${resource.name} to ${config.archiveResource}`);
36415
+ }
36416
+ }
36417
+ /**
36418
+ * Manual cleanup of a specific resource
36419
+ */
36420
+ async cleanupResource(resourceName) {
36421
+ const config = this.resources[resourceName];
36422
+ if (!config) {
36423
+ throw new Error(`Resource "${resourceName}" not configured in TTLPlugin`);
36424
+ }
36425
+ const granularity = config.granularity;
36426
+ await this._cleanupGranularity(granularity, [{ name: resourceName, config }]);
36427
+ return {
36428
+ resource: resourceName,
36429
+ granularity
36430
+ };
36431
+ }
36432
+ /**
36433
+ * Manual cleanup of all resources
36434
+ */
36435
+ async runCleanup() {
36436
+ const byGranularity = {
36437
+ minute: [],
36438
+ hour: [],
36439
+ day: [],
36440
+ week: []
36441
+ };
36442
+ for (const [name, config] of Object.entries(this.resources)) {
36443
+ byGranularity[config.granularity].push({ name, config });
36444
+ }
36445
+ for (const [granularity, resources] of Object.entries(byGranularity)) {
36446
+ if (resources.length > 0) {
36447
+ await this._cleanupGranularity(granularity, resources);
36448
+ }
36449
+ }
36450
+ }
36451
+ /**
36452
+ * Get plugin statistics
36453
+ */
36454
+ getStats() {
36455
+ return {
36456
+ ...this.stats,
36457
+ resources: Object.keys(this.resources).length,
36458
+ isRunning: this.isRunning,
36459
+ intervals: this.intervals.length
36460
+ };
36461
+ }
36462
+ /**
36463
+ * Uninstall the plugin
36464
+ */
36465
+ async uninstall() {
36466
+ this._stopIntervals();
36467
+ await super.uninstall();
36468
+ if (this.verbose) {
36469
+ console.log("[TTLPlugin] Uninstalled");
36470
+ }
36471
+ }
36472
+ }
36473
+
35349
36474
  function cosineDistance(a, b) {
35350
36475
  if (a.length !== b.length) {
35351
36476
  throw new Error(`Dimension mismatch: ${a.length} vs ${b.length}`);
@@ -37116,5 +38241,5 @@ var metrics = /*#__PURE__*/Object.freeze({
37116
38241
  silhouetteScore: silhouetteScore
37117
38242
  });
37118
38243
 
37119
- export { AVAILABLE_BEHAVIORS, AnalyticsNotEnabledError, ApiPlugin, AuditPlugin, AuthenticationError, BACKUP_DRIVERS, BackupPlugin, BaseBackupDriver, BaseError, BaseReplicator, BehaviorError, BigqueryReplicator, CONSUMER_DRIVERS, Cache, CachePlugin, Client, ConnectionString, ConnectionStringError, CostsPlugin, CryptoError, DEFAULT_BEHAVIOR, Database, DatabaseError, DynamoDBReplicator, EncryptionError, ErrorMap, EventualConsistencyPlugin, Factory, FilesystemBackupDriver, FilesystemCache, FullTextPlugin, InvalidResourceItem, MemoryCache, MetadataLimitError, MetricsPlugin, MissingMetadata, MongoDBReplicator, MultiBackupDriver, MySQLReplicator, NoSuchBucket, NoSuchKey, NotFound, PartitionAwareFilesystemCache, PartitionDriverError, PartitionError, PermissionError, PlanetScaleReplicator, Plugin, PluginError, PluginObject, PluginStorageError, PostgresReplicator, QueueConsumerPlugin, REPLICATOR_DRIVERS, RabbitMqConsumer, RelationPlugin, ReplicatorPlugin, Resource, ResourceError, ResourceIdsPageReader, ResourceIdsReader, ResourceNotFound, ResourceReader, ResourceWriter, S3BackupDriver, S3Cache, S3QueuePlugin, Database as S3db, S3dbError, S3dbReplicator, SchedulerPlugin, Schema, SchemaError, Seeder, SqsConsumer, SqsReplicator, StateMachinePlugin, StreamError, TfStatePlugin, TursoReplicator, UnknownError, ValidationError, Validator, VectorPlugin, WebhookReplicator, behaviors, calculateAttributeNamesSize, calculateAttributeSizes, calculateEffectiveLimit, calculateSystemOverhead, calculateTotalSize, calculateUTF8Bytes, clearUTF8Memory, createBackupDriver, createConsumer, createReplicator, decode, decodeDecimal, decodeFixedPoint, decodeFixedPointBatch, decrypt, S3db as default, encode, encodeDecimal, encodeFixedPoint, encodeFixedPointBatch, encrypt, generateTypes, getBehavior, getSizeBreakdown, idGenerator, mapAwsError, md5, passwordGenerator, printTypes, sha256, streamToString, transformValue, tryFn, tryFnSync, validateBackupConfig, validateReplicatorConfig };
38244
+ export { AVAILABLE_BEHAVIORS, AnalyticsNotEnabledError, ApiPlugin, AuditPlugin, AuthenticationError, BACKUP_DRIVERS, BackupPlugin, BaseBackupDriver, BaseError, BaseReplicator, BehaviorError, BigqueryReplicator, CONSUMER_DRIVERS, Cache, CachePlugin, Client, ConnectionString, ConnectionStringError, CostsPlugin, CryptoError, DEFAULT_BEHAVIOR, Database, DatabaseError, DynamoDBReplicator, EncryptionError, ErrorMap, EventualConsistencyPlugin, Factory, FilesystemBackupDriver, FilesystemCache, FullTextPlugin, GeoPlugin, InvalidResourceItem, MemoryCache, MetadataLimitError, MetricsPlugin, MissingMetadata, MongoDBReplicator, MultiBackupDriver, MySQLReplicator, NoSuchBucket, NoSuchKey, NotFound, PartitionAwareFilesystemCache, PartitionDriverError, PartitionError, PermissionError, PlanetScaleReplicator, Plugin, PluginError, PluginObject, PluginStorageError, PostgresReplicator, QueueConsumerPlugin, REPLICATOR_DRIVERS, RabbitMqConsumer, RelationPlugin, ReplicatorPlugin, Resource, ResourceError, ResourceIdsPageReader, ResourceIdsReader, ResourceNotFound, ResourceReader, ResourceWriter, S3BackupDriver, S3Cache, S3QueuePlugin, Database as S3db, S3dbError, S3dbReplicator, SchedulerPlugin, Schema, SchemaError, Seeder, SqsConsumer, SqsReplicator, StateMachinePlugin, StreamError, TTLPlugin, TfStatePlugin, TursoReplicator, UnknownError, ValidationError, Validator, VectorPlugin, WebhookReplicator, behaviors, calculateAttributeNamesSize, calculateAttributeSizes, calculateEffectiveLimit, calculateSystemOverhead, calculateTotalSize, calculateUTF8Bytes, clearUTF8Memory, createBackupDriver, createConsumer, createReplicator, decode, decodeDecimal, decodeFixedPoint, decodeFixedPointBatch, decrypt, S3db as default, encode, encodeDecimal, encodeFixedPoint, encodeFixedPointBatch, encrypt, generateTypes, getBehavior, getSizeBreakdown, idGenerator, mapAwsError, md5, passwordGenerator, printTypes, sha256, streamToString, transformValue, tryFn, tryFnSync, validateBackupConfig, validateReplicatorConfig };
37120
38245
  //# sourceMappingURL=s3db.es.js.map