s3db.js 10.0.3 → 10.0.5
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-cli.js +0 -0
- package/dist/s3db.cjs.js +549 -2
- package/dist/s3db.cjs.js.map +1 -1
- package/dist/s3db.es.js +549 -2
- package/dist/s3db.es.js.map +1 -1
- package/mcp/README.md +1728 -0
- package/package.json +24 -22
- package/src/plugins/eventual-consistency.plugin.js +686 -2
package/dist/s3db.es.js
CHANGED
|
@@ -4339,10 +4339,20 @@ class EventualConsistencyPlugin extends Plugin {
|
|
|
4339
4339
|
// Days to keep applied transactions
|
|
4340
4340
|
gcInterval: options.gcInterval || 86400,
|
|
4341
4341
|
// 24 hours (in seconds)
|
|
4342
|
-
verbose: options.verbose || false
|
|
4342
|
+
verbose: options.verbose || false,
|
|
4343
|
+
// Analytics configuration
|
|
4344
|
+
enableAnalytics: options.enableAnalytics || false,
|
|
4345
|
+
analyticsConfig: {
|
|
4346
|
+
periods: options.analyticsConfig?.periods || ["hour", "day", "month"],
|
|
4347
|
+
metrics: options.analyticsConfig?.metrics || ["count", "sum", "avg", "min", "max"],
|
|
4348
|
+
rollupStrategy: options.analyticsConfig?.rollupStrategy || "incremental",
|
|
4349
|
+
// 'incremental' or 'batch'
|
|
4350
|
+
retentionDays: options.analyticsConfig?.retentionDays || 365
|
|
4351
|
+
}
|
|
4343
4352
|
};
|
|
4344
4353
|
this.transactionResource = null;
|
|
4345
4354
|
this.targetResource = null;
|
|
4355
|
+
this.analyticsResource = null;
|
|
4346
4356
|
this.consolidationTimer = null;
|
|
4347
4357
|
this.gcTimer = null;
|
|
4348
4358
|
this.pendingTransactions = /* @__PURE__ */ new Map();
|
|
@@ -4429,6 +4439,9 @@ class EventualConsistencyPlugin extends Plugin {
|
|
|
4429
4439
|
throw new Error(`Failed to create lock resource: ${lockErr?.message}`);
|
|
4430
4440
|
}
|
|
4431
4441
|
this.lockResource = lockOk ? lockResource : this.database.resources[lockResourceName];
|
|
4442
|
+
if (this.config.enableAnalytics) {
|
|
4443
|
+
await this.createAnalyticsResource();
|
|
4444
|
+
}
|
|
4432
4445
|
this.addHelperMethods();
|
|
4433
4446
|
if (this.config.autoConsolidate) {
|
|
4434
4447
|
this.startConsolidationTimer();
|
|
@@ -4480,6 +4493,53 @@ class EventualConsistencyPlugin extends Plugin {
|
|
|
4480
4493
|
};
|
|
4481
4494
|
return partitions;
|
|
4482
4495
|
}
|
|
4496
|
+
async createAnalyticsResource() {
|
|
4497
|
+
const analyticsResourceName = `${this.config.resource}_analytics_${this.config.field}`;
|
|
4498
|
+
const [ok, err, analyticsResource] = await tryFn(
|
|
4499
|
+
() => this.database.createResource({
|
|
4500
|
+
name: analyticsResourceName,
|
|
4501
|
+
attributes: {
|
|
4502
|
+
id: "string|required",
|
|
4503
|
+
period: "string|required",
|
|
4504
|
+
// 'hour', 'day', 'month'
|
|
4505
|
+
cohort: "string|required",
|
|
4506
|
+
// ISO format: '2025-10-09T14', '2025-10-09', '2025-10'
|
|
4507
|
+
// Aggregated metrics
|
|
4508
|
+
transactionCount: "number|required",
|
|
4509
|
+
totalValue: "number|required",
|
|
4510
|
+
avgValue: "number|required",
|
|
4511
|
+
minValue: "number|required",
|
|
4512
|
+
maxValue: "number|required",
|
|
4513
|
+
// Operation breakdown
|
|
4514
|
+
operations: "object|optional",
|
|
4515
|
+
// { add: { count, sum }, sub: { count, sum }, set: { count, sum } }
|
|
4516
|
+
// Metadata
|
|
4517
|
+
recordCount: "number|required",
|
|
4518
|
+
// Distinct originalIds
|
|
4519
|
+
consolidatedAt: "string|required",
|
|
4520
|
+
updatedAt: "string|required"
|
|
4521
|
+
},
|
|
4522
|
+
behavior: "body-overflow",
|
|
4523
|
+
timestamps: false,
|
|
4524
|
+
partitions: {
|
|
4525
|
+
byPeriod: {
|
|
4526
|
+
fields: { period: "string" }
|
|
4527
|
+
},
|
|
4528
|
+
byCohort: {
|
|
4529
|
+
fields: { cohort: "string" }
|
|
4530
|
+
}
|
|
4531
|
+
}
|
|
4532
|
+
})
|
|
4533
|
+
);
|
|
4534
|
+
if (!ok && !this.database.resources[analyticsResourceName]) {
|
|
4535
|
+
console.warn(`[EventualConsistency] Failed to create analytics resource: ${err?.message}`);
|
|
4536
|
+
return;
|
|
4537
|
+
}
|
|
4538
|
+
this.analyticsResource = ok ? analyticsResource : this.database.resources[analyticsResourceName];
|
|
4539
|
+
if (this.config.verbose) {
|
|
4540
|
+
console.log(`[EventualConsistency] Analytics resource created: ${analyticsResourceName}`);
|
|
4541
|
+
}
|
|
4542
|
+
}
|
|
4483
4543
|
/**
|
|
4484
4544
|
* Auto-detect timezone from environment or system
|
|
4485
4545
|
* @private
|
|
@@ -4827,6 +4887,9 @@ class EventualConsistencyPlugin extends Plugin {
|
|
|
4827
4887
|
if (errors && errors.length > 0 && this.config.verbose) {
|
|
4828
4888
|
console.warn(`[EventualConsistency] ${errors.length} transactions failed to mark as applied`);
|
|
4829
4889
|
}
|
|
4890
|
+
if (this.config.enableAnalytics && transactionsToUpdate.length > 0) {
|
|
4891
|
+
await this.updateAnalytics(transactionsToUpdate);
|
|
4892
|
+
}
|
|
4830
4893
|
}
|
|
4831
4894
|
return consolidatedValue;
|
|
4832
4895
|
} finally {
|
|
@@ -5034,6 +5097,490 @@ class EventualConsistencyPlugin extends Plugin {
|
|
|
5034
5097
|
await tryFn(() => this.lockResource.delete(gcLockId));
|
|
5035
5098
|
}
|
|
5036
5099
|
}
|
|
5100
|
+
/**
|
|
5101
|
+
* Update analytics with consolidated transactions
|
|
5102
|
+
* @param {Array} transactions - Array of transactions that were just consolidated
|
|
5103
|
+
* @private
|
|
5104
|
+
*/
|
|
5105
|
+
async updateAnalytics(transactions) {
|
|
5106
|
+
if (!this.analyticsResource || transactions.length === 0) return;
|
|
5107
|
+
try {
|
|
5108
|
+
const byHour = this._groupByCohort(transactions, "cohortHour");
|
|
5109
|
+
for (const [cohort, txns] of Object.entries(byHour)) {
|
|
5110
|
+
await this._upsertAnalytics("hour", cohort, txns);
|
|
5111
|
+
}
|
|
5112
|
+
if (this.config.analyticsConfig.rollupStrategy === "incremental") {
|
|
5113
|
+
const uniqueHours = Object.keys(byHour);
|
|
5114
|
+
for (const cohortHour of uniqueHours) {
|
|
5115
|
+
await this._rollupAnalytics(cohortHour);
|
|
5116
|
+
}
|
|
5117
|
+
}
|
|
5118
|
+
} catch (error) {
|
|
5119
|
+
if (this.config.verbose) {
|
|
5120
|
+
console.warn(`[EventualConsistency] Analytics update error:`, error.message);
|
|
5121
|
+
}
|
|
5122
|
+
}
|
|
5123
|
+
}
|
|
5124
|
+
/**
|
|
5125
|
+
* Group transactions by cohort
|
|
5126
|
+
* @private
|
|
5127
|
+
*/
|
|
5128
|
+
_groupByCohort(transactions, cohortField) {
|
|
5129
|
+
const groups = {};
|
|
5130
|
+
for (const txn of transactions) {
|
|
5131
|
+
const cohort = txn[cohortField];
|
|
5132
|
+
if (!cohort) continue;
|
|
5133
|
+
if (!groups[cohort]) {
|
|
5134
|
+
groups[cohort] = [];
|
|
5135
|
+
}
|
|
5136
|
+
groups[cohort].push(txn);
|
|
5137
|
+
}
|
|
5138
|
+
return groups;
|
|
5139
|
+
}
|
|
5140
|
+
/**
|
|
5141
|
+
* Upsert analytics for a specific period and cohort
|
|
5142
|
+
* @private
|
|
5143
|
+
*/
|
|
5144
|
+
async _upsertAnalytics(period, cohort, transactions) {
|
|
5145
|
+
const id = `${period}-${cohort}`;
|
|
5146
|
+
const transactionCount = transactions.length;
|
|
5147
|
+
const signedValues = transactions.map((t) => {
|
|
5148
|
+
if (t.operation === "sub") return -t.value;
|
|
5149
|
+
return t.value;
|
|
5150
|
+
});
|
|
5151
|
+
const totalValue = signedValues.reduce((sum, v) => sum + v, 0);
|
|
5152
|
+
const avgValue = totalValue / transactionCount;
|
|
5153
|
+
const minValue = Math.min(...signedValues);
|
|
5154
|
+
const maxValue = Math.max(...signedValues);
|
|
5155
|
+
const operations = this._calculateOperationBreakdown(transactions);
|
|
5156
|
+
const recordCount = new Set(transactions.map((t) => t.originalId)).size;
|
|
5157
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
5158
|
+
const [existingOk, existingErr, existing] = await tryFn(
|
|
5159
|
+
() => this.analyticsResource.get(id)
|
|
5160
|
+
);
|
|
5161
|
+
if (existingOk && existing) {
|
|
5162
|
+
const newTransactionCount = existing.transactionCount + transactionCount;
|
|
5163
|
+
const newTotalValue = existing.totalValue + totalValue;
|
|
5164
|
+
const newAvgValue = newTotalValue / newTransactionCount;
|
|
5165
|
+
const newMinValue = Math.min(existing.minValue, minValue);
|
|
5166
|
+
const newMaxValue = Math.max(existing.maxValue, maxValue);
|
|
5167
|
+
const newOperations = { ...existing.operations };
|
|
5168
|
+
for (const [op, stats] of Object.entries(operations)) {
|
|
5169
|
+
if (!newOperations[op]) {
|
|
5170
|
+
newOperations[op] = { count: 0, sum: 0 };
|
|
5171
|
+
}
|
|
5172
|
+
newOperations[op].count += stats.count;
|
|
5173
|
+
newOperations[op].sum += stats.sum;
|
|
5174
|
+
}
|
|
5175
|
+
const newRecordCount = Math.max(existing.recordCount, recordCount);
|
|
5176
|
+
await tryFn(
|
|
5177
|
+
() => this.analyticsResource.update(id, {
|
|
5178
|
+
transactionCount: newTransactionCount,
|
|
5179
|
+
totalValue: newTotalValue,
|
|
5180
|
+
avgValue: newAvgValue,
|
|
5181
|
+
minValue: newMinValue,
|
|
5182
|
+
maxValue: newMaxValue,
|
|
5183
|
+
operations: newOperations,
|
|
5184
|
+
recordCount: newRecordCount,
|
|
5185
|
+
updatedAt: now
|
|
5186
|
+
})
|
|
5187
|
+
);
|
|
5188
|
+
} else {
|
|
5189
|
+
await tryFn(
|
|
5190
|
+
() => this.analyticsResource.insert({
|
|
5191
|
+
id,
|
|
5192
|
+
period,
|
|
5193
|
+
cohort,
|
|
5194
|
+
transactionCount,
|
|
5195
|
+
totalValue,
|
|
5196
|
+
avgValue,
|
|
5197
|
+
minValue,
|
|
5198
|
+
maxValue,
|
|
5199
|
+
operations,
|
|
5200
|
+
recordCount,
|
|
5201
|
+
consolidatedAt: now,
|
|
5202
|
+
updatedAt: now
|
|
5203
|
+
})
|
|
5204
|
+
);
|
|
5205
|
+
}
|
|
5206
|
+
}
|
|
5207
|
+
/**
|
|
5208
|
+
* Calculate operation breakdown
|
|
5209
|
+
* @private
|
|
5210
|
+
*/
|
|
5211
|
+
_calculateOperationBreakdown(transactions) {
|
|
5212
|
+
const breakdown = {};
|
|
5213
|
+
for (const txn of transactions) {
|
|
5214
|
+
const op = txn.operation;
|
|
5215
|
+
if (!breakdown[op]) {
|
|
5216
|
+
breakdown[op] = { count: 0, sum: 0 };
|
|
5217
|
+
}
|
|
5218
|
+
breakdown[op].count++;
|
|
5219
|
+
const signedValue = op === "sub" ? -txn.value : txn.value;
|
|
5220
|
+
breakdown[op].sum += signedValue;
|
|
5221
|
+
}
|
|
5222
|
+
return breakdown;
|
|
5223
|
+
}
|
|
5224
|
+
/**
|
|
5225
|
+
* Roll up hourly analytics to daily and monthly
|
|
5226
|
+
* @private
|
|
5227
|
+
*/
|
|
5228
|
+
async _rollupAnalytics(cohortHour) {
|
|
5229
|
+
const cohortDate = cohortHour.substring(0, 10);
|
|
5230
|
+
const cohortMonth = cohortHour.substring(0, 7);
|
|
5231
|
+
await this._rollupPeriod("day", cohortDate, cohortDate);
|
|
5232
|
+
await this._rollupPeriod("month", cohortMonth, cohortMonth);
|
|
5233
|
+
}
|
|
5234
|
+
/**
|
|
5235
|
+
* Roll up analytics for a specific period
|
|
5236
|
+
* @private
|
|
5237
|
+
*/
|
|
5238
|
+
async _rollupPeriod(period, cohort, sourcePrefix) {
|
|
5239
|
+
const sourcePeriod = period === "day" ? "hour" : "day";
|
|
5240
|
+
const [ok, err, allAnalytics] = await tryFn(
|
|
5241
|
+
() => this.analyticsResource.list()
|
|
5242
|
+
);
|
|
5243
|
+
if (!ok || !allAnalytics) return;
|
|
5244
|
+
const sourceAnalytics = allAnalytics.filter(
|
|
5245
|
+
(a) => a.period === sourcePeriod && a.cohort.startsWith(sourcePrefix)
|
|
5246
|
+
);
|
|
5247
|
+
if (sourceAnalytics.length === 0) return;
|
|
5248
|
+
const transactionCount = sourceAnalytics.reduce((sum, a) => sum + a.transactionCount, 0);
|
|
5249
|
+
const totalValue = sourceAnalytics.reduce((sum, a) => sum + a.totalValue, 0);
|
|
5250
|
+
const avgValue = totalValue / transactionCount;
|
|
5251
|
+
const minValue = Math.min(...sourceAnalytics.map((a) => a.minValue));
|
|
5252
|
+
const maxValue = Math.max(...sourceAnalytics.map((a) => a.maxValue));
|
|
5253
|
+
const operations = {};
|
|
5254
|
+
for (const analytics of sourceAnalytics) {
|
|
5255
|
+
for (const [op, stats] of Object.entries(analytics.operations || {})) {
|
|
5256
|
+
if (!operations[op]) {
|
|
5257
|
+
operations[op] = { count: 0, sum: 0 };
|
|
5258
|
+
}
|
|
5259
|
+
operations[op].count += stats.count;
|
|
5260
|
+
operations[op].sum += stats.sum;
|
|
5261
|
+
}
|
|
5262
|
+
}
|
|
5263
|
+
const recordCount = Math.max(...sourceAnalytics.map((a) => a.recordCount));
|
|
5264
|
+
const id = `${period}-${cohort}`;
|
|
5265
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
5266
|
+
const [existingOk, existingErr, existing] = await tryFn(
|
|
5267
|
+
() => this.analyticsResource.get(id)
|
|
5268
|
+
);
|
|
5269
|
+
if (existingOk && existing) {
|
|
5270
|
+
await tryFn(
|
|
5271
|
+
() => this.analyticsResource.update(id, {
|
|
5272
|
+
transactionCount,
|
|
5273
|
+
totalValue,
|
|
5274
|
+
avgValue,
|
|
5275
|
+
minValue,
|
|
5276
|
+
maxValue,
|
|
5277
|
+
operations,
|
|
5278
|
+
recordCount,
|
|
5279
|
+
updatedAt: now
|
|
5280
|
+
})
|
|
5281
|
+
);
|
|
5282
|
+
} else {
|
|
5283
|
+
await tryFn(
|
|
5284
|
+
() => this.analyticsResource.insert({
|
|
5285
|
+
id,
|
|
5286
|
+
period,
|
|
5287
|
+
cohort,
|
|
5288
|
+
transactionCount,
|
|
5289
|
+
totalValue,
|
|
5290
|
+
avgValue,
|
|
5291
|
+
minValue,
|
|
5292
|
+
maxValue,
|
|
5293
|
+
operations,
|
|
5294
|
+
recordCount,
|
|
5295
|
+
consolidatedAt: now,
|
|
5296
|
+
updatedAt: now
|
|
5297
|
+
})
|
|
5298
|
+
);
|
|
5299
|
+
}
|
|
5300
|
+
}
|
|
5301
|
+
/**
|
|
5302
|
+
* Get analytics for a specific period
|
|
5303
|
+
* @param {string} resourceName - Resource name
|
|
5304
|
+
* @param {string} field - Field name
|
|
5305
|
+
* @param {Object} options - Query options
|
|
5306
|
+
* @returns {Promise<Array>} Analytics data
|
|
5307
|
+
*/
|
|
5308
|
+
async getAnalytics(resourceName, field, options = {}) {
|
|
5309
|
+
if (!this.analyticsResource) {
|
|
5310
|
+
throw new Error("Analytics not enabled for this plugin");
|
|
5311
|
+
}
|
|
5312
|
+
const { period = "day", date, startDate, endDate, month, year, breakdown = false } = options;
|
|
5313
|
+
const [ok, err, allAnalytics] = await tryFn(
|
|
5314
|
+
() => this.analyticsResource.list()
|
|
5315
|
+
);
|
|
5316
|
+
if (!ok || !allAnalytics) {
|
|
5317
|
+
return [];
|
|
5318
|
+
}
|
|
5319
|
+
let filtered = allAnalytics.filter((a) => a.period === period);
|
|
5320
|
+
if (date) {
|
|
5321
|
+
if (period === "hour") {
|
|
5322
|
+
filtered = filtered.filter((a) => a.cohort.startsWith(date));
|
|
5323
|
+
} else {
|
|
5324
|
+
filtered = filtered.filter((a) => a.cohort === date);
|
|
5325
|
+
}
|
|
5326
|
+
} else if (startDate && endDate) {
|
|
5327
|
+
filtered = filtered.filter((a) => a.cohort >= startDate && a.cohort <= endDate);
|
|
5328
|
+
} else if (month) {
|
|
5329
|
+
filtered = filtered.filter((a) => a.cohort.startsWith(month));
|
|
5330
|
+
} else if (year) {
|
|
5331
|
+
filtered = filtered.filter((a) => a.cohort.startsWith(String(year)));
|
|
5332
|
+
}
|
|
5333
|
+
filtered.sort((a, b) => a.cohort.localeCompare(b.cohort));
|
|
5334
|
+
if (breakdown === "operations") {
|
|
5335
|
+
return filtered.map((a) => ({
|
|
5336
|
+
cohort: a.cohort,
|
|
5337
|
+
...a.operations
|
|
5338
|
+
}));
|
|
5339
|
+
}
|
|
5340
|
+
return filtered.map((a) => ({
|
|
5341
|
+
cohort: a.cohort,
|
|
5342
|
+
count: a.transactionCount,
|
|
5343
|
+
sum: a.totalValue,
|
|
5344
|
+
avg: a.avgValue,
|
|
5345
|
+
min: a.minValue,
|
|
5346
|
+
max: a.maxValue,
|
|
5347
|
+
operations: a.operations,
|
|
5348
|
+
recordCount: a.recordCount
|
|
5349
|
+
}));
|
|
5350
|
+
}
|
|
5351
|
+
/**
|
|
5352
|
+
* Fill gaps in analytics data with zeros for continuous time series
|
|
5353
|
+
* @private
|
|
5354
|
+
* @param {Array} data - Sparse analytics data
|
|
5355
|
+
* @param {string} period - Period type ('hour', 'day', 'month')
|
|
5356
|
+
* @param {string} startDate - Start date (ISO format)
|
|
5357
|
+
* @param {string} endDate - End date (ISO format)
|
|
5358
|
+
* @returns {Array} Complete time series with gaps filled
|
|
5359
|
+
*/
|
|
5360
|
+
_fillGaps(data, period, startDate, endDate) {
|
|
5361
|
+
if (!data || data.length === 0) {
|
|
5362
|
+
data = [];
|
|
5363
|
+
}
|
|
5364
|
+
const dataMap = /* @__PURE__ */ new Map();
|
|
5365
|
+
data.forEach((item) => {
|
|
5366
|
+
dataMap.set(item.cohort, item);
|
|
5367
|
+
});
|
|
5368
|
+
const result = [];
|
|
5369
|
+
const emptyRecord = {
|
|
5370
|
+
count: 0,
|
|
5371
|
+
sum: 0,
|
|
5372
|
+
avg: 0,
|
|
5373
|
+
min: 0,
|
|
5374
|
+
max: 0,
|
|
5375
|
+
recordCount: 0
|
|
5376
|
+
};
|
|
5377
|
+
if (period === "hour") {
|
|
5378
|
+
const start = /* @__PURE__ */ new Date(startDate + "T00:00:00Z");
|
|
5379
|
+
const end = /* @__PURE__ */ new Date(endDate + "T23:59:59Z");
|
|
5380
|
+
for (let dt = new Date(start); dt <= end; dt.setHours(dt.getHours() + 1)) {
|
|
5381
|
+
const cohort = dt.toISOString().substring(0, 13);
|
|
5382
|
+
result.push(dataMap.get(cohort) || { cohort, ...emptyRecord });
|
|
5383
|
+
}
|
|
5384
|
+
} else if (period === "day") {
|
|
5385
|
+
const start = new Date(startDate);
|
|
5386
|
+
const end = new Date(endDate);
|
|
5387
|
+
for (let dt = new Date(start); dt <= end; dt.setDate(dt.getDate() + 1)) {
|
|
5388
|
+
const cohort = dt.toISOString().substring(0, 10);
|
|
5389
|
+
result.push(dataMap.get(cohort) || { cohort, ...emptyRecord });
|
|
5390
|
+
}
|
|
5391
|
+
} else if (period === "month") {
|
|
5392
|
+
const startYear = parseInt(startDate.substring(0, 4));
|
|
5393
|
+
const startMonth = parseInt(startDate.substring(5, 7));
|
|
5394
|
+
const endYear = parseInt(endDate.substring(0, 4));
|
|
5395
|
+
const endMonth = parseInt(endDate.substring(5, 7));
|
|
5396
|
+
for (let year = startYear; year <= endYear; year++) {
|
|
5397
|
+
const firstMonth = year === startYear ? startMonth : 1;
|
|
5398
|
+
const lastMonth = year === endYear ? endMonth : 12;
|
|
5399
|
+
for (let month = firstMonth; month <= lastMonth; month++) {
|
|
5400
|
+
const cohort = `${year}-${month.toString().padStart(2, "0")}`;
|
|
5401
|
+
result.push(dataMap.get(cohort) || { cohort, ...emptyRecord });
|
|
5402
|
+
}
|
|
5403
|
+
}
|
|
5404
|
+
}
|
|
5405
|
+
return result;
|
|
5406
|
+
}
|
|
5407
|
+
/**
|
|
5408
|
+
* Get analytics for entire month, broken down by days
|
|
5409
|
+
* @param {string} resourceName - Resource name
|
|
5410
|
+
* @param {string} field - Field name
|
|
5411
|
+
* @param {string} month - Month in YYYY-MM format
|
|
5412
|
+
* @param {Object} options - Options
|
|
5413
|
+
* @param {boolean} options.fillGaps - Fill missing days with zeros (default: false)
|
|
5414
|
+
* @returns {Promise<Array>} Daily analytics for the month
|
|
5415
|
+
*/
|
|
5416
|
+
async getMonthByDay(resourceName, field, month, options = {}) {
|
|
5417
|
+
const year = parseInt(month.substring(0, 4));
|
|
5418
|
+
const monthNum = parseInt(month.substring(5, 7));
|
|
5419
|
+
const firstDay = new Date(year, monthNum - 1, 1);
|
|
5420
|
+
const lastDay = new Date(year, monthNum, 0);
|
|
5421
|
+
const startDate = firstDay.toISOString().substring(0, 10);
|
|
5422
|
+
const endDate = lastDay.toISOString().substring(0, 10);
|
|
5423
|
+
const data = await this.getAnalytics(resourceName, field, {
|
|
5424
|
+
period: "day",
|
|
5425
|
+
startDate,
|
|
5426
|
+
endDate
|
|
5427
|
+
});
|
|
5428
|
+
if (options.fillGaps) {
|
|
5429
|
+
return this._fillGaps(data, "day", startDate, endDate);
|
|
5430
|
+
}
|
|
5431
|
+
return data;
|
|
5432
|
+
}
|
|
5433
|
+
/**
|
|
5434
|
+
* Get analytics for entire day, broken down by hours
|
|
5435
|
+
* @param {string} resourceName - Resource name
|
|
5436
|
+
* @param {string} field - Field name
|
|
5437
|
+
* @param {string} date - Date in YYYY-MM-DD format
|
|
5438
|
+
* @param {Object} options - Options
|
|
5439
|
+
* @param {boolean} options.fillGaps - Fill missing hours with zeros (default: false)
|
|
5440
|
+
* @returns {Promise<Array>} Hourly analytics for the day
|
|
5441
|
+
*/
|
|
5442
|
+
async getDayByHour(resourceName, field, date, options = {}) {
|
|
5443
|
+
const data = await this.getAnalytics(resourceName, field, {
|
|
5444
|
+
period: "hour",
|
|
5445
|
+
date
|
|
5446
|
+
});
|
|
5447
|
+
if (options.fillGaps) {
|
|
5448
|
+
return this._fillGaps(data, "hour", date, date);
|
|
5449
|
+
}
|
|
5450
|
+
return data;
|
|
5451
|
+
}
|
|
5452
|
+
/**
|
|
5453
|
+
* Get analytics for last N days, broken down by days
|
|
5454
|
+
* @param {string} resourceName - Resource name
|
|
5455
|
+
* @param {string} field - Field name
|
|
5456
|
+
* @param {number} days - Number of days to look back (default: 7)
|
|
5457
|
+
* @param {Object} options - Options
|
|
5458
|
+
* @param {boolean} options.fillGaps - Fill missing days with zeros (default: false)
|
|
5459
|
+
* @returns {Promise<Array>} Daily analytics
|
|
5460
|
+
*/
|
|
5461
|
+
async getLastNDays(resourceName, field, days = 7, options = {}) {
|
|
5462
|
+
const dates = Array.from({ length: days }, (_, i) => {
|
|
5463
|
+
const date = /* @__PURE__ */ new Date();
|
|
5464
|
+
date.setDate(date.getDate() - i);
|
|
5465
|
+
return date.toISOString().substring(0, 10);
|
|
5466
|
+
}).reverse();
|
|
5467
|
+
const data = await this.getAnalytics(resourceName, field, {
|
|
5468
|
+
period: "day",
|
|
5469
|
+
startDate: dates[0],
|
|
5470
|
+
endDate: dates[dates.length - 1]
|
|
5471
|
+
});
|
|
5472
|
+
if (options.fillGaps) {
|
|
5473
|
+
return this._fillGaps(data, "day", dates[0], dates[dates.length - 1]);
|
|
5474
|
+
}
|
|
5475
|
+
return data;
|
|
5476
|
+
}
|
|
5477
|
+
/**
|
|
5478
|
+
* Get analytics for entire year, broken down by months
|
|
5479
|
+
* @param {string} resourceName - Resource name
|
|
5480
|
+
* @param {string} field - Field name
|
|
5481
|
+
* @param {number} year - Year (e.g., 2025)
|
|
5482
|
+
* @param {Object} options - Options
|
|
5483
|
+
* @param {boolean} options.fillGaps - Fill missing months with zeros (default: false)
|
|
5484
|
+
* @returns {Promise<Array>} Monthly analytics for the year
|
|
5485
|
+
*/
|
|
5486
|
+
async getYearByMonth(resourceName, field, year, options = {}) {
|
|
5487
|
+
const data = await this.getAnalytics(resourceName, field, {
|
|
5488
|
+
period: "month",
|
|
5489
|
+
year
|
|
5490
|
+
});
|
|
5491
|
+
if (options.fillGaps) {
|
|
5492
|
+
const startDate = `${year}-01`;
|
|
5493
|
+
const endDate = `${year}-12`;
|
|
5494
|
+
return this._fillGaps(data, "month", startDate, endDate);
|
|
5495
|
+
}
|
|
5496
|
+
return data;
|
|
5497
|
+
}
|
|
5498
|
+
/**
|
|
5499
|
+
* Get analytics for entire month, broken down by hours
|
|
5500
|
+
* @param {string} resourceName - Resource name
|
|
5501
|
+
* @param {string} field - Field name
|
|
5502
|
+
* @param {string} month - Month in YYYY-MM format (or 'last' for previous month)
|
|
5503
|
+
* @param {Object} options - Options
|
|
5504
|
+
* @param {boolean} options.fillGaps - Fill missing hours with zeros (default: false)
|
|
5505
|
+
* @returns {Promise<Array>} Hourly analytics for the month (up to 24*31=744 records)
|
|
5506
|
+
*/
|
|
5507
|
+
async getMonthByHour(resourceName, field, month, options = {}) {
|
|
5508
|
+
let year, monthNum;
|
|
5509
|
+
if (month === "last") {
|
|
5510
|
+
const now = /* @__PURE__ */ new Date();
|
|
5511
|
+
now.setMonth(now.getMonth() - 1);
|
|
5512
|
+
year = now.getFullYear();
|
|
5513
|
+
monthNum = now.getMonth() + 1;
|
|
5514
|
+
} else {
|
|
5515
|
+
year = parseInt(month.substring(0, 4));
|
|
5516
|
+
monthNum = parseInt(month.substring(5, 7));
|
|
5517
|
+
}
|
|
5518
|
+
const firstDay = new Date(year, monthNum - 1, 1);
|
|
5519
|
+
const lastDay = new Date(year, monthNum, 0);
|
|
5520
|
+
const startDate = firstDay.toISOString().substring(0, 10);
|
|
5521
|
+
const endDate = lastDay.toISOString().substring(0, 10);
|
|
5522
|
+
const data = await this.getAnalytics(resourceName, field, {
|
|
5523
|
+
period: "hour",
|
|
5524
|
+
startDate,
|
|
5525
|
+
endDate
|
|
5526
|
+
});
|
|
5527
|
+
if (options.fillGaps) {
|
|
5528
|
+
return this._fillGaps(data, "hour", startDate, endDate);
|
|
5529
|
+
}
|
|
5530
|
+
return data;
|
|
5531
|
+
}
|
|
5532
|
+
/**
|
|
5533
|
+
* Get top records by volume
|
|
5534
|
+
* @param {string} resourceName - Resource name
|
|
5535
|
+
* @param {string} field - Field name
|
|
5536
|
+
* @param {Object} options - Query options
|
|
5537
|
+
* @returns {Promise<Array>} Top records
|
|
5538
|
+
*/
|
|
5539
|
+
async getTopRecords(resourceName, field, options = {}) {
|
|
5540
|
+
if (!this.transactionResource) {
|
|
5541
|
+
throw new Error("Transaction resource not initialized");
|
|
5542
|
+
}
|
|
5543
|
+
const { period = "day", date, metric = "transactionCount", limit = 10 } = options;
|
|
5544
|
+
const [ok, err, transactions] = await tryFn(
|
|
5545
|
+
() => this.transactionResource.list()
|
|
5546
|
+
);
|
|
5547
|
+
if (!ok || !transactions) {
|
|
5548
|
+
return [];
|
|
5549
|
+
}
|
|
5550
|
+
let filtered = transactions;
|
|
5551
|
+
if (date) {
|
|
5552
|
+
if (period === "hour") {
|
|
5553
|
+
filtered = transactions.filter((t) => t.cohortHour && t.cohortHour.startsWith(date));
|
|
5554
|
+
} else if (period === "day") {
|
|
5555
|
+
filtered = transactions.filter((t) => t.cohortDate === date);
|
|
5556
|
+
} else if (period === "month") {
|
|
5557
|
+
filtered = transactions.filter((t) => t.cohortMonth && t.cohortMonth.startsWith(date));
|
|
5558
|
+
}
|
|
5559
|
+
}
|
|
5560
|
+
const byRecord = {};
|
|
5561
|
+
for (const txn of filtered) {
|
|
5562
|
+
const recordId = txn.originalId;
|
|
5563
|
+
if (!byRecord[recordId]) {
|
|
5564
|
+
byRecord[recordId] = { count: 0, sum: 0 };
|
|
5565
|
+
}
|
|
5566
|
+
byRecord[recordId].count++;
|
|
5567
|
+
byRecord[recordId].sum += txn.value;
|
|
5568
|
+
}
|
|
5569
|
+
const records = Object.entries(byRecord).map(([recordId, stats]) => ({
|
|
5570
|
+
recordId,
|
|
5571
|
+
count: stats.count,
|
|
5572
|
+
sum: stats.sum
|
|
5573
|
+
}));
|
|
5574
|
+
records.sort((a, b) => {
|
|
5575
|
+
if (metric === "transactionCount") {
|
|
5576
|
+
return b.count - a.count;
|
|
5577
|
+
} else if (metric === "totalValue") {
|
|
5578
|
+
return b.sum - a.sum;
|
|
5579
|
+
}
|
|
5580
|
+
return 0;
|
|
5581
|
+
});
|
|
5582
|
+
return records.slice(0, limit);
|
|
5583
|
+
}
|
|
5037
5584
|
}
|
|
5038
5585
|
|
|
5039
5586
|
class FullTextPlugin extends Plugin {
|
|
@@ -11101,7 +11648,7 @@ class Database extends EventEmitter {
|
|
|
11101
11648
|
this.id = idGenerator(7);
|
|
11102
11649
|
this.version = "1";
|
|
11103
11650
|
this.s3dbVersion = (() => {
|
|
11104
|
-
const [ok, err, version] = tryFn(() => true ? "10.0.
|
|
11651
|
+
const [ok, err, version] = tryFn(() => true ? "10.0.5" : "latest");
|
|
11105
11652
|
return ok ? version : "latest";
|
|
11106
11653
|
})();
|
|
11107
11654
|
this.resources = {};
|