@objectstack/service-analytics 4.0.4 → 4.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/index.d.ts CHANGED
@@ -133,6 +133,32 @@ declare class AnalyticsService implements IAnalyticsService {
133
133
  sql: string;
134
134
  params: unknown[];
135
135
  }>;
136
+ /**
137
+ * Normalise a query into a canonical shape that strategies can rely on:
138
+ *
139
+ * 1. **Filters as object** — Some clients (e.g. dashboard widget translators)
140
+ * send `filters` as a Mongo-style object `{ stage: { $nin: [...] } }`
141
+ * instead of the schema's `Array<{ member, operator, values }>`. We
142
+ * translate the object form into the array form so existing strategies
143
+ * work unchanged.
144
+ * 2. Other shapes are returned as-is.
145
+ */
146
+ private normalizeQuery;
147
+ /**
148
+ * Ensure a cube exists for the given query and that it knows about every
149
+ * measure referenced by the query.
150
+ *
151
+ * - If no cube is registered for `query.cube`, infer a minimal cube from
152
+ * the query so downstream strategies (which assume `cube.sql` exists)
153
+ * don't crash.
154
+ * - If a cube exists but the query references measures that aren't in
155
+ * `cube.measures` (e.g. `amount_sum`, `amount_avg` emitted by dashboard
156
+ * widget translators), inject suffix-inferred Metric entries so the
157
+ * strategies pick the right aggregation function and field.
158
+ */
159
+ private ensureCube;
160
+ /** Build a minimal Cube from the fields referenced by an AnalyticsQuery. */
161
+ private inferCubeFromQuery;
136
162
  /**
137
163
  * Walk the strategy chain and return the first strategy that can handle the query.
138
164
  */
package/dist/index.js CHANGED
@@ -245,6 +245,14 @@ var NativeSQLStrategy = class {
245
245
  };
246
246
  if (operator === "set") return `${col} IS NOT NULL`;
247
247
  if (operator === "notSet") return `${col} IS NULL`;
248
+ if (operator === "in" || operator === "notIn") {
249
+ if (!values || values.length === 0) return null;
250
+ const placeholders = values.map((v) => {
251
+ params.push(v);
252
+ return `$${params.length}`;
253
+ }).join(", ");
254
+ return `${col} ${operator === "in" ? "IN" : "NOT IN"} (${placeholders})`;
255
+ }
248
256
  const sqlOp = opMap[operator];
249
257
  if (!sqlOp || !values || values.length === 0) return null;
250
258
  if (operator === "contains" || operator === "notContains") {
@@ -375,12 +383,28 @@ var ObjectQLStrategy = class {
375
383
  }
376
384
  resolveMeasureAggregation(cube, measureName) {
377
385
  const fieldName = measureName.includes(".") ? measureName.split(".")[1] : measureName;
378
- const measure = cube.measures[fieldName];
379
- if (!measure) return { field: "*", method: "count" };
380
- return {
381
- field: measure.sql.replace(/^\$/, ""),
382
- method: measure.type === "count_distinct" ? "count_distinct" : measure.type
383
- };
386
+ const direct = cube.measures[fieldName];
387
+ if (direct) {
388
+ return {
389
+ field: direct.sql.replace(/^\$/, ""),
390
+ method: direct.type === "count_distinct" ? "count_distinct" : direct.type
391
+ };
392
+ }
393
+ const aggTypes = ["count", "sum", "avg", "min", "max", "count_distinct"];
394
+ for (const type of aggTypes) {
395
+ const suffix = `_${type}`;
396
+ if (fieldName.endsWith(suffix)) {
397
+ const baseField = fieldName.slice(0, -suffix.length);
398
+ const candidate = cube.measures[baseField];
399
+ if (candidate && candidate.type === type) {
400
+ return {
401
+ field: candidate.sql.replace(/^\$/, ""),
402
+ method: candidate.type === "count_distinct" ? "count_distinct" : candidate.type
403
+ };
404
+ }
405
+ }
406
+ }
407
+ return { field: "*", method: "count" };
384
408
  }
385
409
  convertFilter(operator, values) {
386
410
  if (operator === "set") return { $ne: null };
@@ -401,6 +425,10 @@ var ObjectQLStrategy = class {
401
425
  return { $lte: values[0] };
402
426
  case "contains":
403
427
  return { $regex: values[0] };
428
+ case "in":
429
+ return { $in: values };
430
+ case "notIn":
431
+ return { $nin: values };
404
432
  default:
405
433
  return values[0];
406
434
  }
@@ -466,9 +494,11 @@ var AnalyticsService = class {
466
494
  if (!query.cube) {
467
495
  throw new Error("Cube name is required in analytics query");
468
496
  }
469
- const strategy = this.resolveStrategy(query);
470
- this.logger.debug(`[Analytics] Query on cube "${query.cube}" \u2192 ${strategy.name}`);
471
- return strategy.execute(query, this.strategyCtx);
497
+ const normalized = this.normalizeQuery(query);
498
+ this.ensureCube(normalized);
499
+ const strategy = this.resolveStrategy(normalized);
500
+ this.logger.debug(`[Analytics] Query on cube "${normalized.cube}" \u2192 ${strategy.name}`);
501
+ return strategy.execute(normalized, this.strategyCtx);
472
502
  }
473
503
  /**
474
504
  * Get cube metadata for discovery.
@@ -497,11 +527,133 @@ var AnalyticsService = class {
497
527
  if (!query.cube) {
498
528
  throw new Error("Cube name is required for SQL generation");
499
529
  }
500
- const strategy = this.resolveStrategy(query);
501
- this.logger.debug(`[Analytics] generateSql on cube "${query.cube}" \u2192 ${strategy.name}`);
502
- return strategy.generateSql(query, this.strategyCtx);
530
+ const normalized = this.normalizeQuery(query);
531
+ this.ensureCube(normalized);
532
+ const strategy = this.resolveStrategy(normalized);
533
+ this.logger.debug(`[Analytics] generateSql on cube "${normalized.cube}" \u2192 ${strategy.name}`);
534
+ return strategy.generateSql(normalized, this.strategyCtx);
503
535
  }
504
536
  // ── Internal ─────────────────────────────────────────────────────
537
+ /**
538
+ * Normalise a query into a canonical shape that strategies can rely on:
539
+ *
540
+ * 1. **Filters as object** — Some clients (e.g. dashboard widget translators)
541
+ * send `filters` as a Mongo-style object `{ stage: { $nin: [...] } }`
542
+ * instead of the schema's `Array<{ member, operator, values }>`. We
543
+ * translate the object form into the array form so existing strategies
544
+ * work unchanged.
545
+ * 2. Other shapes are returned as-is.
546
+ */
547
+ normalizeQuery(query) {
548
+ const filters = query.filters;
549
+ if (!filters || Array.isArray(filters)) return query;
550
+ if (typeof filters !== "object") return query;
551
+ const arr = [];
552
+ for (const [member, raw] of Object.entries(filters)) {
553
+ if (raw && typeof raw === "object" && !Array.isArray(raw) && !(raw instanceof Date)) {
554
+ for (const [op, val] of Object.entries(raw)) {
555
+ const mapped = mongoOperatorToFilter(op, val);
556
+ if (!mapped) continue;
557
+ if (mapped.multi) {
558
+ arr.push({ member, operator: mapped.operator, values: mapped.values });
559
+ } else if (mapped.values.length === 0) {
560
+ arr.push({ member, operator: mapped.operator, values: [] });
561
+ } else {
562
+ for (const v of mapped.values) arr.push({ member, operator: mapped.operator, values: [v] });
563
+ }
564
+ }
565
+ } else if (Array.isArray(raw)) {
566
+ arr.push({ member, operator: "in", values: raw.map(String) });
567
+ } else {
568
+ arr.push({ member, operator: "equals", values: [String(raw)] });
569
+ }
570
+ }
571
+ return { ...query, filters: arr };
572
+ }
573
+ /**
574
+ * Ensure a cube exists for the given query and that it knows about every
575
+ * measure referenced by the query.
576
+ *
577
+ * - If no cube is registered for `query.cube`, infer a minimal cube from
578
+ * the query so downstream strategies (which assume `cube.sql` exists)
579
+ * don't crash.
580
+ * - If a cube exists but the query references measures that aren't in
581
+ * `cube.measures` (e.g. `amount_sum`, `amount_avg` emitted by dashboard
582
+ * widget translators), inject suffix-inferred Metric entries so the
583
+ * strategies pick the right aggregation function and field.
584
+ */
585
+ ensureCube(query) {
586
+ const name = query.cube;
587
+ let cube = this.cubeRegistry.get(name);
588
+ if (!cube) {
589
+ cube = this.inferCubeFromQuery(query);
590
+ this.cubeRegistry.register(cube);
591
+ this.logger.warn(
592
+ `[Analytics] No cube registered for "${name}"; auto-inferred a minimal cube (sql="${name}", measures=${Object.keys(cube.measures).join(",") || "(none)"}, dimensions=${Object.keys(cube.dimensions).join(",") || "(none)"}). Define an explicit Cube in your stack for full control.`
593
+ );
594
+ return;
595
+ }
596
+ const stripPrefix = (m) => m.includes(".") ? m.split(".").slice(1).join(".") : m;
597
+ const extraMeasures = {};
598
+ for (const m of query.measures || []) {
599
+ const key = stripPrefix(m);
600
+ if (cube.measures[key] || extraMeasures[key]) continue;
601
+ extraMeasures[key] = inferMeasure(key);
602
+ }
603
+ if (Object.keys(extraMeasures).length > 0) {
604
+ const augmented = {
605
+ ...cube,
606
+ measures: { ...cube.measures, ...extraMeasures }
607
+ };
608
+ this.cubeRegistry.register(augmented);
609
+ this.logger.debug(
610
+ `[Analytics] Augmented cube "${name}" with inferred measures: ${Object.keys(extraMeasures).join(",")}`
611
+ );
612
+ }
613
+ }
614
+ /** Build a minimal Cube from the fields referenced by an AnalyticsQuery. */
615
+ inferCubeFromQuery(query) {
616
+ const cubeName = query.cube;
617
+ const measures = {};
618
+ const dimensions = {};
619
+ const stripPrefix = (m) => m.includes(".") ? m.split(".").slice(1).join(".") : m;
620
+ measures.count = { name: "count", label: "Count", type: "count", sql: "*" };
621
+ for (const m of query.measures || []) {
622
+ const key = stripPrefix(m);
623
+ if (measures[key]) continue;
624
+ const inferred = inferMeasure(key);
625
+ measures[key] = inferred;
626
+ }
627
+ for (const d of query.dimensions || []) {
628
+ const key = stripPrefix(d);
629
+ if (dimensions[key]) continue;
630
+ dimensions[key] = { name: key, label: key, type: "string", sql: key };
631
+ }
632
+ for (const f of query.filters || []) {
633
+ const key = stripPrefix(f.member);
634
+ if (dimensions[key] || measures[key]) continue;
635
+ dimensions[key] = { name: key, label: key, type: "string", sql: key };
636
+ }
637
+ for (const td of query.timeDimensions || []) {
638
+ const key = stripPrefix(td.dimension);
639
+ if (dimensions[key]) continue;
640
+ dimensions[key] = {
641
+ name: key,
642
+ label: key,
643
+ type: "time",
644
+ sql: key,
645
+ granularities: ["day", "week", "month", "quarter", "year"]
646
+ };
647
+ }
648
+ return {
649
+ name: cubeName,
650
+ title: cubeName,
651
+ sql: cubeName,
652
+ measures,
653
+ dimensions,
654
+ public: false
655
+ };
656
+ }
505
657
  /**
506
658
  * Walk the strategy chain and return the first strategy that can handle the query.
507
659
  */
@@ -516,6 +668,53 @@ var AnalyticsService = class {
516
668
  );
517
669
  }
518
670
  };
671
+ function inferMeasure(key) {
672
+ if (key === "count") {
673
+ return { name: "count", label: "Count", type: "count", sql: "*" };
674
+ }
675
+ const suffixes = [
676
+ ["_count_distinct", "count_distinct"],
677
+ ["_sum", "sum"],
678
+ ["_avg", "avg"],
679
+ ["_average", "avg"],
680
+ ["_min", "min"],
681
+ ["_max", "max"]
682
+ ];
683
+ for (const [suffix, type] of suffixes) {
684
+ if (key.endsWith(suffix)) {
685
+ const field = key.slice(0, -suffix.length) || "*";
686
+ return { name: key, label: key, type, sql: field };
687
+ }
688
+ }
689
+ return { name: key, label: key, type: "sum", sql: key };
690
+ }
691
+ function mongoOperatorToFilter(op, val) {
692
+ const toStrArr = (v) => v == null ? [] : Array.isArray(v) ? v.map(String) : [String(v)];
693
+ switch (op) {
694
+ case "$eq":
695
+ return { operator: "equals", values: toStrArr(val) };
696
+ case "$ne":
697
+ return { operator: "notEquals", values: toStrArr(val) };
698
+ case "$gt":
699
+ return { operator: "gt", values: toStrArr(val) };
700
+ case "$gte":
701
+ return { operator: "gte", values: toStrArr(val) };
702
+ case "$lt":
703
+ return { operator: "lt", values: toStrArr(val) };
704
+ case "$lte":
705
+ return { operator: "lte", values: toStrArr(val) };
706
+ case "$in":
707
+ return { operator: "in", values: toStrArr(val), multi: true };
708
+ case "$nin":
709
+ return { operator: "notIn", values: toStrArr(val), multi: true };
710
+ case "$regex":
711
+ return { operator: "contains", values: toStrArr(val) };
712
+ case "$exists":
713
+ return val ? { operator: "set", values: [] } : { operator: "notSet", values: [] };
714
+ default:
715
+ return null;
716
+ }
717
+ }
519
718
  var FallbackDelegateStrategy = class {
520
719
  constructor() {
521
720
  this.name = "FallbackDelegateStrategy";
@@ -558,14 +757,58 @@ var AnalyticsServicePlugin = class {
558
757
  }
559
758
  } catch {
560
759
  }
760
+ let executeAggregate = this.options.executeAggregate;
761
+ let autoBridged = false;
762
+ if (!executeAggregate) {
763
+ const tryGetDataEngine = () => {
764
+ try {
765
+ const svc = ctx.getService("data");
766
+ return svc && typeof svc.aggregate === "function" ? svc : void 0;
767
+ } catch {
768
+ return void 0;
769
+ }
770
+ };
771
+ if (!tryGetDataEngine()) {
772
+ ctx.logger.warn(
773
+ '[Analytics] No "data" service registered yet at init; will retry per-query. Register ObjectQLPlugin or pass executeAggregate.'
774
+ );
775
+ }
776
+ executeAggregate = async (objectName, { groupBy, aggregations, filter }) => {
777
+ const engine = tryGetDataEngine();
778
+ if (!engine) {
779
+ throw new Error(
780
+ '[Analytics] Cannot execute aggregate: no IDataEngine ("data") service is registered. Add ObjectQLPlugin to the kernel or supply AnalyticsServicePlugin({ executeAggregate }).'
781
+ );
782
+ }
783
+ const rows = await engine.aggregate(objectName, {
784
+ where: filter,
785
+ groupBy,
786
+ aggregations: aggregations?.map((a) => ({
787
+ function: a.method,
788
+ field: a.field,
789
+ alias: a.alias
790
+ }))
791
+ });
792
+ return rows;
793
+ };
794
+ autoBridged = true;
795
+ }
796
+ const queryCapabilities = this.options.queryCapabilities ?? (() => ({
797
+ nativeSql: !!this.options.executeRawSql,
798
+ objectqlAggregate: !!executeAggregate,
799
+ inMemory: false
800
+ }));
561
801
  const config = {
562
802
  cubes: this.options.cubes,
563
803
  logger: ctx.logger,
564
- queryCapabilities: this.options.queryCapabilities,
804
+ queryCapabilities,
565
805
  executeRawSql: this.options.executeRawSql,
566
- executeAggregate: this.options.executeAggregate,
806
+ executeAggregate,
567
807
  fallbackService
568
808
  };
809
+ if (autoBridged) {
810
+ ctx.logger.info('[Analytics] Auto-bridged executeAggregate \u2192 "data" service (IDataEngine)');
811
+ }
569
812
  this.service = new AnalyticsService(config);
570
813
  if (fallbackService) {
571
814
  ctx.replaceService("analytics", this.service);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/analytics-service.ts","../src/cube-registry.ts","../src/strategies/native-sql-strategy.ts","../src/strategies/objectql-strategy.ts","../src/plugin.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IAnalyticsService,\n AnalyticsQuery,\n AnalyticsResult,\n CubeMeta,\n} from '@objectstack/spec/contracts';\nimport type { Cube } from '@objectstack/spec/data';\nimport type { Logger } from '@objectstack/spec/contracts';\nimport { createLogger } from '@objectstack/core';\nimport { CubeRegistry } from './cube-registry.js';\nimport type { AnalyticsStrategy, DriverCapabilities, StrategyContext } from './strategies/types.js';\nimport { NativeSQLStrategy } from './strategies/native-sql-strategy.js';\nimport { ObjectQLStrategy } from './strategies/objectql-strategy.js';\n\n/**\n * Configuration for AnalyticsService.\n */\nexport interface AnalyticsServiceConfig {\n /** Pre-defined cube definitions (from manifest). */\n cubes?: Cube[];\n /** Logger instance. */\n logger?: Logger;\n /**\n * Probe driver capabilities for the object that backs a cube.\n * The service calls this function to decide which strategy can handle a query.\n */\n queryCapabilities?: (cubeName: string) => DriverCapabilities;\n /**\n * Execute raw SQL on the driver for a given object.\n * Required for NativeSQLStrategy.\n */\n executeRawSql?: (objectName: string, sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>;\n /**\n * Execute an ObjectQL aggregate query.\n * Required for ObjectQLStrategy.\n */\n executeAggregate?: (objectName: string, options: {\n groupBy?: string[];\n aggregations?: Array<{ field: string; method: string; alias: string }>;\n filter?: Record<string, unknown>;\n }) => Promise<Record<string, unknown>[]>;\n /**\n * Fallback IAnalyticsService (e.g. MemoryAnalyticsService).\n * Used by InMemoryStrategy.\n */\n fallbackService?: IAnalyticsService;\n /**\n * Custom strategies to add/replace the defaults.\n * They are merged with the built-in strategies and sorted by priority.\n */\n strategies?: AnalyticsStrategy[];\n}\n\n/**\n * Default capabilities when probing is not configured — assumes in-memory only.\n */\nconst DEFAULT_CAPABILITIES: DriverCapabilities = {\n nativeSql: false,\n objectqlAggregate: false,\n inMemory: true,\n};\n\n/**\n * AnalyticsService — Multi-driver analytics orchestrator.\n *\n * Implements `IAnalyticsService` by delegating to a priority-ordered\n * strategy chain:\n *\n * | Priority | Strategy | Condition |\n * |:---:|:---|:---|\n * | P1 (10) | NativeSQLStrategy | Driver supports raw SQL |\n * | P2 (20) | ObjectQLStrategy | Driver supports aggregate AST |\n * | P3 (30) | (custom / InMemoryStrategy from driver-memory) | Injected by user |\n *\n * When `fallbackService` is configured, an internal delegate strategy\n * is automatically appended at priority 30 as a safety net.\n *\n * The service also owns a `CubeRegistry` for metadata discovery and\n * auto-inference from object schemas.\n */\nexport class AnalyticsService implements IAnalyticsService {\n private readonly strategies: AnalyticsStrategy[];\n private readonly strategyCtx: StrategyContext;\n readonly cubeRegistry: CubeRegistry;\n private readonly logger: Logger;\n\n constructor(config: AnalyticsServiceConfig = {}) {\n this.logger = config.logger || createLogger({ level: 'info', format: 'pretty' });\n this.cubeRegistry = new CubeRegistry();\n\n // Register pre-defined cubes\n if (config.cubes) {\n this.cubeRegistry.registerAll(config.cubes);\n }\n\n // Build strategy context\n this.strategyCtx = {\n getCube: (name) => this.cubeRegistry.get(name),\n queryCapabilities: config.queryCapabilities || (() => DEFAULT_CAPABILITIES),\n executeRawSql: config.executeRawSql,\n executeAggregate: config.executeAggregate,\n fallbackService: config.fallbackService,\n };\n\n // Build strategy chain (built-in + custom, sorted by priority)\n // InMemoryStrategy is NOT built-in — it lives in @objectstack/driver-memory\n // and should be passed via config.strategies when needed.\n // When fallbackService is configured, an internal delegate is added at P3.\n const builtIn: AnalyticsStrategy[] = [\n new NativeSQLStrategy(),\n new ObjectQLStrategy(),\n ];\n\n // Auto-add fallback delegate when fallbackService is provided\n if (config.fallbackService) {\n builtIn.push(new FallbackDelegateStrategy());\n }\n\n const custom = config.strategies || [];\n this.strategies = [...builtIn, ...custom].sort((a, b) => a.priority - b.priority);\n\n this.logger.info(\n `[Analytics] Initialized with ${this.cubeRegistry.size} cubes, ` +\n `${this.strategies.length} strategies: ${this.strategies.map(s => s.name).join(' → ')}`,\n );\n }\n\n /**\n * Execute an analytical query by delegating to the first capable strategy.\n */\n async query(query: AnalyticsQuery): Promise<AnalyticsResult> {\n if (!query.cube) {\n throw new Error('Cube name is required in analytics query');\n }\n\n const strategy = this.resolveStrategy(query);\n this.logger.debug(`[Analytics] Query on cube \"${query.cube}\" → ${strategy.name}`);\n\n return strategy.execute(query, this.strategyCtx);\n }\n\n /**\n * Get cube metadata for discovery.\n */\n async getMeta(cubeName?: string): Promise<CubeMeta[]> {\n // If a fallback service is configured, merge its metadata with the registry\n const cubes = cubeName\n ? [this.cubeRegistry.get(cubeName)].filter(Boolean) as Cube[]\n : this.cubeRegistry.getAll();\n\n return cubes.map(cube => ({\n name: cube.name,\n title: cube.title,\n measures: Object.entries(cube.measures).map(([key, measure]) => ({\n name: `${cube.name}.${key}`,\n type: measure.type,\n title: measure.label,\n })),\n dimensions: Object.entries(cube.dimensions).map(([key, dimension]) => ({\n name: `${cube.name}.${key}`,\n type: dimension.type,\n title: dimension.label,\n })),\n }));\n }\n\n /**\n * Generate SQL for a query without executing it (dry-run).\n */\n async generateSql(query: AnalyticsQuery): Promise<{ sql: string; params: unknown[] }> {\n if (!query.cube) {\n throw new Error('Cube name is required for SQL generation');\n }\n\n const strategy = this.resolveStrategy(query);\n this.logger.debug(`[Analytics] generateSql on cube \"${query.cube}\" → ${strategy.name}`);\n\n return strategy.generateSql(query, this.strategyCtx);\n }\n\n // ── Internal ─────────────────────────────────────────────────────\n\n /**\n * Walk the strategy chain and return the first strategy that can handle the query.\n */\n private resolveStrategy(query: AnalyticsQuery): AnalyticsStrategy {\n for (const strategy of this.strategies) {\n if (strategy.canHandle(query, this.strategyCtx)) {\n return strategy;\n }\n }\n throw new Error(\n `[Analytics] No strategy can handle query for cube \"${query.cube}\". ` +\n `Checked: ${this.strategies.map(s => s.name).join(', ')}. ` +\n 'Ensure a compatible driver is configured or a fallback service is registered.',\n );\n }\n}\n\n/**\n * FallbackDelegateStrategy — Internal strategy for fallback service delegation.\n *\n * Automatically added to the strategy chain when `fallbackService` is configured.\n * Not exported — consumers who need explicit in-memory support should use\n * `InMemoryStrategy` from `@objectstack/driver-memory`.\n */\nclass FallbackDelegateStrategy implements AnalyticsStrategy {\n readonly name = 'FallbackDelegateStrategy';\n readonly priority = 30;\n\n canHandle(query: AnalyticsQuery, ctx: StrategyContext): boolean {\n if (!query.cube) return false;\n return !!ctx.fallbackService;\n }\n\n async execute(query: AnalyticsQuery, ctx: StrategyContext): Promise<AnalyticsResult> {\n return ctx.fallbackService!.query(query);\n }\n\n async generateSql(query: AnalyticsQuery, ctx: StrategyContext): Promise<{ sql: string; params: unknown[] }> {\n if (ctx.fallbackService?.generateSql) {\n return ctx.fallbackService.generateSql(query);\n }\n return {\n sql: `-- FallbackDelegateStrategy: SQL generation not supported for cube \"${query.cube}\"`,\n params: [],\n };\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Cube } from '@objectstack/spec/data';\n\n/**\n * CubeRegistry — Central registry for analytics cube definitions.\n *\n * Cubes can be registered from two sources:\n * 1. **Manifest definitions** — Explicit cube definitions in `objectstack.config.ts`.\n * 2. **Object schema inference** — Auto-generated cubes from ObjectQL object schemas.\n *\n * The registry is the single source of truth for cube metadata discovery\n * (used by `getMeta()` and the strategy chain).\n */\nexport class CubeRegistry {\n private cubes = new Map<string, Cube>();\n\n /** Register a single cube definition. Overwrites if name already exists. */\n register(cube: Cube): void {\n this.cubes.set(cube.name, cube);\n }\n\n /** Register multiple cube definitions at once. */\n registerAll(cubes: Cube[]): void {\n for (const cube of cubes) {\n this.register(cube);\n }\n }\n\n /** Get a cube definition by name. */\n get(name: string): Cube | undefined {\n return this.cubes.get(name);\n }\n\n /** Check if a cube is registered. */\n has(name: string): boolean {\n return this.cubes.has(name);\n }\n\n /** Return all registered cubes. */\n getAll(): Cube[] {\n return Array.from(this.cubes.values());\n }\n\n /** Return all cube names. */\n names(): string[] {\n return Array.from(this.cubes.keys());\n }\n\n /** Number of registered cubes. */\n get size(): number {\n return this.cubes.size;\n }\n\n /** Remove all cubes. */\n clear(): void {\n this.cubes.clear();\n }\n\n /**\n * Auto-generate a cube definition from an object schema.\n *\n * Heuristic rules:\n * - `number` fields → `sum`, `avg`, `min`, `max` measures\n * - `boolean` fields → `count` measure (count where true)\n * - All non-computed fields → dimensions\n * - `date`/`datetime` fields → time dimensions with standard granularities\n * - A default `count` measure is always added\n *\n * @param objectName - The snake_case object name (used as table/cube name)\n * @param fields - Array of field descriptors `{ name, type, label? }`\n */\n inferFromObject(\n objectName: string,\n fields: Array<{ name: string; type: string; label?: string }>,\n ): Cube {\n const measures: Record<string, any> = {\n count: {\n name: 'count',\n label: 'Count',\n type: 'count',\n sql: '*',\n },\n };\n const dimensions: Record<string, any> = {};\n\n for (const field of fields) {\n const label = field.label || field.name;\n\n // All fields become dimensions\n const dimType = this.fieldTypeToDimensionType(field.type);\n dimensions[field.name] = {\n name: field.name,\n label,\n type: dimType,\n sql: field.name,\n ...(dimType === 'time'\n ? { granularities: ['day', 'week', 'month', 'quarter', 'year'] }\n : {}),\n };\n\n // Numeric fields also become aggregation measures\n if (field.type === 'number' || field.type === 'currency' || field.type === 'percent') {\n measures[`${field.name}_sum`] = {\n name: `${field.name}_sum`,\n label: `${label} (Sum)`,\n type: 'sum',\n sql: field.name,\n };\n measures[`${field.name}_avg`] = {\n name: `${field.name}_avg`,\n label: `${label} (Avg)`,\n type: 'avg',\n sql: field.name,\n };\n }\n }\n\n const cube: Cube = {\n name: objectName,\n title: objectName,\n sql: objectName,\n measures,\n dimensions,\n public: false,\n };\n\n this.register(cube);\n return cube;\n }\n\n private fieldTypeToDimensionType(fieldType: string): string {\n switch (fieldType) {\n case 'number':\n case 'currency':\n case 'percent':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'date':\n case 'datetime':\n return 'time';\n default:\n return 'string';\n }\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { AnalyticsQuery, AnalyticsResult } from '@objectstack/spec/contracts';\nimport type { Cube } from '@objectstack/spec/data';\nimport type { AnalyticsStrategy, StrategyContext } from './types.js';\n\n/**\n * NativeSQLStrategy — Priority 1\n *\n * Pushes the analytics query down to the database as a native SQL statement.\n * This is the most efficient path and is preferred whenever the backing driver\n * supports raw SQL execution (e.g. Postgres, MySQL, SQLite).\n */\nexport class NativeSQLStrategy implements AnalyticsStrategy {\n readonly name = 'NativeSQLStrategy';\n readonly priority = 10;\n\n canHandle(query: AnalyticsQuery, ctx: StrategyContext): boolean {\n if (!query.cube) return false;\n const caps = ctx.queryCapabilities(query.cube);\n return caps.nativeSql && typeof ctx.executeRawSql === 'function';\n }\n\n async execute(query: AnalyticsQuery, ctx: StrategyContext): Promise<AnalyticsResult> {\n const { sql, params } = await this.generateSql(query, ctx);\n const cube = ctx.getCube(query.cube!)!;\n const objectName = this.extractObjectName(cube);\n\n const rows = await ctx.executeRawSql!(objectName, sql, params);\n\n // Build field metadata\n const fields = this.buildFieldMeta(query, cube);\n\n return { rows, fields, sql };\n }\n\n async generateSql(query: AnalyticsQuery, ctx: StrategyContext): Promise<{ sql: string; params: unknown[] }> {\n const cube = ctx.getCube(query.cube!);\n if (!cube) {\n throw new Error(`Cube not found: ${query.cube}`);\n }\n\n const params: unknown[] = [];\n const selectClauses: string[] = [];\n const groupByClauses: string[] = [];\n\n // Build SELECT for dimensions\n if (query.dimensions && query.dimensions.length > 0) {\n for (const dim of query.dimensions) {\n const colExpr = this.resolveDimensionSql(cube, dim);\n selectClauses.push(`${colExpr} AS \"${dim}\"`);\n groupByClauses.push(colExpr);\n }\n }\n\n // Build SELECT for measures\n if (query.measures && query.measures.length > 0) {\n for (const measure of query.measures) {\n const aggExpr = this.resolveMeasureSql(cube, measure);\n selectClauses.push(`${aggExpr} AS \"${measure}\"`);\n }\n }\n\n // Build WHERE clause\n const whereClauses: string[] = [];\n if (query.filters && query.filters.length > 0) {\n for (const filter of query.filters) {\n const colExpr = this.resolveFieldSql(cube, filter.member);\n const clause = this.buildFilterClause(colExpr, filter.operator, filter.values, params);\n if (clause) whereClauses.push(clause);\n }\n }\n\n // Build time dimension filters\n if (query.timeDimensions && query.timeDimensions.length > 0) {\n for (const td of query.timeDimensions) {\n const colExpr = this.resolveFieldSql(cube, td.dimension);\n if (td.dateRange) {\n const range = Array.isArray(td.dateRange) ? td.dateRange : [td.dateRange, td.dateRange];\n if (range.length === 2) {\n params.push(range[0], range[1]);\n whereClauses.push(`${colExpr} BETWEEN $${params.length - 1} AND $${params.length}`);\n }\n }\n }\n }\n\n const tableName = this.extractObjectName(cube);\n let sql = `SELECT ${selectClauses.join(', ')} FROM \"${tableName}\"`;\n if (whereClauses.length > 0) {\n sql += ` WHERE ${whereClauses.join(' AND ')}`;\n }\n if (groupByClauses.length > 0) {\n sql += ` GROUP BY ${groupByClauses.join(', ')}`;\n }\n if (query.order && Object.keys(query.order).length > 0) {\n const orderClauses = Object.entries(query.order).map(([f, d]) => `\"${f}\" ${d.toUpperCase()}`);\n sql += ` ORDER BY ${orderClauses.join(', ')}`;\n }\n if (query.limit != null) {\n sql += ` LIMIT ${query.limit}`;\n }\n if (query.offset != null) {\n sql += ` OFFSET ${query.offset}`;\n }\n\n return { sql, params };\n }\n\n // ── Helpers ──────────────────────────────────────────────────────\n\n private resolveDimensionSql(cube: Cube, member: string): string {\n const fieldName = member.includes('.') ? member.split('.')[1] : member;\n const dim = cube.dimensions[fieldName];\n return dim ? dim.sql : fieldName;\n }\n\n private resolveMeasureSql(cube: Cube, member: string): string {\n const fieldName = member.includes('.') ? member.split('.')[1] : member;\n const measure = cube.measures[fieldName];\n if (!measure) return `COUNT(*)`;\n\n const col = measure.sql;\n switch (measure.type) {\n case 'count': return 'COUNT(*)';\n case 'sum': return `SUM(${col})`;\n case 'avg': return `AVG(${col})`;\n case 'min': return `MIN(${col})`;\n case 'max': return `MAX(${col})`;\n case 'count_distinct': return `COUNT(DISTINCT ${col})`;\n default: return `COUNT(*)`;\n }\n }\n\n private resolveFieldSql(cube: Cube, member: string): string {\n const fieldName = member.includes('.') ? member.split('.')[1] : member;\n const dim = cube.dimensions[fieldName];\n if (dim) return dim.sql;\n const measure = cube.measures[fieldName];\n if (measure) return measure.sql;\n return fieldName;\n }\n\n private buildFilterClause(col: string, operator: string, values: string[] | undefined, params: unknown[]): string | null {\n const opMap: Record<string, string> = {\n equals: '=', notEquals: '!=', gt: '>', gte: '>=', lt: '<', lte: '<=',\n contains: 'LIKE', notContains: 'NOT LIKE',\n };\n\n if (operator === 'set') return `${col} IS NOT NULL`;\n if (operator === 'notSet') return `${col} IS NULL`;\n\n const sqlOp = opMap[operator];\n if (!sqlOp || !values || values.length === 0) return null;\n\n if (operator === 'contains' || operator === 'notContains') {\n params.push(`%${values[0]}%`);\n } else {\n params.push(values[0]);\n }\n return `${col} ${sqlOp} $${params.length}`;\n }\n\n private extractObjectName(cube: Cube): string {\n return cube.sql.trim();\n }\n\n private buildFieldMeta(query: AnalyticsQuery, cube: Cube): Array<{ name: string; type: string }> {\n const fields: Array<{ name: string; type: string }> = [];\n if (query.dimensions) {\n for (const dim of query.dimensions) {\n const fieldName = dim.includes('.') ? dim.split('.')[1] : dim;\n const d = cube.dimensions[fieldName];\n fields.push({ name: dim, type: d?.type || 'string' });\n }\n }\n if (query.measures) {\n for (const m of query.measures) {\n fields.push({ name: m, type: 'number' });\n }\n }\n return fields;\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { AnalyticsQuery, AnalyticsResult } from '@objectstack/spec/contracts';\nimport type { Cube } from '@objectstack/spec/data';\nimport type { AnalyticsStrategy, StrategyContext } from './types.js';\n\n/**\n * ObjectQLStrategy — Priority 2\n *\n * Translates an analytics query into an ObjectQL `engine.aggregate()` call.\n * This path works with any driver that supports the ObjectQL aggregate AST\n * (Postgres, Mongo, SQLite, etc.) without requiring raw SQL access.\n */\nexport class ObjectQLStrategy implements AnalyticsStrategy {\n readonly name = 'ObjectQLStrategy';\n readonly priority = 20;\n\n canHandle(query: AnalyticsQuery, ctx: StrategyContext): boolean {\n if (!query.cube) return false;\n const caps = ctx.queryCapabilities(query.cube);\n return caps.objectqlAggregate && typeof ctx.executeAggregate === 'function';\n }\n\n async execute(query: AnalyticsQuery, ctx: StrategyContext): Promise<AnalyticsResult> {\n const cube = ctx.getCube(query.cube!)!;\n const objectName = this.extractObjectName(cube);\n\n // Build groupBy from dimensions\n const groupBy: string[] = [];\n if (query.dimensions && query.dimensions.length > 0) {\n for (const dim of query.dimensions) {\n groupBy.push(this.resolveFieldName(cube, dim, 'dimension'));\n }\n }\n\n // Build aggregations from measures\n const aggregations: Array<{ field: string; method: string; alias: string }> = [];\n if (query.measures && query.measures.length > 0) {\n for (const measure of query.measures) {\n const { field, method } = this.resolveMeasureAggregation(cube, measure);\n aggregations.push({ field, method, alias: measure });\n }\n }\n\n // Build filter from query filters\n const filter: Record<string, unknown> = {};\n if (query.filters && query.filters.length > 0) {\n for (const f of query.filters) {\n const fieldName = this.resolveFieldName(cube, f.member, 'any');\n filter[fieldName] = this.convertFilter(f.operator, f.values);\n }\n }\n\n const rows = await ctx.executeAggregate!(objectName, {\n groupBy: groupBy.length > 0 ? groupBy : undefined,\n aggregations: aggregations.length > 0 ? aggregations : undefined,\n filter: Object.keys(filter).length > 0 ? filter : undefined,\n });\n\n // Remap short field names back to cube-qualified names\n const mappedRows = rows.map(row => {\n const mapped: Record<string, unknown> = {};\n if (query.dimensions) {\n for (const dim of query.dimensions) {\n const shortName = this.resolveFieldName(cube, dim, 'dimension');\n if (shortName in row) mapped[dim] = row[shortName];\n }\n }\n if (query.measures) {\n for (const m of query.measures) {\n // Alias was set to the full measure name\n if (m in row) mapped[m] = row[m];\n }\n }\n return mapped;\n });\n\n const fields = this.buildFieldMeta(query, cube);\n return { rows: mappedRows, fields };\n }\n\n async generateSql(query: AnalyticsQuery, ctx: StrategyContext): Promise<{ sql: string; params: unknown[] }> {\n const cube = ctx.getCube(query.cube!);\n if (!cube) {\n throw new Error(`Cube not found: ${query.cube}`);\n }\n\n // Generate a representative SQL even though ObjectQL uses AST internally\n const selectParts: string[] = [];\n const groupByParts: string[] = [];\n\n if (query.dimensions) {\n for (const dim of query.dimensions) {\n const col = this.resolveFieldName(cube, dim, 'dimension');\n selectParts.push(`${col} AS \"${dim}\"`);\n groupByParts.push(col);\n }\n }\n if (query.measures) {\n for (const m of query.measures) {\n const { field, method } = this.resolveMeasureAggregation(cube, m);\n const aggSql = method === 'count' ? 'COUNT(*)' : `${method.toUpperCase()}(${field})`;\n selectParts.push(`${aggSql} AS \"${m}\"`);\n }\n }\n\n const tableName = this.extractObjectName(cube);\n let sql = `SELECT ${selectParts.join(', ')} FROM \"${tableName}\"`;\n if (groupByParts.length > 0) {\n sql += ` GROUP BY ${groupByParts.join(', ')}`;\n }\n\n return { sql, params: [] };\n }\n\n // ── Helpers ──────────────────────────────────────────────────────\n\n private resolveFieldName(cube: Cube, member: string, kind: 'dimension' | 'measure' | 'any'): string {\n const fieldName = member.includes('.') ? member.split('.')[1] : member;\n if (kind === 'dimension' || kind === 'any') {\n const dim = cube.dimensions[fieldName];\n if (dim) return dim.sql.replace(/^\\$/, '');\n }\n if (kind === 'measure' || kind === 'any') {\n const measure = cube.measures[fieldName];\n if (measure) return measure.sql.replace(/^\\$/, '');\n }\n return fieldName;\n }\n\n private resolveMeasureAggregation(cube: Cube, measureName: string): { field: string; method: string } {\n const fieldName = measureName.includes('.') ? measureName.split('.')[1] : measureName;\n const measure = cube.measures[fieldName];\n if (!measure) return { field: '*', method: 'count' };\n return {\n field: measure.sql.replace(/^\\$/, ''),\n method: measure.type === 'count_distinct' ? 'count_distinct' : measure.type,\n };\n }\n\n private convertFilter(operator: string, values?: string[]): unknown {\n if (operator === 'set') return { $ne: null };\n if (operator === 'notSet') return null;\n if (!values || values.length === 0) return undefined;\n\n switch (operator) {\n case 'equals': return values[0];\n case 'notEquals': return { $ne: values[0] };\n case 'gt': return { $gt: values[0] };\n case 'gte': return { $gte: values[0] };\n case 'lt': return { $lt: values[0] };\n case 'lte': return { $lte: values[0] };\n case 'contains': return { $regex: values[0] };\n default: return values[0];\n }\n }\n\n private extractObjectName(cube: Cube): string {\n return cube.sql.trim();\n }\n\n private buildFieldMeta(query: AnalyticsQuery, cube: Cube): Array<{ name: string; type: string }> {\n const fields: Array<{ name: string; type: string }> = [];\n if (query.dimensions) {\n for (const dim of query.dimensions) {\n const fieldName = dim.includes('.') ? dim.split('.')[1] : dim;\n const d = cube.dimensions[fieldName];\n fields.push({ name: dim, type: d?.type || 'string' });\n }\n }\n if (query.measures) {\n for (const m of query.measures) {\n fields.push({ name: m, type: 'number' });\n }\n }\n return fields;\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport type { Cube } from '@objectstack/spec/data';\nimport type { IAnalyticsService } from '@objectstack/spec/contracts';\nimport { AnalyticsService } from './analytics-service.js';\nimport type { AnalyticsServiceConfig } from './analytics-service.js';\nimport type { DriverCapabilities } from './strategies/types.js';\n\n/**\n * Configuration for AnalyticsServicePlugin.\n */\nexport interface AnalyticsServicePluginOptions {\n /** Pre-defined cube definitions (from manifest). */\n cubes?: Cube[];\n /**\n * Probe driver capabilities for a given cube.\n * When omitted, defaults to in-memory only.\n */\n queryCapabilities?: (cubeName: string) => DriverCapabilities;\n /**\n * Execute raw SQL on a driver. Enables NativeSQLStrategy.\n */\n executeRawSql?: (objectName: string, sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>;\n /**\n * Execute ObjectQL aggregate. Enables ObjectQLStrategy.\n */\n executeAggregate?: (objectName: string, options: {\n groupBy?: string[];\n aggregations?: Array<{ field: string; method: string; alias: string }>;\n filter?: Record<string, unknown>;\n }) => Promise<Record<string, unknown>[]>;\n /** Enable debug logging. */\n debug?: boolean;\n}\n\n/**\n * AnalyticsServicePlugin — Kernel plugin for multi-driver analytics.\n *\n * Lifecycle:\n * 1. **init** — Creates `AnalyticsService`, registers as `'analytics'` service.\n * If an existing analytics service is already registered (e.g. MemoryAnalyticsService\n * from dev-plugin), it is captured as the `fallbackService`.\n * 2. **start** — Triggers `'analytics:ready'` hook so other plugins can\n * register cubes or extend the service.\n * 3. **destroy** — Cleans up references.\n *\n * @example\n * ```ts\n * import { LiteKernel } from '@objectstack/core';\n * import { AnalyticsServicePlugin } from '@objectstack/service-analytics';\n *\n * const kernel = new LiteKernel();\n * kernel.use(new AnalyticsServicePlugin({\n * cubes: [ordersCube],\n * queryCapabilities: (cube) => ({ nativeSql: true, objectqlAggregate: true, inMemory: false }),\n * executeRawSql: async (obj, sql, params) => pgPool.query(sql, params).then(r => r.rows),\n * }));\n * await kernel.bootstrap();\n *\n * const analytics = kernel.getService<IAnalyticsService>('analytics');\n * const result = await analytics.query({ cube: 'orders', measures: ['orders.count'] });\n * ```\n */\nexport class AnalyticsServicePlugin implements Plugin {\n name = 'com.objectstack.service-analytics';\n version = '1.0.0';\n type = 'standard' as const;\n dependencies: string[] = [];\n\n private service?: AnalyticsService;\n private readonly options: AnalyticsServicePluginOptions;\n\n constructor(options: AnalyticsServicePluginOptions = {}) {\n this.options = options;\n }\n\n async init(ctx: PluginContext): Promise<void> {\n // Check if there is an existing analytics service (e.g. from dev-plugin)\n let fallbackService: IAnalyticsService | undefined;\n try {\n const existing = ctx.getService<IAnalyticsService>('analytics');\n if (existing && typeof existing.query === 'function') {\n fallbackService = existing;\n ctx.logger.debug('[Analytics] Found existing analytics service, using as fallback');\n }\n } catch {\n // No existing service — that's fine\n }\n\n const config: AnalyticsServiceConfig = {\n cubes: this.options.cubes,\n logger: ctx.logger,\n queryCapabilities: this.options.queryCapabilities,\n executeRawSql: this.options.executeRawSql,\n executeAggregate: this.options.executeAggregate,\n fallbackService,\n };\n\n this.service = new AnalyticsService(config);\n\n // Register or replace the analytics service\n if (fallbackService) {\n ctx.replaceService('analytics', this.service);\n } else {\n ctx.registerService('analytics', this.service);\n }\n\n if (this.options.debug) {\n ctx.hook('analytics:beforeQuery', async (query: unknown) => {\n ctx.logger.debug('[Analytics] Before query', { query });\n });\n }\n\n ctx.logger.info('[Analytics] Service initialized');\n }\n\n async start(ctx: PluginContext): Promise<void> {\n if (!this.service) return;\n\n // Notify other plugins that analytics is ready\n await ctx.trigger('analytics:ready', this.service);\n\n ctx.logger.info(\n `[Analytics] Service started with ${this.service.cubeRegistry.size} cubes: ` +\n `${this.service.cubeRegistry.names().join(', ') || '(none)'}`,\n );\n }\n\n async destroy(): Promise<void> {\n this.service = undefined;\n }\n}\n"],"mappings":";AAUA,SAAS,oBAAoB;;;ACItB,IAAM,eAAN,MAAm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jB;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/analytics-service.ts","../src/cube-registry.ts","../src/strategies/native-sql-strategy.ts","../src/strategies/objectql-strategy.ts","../src/plugin.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IAnalyticsService,\n AnalyticsQuery,\n AnalyticsResult,\n CubeMeta,\n} from '@objectstack/spec/contracts';\nimport type { Cube } from '@objectstack/spec/data';\nimport type { Logger } from '@objectstack/spec/contracts';\nimport { createLogger } from '@objectstack/core';\nimport { CubeRegistry } from './cube-registry.js';\nimport type { AnalyticsStrategy, DriverCapabilities, StrategyContext } from './strategies/types.js';\nimport { NativeSQLStrategy } from './strategies/native-sql-strategy.js';\nimport { ObjectQLStrategy } from './strategies/objectql-strategy.js';\n\n/**\n * Configuration for AnalyticsService.\n */\nexport interface AnalyticsServiceConfig {\n /** Pre-defined cube definitions (from manifest). */\n cubes?: Cube[];\n /** Logger instance. */\n logger?: Logger;\n /**\n * Probe driver capabilities for the object that backs a cube.\n * The service calls this function to decide which strategy can handle a query.\n */\n queryCapabilities?: (cubeName: string) => DriverCapabilities;\n /**\n * Execute raw SQL on the driver for a given object.\n * Required for NativeSQLStrategy.\n */\n executeRawSql?: (objectName: string, sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>;\n /**\n * Execute an ObjectQL aggregate query.\n * Required for ObjectQLStrategy.\n */\n executeAggregate?: (objectName: string, options: {\n groupBy?: string[];\n aggregations?: Array<{ field: string; method: string; alias: string }>;\n filter?: Record<string, unknown>;\n }) => Promise<Record<string, unknown>[]>;\n /**\n * Fallback IAnalyticsService (e.g. MemoryAnalyticsService).\n * Used by InMemoryStrategy.\n */\n fallbackService?: IAnalyticsService;\n /**\n * Custom strategies to add/replace the defaults.\n * They are merged with the built-in strategies and sorted by priority.\n */\n strategies?: AnalyticsStrategy[];\n}\n\n/**\n * Default capabilities when probing is not configured — assumes in-memory only.\n */\nconst DEFAULT_CAPABILITIES: DriverCapabilities = {\n nativeSql: false,\n objectqlAggregate: false,\n inMemory: true,\n};\n\n/**\n * AnalyticsService — Multi-driver analytics orchestrator.\n *\n * Implements `IAnalyticsService` by delegating to a priority-ordered\n * strategy chain:\n *\n * | Priority | Strategy | Condition |\n * |:---:|:---|:---|\n * | P1 (10) | NativeSQLStrategy | Driver supports raw SQL |\n * | P2 (20) | ObjectQLStrategy | Driver supports aggregate AST |\n * | P3 (30) | (custom / InMemoryStrategy from driver-memory) | Injected by user |\n *\n * When `fallbackService` is configured, an internal delegate strategy\n * is automatically appended at priority 30 as a safety net.\n *\n * The service also owns a `CubeRegistry` for metadata discovery and\n * auto-inference from object schemas.\n */\nexport class AnalyticsService implements IAnalyticsService {\n private readonly strategies: AnalyticsStrategy[];\n private readonly strategyCtx: StrategyContext;\n readonly cubeRegistry: CubeRegistry;\n private readonly logger: Logger;\n\n constructor(config: AnalyticsServiceConfig = {}) {\n this.logger = config.logger || createLogger({ level: 'info', format: 'pretty' });\n this.cubeRegistry = new CubeRegistry();\n\n // Register pre-defined cubes\n if (config.cubes) {\n this.cubeRegistry.registerAll(config.cubes);\n }\n\n // Build strategy context\n this.strategyCtx = {\n getCube: (name) => this.cubeRegistry.get(name),\n queryCapabilities: config.queryCapabilities || (() => DEFAULT_CAPABILITIES),\n executeRawSql: config.executeRawSql,\n executeAggregate: config.executeAggregate,\n fallbackService: config.fallbackService,\n };\n\n // Build strategy chain (built-in + custom, sorted by priority)\n // InMemoryStrategy is NOT built-in — it lives in @objectstack/driver-memory\n // and should be passed via config.strategies when needed.\n // When fallbackService is configured, an internal delegate is added at P3.\n const builtIn: AnalyticsStrategy[] = [\n new NativeSQLStrategy(),\n new ObjectQLStrategy(),\n ];\n\n // Auto-add fallback delegate when fallbackService is provided\n if (config.fallbackService) {\n builtIn.push(new FallbackDelegateStrategy());\n }\n\n const custom = config.strategies || [];\n this.strategies = [...builtIn, ...custom].sort((a, b) => a.priority - b.priority);\n\n this.logger.info(\n `[Analytics] Initialized with ${this.cubeRegistry.size} cubes, ` +\n `${this.strategies.length} strategies: ${this.strategies.map(s => s.name).join(' → ')}`,\n );\n }\n\n /**\n * Execute an analytical query by delegating to the first capable strategy.\n */\n async query(query: AnalyticsQuery): Promise<AnalyticsResult> {\n if (!query.cube) {\n throw new Error('Cube name is required in analytics query');\n }\n\n const normalized = this.normalizeQuery(query);\n this.ensureCube(normalized);\n const strategy = this.resolveStrategy(normalized);\n this.logger.debug(`[Analytics] Query on cube \"${normalized.cube}\" → ${strategy.name}`);\n\n return strategy.execute(normalized, this.strategyCtx);\n }\n\n /**\n * Get cube metadata for discovery.\n */\n async getMeta(cubeName?: string): Promise<CubeMeta[]> {\n // If a fallback service is configured, merge its metadata with the registry\n const cubes = cubeName\n ? [this.cubeRegistry.get(cubeName)].filter(Boolean) as Cube[]\n : this.cubeRegistry.getAll();\n\n return cubes.map(cube => ({\n name: cube.name,\n title: cube.title,\n measures: Object.entries(cube.measures).map(([key, measure]) => ({\n name: `${cube.name}.${key}`,\n type: measure.type,\n title: measure.label,\n })),\n dimensions: Object.entries(cube.dimensions).map(([key, dimension]) => ({\n name: `${cube.name}.${key}`,\n type: dimension.type,\n title: dimension.label,\n })),\n }));\n }\n\n /**\n * Generate SQL for a query without executing it (dry-run).\n */\n async generateSql(query: AnalyticsQuery): Promise<{ sql: string; params: unknown[] }> {\n if (!query.cube) {\n throw new Error('Cube name is required for SQL generation');\n }\n\n const normalized = this.normalizeQuery(query);\n this.ensureCube(normalized);\n const strategy = this.resolveStrategy(normalized);\n this.logger.debug(`[Analytics] generateSql on cube \"${normalized.cube}\" → ${strategy.name}`);\n\n return strategy.generateSql(normalized, this.strategyCtx);\n }\n\n // ── Internal ─────────────────────────────────────────────────────\n\n /**\n * Normalise a query into a canonical shape that strategies can rely on:\n *\n * 1. **Filters as object** — Some clients (e.g. dashboard widget translators)\n * send `filters` as a Mongo-style object `{ stage: { $nin: [...] } }`\n * instead of the schema's `Array<{ member, operator, values }>`. We\n * translate the object form into the array form so existing strategies\n * work unchanged.\n * 2. Other shapes are returned as-is.\n */\n private normalizeQuery(query: AnalyticsQuery): AnalyticsQuery {\n const filters = query.filters as unknown;\n if (!filters || Array.isArray(filters)) return query;\n if (typeof filters !== 'object') return query;\n\n const arr: AnalyticsQuery['filters'] = [];\n for (const [member, raw] of Object.entries(filters as Record<string, unknown>)) {\n if (raw && typeof raw === 'object' && !Array.isArray(raw) && !(raw instanceof Date)) {\n for (const [op, val] of Object.entries(raw as Record<string, unknown>)) {\n const mapped = mongoOperatorToFilter(op, val);\n if (!mapped) continue;\n if (mapped.multi) {\n arr.push({ member, operator: mapped.operator, values: mapped.values });\n } else if (mapped.values.length === 0) {\n arr.push({ member, operator: mapped.operator, values: [] });\n } else {\n for (const v of mapped.values) arr.push({ member, operator: mapped.operator, values: [v] });\n }\n }\n } else if (Array.isArray(raw)) {\n arr.push({ member, operator: 'in', values: raw.map(String) });\n } else {\n arr.push({ member, operator: 'equals', values: [String(raw)] });\n }\n }\n return { ...query, filters: arr };\n }\n\n /**\n * Ensure a cube exists for the given query and that it knows about every\n * measure referenced by the query.\n *\n * - If no cube is registered for `query.cube`, infer a minimal cube from\n * the query so downstream strategies (which assume `cube.sql` exists)\n * don't crash.\n * - If a cube exists but the query references measures that aren't in\n * `cube.measures` (e.g. `amount_sum`, `amount_avg` emitted by dashboard\n * widget translators), inject suffix-inferred Metric entries so the\n * strategies pick the right aggregation function and field.\n */\n private ensureCube(query: AnalyticsQuery): void {\n const name = query.cube!;\n let cube = this.cubeRegistry.get(name);\n\n if (!cube) {\n cube = this.inferCubeFromQuery(query);\n this.cubeRegistry.register(cube);\n this.logger.warn(\n `[Analytics] No cube registered for \"${name}\"; auto-inferred a minimal cube ` +\n `(sql=\"${name}\", measures=${Object.keys(cube.measures).join(',') || '(none)'}, ` +\n `dimensions=${Object.keys(cube.dimensions).join(',') || '(none)'}). ` +\n `Define an explicit Cube in your stack for full control.`,\n );\n return;\n }\n\n // Cube exists — check for unknown measures referenced by the query and\n // augment the cube with suffix-inferred Metric definitions so callers\n // that pass `<field>_sum` / `<field>_avg` etc. get the right aggregation.\n const stripPrefix = (m: string) => (m.includes('.') ? m.split('.').slice(1).join('.') : m);\n const extraMeasures: Record<string, any> = {};\n for (const m of query.measures || []) {\n const key = stripPrefix(m);\n if (cube.measures[key] || extraMeasures[key]) continue;\n extraMeasures[key] = inferMeasure(key);\n }\n if (Object.keys(extraMeasures).length > 0) {\n const augmented: Cube = {\n ...cube,\n measures: { ...cube.measures, ...extraMeasures },\n };\n this.cubeRegistry.register(augmented);\n this.logger.debug(\n `[Analytics] Augmented cube \"${name}\" with inferred measures: ${Object.keys(extraMeasures).join(',')}`,\n );\n }\n }\n\n /** Build a minimal Cube from the fields referenced by an AnalyticsQuery. */\n private inferCubeFromQuery(query: AnalyticsQuery): Cube {\n const cubeName = query.cube!;\n const measures: Record<string, any> = {};\n const dimensions: Record<string, any> = {};\n\n const stripPrefix = (m: string) => (m.includes('.') ? m.split('.').slice(1).join('.') : m);\n\n // Always provide a default `count` measure\n measures.count = { name: 'count', label: 'Count', type: 'count', sql: '*' };\n\n for (const m of query.measures || []) {\n const key = stripPrefix(m);\n if (measures[key]) continue;\n const inferred = inferMeasure(key);\n measures[key] = inferred;\n }\n\n for (const d of query.dimensions || []) {\n const key = stripPrefix(d);\n if (dimensions[key]) continue;\n dimensions[key] = { name: key, label: key, type: 'string', sql: key };\n }\n\n for (const f of query.filters || []) {\n const key = stripPrefix(f.member);\n if (dimensions[key] || measures[key]) continue;\n dimensions[key] = { name: key, label: key, type: 'string', sql: key };\n }\n\n for (const td of query.timeDimensions || []) {\n const key = stripPrefix(td.dimension);\n if (dimensions[key]) continue;\n dimensions[key] = {\n name: key, label: key, type: 'time', sql: key,\n granularities: ['day', 'week', 'month', 'quarter', 'year'],\n };\n }\n\n return {\n name: cubeName,\n title: cubeName,\n sql: cubeName,\n measures,\n dimensions,\n public: false,\n };\n }\n\n /**\n * Walk the strategy chain and return the first strategy that can handle the query.\n */\n private resolveStrategy(query: AnalyticsQuery): AnalyticsStrategy {\n for (const strategy of this.strategies) {\n if (strategy.canHandle(query, this.strategyCtx)) {\n return strategy;\n }\n }\n throw new Error(\n `[Analytics] No strategy can handle query for cube \"${query.cube}\". ` +\n `Checked: ${this.strategies.map(s => s.name).join(', ')}. ` +\n 'Ensure a compatible driver is configured or a fallback service is registered.',\n );\n }\n}\n\n/**\n * Infer a Metric definition from a measure key name.\n *\n * Recognised suffix conventions (matches dashboard widget translators that\n * emit measures like `<field>_sum`, `<field>_avg`):\n *\n * | Suffix | Aggregation |\n * |:-------------------|:----------------|\n * | `count` | `count(*)` |\n * | `_sum` | `sum(field)` |\n * | `_avg` / `_average`| `avg(field)` |\n * | `_min` | `min(field)` |\n * | `_max` | `max(field)` |\n * | `_count_distinct` | `count(distinct field)` |\n *\n * Anything else is treated as a `sum(<key>)` — best-effort default for an\n * unknown numeric measure.\n */\nexport function inferMeasure(key: string): { name: string; label: string; type: 'count' | 'sum' | 'avg' | 'min' | 'max' | 'count_distinct'; sql: string } {\n if (key === 'count') {\n return { name: 'count', label: 'Count', type: 'count', sql: '*' };\n }\n const suffixes: Array<[string, 'sum' | 'avg' | 'min' | 'max' | 'count_distinct']> = [\n ['_count_distinct', 'count_distinct'],\n ['_sum', 'sum'],\n ['_avg', 'avg'],\n ['_average', 'avg'],\n ['_min', 'min'],\n ['_max', 'max'],\n ];\n for (const [suffix, type] of suffixes) {\n if (key.endsWith(suffix)) {\n const field = key.slice(0, -suffix.length) || '*';\n return { name: key, label: key, type, sql: field };\n }\n }\n return { name: key, label: key, type: 'sum', sql: key };\n}\n\n/**\n * Translate a Mongo-style filter operator (e.g. `$gte`, `$nin`, `$regex`)\n * into the AnalyticsQuery filter shape (`operator` + flat `values` array).\n *\n * Multi-value Mongo operators (`$in`, `$nin`) are returned as a single\n * filter clause with multiple values — the calling normaliser splits them\n * into one filter per value so downstream strategies that take `values[0]`\n * still produce the correct AND-combined SQL (`col != $1 AND col != $2`).\n *\n * Returns `null` when the operator can't be safely represented (e.g.\n * unsupported complex operators).\n */\nfunction mongoOperatorToFilter(\n op: string,\n val: unknown,\n): { operator: 'equals' | 'notEquals' | 'gt' | 'gte' | 'lt' | 'lte' | 'contains' | 'notContains' | 'in' | 'notIn' | 'set' | 'notSet' | 'inDateRange'; values: string[]; multi?: boolean } | null {\n const toStrArr = (v: unknown): string[] =>\n v == null ? [] : Array.isArray(v) ? v.map(String) : [String(v)];\n switch (op) {\n case '$eq': return { operator: 'equals', values: toStrArr(val) };\n case '$ne': return { operator: 'notEquals', values: toStrArr(val) };\n case '$gt': return { operator: 'gt', values: toStrArr(val) };\n case '$gte': return { operator: 'gte', values: toStrArr(val) };\n case '$lt': return { operator: 'lt', values: toStrArr(val) };\n case '$lte': return { operator: 'lte', values: toStrArr(val) };\n case '$in': return { operator: 'in', values: toStrArr(val), multi: true };\n case '$nin': return { operator: 'notIn', values: toStrArr(val), multi: true };\n case '$regex': return { operator: 'contains', values: toStrArr(val) };\n case '$exists': return val ? { operator: 'set', values: [] } : { operator: 'notSet', values: [] };\n default: return null;\n }\n}\n\n/**\n * FallbackDelegateStrategy — Internal strategy for fallback service delegation.\n *\n * Automatically added to the strategy chain when `fallbackService` is configured.\n * Not exported — consumers who need explicit in-memory support should use\n * `InMemoryStrategy` from `@objectstack/driver-memory`.\n */\nclass FallbackDelegateStrategy implements AnalyticsStrategy {\n readonly name = 'FallbackDelegateStrategy';\n readonly priority = 30;\n\n canHandle(query: AnalyticsQuery, ctx: StrategyContext): boolean {\n if (!query.cube) return false;\n return !!ctx.fallbackService;\n }\n\n async execute(query: AnalyticsQuery, ctx: StrategyContext): Promise<AnalyticsResult> {\n return ctx.fallbackService!.query(query);\n }\n\n async generateSql(query: AnalyticsQuery, ctx: StrategyContext): Promise<{ sql: string; params: unknown[] }> {\n if (ctx.fallbackService?.generateSql) {\n return ctx.fallbackService.generateSql(query);\n }\n return {\n sql: `-- FallbackDelegateStrategy: SQL generation not supported for cube \"${query.cube}\"`,\n params: [],\n };\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Cube } from '@objectstack/spec/data';\n\n/**\n * CubeRegistry — Central registry for analytics cube definitions.\n *\n * Cubes can be registered from two sources:\n * 1. **Manifest definitions** — Explicit cube definitions in `objectstack.config.ts`.\n * 2. **Object schema inference** — Auto-generated cubes from ObjectQL object schemas.\n *\n * The registry is the single source of truth for cube metadata discovery\n * (used by `getMeta()` and the strategy chain).\n */\nexport class CubeRegistry {\n private cubes = new Map<string, Cube>();\n\n /** Register a single cube definition. Overwrites if name already exists. */\n register(cube: Cube): void {\n this.cubes.set(cube.name, cube);\n }\n\n /** Register multiple cube definitions at once. */\n registerAll(cubes: Cube[]): void {\n for (const cube of cubes) {\n this.register(cube);\n }\n }\n\n /** Get a cube definition by name. */\n get(name: string): Cube | undefined {\n return this.cubes.get(name);\n }\n\n /** Check if a cube is registered. */\n has(name: string): boolean {\n return this.cubes.has(name);\n }\n\n /** Return all registered cubes. */\n getAll(): Cube[] {\n return Array.from(this.cubes.values());\n }\n\n /** Return all cube names. */\n names(): string[] {\n return Array.from(this.cubes.keys());\n }\n\n /** Number of registered cubes. */\n get size(): number {\n return this.cubes.size;\n }\n\n /** Remove all cubes. */\n clear(): void {\n this.cubes.clear();\n }\n\n /**\n * Auto-generate a cube definition from an object schema.\n *\n * Heuristic rules:\n * - `number` fields → `sum`, `avg`, `min`, `max` measures\n * - `boolean` fields → `count` measure (count where true)\n * - All non-computed fields → dimensions\n * - `date`/`datetime` fields → time dimensions with standard granularities\n * - A default `count` measure is always added\n *\n * @param objectName - The snake_case object name (used as table/cube name)\n * @param fields - Array of field descriptors `{ name, type, label? }`\n */\n inferFromObject(\n objectName: string,\n fields: Array<{ name: string; type: string; label?: string }>,\n ): Cube {\n const measures: Record<string, any> = {\n count: {\n name: 'count',\n label: 'Count',\n type: 'count',\n sql: '*',\n },\n };\n const dimensions: Record<string, any> = {};\n\n for (const field of fields) {\n const label = field.label || field.name;\n\n // All fields become dimensions\n const dimType = this.fieldTypeToDimensionType(field.type);\n dimensions[field.name] = {\n name: field.name,\n label,\n type: dimType,\n sql: field.name,\n ...(dimType === 'time'\n ? { granularities: ['day', 'week', 'month', 'quarter', 'year'] }\n : {}),\n };\n\n // Numeric fields also become aggregation measures\n if (field.type === 'number' || field.type === 'currency' || field.type === 'percent') {\n measures[`${field.name}_sum`] = {\n name: `${field.name}_sum`,\n label: `${label} (Sum)`,\n type: 'sum',\n sql: field.name,\n };\n measures[`${field.name}_avg`] = {\n name: `${field.name}_avg`,\n label: `${label} (Avg)`,\n type: 'avg',\n sql: field.name,\n };\n }\n }\n\n const cube: Cube = {\n name: objectName,\n title: objectName,\n sql: objectName,\n measures,\n dimensions,\n public: false,\n };\n\n this.register(cube);\n return cube;\n }\n\n private fieldTypeToDimensionType(fieldType: string): string {\n switch (fieldType) {\n case 'number':\n case 'currency':\n case 'percent':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'date':\n case 'datetime':\n return 'time';\n default:\n return 'string';\n }\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { AnalyticsQuery, AnalyticsResult } from '@objectstack/spec/contracts';\nimport type { Cube } from '@objectstack/spec/data';\nimport type { AnalyticsStrategy, StrategyContext } from './types.js';\n\n/**\n * NativeSQLStrategy — Priority 1\n *\n * Pushes the analytics query down to the database as a native SQL statement.\n * This is the most efficient path and is preferred whenever the backing driver\n * supports raw SQL execution (e.g. Postgres, MySQL, SQLite).\n */\nexport class NativeSQLStrategy implements AnalyticsStrategy {\n readonly name = 'NativeSQLStrategy';\n readonly priority = 10;\n\n canHandle(query: AnalyticsQuery, ctx: StrategyContext): boolean {\n if (!query.cube) return false;\n const caps = ctx.queryCapabilities(query.cube);\n return caps.nativeSql && typeof ctx.executeRawSql === 'function';\n }\n\n async execute(query: AnalyticsQuery, ctx: StrategyContext): Promise<AnalyticsResult> {\n const { sql, params } = await this.generateSql(query, ctx);\n const cube = ctx.getCube(query.cube!)!;\n const objectName = this.extractObjectName(cube);\n\n const rows = await ctx.executeRawSql!(objectName, sql, params);\n\n // Build field metadata\n const fields = this.buildFieldMeta(query, cube);\n\n return { rows, fields, sql };\n }\n\n async generateSql(query: AnalyticsQuery, ctx: StrategyContext): Promise<{ sql: string; params: unknown[] }> {\n const cube = ctx.getCube(query.cube!);\n if (!cube) {\n throw new Error(`Cube not found: ${query.cube}`);\n }\n\n const params: unknown[] = [];\n const selectClauses: string[] = [];\n const groupByClauses: string[] = [];\n\n // Build SELECT for dimensions\n if (query.dimensions && query.dimensions.length > 0) {\n for (const dim of query.dimensions) {\n const colExpr = this.resolveDimensionSql(cube, dim);\n selectClauses.push(`${colExpr} AS \"${dim}\"`);\n groupByClauses.push(colExpr);\n }\n }\n\n // Build SELECT for measures\n if (query.measures && query.measures.length > 0) {\n for (const measure of query.measures) {\n const aggExpr = this.resolveMeasureSql(cube, measure);\n selectClauses.push(`${aggExpr} AS \"${measure}\"`);\n }\n }\n\n // Build WHERE clause\n const whereClauses: string[] = [];\n if (query.filters && query.filters.length > 0) {\n for (const filter of query.filters) {\n const colExpr = this.resolveFieldSql(cube, filter.member);\n const clause = this.buildFilterClause(colExpr, filter.operator, filter.values, params);\n if (clause) whereClauses.push(clause);\n }\n }\n\n // Build time dimension filters\n if (query.timeDimensions && query.timeDimensions.length > 0) {\n for (const td of query.timeDimensions) {\n const colExpr = this.resolveFieldSql(cube, td.dimension);\n if (td.dateRange) {\n const range = Array.isArray(td.dateRange) ? td.dateRange : [td.dateRange, td.dateRange];\n if (range.length === 2) {\n params.push(range[0], range[1]);\n whereClauses.push(`${colExpr} BETWEEN $${params.length - 1} AND $${params.length}`);\n }\n }\n }\n }\n\n const tableName = this.extractObjectName(cube);\n let sql = `SELECT ${selectClauses.join(', ')} FROM \"${tableName}\"`;\n if (whereClauses.length > 0) {\n sql += ` WHERE ${whereClauses.join(' AND ')}`;\n }\n if (groupByClauses.length > 0) {\n sql += ` GROUP BY ${groupByClauses.join(', ')}`;\n }\n if (query.order && Object.keys(query.order).length > 0) {\n const orderClauses = Object.entries(query.order).map(([f, d]) => `\"${f}\" ${d.toUpperCase()}`);\n sql += ` ORDER BY ${orderClauses.join(', ')}`;\n }\n if (query.limit != null) {\n sql += ` LIMIT ${query.limit}`;\n }\n if (query.offset != null) {\n sql += ` OFFSET ${query.offset}`;\n }\n\n return { sql, params };\n }\n\n // ── Helpers ──────────────────────────────────────────────────────\n\n private resolveDimensionSql(cube: Cube, member: string): string {\n const fieldName = member.includes('.') ? member.split('.')[1] : member;\n const dim = cube.dimensions[fieldName];\n return dim ? dim.sql : fieldName;\n }\n\n private resolveMeasureSql(cube: Cube, member: string): string {\n const fieldName = member.includes('.') ? member.split('.')[1] : member;\n const measure = cube.measures[fieldName];\n if (!measure) return `COUNT(*)`;\n\n const col = measure.sql;\n switch (measure.type) {\n case 'count': return 'COUNT(*)';\n case 'sum': return `SUM(${col})`;\n case 'avg': return `AVG(${col})`;\n case 'min': return `MIN(${col})`;\n case 'max': return `MAX(${col})`;\n case 'count_distinct': return `COUNT(DISTINCT ${col})`;\n default: return `COUNT(*)`;\n }\n }\n\n private resolveFieldSql(cube: Cube, member: string): string {\n const fieldName = member.includes('.') ? member.split('.')[1] : member;\n const dim = cube.dimensions[fieldName];\n if (dim) return dim.sql;\n const measure = cube.measures[fieldName];\n if (measure) return measure.sql;\n return fieldName;\n }\n\n private buildFilterClause(col: string, operator: string, values: string[] | undefined, params: unknown[]): string | null {\n const opMap: Record<string, string> = {\n equals: '=', notEquals: '!=', gt: '>', gte: '>=', lt: '<', lte: '<=',\n contains: 'LIKE', notContains: 'NOT LIKE',\n };\n\n if (operator === 'set') return `${col} IS NOT NULL`;\n if (operator === 'notSet') return `${col} IS NULL`;\n\n if (operator === 'in' || operator === 'notIn') {\n if (!values || values.length === 0) return null;\n const placeholders = values.map(v => { params.push(v); return `$${params.length}`; }).join(', ');\n return `${col} ${operator === 'in' ? 'IN' : 'NOT IN'} (${placeholders})`;\n }\n\n const sqlOp = opMap[operator];\n if (!sqlOp || !values || values.length === 0) return null;\n\n if (operator === 'contains' || operator === 'notContains') {\n params.push(`%${values[0]}%`);\n } else {\n params.push(values[0]);\n }\n return `${col} ${sqlOp} $${params.length}`;\n }\n\n private extractObjectName(cube: Cube): string {\n return cube.sql.trim();\n }\n\n private buildFieldMeta(query: AnalyticsQuery, cube: Cube): Array<{ name: string; type: string }> {\n const fields: Array<{ name: string; type: string }> = [];\n if (query.dimensions) {\n for (const dim of query.dimensions) {\n const fieldName = dim.includes('.') ? dim.split('.')[1] : dim;\n const d = cube.dimensions[fieldName];\n fields.push({ name: dim, type: d?.type || 'string' });\n }\n }\n if (query.measures) {\n for (const m of query.measures) {\n fields.push({ name: m, type: 'number' });\n }\n }\n return fields;\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { AnalyticsQuery, AnalyticsResult } from '@objectstack/spec/contracts';\nimport type { Cube } from '@objectstack/spec/data';\nimport type { AnalyticsStrategy, StrategyContext } from './types.js';\n\n/**\n * ObjectQLStrategy — Priority 2\n *\n * Translates an analytics query into an ObjectQL `engine.aggregate()` call.\n * This path works with any driver that supports the ObjectQL aggregate AST\n * (Postgres, Mongo, SQLite, etc.) without requiring raw SQL access.\n */\nexport class ObjectQLStrategy implements AnalyticsStrategy {\n readonly name = 'ObjectQLStrategy';\n readonly priority = 20;\n\n canHandle(query: AnalyticsQuery, ctx: StrategyContext): boolean {\n if (!query.cube) return false;\n const caps = ctx.queryCapabilities(query.cube);\n return caps.objectqlAggregate && typeof ctx.executeAggregate === 'function';\n }\n\n async execute(query: AnalyticsQuery, ctx: StrategyContext): Promise<AnalyticsResult> {\n const cube = ctx.getCube(query.cube!)!;\n const objectName = this.extractObjectName(cube);\n\n // Build groupBy from dimensions\n const groupBy: string[] = [];\n if (query.dimensions && query.dimensions.length > 0) {\n for (const dim of query.dimensions) {\n groupBy.push(this.resolveFieldName(cube, dim, 'dimension'));\n }\n }\n\n // Build aggregations from measures\n const aggregations: Array<{ field: string; method: string; alias: string }> = [];\n if (query.measures && query.measures.length > 0) {\n for (const measure of query.measures) {\n const { field, method } = this.resolveMeasureAggregation(cube, measure);\n aggregations.push({ field, method, alias: measure });\n }\n }\n\n // Build filter from query filters\n const filter: Record<string, unknown> = {};\n if (query.filters && query.filters.length > 0) {\n for (const f of query.filters) {\n const fieldName = this.resolveFieldName(cube, f.member, 'any');\n filter[fieldName] = this.convertFilter(f.operator, f.values);\n }\n }\n\n const rows = await ctx.executeAggregate!(objectName, {\n groupBy: groupBy.length > 0 ? groupBy : undefined,\n aggregations: aggregations.length > 0 ? aggregations : undefined,\n filter: Object.keys(filter).length > 0 ? filter : undefined,\n });\n\n // Remap short field names back to cube-qualified names\n const mappedRows = rows.map(row => {\n const mapped: Record<string, unknown> = {};\n if (query.dimensions) {\n for (const dim of query.dimensions) {\n const shortName = this.resolveFieldName(cube, dim, 'dimension');\n if (shortName in row) mapped[dim] = row[shortName];\n }\n }\n if (query.measures) {\n for (const m of query.measures) {\n // Alias was set to the full measure name\n if (m in row) mapped[m] = row[m];\n }\n }\n return mapped;\n });\n\n const fields = this.buildFieldMeta(query, cube);\n return { rows: mappedRows, fields };\n }\n\n async generateSql(query: AnalyticsQuery, ctx: StrategyContext): Promise<{ sql: string; params: unknown[] }> {\n const cube = ctx.getCube(query.cube!);\n if (!cube) {\n throw new Error(`Cube not found: ${query.cube}`);\n }\n\n // Generate a representative SQL even though ObjectQL uses AST internally\n const selectParts: string[] = [];\n const groupByParts: string[] = [];\n\n if (query.dimensions) {\n for (const dim of query.dimensions) {\n const col = this.resolveFieldName(cube, dim, 'dimension');\n selectParts.push(`${col} AS \"${dim}\"`);\n groupByParts.push(col);\n }\n }\n if (query.measures) {\n for (const m of query.measures) {\n const { field, method } = this.resolveMeasureAggregation(cube, m);\n const aggSql = method === 'count' ? 'COUNT(*)' : `${method.toUpperCase()}(${field})`;\n selectParts.push(`${aggSql} AS \"${m}\"`);\n }\n }\n\n const tableName = this.extractObjectName(cube);\n let sql = `SELECT ${selectParts.join(', ')} FROM \"${tableName}\"`;\n if (groupByParts.length > 0) {\n sql += ` GROUP BY ${groupByParts.join(', ')}`;\n }\n\n return { sql, params: [] };\n }\n\n // ── Helpers ──────────────────────────────────────────────────────\n\n private resolveFieldName(cube: Cube, member: string, kind: 'dimension' | 'measure' | 'any'): string {\n const fieldName = member.includes('.') ? member.split('.')[1] : member;\n if (kind === 'dimension' || kind === 'any') {\n const dim = cube.dimensions[fieldName];\n if (dim) return dim.sql.replace(/^\\$/, '');\n }\n if (kind === 'measure' || kind === 'any') {\n const measure = cube.measures[fieldName];\n if (measure) return measure.sql.replace(/^\\$/, '');\n }\n return fieldName;\n }\n\n private resolveMeasureAggregation(cube: Cube, measureName: string): { field: string; method: string } {\n const fieldName = measureName.includes('.') ? measureName.split('.')[1] : measureName;\n const direct = cube.measures[fieldName];\n if (direct) {\n return {\n field: direct.sql.replace(/^\\$/, ''),\n method: direct.type === 'count_distinct' ? 'count_distinct' : direct.type,\n };\n }\n // Accept `${field}_${type}` aliases (e.g. 'amount_sum') for measures whose\n // canonical name is just `${field}` (e.g. measure 'amount' of type 'sum').\n // This matches the convention used by clients that build measure names\n // from (field, function) pairs (e.g. the data-objectstack adapter).\n const aggTypes = ['count', 'sum', 'avg', 'min', 'max', 'count_distinct'];\n for (const type of aggTypes) {\n const suffix = `_${type}`;\n if (fieldName.endsWith(suffix)) {\n const baseField = fieldName.slice(0, -suffix.length);\n const candidate = cube.measures[baseField];\n if (candidate && candidate.type === type) {\n return {\n field: candidate.sql.replace(/^\\$/, ''),\n method: candidate.type === 'count_distinct' ? 'count_distinct' : candidate.type,\n };\n }\n }\n }\n return { field: '*', method: 'count' };\n }\n\n private convertFilter(operator: string, values?: string[]): unknown {\n if (operator === 'set') return { $ne: null };\n if (operator === 'notSet') return null;\n if (!values || values.length === 0) return undefined;\n\n switch (operator) {\n case 'equals': return values[0];\n case 'notEquals': return { $ne: values[0] };\n case 'gt': return { $gt: values[0] };\n case 'gte': return { $gte: values[0] };\n case 'lt': return { $lt: values[0] };\n case 'lte': return { $lte: values[0] };\n case 'contains': return { $regex: values[0] };\n case 'in': return { $in: values };\n case 'notIn': return { $nin: values };\n default: return values[0];\n }\n }\n\n private extractObjectName(cube: Cube): string {\n return cube.sql.trim();\n }\n\n private buildFieldMeta(query: AnalyticsQuery, cube: Cube): Array<{ name: string; type: string }> {\n const fields: Array<{ name: string; type: string }> = [];\n if (query.dimensions) {\n for (const dim of query.dimensions) {\n const fieldName = dim.includes('.') ? dim.split('.')[1] : dim;\n const d = cube.dimensions[fieldName];\n fields.push({ name: dim, type: d?.type || 'string' });\n }\n }\n if (query.measures) {\n for (const m of query.measures) {\n fields.push({ name: m, type: 'number' });\n }\n }\n return fields;\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport type { Cube } from '@objectstack/spec/data';\nimport type { IAnalyticsService } from '@objectstack/spec/contracts';\nimport { AnalyticsService } from './analytics-service.js';\nimport type { AnalyticsServiceConfig } from './analytics-service.js';\nimport type { DriverCapabilities } from './strategies/types.js';\n\n/**\n * Minimal IDataEngine surface required for the auto-bridge.\n * ObjectQL exposes `aggregate(object, { where, groupBy, aggregations: [{ function, field, alias }] })`.\n */\ninterface DataEngineLike {\n aggregate(object: string, options: {\n where?: Record<string, unknown>;\n groupBy?: string[];\n aggregations?: Array<{ function: string; field: string; alias: string }>;\n }): Promise<unknown[]>;\n}\n\n/**\n * Configuration for AnalyticsServicePlugin.\n */\nexport interface AnalyticsServicePluginOptions {\n /** Pre-defined cube definitions (from manifest). */\n cubes?: Cube[];\n /**\n * Probe driver capabilities for a given cube.\n * When omitted, defaults to in-memory only.\n */\n queryCapabilities?: (cubeName: string) => DriverCapabilities;\n /**\n * Execute raw SQL on a driver. Enables NativeSQLStrategy.\n */\n executeRawSql?: (objectName: string, sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>;\n /**\n * Execute ObjectQL aggregate. Enables ObjectQLStrategy.\n */\n executeAggregate?: (objectName: string, options: {\n groupBy?: string[];\n aggregations?: Array<{ field: string; method: string; alias: string }>;\n filter?: Record<string, unknown>;\n }) => Promise<Record<string, unknown>[]>;\n /** Enable debug logging. */\n debug?: boolean;\n}\n\n/**\n * AnalyticsServicePlugin — Kernel plugin for multi-driver analytics.\n *\n * Lifecycle:\n * 1. **init** — Creates `AnalyticsService`, registers as `'analytics'` service.\n * If an existing analytics service is already registered (e.g. MemoryAnalyticsService\n * from dev-plugin), it is captured as the `fallbackService`.\n * 2. **start** — Triggers `'analytics:ready'` hook so other plugins can\n * register cubes or extend the service.\n * 3. **destroy** — Cleans up references.\n *\n * @example\n * ```ts\n * import { LiteKernel } from '@objectstack/core';\n * import { AnalyticsServicePlugin } from '@objectstack/service-analytics';\n *\n * const kernel = new LiteKernel();\n * kernel.use(new AnalyticsServicePlugin({\n * cubes: [ordersCube],\n * queryCapabilities: (cube) => ({ nativeSql: true, objectqlAggregate: true, inMemory: false }),\n * executeRawSql: async (obj, sql, params) => pgPool.query(sql, params).then(r => r.rows),\n * }));\n * await kernel.bootstrap();\n *\n * const analytics = kernel.getService<IAnalyticsService>('analytics');\n * const result = await analytics.query({ cube: 'orders', measures: ['orders.count'] });\n * ```\n */\nexport class AnalyticsServicePlugin implements Plugin {\n name = 'com.objectstack.service-analytics';\n version = '1.0.0';\n type = 'standard' as const;\n dependencies: string[] = [];\n\n private service?: AnalyticsService;\n private readonly options: AnalyticsServicePluginOptions;\n\n constructor(options: AnalyticsServicePluginOptions = {}) {\n this.options = options;\n }\n\n async init(ctx: PluginContext): Promise<void> {\n // Check if there is an existing analytics service (e.g. from dev-plugin)\n let fallbackService: IAnalyticsService | undefined;\n try {\n const existing = ctx.getService<IAnalyticsService>('analytics');\n if (existing && typeof existing.query === 'function') {\n fallbackService = existing;\n ctx.logger.debug('[Analytics] Found existing analytics service, using as fallback');\n }\n } catch {\n // No existing service — that's fine\n }\n\n // Auto-bridge: when caller did not supply executeAggregate, look up the\n // kernel's IDataEngine (registered as 'data' by ObjectQLPlugin) lazily and\n // translate AnalyticsStrategy's `{method, filter}` shape into the engine's\n // `{function, where}` shape. This lets users write\n // `new AnalyticsServicePlugin({ cubes })`\n // without re-implementing the bridge in every app.\n let executeAggregate = this.options.executeAggregate;\n let autoBridged = false;\n if (!executeAggregate) {\n const tryGetDataEngine = (): DataEngineLike | undefined => {\n try {\n const svc = ctx.getService<DataEngineLike>('data');\n return svc && typeof svc.aggregate === 'function' ? svc : undefined;\n } catch {\n return undefined;\n }\n };\n // Probe now (warn if missing) but resolve at call time so plugin order\n // does not matter as long as 'data' exists by the time a query runs.\n if (!tryGetDataEngine()) {\n ctx.logger.warn(\n '[Analytics] No \"data\" service registered yet at init; ' +\n 'will retry per-query. Register ObjectQLPlugin or pass executeAggregate.',\n );\n }\n executeAggregate = async (objectName, { groupBy, aggregations, filter }) => {\n const engine = tryGetDataEngine();\n if (!engine) {\n throw new Error(\n '[Analytics] Cannot execute aggregate: no IDataEngine (\"data\") service is registered. ' +\n 'Add ObjectQLPlugin to the kernel or supply AnalyticsServicePlugin({ executeAggregate }).',\n );\n }\n const rows = await engine.aggregate(objectName, {\n where: filter,\n groupBy,\n aggregations: aggregations?.map((a) => ({\n function: a.method,\n field: a.field,\n alias: a.alias,\n })),\n });\n return rows as Record<string, unknown>[];\n };\n autoBridged = true;\n }\n\n // Default capabilities: when we have an aggregate bridge, advertise\n // ObjectQL support so ObjectQLStrategy is selected. Callers can still\n // override via options.queryCapabilities.\n const queryCapabilities = this.options.queryCapabilities\n ?? (() => ({\n nativeSql: !!this.options.executeRawSql,\n objectqlAggregate: !!executeAggregate,\n inMemory: false,\n }));\n\n const config: AnalyticsServiceConfig = {\n cubes: this.options.cubes,\n logger: ctx.logger,\n queryCapabilities,\n executeRawSql: this.options.executeRawSql,\n executeAggregate,\n fallbackService,\n };\n\n if (autoBridged) {\n ctx.logger.info('[Analytics] Auto-bridged executeAggregate → \"data\" service (IDataEngine)');\n }\n\n this.service = new AnalyticsService(config);\n\n // Register or replace the analytics service\n if (fallbackService) {\n ctx.replaceService('analytics', this.service);\n } else {\n ctx.registerService('analytics', this.service);\n }\n\n if (this.options.debug) {\n ctx.hook('analytics:beforeQuery', async (query: unknown) => {\n ctx.logger.debug('[Analytics] Before query', { query });\n });\n }\n\n ctx.logger.info('[Analytics] Service initialized');\n }\n\n async start(ctx: PluginContext): Promise<void> {\n if (!this.service) return;\n\n // Notify other plugins that analytics is ready\n await ctx.trigger('analytics:ready', this.service);\n\n ctx.logger.info(\n `[Analytics] Service started with ${this.service.cubeRegistry.size} cubes: ` +\n `${this.service.cubeRegistry.names().join(', ') || '(none)'}`,\n );\n }\n\n async destroy(): Promise<void> {\n this.service = undefined;\n }\n}\n"],"mappings":";AAUA,SAAS,oBAAoB;;;ACItB,IAAM,eAAN,MAAmB;AAAA,EAAnB;AACL,SAAQ,QAAQ,oBAAI,IAAkB;AAAA;AAAA;AAAA,EAGtC,SAAS,MAAkB;AACzB,SAAK,MAAM,IAAI,KAAK,MAAM,IAAI;AAAA,EAChC;AAAA;AAAA,EAGA,YAAY,OAAqB;AAC/B,eAAW,QAAQ,OAAO;AACxB,WAAK,SAAS,IAAI;AAAA,IACpB;AAAA,EACF;AAAA;AAAA,EAGA,IAAI,MAAgC;AAClC,WAAO,KAAK,MAAM,IAAI,IAAI;AAAA,EAC5B;AAAA;AAAA,EAGA,IAAI,MAAuB;AACzB,WAAO,KAAK,MAAM,IAAI,IAAI;AAAA,EAC5B;AAAA;AAAA,EAGA,SAAiB;AACf,WAAO,MAAM,KAAK,KAAK,MAAM,OAAO,CAAC;AAAA,EACvC;AAAA;AAAA,EAGA,QAAkB;AAChB,WAAO,MAAM,KAAK,KAAK,MAAM,KAAK,CAAC;AAAA,EACrC;AAAA;AAAA,EAGA,IAAI,OAAe;AACjB,WAAO,KAAK,MAAM;AAAA,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