@routier/core 0.3.0 → 0.5.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.
Files changed (35) hide show
  1. package/README.md +2 -2
  2. package/dist/index.cjs +549 -462
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.ts +0 -1
  5. package/dist/index.js +554 -462
  6. package/dist/index.js.map +1 -1
  7. package/dist/plugins/TelemetryDbPlugin.d.ts +43 -0
  8. package/dist/plugins/index.cjs +538 -24
  9. package/dist/plugins/index.cjs.map +1 -1
  10. package/dist/plugins/index.d.ts +1 -0
  11. package/dist/plugins/index.js +544 -22
  12. package/dist/plugins/index.js.map +1 -1
  13. package/dist/plugins/query/QueryOptionsCollection.d.ts +13 -0
  14. package/dist/plugins/query/explain.d.ts +82 -0
  15. package/dist/plugins/query/formatExplanation.d.ts +9 -0
  16. package/dist/plugins/query/index.d.ts +2 -0
  17. package/dist/plugins/query/types.d.ts +11 -0
  18. package/dist/plugins/types.d.ts +43 -1
  19. package/dist/plugins/wire/types.d.ts +17 -1
  20. package/dist/utilities/index.cjs +43 -12
  21. package/dist/utilities/index.cjs.map +1 -1
  22. package/dist/utilities/index.js +43 -12
  23. package/dist/utilities/index.js.map +1 -1
  24. package/package.json +6 -10
  25. package/dist/capabilities/Capability.d.ts +0 -11
  26. package/dist/capabilities/PerformanceCapability.d.ts +0 -13
  27. package/dist/capabilities/TracingCapability.d.ts +0 -11
  28. package/dist/capabilities/index.cjs +0 -820
  29. package/dist/capabilities/index.cjs.map +0 -1
  30. package/dist/capabilities/index.d.ts +0 -4
  31. package/dist/capabilities/index.js +0 -808
  32. package/dist/capabilities/index.js.map +0 -1
  33. package/dist/capabilities/performance/PerformanceTracker.d.ts +0 -11
  34. package/dist/capabilities/tracing/CallTraceManager.d.ts +0 -12
  35. package/dist/capabilities/types.d.ts +0 -17
package/dist/index.cjs CHANGED
@@ -101,436 +101,6 @@ function isObjectWithType(value) {
101
101
  }
102
102
 
103
103
 
104
- },
105
- 599(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
106
-
107
- // EXPORTS
108
- __webpack_require__.d(__webpack_exports__, {
109
- TracingCapability: () => (/* reexport */ TracingCapability),
110
- Capability: () => (/* reexport */ Capability),
111
- PerformanceCapability: () => (/* reexport */ PerformanceCapability)
112
- });
113
-
114
- ;// CONCATENATED MODULE: ./src/capabilities/Capability.ts
115
- class Capability {
116
- excludedNames = new Set([
117
- "Array",
118
- "Set",
119
- "Map",
120
- "AbortController",
121
- "AbortSignal",
122
- "SchemaString",
123
- "SchemaNumber",
124
- "SchemaArray",
125
- "SchemaBoolean",
126
- "SchemaDate",
127
- "SchemaObject",
128
- "SchemaDefault",
129
- "SchemaDeserialize",
130
- "SchemaDistinct",
131
- "SchemaSearchable",
132
- "SchemaFrom",
133
- "SchemaIdentity",
134
- "SchemaIndex",
135
- "SchemaKey",
136
- "SchemaNullable",
137
- "SchemaOptional",
138
- "SchemaReadonly",
139
- "SchemaSerialize",
140
- "SchemaTracked",
141
- "SchemaComputed",
142
- "SchemaFunction",
143
- "SchemaBase",
144
- "SchemaDefinition"
145
- ]);
146
- isValidObject(obj) {
147
- return typeof obj === "object" && obj !== null;
148
- }
149
- isCallableMethod(descriptor, key) {
150
- return descriptor?.value && typeof descriptor.value === 'function' && key !== 'constructor' && key !== 'undefined';
151
- }
152
- canExplore(descriptor) {
153
- if (typeof descriptor.value !== "object") {
154
- return false;
155
- }
156
- if (descriptor.value == null) {
157
- return false;
158
- }
159
- const name = this.getName(descriptor.value);
160
- if (name == null) {
161
- return true;
162
- }
163
- return this.excludedNames.has(name) === false;
164
- }
165
- getName(value) {
166
- if (value.constructor != null) {
167
- return value.constructor.name;
168
- }
169
- return null;
170
- }
171
- getPath(info, propertyName) {
172
- let parent = info.parent;
173
- const path = [
174
- info.propertyName,
175
- propertyName
176
- ];
177
- while(parent != null){
178
- path.unshift(parent.propertyName);
179
- parent = parent.parent;
180
- }
181
- return path.join(".");
182
- }
183
- explore(instance, onDiscover) {
184
- if (!this.isValidObject(instance)) {
185
- return;
186
- }
187
- const explore = [
188
- {
189
- instance,
190
- propertyName: this.getName(instance)
191
- }
192
- ];
193
- const visited = new Set();
194
- for(let i = 0; i < explore.length; i++){
195
- const info = explore[i];
196
- const item = info.instance;
197
- if (visited.has(item)) {
198
- continue;
199
- }
200
- const allKeys = [
201
- ...Object.getOwnPropertyNames(item),
202
- ...Object.getOwnPropertySymbols(item)
203
- ];
204
- for (const key of allKeys){
205
- const descriptor = Object.getOwnPropertyDescriptor(item, key);
206
- const isCallable = this.isCallableMethod(descriptor, key);
207
- onDiscover(info, {
208
- name: key,
209
- isCallable
210
- });
211
- if (this.canExplore(descriptor) === false) {
212
- continue;
213
- }
214
- const path = this.getPath(info, key);
215
- explore.push({
216
- instance: descriptor.value,
217
- parent: info,
218
- propertyName: key,
219
- path
220
- });
221
- }
222
- visited.add(item);
223
- }
224
- }
225
- }
226
-
227
- // EXTERNAL MODULE: ./src/utilities/strings.ts
228
- var strings = __webpack_require__(615);
229
- ;// CONCATENATED MODULE: ./src/capabilities/performance/PerformanceTracker.ts
230
- class PerformanceTracker {
231
- methodTimings = new Map();
232
- operationStartTimes = new Map();
233
- startMethodTiming(operationId, methodPath) {
234
- const startTime = performance.now();
235
- const key = `${operationId}:${methodPath}`;
236
- // Track operation start time for delta calculations
237
- if (!this.operationStartTimes.has(operationId)) {
238
- this.operationStartTimes.set(operationId, startTime);
239
- }
240
- this.methodTimings.set(key, {
241
- startTime
242
- });
243
- return startTime;
244
- }
245
- recordNextMethodStart(operationId, methodPath) {
246
- const key = `${operationId}:${methodPath}`;
247
- const timing = this.methodTimings.get(key);
248
- if (timing) {
249
- timing.nextMethodStartTime = performance.now();
250
- }
251
- }
252
- endMethodTiming(operationId, methodPath) {
253
- const endTime = performance.now();
254
- const key = `${operationId}:${methodPath}`;
255
- const timing = this.methodTimings.get(key);
256
- if (!timing) {
257
- return {
258
- startTime: endTime
259
- };
260
- }
261
- const duration = endTime - timing.startTime;
262
- const timeToNextCall = timing.nextMethodStartTime ? timing.nextMethodStartTime - timing.startTime : undefined;
263
- // Clean up
264
- this.methodTimings.delete(key);
265
- return {
266
- startTime: timing.startTime,
267
- endTime,
268
- duration,
269
- nextMethodStartTime: timing.nextMethodStartTime,
270
- timeToNextCall
271
- };
272
- }
273
- formatDuration(milliseconds) {
274
- if (milliseconds < 1) {
275
- return `${(milliseconds * 1000).toFixed(1)}μs`;
276
- } else if (milliseconds < 1000) {
277
- return `${milliseconds.toFixed(2)}ms`;
278
- } else {
279
- return `${(milliseconds / 1000).toFixed(2)}s`;
280
- }
281
- }
282
- getDeltaFromOperationStart(operationId, currentTime) {
283
- const operationStartTime = this.operationStartTimes.get(operationId);
284
- return operationStartTime ? currentTime - operationStartTime : 0;
285
- }
286
- cleanupOperation(operationId) {
287
- this.operationStartTimes.delete(operationId);
288
- }
289
- }
290
-
291
- // EXTERNAL MODULE: ./src/utilities/uuid.ts
292
- var uuid = __webpack_require__(618);
293
- ;// CONCATENATED MODULE: ./src/capabilities/tracing/CallTraceManager.ts
294
-
295
- class CallTraceManager {
296
- activeOperationId = null;
297
- activeCallStack = [];
298
- startNewOperation() {
299
- const operationId = (0,uuid/* .uuid */.u)(8);
300
- this.activeOperationId = operationId;
301
- this.activeCallStack = [];
302
- return operationId;
303
- }
304
- isNewOperation() {
305
- return this.activeOperationId === null;
306
- }
307
- getActiveOperationId() {
308
- if (!this.activeOperationId) {
309
- throw new Error('No active operation context');
310
- }
311
- return this.activeOperationId;
312
- }
313
- addMethodToTrace(methodPath) {
314
- if (this.isNewOperation()) {
315
- this.activeCallStack = [
316
- methodPath
317
- ];
318
- } else {
319
- this.activeCallStack.push(methodPath);
320
- }
321
- return [
322
- ...this.activeCallStack
323
- ];
324
- }
325
- removeMethodFromTrace() {
326
- if (!this.isNewOperation()) {
327
- this.activeCallStack.pop();
328
- }
329
- }
330
- endOperation() {
331
- this.activeOperationId = null;
332
- this.activeCallStack = [];
333
- }
334
- formatMethodPaths(methodPaths) {
335
- return methodPaths.map((path)=>path.replace(/ → /g, '.'));
336
- }
337
- getCurrentTrace() {
338
- return [
339
- ...this.activeCallStack
340
- ];
341
- }
342
- }
343
-
344
- // EXTERNAL MODULE: ./src/utilities/logger.ts
345
- var logger = __webpack_require__(581);
346
- ;// CONCATENATED MODULE: ./src/capabilities/PerformanceCapability.ts
347
-
348
-
349
-
350
-
351
-
352
- class PerformanceCapability extends Capability {
353
- callTraceManager;
354
- performanceTracker;
355
- filter;
356
- childDurations = new Map();
357
- constructor(options){
358
- super();
359
- this.filter = options?.filter ?? (()=>true);
360
- this.callTraceManager = new CallTraceManager();
361
- this.performanceTracker = new PerformanceTracker();
362
- }
363
- apply(instance) {
364
- this.explore(instance, (meta, info)=>{
365
- if (info.isCallable) {
366
- const originalMethod = meta.instance[info.name].bind(meta.instance);
367
- meta.instance[info.name] = (...args)=>{
368
- const path = `${meta.path}.${String(info.name)}()`;
369
- if (this.filter(path, info, meta) === false) {
370
- return originalMethod(...args);
371
- }
372
- const isNewOperation = this.callTraceManager.isNewOperation();
373
- let operationId;
374
- let callTrace;
375
- let depth;
376
- if (isNewOperation) {
377
- operationId = this.callTraceManager.startNewOperation();
378
- this.childDurations.set(operationId, []);
379
- callTrace = this.callTraceManager.addMethodToTrace(path);
380
- depth = callTrace.length - 1;
381
- const formattedCallTrace = this.callTraceManager.formatMethodPaths(callTrace);
382
- this.performanceTracker.startMethodTiming(operationId, path);
383
- logger/* .logger.log */.vF.log(`\n${'═'.repeat(60)}`);
384
- logger/* .logger.log */.vF.log(`▶ ORIGIN [${operationId}] ${path}`);
385
- if (args.length > 0) {
386
- logger/* .logger.log */.vF.log(` Args:`, (0,strings/* .stringifyObject */.Zm)(args, 4, 0));
387
- }
388
- logger/* .logger.log */.vF.log(` Call Stack: ${formattedCallTrace.join(' → ')}`);
389
- } else {
390
- operationId = this.callTraceManager.getActiveOperationId();
391
- callTrace = this.callTraceManager.addMethodToTrace(path);
392
- depth = callTrace.length - 1;
393
- const indent = ' '.repeat(Math.min(depth, 4));
394
- // Track children for this child method too
395
- const childMethodKey = `${operationId}:${path}`;
396
- this.childDurations.set(childMethodKey, []);
397
- this.performanceTracker.startMethodTiming(operationId, path);
398
- logger/* .logger.log */.vF.log(`${indent}└─ CHILD [${operationId}] ${path}`);
399
- if (args.length > 0) {
400
- logger/* .logger.log */.vF.log(`${indent} Args:`, (0,strings/* .stringifyObject */.Zm)(args, 4, 0));
401
- }
402
- }
403
- try {
404
- return originalMethod(...args);
405
- } finally{
406
- const metrics = this.performanceTracker.endMethodTiming(operationId, path);
407
- const duration = metrics.duration ?? 0;
408
- const formattedDuration = this.performanceTracker.formatDuration(duration);
409
- if (isNewOperation) {
410
- const childDurations = this.childDurations.get(operationId) ?? [];
411
- const totalChildTime = childDurations.reduce((sum, d)=>sum + d, 0);
412
- const formattedTotalChildTime = this.performanceTracker.formatDuration(totalChildTime);
413
- const overhead = duration - totalChildTime;
414
- const formattedOverhead = this.performanceTracker.formatDuration(Math.max(0, overhead));
415
- logger/* .logger.log */.vF.log(`\n${'═'.repeat(60)}`);
416
- logger/* .logger.log */.vF.log(`◀ COMPLETE [${operationId}] ${path}`);
417
- logger/* .logger.log */.vF.log(` Total Duration: ${formattedDuration}`);
418
- if (childDurations.length > 0) {
419
- logger/* .logger.log */.vF.log(` Children Duration: ${formattedTotalChildTime} (${childDurations.length} calls)`);
420
- logger/* .logger.log */.vF.log(` Overhead: ${formattedOverhead}`);
421
- }
422
- logger/* .logger.log */.vF.log(`${'═'.repeat(60)}\n`);
423
- this.childDurations.delete(operationId);
424
- this.performanceTracker.cleanupOperation(operationId);
425
- this.callTraceManager.endOperation();
426
- } else {
427
- const indent = ' '.repeat(Math.min(depth, 4));
428
- const childMethodKey = `${operationId}:${path}`;
429
- const childDurations = this.childDurations.get(childMethodKey) ?? [];
430
- const totalChildTime = childDurations.reduce((sum, d)=>sum + d, 0);
431
- const formattedTotalChildTime = this.performanceTracker.formatDuration(totalChildTime);
432
- const overhead = duration - totalChildTime;
433
- const formattedOverhead = this.performanceTracker.formatDuration(Math.max(0, overhead));
434
- logger/* .logger.log */.vF.log(`${indent} ✓ ${formattedDuration}`);
435
- if (childDurations.length > 0) {
436
- logger/* .logger.log */.vF.log(`${indent} Children: ${formattedTotalChildTime} (${childDurations.length} calls), Overhead: ${formattedOverhead}`);
437
- }
438
- // Clean up child method tracking
439
- this.childDurations.delete(childMethodKey);
440
- // Find the parent method and add this duration to its children list
441
- // The parent is the method one level up in the call trace
442
- const currentTrace = this.callTraceManager.getCurrentTrace();
443
- if (currentTrace.length > 1) {
444
- // Parent is the second-to-last item in the trace (before we remove current)
445
- const parentPath = currentTrace[currentTrace.length - 2];
446
- // Check if parent is the root operation (trace length 2 means root + this child)
447
- if (currentTrace.length === 2) {
448
- // Direct child of root - add to root's children list
449
- const rootChildDurations = this.childDurations.get(operationId);
450
- if (rootChildDurations) {
451
- rootChildDurations.push(duration);
452
- }
453
- } else {
454
- // Nested child - add to parent method's children list
455
- const parentMethodKey = `${operationId}:${parentPath}`;
456
- const parentChildDurations = this.childDurations.get(parentMethodKey);
457
- if (parentChildDurations) {
458
- parentChildDurations.push(duration);
459
- }
460
- }
461
- }
462
- }
463
- this.callTraceManager.removeMethodFromTrace();
464
- }
465
- };
466
- }
467
- });
468
- }
469
- }
470
-
471
- ;// CONCATENATED MODULE: ./src/capabilities/TracingCapability.ts
472
-
473
-
474
-
475
- class TracingCapability extends Capability {
476
- callTraceManager;
477
- filter;
478
- constructor(options){
479
- super();
480
- this.filter = options?.filter ?? (()=>true);
481
- this.callTraceManager = new CallTraceManager();
482
- }
483
- apply(instance) {
484
- this.explore(instance, (meta, info)=>{
485
- if (info.isCallable) {
486
- const originalMethod = meta.instance[info.name].bind(meta.instance);
487
- meta.instance[info.name] = (...args)=>{
488
- const path = `${meta.path}.${String(info.name)}()`;
489
- if (this.filter(path, info, meta) === false) {
490
- return originalMethod(...args);
491
- }
492
- const isNewOperation = this.callTraceManager.isNewOperation();
493
- let operationId;
494
- if (isNewOperation) {
495
- operationId = this.callTraceManager.startNewOperation();
496
- const callTrace = this.callTraceManager.addMethodToTrace(path);
497
- const formattedCallTrace = this.callTraceManager.formatMethodPaths(callTrace);
498
- console.log(`\n${'═'.repeat(60)}`);
499
- console.log(`▶ ORIGIN [${operationId}] ${path}`);
500
- if (args.length > 0) {
501
- console.log(` Args:`, (0,strings/* .stringifyObject */.Zm)(args, 4, 0));
502
- }
503
- console.log(` Call Stack: ${formattedCallTrace.join(' → ')}`);
504
- } else {
505
- operationId = this.callTraceManager.getActiveOperationId();
506
- const callTrace = this.callTraceManager.addMethodToTrace(path);
507
- const indent = ' '.repeat(Math.min(callTrace.length - 1, 4));
508
- console.log(`${indent}└─ CHILD [${operationId}] ${path}`);
509
- if (args.length > 0) {
510
- console.log(`${indent} Args:`, (0,strings/* .stringifyObject */.Zm)(args, 4, 0));
511
- }
512
- }
513
- try {
514
- return originalMethod(...args);
515
- } finally{
516
- this.callTraceManager.removeMethodFromTrace();
517
- if (isNewOperation) {
518
- this.callTraceManager.endOperation();
519
- }
520
- }
521
- };
522
- }
523
- });
524
- }
525
- }
526
-
527
- ;// CONCATENATED MODULE: ./src/capabilities/index.ts
528
-
529
-
530
-
531
-
532
-
533
-
534
104
  },
535
105
  980(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
536
106
  __webpack_require__.d(__webpack_exports__, {
@@ -3687,38 +3257,46 @@ var TrampolinePipeline = __webpack_require__(416);
3687
3257
 
3688
3258
 
3689
3259
  },
3690
- 771(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
3260
+ 454(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
3691
3261
 
3692
3262
  // EXPORTS
3693
3263
  __webpack_require__.d(__webpack_exports__, {
3694
3264
  DEFAULT_SEMI_JOIN_KEY_THRESHOLD: () => (/* reexport */ DEFAULT_SEMI_JOIN_KEY_THRESHOLD),
3695
3265
  TranslatedArrayValue: () => (/* reexport */ TranslatedArrayValue),
3266
+ collectingSink: () => (/* reexport */ collectingSink),
3696
3267
  semiJoinFilter: () => (/* reexport */ semiJoinFilter),
3697
3268
  CacheDbPlugin: () => (/* reexport */ CacheDbPlugin),
3698
3269
  Query: () => (/* reexport */ Query),
3699
3270
  splitSendableOptions: () => (/* reexport */ splitSendableOptions),
3700
3271
  executeJoin: () => (/* reexport */ executeJoin),
3272
+ formatExplanation: () => (/* reexport */ formatExplanation),
3701
3273
  serializePersistResult: () => (/* reexport */ serializePersistResult),
3274
+ explainQuery: () => (/* reexport */ explainQuery),
3275
+ cosineDistance: () => (/* reexport */ cosineDistance),
3702
3276
  RetryDbPlugin: () => (/* reexport */ RetryDbPlugin),
3703
- nearestBy: () => (/* reexport */ nearestBy),
3704
3277
  BatchingDbPlugin: () => (/* reexport */ BatchingDbPlugin),
3705
3278
  applyInnerOptions: () => (/* reexport */ applyInnerOptions),
3706
- TranslatedSingleValue: () => (/* reexport */ TranslatedSingleValue),
3279
+ MEMORY_EXECUTION_EXPLANATIONS: () => (/* reexport */ MEMORY_EXECUTION_EXPLANATIONS),
3707
3280
  TupleTranslator: () => (/* reexport */ TupleTranslator),
3708
- cosineDistance: () => (/* reexport */ cosineDistance),
3281
+ TranslatedSingleValue: () => (/* reexport */ TranslatedSingleValue),
3709
3282
  ConcurrencyDbPlugin: () => (/* reexport */ ConcurrencyDbPlugin),
3710
3283
  TranslatedGroupValue: () => (/* reexport */ TranslatedGroupValue),
3711
3284
  deserializeBulkPersist: () => (/* reexport */ deserializeBulkPersist),
3285
+ EXECUTED_QUERIES_UNSUPPORTED: () => (/* reexport */ EXECUTED_QUERIES_UNSUPPORTED),
3712
3286
  joinInPlugin: () => (/* reexport */ joinInPlugin),
3713
- readJoinKey: () => (/* reexport */ readJoinKey),
3714
3287
  deserializePersistResult: () => (/* reexport */ deserializePersistResult),
3715
- toEntityShape: () => (/* reexport */ toEntityShape),
3716
- serializeBulkPersist: () => (/* reexport */ serializeBulkPersist),
3288
+ loggerSink: () => (/* reexport */ loggerSink),
3289
+ nearestBy: () => (/* reexport */ nearestBy),
3290
+ readJoinKey: () => (/* reexport */ readJoinKey),
3717
3291
  hashJoin: () => (/* reexport */ hashJoin),
3718
3292
  EphemeralDataPlugin: () => (/* reexport */ EphemeralDataPlugin),
3719
3293
  QueryOptionsCollection: () => (/* reexport */ QueryOptionsCollection/* .QueryOptionsCollection */.H),
3294
+ serializeBulkPersist: () => (/* reexport */ serializeBulkPersist),
3295
+ toEntityShape: () => (/* reexport */ toEntityShape),
3720
3296
  loadJoinInnerSide: () => (/* reexport */ loadJoinInnerSide),
3721
3297
  DataTranslator: () => (/* reexport */ DataTranslator),
3298
+ withExecutedQueries: () => (/* reexport */ withExecutedQueries),
3299
+ TelemetryDbPlugin: () => (/* reexport */ TelemetryDbPlugin),
3722
3300
  createRequestHandler: () => (/* reexport */ createRequestHandler),
3723
3301
  SqlTranslator: () => (/* reexport */ SqlTranslator),
3724
3302
  QueryOrdering: () => (/* reexport */ types_QueryOrdering),
@@ -4260,7 +3838,11 @@ class Query {
4260
3838
  id: `${event.id}-inner`,
4261
3839
  source: event.source,
4262
3840
  action: "query",
4263
- reason: "join inner side"
3841
+ reason: "join inner side",
3842
+ explain: event.explain,
3843
+ // The same array the outer read pushes into, so a join reports BOTH reads in execution
3844
+ // order. Built fresh rather than spread, so this has to be carried explicitly.
3845
+ executedQueries: event.executedQueries
4264
3846
  };
4265
3847
  query(innerEvent, (result)=>{
4266
3848
  if (result.ok === Result/* .PluginEventResult.ERROR */.D.ERROR) {
@@ -4960,6 +4542,386 @@ class SqlTranslator extends DataTranslator {
4960
4542
 
4961
4543
 
4962
4544
 
4545
+ ;// CONCATENATED MODULE: ./src/plugins/query/explain.ts
4546
+
4547
+ /**
4548
+ * One sentence per reason code, written for someone meeting pushdown for the first time.
4549
+ *
4550
+ * Beside the codes rather than in the formatter, so console output, a failing test and the
4551
+ * docs all say the same thing.
4552
+ */ const MEMORY_EXECUTION_EXPLANATIONS = {
4553
+ "not-parsable": "A filter could not be parsed into an expression tree, so it and every option after it run in memory.",
4554
+ "unmapped-property": "The property is not stored in the database, so it can only be read after deserialization.",
4555
+ "renamed-property": "The property is stored under a different name, and selectors use the in-memory name, so it can only be read after deserialization.",
4556
+ "map-rename": "A map renames or drops properties, so every option after it refers to names the database does not have.",
4557
+ "after-nearest": "A similarity search orders and limits rows, and the plugin cannot report whether it performed the search, so every option after it runs in memory.",
4558
+ "after-join": "A join produces [outer, inner] tuples rather than entities, and the plugin cannot report how it joined, so every option after it runs in memory.",
4559
+ "cross-plugin-join": "The two sides of this join live on different plugins, so neither can read the other's rows and the join runs in the datastore."
4560
+ };
4561
+ const EXECUTED_QUERIES_UNSUPPORTED = "This plugin did not report what it executed. It may not support explain.";
4562
+ const DATABASE_STEP_DESCRIPTION = "These options are sent to the plugin.";
4563
+ const MEMORY_STEP_DESCRIPTION = "Routier runs these over the rows the database returned, after deserializing them.";
4564
+ const UNNARROWED_READ_DESCRIPTION = "No option could be pushed down, so the plugin reads the whole collection.";
4565
+ /**
4566
+ * The reportable shape of one option's value.
4567
+ *
4568
+ * Serializable facts only, never the live selector functions — an explanation is a document a
4569
+ * caller may log, diff in a test, or send to a server, and a closure survives none of that.
4570
+ */ const detailOf = (option)=>{
4571
+ if (option.name === "filter") {
4572
+ const value = option.value;
4573
+ if (value.expression == null) {
4574
+ return undefined;
4575
+ }
4576
+ try {
4577
+ return {
4578
+ expression: types/* .Expression.toJson */.r4.toJson(value.expression)
4579
+ };
4580
+ } catch {
4581
+ // `valueToJson` rejects a value no wire can carry. Reporting the rest of the
4582
+ // explanation beats taking the diagnostic down with the query it describes.
4583
+ return {
4584
+ expressionUnavailable: "This filter holds a value that cannot be serialized."
4585
+ };
4586
+ }
4587
+ }
4588
+ if (option.name === "sort") {
4589
+ const value = option.value;
4590
+ return {
4591
+ propertyName: value.propertyName,
4592
+ direction: value.direction
4593
+ };
4594
+ }
4595
+ if (option.name === "skip" || option.name === "take") {
4596
+ return {
4597
+ value: option.value
4598
+ };
4599
+ }
4600
+ if (option.name === "nearest") {
4601
+ const value = option.value;
4602
+ return {
4603
+ propertyName: value.propertyName,
4604
+ dimensions: value.vector.length,
4605
+ count: value.count
4606
+ };
4607
+ }
4608
+ if (option.name === "join") {
4609
+ const value = option.value;
4610
+ return {
4611
+ kind: value.kind,
4612
+ outerKey: value.outerKey.propertyName,
4613
+ innerKey: value.innerKey.propertyName,
4614
+ crossPlugin: value.crossPlugin,
4615
+ innerOptions: explainedOptionsOf(value.innerOptions)
4616
+ };
4617
+ }
4618
+ if (option.name === "map" || option.name === "group") {
4619
+ const value = option.value;
4620
+ return {
4621
+ fields: value.fields.map((x)=>({
4622
+ from: x.sourceName,
4623
+ to: x.destinationName
4624
+ }))
4625
+ };
4626
+ }
4627
+ return undefined;
4628
+ };
4629
+ const explainedOptionOf = (option, index)=>{
4630
+ const detail = detailOf(option);
4631
+ return {
4632
+ index,
4633
+ name: option.name,
4634
+ ...detail == null ? {} : {
4635
+ detail
4636
+ }
4637
+ };
4638
+ };
4639
+ const explainedOptionsOf = (options)=>{
4640
+ const explained = [];
4641
+ let index = 0;
4642
+ options.forEach((option)=>explained.push(explainedOptionOf(option, index++)));
4643
+ return explained;
4644
+ };
4645
+ const summarize = (steps)=>{
4646
+ const reasons = [];
4647
+ let database = 0;
4648
+ let memory = 0;
4649
+ for (const step of steps){
4650
+ if (step.executedIn === "database") {
4651
+ database += step.options.length;
4652
+ continue;
4653
+ }
4654
+ memory += step.options.length;
4655
+ if (step.reason != null && reasons.includes(step.reason) === false) {
4656
+ reasons.push(step.reason);
4657
+ }
4658
+ }
4659
+ const counts = `${database} ${database === 1 ? "option ran" : "options ran"} in the database, ${memory} ran in memory.`;
4660
+ const causes = reasons.map((reason)=>MEMORY_EXECUTION_EXPLANATIONS[reason]).join(" ");
4661
+ return {
4662
+ database,
4663
+ memory,
4664
+ reasons,
4665
+ explanation: causes.length === 0 ? counts : `${counts} ${causes}`
4666
+ };
4667
+ };
4668
+ /**
4669
+ * Groups options into consecutive runs that execute in the same place.
4670
+ *
4671
+ * A step boundary is where execution moves, and a reader has to see the statement as step 1 OF
4672
+ * 2 to understand it is not the whole query. Cutting over to memory is a ratchet, so the
4673
+ * database options are always a prefix and there are at most two steps.
4674
+ *
4675
+ * A database step is emitted even when NO option pushed down, because the plugin is dispatched
4676
+ * either way — `createQueryPayload` always builds a database event. Without it, the worst case
4677
+ * the feature exists to expose reports "0 in the database" while the backend reads the whole
4678
+ * table, which is the opposite of the truth.
4679
+ */ const toExecutionSteps = (options)=>{
4680
+ const steps = [];
4681
+ let index = 0;
4682
+ options.forEach((option)=>{
4683
+ const explained = explainedOptionOf(option, index++);
4684
+ const current = steps[steps.length - 1];
4685
+ if (current != null && current.executedIn === option.target) {
4686
+ current.options.push(explained);
4687
+ return;
4688
+ }
4689
+ steps.push({
4690
+ step: steps.length + 1,
4691
+ of: 0,
4692
+ executedIn: option.target,
4693
+ description: option.target === "database" ? DATABASE_STEP_DESCRIPTION : MEMORY_STEP_DESCRIPTION,
4694
+ options: [
4695
+ explained
4696
+ ],
4697
+ ...option.reason == null ? {} : {
4698
+ reason: option.reason,
4699
+ explanation: MEMORY_EXECUTION_EXPLANATIONS[option.reason]
4700
+ }
4701
+ });
4702
+ });
4703
+ if (steps[0]?.executedIn !== "database") {
4704
+ steps.unshift({
4705
+ step: 0,
4706
+ of: 0,
4707
+ executedIn: "database",
4708
+ description: UNNARROWED_READ_DESCRIPTION,
4709
+ options: []
4710
+ });
4711
+ }
4712
+ for(let i = 0; i < steps.length; i++){
4713
+ steps[i].step = i + 1;
4714
+ steps[i].of = steps.length;
4715
+ }
4716
+ return steps;
4717
+ };
4718
+ /**
4719
+ * Builds the explanation from the resolved options, with no plugin involvement.
4720
+ *
4721
+ * Takes the collection BEFORE `split()`, and throws otherwise. Splitting re-adds each half
4722
+ * into a fresh collection, which re-derives targets without the options that caused them — a
4723
+ * post-join filter alone in the memory half derives back to `"database"`, and the document
4724
+ * would report memory work as having run in the database.
4725
+ */ const explainQuery = (options, context)=>{
4726
+ if (options.isDerived === true) {
4727
+ throw new Error("explainQuery was given a collection produced by split() or splitAt(). Those re-derive " + "execution targets without the options that caused them, so the explanation would report " + "memory work as having run in the database. Pass the collection as it was resolved, " + "before splitting.");
4728
+ }
4729
+ const executionSteps = toExecutionSteps(options);
4730
+ return {
4731
+ collection: context.collection,
4732
+ database: context.database,
4733
+ summary: summarize(executionSteps),
4734
+ executionSteps,
4735
+ plugin: {
4736
+ kind: context.pluginKind
4737
+ }
4738
+ };
4739
+ };
4740
+ /**
4741
+ * Attaches what the backend reported to the step that was sent to it.
4742
+ *
4743
+ * Reporting is optional for a plugin, so an empty report is not an error: the step is marked
4744
+ * `executedQueriesUnsupported` instead, and the rest of the explanation stands — the pushdown
4745
+ * analysis comes from the options and is correct with or without the plugin's statements.
4746
+ *
4747
+ * Copies the steps rather than writing into them, so the explanation a caller already holds
4748
+ * does not gain statements after the fact. Options and their details are shared with the
4749
+ * original — nothing mutates them, and copying deeper would only look safer than it is.
4750
+ */ const withExecutedQueries = (explanation, executedQueries)=>{
4751
+ let attached = false;
4752
+ const executionSteps = explanation.executionSteps.map((step)=>{
4753
+ // Only the first database step: a plugin reports what IT ran, and everything it ran
4754
+ // was sent as one dispatch. Stamping the same statements onto a second database step
4755
+ // would claim they ran twice.
4756
+ if (step.executedIn !== "database" || attached === true) {
4757
+ return {
4758
+ ...step,
4759
+ options: [
4760
+ ...step.options
4761
+ ]
4762
+ };
4763
+ }
4764
+ attached = true;
4765
+ if (executedQueries.length === 0) {
4766
+ return {
4767
+ ...step,
4768
+ options: [
4769
+ ...step.options
4770
+ ],
4771
+ executedQueriesUnsupported: EXECUTED_QUERIES_UNSUPPORTED
4772
+ };
4773
+ }
4774
+ return {
4775
+ ...step,
4776
+ options: [
4777
+ ...step.options
4778
+ ],
4779
+ executedQueries: [
4780
+ ...executedQueries
4781
+ ]
4782
+ };
4783
+ });
4784
+ return {
4785
+ ...explanation,
4786
+ executionSteps
4787
+ };
4788
+ };
4789
+
4790
+ ;// CONCATENATED MODULE: ./src/plugins/query/formatExplanation.ts
4791
+ const OPTION_LABEL_WIDTH = 8;
4792
+ const WRAP_WIDTH = 68;
4793
+ /** Wraps `text` to `WRAP_WIDTH`, prefixing every line with `indent`. */ const wrap = (text, indent)=>{
4794
+ const lines = [];
4795
+ let line = "";
4796
+ for (const word of text.split(" ")){
4797
+ if (line.length > 0 && line.length + word.length + 1 > WRAP_WIDTH) {
4798
+ lines.push(indent + line);
4799
+ line = word;
4800
+ continue;
4801
+ }
4802
+ line = line.length === 0 ? word : `${line} ${word}`;
4803
+ }
4804
+ if (line.length > 0) {
4805
+ lines.push(indent + line);
4806
+ }
4807
+ return lines;
4808
+ };
4809
+ const COMPARATOR_SYMBOLS = {
4810
+ "equals": "===",
4811
+ "greater-than": ">",
4812
+ "greater-than-equals": ">=",
4813
+ "less-than": "<",
4814
+ "less-than-equals": "<="
4815
+ };
4816
+ const describeValue = (value)=>{
4817
+ if (value == null) {
4818
+ return "?";
4819
+ }
4820
+ if (value.k === "raw") {
4821
+ return typeof value.v === "string" ? `"${value.v}"` : String(value.v);
4822
+ }
4823
+ if (value.k === "date") {
4824
+ return value.v;
4825
+ }
4826
+ if (value.k === "array") {
4827
+ return `[${value.v.map(describeValue).join(", ")}]`;
4828
+ }
4829
+ return value.k === "undefined" ? "undefined" : String(value.v);
4830
+ };
4831
+ /** Renders a serialized expression back to something close to the source predicate. */ const describeExpression = (expression)=>{
4832
+ if (expression == null) {
4833
+ return "?";
4834
+ }
4835
+ if (expression.t === "operator") {
4836
+ return `${describeExpression(expression.left)} ${expression.operator} ${describeExpression(expression.right)}`;
4837
+ }
4838
+ if (expression.t === "comparator") {
4839
+ const left = describeExpression(expression.left);
4840
+ const right = describeExpression(expression.right);
4841
+ const symbol = COMPARATOR_SYMBOLS[expression.comparator];
4842
+ if (symbol == null) {
4843
+ return `${left}.${expression.comparator}(${right})${expression.negated === true ? " === false" : ""}`;
4844
+ }
4845
+ return `${left} ${expression.negated === true ? "!==" : symbol} ${right}`;
4846
+ }
4847
+ if (expression.t === "property") {
4848
+ return expression.path;
4849
+ }
4850
+ if (expression.t === "value") {
4851
+ return describeValue(expression.value);
4852
+ }
4853
+ return expression.t === "empty" ? "(no filter)" : "(not parsable)";
4854
+ };
4855
+ const describeOption = (option)=>{
4856
+ const detail = option.detail;
4857
+ if (detail == null) {
4858
+ return "";
4859
+ }
4860
+ if (option.name === "filter") {
4861
+ return detail.expression == null ? String(detail.expressionUnavailable ?? "") : describeExpression(detail.expression);
4862
+ }
4863
+ if (option.name === "sort") {
4864
+ return `${detail.propertyName} ${detail.direction}`;
4865
+ }
4866
+ if (option.name === "skip" || option.name === "take") {
4867
+ return String(detail.value);
4868
+ }
4869
+ if (option.name === "join") {
4870
+ return `${detail.kind} → ${detail.outerKey} = ${detail.innerKey}`;
4871
+ }
4872
+ if (option.name === "nearest") {
4873
+ return `${detail.propertyName}, ${detail.count} nearest`;
4874
+ }
4875
+ if (option.name === "map" || option.name === "group") {
4876
+ const fields = detail.fields;
4877
+ return fields.map((x)=>x.from === x.to ? x.from : `${x.from} → ${x.to}`).join(", ");
4878
+ }
4879
+ return "";
4880
+ };
4881
+ const formatStep = (step, lines)=>{
4882
+ const reason = step.reason == null ? "" : ` [${step.reason}]`;
4883
+ lines.push(` STEP ${step.step} of ${step.of} — ${step.executedIn}${reason}`);
4884
+ lines.push(...wrap(step.description, " "));
4885
+ if (step.explanation != null) {
4886
+ lines.push(...wrap(step.explanation, " "));
4887
+ }
4888
+ lines.push("");
4889
+ for (const option of step.options){
4890
+ lines.push(` ${option.name.padEnd(OPTION_LABEL_WIDTH)} ${describeOption(option)}`.trimEnd());
4891
+ }
4892
+ for (const executed of step.executedQueries ?? []){
4893
+ lines.push("");
4894
+ lines.push(...executed.text.split("\n").map((line)=>` ${line}`));
4895
+ if (executed.parameters != null && executed.parameters.length > 0) {
4896
+ lines.push(` parameters: ${JSON.stringify(executed.parameters)}`);
4897
+ }
4898
+ }
4899
+ if (step.executedQueriesUnsupported != null) {
4900
+ lines.push("");
4901
+ lines.push(...wrap(step.executedQueriesUnsupported, " "));
4902
+ }
4903
+ lines.push("");
4904
+ };
4905
+ /**
4906
+ * Renders an explanation for a terminal.
4907
+ *
4908
+ * The STEP headers carry the whole lesson: a reader who has never heard of pushdown still sees
4909
+ * that the statement in step 1 is not the entire query. Nobody should have to notice a missing
4910
+ * ORDER BY to work that out.
4911
+ */ const formatExplanation = (explanation)=>{
4912
+ const { collection, database, summary, executionSteps } = explanation;
4913
+ const stepCount = `${executionSteps.length} ${executionSteps.length === 1 ? "step" : "steps"}`;
4914
+ const lines = [
4915
+ `${collection} · ${database} · ${stepCount}`,
4916
+ ""
4917
+ ];
4918
+ for (const step of executionSteps){
4919
+ formatStep(step, lines);
4920
+ }
4921
+ lines.push(...wrap(summary.explanation, " "));
4922
+ return lines.join("\n");
4923
+ };
4924
+
4963
4925
  ;// CONCATENATED MODULE: ./src/plugins/query/types.ts
4964
4926
  var types_QueryOrdering = /*#__PURE__*/ function(QueryOrdering) {
4965
4927
  QueryOrdering["Descending"] = "desc";
@@ -4974,6 +4936,8 @@ var types_QueryOrdering = /*#__PURE__*/ function(QueryOrdering) {
4974
4936
 
4975
4937
 
4976
4938
 
4939
+
4940
+
4977
4941
  // EXTERNAL MODULE: ./src/expressions/evaluate.ts
4978
4942
  var evaluate = __webpack_require__(379);
4979
4943
  ;// CONCATENATED MODULE: ./src/plugins/wire/query.ts
@@ -5445,6 +5409,7 @@ const createRequestHandler = (options)=>{
5445
5409
  const queryOptions = deserializeQueryOptions(request.options, schema, resolveSchema, // Applied to the outer collection AND to every collection a join reaches, so a
5446
5410
  // join cannot be used to read around a scope
5447
5411
  (target)=>scopeExpressionFor(target, context, "query"));
5412
+ const executedQueries = [];
5448
5413
  return await new Promise((resolve)=>{
5449
5414
  plugin.query({
5450
5415
  // `false`: nothing here attaches to a change tracker — the tracker lives on
@@ -5453,7 +5418,9 @@ const createRequestHandler = (options)=>{
5453
5418
  schemas: schemas,
5454
5419
  id: (0,uuid/* .uuid */.u)(8),
5455
5420
  source: "RequestHandler",
5456
- action: "query"
5421
+ action: "query",
5422
+ explain: request.explain,
5423
+ executedQueries
5457
5424
  }, (result)=>{
5458
5425
  if (result.ok === Result/* .PluginEventResult.ERROR */.D.ERROR) {
5459
5426
  resolve(failed(result.error));
@@ -5462,7 +5429,13 @@ const createRequestHandler = (options)=>{
5462
5429
  resolve({
5463
5430
  ok: true,
5464
5431
  kind: "query",
5465
- value: result.data.value
5432
+ value: result.data.value,
5433
+ // Only when asked, and only what the plugin reported. A plugin
5434
+ // that reported nothing sends nothing, and the caller marks the
5435
+ // remote step as not reported.
5436
+ ...request.explain === true && executedQueries.length > 0 ? {
5437
+ executedQueries
5438
+ } : {}
5466
5439
  });
5467
5440
  });
5468
5441
  });
@@ -6111,6 +6084,10 @@ class EphemeralDataPlugin {
6111
6084
  }
6112
6085
  innerRows.push(cloneRecord(record));
6113
6086
  }
6087
+ const narrowing = outerKeys == null ? "full scan" : `narrowed by ${outerKeys.size} outer ${outerKeys.size === 1 ? "key" : "keys"}`;
6088
+ event.executedQueries.push({
6089
+ text: `${innerSchema.collectionName}: scanned ${innerRows.length} in-memory ${innerRows.length === 1 ? "record" : "records"} for join inner side (${narrowing})`
6090
+ });
6114
6091
  done({
6115
6092
  ok: "success",
6116
6093
  innerSide: {
@@ -6220,7 +6197,13 @@ class EphemeralDataPlugin {
6220
6197
  * collection to pair it with three rows.
6221
6198
  *
6222
6199
  * `cloned` is in storage shape, so the keys are read by resolved column name.
6223
- */ const joinOption = operation.options.getLast("join");
6200
+ */ // No statement to quote — an ephemeral store walks its own records. Said
6201
+ // plainly so `.explain()` does not leave a reader wondering whether the
6202
+ // plugin simply failed to report. Before the inner side, to match execution order.
6203
+ event.executedQueries.push({
6204
+ text: `${operation.schema.collectionName}: scanned ${cloned.length} in-memory ${cloned.length === 1 ? "record" : "records"}`
6205
+ });
6206
+ const joinOption = operation.options.getLast("join");
6224
6207
  const outerKeys = joinOption == null ? null : distinctJoinKeys(cloned, joinOption.value.outerKey, joinOption.value.semiJoinKeyThreshold, {
6225
6208
  storageShape: true
6226
6209
  });
@@ -6304,6 +6287,69 @@ class RetryDbPlugin {
6304
6287
  }
6305
6288
  }
6306
6289
 
6290
+ ;// CONCATENATED MODULE: ./src/plugins/TelemetryDbPlugin.ts
6291
+
6292
+ /** Default sink: writes through the levelled logger, so ROUTIER_LOG_LEVEL governs it. */ const loggerSink = ()=>(e)=>{
6293
+ const line = `[routier] ${e.operation} ${e.schemas.join(",")} ${e.durationMs.toFixed(1)}ms`;
6294
+ if (e.ok === "error") {
6295
+ logger/* .logger.error */.vF.error(line, e.error);
6296
+ return;
6297
+ }
6298
+ logger/* .logger.info */.vF.info(line);
6299
+ };
6300
+ /** Pushes every event into `into`. For tests and custom buffering. */ const collectingSink = (into)=>(e)=>{
6301
+ into.push(e);
6302
+ };
6303
+ class TelemetryDbPlugin {
6304
+ plugin;
6305
+ onEvent;
6306
+ constructor(plugin, options = {}){
6307
+ this.plugin = plugin;
6308
+ this.onEvent = options.onEvent ?? loggerSink();
6309
+ }
6310
+ get databaseName() {
6311
+ return this.plugin.databaseName;
6312
+ }
6313
+ query(event, done) {
6314
+ const start = performance.now();
6315
+ this.plugin.query(event, (result)=>{
6316
+ this.emit("query", event, result, start);
6317
+ done(result);
6318
+ });
6319
+ }
6320
+ bulkPersist(event, done) {
6321
+ const start = performance.now();
6322
+ this.plugin.bulkPersist(event, (result)=>{
6323
+ this.emit("bulkPersist", event, result, start);
6324
+ done(result);
6325
+ });
6326
+ }
6327
+ destroy(event, done) {
6328
+ const start = performance.now();
6329
+ this.plugin.destroy(event, (result)=>{
6330
+ this.emit("destroy", event, result, start);
6331
+ done(result);
6332
+ });
6333
+ }
6334
+ emit(operation, event, result, start) {
6335
+ try {
6336
+ this.onEvent({
6337
+ operation,
6338
+ eventId: event.id,
6339
+ source: event.source,
6340
+ schemas: [
6341
+ ...event.schemas.values()
6342
+ ].map((s)=>s.collectionName),
6343
+ durationMs: performance.now() - start,
6344
+ ok: result.ok,
6345
+ error: result.ok === "success" ? undefined : result.error
6346
+ });
6347
+ } catch {
6348
+ // A broken sink must never fail the data operation.
6349
+ }
6350
+ }
6351
+ }
6352
+
6307
6353
  ;// CONCATENATED MODULE: ./src/plugins/CacheDbPlugin.ts
6308
6354
 
6309
6355
  /**
@@ -6313,7 +6359,7 @@ class RetryDbPlugin {
6313
6359
  * `PropertyInfo` objects carrying functions and would not survive `JSON.stringify`. A filter is
6314
6360
  * identified by its source text plus its params, which is what the expression is derived from
6315
6361
  * anyway — two queries with the same source and params are the same query.
6316
- */ const describeOption = (option)=>{
6362
+ */ const CacheDbPlugin_describeOption = (option)=>{
6317
6363
  const value = option.value;
6318
6364
  switch(option.name){
6319
6365
  case "filter":
@@ -6347,7 +6393,7 @@ class CacheDbPlugin {
6347
6393
  /** `schemaId` first, so invalidating a schema is a prefix match. */ keyFor(event) {
6348
6394
  const parts = [];
6349
6395
  event.operation.options.forEach((option)=>{
6350
- parts.push(`${option.name}:${describeOption(option)}`);
6396
+ parts.push(`${option.name}:${CacheDbPlugin_describeOption(option)}`);
6351
6397
  });
6352
6398
  return `${String(event.operation.schema.id)}\u0000${parts.join("\u0001")}`;
6353
6399
  }
@@ -6377,6 +6423,12 @@ class CacheDbPlugin {
6377
6423
  // Re-set to move it to the end of the insertion order: most recently used.
6378
6424
  this.entries.delete(key);
6379
6425
  this.entries.set(key, cached);
6426
+ // Said rather than left blank. A hit means no database was touched, which is a fact
6427
+ // worth reporting — and an empty report would otherwise read as a plugin that failed
6428
+ // to say what it ran.
6429
+ event.executedQueries.push({
6430
+ text: "cache hit — no query was executed"
6431
+ });
6380
6432
  done(Result/* .PluginEventResult.success */.D.success(event.id, this.rebuild(cached)));
6381
6433
  return;
6382
6434
  }
@@ -6762,6 +6814,7 @@ const DEFAULT_MAX_BATCH_SIZE = 100;
6762
6814
 
6763
6815
 
6764
6816
 
6817
+
6765
6818
  },
6766
6819
  198(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
6767
6820
  __webpack_require__.d(__webpack_exports__, {
@@ -6774,8 +6827,26 @@ __webpack_require__.d(__webpack_exports__, {
6774
6827
  class QueryOptionsCollection {
6775
6828
  options = new Map();
6776
6829
  nextExecutionTarget = "database";
6830
+ nextExecutionReason = null;
6777
6831
  nextIndex = 0;
6778
6832
  enumeratedItems = [];
6833
+ /** Cuts over to memory execution, keeping the first cause. See `MemoryExecutionReason`. */ cutOverToMemory(reason) {
6834
+ this.nextExecutionTarget = "memory";
6835
+ if (this.nextExecutionReason == null) {
6836
+ this.nextExecutionReason = reason;
6837
+ }
6838
+ }
6839
+ /**
6840
+ * True when `split()` or `splitAt()` produced this collection.
6841
+ *
6842
+ * Those rebuild each half by re-adding its options, which re-derives execution targets
6843
+ * without the options that caused them — a post-join filter alone in the memory half
6844
+ * derives back to `"database"`. Anything reading `target` as a report of where work runs
6845
+ * has to reject a derived collection; see `explainQuery`.
6846
+ */ derived = false;
6847
+ get isDerived() {
6848
+ return this.derived;
6849
+ }
6779
6850
  get items() {
6780
6851
  return this.options;
6781
6852
  }
@@ -6796,7 +6867,7 @@ class QueryOptionsCollection {
6796
6867
  if (mapValue.fields.some((x)=>x.isRename === true) || mapValue.fields.some((x)=>x.property?.isUnmapped === true)) {
6797
6868
  // Cut over to memory execution since we are renaming a property with .map
6798
6869
  // We do not want to figure out how the new name flows through the entire query
6799
- this.nextExecutionTarget = "memory";
6870
+ this.cutOverToMemory("map-rename");
6800
6871
  }
6801
6872
  }
6802
6873
  if (name === "filter") {
@@ -6808,13 +6879,13 @@ class QueryOptionsCollection {
6808
6879
  return;
6809
6880
  }
6810
6881
  if (filterValue.expression.type === "not-parsable") {
6811
- this.nextExecutionTarget = "memory";
6882
+ this.cutOverToMemory("not-parsable");
6812
6883
  } else {
6813
6884
  (0,_expressions_utils__rspack_import_0/* .forEach */.j)(filterValue.expression, (expression)=>{
6814
6885
  if ((0,_assertions__rspack_import_1.isPropertyExpression)(expression) && expression.property.isUnmapped) {
6815
6886
  // Cut over to memory execution, unmapped properties are not in the database and
6816
6887
  // cannot be queried
6817
- this.nextExecutionTarget = "memory";
6888
+ this.cutOverToMemory("unmapped-property");
6818
6889
  return false;
6819
6890
  }
6820
6891
  if ((0,_assertions__rspack_import_1.isPropertyExpression)(expression) && expression.property.hasRenamedSegments) {
@@ -6822,7 +6893,7 @@ class QueryOptionsCollection {
6822
6893
  // `from` (storage) names, but filter selectors reference the
6823
6894
  // in-memory names. Memory execution runs after deserialization,
6824
6895
  // where the in-memory names exist
6825
- this.nextExecutionTarget = "memory";
6896
+ this.cutOverToMemory("renamed-property");
6826
6897
  return false;
6827
6898
  }
6828
6899
  return true;
@@ -6833,8 +6904,10 @@ class QueryOptionsCollection {
6833
6904
  const sortValue = value;
6834
6905
  // Same rule as filters: sort selectors reference in-memory names, which
6835
6906
  // only exist after deserialization when the property is renamed or unmapped
6836
- if (sortValue.property != null && (sortValue.property.isUnmapped || sortValue.property.hasRenamedSegments)) {
6837
- this.nextExecutionTarget = "memory";
6907
+ if (sortValue.property != null && sortValue.property.isUnmapped) {
6908
+ this.cutOverToMemory("unmapped-property");
6909
+ } else if (sortValue.property != null && sortValue.property.hasRenamedSegments) {
6910
+ this.cutOverToMemory("renamed-property");
6838
6911
  }
6839
6912
  }
6840
6913
  if (name === "nearest") {
@@ -6845,8 +6918,10 @@ class QueryOptionsCollection {
6845
6918
  //
6846
6919
  // This is also what lets every translator's in-memory fallback read the column by
6847
6920
  // its resolved name — anything whose storage name differs never reaches them.
6848
- if (nearestValue.property != null && (nearestValue.property.isUnmapped || nearestValue.property.hasRenamedSegments)) {
6849
- this.nextExecutionTarget = "memory";
6921
+ if (nearestValue.property != null && nearestValue.property.isUnmapped) {
6922
+ this.cutOverToMemory("unmapped-property");
6923
+ } else if (nearestValue.property != null && nearestValue.property.hasRenamedSegments) {
6924
+ this.cutOverToMemory("renamed-property");
6850
6925
  }
6851
6926
  }
6852
6927
  if (name === "join") {
@@ -6858,7 +6933,7 @@ class QueryOptionsCollection {
6858
6933
  // Set BEFORE the item is created, unlike `nearest`'s ratchet below, because this
6859
6934
  // moves the join option itself rather than everything after it.
6860
6935
  if (joinValue.crossPlugin === true) {
6861
- this.nextExecutionTarget = "memory";
6936
+ this.cutOverToMemory("cross-plugin-join");
6862
6937
  }
6863
6938
  }
6864
6939
  const item = {
@@ -6866,7 +6941,10 @@ class QueryOptionsCollection {
6866
6941
  option: {
6867
6942
  name,
6868
6943
  target: this.nextExecutionTarget,
6869
- value
6944
+ value,
6945
+ ...this.nextExecutionReason == null ? {} : {
6946
+ reason: this.nextExecutionReason
6947
+ }
6870
6948
  }
6871
6949
  };
6872
6950
  this.nextIndex++;
@@ -6889,7 +6967,7 @@ class QueryOptionsCollection {
6889
6967
  //
6890
6968
  // A plugin that DID push the search down loses nothing but the chance to also
6891
6969
  // push down what follows it, which is a limit over ten rows.
6892
- this.nextExecutionTarget = "memory";
6970
+ this.cutOverToMemory("after-nearest");
6893
6971
  }
6894
6972
  if (name === "join") {
6895
6973
  // Everything AFTER a join runs in memory, for the same reason as `nearest`: this
@@ -6900,7 +6978,7 @@ class QueryOptionsCollection {
6900
6978
  // OUTER rows read, not the pairs produced — a plausible-looking result with the
6901
6979
  // wrong number of rows in it. Conjuncts that can safely run earlier are split off
6902
6980
  // by the query builder BEFORE dispatch, which is the only exception.
6903
- this.nextExecutionTarget = "memory";
6981
+ this.cutOverToMemory("after-join");
6904
6982
  }
6905
6983
  }
6906
6984
  /**
@@ -6914,6 +6992,8 @@ class QueryOptionsCollection {
6914
6992
  const sortedItems = this.enumeratedItems.toSorted((a, b)=>a.index - b.index);
6915
6993
  const before = new QueryOptionsCollection();
6916
6994
  const after = new QueryOptionsCollection();
6995
+ before.derived = true;
6996
+ after.derived = true;
6917
6997
  let at = null;
6918
6998
  for(let i = 0, length = sortedItems.length; i < length; i++){
6919
6999
  const { option } = sortedItems[i];
@@ -6947,10 +7027,12 @@ class QueryOptionsCollection {
6947
7027
  ]
6948
7028
  ]));
6949
7029
  const nextExecutionTarget = this.nextExecutionTarget;
7030
+ const nextExecutionReason = this.nextExecutionReason;
6950
7031
  const nextIndex = this.nextIndex;
6951
7032
  return ()=>{
6952
7033
  this.options = new Map(options);
6953
7034
  this.nextExecutionTarget = nextExecutionTarget;
7035
+ this.nextExecutionReason = nextExecutionReason;
6954
7036
  this.nextIndex = nextIndex;
6955
7037
  this.enumeratedItems = [];
6956
7038
  };
@@ -6960,6 +7042,8 @@ class QueryOptionsCollection {
6960
7042
  const sortedItems = this.enumeratedItems.toSorted((a, b)=>a.index - b.index);
6961
7043
  const memoryQueryOptionsCollection = new QueryOptionsCollection();
6962
7044
  const databaseQueryOptionsCollection = new QueryOptionsCollection();
7045
+ memoryQueryOptionsCollection.derived = true;
7046
+ databaseQueryOptionsCollection.derived = true;
6963
7047
  for(let i = 0, length = sortedItems.length; i < length; i++){
6964
7048
  const sortedItem = sortedItems[i];
6965
7049
  if (sortedItem.option.target === "database") {
@@ -13736,13 +13820,13 @@ __webpack_require__.d(__webpack_exports__, {
13736
13820
  BulkPersistChanges: () => (/* reexport safe */ _collections__rspack_import_2.BulkPersistChanges),
13737
13821
  BulkPersistResult: () => (/* reexport safe */ _collections__rspack_import_2.BulkPersistResult),
13738
13822
  CacheDbPlugin: () => (/* reexport safe */ _plugins__rspack_import_7.CacheDbPlugin),
13739
- Capability: () => (/* reexport safe */ _capabilities__rspack_import_11.Capability),
13740
13823
  CodeBuilder: () => (/* reexport safe */ _codegen__rspack_import_1.CodeBuilder),
13741
13824
  ComparatorExpression: () => (/* reexport safe */ _expressions__rspack_import_4.ComparatorExpression),
13742
13825
  ConcurrencyDbPlugin: () => (/* reexport safe */ _plugins__rspack_import_7.ConcurrencyDbPlugin),
13743
13826
  ContainerBlock: () => (/* reexport safe */ _codegen__rspack_import_1.ContainerBlock),
13744
13827
  DEFAULT_SEMI_JOIN_KEY_THRESHOLD: () => (/* reexport safe */ _plugins__rspack_import_7.DEFAULT_SEMI_JOIN_KEY_THRESHOLD),
13745
13828
  DataTranslator: () => (/* reexport safe */ _plugins__rspack_import_7.DataTranslator),
13829
+ EXECUTED_QUERIES_UNSUPPORTED: () => (/* reexport safe */ _plugins__rspack_import_7.EXECUTED_QUERIES_UNSUPPORTED),
13746
13830
  EXPRESSION_TYPES: () => (/* reexport safe */ _expressions__rspack_import_4.EXPRESSION_TYPES),
13747
13831
  EmptyExpression: () => (/* reexport safe */ _expressions__rspack_import_4.EmptyExpression),
13748
13832
  EphemeralDataPlugin: () => (/* reexport safe */ _plugins__rspack_import_7.EphemeralDataPlugin),
@@ -13754,12 +13838,12 @@ __webpack_require__.d(__webpack_exports__, {
13754
13838
  IfBuilder: () => (/* reexport safe */ _codegen__rspack_import_1.IfBuilder),
13755
13839
  JsonTranslator: () => (/* reexport safe */ _plugins__rspack_import_7.JsonTranslator),
13756
13840
  LOG_LEVELS: () => (/* reexport safe */ _utilities__rspack_import_10.LOG_LEVELS),
13841
+ MEMORY_EXECUTION_EXPLANATIONS: () => (/* reexport safe */ _plugins__rspack_import_7.MEMORY_EXECUTION_EXPLANATIONS),
13757
13842
  MemoryDataCollection: () => (/* reexport safe */ _collections__rspack_import_2.MemoryDataCollection),
13758
13843
  NotParsableExpression: () => (/* reexport safe */ _expressions__rspack_import_4.NotParsableExpression),
13759
13844
  ObjectBuilder: () => (/* reexport safe */ _codegen__rspack_import_1.ObjectBuilder),
13760
13845
  OperatorExpression: () => (/* reexport safe */ _expressions__rspack_import_4.OperatorExpression),
13761
13846
  OptimisticConcurrencyError: () => (/* reexport safe */ _errors__rspack_import_3.OptimisticConcurrencyError),
13762
- PerformanceCapability: () => (/* reexport safe */ _capabilities__rspack_import_11.PerformanceCapability),
13763
13847
  PluginDestroyedError: () => (/* reexport safe */ _errors__rspack_import_3.PluginDestroyedError),
13764
13848
  PluginEventResult: () => (/* reexport safe */ _results__rspack_import_8.PluginEventResult),
13765
13849
  PropertyExpression: () => (/* reexport safe */ _expressions__rspack_import_4.PropertyExpression),
@@ -13809,7 +13893,7 @@ __webpack_require__.d(__webpack_exports__, {
13809
13893
  StringBuilder: () => (/* reexport safe */ _codegen__rspack_import_1.StringBuilder),
13810
13894
  SyncronousQueue: () => (/* reexport safe */ _pipeline__rspack_import_6.SyncronousQueue),
13811
13895
  TagCollection: () => (/* reexport safe */ _collections__rspack_import_2.TagCollection),
13812
- TracingCapability: () => (/* reexport safe */ _capabilities__rspack_import_11.TracingCapability),
13896
+ TelemetryDbPlugin: () => (/* reexport safe */ _plugins__rspack_import_7.TelemetryDbPlugin),
13813
13897
  TrampolinePipeline: () => (/* reexport safe */ _pipeline__rspack_import_6.TrampolinePipeline),
13814
13898
  TranslatedArrayValue: () => (/* reexport safe */ _plugins__rspack_import_7.TranslatedArrayValue),
13815
13899
  TranslatedGroupValue: () => (/* reexport safe */ _plugins__rspack_import_7.TranslatedGroupValue),
@@ -13827,6 +13911,7 @@ __webpack_require__.d(__webpack_exports__, {
13827
13911
  assertString: () => (/* reexport safe */ _assertions__rspack_import_0.assertString),
13828
13912
  cast: () => (/* reexport safe */ _utilities__rspack_import_10.cast),
13829
13913
  clone: () => (/* reexport safe */ _utilities__rspack_import_10.clone),
13914
+ collectingSink: () => (/* reexport safe */ _plugins__rspack_import_7.collectingSink),
13830
13915
  combineExpressions: () => (/* reexport safe */ _expressions__rspack_import_4.combineExpressions),
13831
13916
  combineQueryOptionsCollections: () => (/* reexport safe */ _utilities__rspack_import_10.combineQueryOptionsCollections),
13832
13917
  compiledSchemaToJsonSchema: () => (/* reexport safe */ _schema__rspack_import_9.compiledSchemaToJsonSchema),
@@ -13839,9 +13924,11 @@ __webpack_require__.d(__webpack_exports__, {
13839
13924
  distinctJoinKeys: () => (/* reexport safe */ _plugins__rspack_import_7.distinctJoinKeys),
13840
13925
  evaluate: () => (/* reexport safe */ _expressions__rspack_import_4.evaluate),
13841
13926
  executeJoin: () => (/* reexport safe */ _plugins__rspack_import_7.executeJoin),
13927
+ explainQuery: () => (/* reexport safe */ _plugins__rspack_import_7.explainQuery),
13842
13928
  extractTypeInfo: () => (/* reexport safe */ _schema__rspack_import_9.extractTypeInfo),
13843
13929
  fastHash: () => (/* reexport safe */ _utilities__rspack_import_10.fastHash),
13844
13930
  forEach: () => (/* reexport safe */ _expressions__rspack_import_4.forEach),
13931
+ formatExplanation: () => (/* reexport safe */ _plugins__rspack_import_7.formatExplanation),
13845
13932
  getLogLevel: () => (/* reexport safe */ _utilities__rspack_import_10.getLogLevel),
13846
13933
  getProperties: () => (/* reexport safe */ _expressions__rspack_import_4.getProperties),
13847
13934
  hasPrimitiveElements: () => (/* reexport safe */ _schema__rspack_import_9.hasPrimitiveElements),
@@ -13861,6 +13948,7 @@ __webpack_require__.d(__webpack_exports__, {
13861
13948
  joinInPlugin: () => (/* reexport safe */ _plugins__rspack_import_7.joinInPlugin),
13862
13949
  loadJoinInnerSide: () => (/* reexport safe */ _plugins__rspack_import_7.loadJoinInnerSide),
13863
13950
  logger: () => (/* reexport safe */ _utilities__rspack_import_10.logger),
13951
+ loggerSink: () => (/* reexport safe */ _plugins__rspack_import_7.loggerSink),
13864
13952
  measure: () => (/* reexport safe */ _performance__rspack_import_5.measure),
13865
13953
  nearestBy: () => (/* reexport safe */ _plugins__rspack_import_7.nearestBy),
13866
13954
  noop: () => (/* reexport safe */ _utilities__rspack_import_10.noop),
@@ -13889,7 +13977,8 @@ __webpack_require__.d(__webpack_exports__, {
13889
13977
  toStrictPredicate: () => (/* reexport safe */ _expressions__rspack_import_4.toStrictPredicate),
13890
13978
  unsafeCast: () => (/* reexport safe */ _utilities__rspack_import_10.unsafeCast),
13891
13979
  uuid: () => (/* reexport safe */ _utilities__rspack_import_10.uuid),
13892
- uuidv4: () => (/* reexport safe */ _utilities__rspack_import_10.uuidv4)
13980
+ uuidv4: () => (/* reexport safe */ _utilities__rspack_import_10.uuidv4),
13981
+ withExecutedQueries: () => (/* reexport safe */ _plugins__rspack_import_7.withExecutedQueries)
13893
13982
  });
13894
13983
  /* import */ var _assertions__rspack_import_0 = __webpack_require__(126);
13895
13984
  /* import */ var _codegen__rspack_import_1 = __webpack_require__(80);
@@ -13898,12 +13987,10 @@ __webpack_require__.d(__webpack_exports__, {
13898
13987
  /* import */ var _expressions__rspack_import_4 = __webpack_require__(138);
13899
13988
  /* import */ var _performance__rspack_import_5 = __webpack_require__(971);
13900
13989
  /* import */ var _pipeline__rspack_import_6 = __webpack_require__(314);
13901
- /* import */ var _plugins__rspack_import_7 = __webpack_require__(771);
13990
+ /* import */ var _plugins__rspack_import_7 = __webpack_require__(454);
13902
13991
  /* import */ var _results__rspack_import_8 = __webpack_require__(264);
13903
13992
  /* import */ var _schema__rspack_import_9 = __webpack_require__(755);
13904
13993
  /* import */ var _utilities__rspack_import_10 = __webpack_require__(222);
13905
- /* import */ var _capabilities__rspack_import_11 = __webpack_require__(599);
13906
-
13907
13994
 
13908
13995
 
13909
13996