react-semaphor 0.1.370 → 0.1.371

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 (52) hide show
  1. package/dist/analytics-protocol/index.cjs +1 -1
  2. package/dist/analytics-protocol/index.js +40 -38
  3. package/dist/chunks/{calendar-preferences-dialog-6q51A6XC.js → calendar-preferences-dialog-ClBAkMmF.js} +1 -1
  4. package/dist/chunks/{calendar-preferences-dialog-CUGzkNcE.js → calendar-preferences-dialog-Dn6o2r2Y.js} +1 -1
  5. package/dist/chunks/{dashboard-briefing-launcher-BEZnvIla.js → dashboard-briefing-launcher-BO-kXtEd.js} +1 -1
  6. package/dist/chunks/{dashboard-briefing-launcher-ptERmNJr.js → dashboard-briefing-launcher-D3Xfc_26.js} +3 -3
  7. package/dist/chunks/{dashboard-controls-CqKC5oEk.js → dashboard-controls-B3sdy_Zx.js} +3 -3
  8. package/dist/chunks/{dashboard-controls-CGt6_hMf.js → dashboard-controls-DcXMFgGR.js} +1 -1
  9. package/dist/chunks/{dashboard-json-6SgPm_QW.js → dashboard-json-BWfkEy48.js} +1 -1
  10. package/dist/chunks/{dashboard-json-CYSbOdmE.js → dashboard-json-CFURS_OR.js} +1 -1
  11. package/dist/chunks/{edit-dashboard-visual-w6hKbjlw.js → edit-dashboard-visual-BD2AJLiT.js} +1 -1
  12. package/dist/chunks/{edit-dashboard-visual-ByQx_M2i.js → edit-dashboard-visual-DjdhKiP2.js} +3 -3
  13. package/dist/chunks/{index-CPyEi9gS.js → index-C0Qnfr_7.js} +5 -4
  14. package/dist/chunks/{index-BtqYNH_S.js → index-DlLvzmJF.js} +2 -2
  15. package/dist/chunks/{resource-management-panel-Bf8-3eUf.js → resource-management-panel-DytUMSGA.js} +1 -1
  16. package/dist/chunks/{resource-management-panel-mJ84NxzC.js → resource-management-panel-YvIfaphX.js} +2 -2
  17. package/dist/chunks/{use-create-flow-overlay-state-BfoXDDrd.js → use-create-flow-overlay-state-BETXykC9.js} +2 -2
  18. package/dist/chunks/{use-create-flow-overlay-state-c6rCm36x.js → use-create-flow-overlay-state-CwIG1Ekp.js} +1 -1
  19. package/dist/chunks/{use-visual-utils-NN0e3fBP.js → use-visual-utils-Bk135OgA.js} +1 -1
  20. package/dist/chunks/{use-visual-utils-C_c-aiqi.js → use-visual-utils-BzFjIykb.js} +1 -1
  21. package/dist/chunks/{validation-PPSpYtVf.js → validation-CQFpcSSP.js} +295 -192
  22. package/dist/chunks/validation-D4Zz6WPD.js +1 -0
  23. package/dist/chunks/{validators-DBNa-eb1.js → validators-CuKnUZFO.js} +717 -345
  24. package/dist/chunks/validators-DHee9kM2.js +1 -0
  25. package/dist/dashboard/index.cjs +1 -1
  26. package/dist/dashboard/index.js +1 -1
  27. package/dist/dashboard-authoring/index.cjs +1 -1
  28. package/dist/dashboard-authoring/index.js +1 -1
  29. package/dist/data-app-builder/index.cjs +1 -1
  30. package/dist/data-app-builder/index.js +1 -1
  31. package/dist/data-app-sdk/index.cjs +1 -1
  32. package/dist/data-app-sdk/index.js +56 -49
  33. package/dist/data-app-sdk-validation/index.cjs +1 -1
  34. package/dist/data-app-sdk-validation/index.js +5 -4
  35. package/dist/index.cjs +1 -1
  36. package/dist/index.js +5 -5
  37. package/dist/surfboard/index.cjs +1 -1
  38. package/dist/surfboard/index.js +2 -2
  39. package/dist/types/analytics-protocol.d.ts +91 -0
  40. package/dist/types/dashboard-assistant.d.ts +60 -2
  41. package/dist/types/dashboard-authoring.d.ts +58 -2
  42. package/dist/types/dashboard.d.ts +67 -2
  43. package/dist/types/data-app-builder.d.ts +41 -0
  44. package/dist/types/data-app-sdk-validation.d.ts +50 -3
  45. package/dist/types/data-app-sdk.d.ts +53 -3
  46. package/dist/types/main.d.ts +59 -2
  47. package/dist/types/shared.d.ts +66 -2
  48. package/dist/types/surfboard.d.ts +67 -2
  49. package/dist/types/types.d.ts +67 -2
  50. package/package.json +1 -1
  51. package/dist/chunks/validation-DYL3ArlL.js +0 -1
  52. package/dist/chunks/validators-CgxWT8UX.js +0 -1
@@ -1083,8 +1083,14 @@ export declare const CALCULATED_FIELD_ENTITY_MARKER: "SEMAPHOR_CALCULATED_FIELD"
1083
1083
 
1084
1084
  /**
1085
1085
  * Formula metadata for calculated fields (UI-only metadata)
1086
- * This is supplementary data to help the UI display and edit calculated fields.
1087
- * The `expression` field remains the source of truth for the backend.
1086
+ * This is supplementary runtime/compiler data to help dashboard UI display,
1087
+ * edit, and execute calculated fields.
1088
+ *
1089
+ * Public source-level calculation metadata belongs in `Field.derivedField`
1090
+ * (`SemaphorDerivedFieldDefinition`). `calculatedFormula` deliberately uses
1091
+ * indexed `{field_N}` tokens and full runtime Field objects so current dashboard
1092
+ * query execution can resolve aliases, joins, filters, and aggregates without
1093
+ * doing catalog lookups.
1088
1094
  *
1089
1095
  * IMPORTANT: This metadata is ALWAYS updated atomically with the expression field.
1090
1096
  * Both are generated together from the same dialog inputs, preventing drift.
@@ -3257,6 +3263,15 @@ export declare interface Field {
3257
3263
  role?: 'groupby' | 'metric' | 'sortby' | 'pivotby' | 'detail';
3258
3264
  expression?: string;
3259
3265
  calculatedFormula?: CalculatedFieldFormula;
3266
+ /**
3267
+ * Public, source-level derived-field metadata for semantic/domain-authored
3268
+ * calculations. This is the AI/MCP/Data App-facing contract: named-token
3269
+ * expression, typed inputs, result role, and compute stage.
3270
+ *
3271
+ * Dashboard-local calculated fields may omit this because they are local
3272
+ * runtime artifacts rather than semantic-domain definitions.
3273
+ */
3274
+ derivedField?: SemaphorDerivedFieldDefinition;
3260
3275
  format?: FormatSpec;
3261
3276
  aggregate?: AggregateFunction;
3262
3277
  fieldScope?: FieldScope;
@@ -4441,6 +4456,44 @@ export declare const SemaphorContextProvider: ({ children, dashboardProps, }: {
4441
4456
  dashboardProps: DashboardProps;
4442
4457
  }) => JSX.Element;
4443
4458
 
4459
+ declare type SemaphorDerivedFieldAggregationBehavior = 'additive' | 'non_additive' | 'ratio_of_sums' | 'weighted' | 'pre_aggregated' | 'snapshot';
4460
+
4461
+ declare type SemaphorDerivedFieldAggregationStrategy = 'default' | 'symmetric_aggregate' | 'aggregate_then_join' | 'weighted';
4462
+
4463
+ declare type SemaphorDerivedFieldComputeStage = 'row' | 'aggregate';
4464
+
4465
+ declare type SemaphorDerivedFieldDefinition = {
4466
+ kind: 'derived_field';
4467
+ name: string;
4468
+ label: string;
4469
+ description?: string;
4470
+ resultRole: SemaphorDerivedFieldResultRole;
4471
+ dataType: NonNullable<SemaphorFieldRef['dataType']>;
4472
+ computeStage: SemaphorDerivedFieldComputeStage;
4473
+ expression: string;
4474
+ expressionLanguage?: 'semaphor_sql_template';
4475
+ inputs: Record<string, SemaphorDerivedFieldInput>;
4476
+ defaultAggregate?: SemaphorAggregateFunction;
4477
+ aggregationBehavior?: SemaphorDerivedFieldAggregationBehavior;
4478
+ aggregationStrategy?: SemaphorDerivedFieldAggregationStrategy;
4479
+ format?: unknown;
4480
+ tags?: string[];
4481
+ };
4482
+
4483
+ declare type SemaphorDerivedFieldInput = {
4484
+ kind: 'field';
4485
+ field: SemaphorFieldRef;
4486
+ aggregate?: SemaphorAggregateFunction;
4487
+ } | {
4488
+ kind: 'metric';
4489
+ metric: SemaphorFieldRef;
4490
+ } | {
4491
+ kind: 'dimension';
4492
+ dimension: SemaphorFieldRef;
4493
+ };
4494
+
4495
+ declare type SemaphorDerivedFieldResultRole = 'measure' | 'group' | 'date' | 'id' | 'filter';
4496
+
4444
4497
  declare type SemaphorDialect = 'postgres' | 'mysql' | 'mssql' | 'snowflake' | 'clickhouse' | 'bigquery' | 'redshift' | 'duckdb' | 'sqlite' | 'unknown';
4445
4498
 
4446
4499
  /**
@@ -4479,6 +4532,7 @@ declare type SemaphorInputOptionsIntent = {
4479
4532
  field: SemaphorFieldRef;
4480
4533
  search?: string;
4481
4534
  limit?: number;
4535
+ derivedFields?: SemaphorDerivedFieldDefinition[];
4482
4536
  };
4483
4537
 
4484
4538
  declare type SemaphorMatrixAxisExpansionOptions = {
@@ -4655,6 +4709,7 @@ declare type SemaphorMetricIntent = {
4655
4709
  };
4656
4710
  inputs?: SemaphorInputBinding[];
4657
4711
  limit?: number;
4712
+ derivedFields?: SemaphorDerivedFieldDefinition[];
4658
4713
  };
4659
4714
 
4660
4715
  declare type SemaphorPaginationRequest = {
@@ -4688,6 +4743,7 @@ declare type SemaphorRecordsIntent = {
4688
4743
  direction: 'asc' | 'desc';
4689
4744
  };
4690
4745
  inputs?: SemaphorInputBinding[];
4746
+ derivedFields?: SemaphorDerivedFieldDefinition[];
4691
4747
  };
4692
4748
 
4693
4749
  declare type SemaphorRelativeTimeWindow = {
@@ -5538,6 +5594,7 @@ export declare type TDataColumn = {
5538
5594
  role?: 'groupby' | 'metric' | 'sortby' | 'pivotby' | 'detail';
5539
5595
  expression?: string;
5540
5596
  calculatedFormula?: CalculatedFieldFormula;
5597
+ derivedField?: SemaphorDerivedFieldDefinition;
5541
5598
  format?: FormatSpec;
5542
5599
  sourceField?: string;
5543
5600
  aggregate?: AggregateFunction;
@@ -73,8 +73,14 @@ declare type CacheConfig = {
73
73
 
74
74
  /**
75
75
  * Formula metadata for calculated fields (UI-only metadata)
76
- * This is supplementary data to help the UI display and edit calculated fields.
77
- * The `expression` field remains the source of truth for the backend.
76
+ * This is supplementary runtime/compiler data to help dashboard UI display,
77
+ * edit, and execute calculated fields.
78
+ *
79
+ * Public source-level calculation metadata belongs in `Field.derivedField`
80
+ * (`SemaphorDerivedFieldDefinition`). `calculatedFormula` deliberately uses
81
+ * indexed `{field_N}` tokens and full runtime Field objects so current dashboard
82
+ * query execution can resolve aliases, joins, filters, and aggregates without
83
+ * doing catalog lookups.
78
84
  *
79
85
  * IMPORTANT: This metadata is ALWAYS updated atomically with the expression field.
80
86
  * Both are generated together from the same dialog inputs, preventing drift.
@@ -1047,6 +1053,15 @@ declare interface Field {
1047
1053
  role?: 'groupby' | 'metric' | 'sortby' | 'pivotby' | 'detail';
1048
1054
  expression?: string;
1049
1055
  calculatedFormula?: CalculatedFieldFormula;
1056
+ /**
1057
+ * Public, source-level derived-field metadata for semantic/domain-authored
1058
+ * calculations. This is the AI/MCP/Data App-facing contract: named-token
1059
+ * expression, typed inputs, result role, and compute stage.
1060
+ *
1061
+ * Dashboard-local calculated fields may omit this because they are local
1062
+ * runtime artifacts rather than semantic-domain definitions.
1063
+ */
1064
+ derivedField?: SemaphorDerivedFieldDefinition;
1050
1065
  format?: FormatSpec;
1051
1066
  aggregate?: AggregateFunction;
1052
1067
  fieldScope?: FieldScope;
@@ -1557,8 +1572,57 @@ declare type SelectedEntities = SelectedEntity[];
1557
1572
 
1558
1573
  declare type SelectedEntity = DatabaseEntityReference | DataModelEntityReference | DatasetEntityReference | FileEntityReference;
1559
1574
 
1575
+ declare type SemaphorAggregateFunction = 'SUM' | 'COUNT' | 'AVG' | 'MIN' | 'MAX' | 'MEDIAN' | 'DISTINCT';
1576
+
1577
+ declare type SemaphorDerivedFieldAggregationBehavior = 'additive' | 'non_additive' | 'ratio_of_sums' | 'weighted' | 'pre_aggregated' | 'snapshot';
1578
+
1579
+ declare type SemaphorDerivedFieldAggregationStrategy = 'default' | 'symmetric_aggregate' | 'aggregate_then_join' | 'weighted';
1580
+
1581
+ declare type SemaphorDerivedFieldComputeStage = 'row' | 'aggregate';
1582
+
1583
+ declare type SemaphorDerivedFieldDefinition = {
1584
+ kind: 'derived_field';
1585
+ name: string;
1586
+ label: string;
1587
+ description?: string;
1588
+ resultRole: SemaphorDerivedFieldResultRole;
1589
+ dataType: NonNullable<SemaphorFieldRef['dataType']>;
1590
+ computeStage: SemaphorDerivedFieldComputeStage;
1591
+ expression: string;
1592
+ expressionLanguage?: 'semaphor_sql_template';
1593
+ inputs: Record<string, SemaphorDerivedFieldInput>;
1594
+ defaultAggregate?: SemaphorAggregateFunction;
1595
+ aggregationBehavior?: SemaphorDerivedFieldAggregationBehavior;
1596
+ aggregationStrategy?: SemaphorDerivedFieldAggregationStrategy;
1597
+ format?: unknown;
1598
+ tags?: string[];
1599
+ };
1600
+
1601
+ declare type SemaphorDerivedFieldInput = {
1602
+ kind: 'field';
1603
+ field: SemaphorFieldRef;
1604
+ aggregate?: SemaphorAggregateFunction;
1605
+ } | {
1606
+ kind: 'metric';
1607
+ metric: SemaphorFieldRef;
1608
+ } | {
1609
+ kind: 'dimension';
1610
+ dimension: SemaphorFieldRef;
1611
+ };
1612
+
1613
+ declare type SemaphorDerivedFieldResultRole = 'measure' | 'group' | 'date' | 'id' | 'filter';
1614
+
1560
1615
  declare type SemaphorDialect = 'postgres' | 'mysql' | 'mssql' | 'snowflake' | 'clickhouse' | 'bigquery' | 'redshift' | 'duckdb' | 'sqlite' | 'unknown';
1561
1616
 
1617
+ declare type SemaphorFieldRef = {
1618
+ name: string;
1619
+ label?: string;
1620
+ role?: 'dimension' | 'measure' | 'date' | 'id' | 'unknown';
1621
+ dataType?: 'string' | 'number' | 'boolean' | 'date' | 'datetime' | 'unknown';
1622
+ source?: SemaphorSourceRef;
1623
+ aggregate?: SemaphorAggregateFunction;
1624
+ };
1625
+
1562
1626
  declare type SemaphorSourceRef = {
1563
1627
  kind: 'semantic';
1564
1628
  domainId: string;
@@ -158,8 +158,14 @@ export declare type CacheConfig = {
158
158
 
159
159
  /**
160
160
  * Formula metadata for calculated fields (UI-only metadata)
161
- * This is supplementary data to help the UI display and edit calculated fields.
162
- * The `expression` field remains the source of truth for the backend.
161
+ * This is supplementary runtime/compiler data to help dashboard UI display,
162
+ * edit, and execute calculated fields.
163
+ *
164
+ * Public source-level calculation metadata belongs in `Field.derivedField`
165
+ * (`SemaphorDerivedFieldDefinition`). `calculatedFormula` deliberately uses
166
+ * indexed `{field_N}` tokens and full runtime Field objects so current dashboard
167
+ * query execution can resolve aliases, joins, filters, and aggregates without
168
+ * doing catalog lookups.
163
169
  *
164
170
  * IMPORTANT: This metadata is ALWAYS updated atomically with the expression field.
165
171
  * Both are generated together from the same dialog inputs, preventing drift.
@@ -1298,6 +1304,15 @@ declare interface Field {
1298
1304
  role?: 'groupby' | 'metric' | 'sortby' | 'pivotby' | 'detail';
1299
1305
  expression?: string;
1300
1306
  calculatedFormula?: CalculatedFieldFormula;
1307
+ /**
1308
+ * Public, source-level derived-field metadata for semantic/domain-authored
1309
+ * calculations. This is the AI/MCP/Data App-facing contract: named-token
1310
+ * expression, typed inputs, result role, and compute stage.
1311
+ *
1312
+ * Dashboard-local calculated fields may omit this because they are local
1313
+ * runtime artifacts rather than semantic-domain definitions.
1314
+ */
1315
+ derivedField?: SemaphorDerivedFieldDefinition;
1301
1316
  format?: FormatSpec;
1302
1317
  aggregate?: AggregateFunction;
1303
1318
  fieldScope?: FieldScope;
@@ -1917,8 +1932,57 @@ declare type SemanticExecutionPayload = {
1917
1932
  }>;
1918
1933
  };
1919
1934
 
1935
+ declare type SemaphorAggregateFunction = 'SUM' | 'COUNT' | 'AVG' | 'MIN' | 'MAX' | 'MEDIAN' | 'DISTINCT';
1936
+
1937
+ declare type SemaphorDerivedFieldAggregationBehavior = 'additive' | 'non_additive' | 'ratio_of_sums' | 'weighted' | 'pre_aggregated' | 'snapshot';
1938
+
1939
+ declare type SemaphorDerivedFieldAggregationStrategy = 'default' | 'symmetric_aggregate' | 'aggregate_then_join' | 'weighted';
1940
+
1941
+ declare type SemaphorDerivedFieldComputeStage = 'row' | 'aggregate';
1942
+
1943
+ declare type SemaphorDerivedFieldDefinition = {
1944
+ kind: 'derived_field';
1945
+ name: string;
1946
+ label: string;
1947
+ description?: string;
1948
+ resultRole: SemaphorDerivedFieldResultRole;
1949
+ dataType: NonNullable<SemaphorFieldRef['dataType']>;
1950
+ computeStage: SemaphorDerivedFieldComputeStage;
1951
+ expression: string;
1952
+ expressionLanguage?: 'semaphor_sql_template';
1953
+ inputs: Record<string, SemaphorDerivedFieldInput>;
1954
+ defaultAggregate?: SemaphorAggregateFunction;
1955
+ aggregationBehavior?: SemaphorDerivedFieldAggregationBehavior;
1956
+ aggregationStrategy?: SemaphorDerivedFieldAggregationStrategy;
1957
+ format?: unknown;
1958
+ tags?: string[];
1959
+ };
1960
+
1961
+ declare type SemaphorDerivedFieldInput = {
1962
+ kind: 'field';
1963
+ field: SemaphorFieldRef;
1964
+ aggregate?: SemaphorAggregateFunction;
1965
+ } | {
1966
+ kind: 'metric';
1967
+ metric: SemaphorFieldRef;
1968
+ } | {
1969
+ kind: 'dimension';
1970
+ dimension: SemaphorFieldRef;
1971
+ };
1972
+
1973
+ declare type SemaphorDerivedFieldResultRole = 'measure' | 'group' | 'date' | 'id' | 'filter';
1974
+
1920
1975
  declare type SemaphorDialect = 'postgres' | 'mysql' | 'mssql' | 'snowflake' | 'clickhouse' | 'bigquery' | 'redshift' | 'duckdb' | 'sqlite' | 'unknown';
1921
1976
 
1977
+ declare type SemaphorFieldRef = {
1978
+ name: string;
1979
+ label?: string;
1980
+ role?: 'dimension' | 'measure' | 'date' | 'id' | 'unknown';
1981
+ dataType?: 'string' | 'number' | 'boolean' | 'date' | 'datetime' | 'unknown';
1982
+ source?: SemaphorSourceRef;
1983
+ aggregate?: SemaphorAggregateFunction;
1984
+ };
1985
+
1922
1986
  declare type SemaphorSourceRef = {
1923
1987
  kind: 'semantic';
1924
1988
  domainId: string;
@@ -2578,6 +2642,7 @@ export declare type TDataColumn = {
2578
2642
  role?: 'groupby' | 'metric' | 'sortby' | 'pivotby' | 'detail';
2579
2643
  expression?: string;
2580
2644
  calculatedFormula?: CalculatedFieldFormula;
2645
+ derivedField?: SemaphorDerivedFieldDefinition;
2581
2646
  format?: FormatSpec;
2582
2647
  sourceField?: string;
2583
2648
  aggregate?: AggregateFunction;
@@ -571,8 +571,14 @@ export declare const CALCULATED_FIELD_ENTITY_MARKER: "SEMAPHOR_CALCULATED_FIELD"
571
571
 
572
572
  /**
573
573
  * Formula metadata for calculated fields (UI-only metadata)
574
- * This is supplementary data to help the UI display and edit calculated fields.
575
- * The `expression` field remains the source of truth for the backend.
574
+ * This is supplementary runtime/compiler data to help dashboard UI display,
575
+ * edit, and execute calculated fields.
576
+ *
577
+ * Public source-level calculation metadata belongs in `Field.derivedField`
578
+ * (`SemaphorDerivedFieldDefinition`). `calculatedFormula` deliberately uses
579
+ * indexed `{field_N}` tokens and full runtime Field objects so current dashboard
580
+ * query execution can resolve aliases, joins, filters, and aggregates without
581
+ * doing catalog lookups.
576
582
  *
577
583
  * IMPORTANT: This metadata is ALWAYS updated atomically with the expression field.
578
584
  * Both are generated together from the same dialog inputs, preventing drift.
@@ -1846,6 +1852,15 @@ export declare interface Field {
1846
1852
  role?: 'groupby' | 'metric' | 'sortby' | 'pivotby' | 'detail';
1847
1853
  expression?: string;
1848
1854
  calculatedFormula?: CalculatedFieldFormula;
1855
+ /**
1856
+ * Public, source-level derived-field metadata for semantic/domain-authored
1857
+ * calculations. This is the AI/MCP/Data App-facing contract: named-token
1858
+ * expression, typed inputs, result role, and compute stage.
1859
+ *
1860
+ * Dashboard-local calculated fields may omit this because they are local
1861
+ * runtime artifacts rather than semantic-domain definitions.
1862
+ */
1863
+ derivedField?: SemaphorDerivedFieldDefinition;
1849
1864
  format?: FormatSpec;
1850
1865
  aggregate?: AggregateFunction;
1851
1866
  fieldScope?: FieldScope;
@@ -2677,8 +2692,57 @@ declare type SemanticExecutionPayload = {
2677
2692
  }>;
2678
2693
  };
2679
2694
 
2695
+ declare type SemaphorAggregateFunction = 'SUM' | 'COUNT' | 'AVG' | 'MIN' | 'MAX' | 'MEDIAN' | 'DISTINCT';
2696
+
2697
+ declare type SemaphorDerivedFieldAggregationBehavior = 'additive' | 'non_additive' | 'ratio_of_sums' | 'weighted' | 'pre_aggregated' | 'snapshot';
2698
+
2699
+ declare type SemaphorDerivedFieldAggregationStrategy = 'default' | 'symmetric_aggregate' | 'aggregate_then_join' | 'weighted';
2700
+
2701
+ declare type SemaphorDerivedFieldComputeStage = 'row' | 'aggregate';
2702
+
2703
+ declare type SemaphorDerivedFieldDefinition = {
2704
+ kind: 'derived_field';
2705
+ name: string;
2706
+ label: string;
2707
+ description?: string;
2708
+ resultRole: SemaphorDerivedFieldResultRole;
2709
+ dataType: NonNullable<SemaphorFieldRef['dataType']>;
2710
+ computeStage: SemaphorDerivedFieldComputeStage;
2711
+ expression: string;
2712
+ expressionLanguage?: 'semaphor_sql_template';
2713
+ inputs: Record<string, SemaphorDerivedFieldInput>;
2714
+ defaultAggregate?: SemaphorAggregateFunction;
2715
+ aggregationBehavior?: SemaphorDerivedFieldAggregationBehavior;
2716
+ aggregationStrategy?: SemaphorDerivedFieldAggregationStrategy;
2717
+ format?: unknown;
2718
+ tags?: string[];
2719
+ };
2720
+
2721
+ declare type SemaphorDerivedFieldInput = {
2722
+ kind: 'field';
2723
+ field: SemaphorFieldRef;
2724
+ aggregate?: SemaphorAggregateFunction;
2725
+ } | {
2726
+ kind: 'metric';
2727
+ metric: SemaphorFieldRef;
2728
+ } | {
2729
+ kind: 'dimension';
2730
+ dimension: SemaphorFieldRef;
2731
+ };
2732
+
2733
+ declare type SemaphorDerivedFieldResultRole = 'measure' | 'group' | 'date' | 'id' | 'filter';
2734
+
2680
2735
  declare type SemaphorDialect = 'postgres' | 'mysql' | 'mssql' | 'snowflake' | 'clickhouse' | 'bigquery' | 'redshift' | 'duckdb' | 'sqlite' | 'unknown';
2681
2736
 
2737
+ declare type SemaphorFieldRef = {
2738
+ name: string;
2739
+ label?: string;
2740
+ role?: 'dimension' | 'measure' | 'date' | 'id' | 'unknown';
2741
+ dataType?: 'string' | 'number' | 'boolean' | 'date' | 'datetime' | 'unknown';
2742
+ source?: SemaphorSourceRef;
2743
+ aggregate?: SemaphorAggregateFunction;
2744
+ };
2745
+
2682
2746
  declare type SemaphorSourceRef = {
2683
2747
  kind: 'semantic';
2684
2748
  domainId: string;
@@ -3362,6 +3426,7 @@ export declare type TDataColumn = {
3362
3426
  role?: 'groupby' | 'metric' | 'sortby' | 'pivotby' | 'detail';
3363
3427
  expression?: string;
3364
3428
  calculatedFormula?: CalculatedFieldFormula;
3429
+ derivedField?: SemaphorDerivedFieldDefinition;
3365
3430
  format?: FormatSpec;
3366
3431
  sourceField?: string;
3367
3432
  aggregate?: AggregateFunction;
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "email": "support@semaphor.cloud"
6
6
  },
7
7
  "license": "MIT",
8
- "version": "0.1.370",
8
+ "version": "0.1.371",
9
9
  "description": "Fully interactive and customizable dashboards for your apps.",
10
10
  "keywords": [
11
11
  "react",
@@ -1 +0,0 @@
1
- "use strict";const M=require("./validators-CgxWT8UX.js"),u=require("./source-identity-C-xaeE_I.js");function I(e){var t;const r=E(e);return{version:1,kind:"metric",id:e.id,label:e.label,source:y(e),metrics:r,primaryMetric:K(e,r),dateField:e.dateField?a(e.dateField,"date"):void 0,timeGrain:e.timeGrain,dimensions:(t=e.dimensions)==null?void 0:t.map(i=>a(i,"dimension")),comparison:oe(e.comparison),orderBy:e.orderBy?{field:a(e.orderBy.field),direction:e.orderBy.direction}:void 0,inputs:f(e.inputs),limit:e.limit}}function x(e){var t;return{...I(e),...e.timeWindow?{timeWindow:e.timeWindow}:{},...(t=e.filters)!=null&&t.length?{filters:e.filters}:{},...e.analysis?{analysis:e.analysis}:{}}}function j(e){return{...e.chartTitle?{chartTitle:e.chartTitle}:{},...e.chartType?{chartType:e.chartType}:{},...e.driverMode?{driverMode:e.driverMode}:{},...e.includePopulation!==void 0?{includePopulation:e.includePopulation}:{},...e.calendarContext?{calendarContext:e.calendarContext}:{}}}function K(e,r){if(!e.primaryMetric)return r[0]||{name:"",role:"measure"};const t=a(e.primaryMetric,"measure"),i=W(t,r),o=i.length===1?i[0]:void 0;return o?$(t,o):t}function E(e){const r=[];for(const t of e.metrics.map(i=>a(i,"measure"))){if(!t.name)continue;const i=r.findIndex(o=>N(o,t));if(i===-1){r.push(t);continue}r[i]=$(r[i],t)}return r}function N(e,r){return u.semaphorFieldRefsMatch(e,r)&&m(e)===m(r)}function V(e,r){return m(r)===m(e)}function L(e,r){return r.name!==e.name||e.source&&!u.semaphorFieldRefsMatch(r,e)?!1:V(e,r)}function W(e,r){const t=r.filter(i=>L(e,i));return e.aggregate!==void 0,t}function m(e){return(e.aggregate||"SUM").toUpperCase()}function $(e,r){if(e.aggregate&&r.aggregate&&e.aggregate!==r.aggregate)throw new Error(`Metric "${e.name}" was requested with conflicting aggregate semantics: ${e.aggregate} and ${r.aggregate}.`);return{...u.preferSemaphorFieldRefMetadata(e,r),aggregate:e.aggregate||r.aggregate}}function _(e){var t;if("sort"in e)throw new Error("semaphor.records supports orderBy for a single deterministic sort. Multiple sort clauses are not supported by the analytics protocol yet.");if(!ie(e))throw new Error("semaphor.records needs at least one field.");const r=U(e.fields);return{version:1,kind:"records",id:e.id,label:e.label,source:y(e),fields:r,dateField:e.dateField?a(e.dateField,"date"):void 0,timeGrain:e.timeGrain,...e.timeWindow?{timeWindow:e.timeWindow}:{},...(t=e.filters)!=null&&t.length?{filters:e.filters}:{},orderBy:e.orderBy?{field:a(e.orderBy.field),direction:e.orderBy.direction}:void 0,inputs:f(e.inputs),limit:e.limit,...e.pagination?{pagination:e.pagination}:{}}}function U(e){return e.map(r=>{const t=a(r);if(!t.role)throw new Error(`semaphor.records field "${t.name}" needs an explicit role.`);return t})}function C(e){return{version:1,kind:"inputOptions",id:e.id,label:e.label,source:y(e),field:a(e.field,"dimension"),search:e.search,limit:e.limit}}function R(e){var r;return{version:1,kind:"sql",id:e.id,label:e.label,source:e.source,sql:e.sql,...e.defaultParameters?{defaultParameters:e.defaultParameters}:{},...e.pythonCode?{pythonCode:e.pythonCode}:{},...(r=e.fields)!=null&&r.length?{fields:e.fields.map(t=>a(t))}:{},inputs:f(e.inputs),limit:e.limit,...e.pagination?{pagination:e.pagination}:{},rationale:e.rationale}}function F(e){var r,t;return{version:1,kind:"matrix",id:e.id,label:e.label,source:y(e),rows:e.rows.map(i=>q(i,"dimension")),...e.columns?{columns:e.columns.map(i=>q(i,"dimension"))}:{},values:e.values.map(G),...(r=e.filters)!=null&&r.length?{filters:e.filters}:{},inputs:f(e.inputs),...e.totals?{totals:e.totals}:{},...(t=e.sort)!=null&&t.length?{sort:e.sort}:{},...e.expansion?{expansion:e.expansion}:{},...e.layout?{layout:e.layout}:{},...e.displayLimits?{displayLimits:e.displayLimits}:{}}}function q(e,r){return J(e)?{...e,field:a(e.field,r)}:{field:a(e,r)}}function G(e){return X(e)?{...e,field:a(e.field,"measure")}:{field:a(e,"measure"),aggregate:e.aggregate}}function J(e){return"field"in e}function X(e){return"field"in e}function T(e){if("toAnalyticsInput"in e){const n=e.toAnalyticsInput();return{inputId:n.inputId,kind:n.kind,...n.controlRole?{controlRole:n.controlRole}:{},...n.operator?{operator:n.operator}:{},...n.field?{field:n.field}:{}}}if("id"in e){const n=S(e);return{inputId:n.inputId,kind:n.kind,...n.controlRole?{controlRole:n.controlRole}:{},...n.operator?{operator:n.operator}:{},...n.field?{field:n.field}:{}}}const r="kind"in e?e.kind:void 0,t="operator"in e?H(e.operator,e.inputId):void 0,i="controlRole"in e?e.controlRole:"role"in e?e.role:void 0,o=Y(i)?i:void 0;return{inputId:e.inputId,...r?{kind:r}:{},...o?{controlRole:o}:{},...t?{operator:t}:{},...e.field?{field:e.field}:{}}}function Y(e){return e==="grain"||e==="metric"||e==="dimension"||e==="aggregation"||e==="sqlParam"}function Z(e){const r=f(e);return r.length>0?r:void 0}function P(e){return(e||[]).map(te)}function ee(e){return P(e).filter(r=>r.isActive)}function S(e){if(e.kind==="filter"){const r=H(e.operator,e.id);return{inputId:e.id,kind:e.kind,label:e.label,field:a(e.field,"dimension"),operator:r||"in"}}return{inputId:e.id,kind:e.kind,label:e.label,controlRole:e.role}}function re(e=[]){return e.map(r=>typeof r=="object"?r:{label:String(r),value:r})}function g(e){return e==null?!1:Array.isArray(e)?e.length>0:typeof e=="string"?e.trim().length>0:!0}function te(e){if("toAnalyticsInput"in e)return e.toAnalyticsInput();if("kind"in e&&"isActive"in e)return e;if("id"in e){const r=S(e),t=Object.prototype.hasOwnProperty.call(e,"value")?e.value:e.defaultValue;return{inputId:r.inputId,kind:r.kind,label:r.label,...r.field?{field:r.field}:{},...r.operator?{operator:r.operator}:{},...r.controlRole?{controlRole:r.controlRole}:{},value:t,isActive:g(t)}}return{...e,kind:"filter",isActive:g(e.value),value:e.value}}function y(e){return e.source}function ie(e){var r;return!!((r=e.fields)!=null&&r.length)}function a(e,r){return{...e,role:e.role||r}}function f(e){return(e||[]).map(T)}function oe(e){if(e)return e}function H(e,r){if(e===void 0)return;const t=M.normalizeSemaphorInputOperator(e);if(!t)throw new Error(`useSemaphorInput "${r}" uses unsupported filter operator "${e}".`);return t}function B(e,r={}){const t=r.pathPrefix||"analysisOptions";if(e===void 0)return{ok:!0};if(!e||typeof e!="object"||Array.isArray(e))return s(t,"Data App analysis options must be an object.");const i=e,o={};if(i.chartTitle!==void 0){if(typeof i.chartTitle!="string")return s(`${t}.chartTitle`,'Data App analysis option "chartTitle" must be a string.');o.chartTitle=i.chartTitle}if(i.chartType!==void 0){if(typeof i.chartType!="string")return s(`${t}.chartType`,'Data App analysis option "chartType" must be a string.');o.chartType=i.chartType}if(i.driverMode!==void 0){if(!se(i.driverMode))return s(`${t}.driverMode`,'Data App analysis option "driverMode" must be absolute_delta, largest_negative, largest_positive, positive_and_negative, or all.');o.driverMode=i.driverMode}if(i.includePopulation!==void 0){if(typeof i.includePopulation!="boolean")return s(`${t}.includePopulation`,'Data App analysis option "includePopulation" must be a boolean.');o.includePopulation=i.includePopulation}if(i.calendarContext!==void 0){const n=le(i.calendarContext,{pathPrefix:`${t}.calendarContext`,validateTimezone:r.validateTimezone});if(!n.ok)return n;o.calendarContext=n.calendarContext}return{ok:!0,analysisOptions:o}}function ne(e){const r=e.queries.map((o,n)=>ae(o,n,{fieldCatalogs:e.fieldCatalogs||[],requireFieldCatalog:!!e.requireFieldCatalog,validateTimezone:e.validateTimezone})),t=r.flatMap(o=>o.diagnostics),i=r.map(o=>o.executionResult);return{ok:t.every(o=>o.severity!=="error"),diagnostics:t,queries:r,intents:r.flatMap(o=>o.intent?[o.intent]:[]),executionResults:i}}function ae(e,r,t){const i=`queries.${r}`;try{const o=ue(e),n=qe(e,o),d=M.validateSemaphorAnalyticsIntent(o),l=[...he({querySpec:e,queryId:n,intent:o,pathPrefix:i}),...d.errors.map(h=>k(h,{queryHook:e.queryHook,queryId:n,pathPrefix:i,severity:"error",intent:o})),...d.warnings.map(h=>k(h,{queryHook:e.queryHook,queryId:n,pathPrefix:i,severity:"warning",intent:o})),...ce({querySpec:e,queryId:n,intent:o,pathPrefix:i,fieldCatalogs:t.fieldCatalogs,requireFieldCatalog:t.requireFieldCatalog}),...ye({querySpec:e,queryId:n,intent:o,pathPrefix:i,validateTimezone:t.validateTimezone})],c=Se(d,l);return{queryHook:e.queryHook,queryId:n,intent:o,diagnostics:l,executionResult:A({intent:o,validation:c,diagnostics:l})}}catch(o){const n={severity:"error",code:"invalid_query_spec",message:o instanceof Error?o.message:String(o),path:i,queryHook:e.queryHook,queryId:Q(e.spec)},d=D([n]);return{queryHook:e.queryHook,queryId:n.queryId,diagnostics:[n],executionResult:A({validation:d,diagnostics:[n]})}}}function s(e,r){return{ok:!1,issues:[{code:"invalid_analysis_option",message:r,path:e}]}}function z(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function se(e){return e==="absolute_delta"||e==="largest_negative"||e==="largest_positive"||e==="positive_and_negative"||e==="all"}function de(e){return e.trim().length>0&&!Number.isNaN(Date.parse(e))}function le(e,r){var c;if(!e||typeof e!="object"||Array.isArray(e))return s(r.pathPrefix,'Data App analysis option "calendarContext" must be an object.');const t=e,i=t.tz,o=t.weekStart,n=t.anchor,d=n&&typeof n=="object"&&!Array.isArray(n)?n.iso:void 0,l=typeof i=="string"?((c=r.validateTimezone)==null?void 0:c.call(r,i))??i:null;return l?typeof o!="number"||!Number.isInteger(o)||o<0||o>6?s(`${r.pathPrefix}.weekStart`,'Data App analysis option "calendarContext.weekStart" must be an integer from 0 to 6.'):n!=="now"&&!(typeof d=="string"&&de(d))?s(`${r.pathPrefix}.anchor`,'Data App analysis option "calendarContext.anchor" must be "now" or an object with a valid iso string.'):{ok:!0,calendarContext:{tz:l,weekStart:o,anchor:n}}:s(`${r.pathPrefix}.tz`,'Data App analysis option "calendarContext.tz" must be a valid timezone string.')}function ue(e){return fe(e.spec)}function fe(e){if(!z(e))throw new Error("useSemaphorQuery spec must be an object.");if(e.queryKind==="metric")return I(e);if(e.queryKind==="analysis")return x(e);if(e.queryKind==="records")return _(e);if(e.queryKind==="sql")return R(e);if(e.queryKind==="matrix")return F(e);if(e.queryKind==="inputOptions")return C(e);throw new Error("useSemaphorQuery spec.queryKind must be metric, analysis, records, inputOptions, sql, or matrix.")}function ce(e){if(e.intent.kind==="sql")return[];if(e.fieldCatalogs.length===0&&!e.requireFieldCatalog)return[];const r=ve(e.fieldCatalogs,e.intent.source);return r?[...me({...e,catalog:r}),...pe({...e,catalog:r})]:[{severity:"error",code:"invalid_source_ref",message:`Source ref for ${e.querySpec.queryHook} does not match a visible Semaphor source.`,path:`${e.pathPrefix}.spec.source`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:e.intent.source}]}function me(e){return ge(e.intent).flatMap(({field:r,path:t})=>O(e.catalog,r,e.intent.source)?[]:[{severity:"error",code:"missing_field",message:`Field "${r.name}" is not visible on the selected Semaphor source.`,path:`${e.pathPrefix}.${t}`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:p(r,e.intent.source),field:r}])}function pe(e){return("inputs"in e.intent?e.intent.inputs||[]:[]).flatMap((t,i)=>{if(!t.field)return[];const o=p(t.field,e.intent.source);return u.semaphorSourcesReferToSameDataset(o,e.intent.source)?O(e.catalog,t.field,e.intent.source)?[]:[{severity:"error",code:"missing_field",message:`Input "${t.inputId}" references field "${t.field.name}", which is not visible on the selected Semaphor source.`,path:`${e.pathPrefix}.spec.inputs.${i}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:o,field:t.field}]:[{severity:"error",code:"unsupported_input_filter_composition",message:`Input "${t.inputId}" filters a different Semaphor source than the query. Cross-source Data App inputs are not supported yet.`,path:`${e.pathPrefix}.spec.inputs.${i}.field`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:o,field:t.field}]})}function ye(e){if(e.querySpec.spec.queryKind!=="analysis")return[];const r=B(e.querySpec.spec,{pathPrefix:`${e.pathPrefix}.spec`,validateTimezone:e.validateTimezone});return r.ok?[]:r.issues.map(t=>({severity:"error",code:t.code,message:t.message,path:t.path,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id,source:e.intent.source}))}function he(e){return e.querySpec.spec.queryKind!=="sql"?[]:z(e.querySpec.spec)?Object.prototype.hasOwnProperty.call(e.querySpec.spec,"parameters")?[{severity:"error",code:"deprecated_sql_parameters",message:"semaphor.sql uses defaultParameters for static SQL param(...) fallback values. The legacy parameters field is not supported.",path:`${e.pathPrefix}.spec.parameters`,queryHook:e.querySpec.queryHook,queryId:e.queryId,intentId:e.intent.id}]:[]:[]}function ge(e){return e.kind==="metric"?[...e.metrics.map((r,t)=>({field:r,path:`spec.metrics.${t}`})),...e.primaryMetric?[{field:e.primaryMetric,path:"spec.primaryMetric"}]:[],...e.dateField?[{field:e.dateField,path:"spec.dateField"}]:[],...(e.dimensions||[]).map((r,t)=>({field:r,path:`spec.dimensions.${t}`})),...e.orderBy?[{field:e.orderBy.field,path:"spec.orderBy.field"}]:[],...(e.filters||[]).map((r,t)=>({field:r.field,path:`spec.filters.${t}.field`}))]:e.kind==="records"?[...e.fields.map((r,t)=>({field:r,path:`spec.fields.${t}`})),...e.dateField?[{field:e.dateField,path:"spec.dateField"}]:[],...e.orderBy?[{field:e.orderBy.field,path:"spec.orderBy.field"}]:[],...(e.filters||[]).map((r,t)=>({field:r.field,path:`spec.filters.${t}.field`}))]:e.kind==="inputOptions"?[{field:e.field,path:"spec.field"}]:e.kind==="matrix"?[...e.rows.map((r,t)=>({field:r.field,path:`spec.rows.${t}.field`})),...e.rows.flatMap((r,t)=>{var i;return((i=r.sortBy)==null?void 0:i.by.kind)==="field"?[{field:r.sortBy.by.field,path:`spec.rows.${t}.sortBy.by.field`}]:[]}),...(e.columns||[]).map((r,t)=>({field:r.field,path:`spec.columns.${t}.field`})),...(e.columns||[]).flatMap((r,t)=>{var i;return((i=r.sortBy)==null?void 0:i.by.kind)==="field"?[{field:r.sortBy.by.field,path:`spec.columns.${t}.sortBy.by.field`}]:[]}),...e.values.map((r,t)=>({field:r.field,path:`spec.values.${t}.field`})),...(e.sort||[]).flatMap((r,t)=>r.by.kind==="field"?[{field:r.by.field,path:`spec.sort.${t}.by.field`}]:[]),...(e.filters||[]).map((r,t)=>({field:r.field,path:`spec.filters.${t}.field`}))]:[]}function ve(e,r){return e.find(t=>v(t,r))}function O(e,r,t){const i=p(r,t);if(v(e,i))return e.fields.find(o=>Ie(o,r)&&v(e,p(o,e.source)))}function v(e,r){return[e.source,...e.sourceAliases||[]].some(t=>u.semaphorSourcesReferToSameDataset(t,r))}function p(e,r){return e.source||r}function Ie(e,r){return!!(e.name&&r.name&&e.name===r.name)}function k(e,r){return{severity:r.severity,code:e.code||"invalid_analytics_intent",message:e.message,path:e.path?`${r.pathPrefix}.spec.${e.path}`:r.pathPrefix,queryHook:r.queryHook,queryId:r.queryId,intentId:r.intent.id,source:r.intent.source}}function Se(e,r){const t=D(r);return{ok:t.ok&&e.ok,errors:w([...e.errors,...t.errors]),warnings:w([...e.warnings,...t.warnings]),repairHints:[...e.repairHints,...t.repairHints]}}function D(e){const r=e.filter(i=>i.severity==="error").map(b),t=e.filter(i=>i.severity==="warning").map(b);return{ok:r.length===0,errors:r,warnings:t,repairHints:r.map(i=>{var o,n;return{code:i.code,message:i.message,fieldRole:i.fieldRole,invalidField:(o=i.repairHint)==null?void 0:o.invalidField,recommendedNextStep:((n=i.repairHint)==null?void 0:n.recommendedNextStep)||"Update the Data App SDK query spec to use visible Semaphor source and field refs."}})}}function b(e){var r;return{code:e.code,message:e.message,path:e.path,fieldRole:e.code==="invalid_source_ref"?"source":void 0,repairHint:{code:e.code,message:e.message,invalidField:(r=e.field)==null?void 0:r.name,fieldRole:e.code==="invalid_source_ref"?"source":void 0,recommendedNextStep:e.code==="unsupported_input_filter_composition"?"Use an input field from the same Semaphor source as the query, or split the query into separate source-scoped queries.":"Update the query spec to use a visible Semaphor source and field ref."}}}function w(e){const r=new Set;return e.filter(t=>{const i=`${t.code}:${t.path||""}:${t.message}`;return r.has(i)?!1:(r.add(i),!0)})}function A(e){var t,i;const r=e.diagnostics.filter(o=>o.severity==="error");return{intentId:(t=e.intent)==null?void 0:t.id,status:r.length?"failed":"answered",resultShape:(i=e.intent)==null?void 0:i.kind,intent:e.intent,validation:e.validation,coverage:{answeredObligations:r.length?[]:["query_spec_validation"],missingObligations:r.length?["query_spec_validation"]:[],warnings:e.validation.warnings},missingFields:r.filter(o=>o.code==="missing_field").flatMap(o=>{var n;return(n=o.field)!=null&&n.name?[o.field.name]:[]}),warnings:e.diagnostics.filter(o=>o.severity==="warning").map(o=>o.message),metadata:{validationKind:"data_app_sdk_query_spec"}}}function qe(e,r){return r.id||Q(e.spec)}function Q(e){if(!e||typeof e!="object"||!("id"in e))return;const r=e.id;return typeof r=="string"&&r.trim()?r:void 0}exports.hasSemaphorInputValue=g;exports.normalizeSemaphorAnalysisQueryOptions=B;exports.normalizeSemaphorInputOptions=re;exports.toSemaphorActiveInputSnapshots=ee;exports.toSemaphorAnalysisIntent=x;exports.toSemaphorAnalysisQueryOptions=j;exports.toSemaphorInputBinding=T;exports.toSemaphorInputBindings=Z;exports.toSemaphorInputOptionsIntent=C;exports.toSemaphorInputSnapshots=P;exports.toSemaphorInputSpec=S;exports.toSemaphorMatrixIntent=F;exports.toSemaphorMetricIntent=I;exports.toSemaphorRecordsIntent=_;exports.toSemaphorSqlIntent=R;exports.validateSemaphorDataAppQuerySpecs=ne;
@@ -1 +0,0 @@
1
- "use strict";const G=require("./source-identity-C-xaeE_I.js");function Q(e){const i=D(e);return O(i)?i:void 0}function D(e){if(typeof e!="string"||e.trim().length===0)return;const i=e.trim().toLowerCase().replace(/_/g," ");switch(i){case"eq":case"equals":case"=":return"=";case"neq":case"not equals":case"not equal":case"!=":return"!=";case"in":return"in";case"not in":return"not_in";case"contains":case"like":return"contains";case"not contains":case"not like":return"not_contains";case"between":return"between";case"not between":return"not_between";case">":case">=":case"<":case"<=":return i;case"is null":return"is_null";case"is not null":return"is_not_null";default:return X(e)?e:void 0}}function O(e){return e==="="||e==="!="||e==="in"||e==="not_in"||e==="contains"||e==="not_contains"||e==="between"||e==="not_between"||e===">"||e===">="||e==="<"||e==="<="}function X(e){return O(e)||e==="not_contains"||e==="is_null"||e==="is_not_null"}function a(e,i,t){return t?{code:e,message:i,path:t}:{code:e,message:i}}function Y(e){for(let i=0;i<e.length;i+=1){const t=e[i];if(e.some((s,n)=>n!==i&&E(s,t)))return!1}return!0}function F(e,i){return G.semaphorFieldRefsMatch(e,i)}function E(e,i){return F(e,i)&&b(e)===b(i)}function Z(e){return`Metric intent has duplicate metric "${e.name}" with the same aggregate (${b(e)}). Use different aggregates to request both, or remove one entry.`}function N(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null}function J(e,i,t){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e)){t.push(a("invalid_sql_default_parameters","SQL defaultParameters must be an object keyed by parameter name.",i));return}Object.entries(e).forEach(([s,n])=>{if(!s.trim()){t.push(a("invalid_sql_default_parameter_name","SQL defaultParameters names must be non-empty strings.",`${i}.${s}`));return}(Array.isArray(n)?n.every(N):N(n))||t.push(a("invalid_sql_default_parameter_value","SQL defaultParameters values must be strings, numbers, booleans, nulls, or arrays of those scalar values.",`${i}.${s}`))})}}function K(e,i){return S(e,i).length===1}function W(e,i){return S(e,i).length===1}function S(e,i){return i.filter(s=>ee(e,s))}function ee(e,i){return ie(e,i)?e.source?F(i,e):!0:!1}function ie(e,i){return!(i.name!==e.name||e.role!==void 0&&i.role!==void 0&&i.role!==e.role||te(e,i)&&b(i)!==b(e))}function te(e,i){return e.role==="measure"||i.role==="measure"||e.aggregate!==void 0||i.aggregate!==void 0}function b(e){return(e.aggregate||"SUM").toUpperCase()}const ae=/^(\d{4})-(\d{2})-(\d{2})$/,ne=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})$/;function x(e){if(typeof e!="string")return null;const i=e.trim(),t=ae.exec(i);if(t){const[,v,I,P]=t;return q(v,I,P)?new Date(Date.UTC(Number(v),Number(I)-1,Number(P))):null}const s=ne.exec(i);if(!s)return null;const[,n,o,r,d,l,u="00",,p]=s;if(!q(n,o,r)||!_(d,0,23)||!_(l,0,59)||!_(u,0,59)||!se(p))return null;const h=new Date(i);return Number.isFinite(h.getTime())?h:null}function q(e,i,t){const s=Number(e),n=Number(i),o=Number(t);if(!Number.isInteger(s)||!Number.isInteger(n)||!Number.isInteger(o)||n<1||n>12)return!1;const r=new Date(Date.UTC(s,n-1,o));return r.getUTCFullYear()===s&&r.getUTCMonth()===n-1&&r.getUTCDate()===o}function _(e,i,t){const s=Number(e);return Number.isInteger(s)&&s>=i&&s<=t}function se(e){if(e==="Z")return!0;const i=/^([+-])(\d{2}):(\d{2})$/.exec(e);return!!(i&&_(i[2],0,23)&&_(i[3],0,59))}function c(e){return typeof e=="string"&&e.trim().length>0}function m(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function B(e,i,t){if(e!==void 0){if(!m(e)){t.push(a("invalid_pagination","Pagination must be an object with positive integer page and pageSize.",i));return}(!Number.isInteger(e.page)||typeof e.page!="number"||e.page<1)&&t.push(a("invalid_pagination_page","Pagination page must be a positive integer.",`${i}.page`)),(!Number.isInteger(e.pageSize)||typeof e.pageSize!="number"||e.pageSize<1)&&t.push(a("invalid_pagination_page_size","Pagination pageSize must be a positive integer.",`${i}.pageSize`))}}function w(e){const i=new Set;for(const t of e){if(i.has(t))return t;i.add(t)}return null}function g(e,i,t,s){w(e.filter(o=>c(o)))&&s.push(a("duplicate_matrix_public_id",`Matrix ${t} ids must be unique so sort and expansion references are unambiguous.`,i))}const re=new Set(["SUM","COUNT","AVG","MIN","MAX","MEDIAN","DISTINCT"]);function C(e,i,t){if(!e||typeof e!="object"){t.push(a("missing_source","Analytics intent needs a source.",i));return}if(e.kind==="semantic"){c(e.domainId)||t.push(a("missing_semantic_domain","Semantic source needs a domainId.",`${i}.domainId`)),c(e.datasetName)||t.push(a("missing_dataset_name","Semantic source needs a datasetName.",`${i}.datasetName`));return}if(e.kind==="physical"){c(e.connectionId)||t.push(a("missing_connection_id","Physical source needs a connectionId.",`${i}.connectionId`)),c(e.tableName)||t.push(a("missing_table_name","Physical source needs a tableName.",`${i}.tableName`));return}if(e.kind==="sql"){c(e.connectionId)||t.push(a("missing_connection_id","SQL source needs a connectionId.",`${i}.connectionId`));return}t.push(a("invalid_source_kind","Source kind is not supported.",i))}function f(e,i,t,s={}){if(!e||!m(e)){s.required&&t.push(a("missing_field_ref","Field reference needs a name.",i));return}c(e.name)||t.push(a("missing_field_ref","Field reference needs a name.",`${i}.name`)),e.source!==void 0&&C(e.source,`${i}.source`,t),y(e.aggregate,`${i}.aggregate`,t)}function y(e,i,t){e!==void 0&&(typeof e!="string"||!re.has(e))&&t.push(a("invalid_aggregate","Field aggregate must be SUM, COUNT, AVG, MIN, MAX, MEDIAN, or DISTINCT.",i))}function oe(e,i,t){e!==void 0&&e!=="hour"&&e!=="day"&&e!=="week"&&e!=="month"&&e!=="quarter"&&e!=="year"&&t.push(a("invalid_time_grain","Time grain must be hour, day, week, month, quarter, or year.",i))}function L(e,i,t,s){e!=="asc"&&e!=="desc"&&t.push(a(s,"Sort direction must be asc or desc.",i))}function U(e,i,t,s){e!==void 0&&e!=="warehouseDefault"&&e!=="first"&&e!=="last"&&t.push(a(s,"Null ordering must be warehouseDefault, first, or last.",i))}function H(e,i,t,s){e!==void 0&&e!=="global"&&e!=="withinParent"&&t.push(a(s,"Sort scope must be global or withinParent.",i))}function le(e,i,t){e.enabled!==void 0&&typeof e.enabled!="boolean"&&t.push(a("invalid_matrix_subtotal","Matrix subtotal enabled must be a boolean.",`${i}.enabled`)),e.position!==void 0&&e.position!=="before"&&e.position!=="after"&&t.push(a("invalid_matrix_subtotal","Matrix subtotal position must be before or after.",`${i}.position`)),e.label!==void 0&&typeof e.label!="string"&&t.push(a("invalid_matrix_subtotal","Matrix subtotal label must be a string.",`${i}.label`))}function de(e,i,t){if(L(e.direction,`${i}.direction`,t,"invalid_matrix_sort_direction"),U(e.nulls,`${i}.nulls`,t,"invalid_matrix_sort_nulls"),H(e.scope,`${i}.scope`,t,"invalid_matrix_sort_scope"),!m(e.by)){t.push(a("invalid_matrix_sort_by","Matrix sort by must be a structured object.",`${i}.by`));return}if(e.by.kind!=="label"){if(e.by.kind==="field"){f(e.by.field,`${i}.by.field`,t,{required:!0}),y(e.by.aggregate,`${i}.by.aggregate`,t);return}t.push(a("invalid_matrix_sort_by","Matrix axis sort by must be label or field.",`${i}.by.kind`))}}function T(e,i,t,s){if(!Array.isArray(e))return s.required?t.push(a("missing_matrix_rows","Matrix intent needs at least one row axis level.",i)):e!==void 0&&t.push(a("invalid_matrix_columns","Matrix columns must be an array of axis levels.",i)),[];s.required&&e.length===0&&t.push(a("missing_matrix_rows","Matrix intent needs at least one row axis level.",i));const n=[];return e.forEach((o,r)=>{const d=`${i}.${r}`;if(!m(o)){t.push(a("invalid_matrix_axis_level","Matrix axis levels must be structured objects.",d));return}const l=o;n.push(l),l.id!==void 0&&!c(l.id)&&t.push(a("invalid_matrix_axis_level_id","Matrix axis level id must be a non-empty string.",`${d}.id`)),f(l.field,`${d}.field`,t,{required:!0}),oe(l.grain,`${d}.grain`,t),l.label!==void 0&&typeof l.label!="string"&&t.push(a("invalid_matrix_axis_label","Matrix axis level label must be a string.",`${d}.label`)),l.subtotal!==void 0&&typeof l.subtotal!="boolean"&&(m(l.subtotal)?le(l.subtotal,`${d}.subtotal`,t):t.push(a("invalid_matrix_subtotal","Matrix subtotal must be a boolean or structured options object.",`${d}.subtotal`))),l.sortBy!==void 0&&(m(l.sortBy)?de(l.sortBy,`${d}.sortBy`,t):t.push(a("invalid_matrix_sort_by","Matrix axis sortBy must be a structured object.",`${d}.sortBy`)))}),n}function ue(e,i,t){if(!m(e)){t.push(a("invalid_matrix_total_behavior","Matrix total behavior must be a structured object.",i));return}if(e.kind!=="defaultAggregate"&&e.kind!=="blank"&&e.kind!=="labelOnly"&&e.kind!=="customAggregate"&&e.kind!=="percentOfParent"&&e.kind!=="percentOfGrandTotal"&&e.kind!=="customExpression"){t.push(a("invalid_matrix_total_behavior","Matrix total behavior kind is not supported.",`${i}.kind`));return}e.kind==="customAggregate"&&(Object.prototype.hasOwnProperty.call(e,"aggregate")?y(e.aggregate,`${i}.aggregate`,t):t.push(a("invalid_matrix_total_behavior","Custom matrix total behavior needs an aggregate.",`${i}.aggregate`))),e.kind==="customExpression"&&!c(e.expressionId)&&t.push(a("invalid_matrix_total_behavior","Custom matrix total behavior needs an expressionId.",`${i}.expressionId`)),e.kind==="labelOnly"&&e.label!==void 0&&typeof e.label!="string"&&t.push(a("invalid_matrix_total_behavior","Matrix label-only total behavior label must be a string.",`${i}.label`))}function ce(e,i,t){if(!Array.isArray(e)||e.length===0)return t.push(a("missing_matrix_values","Matrix intent needs at least one value field.",i)),[];const s=[];return e.forEach((n,o)=>{const r=`${i}.${o}`;if(!m(n)){t.push(a("invalid_matrix_value","Matrix values must be structured objects.",r));return}const d=n;s.push(d),d.id!==void 0&&!c(d.id)&&t.push(a("invalid_matrix_value_id","Matrix value id must be a non-empty string.",`${r}.id`)),f(d.field,`${r}.field`,t,{required:!0}),y(d.aggregate,`${r}.aggregate`,t),d.label!==void 0&&typeof d.label!="string"&&t.push(a("invalid_matrix_value_label","Matrix value label must be a string.",`${r}.label`)),d.totalBehavior!==void 0&&ue(d.totalBehavior,`${r}.totalBehavior`,t)}),s}function me(e,i,t){if(!m(e)){t.push(a("invalid_matrix_totals","Matrix totals must be a structured object.",i));return}for(const s of["rows","columns"]){const n=e[s];n!==void 0&&n!==!0&&n!==!1&&n!=="perLevel"&&t.push(a("invalid_matrix_totals","Matrix total axis setting must be a boolean or perLevel.",`${i}.${s}`))}if(e.grandTotal!==void 0&&typeof e.grandTotal!="boolean")if(!m(e.grandTotal))t.push(a("invalid_matrix_totals","Matrix grandTotal must be a boolean or structured object.",`${i}.grandTotal`));else for(const s of["rows","columns"]){const n=e.grandTotal[s];n!==void 0&&typeof n!="boolean"&&t.push(a("invalid_matrix_totals","Matrix grandTotal rows/columns must be booleans.",`${i}.grandTotal.${s}`))}e.rowPosition!==void 0&&e.rowPosition!=="top"&&e.rowPosition!=="bottom"&&t.push(a("invalid_matrix_totals","Matrix row total position must be top or bottom.",`${i}.rowPosition`)),e.columnPosition!==void 0&&e.columnPosition!=="left"&&e.columnPosition!=="right"&&t.push(a("invalid_matrix_totals","Matrix column total position must be left or right.",`${i}.columnPosition`))}function $(e,i,t,s){if(!Array.isArray(e)){s.push(a("invalid_matrix_path","Matrix member path must be an array of path segments.",i));return}e.forEach((n,o)=>{const r=`${i}.${o}`;if(!m(n)){s.push(a("invalid_matrix_path","Matrix path segment must be a structured object.",r));return}const d=n;if(!c(d.levelId)){s.push(a("stable_id_required","Matrix path segments must reference an explicit public axis level id.",`${r}.levelId`));return}Object.prototype.hasOwnProperty.call(n,"value")||s.push(a("invalid_matrix_path","Matrix path segments must include a value property; use explicit null for null members.",`${r}.value`)),t.has(d.levelId)||s.push(a("stable_id_required","Matrix path segment levelId must match an explicit public axis level id.",`${r}.levelId`))})}function j(e,i,t,s){if(!m(e)){s.push(a("invalid_matrix_expansion","Matrix expansion axis options must be structured objects.",i));return}e.defaultDepth!==void 0&&(typeof e.defaultDepth!="number"||!Number.isInteger(e.defaultDepth)||e.defaultDepth<0)&&s.push(a("invalid_matrix_expansion","Matrix expansion defaultDepth must be a non-negative integer.",`${i}.defaultDepth`)),e.lazy!==void 0&&typeof e.lazy!="boolean"&&s.push(a("invalid_matrix_expansion","Matrix expansion lazy must be a boolean.",`${i}.lazy`)),e.expandedPaths!==void 0&&(Array.isArray(e.expandedPaths)?e.expandedPaths.forEach((n,o)=>{$(n,`${i}.expandedPaths.${o}`,t,s)}):s.push(a("invalid_matrix_expansion","Matrix expandedPaths must be an array of member paths.",`${i}.expandedPaths`)))}function fe(e,i,t,s){if(e!==void 0){if(!m(e)){s.push(a("invalid_matrix_expansion","Matrix expansion must be a structured object.","expansion"));return}e.rows!==void 0&&j(e.rows,"expansion.rows",i,s),e.columns!==void 0&&j(e.columns,"expansion.columns",t,s)}}function pe(e,i,t,s,n){if(e!==void 0){if(!Array.isArray(e)){n.push(a("invalid_matrix_sort","Matrix sort must be an array of sort rules.","sort"));return}e.forEach((o,r)=>{const d=`sort.${r}`;if(!m(o)){n.push(a("invalid_matrix_sort","Matrix sort rule must be a structured object.",d));return}const l=o;l.axis!=="row"&&l.axis!=="column"&&n.push(a("invalid_matrix_sort","Matrix sort axis must be row or column.",`${d}.axis`));const u=l.axis==="column"?t:i;if(l.targetId!==void 0&&!u.has(l.targetId)&&n.push(a("stable_id_required","Matrix sort targetId must reference an explicit public axis level id.",`${d}.targetId`)),L(l.direction,`${d}.direction`,n,"invalid_matrix_sort_direction"),U(l.nulls,`${d}.nulls`,n,"invalid_matrix_sort_nulls"),H(l.scope,`${d}.scope`,n,"invalid_matrix_sort_scope"),!m(l.by)){n.push(a("invalid_matrix_sort_by","Matrix sort by must be a structured object.",`${d}.by`));return}if(l.by.kind!=="label"){if(l.by.kind==="field"){f(l.by.field,`${d}.by.field`,n,{required:!0}),y(l.by.aggregate,`${d}.by.aggregate`,n);return}if(l.by.kind==="value"){(!c(l.by.valueId)||!s.has(l.by.valueId))&&n.push(a("stable_id_required","Matrix value sort must reference an explicit public value id.",`${d}.by.valueId`)),l.by.rowPath!==void 0&&$(l.by.rowPath,`${d}.by.rowPath`,i,n),l.by.columnPath!==void 0&&$(l.by.columnPath,`${d}.by.columnPath`,t,n);return}n.push(a("invalid_matrix_sort_by","Matrix sort by must be label, field, or value.",`${d}.by.kind`))}})}}function _e(e,i){if(e!==void 0){if(!m(e)){i.push(a("invalid_matrix_layout","Matrix layout must be a structured object.","layout"));return}e.hierarchy!==void 0&&e.hierarchy!=="compact"&&e.hierarchy!=="tabular"&&e.hierarchy!=="outline"&&i.push(a("invalid_matrix_layout","Matrix hierarchy layout must be compact, tabular, or outline.","layout.hierarchy")),e.valuesPlacement!==void 0&&e.valuesPlacement!=="columns"&&e.valuesPlacement!=="rows"&&i.push(a("invalid_matrix_layout","Matrix valuesPlacement must be columns or rows.","layout.valuesPlacement")),e.stickyRowHeaders!==void 0&&typeof e.stickyRowHeaders!="boolean"&&i.push(a("invalid_matrix_layout","Matrix stickyRowHeaders must be a boolean.","layout.stickyRowHeaders")),e.stickyColumnHeaders!==void 0&&typeof e.stickyColumnHeaders!="boolean"&&i.push(a("invalid_matrix_layout","Matrix stickyColumnHeaders must be a boolean.","layout.stickyColumnHeaders"))}}function R(e,i,t){if(!m(e)){t.push(a("invalid_matrix_display_limits","Matrix display limit must be a structured object.",i));return}(typeof e.limit!="number"||!Number.isInteger(e.limit)||e.limit<1)&&t.push(a("invalid_matrix_display_limits","Matrix display limit must be a positive integer.",`${i}.limit`)),e.by!==void 0&&e.by!=="label"&&e.by!=="value"&&t.push(a("invalid_matrix_display_limits","Matrix display limit by must be label or value.",`${i}.by`)),e.direction!==void 0&&e.direction!=="top"&&e.direction!=="bottom"&&t.push(a("invalid_matrix_display_limits","Matrix display limit direction must be top or bottom.",`${i}.direction`)),e.others!==void 0&&typeof e.others!="boolean"&&(m(e.others)?e.others.label!==void 0&&typeof e.others.label!="string"&&t.push(a("invalid_matrix_display_limits","Matrix display limit others label must be a string.",`${i}.others.label`)):t.push(a("invalid_matrix_display_limits","Matrix display limit others must be a boolean or structured object.",`${i}.others`)))}function be(e,i){if(e!==void 0){if(!m(e)){i.push(a("invalid_matrix_display_limits","Matrix displayLimits must be a structured object.","displayLimits"));return}e.rows!==void 0&&R(e.rows,"displayLimits.rows",i),e.columns!==void 0&&R(e.columns,"displayLimits.columns",i)}}function ye(e,i){var l;((l=e.source)==null?void 0:l.kind)==="sql"&&i.push(a("unsupported_matrix_sql_source","Matrix analytics intent does not support raw SQL sources.","source.kind"));const t=T(e.rows,"rows",i,{required:!0}),s=T(e.columns,"columns",i,{required:!1}),n=ce(e.values,"values",i);A(e.filters,"filters",i),e.totals!==void 0&&me(e.totals,"totals",i),g(t.map(u=>u.id),"rows","row axis level",i),g(s.map(u=>u.id),"columns","column axis level",i),g(n.map(u=>u.id),"values","value",i);const o=new Set(t.map(u=>u.id).filter(u=>c(u))),r=new Set(s.map(u=>u.id).filter(u=>c(u))),d=new Set(n.map(u=>u.id).filter(u=>c(u)));pe(e.sort,o,r,d,i),fe(e.expansion,o,r,i),_e(e.layout,i),be(e.displayLimits,i)}function he(e,i){if(e.analysis===void 0)return;if(!m(e.analysis)){i.push(a("invalid_metric_analysis","Metric analysis must be a structured object.","analysis"));return}if(e.analysis.kind!=="period_change"){i.push(a("invalid_metric_analysis","Metric analysis kind is not supported.","analysis.kind"));return}e.dateField||i.push(a("missing_analysis_date_field","Period-change analysis needs a dateField.","dateField")),e.timeGrain||i.push(a("missing_analysis_time_grain","Period-change analysis needs a timeGrain.","timeGrain")),e.analysis.orderBy!==void 0&&e.analysis.orderBy!=="absolute_change"&&e.analysis.orderBy!=="positive_change"&&e.analysis.orderBy!=="negative_change"&&e.analysis.orderBy!=="period"&&i.push(a("invalid_metric_analysis","Period-change analysis orderBy must be absolute_change, positive_change, negative_change, or period.","analysis.orderBy"));const{timeWindow:t}=e.analysis;t!==void 0&&M(t,"analysis.timeWindow",i)}function M(e,i,t){if(!m(e)){t.push(a("invalid_time_window","Time window must be a structured object.",i));return}if(e.kind!==void 0&&e.kind!=="relative"&&e.kind!=="absolute"&&t.push(a("invalid_time_window","Time window kind must be relative or absolute.",`${i}.kind`)),e.kind==="absolute"){if(c(e.start)||t.push(a("invalid_time_window","Absolute time window start must be a non-empty ISO date or timestamp string.",`${i}.start`)),c(e.end)||t.push(a("invalid_time_window","Absolute time window end must be a non-empty ISO date or timestamp string.",`${i}.end`)),c(e.start)&&c(e.end)){const s=x(e.start),n=x(e.end);s||t.push(a("invalid_time_window","Absolute time window start must be a valid ISO date or timestamp.",`${i}.start`)),n||t.push(a("invalid_time_window","Absolute time window end must be a valid ISO date or timestamp.",`${i}.end`)),s&&n&&s.getTime()>n.getTime()&&t.push(a("invalid_time_window","Absolute time window start must be before or equal to end.",i))}return}e.unit!=="second"&&e.unit!=="minute"&&e.unit!=="hour"&&e.unit!=="day"&&e.unit!=="week"&&e.unit!=="month"&&e.unit!=="quarter"&&e.unit!=="year"&&t.push(a("invalid_time_window","Time window unit must be second, minute, hour, day, week, month, quarter, or year.",`${i}.unit`)),(typeof e.value!="number"||!Number.isFinite(e.value)||e.value<=0)&&t.push(a("invalid_time_window","Time window value must be a positive number.",`${i}.value`)),e.anchor!==void 0&&e.anchor!=="now"&&e.anchor!=="latest_available"&&t.push(a("invalid_time_window","Time window anchor must be now or latest_available.",`${i}.anchor`)),e.completeness!==void 0&&e.completeness!=="include_partial"&&e.completeness!=="complete_periods"&&t.push(a("invalid_time_window","Time window completeness must be include_partial or complete_periods.",`${i}.completeness`))}function A(e,i,t){if(e!==void 0){if(!Array.isArray(e)){t.push(a("invalid_analytics_filters","Analytics filters must be an array.",i));return}e.forEach((s,n)=>{var l;const o=`${i}.${n}`;if(!m(s)){t.push(a("invalid_analytics_filter","Analytics filter must be a structured object.",o));return}const r=s;f(r.field,`${o}.field`,t,{required:!0}),r.scope!==void 0&&r.scope!=="row"&&r.scope!=="aggregate"&&t.push(a("invalid_analytics_filter_scope","Analytics filter scope must be row or aggregate.",`${o}.scope`)),r.scope==="aggregate"&&((l=r.field)==null?void 0:l.role)!==void 0&&r.field.role!=="measure"&&t.push(a("invalid_analytics_filter_scope","Aggregate-scope analytics filters must target a measure field.",`${o}.scope`));const d=r.operator==="is_null"||r.operator==="is_not_null";if(r.operator!==void 0&&r.operator!=="="&&r.operator!=="!="&&r.operator!=="in"&&r.operator!=="not_in"&&r.operator!=="contains"&&r.operator!=="not_contains"&&r.operator!=="between"&&r.operator!=="not_between"&&r.operator!==">"&&r.operator!==">="&&r.operator!=="<"&&r.operator!=="<="&&r.operator!=="is_null"&&r.operator!=="is_not_null"&&t.push(a("invalid_analytics_filter_operator","Analytics filter operator is not supported.",`${o}.operator`)),r.values===void 0&&!d&&t.push(a("missing_analytics_filter_value","Analytics filter needs values unless it is a null check.",o)),d&&r.values!==void 0){t.push(a("invalid_analytics_filter_values","Null-check analytics filters must not include values.",`${o}.values`));return}if(r.values!==void 0&&!Array.isArray(r.values)){t.push(a("invalid_analytics_filter_values","Analytics filter values must be an array when provided.",`${o}.values`));return}if(r.values!==void 0){const u=r.values.length;if(r.operator==="between"||r.operator==="not_between"){u!==2&&t.push(a("invalid_analytics_filter_values","Between analytics filters must include exactly two values.",`${o}.values`));return}(r.operator==="contains"||r.operator==="not_contains"||r.operator==="="||r.operator==="!="||r.operator===">"||r.operator===">="||r.operator==="<"||r.operator==="<="||r.operator===void 0)&&u!==1&&t.push(a("invalid_analytics_filter_values","Scalar analytics filters must include exactly one value. Use in/not_in for multiple values.",`${o}.values`))}})}}function k(e){var s;const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[a("invalid_analytics_intent","Analytics intent must be a structured object.")],warnings:t,repairHints:[{code:"invalid_analytics_intent",recommendedNextStep:"Send one structured analytics intent object with kind, source, and required fields."}]};if(e.version!==void 0&&e.version!==1&&i.push(a("invalid_version","Analytics intent version must be 1.","version")),C(e.source,"source",i),e.kind==="metric"){const n=Array.isArray(e.metrics)?e.metrics.filter(o=>m(o)&&c(o.name)):[];if(!Array.isArray(e.metrics)||e.metrics.length===0?i.push(a("missing_metric","Metric intent needs at least one metric.","metrics")):e.metrics.some(o=>!m(o)||!c(o.name))&&i.push(a("invalid_metric_list","Metric intent metrics must be an array of field references with names.","metrics")),n.forEach((o,r)=>{f(o,`metrics.${r}`,i,{required:!0})}),n.length>0&&!Y(n)){const o=n.find((r,d)=>n.some((l,u)=>u!==d&&E(l,r)));o&&i.push(a("duplicate_metric",Z(o),"metrics"))}if(m(e.primaryMetric)&&c(e.primaryMetric.name)&&S(e.primaryMetric,n).length>1&&i.push(a("ambiguous_primary_metric","Metric intent primaryMetric must identify exactly one selected metric.","primaryMetric")),e.primaryMetric!==void 0&&(f(e.primaryMetric,"primaryMetric",i,{required:!0}),m(e.primaryMetric)&&c(e.primaryMetric.name)&&n.length>0&&!K(e.primaryMetric,n)&&i.push(a("invalid_primary_metric","Metric intent primaryMetric must match one metric field reference.","primaryMetric"))),e.dimensions!==void 0&&!Array.isArray(e.dimensions)?i.push(a("invalid_metric_dimensions","Metric intent dimensions must be an array of field references.","dimensions")):Array.isArray(e.dimensions)&&e.dimensions.some(o=>!m(o)||!c(o.name))&&i.push(a("invalid_metric_dimensions","Metric intent dimensions must be an array of field references with names.","dimensions")),e.dateField!==void 0&&f(e.dateField,"dateField",i),e.timeWindow!==void 0&&(M(e.timeWindow,"timeWindow",i),e.dateField||i.push(a("missing_time_window_date_field","Metric timeWindow needs a dateField.","dateField"))),A(e.filters,"filters",i),Array.isArray(e.dimensions)&&e.dimensions.forEach((o,r)=>{f(o,`dimensions.${r}`,i)}),e.orderBy!==void 0){if(!m(e.orderBy))i.push(a("invalid_metric_order_by","Metric intent orderBy must be a structured object.","orderBy"));else if(f(e.orderBy.field,"orderBy.field",i,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&i.push(a("invalid_metric_order_direction","Metric intent orderBy direction must be asc or desc.","orderBy.direction")),m(e.orderBy.field)&&c(e.orderBy.field.name)){const o=[...n,...e.timeGrain&&e.dateField&&m(e.dateField)?[e.dateField]:[],...Array.isArray(e.dimensions)?e.dimensions.filter(r=>m(r)&&c(r.name)):[]];o.length>0&&!W(e.orderBy.field,o)&&i.push(a("invalid_metric_order_by","Metric intent orderBy.field must match one selected metric, grouped dateField, or dimension.","orderBy.field"))}}he(e,i)}else e.kind==="records"?(!Array.isArray(e.fields)||e.fields.length===0?i.push(a("missing_record_fields","Records intent needs at least one field.","fields")):e.fields.some(n=>!m(n)||!c(n.name))&&i.push(a("invalid_record_fields","Records intent fields must be field references with names.","fields")),Array.isArray(e.fields)&&e.fields.forEach((n,o)=>{f(n,`fields.${o}`,i)}),e.dateField!==void 0&&f(e.dateField,"dateField",i),B(e.pagination,"pagination",i),e.timeWindow!==void 0&&(M(e.timeWindow,"timeWindow",i),e.dateField||i.push(a("missing_time_window_date_field","Records timeWindow needs a dateField.","dateField"))),A(e.filters,"filters",i),Array.isArray(e.filters)&&e.filters.forEach((n,o)=>{m(n)&&n.scope==="aggregate"&&i.push(a("unsupported_record_filter_scope","Records intents support row-scope filters only. Use a metric intent for aggregate-scope filters.",`filters.${o}.scope`))}),e.orderBy!==void 0&&(m(e.orderBy)?(f(e.orderBy.field,"orderBy.field",i,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&i.push(a("invalid_record_order_direction","Records intent orderBy direction must be asc or desc.","orderBy.direction"))):i.push(a("invalid_record_order_by","Records intent orderBy must be a structured object.","orderBy")))):e.kind==="inputOptions"?((!e.field||!c(e.field.name))&&i.push(a("missing_input_options_field","Input options intent needs a field.","field")),f(e.field,"field",i,{required:!0})):e.kind==="matrix"?ye(e,i):e.kind==="sql"?(((s=e.source)==null?void 0:s.kind)!=="sql"&&i.push(a("invalid_sql_source","SQL analytics intent must use a SQL execution source.","source")),c(e.sql)||i.push(a("missing_sql","SQL analytics intent needs SQL text.","sql")),J(e.defaultParameters,"defaultParameters",i),Array.isArray(e.fields)&&e.fields.forEach((n,o)=>{f(n,`fields.${o}`,i)}),B(e.pagination,"pagination",i)):i.push(a("invalid_analytics_kind","Analytics kind is not supported.","kind"));return{ok:i.length===0,errors:i,warnings:t,repairHints:ge(i)}}function z(e){const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[a("invalid_operation_intent","Operation intent must be a structured object.")],warnings:t,repairHints:[{code:"invalid_operation_intent",recommendedNextStep:"Send one typed operation intent with version, kind, and required operation fields."}]};if(e.version!==1&&i.push(a("invalid_version","Operation intent version must be 1.","version")),e.kind==="answer_obligations")!Array.isArray(e.obligations)||e.obligations.length===0?i.push(a("missing_obligations","Answer-obligations operation intent needs at least one obligation.","obligations")):e.obligations.forEach((s,n)=>{c(s.id)||i.push(a("missing_obligation_id","Each analytics obligation needs an id.",`obligations.${n}.id`)),c(s.prompt)||i.push(a("missing_obligation_prompt","Each analytics obligation needs a prompt.",`obligations.${n}.prompt`))});else if(e.kind==="dashboard_change"||e.kind==="data_app_change"){if(c(e.instruction)||i.push(a("missing_instruction","Change operation intent needs an instruction.","instruction")),e.analyticsIntent){const s=k(e.analyticsIntent);i.push(...s.errors),t.push(...s.warnings)}}else i.push(a("invalid_operation_kind","Operation intent kind is not supported.","kind"));return{ok:i.length===0,errors:i,warnings:t,repairHints:V(i)}}function ve(e){const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[a("invalid_recovery_plan","Analytics recovery plan must be a structured object.")],warnings:t,repairHints:[{code:"invalid_recovery_plan",recommendedNextStep:"Return a typed recovery plan with operationIntent and plannedToolCalls."}]};e.version!==1&&i.push(a("invalid_version","Recovery plan version must be 1.","version")),e.kind!=="analytics_recovery_plan"&&i.push(a("invalid_recovery_plan_kind","Recovery plan kind must be analytics_recovery_plan.","kind"));const s=z(e.operationIntent);return i.push(...s.errors),t.push(...s.warnings),Array.isArray(e.plannedToolCalls)||i.push(a("invalid_planned_tool_calls","Recovery plan plannedToolCalls must be an array.","plannedToolCalls")),{ok:i.length===0,errors:i,warnings:t,repairHints:V(i)}}function V(e){return e.map(i=>({code:i.code,recommendedNextStep:i.code==="missing_obligations"?"Normalize the user request into one or more typed analytics obligations before recovery planning.":"Correct the operation/recovery contract shape before planning execution."}))}function ge(e){return e.map(i=>{switch(i.code){case"missing_source":return{code:i.code,fieldRole:"source",recommendedNextStep:"Provide a semantic, physical, or SQL source before executing analytics."};case"missing_metric":return{code:i.code,fieldRole:"metric",recommendedNextStep:"Choose one exact metric from the grounded schema candidates."};case"missing_record_fields":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Provide at least one field for the records intent."};case"missing_matrix_rows":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Choose at least one row axis level for the matrix table."};case"missing_matrix_values":return{code:i.code,fieldRole:"metric",recommendedNextStep:"Choose at least one value field for the matrix table."};case"unsupported_matrix_sql_source":return{code:i.code,fieldRole:"source",recommendedNextStep:"Use a semantic or explorer-backed source for matrix tables; raw SQL matrix tables are not supported."};case"missing_input_options_field":return{code:i.code,fieldRole:"input",recommendedNextStep:"Provide the exact field whose option values should be listed."};case"missing_sql":return{code:i.code,fieldRole:"sql",recommendedNextStep:"Provide bounded read-only SQL with an explicit outer LIMIT."};case"conflicting_sql":return{code:i.code,fieldRole:"sql",recommendedNextStep:"Use one canonical SQL text location for the intent; prefer top-level sql."};case"missing_semantic_domain":case"missing_dataset_name":case"missing_connection_id":case"missing_table_name":return{code:i.code,fieldRole:"source",recommendedNextStep:"Use grounded catalog metadata to fill the missing source reference."};default:return}}).filter(i=>!!i)}function xe(e,i,t,s){if(!e||typeof e!="object"){t.push(a("invalid_view","Dashboard view must be an object.",i));return}if(c(e.title)||t.push(a("missing_view_title","Dashboard view needs a title.",i)),!e.presentation||typeof e.presentation!="object"){t.push(a("missing_presentation","Dashboard view needs a presentation.",`${i}.presentation`));return}if(e.presentation.kind==="text"){c(e.text)||s.push(a("missing_text_content","Text views should include text content.",`${i}.text`));return}if(!e.analytics){t.push(a("missing_view_analytics","Non-text dashboard views need analytics intent.",`${i}.analytics`));return}e.presentation.kind==="matrixTable"&&e.analytics.kind!=="matrix"&&t.push(a("invalid_matrix_view_analytics","Matrix table views need matrix analytics intent.",`${i}.analytics.kind`));const n=k(e.analytics);for(const o of n.errors)t.push(a(o.code,o.message,`${i}.analytics${o.path?`.${o.path}`:""}`));for(const o of n.warnings)s.push(a(o.code,o.message,`${i}.analytics${o.path?`.${o.path}`:""}`))}function we(e){const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[a("invalid_dashboard_intent","Dashboard intent must be a structured object.")],warnings:t};e.version!==1&&i.push(a("invalid_version","Dashboard intent version must be 1.")),e.kind!=="dashboard"&&i.push(a("invalid_kind","Experience intent kind must be dashboard.")),c(e.title)||i.push(a("missing_title","Dashboard intent needs a title.","title"));const s=Array.isArray(e.inputs)?e.inputs:[],n=w(s.filter(m).map(l=>l.id).filter(l=>typeof l=="string"));n&&i.push(a("duplicate_input_id",`Duplicate input id: ${n}.`,"inputs"));for(const[l,u]of s.entries()){const p=`inputs.${l}`;if(!m(u)){i.push(a("invalid_input","Dashboard input must be an object.",p));continue}c(u.id)||i.push(a("missing_input_id","Input needs an id.",`${p}.id`)),c(u.label)||i.push(a("missing_input_label","Input needs a label.",`${p}.label`)),!u.field||!c(u.field.name)?i.push(a("missing_input_field","Input needs a field.",`${p}.field`)):f(u.field,`${p}.field`,i)}const o=Array.isArray(e.sections)?e.sections:[];o.length===0&&i.push(a("missing_sections","Dashboard intent needs at least one section.","sections"));const r=o.flatMap(l=>l&&typeof l=="object"&&Array.isArray(l.views)?l.views.filter(m).map(u=>u.id).filter(u=>!!u):[]),d=w(r);d&&i.push(a("duplicate_view_id",`Duplicate dashboard view id: ${d}.`,"sections"));for(const[l,u]of o.entries()){const p=`sections.${l}`;if(!u||typeof u!="object"){i.push(a("invalid_section","Dashboard section must be an object.",p));continue}if(c(u.title)||i.push(a("missing_section_title","Dashboard section needs a title.",p)),!Array.isArray(u.views)||u.views.length===0){i.push(a("missing_section_views","Dashboard section needs at least one view.",`${p}.views`));continue}for(const[h,v]of u.views.entries())xe(v,`${p}.views.${h}`,i,t)}return{ok:i.length===0,errors:i,warnings:t}}exports.normalizeSemaphorAnalyticsFilterOperator=D;exports.normalizeSemaphorInputOperator=Q;exports.parseSemaphorIsoTimeWindowBoundary=x;exports.validateSemaphorAnalyticsIntent=k;exports.validateSemaphorAnalyticsRecoveryPlan=ve;exports.validateSemaphorDashboardIntent=we;exports.validateSemaphorOperationIntent=z;