react-semaphor 0.1.459 → 0.1.461

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 (114) hide show
  1. package/dist/analytics-protocol/index.cjs +1 -1
  2. package/dist/analytics-protocol/index.js +32 -32
  3. package/dist/brand-studio/index.cjs +1 -1
  4. package/dist/brand-studio/index.js +4 -4
  5. package/dist/briefings/index.cjs +1 -1
  6. package/dist/briefings/index.js +4 -4
  7. package/dist/chunks/{analyze-result-contract-BbRJ-C06.js → analyze-result-contract-DROq4vgY.js} +1 -1
  8. package/dist/chunks/{analyze-result-contract-LPDNldic.cjs → analyze-result-contract-DSGoFuXQ.cjs} +1 -1
  9. package/dist/chunks/canonical-result-keys-CEQefvdO.js +33 -0
  10. package/dist/chunks/canonical-result-keys-Cb96edol.cjs +1 -0
  11. package/dist/chunks/{common-types-H51FLKB7.js → common-types-BHVKgxRR.js} +1 -1
  12. package/dist/chunks/{common-types-C57kJ59w.cjs → common-types-BcV9PD9D.cjs} +1 -1
  13. package/dist/chunks/{dashboard-briefing-launcher-ClCj98sq.js → dashboard-briefing-launcher-3owMxX5K.js} +60 -61
  14. package/dist/chunks/{dashboard-briefing-launcher-DHtEouuH.cjs → dashboard-briefing-launcher-xuGrw8H3.cjs} +2 -2
  15. package/dist/chunks/{dashboard-controls-B8gsKlxc.js → dashboard-controls-B4GvjGr1.js} +44 -45
  16. package/dist/chunks/{dashboard-controls-VRShl9J0.cjs → dashboard-controls-Bpm_xOXQ.cjs} +1 -1
  17. package/dist/chunks/dashboard-filter-value-compatibility-KXIyvbhc.js +677 -0
  18. package/dist/chunks/dashboard-filter-value-compatibility-UapptYnn.cjs +1 -0
  19. package/dist/chunks/dashboard-input-contract-BkRFQ7Tq.cjs +1 -0
  20. package/dist/chunks/{dashboard-date-comparison-definition-DC3ekV2S.js → dashboard-input-contract-D5dxTWJ5.js} +41 -25
  21. package/dist/chunks/{dashboard-json-i_Auue_K.js → dashboard-json-DzyxoBp-.js} +13 -14
  22. package/dist/chunks/dashboard-json-yLM01xK4.cjs +1 -0
  23. package/dist/chunks/{edit-dashboard-visual-DWWyT55u.cjs → edit-dashboard-visual-1T278Nr_.cjs} +28 -28
  24. package/dist/chunks/{edit-dashboard-visual-B3JF0fe4.js → edit-dashboard-visual-nwSasO_j.js} +880 -894
  25. package/dist/chunks/{editor-action-buttons-BTlCsP63.cjs → editor-action-buttons-CX1Pken3.cjs} +2 -2
  26. package/dist/chunks/{editor-action-buttons-C9x3nGnb.js → editor-action-buttons-Dqw0asfA.js} +28 -28
  27. package/dist/chunks/index-B1qplNxl.cjs +1392 -0
  28. package/dist/chunks/{index-BS2-ZZGf.js → index-DazD5k0F.js} +45362 -42931
  29. package/dist/chunks/{index-BIFLI8ul.js → index-De_7nrwb.js} +10 -10
  30. package/dist/chunks/index-DjjKJPDy.cjs +4 -0
  31. package/dist/chunks/{matrix-result-contract-CofATICL.js → matrix-result-contract-BTpPuHOc.js} +88 -104
  32. package/dist/chunks/matrix-result-contract-ZRNfeIbI.cjs +1 -0
  33. package/dist/chunks/{pivot-header-presentation-B9nXXKlW.cjs → pivot-header-presentation-BijPbP33.cjs} +1 -1
  34. package/dist/chunks/{pivot-header-presentation-D-0jvUwn.js → pivot-header-presentation-DW0gKG8g.js} +2 -2
  35. package/dist/chunks/{pivot-result-identity-Bb4EixVN.cjs → pivot-result-identity-DxHtiKVj.cjs} +1 -1
  36. package/dist/chunks/{pivot-result-identity-DU1v-5Xk.js → pivot-result-identity-Z9tN2tEV.js} +1 -1
  37. package/dist/chunks/{pivot-result-lifecycle-DTLRuDEW.cjs → pivot-result-lifecycle-BXzIlQVu.cjs} +1 -1
  38. package/dist/chunks/{pivot-result-lifecycle-CHWEGU2o.js → pivot-result-lifecycle-g2U-vzQb.js} +7 -7
  39. package/dist/chunks/{raw-temporal-contract-BtjH_G-d.cjs → raw-temporal-contract-DfAvqNMo.cjs} +1 -1
  40. package/dist/chunks/{raw-temporal-contract-CxncLze5.js → raw-temporal-contract-UtAqoOZO.js} +1 -1
  41. package/dist/chunks/{report-preferences-dialog-BK0yAJnQ.cjs → report-preferences-dialog-DKPyjiCt.cjs} +1 -1
  42. package/dist/chunks/{report-preferences-dialog-BDpkcUtz.js → report-preferences-dialog-Dv3vCCFt.js} +6 -6
  43. package/dist/chunks/{report-runtime-context-DqxS4wbi.cjs → report-runtime-context-C0NfLPfc.cjs} +1 -1
  44. package/dist/chunks/{report-runtime-context-SM6YO61_.js → report-runtime-context-CNncA3VD.js} +11 -11
  45. package/dist/chunks/{saved-temporal-bucket-format-CFfWXRl9.cjs → saved-temporal-bucket-format-3QKveR3v.cjs} +1 -1
  46. package/dist/chunks/{saved-temporal-bucket-format-SGAV0ivR.js → saved-temporal-bucket-format-Dd2eixTH.js} +11 -11
  47. package/dist/chunks/switch-DBZsEV0U.cjs +138 -0
  48. package/dist/chunks/{switch-DQR-Va05.js → switch-kPUJEC1A.js} +6615 -5219
  49. package/dist/chunks/{temporal-bucket-5UYEotyQ.js → temporal-bucket-C85rmFmC.js} +4 -4
  50. package/dist/chunks/temporal-bucket-authoring-1fZuPAVb.js +653 -0
  51. package/dist/chunks/temporal-bucket-authoring-BK1UhYpD.cjs +1 -0
  52. package/dist/chunks/{temporal-bucket-contract-D5d-xEl3.js → temporal-bucket-contract-DXXNZssK.js} +1 -1
  53. package/dist/chunks/{temporal-bucket-contract-D2-93DGr.cjs → temporal-bucket-contract-xFkvboaw.cjs} +1 -1
  54. package/dist/chunks/{temporal-bucket-DHY1y9lq.cjs → temporal-bucket-pMfghsLX.cjs} +1 -1
  55. package/dist/chunks/{token-types-GbxRUozo.js → token-types-BLxc7UwR.js} +1 -1
  56. package/dist/chunks/{token-types-D7CaaI80.cjs → token-types-BYYO109W.cjs} +1 -1
  57. package/dist/chunks/{update-policy-hednMF-0.js → update-policy-CB8XJIoY.js} +1 -1
  58. package/dist/chunks/{update-policy-BmiOd0PB.cjs → update-policy-DMjjGjQY.cjs} +1 -1
  59. package/dist/chunks/{validators-DEmd8Sin.js → validators-DVd8s3qY.js} +416 -350
  60. package/dist/chunks/validators-dJlwubP4.cjs +1 -0
  61. package/dist/dashboard/index.cjs +1 -1
  62. package/dist/dashboard/index.js +2 -2
  63. package/dist/dashboard-authoring/index.cjs +3 -3
  64. package/dist/dashboard-authoring/index.js +328 -311
  65. package/dist/data-app-builder/index.cjs +1 -1
  66. package/dist/data-app-builder/index.js +2 -2
  67. package/dist/data-app-codegen/index.cjs +1 -1
  68. package/dist/data-app-codegen/index.js +2 -2
  69. package/dist/data-app-codegen-node/index.cjs +1 -1
  70. package/dist/data-app-codegen-node/index.js +3 -3
  71. package/dist/data-app-sdk/index.cjs +1 -1
  72. package/dist/data-app-sdk/index.js +55 -55
  73. package/dist/data-app-sdk-adapters/index.cjs +1 -1
  74. package/dist/data-app-sdk-adapters/index.js +61 -56
  75. package/dist/data-app-sdk-validation/index.cjs +1 -1
  76. package/dist/data-app-sdk-validation/index.js +9 -9
  77. package/dist/format-utils/index.cjs +1 -1
  78. package/dist/format-utils/index.js +15 -15
  79. package/dist/index.cjs +1 -1
  80. package/dist/index.js +154 -155
  81. package/dist/report-runtime-context/index.cjs +1 -1
  82. package/dist/report-runtime-context/index.js +2 -2
  83. package/dist/style.css +1 -1
  84. package/dist/surfboard/index.cjs +1 -1
  85. package/dist/surfboard/index.js +3 -3
  86. package/dist/types/analytics-protocol.d.ts +16 -8
  87. package/dist/types/briefings.d.ts +95 -13
  88. package/dist/types/dashboard-assistant.d.ts +11 -6
  89. package/dist/types/dashboard-authoring.d.ts +257 -19
  90. package/dist/types/dashboard.d.ts +109 -14
  91. package/dist/types/data-app-builder.d.ts +11 -6
  92. package/dist/types/data-app-codegen-node.d.ts +16 -8
  93. package/dist/types/data-app-codegen.d.ts +16 -8
  94. package/dist/types/data-app-sdk-adapters.d.ts +17 -11
  95. package/dist/types/data-app-sdk-validation.d.ts +17 -11
  96. package/dist/types/data-app-sdk.d.ts +17 -11
  97. package/dist/types/index.cjs +1 -1
  98. package/dist/types/index.js +4 -4
  99. package/dist/types/main.d.ts +225 -20
  100. package/dist/types/shared.d.ts +95 -13
  101. package/dist/types/surfboard.d.ts +109 -14
  102. package/dist/types/types.d.ts +109 -14
  103. package/package.json +1 -1
  104. package/dist/chunks/canonical-result-keys-BA0HCP4e.cjs +0 -1
  105. package/dist/chunks/canonical-result-keys-D6avdjpA.js +0 -467
  106. package/dist/chunks/dashboard-date-comparison-definition-Ces4alFm.cjs +0 -1
  107. package/dist/chunks/dashboard-json-BhvPMpZA.cjs +0 -1
  108. package/dist/chunks/index-DHF-2AqS.cjs +0 -1392
  109. package/dist/chunks/index-k8tEp0ys.cjs +0 -4
  110. package/dist/chunks/matrix-result-contract-zamd9euI.cjs +0 -1
  111. package/dist/chunks/switch-f3TuZNLr.cjs +0 -138
  112. package/dist/chunks/temporal-bucket-authoring-K1kE6R_z.js +0 -222
  113. package/dist/chunks/temporal-bucket-authoring-o3Emn05L.cjs +0 -1
  114. package/dist/chunks/validators-BDYprKI9.cjs +0 -1
@@ -0,0 +1 @@
1
+ "use strict";const C=require("./validators-dJlwubP4.cjs");require("./analyze-result-contract-DSGoFuXQ.cjs");const P=require("./temporal-bucket-pMfghsLX.cjs"),H=require("../value-format-preferences/index.cjs"),O=new Set(["previous_period","same_period_last_year","start_vs_end","target"]),U=new Set([...O,"none",""]);function m(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function I(e){const o=m(e.preferences)?e.preferences:void 0,t=o&&m(o.kpiVisualOptions)?o.kpiVisualOptions:void 0,r=o&&m(o.tableVisualOptions)?o.tableVisualOptions:void 0;return{preferences:o,kpiOptions:t,kpiComparison:t&&m(t.metricComparison)?t.metricComparison:void 0,kpiComparisonPresent:!!t&&"metricComparison"in t,tableOptions:r,tableComparison:r&&m(r.metricComparison)?r.metricComparison:void 0,tableComparisonPresent:!!r&&"metricComparison"in r}}function w(e){const o=[],t=(r,a)=>{if(Array.isArray(r)){r.forEach((n,s)=>t(n,`${a}[${s}]`));return}if(!m(r))return;const c=r.config;if(m(c)){const n=I(r),s=!!(n.kpiComparisonPresent||n.tableComparisonPresent),u=c.metricColumns,l=Array.isArray(u)?u.flatMap((p,i)=>m(p)?[{index:i,metric:p}]:[]):[];if((l.some(({metric:p})=>"comparisonType"in p)||s)&&o.push({path:a,card:r,metrics:l,malformedMetricIndexes:Array.isArray(u)?u.flatMap((p,i)=>m(p)?[]:[i]):[],malformedMetricColumns:"metricColumns"in c&&!Array.isArray(u),hasLegacyPresentation:s}),"metricColumns"in c||s)return}Object.entries(r).forEach(([n,s])=>t(s,a?`${a}.${n}`:n))};return t(e,"$"),o}const R={difference:"difference",change:"percent_change",change_difference:"both",ratio:"ratio"};function D(e,o){if(!e)return;const t=Object.fromEntries(o.flatMap(r=>typeof e[r]=="string"?[[r,e[r]]]:[]));return Object.keys(t).length?t:void 0}function q(e,o,t){if(e!==void 0){if(!m(e)){t.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:o,message:"Legacy comparison formatOptions must be an object."});return}Object.entries(e).forEach(([r,a])=>{if(r==="decimalPlaces"){(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&t.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${o}.decimalPlaces`,message:"Legacy comparison decimalPlaces must be an integer from 0 through 6."});return}r==="type"&&(a===void 0||a==="auto")||a!==void 0&&t.push({severity:"error",code:"unsupported_comparison_format",path:`${o}.${r}`,message:`Legacy comparison format option "${r}" has no canonical presentation mapping.`})})}}function k(e,o){const t=o==="kpi"?e.calculationType:e.calculatedAs,r=o==="table"&&t===void 0?"both":R[String(t)],a=m(e.formatOptions)?e.formatOptions:void 0,c=m(e.conditionalLabels)?e.conditionalLabels:void 0,n=m(o==="kpi"?e.colorConfig:e.colors)?o==="kpi"?e.colorConfig:e.colors:void 0,s={};if(r&&(s.displayMode=r),typeof(a==null?void 0:a.decimalPlaces)=="number"&&(s.precision=a.decimalPlaces),o==="kpi"){const p=e.showArrow!==!1,i=e.showColor!==!1;s.indicatorStyle=p?i?"arrow_badge":"arrow":i?"badge":"none",s.showColor=i,(e.position==="left"||e.position==="right"||e.position==="top")&&(s.position=e.position),typeof e.conditionalLabel=="boolean"&&(s.conditionalLabel=e.conditionalLabel),typeof e.labelName=="string"&&(s.labelName=e.labelName)}else(e.indicatorStyle==="arrow_badge"||e.indicatorStyle==="arrow"||e.indicatorStyle==="badge"||e.indicatorStyle==="none")&&(s.indicatorStyle=e.indicatorStyle);const u=c?{...D(c,["increase","decrease"]),...typeof c.noChange=="string"?{neutral:c.noChange}:typeof c.neutral=="string"?{neutral:c.neutral}:{}}:void 0;u&&Object.keys(u).length&&(s.conditionalLabels=u);const l=n?{...D(n,["increase","decrease"]),...typeof n.noChange=="string"?{neutral:n.noChange}:typeof n.neutral=="string"?{neutral:n.neutral}:{}}:void 0;return l&&Object.keys(l).length&&(s.colors=l),s}function $(e){return{...P.COMPARISON_PRESENTATION_DEFAULTS,...e}}function S(e){return e.some(({metric:o})=>o.comparisonType==="previous_period"||o.comparisonType==="same_period_last_year"||o.comparisonType==="target"?!0:m(o.comparison)&&o.comparison.mode==="explicit")}function A(e){const o=e.card.config;return e.metrics.length===2&&(o.groupByColumns===void 0||Array.isArray(o.groupByColumns)&&o.groupByColumns.length===0)}function L(e,o,t,r){const a=o==="kpi"?["enabled","calculationType","formatOptions","showArrow","showColor","conditionalLabel","labelName","position","conditionalLabels","colorConfig","lowerIsBetter"]:["calculatedAs","indicatorStyle","formatOptions","colors","lowerIsBetter"];Object.keys(e).forEach(p=>{a.includes(p)||r.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${t}.${p}`,message:`Unknown legacy comparison presentation field "${p}" cannot be dropped automatically.`})});const c=o==="kpi"?"calculationType":"calculatedAs";e[c]!==void 0&&!R[String(e[c])]&&r.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${t}.${c}`,message:`Legacy comparison ${c} is unsupported.`}),o==="kpi"&&e.position!==void 0&&!["left","right","top"].includes(String(e.position))&&r.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${t}.position`,message:"Legacy comparison position is unsupported."}),o==="kpi"&&e.labelName!==void 0&&typeof e.labelName!="string"&&r.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${t}.labelName`,message:"Legacy comparison labelName must be a string."}),(o==="kpi"?[["conditionalLabels",["increase","decrease","noChange"]],["colorConfig",["increase","decrease","noChange"]]]:[["colors",["increase","decrease","neutral"]]]).forEach(([p,i])=>{if(e[p]!==void 0){if(!m(e[p])){r.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${t}.${p}`,message:`Legacy comparison ${p} must be an object.`});return}Object.entries(e[p]).forEach(([h,d])=>{i.includes(h)?typeof d!="string"&&r.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${t}.${p}.${h}`,message:`Legacy comparison ${p}.${h} must be a string.`}):r.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${t}.${p}.${h}`,message:`Unknown legacy comparison ${p} field "${h}" cannot be dropped automatically.`})})}}),(o==="kpi"?["enabled","showArrow","showColor","conditionalLabel","lowerIsBetter"]:["lowerIsBetter"]).forEach(p=>{e[p]!==void 0&&typeof e[p]!="boolean"&&r.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${t}.${p}`,message:`Legacy comparison ${p} must be a boolean.`})}),o==="table"&&e.indicatorStyle!==void 0&&!["arrow_badge","arrow","badge","none"].includes(String(e.indicatorStyle))&&r.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${t}.indicatorStyle`,message:"Legacy comparison indicatorStyle is unsupported."}),q(e.formatOptions,`${t}.formatOptions`,r);const u=k(e,o);P.validateComparisonPresentationSpec(u,t).errors.forEach(p=>{r.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:p.path||t,message:p.message})})}function B(e){const o=I(e.card),t=o.kpiComparison?k(o.kpiComparison,"kpi"):void 0,r=o.tableComparison?k(o.tableComparison,"table"):void 0;return{namespaces:o,kpi:t,table:r,presentation:t||r}}function J(e){const o=m(e.preferences)?e.preferences:{},t=m(o.kpiVisualOptions)?o.kpiVisualOptions:{},r=m(t.metricComparison)?t.metricComparison:{},a=m(o.tableVisualOptions)?o.tableVisualOptions:{},c=m(a.metricComparison)?a.metricComparison:{};return t.lowerIsBetter===!0||r.lowerIsBetter===!0||c.lowerIsBetter===!0?"lower_is_better":"higher_is_better"}function x(e){switch(e.comparisonType){case"previous_period":return{mode:"explicit",spec:{kind:"previous_period"}};case"same_period_last_year":return{mode:"explicit",spec:{kind:"previous_year"}};case"target":return{mode:"explicit",spec:{kind:"target",targetValue:e.targetValue}};default:return}}function z(e){const o=m(e.preferences)?e.preferences:void 0;if(!o)return;const t=m(o.kpiVisualOptions)?o.kpiVisualOptions:void 0;t&&delete t.lowerIsBetter;const r=m(o.tableVisualOptions)?o.tableVisualOptions:void 0,a=r&&m(r.metricComparison)?r.metricComparison:void 0;a&&delete a.lowerIsBetter}function G(e){const o=w(e);if(!o.length)return{document:e,changed:!1,changes:[],diagnostics:[]};const t=[];if(o.forEach(n=>{var s,u,l,p;if(n.malformedMetricColumns&&t.push({severity:"error",code:"malformed_metric_columns",path:`${n.path}.config.metricColumns`,message:"Metric columns must be an array before comparison migration."}),n.malformedMetricIndexes.forEach(i=>{t.push({severity:"error",code:"malformed_metric_columns",path:`${n.path}.config.metricColumns[${i}]`,message:"Metric columns must contain objects before comparison migration."})}),n.metrics.forEach(({metric:i,index:h})=>{if(!("comparisonType"in i))return;const d=`${n.path}.config.metricColumns[${h}]`,g=String(i.comparisonType||"");"comparison"in i&&t.push({severity:"error",code:"conflicting_comparison_contracts",path:d,message:"Metric contains both legacy and canonical comparison configuration; resolve the conflict before migration."});const b=m(i.parameters)?i.parameters:void 0,Y=b&&m(b.windowTransform)?b.windowTransform:void 0;O.has(g)&&(Y==null?void 0:Y.function)==="previous_period_delta"&&t.push({severity:"error",code:"conflicting_comparison_window_transform",path:d,message:"A metric cannot combine baseline comparison with previous_period_delta; resolve the authoring intent before migration."}),U.has(g)||t.push({severity:"error",code:"unsupported_comparison_type",path:`${d}.comparisonType`,message:`Unsupported legacy metric comparison type "${g}".`}),i.comparisonType==="target"&&(typeof i.targetValue!="number"||!Number.isFinite(i.targetValue))&&t.push({severity:"error",code:"invalid_target_value",path:`${d}.targetValue`,message:"Legacy target comparison requires a finite metric targetValue."}),i.comparisonType==="start_vs_end"&&t.push({severity:"error",code:"unsupported_start_vs_end",path:`${d}.comparisonType`,message:"start_vs_end is retired and cannot be migrated automatically."}),i.targetValue!==void 0&&i.comparisonType!=="target"&&t.push({severity:"warning",code:"stray_target_value",path:`${d}.targetValue`,message:"Dead non-target targetValue will be removed without changing the baseline."})}),n.hasLegacyPresentation){const{namespaces:i,kpi:h,table:d}=B(n),g=[(s=i.kpiOptions)==null?void 0:s.lowerIsBetter,(u=i.kpiComparison)==null?void 0:u.lowerIsBetter,(l=i.tableComparison)==null?void 0:l.lowerIsBetter].filter(b=>typeof b=="boolean");new Set(g).size>1&&t.push({severity:"error",code:"conflicting_legacy_polarity",path:`${n.path}.preferences`,message:"Legacy comparison polarity values disagree; resolve the conflict before migration."}),((p=i.kpiOptions)==null?void 0:p.lowerIsBetter)!==void 0&&typeof i.kpiOptions.lowerIsBetter!="boolean"&&t.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${n.path}.preferences.kpiVisualOptions.lowerIsBetter`,message:"Legacy comparison lowerIsBetter must be a boolean."}),i.kpiComparisonPresent&&!i.kpiComparison&&t.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${n.path}.preferences.kpiVisualOptions.metricComparison`,message:"Legacy KPI comparison presentation must be an object."}),i.tableComparisonPresent&&!i.tableComparison&&t.push({severity:"error",code:"invalid_legacy_comparison_presentation",path:`${n.path}.preferences.tableVisualOptions.metricComparison`,message:"Legacy table comparison presentation must be an object."}),"comparisonPresentation"in(i.preferences||{})&&t.push({severity:"error",code:"conflicting_comparison_presentation_contracts",path:`${n.path}.preferences.comparisonPresentation`,message:"Card contains both legacy and canonical comparison presentation; resolve the conflict before migration."}),i.kpiComparison&&typeof i.kpiComparison.enabled=="boolean"&&"metricPairComparisonEnabled"in(i.preferences||{})&&A(n)&&t.push({severity:"error",code:"conflicting_comparison_presentation_contracts",path:`${n.path}.preferences.metricPairComparisonEnabled`,message:"Card contains both legacy and canonical metric-pair enablement; resolve the conflict before migration."}),i.kpiComparison&&L(i.kpiComparison,"kpi",`${n.path}.preferences.kpiVisualOptions.metricComparison`,t),i.tableComparison&&L(i.tableComparison,"table",`${n.path}.preferences.tableVisualOptions.metricComparison`,t),h&&d&&JSON.stringify($(h))!==JSON.stringify($(d))&&t.push({severity:"error",code:"conflicting_legacy_presentation_namespaces",path:`${n.path}.preferences`,message:"KPI and table comparison presentation values disagree; resolve the conflict before migration."})}}),t.some(n=>n.severity==="error"))return{document:e,changed:!1,changes:[],diagnostics:t};const r=JSON.parse(JSON.stringify(e)),a=w(r),c=[];return a.forEach(n=>{var u;const s=J(n.card);if(n.metrics.forEach(({metric:l,index:p})=>{if(!("comparisonType"in l))return;const i=String(l.comparisonType||""),h=`${n.path}.config.metricColumns[${p}]`,d=x(l),g=["comparisonType"];delete l.comparisonType,"targetValue"in l&&(delete l.targetValue,g.push("targetValue")),"comparisonDisplay"in l&&(delete l.comparisonDisplay,g.push("comparisonDisplay")),d?l.comparison=d:delete l.comparison,O.has(i)&&(l.comparisonPolarity=s),c.push({kind:"metric",path:h,metricId:typeof l.id=="string"?l.id:void 0,legacyType:i,comparison:d,comparisonPolarity:O.has(i)?s:void 0,removedFields:g})}),z(n.card),n.hasLegacyPresentation){const{namespaces:l,presentation:p}=B(n),i=(u=l.kpiComparison)==null?void 0:u.enabled,h={...p};typeof i=="boolean"&&S(n.metrics)&&(h.showComparison=i);const d=typeof i=="boolean"&&A(n)?i:void 0,g=typeof i=="boolean"&&!S(n.metrics)&&!A(n)?["kpiVisualOptions.metricComparison.enabled"]:void 0,b=l.preferences,Y=[];n.metrics.forEach(({metric:T})=>{"comparisonPolarity"in T||(T.comparisonPolarity=s,typeof T.id=="string"&&Y.push(T.id))}),Object.keys(h).length&&(b.comparisonPresentation=h),d!==void 0&&(b.metricPairComparisonEnabled=d),l.kpiOptions&&delete l.kpiOptions.metricComparison,l.tableOptions&&delete l.tableOptions.metricComparison,c.push({kind:"presentation",path:`${n.path}.preferences`,comparisonPresentation:Object.keys(h).length?h:void 0,metricPairComparisonEnabled:d,comparisonPolarityMetricIds:Y,intentionallyDiscardedFields:g,removedFields:[...l.kpiComparison?["kpiVisualOptions.metricComparison"]:[],...l.tableComparison?["tableVisualOptions.metricComparison"]:[]]})}}),{document:r,changed:!0,changes:c,diagnostics:t}}const N=["bar","horizontalBar","line","area","stackedArea","combo","stackedBar","stackedLine"],K=new Set(N);function F(e){return typeof e=="string"&&K.has(e)}function W(e){return e==="detailTable"||e==="table"||e==="aggregateTable"||e==="pivotTable"||e==="custom"||F(e)}function V(e){return!!(e!=null&&e.trim())}function Q(e){return V(e.sql)||V(e.normalizedPython)?"freeform":e.hasExecutableConfig?"config":"none"}const M={type:"temporal_bucket",presentation:{mode:"auto"}},_={value:"auto",label:"Automatic",format:M};function f(e,o){return{value:`pattern:${e}`,label:o,format:{type:"temporal_bucket",presentation:{mode:"pattern",pattern:e}}}}function v(e,o){return{value:`preset:${e}`,label:o,format:{type:"temporal_bucket",presentation:{mode:"preset",preset:e}}}}function y(e){return{...f(e,"Custom format…"),value:"custom",custom:!0}}const E={second:[_,f("HH:mm:ss","14:30:45 (HH:mm:ss)"),f("YYYY-MM-DD HH:mm:ss","2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"),y("DD/MM/YYYY HH:mm:ss")],minute:[_,f("HH:mm","14:30 (HH:mm)"),f("YYYY-MM-DD HH:mm","2024-01-15 14:30 (YYYY-MM-DD HH:mm)"),y("DD/MM/YYYY HH:mm")],hour:[_,f("HH","14 (HH)"),f("YYYY-MM-DD HH","2024-01-15 14 (YYYY-MM-DD HH)"),y("DD/MM/YYYY HH")],day:[_,f("YYYY-MM-DD","2024-01-15 (YYYY-MM-DD)"),f("MM/DD/YYYY","01/15/2024 (MM/DD/YYYY)"),f("DD/MM/YYYY","15/01/2024 (DD/MM/YYYY)"),f("MMM DD, YYYY","Jan 15, 2024 (MMM DD, YYYY)"),f("MMMM DD, YYYY","January 15, 2024 (MMMM DD, YYYY)"),y("YYYY/MM/DD")],week:[_,v("week_of_short","Week of Jan 15, 2024"),v("week_of_long","Week of January 15, 2024"),f("YYYY-MM-DD","2024-01-15 (YYYY-MM-DD)"),y("YYYY/MM/DD")],month:[_,f("MMM YYYY","Jan 2024 (MMM YYYY)"),f("MMMM YYYY","January 2024 (MMMM YYYY)"),f("YYYY-MM","2024-01 (YYYY-MM)"),f("MM/YYYY","01/2024 (MM/YYYY)"),f("YYYY MMM","2024 Jan (YYYY MMM)"),y("YYYY/MM")],quarter:[_,v("quarter_short","Q1 2024"),v("quarter_long","1st Quarter 2024")],year:[_,f("YYYY","2024 (YYYY)"),f("YY","24 (YY)")]},X={second:"2026-07-31T14:05:09",minute:"2026-07-31T14:05:00",hour:"2026-07-31T14:00:00",day:"2026-07-31",week:"2026-07-27",month:"2026-07-01",quarter:"2026-07-01",year:"2026-01-01"};function j(e,o,t=H.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES){return P.formatTemporalBucket({value:X[o],metadata:{kind:"temporal_bucket",granularity:o,calendar:{tz:"UTC",weekStart:1,...e.presentation.mode==="preset"&&(e.presentation.preset==="fiscal_quarter_short"||e.presentation.preset==="fiscal_year")?{fiscalCalendar:{kind:"month_aligned",yearStartMonth:7}}:{}}},format:e.presentation.mode==="auto"?{type:"temporal_bucket",locale:t.locale,presentation:{mode:"auto",styles:{dateStyle:t.dateStyle,dateTime:{...t.dateTime}}}}:{type:"temporal_bucket",locale:t.locale,presentation:e.presentation}})}function Z(e,o,t=H.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES){const r=E[e],a=(o==null?void 0:o.presentation.mode)==="preset"?o.presentation.preset:void 0,c=a&&o&&C.validateTemporalBucketFormatApplicability(o,e).ok&&!r.some(s=>{var u;return((u=s.format)==null?void 0:u.presentation.mode)==="preset"&&s.format.presentation.preset===a})?v(a,a):void 0;return(c?[...r,c]:r).map(s=>{if(!s.format||s.custom)return s;const u=j(s.format,e,t);return s.format.presentation.mode==="pattern"?{...s,label:`${u} (${s.format.presentation.pattern})`}:s.format.presentation.mode==="auto"?{...s,label:`Automatic (${u})`}:{...s,label:u}})}function ee(e,o){const t=E[o];if(e.presentation.mode==="pattern"){const r=e.presentation.pattern,a=t.find(c=>{var n;return((n=c.format)==null?void 0:n.presentation.mode)==="pattern"&&c.format.presentation.pattern===r});return{value:(a==null?void 0:a.value)??"custom",customPattern:a!=null&&a.custom||!a?r:"",format:e}}if(e.presentation.mode==="preset"){const r=e.presentation.preset,a=t.find(n=>{var s;return((s=n.format)==null?void 0:s.presentation.mode)==="preset"&&n.format.presentation.preset===r}),c=C.validateTemporalBucketFormatApplicability(e,o).ok;return a?{value:a.value,customPattern:"",format:e}:c?{value:`preset:${r}`,customPattern:"",format:e}:{value:"auto",customPattern:"",format:M}}return{value:"auto",customPattern:"",format:e}}function oe(e,o,t=""){var n;const r=E[e].find(s=>s.value===o),a=o.startsWith("preset:")?o.slice(7):void 0,c=o==="custom"?{type:"temporal_bucket",presentation:{mode:"pattern",pattern:t.trim()||(((n=r==null?void 0:r.format)==null?void 0:n.presentation.mode)==="pattern"?r.format.presentation.pattern:"")}}:(r==null?void 0:r.format)??(a&&C.isTemporalBucketPreset(a)?{type:"temporal_bucket",presentation:{mode:"preset",preset:a}}:void 0);return!c||!C.validateTemporalBucketFormatApplicability(c,e).ok?M:c}function te(e,o){return C.validateTemporalBucketFormatApplicability(e,o).ok?e:M}exports.AUTOMATIC_TEMPORAL_BUCKET_FORMAT=M;exports.SEMAPHOR_CARTESIAN_CHART_TYPES=N;exports.getTemporalBucketAuthoringOptions=Z;exports.getTemporalBucketAuthoringSelection=ee;exports.isSemaphorCartesianChartType=F;exports.previewTemporalBucketAuthoringFormat=j;exports.reconcileTemporalBucketAuthoringFormat=te;exports.resolveTemporalBucketAuthoringFormat=oe;exports.resolveTemporalResultOwner=Q;exports.supportsCanonicalDashboardTemporalResult=W;exports.transformComparisonDocument=G;
@@ -1,4 +1,4 @@
1
- import { t as i, T as l, f as u } from "./validators-DEmd8Sin.js";
1
+ import { t as i, T as l, e as u } from "./validators-DVd8s3qY.js";
2
2
  function c(e) {
3
3
  const r = i.safeParse(e);
4
4
  return r.success ? { ok: !0, value: r.data } : {
@@ -1 +1 @@
1
- "use strict";const n=require("./validators-BDYprKI9.cjs");function s(e){const r=n.temporalBucketMetadataSchema.safeParse(e);return r.success?{ok:!0,value:r.data}:{ok:!1,error:{code:n.TEMPORAL_BUCKET_CONTRACT_ERROR_CODES.invalidMetadata,message:"Temporal bucket metadata is invalid.",path:"temporalBucket"}}}function u(e,r){if(!e.temporalBucket)return r.metadataRequired?{ok:!1,error:{code:n.TEMPORAL_BUCKET_CONTRACT_ERROR_CODES.missingMetadata,message:"Activated temporal bucket result is missing metadata.",path:"temporalBucket"}}:{ok:!0};const t=s(e.temporalBucket);if(!t.ok||!t.value)return t;const a=n.temporalBucketDataTypeForGrain(t.value.granularity);return e.dataType!==a?{ok:!1,error:{code:n.TEMPORAL_BUCKET_CONTRACT_ERROR_CODES.invalidMetadata,message:`${t.value.granularity} temporal buckets require dataType ${a}.`,path:"dataType"}}:t}function i(e,r){var t,a,o,l;return e.granularity===r.granularity&&e.calendar.tz===r.calendar.tz&&e.calendar.weekStart===r.calendar.weekStart&&((t=e.calendar.fiscalCalendar)==null?void 0:t.kind)===((a=r.calendar.fiscalCalendar)==null?void 0:a.kind)&&((o=e.calendar.fiscalCalendar)==null?void 0:o.yearStartMonth)===((l=r.calendar.fiscalCalendar)==null?void 0:l.yearStartMonth)}function c(e,r){const t=new Map;for(const a of e){if(t.has(a.key))return{ok:!1,error:{code:n.TEMPORAL_BUCKET_CONTRACT_ERROR_CODES.invalidMetadata,message:`Canonical result contains duplicate column key "${a.key}".`,path:"columns"}};if(t.set(a.key,a),a.temporalBucket){const o=u(a,{metadataRequired:!1});if(!o.ok)return{ok:!1,error:{...o.error,path:`columns.${a.key}.${o.error.path||"temporalBucket"}`}}}}for(const a of r){const o=t.get(a.key);if(!o)return{ok:!1,error:{code:n.TEMPORAL_BUCKET_CONTRACT_ERROR_CODES.missingMetadata,message:`Activated temporal bucket result is missing column "${a.key}".`,path:`columns.${a.key}`}};const l=u(o,{metadataRequired:!0});if(!l.ok)return{ok:!1,error:{...l.error,path:`columns.${a.key}.${l.error.path||"temporalBucket"}`}};if(!l.value||!i(l.value,a.metadata))return{ok:!1,error:{code:n.TEMPORAL_BUCKET_CONTRACT_ERROR_CODES.invalidMetadata,message:`Temporal bucket metadata for column "${a.key}" contradicts the governed query context.`,path:`columns.${a.key}.temporalBucket`}}}return{ok:!0,value:e}}exports.validateActivatedTemporalBucketResultColumns=c;exports.validateTemporalBucketMetadata=s;exports.validateTemporalBucketResultColumn=u;
1
+ "use strict";const n=require("./validators-dJlwubP4.cjs");function s(e){const r=n.temporalBucketMetadataSchema.safeParse(e);return r.success?{ok:!0,value:r.data}:{ok:!1,error:{code:n.TEMPORAL_BUCKET_CONTRACT_ERROR_CODES.invalidMetadata,message:"Temporal bucket metadata is invalid.",path:"temporalBucket"}}}function u(e,r){if(!e.temporalBucket)return r.metadataRequired?{ok:!1,error:{code:n.TEMPORAL_BUCKET_CONTRACT_ERROR_CODES.missingMetadata,message:"Activated temporal bucket result is missing metadata.",path:"temporalBucket"}}:{ok:!0};const t=s(e.temporalBucket);if(!t.ok||!t.value)return t;const a=n.temporalBucketDataTypeForGrain(t.value.granularity);return e.dataType!==a?{ok:!1,error:{code:n.TEMPORAL_BUCKET_CONTRACT_ERROR_CODES.invalidMetadata,message:`${t.value.granularity} temporal buckets require dataType ${a}.`,path:"dataType"}}:t}function i(e,r){var t,a,o,l;return e.granularity===r.granularity&&e.calendar.tz===r.calendar.tz&&e.calendar.weekStart===r.calendar.weekStart&&((t=e.calendar.fiscalCalendar)==null?void 0:t.kind)===((a=r.calendar.fiscalCalendar)==null?void 0:a.kind)&&((o=e.calendar.fiscalCalendar)==null?void 0:o.yearStartMonth)===((l=r.calendar.fiscalCalendar)==null?void 0:l.yearStartMonth)}function c(e,r){const t=new Map;for(const a of e){if(t.has(a.key))return{ok:!1,error:{code:n.TEMPORAL_BUCKET_CONTRACT_ERROR_CODES.invalidMetadata,message:`Canonical result contains duplicate column key "${a.key}".`,path:"columns"}};if(t.set(a.key,a),a.temporalBucket){const o=u(a,{metadataRequired:!1});if(!o.ok)return{ok:!1,error:{...o.error,path:`columns.${a.key}.${o.error.path||"temporalBucket"}`}}}}for(const a of r){const o=t.get(a.key);if(!o)return{ok:!1,error:{code:n.TEMPORAL_BUCKET_CONTRACT_ERROR_CODES.missingMetadata,message:`Activated temporal bucket result is missing column "${a.key}".`,path:`columns.${a.key}`}};const l=u(o,{metadataRequired:!0});if(!l.ok)return{ok:!1,error:{...l.error,path:`columns.${a.key}.${l.error.path||"temporalBucket"}`}};if(!l.value||!i(l.value,a.metadata))return{ok:!1,error:{code:n.TEMPORAL_BUCKET_CONTRACT_ERROR_CODES.invalidMetadata,message:`Temporal bucket metadata for column "${a.key}" contradicts the governed query context.`,path:`columns.${a.key}.temporalBucket`}}}return{ok:!0,value:e}}exports.validateActivatedTemporalBucketResultColumns=c;exports.validateTemporalBucketMetadata=s;exports.validateTemporalBucketResultColumn=u;
@@ -1 +1 @@
1
- "use strict";var q=Object.defineProperty;var B=(e,r,t)=>r in e?q(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var v=(e,r,t)=>B(e,typeof r!="symbol"?r+"":r,t);const h=require("./validators-BDYprKI9.cjs"),I=require("../value-format-preferences/index.cjs"),F="higher_is_better",G={displayMode:"difference",showComparison:!0,indicatorStyle:"arrow_badge",showColor:!0,conditionalLabel:!1};function V(e){return h.parseSemaphorIsoInstant(e)!==null}function H(e){var r,t,o,n;if(((r=e.metricComparison)==null?void 0:r.mode)!=="off"){if(((t=e.metricComparison)==null?void 0:t.mode)==="explicit")return{source:"explicit",spec:e.metricComparison.spec};if(!((e.inheritGlobalComparison??((o=e.globalDateComparison)==null?void 0:o.inheritGlobalComparison))===!1||((n=e.globalDateComparison)==null?void 0:n.selection.mode)!=="period"))return{source:"inherited",spec:e.globalDateComparison.selection.spec,...e.globalDateComparison.owner?{owner:e.globalDateComparison.owner}:{}}}}function J(e){if(e.alias)return e.alias;const r=e.entityName&&e.entityName!=="SEMAPHOR_CALCULATED_FIELD"?e.entityName:void 0,t=r&&r!==e.name?`${r}_`:"";if(e.role!=="metric")return`${t}${e.name}`;let o=e.aggregate||"metric";if(e.expression){const n=e.expression.match(/^(COUNT|SUM|AVG|MIN|MAX|MEDIAN|DISTINCT)\s*\(/i);o=n?n[1].toLowerCase():"expr"}else o=o.toLowerCase();return`${t}${e.name}_${o}`}function i(e,r,t){return t?{code:e,message:r,path:t}:{code:e,message:r}}function d(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function u(e,r,t,o){Object.keys(e).forEach(n=>{r.includes(n)||o.push(i("invalid_comparison_spec",`Comparison kind does not accept field "${n}".`,`${t}.${n}`))})}function D(e,r,t){e.alignment!==void 0&&e.alignment!=="calendar"&&e.alignment!=="weekday"&&t.push(i("invalid_comparison_spec",'Comparison alignment must be "calendar" or "weekday".',`${r}.alignment`)),e.toDate!==void 0&&typeof e.toDate!="boolean"&&t.push(i("invalid_comparison_spec","Comparison toDate must be a boolean.",`${r}.toDate`))}function E(e,r,t){e!==void 0&&(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)&&t.push(i("invalid_comparison_spec","Comparison offset must be a positive safe integer.",r))}function T(e,r="comparison"){const t=[];return d(e)?(e.kind==="previous_period"?(u(e,["kind","offsetPeriods","alignment","toDate"],r,t),E(e.offsetPeriods,`${r}.offsetPeriods`,t),D(e,r,t)):e.kind==="previous_year"?(u(e,["kind","offsetYears","alignment","toDate"],r,t),E(e.offsetYears,`${r}.offsetYears`,t),D(e,r,t)):e.kind==="target"?(u(e,["kind","targetValue"],r,t),(typeof e.targetValue!="number"||!Number.isFinite(e.targetValue))&&t.push(i("invalid_comparison_spec","Target comparison requires a finite targetValue.",`${r}.targetValue`))):t.push(i("invalid_comparison_spec","Comparison kind must be previous_period, previous_year, or target.",`${r}.kind`)),{ok:t.length===0,errors:t,warnings:[]}):{ok:!1,errors:[i("invalid_comparison_spec","Comparison spec must be an object.",r)],warnings:[]}}function z(e,r="comparison"){if(!d(e))return{ok:!1,errors:[i("invalid_comparison_config","Comparison config must be an object.",r)],warnings:[]};const t=[];return e.mode==="off"?u(e,["mode"],r,t):e.mode==="explicit"?(u(e,["mode","spec"],r,t),t.push(...T(e.spec,`${r}.spec`).errors)):t.push(i("invalid_comparison_config","Comparison mode must be off or explicit.",`${r}.mode`)),{ok:t.length===0,errors:t,warnings:[]}}function R(e,r="comparisonSelection"){if(!d(e))return{ok:!1,errors:[i("invalid_global_date_comparison","Global Date comparison selection must be an object.",r)],warnings:[]};const t=[];if(e.mode==="off")u(e,["mode"],r,t);else if(e.mode==="period"){u(e,["mode","spec"],r,t);const o=T(e.spec,`${r}.spec`);t.push(...o.errors),d(e.spec)&&e.spec.kind==="target"&&t.push(i("invalid_global_date_comparison","Global Date comparison supports previous_period or previous_year, not target.",`${r}.spec.kind`))}else t.push(i("invalid_global_date_comparison","Global Date comparison mode must be off or period.",`${r}.mode`));return{ok:t.length===0,errors:t,warnings:[]}}function Z(e,r="globalDateComparison"){if(!d(e))return{ok:!1,errors:[i("invalid_global_date_comparison","Global Date comparison context must be an object.",r)],warnings:[]};const t=[];return u(e,["selection","inheritGlobalComparison","owner","referenceTime"],r,t),t.push(...R(e.selection,`${r}.selection`).errors),e.inheritGlobalComparison!==void 0&&e.inheritGlobalComparison!==!1&&t.push(i("invalid_global_date_comparison","inheritGlobalComparison may only be false when present.",`${r}.inheritGlobalComparison`)),e.owner!==void 0&&(d(e.owner)?e.owner.kind==="global_date"?u(e.owner,["kind"],`${r}.owner`,t):e.owner.kind==="field_date"?(u(e.owner,["kind","filterId","label"],`${r}.owner`,t),(typeof e.owner.filterId!="string"||!e.owner.filterId.trim())&&t.push(i("invalid_global_date_comparison","Field Date comparison owner requires a non-empty filterId.",`${r}.owner.filterId`)),(typeof e.owner.label!="string"||!e.owner.label.trim())&&t.push(i("invalid_global_date_comparison","Field Date comparison owner requires a non-empty label.",`${r}.owner.label`))):t.push(i("invalid_global_date_comparison","Comparison owner kind must be global_date or field_date.",`${r}.owner.kind`)):t.push(i("invalid_global_date_comparison","Comparison owner must be an object.",`${r}.owner`))),e.referenceTime!==void 0&&(typeof e.referenceTime!="string"||!V(e.referenceTime))&&t.push(i("invalid_global_date_comparison","referenceTime must be a valid ISO date-time string when present.",`${r}.referenceTime`)),{ok:t.length===0,errors:t,warnings:[]}}function Q(e,r="comparisonPolarity"){return e==="higher_is_better"||e==="lower_is_better"||e==="neutral"?{ok:!0,errors:[],warnings:[]}:{ok:!1,errors:[i("invalid_comparison_polarity","Comparison polarity must be higher_is_better, lower_is_better, or neutral.",r)],warnings:[]}}function W(e,r="comparisonPresentation"){if(!d(e))return{ok:!1,errors:[i("invalid_comparison_presentation","Comparison presentation must be an object.",r)],warnings:[]};const t=[],o=["displayMode","showComparison","precision","indicatorStyle","showColor","position","conditionalLabel","labelName","conditionalLabels","colors"];return Object.keys(e).forEach(a=>{o.includes(a)||t.push(i("invalid_comparison_presentation",`Comparison presentation does not accept field "${a}".`,`${r}.${a}`))}),[["displayMode",["difference","percent_change","both","ratio"]],["indicatorStyle",["arrow_badge","arrow","badge","none"]],["position",["left","right","top"]]].forEach(([a,s])=>{e[a]!==void 0&&!s.includes(e[a])&&t.push(i("invalid_comparison_presentation",`Comparison presentation ${a} is invalid.`,`${r}.${a}`))}),["showComparison","showColor","conditionalLabel"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="boolean"&&t.push(i("invalid_comparison_presentation",`Comparison presentation ${a} must be a boolean.`,`${r}.${a}`))}),e.precision!==void 0&&(typeof e.precision!="number"||!Number.isInteger(e.precision)||e.precision<0||e.precision>6)&&t.push(i("invalid_comparison_presentation","Comparison presentation precision must be an integer from 0 through 6.",`${r}.precision`)),e.labelName!==void 0&&typeof e.labelName!="string"&&t.push(i("invalid_comparison_presentation","Comparison presentation labelName must be a string.",`${r}.labelName`)),["conditionalLabels","colors"].forEach(a=>{const s=e[a];if(s!==void 0){if(!d(s)){t.push(i("invalid_comparison_presentation",`Comparison presentation ${a} must be an object.`,`${r}.${a}`));return}Object.keys(s).forEach(l=>{["increase","decrease","neutral"].includes(l)||t.push(i("invalid_comparison_presentation",`Comparison presentation ${a} does not accept field "${l}".`,`${r}.${a}.${l}`))}),Object.entries(s).forEach(([l,c])=>{c!==void 0&&typeof c!="string"&&t.push(i("invalid_comparison_presentation",`Comparison presentation ${a}.${l} must be a string.`,`${r}.${a}.${l}`))})}}),{ok:t.length===0,errors:t,warnings:[]}}function K(e){return e===null?"unknown":e>0?"increase":e<0?"decrease":"no_change"}function X(e,r){return e==="unknown"||e==="no_change"||r==="neutral"?"neutral":r==="higher_is_better"&&e==="increase"||r==="lower_is_better"&&e==="decrease"?"favorable":"unfavorable"}function ee(e){const{currentValue:r,comparisonValue:t,polarity:o=F}=e,a=r!==null&&t!==null?r-t:null,s=a!==null&&t!==null&&t!==0?a/Math.abs(t):null,l=r!==null&&t!==null&&t!==0?r/t:null,c=K(a);return{status:t===null?"insufficient_history":"available",currentValue:r,comparisonValue:t,delta:a,percentChange:s,ratio:l,direction:c,sentiment:X(c,o)}}function _(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.getPrototypeOf(e);if(r===null||r===Object.prototype)return!0;const t=Object.prototype.hasOwnProperty.call(r,"constructor")?r.constructor:void 0;return typeof t=="function"&&Function.prototype.toString.call(t)===Function.prototype.toString.call(Object)}const x={dateStyle:"short",dateTime:{dateStyle:"short",timeStyle:"short"}};class y extends Error{constructor(t,o){super(o);v(this,"code");this.name="TemporalBucketContractError",this.code=t}}const re=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],te=["January","February","March","April","May","June","July","August","September","October","November","December"];function $(e){return{ok:!1,error:{code:"invalid_temporal_bucket_value",message:e}}}function oe(e){return e%4===0&&(e%100!==0||e%400===0)}function ne(e,r){return r===2?oe(e)?29:28:[4,6,9,11].includes(r)?30:31}function ae(e,r,t){const o=[0,3,2,5,0,3,5,1,4,6,2,4],n=r<3?e-1:e;return(n+Math.floor(n/4)-Math.floor(n/100)+Math.floor(n/400)+o[r-1]+t)%7}function M(e){var r;return(r=e.calendar.fiscalCalendar)==null?void 0:r.yearStartMonth}function ie(e,r){return(e-r+12)%12%3===0}function se(e,r){const{granularity:t}=r,o=M(r)??1;switch(t){case"second":return!0;case"minute":return e.second===0;case"hour":return e.minute===0&&e.second===0;case"day":return!0;case"week":return ae(e.year,e.month,e.day)===r.calendar.weekStart;case"month":return e.day===1;case"quarter":return e.day===1&&ie(e.month,o);case"year":return e.day===1&&e.month===o}}function L(e,r){if(e===null)return{ok:!0,value:null};const t=r.granularity==="second"||r.granularity==="minute"||r.granularity==="hour",o=t?/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})$/.exec(e):/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!o)return $(`Expected ${t?"YYYY-MM-DDTHH:mm:ss":"YYYY-MM-DD"} for ${r.granularity} granularity.`);const n={year:Number(o[1]),month:Number(o[2]),day:Number(o[3]),hour:t?Number(o[4]):0,minute:t?Number(o[5]):0,second:t?Number(o[6]):0};return n.year<1||n.month<1||n.month>12||n.day<1||n.day>ne(n.year,n.month)||n.hour>23||n.minute>59||n.second>59?$(`Invalid canonical ${r.granularity} bucket value ${e}.`):se(n,r)?{ok:!0,value:n}:$(`Canonical value ${e} is not aligned to ${r.granularity} granularity and its governed Calendar.`)}function Y(e){if(!_(e))return{ok:!1,issues:[{path:"$",message:"Resolved temporal bucket format must be an object."}]};const r=[],t=new Set(["type","presentation","locale"]);for(const s of Object.keys(e))t.has(s)||r.push({path:s,message:`Unknown property "${s}".`});e.type!=="temporal_bucket"&&r.push({path:"type",message:"Expected temporal_bucket."});const o=e.presentation;if(!_(o))r.push({path:"presentation",message:"Expected a presentation object."});else{const s=o.mode,l=s==="preset"?new Set(["mode","preset"]):s==="pattern"?new Set(["mode","pattern"]):s==="auto"?new Set(["mode","styles"]):new Set(["mode"]);for(const c of Object.keys(o))l.has(c)||r.push({path:`presentation.${c}`,message:`Unknown property "${c}".`});if(s==="preset")h.isTemporalBucketPreset(o.preset)||r.push({path:"presentation.preset",message:"Expected a supported preset."});else if(s==="pattern")if(typeof o.pattern!="string"||!o.pattern)r.push({path:"presentation.pattern",message:"Expected a non-empty pattern."});else{const c=h.tokenizeTemporalBucketPattern(o.pattern);c.ok||r.push({path:"presentation.pattern",message:c.message})}else if(s==="auto"){const c=o.styles;(!_(c)||!["short","medium","long"].includes(String(c.dateStyle))||!_(c.dateTime)||!["short","medium","long"].includes(String(c.dateTime.dateStyle))||!["short","medium","long"].includes(String(c.dateTime.timeStyle))||Object.keys(c).some(m=>m!=="dateStyle"&&m!=="dateTime")||Object.keys(c.dateTime).some(m=>m!=="dateStyle"&&m!=="timeStyle"))&&r.push({path:"presentation.styles",message:"Expected complete resolved date and datetime styles."})}else r.push({path:"presentation.mode",message:"Expected auto, preset, or pattern."})}const n=I.canonicalizeSupportedLocale(e.locale);if(n||r.push({path:"locale",message:"Expected a supported base BCP 47 locale."}),r.length>0||!n||!_(o))return{ok:!1,issues:r};if(o.mode==="auto"){const s=o.styles;return{ok:!0,value:{type:"temporal_bucket",locale:n,presentation:{mode:"auto",styles:{dateStyle:s.dateStyle,dateTime:{dateStyle:s.dateTime.dateStyle,timeStyle:s.dateTime.timeStyle}}}}}}return{ok:!0,value:{type:"temporal_bucket",presentation:o.mode==="preset"?{mode:"preset",preset:o.preset}:{mode:"pattern",pattern:o.pattern},locale:n}}}function ce(e,r){const t=!!r.calendar.fiscalCalendar;return e==="fiscal_quarter_short"||e==="fiscal_year"?t:e==="quarter_short"||e==="quarter_long"?!t:!0}function j(e,r){return h.validateTemporalBucketFormatApplicability(e,r.granularity).ok?e.presentation.mode==="preset"?ce(e.presentation.preset,r):!(e.presentation.mode==="pattern"&&r.calendar.fiscalCalendar&&(r.granularity==="quarter"||r.granularity==="year")):!1}function A(e,r){if(!(!e||e.presentation.mode==="auto"))return j(e,r)?{type:"temporal_bucket",presentation:e.presentation}:void 0}function le(e){var n;const r=I.canonicalizeSupportedLocale(e.locale);if(!r)throw new y("invalid_temporal_bucket_format","Temporal bucket locale must be a supported base BCP 47 locale.");const t=A(e.cardFormat,e.metadata);if(t)return{format:{...t,locale:r},source:"card"};const o=((n=e.semanticFormat)==null?void 0:n.granularity)===e.metadata.granularity?A(e.semanticFormat.format,e.metadata):void 0;return o?{format:{...o,locale:r},source:"semantic"}:{format:{type:"temporal_bucket",locale:r,presentation:{mode:"auto",styles:e.styles??x}},source:"automatic"}}function f(e,r=2){return String(e).padStart(r,"0")}function C(e,r,t){if(r==="en-US")return(t==="short"?re:te)[e-1];const o=new Date(Date.UTC(2e3,e-1,15));return new Intl.DateTimeFormat(r,{calendar:"gregory",month:t,timeZone:"UTC"}).format(o)}function ue(e,r,t){return r.map(o=>{if(o.kind==="literal")return o.value;switch(o.value){case"YYYY":return f(e.year,4);case"YY":return f(e.year%100);case"MMMM":return C(e.month,t,"long");case"MMM":return C(e.month,t,"short");case"MM":return f(e.month);case"DD":return f(e.day);case"HH":return f(e.hour);case"mm":return f(e.minute);case"ss":return f(e.second)}}).join("")}const P=new Map;function g(e,r){const t=`${e}:${JSON.stringify(r)}`,o=P.get(t);if(o)return o;const n=new Intl.DateTimeFormat(e,r);return P.set(t,n),n}function w(e){const r=new Date(0);return r.setUTCFullYear(e.year,e.month-1,e.day),r.setUTCHours(e.hour,e.minute,e.second,0),r}function O(e,r,t){return g(r,{calendar:"gregory",dateStyle:t,timeZone:"UTC"}).format(w(e))}function me(e,r,t){return g(r,{calendar:"gregory",dateStyle:t.dateStyle,timeStyle:t.timeStyle==="long"?"medium":t.timeStyle,timeZone:"UTC"}).format(w(e))}function de(e,r,t){var n;if(t==="short"){const a=w(e),s=g(r,{calendar:"gregory",dateStyle:"short",timeZone:"UTC"}).formatToParts(a),l=s.findIndex(p=>p.type==="month"),c=s.findIndex(p=>p.type==="year"),m=(n=g(r,{calendar:"gregory",timeZone:"UTC",year:"numeric"}).formatToParts(a).find(p=>p.type==="year"))==null?void 0:n.value;if(l>=0&&c>=0&&m){const p=Math.min(l,c),U=Math.max(l,c);let k=!1;return s.slice(p,U+1).filter(b=>b.type==="day"?(k=!0,!1):k&&b.type==="literal"?(k=!1,!1):!0).map(b=>b.type==="year"?m:b.value).join("")}}return g(r,{calendar:"gregory",month:t==="short"?"numeric":t==="medium"?"short":"long",timeZone:"UTC",year:"numeric"}).format(w(e))}function pe(e,r){return Math.floor((e.month-r+12)%12/3)+1}function N(e,r){return r===1||e.month<r?e.year:e.year+1}function fe(e){return e===1?"1st":e===2?"2nd":e===3?"3rd":`${e}th`}function S(e,r,t,o){const n=M(o)??1,a=pe(e,n);switch(r){case"week_of_short":return`Week of ${C(e.month,t,"short")} ${e.day}, ${e.year}`;case"week_of_long":return`Week of ${C(e.month,t,"long")} ${e.day}, ${e.year}`;case"quarter_short":return`Q${a} ${e.year}`;case"quarter_long":return`${fe(a)} Quarter ${e.year}`;case"fiscal_quarter_short":return`Q${a} FY${N(e,n)}`;case"fiscal_year":return`FY${N(e,n)}`}}function _e(e,r,t,o){const n=M(r);switch(r.granularity){case"second":case"minute":case"hour":return me(e,t,o.dateTime);case"day":return O(e,t,o.dateStyle);case"week":return`Week of ${O(e,t,o.dateStyle)}`;case"month":return de(e,t,o.dateStyle);case"quarter":return S(e,n?"fiscal_quarter_short":"quarter_short",t,r);case"year":return n?S(e,"fiscal_year",t,r):String(e.year)}}function be(e){const r=Y(e.format);if(!r.ok||!j(r.value,e.metadata))throw new y("invalid_temporal_bucket_format","Resolved temporal bucket format is invalid or inapplicable to its metadata.");const t=L(e.value,e.metadata);if(!t.ok)throw new y(t.error.code,t.error.message);if(t.value===null)return"(Blank)";const{presentation:o,locale:n}=r.value;if(o.mode==="auto")return _e(t.value,e.metadata,n,o.styles);if(o.mode==="preset")return S(t.value,o.preset,n,e.metadata);const a=h.tokenizeTemporalBucketPattern(o.pattern);if(!a.ok)throw new y("invalid_temporal_bucket_format",a.message);return ue(t.value,a.segments,n)}exports.COMPARISON_PRESENTATION_DEFAULTS=G;exports.DEFAULT_METRIC_COMPARISON_POLARITY=F;exports.DEFAULT_RESOLVED_TEMPORAL_STYLE_SET=x;exports.TemporalBucketContractError=y;exports.evaluateMetricComparison=ee;exports.formatTemporalBucket=be;exports.isPlainJsonRecord=_;exports.parseResolvedTemporalBucketFormat=Y;exports.parseTemporalBucketValue=L;exports.resolveMetricComparisonRequest=H;exports.resolveMetricResultAlias=J;exports.resolveTemporalBucketPresentation=le;exports.validateComparisonPresentationSpec=W;exports.validateGlobalDateComparisonContext=Z;exports.validateGlobalDateComparisonSelection=R;exports.validateMetricComparisonConfig=z;exports.validateMetricComparisonPolarity=Q;exports.validateMetricComparisonSpec=T;
1
+ "use strict";var q=Object.defineProperty;var B=(e,r,t)=>r in e?q(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var v=(e,r,t)=>B(e,typeof r!="symbol"?r+"":r,t);const h=require("./validators-dJlwubP4.cjs"),I=require("../value-format-preferences/index.cjs"),F="higher_is_better",G={displayMode:"difference",showComparison:!0,indicatorStyle:"arrow_badge",showColor:!0,conditionalLabel:!1};function V(e){return h.parseSemaphorIsoInstant(e)!==null}function H(e){var r,t,o,n;if(((r=e.metricComparison)==null?void 0:r.mode)!=="off"){if(((t=e.metricComparison)==null?void 0:t.mode)==="explicit")return{source:"explicit",spec:e.metricComparison.spec};if(!((e.inheritGlobalComparison??((o=e.globalDateComparison)==null?void 0:o.inheritGlobalComparison))===!1||((n=e.globalDateComparison)==null?void 0:n.selection.mode)!=="period"))return{source:"inherited",spec:e.globalDateComparison.selection.spec,...e.globalDateComparison.owner?{owner:e.globalDateComparison.owner}:{}}}}function J(e){if(e.alias)return e.alias;const r=e.entityName&&e.entityName!=="SEMAPHOR_CALCULATED_FIELD"?e.entityName:void 0,t=r&&r!==e.name?`${r}_`:"";if(e.role!=="metric")return`${t}${e.name}`;let o=e.aggregate||"metric";if(e.expression){const n=e.expression.match(/^(COUNT|SUM|AVG|MIN|MAX|MEDIAN|DISTINCT)\s*\(/i);o=n?n[1].toLowerCase():"expr"}else o=o.toLowerCase();return`${t}${e.name}_${o}`}function i(e,r,t){return t?{code:e,message:r,path:t}:{code:e,message:r}}function d(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function u(e,r,t,o){Object.keys(e).forEach(n=>{r.includes(n)||o.push(i("invalid_comparison_spec",`Comparison kind does not accept field "${n}".`,`${t}.${n}`))})}function D(e,r,t){e.alignment!==void 0&&e.alignment!=="calendar"&&e.alignment!=="weekday"&&t.push(i("invalid_comparison_spec",'Comparison alignment must be "calendar" or "weekday".',`${r}.alignment`)),e.toDate!==void 0&&typeof e.toDate!="boolean"&&t.push(i("invalid_comparison_spec","Comparison toDate must be a boolean.",`${r}.toDate`))}function E(e,r,t){e!==void 0&&(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)&&t.push(i("invalid_comparison_spec","Comparison offset must be a positive safe integer.",r))}function T(e,r="comparison"){const t=[];return d(e)?(e.kind==="previous_period"?(u(e,["kind","offsetPeriods","alignment","toDate"],r,t),E(e.offsetPeriods,`${r}.offsetPeriods`,t),D(e,r,t)):e.kind==="previous_year"?(u(e,["kind","offsetYears","alignment","toDate"],r,t),E(e.offsetYears,`${r}.offsetYears`,t),D(e,r,t)):e.kind==="target"?(u(e,["kind","targetValue"],r,t),(typeof e.targetValue!="number"||!Number.isFinite(e.targetValue))&&t.push(i("invalid_comparison_spec","Target comparison requires a finite targetValue.",`${r}.targetValue`))):t.push(i("invalid_comparison_spec","Comparison kind must be previous_period, previous_year, or target.",`${r}.kind`)),{ok:t.length===0,errors:t,warnings:[]}):{ok:!1,errors:[i("invalid_comparison_spec","Comparison spec must be an object.",r)],warnings:[]}}function z(e,r="comparison"){if(!d(e))return{ok:!1,errors:[i("invalid_comparison_config","Comparison config must be an object.",r)],warnings:[]};const t=[];return e.mode==="off"?u(e,["mode"],r,t):e.mode==="explicit"?(u(e,["mode","spec"],r,t),t.push(...T(e.spec,`${r}.spec`).errors)):t.push(i("invalid_comparison_config","Comparison mode must be off or explicit.",`${r}.mode`)),{ok:t.length===0,errors:t,warnings:[]}}function R(e,r="comparisonSelection"){if(!d(e))return{ok:!1,errors:[i("invalid_global_date_comparison","Global Date comparison selection must be an object.",r)],warnings:[]};const t=[];if(e.mode==="off")u(e,["mode"],r,t);else if(e.mode==="period"){u(e,["mode","spec"],r,t);const o=T(e.spec,`${r}.spec`);t.push(...o.errors),d(e.spec)&&e.spec.kind==="target"&&t.push(i("invalid_global_date_comparison","Global Date comparison supports previous_period or previous_year, not target.",`${r}.spec.kind`))}else t.push(i("invalid_global_date_comparison","Global Date comparison mode must be off or period.",`${r}.mode`));return{ok:t.length===0,errors:t,warnings:[]}}function Z(e,r="globalDateComparison"){if(!d(e))return{ok:!1,errors:[i("invalid_global_date_comparison","Global Date comparison context must be an object.",r)],warnings:[]};const t=[];return u(e,["selection","inheritGlobalComparison","owner","referenceTime"],r,t),t.push(...R(e.selection,`${r}.selection`).errors),e.inheritGlobalComparison!==void 0&&e.inheritGlobalComparison!==!1&&t.push(i("invalid_global_date_comparison","inheritGlobalComparison may only be false when present.",`${r}.inheritGlobalComparison`)),e.owner!==void 0&&(d(e.owner)?e.owner.kind==="global_date"?u(e.owner,["kind"],`${r}.owner`,t):e.owner.kind==="field_date"?(u(e.owner,["kind","filterId","label"],`${r}.owner`,t),(typeof e.owner.filterId!="string"||!e.owner.filterId.trim())&&t.push(i("invalid_global_date_comparison","Field Date comparison owner requires a non-empty filterId.",`${r}.owner.filterId`)),(typeof e.owner.label!="string"||!e.owner.label.trim())&&t.push(i("invalid_global_date_comparison","Field Date comparison owner requires a non-empty label.",`${r}.owner.label`))):t.push(i("invalid_global_date_comparison","Comparison owner kind must be global_date or field_date.",`${r}.owner.kind`)):t.push(i("invalid_global_date_comparison","Comparison owner must be an object.",`${r}.owner`))),e.referenceTime!==void 0&&(typeof e.referenceTime!="string"||!V(e.referenceTime))&&t.push(i("invalid_global_date_comparison","referenceTime must be a valid ISO date-time string when present.",`${r}.referenceTime`)),{ok:t.length===0,errors:t,warnings:[]}}function Q(e,r="comparisonPolarity"){return e==="higher_is_better"||e==="lower_is_better"||e==="neutral"?{ok:!0,errors:[],warnings:[]}:{ok:!1,errors:[i("invalid_comparison_polarity","Comparison polarity must be higher_is_better, lower_is_better, or neutral.",r)],warnings:[]}}function W(e,r="comparisonPresentation"){if(!d(e))return{ok:!1,errors:[i("invalid_comparison_presentation","Comparison presentation must be an object.",r)],warnings:[]};const t=[],o=["displayMode","showComparison","precision","indicatorStyle","showColor","position","conditionalLabel","labelName","conditionalLabels","colors"];return Object.keys(e).forEach(a=>{o.includes(a)||t.push(i("invalid_comparison_presentation",`Comparison presentation does not accept field "${a}".`,`${r}.${a}`))}),[["displayMode",["difference","percent_change","both","ratio"]],["indicatorStyle",["arrow_badge","arrow","badge","none"]],["position",["left","right","top"]]].forEach(([a,s])=>{e[a]!==void 0&&!s.includes(e[a])&&t.push(i("invalid_comparison_presentation",`Comparison presentation ${a} is invalid.`,`${r}.${a}`))}),["showComparison","showColor","conditionalLabel"].forEach(a=>{e[a]!==void 0&&typeof e[a]!="boolean"&&t.push(i("invalid_comparison_presentation",`Comparison presentation ${a} must be a boolean.`,`${r}.${a}`))}),e.precision!==void 0&&(typeof e.precision!="number"||!Number.isInteger(e.precision)||e.precision<0||e.precision>6)&&t.push(i("invalid_comparison_presentation","Comparison presentation precision must be an integer from 0 through 6.",`${r}.precision`)),e.labelName!==void 0&&typeof e.labelName!="string"&&t.push(i("invalid_comparison_presentation","Comparison presentation labelName must be a string.",`${r}.labelName`)),["conditionalLabels","colors"].forEach(a=>{const s=e[a];if(s!==void 0){if(!d(s)){t.push(i("invalid_comparison_presentation",`Comparison presentation ${a} must be an object.`,`${r}.${a}`));return}Object.keys(s).forEach(l=>{["increase","decrease","neutral"].includes(l)||t.push(i("invalid_comparison_presentation",`Comparison presentation ${a} does not accept field "${l}".`,`${r}.${a}.${l}`))}),Object.entries(s).forEach(([l,c])=>{c!==void 0&&typeof c!="string"&&t.push(i("invalid_comparison_presentation",`Comparison presentation ${a}.${l} must be a string.`,`${r}.${a}.${l}`))})}}),{ok:t.length===0,errors:t,warnings:[]}}function K(e){return e===null?"unknown":e>0?"increase":e<0?"decrease":"no_change"}function X(e,r){return e==="unknown"||e==="no_change"||r==="neutral"?"neutral":r==="higher_is_better"&&e==="increase"||r==="lower_is_better"&&e==="decrease"?"favorable":"unfavorable"}function ee(e){const{currentValue:r,comparisonValue:t,polarity:o=F}=e,a=r!==null&&t!==null?r-t:null,s=a!==null&&t!==null&&t!==0?a/Math.abs(t):null,l=r!==null&&t!==null&&t!==0?r/t:null,c=K(a);return{status:t===null?"insufficient_history":"available",currentValue:r,comparisonValue:t,delta:a,percentChange:s,ratio:l,direction:c,sentiment:X(c,o)}}function _(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.getPrototypeOf(e);if(r===null||r===Object.prototype)return!0;const t=Object.prototype.hasOwnProperty.call(r,"constructor")?r.constructor:void 0;return typeof t=="function"&&Function.prototype.toString.call(t)===Function.prototype.toString.call(Object)}const x={dateStyle:"short",dateTime:{dateStyle:"short",timeStyle:"short"}};class y extends Error{constructor(t,o){super(o);v(this,"code");this.name="TemporalBucketContractError",this.code=t}}const re=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],te=["January","February","March","April","May","June","July","August","September","October","November","December"];function $(e){return{ok:!1,error:{code:"invalid_temporal_bucket_value",message:e}}}function oe(e){return e%4===0&&(e%100!==0||e%400===0)}function ne(e,r){return r===2?oe(e)?29:28:[4,6,9,11].includes(r)?30:31}function ae(e,r,t){const o=[0,3,2,5,0,3,5,1,4,6,2,4],n=r<3?e-1:e;return(n+Math.floor(n/4)-Math.floor(n/100)+Math.floor(n/400)+o[r-1]+t)%7}function M(e){var r;return(r=e.calendar.fiscalCalendar)==null?void 0:r.yearStartMonth}function ie(e,r){return(e-r+12)%12%3===0}function se(e,r){const{granularity:t}=r,o=M(r)??1;switch(t){case"second":return!0;case"minute":return e.second===0;case"hour":return e.minute===0&&e.second===0;case"day":return!0;case"week":return ae(e.year,e.month,e.day)===r.calendar.weekStart;case"month":return e.day===1;case"quarter":return e.day===1&&ie(e.month,o);case"year":return e.day===1&&e.month===o}}function L(e,r){if(e===null)return{ok:!0,value:null};const t=r.granularity==="second"||r.granularity==="minute"||r.granularity==="hour",o=t?/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})$/.exec(e):/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!o)return $(`Expected ${t?"YYYY-MM-DDTHH:mm:ss":"YYYY-MM-DD"} for ${r.granularity} granularity.`);const n={year:Number(o[1]),month:Number(o[2]),day:Number(o[3]),hour:t?Number(o[4]):0,minute:t?Number(o[5]):0,second:t?Number(o[6]):0};return n.year<1||n.month<1||n.month>12||n.day<1||n.day>ne(n.year,n.month)||n.hour>23||n.minute>59||n.second>59?$(`Invalid canonical ${r.granularity} bucket value ${e}.`):se(n,r)?{ok:!0,value:n}:$(`Canonical value ${e} is not aligned to ${r.granularity} granularity and its governed Calendar.`)}function Y(e){if(!_(e))return{ok:!1,issues:[{path:"$",message:"Resolved temporal bucket format must be an object."}]};const r=[],t=new Set(["type","presentation","locale"]);for(const s of Object.keys(e))t.has(s)||r.push({path:s,message:`Unknown property "${s}".`});e.type!=="temporal_bucket"&&r.push({path:"type",message:"Expected temporal_bucket."});const o=e.presentation;if(!_(o))r.push({path:"presentation",message:"Expected a presentation object."});else{const s=o.mode,l=s==="preset"?new Set(["mode","preset"]):s==="pattern"?new Set(["mode","pattern"]):s==="auto"?new Set(["mode","styles"]):new Set(["mode"]);for(const c of Object.keys(o))l.has(c)||r.push({path:`presentation.${c}`,message:`Unknown property "${c}".`});if(s==="preset")h.isTemporalBucketPreset(o.preset)||r.push({path:"presentation.preset",message:"Expected a supported preset."});else if(s==="pattern")if(typeof o.pattern!="string"||!o.pattern)r.push({path:"presentation.pattern",message:"Expected a non-empty pattern."});else{const c=h.tokenizeTemporalBucketPattern(o.pattern);c.ok||r.push({path:"presentation.pattern",message:c.message})}else if(s==="auto"){const c=o.styles;(!_(c)||!["short","medium","long"].includes(String(c.dateStyle))||!_(c.dateTime)||!["short","medium","long"].includes(String(c.dateTime.dateStyle))||!["short","medium","long"].includes(String(c.dateTime.timeStyle))||Object.keys(c).some(m=>m!=="dateStyle"&&m!=="dateTime")||Object.keys(c.dateTime).some(m=>m!=="dateStyle"&&m!=="timeStyle"))&&r.push({path:"presentation.styles",message:"Expected complete resolved date and datetime styles."})}else r.push({path:"presentation.mode",message:"Expected auto, preset, or pattern."})}const n=I.canonicalizeSupportedLocale(e.locale);if(n||r.push({path:"locale",message:"Expected a supported base BCP 47 locale."}),r.length>0||!n||!_(o))return{ok:!1,issues:r};if(o.mode==="auto"){const s=o.styles;return{ok:!0,value:{type:"temporal_bucket",locale:n,presentation:{mode:"auto",styles:{dateStyle:s.dateStyle,dateTime:{dateStyle:s.dateTime.dateStyle,timeStyle:s.dateTime.timeStyle}}}}}}return{ok:!0,value:{type:"temporal_bucket",presentation:o.mode==="preset"?{mode:"preset",preset:o.preset}:{mode:"pattern",pattern:o.pattern},locale:n}}}function ce(e,r){const t=!!r.calendar.fiscalCalendar;return e==="fiscal_quarter_short"||e==="fiscal_year"?t:e==="quarter_short"||e==="quarter_long"?!t:!0}function j(e,r){return h.validateTemporalBucketFormatApplicability(e,r.granularity).ok?e.presentation.mode==="preset"?ce(e.presentation.preset,r):!(e.presentation.mode==="pattern"&&r.calendar.fiscalCalendar&&(r.granularity==="quarter"||r.granularity==="year")):!1}function A(e,r){if(!(!e||e.presentation.mode==="auto"))return j(e,r)?{type:"temporal_bucket",presentation:e.presentation}:void 0}function le(e){var n;const r=I.canonicalizeSupportedLocale(e.locale);if(!r)throw new y("invalid_temporal_bucket_format","Temporal bucket locale must be a supported base BCP 47 locale.");const t=A(e.cardFormat,e.metadata);if(t)return{format:{...t,locale:r},source:"card"};const o=((n=e.semanticFormat)==null?void 0:n.granularity)===e.metadata.granularity?A(e.semanticFormat.format,e.metadata):void 0;return o?{format:{...o,locale:r},source:"semantic"}:{format:{type:"temporal_bucket",locale:r,presentation:{mode:"auto",styles:e.styles??x}},source:"automatic"}}function f(e,r=2){return String(e).padStart(r,"0")}function C(e,r,t){if(r==="en-US")return(t==="short"?re:te)[e-1];const o=new Date(Date.UTC(2e3,e-1,15));return new Intl.DateTimeFormat(r,{calendar:"gregory",month:t,timeZone:"UTC"}).format(o)}function ue(e,r,t){return r.map(o=>{if(o.kind==="literal")return o.value;switch(o.value){case"YYYY":return f(e.year,4);case"YY":return f(e.year%100);case"MMMM":return C(e.month,t,"long");case"MMM":return C(e.month,t,"short");case"MM":return f(e.month);case"DD":return f(e.day);case"HH":return f(e.hour);case"mm":return f(e.minute);case"ss":return f(e.second)}}).join("")}const P=new Map;function g(e,r){const t=`${e}:${JSON.stringify(r)}`,o=P.get(t);if(o)return o;const n=new Intl.DateTimeFormat(e,r);return P.set(t,n),n}function w(e){const r=new Date(0);return r.setUTCFullYear(e.year,e.month-1,e.day),r.setUTCHours(e.hour,e.minute,e.second,0),r}function O(e,r,t){return g(r,{calendar:"gregory",dateStyle:t,timeZone:"UTC"}).format(w(e))}function me(e,r,t){return g(r,{calendar:"gregory",dateStyle:t.dateStyle,timeStyle:t.timeStyle==="long"?"medium":t.timeStyle,timeZone:"UTC"}).format(w(e))}function de(e,r,t){var n;if(t==="short"){const a=w(e),s=g(r,{calendar:"gregory",dateStyle:"short",timeZone:"UTC"}).formatToParts(a),l=s.findIndex(p=>p.type==="month"),c=s.findIndex(p=>p.type==="year"),m=(n=g(r,{calendar:"gregory",timeZone:"UTC",year:"numeric"}).formatToParts(a).find(p=>p.type==="year"))==null?void 0:n.value;if(l>=0&&c>=0&&m){const p=Math.min(l,c),U=Math.max(l,c);let k=!1;return s.slice(p,U+1).filter(b=>b.type==="day"?(k=!0,!1):k&&b.type==="literal"?(k=!1,!1):!0).map(b=>b.type==="year"?m:b.value).join("")}}return g(r,{calendar:"gregory",month:t==="short"?"numeric":t==="medium"?"short":"long",timeZone:"UTC",year:"numeric"}).format(w(e))}function pe(e,r){return Math.floor((e.month-r+12)%12/3)+1}function N(e,r){return r===1||e.month<r?e.year:e.year+1}function fe(e){return e===1?"1st":e===2?"2nd":e===3?"3rd":`${e}th`}function S(e,r,t,o){const n=M(o)??1,a=pe(e,n);switch(r){case"week_of_short":return`Week of ${C(e.month,t,"short")} ${e.day}, ${e.year}`;case"week_of_long":return`Week of ${C(e.month,t,"long")} ${e.day}, ${e.year}`;case"quarter_short":return`Q${a} ${e.year}`;case"quarter_long":return`${fe(a)} Quarter ${e.year}`;case"fiscal_quarter_short":return`Q${a} FY${N(e,n)}`;case"fiscal_year":return`FY${N(e,n)}`}}function _e(e,r,t,o){const n=M(r);switch(r.granularity){case"second":case"minute":case"hour":return me(e,t,o.dateTime);case"day":return O(e,t,o.dateStyle);case"week":return`Week of ${O(e,t,o.dateStyle)}`;case"month":return de(e,t,o.dateStyle);case"quarter":return S(e,n?"fiscal_quarter_short":"quarter_short",t,r);case"year":return n?S(e,"fiscal_year",t,r):String(e.year)}}function be(e){const r=Y(e.format);if(!r.ok||!j(r.value,e.metadata))throw new y("invalid_temporal_bucket_format","Resolved temporal bucket format is invalid or inapplicable to its metadata.");const t=L(e.value,e.metadata);if(!t.ok)throw new y(t.error.code,t.error.message);if(t.value===null)return"(Blank)";const{presentation:o,locale:n}=r.value;if(o.mode==="auto")return _e(t.value,e.metadata,n,o.styles);if(o.mode==="preset")return S(t.value,o.preset,n,e.metadata);const a=h.tokenizeTemporalBucketPattern(o.pattern);if(!a.ok)throw new y("invalid_temporal_bucket_format",a.message);return ue(t.value,a.segments,n)}exports.COMPARISON_PRESENTATION_DEFAULTS=G;exports.DEFAULT_METRIC_COMPARISON_POLARITY=F;exports.DEFAULT_RESOLVED_TEMPORAL_STYLE_SET=x;exports.TemporalBucketContractError=y;exports.evaluateMetricComparison=ee;exports.formatTemporalBucket=be;exports.isPlainJsonRecord=_;exports.parseResolvedTemporalBucketFormat=Y;exports.parseTemporalBucketValue=L;exports.resolveMetricComparisonRequest=H;exports.resolveMetricResultAlias=J;exports.resolveTemporalBucketPresentation=le;exports.validateComparisonPresentationSpec=W;exports.validateGlobalDateComparisonContext=Z;exports.validateGlobalDateComparisonSelection=R;exports.validateMetricComparisonConfig=z;exports.validateMetricComparisonPolarity=Q;exports.validateMetricComparisonSpec=T;
@@ -1,5 +1,5 @@
1
1
  import "../value-format-preferences/index.js";
2
- import "./validators-DEmd8Sin.js";
2
+ import "./validators-DVd8s3qY.js";
3
3
  const A = {
4
4
  mode: "all"
5
5
  };
@@ -1 +1 @@
1
- "use strict";require("../value-format-preferences/index.cjs");require("./validators-BDYprKI9.cjs");const A={mode:"all"};exports.DEFAULT_SEMANTIC_DOMAIN_ACCESS=A;
1
+ "use strict";require("../value-format-preferences/index.cjs");require("./validators-dJlwubP4.cjs");const A={mode:"all"};exports.DEFAULT_SEMANTIC_DOMAIN_ACCESS=A;
@@ -1,4 +1,4 @@
1
- import { S as W, a as X, v as Z } from "./validators-DEmd8Sin.js";
1
+ import { S as W, a as X, v as Z } from "./validators-DVd8s3qY.js";
2
2
  import { toSemaphorInputOptionsIntent as ee, toSemaphorAnalysisQueryOptions as te, toSemaphorAnalysisIntent as re, toSemaphorMetricIntent as ne, toSemaphorRecordsIntent as ae, toSemaphorMatrixIntent as se, toSemaphorSqlIntent as ie } from "../data-app-sdk-adapters/index.js";
3
3
  const Je = W, x = X, G = "semaphor-generated-data-app-contract/v1", T = "semaphor-generated-data-app-contract-manifest/v1";
4
4
  function P(e) {
@@ -1,3 +1,3 @@
1
- "use strict";const K=require("./validators-BDYprKI9.cjs"),S=require("../data-app-sdk-adapters/index.cjs"),re=K.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION,T=K.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION,k="semaphor-generated-data-app-contract/v1",G="semaphor-generated-data-app-contract-manifest/v1";function x(e){return E(e)?[...K.validateSemaphorDataAppCodegenSummary(e).issues,...ae(e)]:["Plan artifact must be a Semaphor codegenSummary object."]}function ne(e){const t=x(e);if(t.length>0)throw new Error(`Invalid Semaphor codegenSummary:
1
+ "use strict";const K=require("./validators-dJlwubP4.cjs"),S=require("../data-app-sdk-adapters/index.cjs"),re=K.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION,T=K.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION,k="semaphor-generated-data-app-contract/v1",G="semaphor-generated-data-app-contract-manifest/v1";function x(e){return E(e)?[...K.validateSemaphorDataAppCodegenSummary(e).issues,...ae(e)]:["Plan artifact must be a Semaphor codegenSummary object."]}function ne(e){const t=x(e);if(t.length>0)throw new Error(`Invalid Semaphor codegenSummary:
2
2
  - ${t.join(`
3
3
  - `)}`)}function ae(e){var r;const t=E(e);if(!t)return[];const n=[];return((r=E(t.validation))==null?void 0:r.status)==="blocked"&&n.push("validation.status blocked cannot be generated. Resolve blocked semantic model gaps and replan before generating contract files."),Array.isArray(t.unsupportedInsights)&&t.unsupportedInsights.forEach((i,o)=>{var a;((a=E(i))==null?void 0:a.reason)==="missing_relationship"&&n.push(`unsupportedInsights.${o}.reason missing_relationship blocks contract generation. Call semaphor_propose_semantic_model_change, apply an approved semantic model patch, and replan before generating contract files.`)}),Array.isArray(t.views)&&t.views.forEach((i,o)=>{var s;const a=E((s=E(i))==null?void 0:s.computation);(a==null?void 0:a.kind)==="unsupported"&&a.reason==="missing_relationship"&&n.push(`views.${o}.computation.reason missing_relationship blocks contract generation. Call semaphor_propose_semantic_model_change, apply an approved semantic model patch, and replan before generating contract files.`)}),n}function E(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}const J=["sources.ts","fields.ts","inputs.ts","queries.ts","bindings.ts","accessors.ts","metadata.ts","index.ts"],ie=["USAGE.md"],Y=[...J,...ie,"contract.manifest.json"];async function se({manifest:e,generatedFiles:t}){const n=[],r=y(e);if(!r)return{issues:[{message:"Generated contract manifest must be an object.",repairHint:"Regenerate the generated contract instead of hand-editing the manifest."}]};r.schemaVersion!==G&&n.push({path:"schemaVersion",message:`schemaVersion must be ${G}. Regenerate the contract with semaphor_create_data_app_contract.`,repairHint:"Regenerate the contract with semaphor_create_data_app_contract."}),r.generatedContractSchemaVersion!==k&&n.push({path:"generatedContractSchemaVersion",message:`generatedContractSchemaVersion must be ${k}. Regenerate the contract with semaphor_generate_data_app_contract.`,repairHint:"Regenerate the contract with semaphor_generate_data_app_contract."});const i=y(r.generator);A(i==null?void 0:i.name)||n.push({path:"generator.name",message:"generator.name is required.",repairHint:"Regenerate the generated contract so manifest generator metadata is written deterministically."}),A(i==null?void 0:i.version)||n.push({path:"generator.version",message:"generator.version is required.",repairHint:"Regenerate the generated contract so manifest generator metadata is written deterministically."});for(const a of x(r.codegenSummary))n.push({path:`codegenSummary.${a}`,message:`codegenSummary.${a}`,repairHint:"Regenerate the generated contract from a valid Data App codegenSummary."});if(r.codegenSummaryValidatorVersion!==T&&n.push({path:"codegenSummaryValidatorVersion",message:`codegenSummaryValidatorVersion must be ${T}. Regenerate the contract with semaphor_generate_data_app_contract.`,repairHint:"Regenerate the contract with semaphor_generate_data_app_contract."}),typeof r.codegenSummaryHash!="string")n.push({path:"codegenSummaryHash",message:"codegenSummaryHash is required.",repairHint:"Regenerate the generated contract so manifest hashes are written deterministically."});else if(y(r.codegenSummary)){const a=await fe(r.codegenSummary);r.codegenSummaryHash!==a&&n.push({path:"codegenSummaryHash",message:"codegenSummaryHash does not match codegenSummary. Regenerate the contract instead of editing the manifest.",repairHint:"Regenerate the generated contract instead of editing the manifest."})}n.push(...de(r.codegenSummary));const o=t?oe(t):[];if(n.push(...o),t&&o.length===0&&n.push(...ce(t)),typeof r.generatedContentHash!="string")n.push({path:"generatedContentHash",message:"generatedContentHash is required.",repairHint:"Regenerate the generated contract so manifest hashes are written deterministically."});else if(t&&o.length===0){const a=await ue(t);r.generatedContentHash!==a&&n.push({path:"generatedContentHash",message:"generatedContentHash does not match generated TypeScript files. Regenerate the contract instead of hand-editing generated files.",repairHint:"Regenerate the contract instead of hand-editing generated files."})}return{issues:n}}function oe(e){var r;const t=[],n=new Set(Y);for(const i of Object.keys(e)){if(i.includes("/")||i.includes("\\")){const o=((r=i.split("/").pop())==null?void 0:r.split("\\").pop())||i;t.push({path:`generatedFiles.${i}`,message:`generatedFiles keys must be generated filenames such as "${o}", not path-qualified keys such as "${i}".`,repairHint:'Pass generatedFiles keyed by filename, for example "queries.ts", not "src/semaphor/generated/queries.ts".'});continue}n.has(i)||t.push({path:`generatedFiles.${i}`,message:`generatedFiles contains unknown generated contract file "${i}".`,repairHint:"Pass only the generated files returned by semaphor_generate_data_app_contract, keyed by filename."})}return t}function ce(e){const t=e["USAGE.md"];return typeof t!="string"?[{path:"generatedFiles.USAGE.md",message:"generatedFiles.USAGE.md is required.",repairHint:"Regenerate the generated contract so the generated usage guide is written."}]:["queries","queryOptionsForView","rowsForView","metricValuesForView","kpiPropsForView","roleValuesForView","appInputSpecs","inputOptionQueries"].filter(r=>!t.includes(`\`${r}\``)).map(r=>({path:"generatedFiles.USAGE.md",message:`generatedFiles.USAGE.md must document ${r}.`,repairHint:"Regenerate the generated contract so the usage guide matches generated exports."}))}function de(e){const t=y(e);if(!t)return[];const n=[],r=new Set(b(t.inputs).map(o=>{var a;return(a=y(o))==null?void 0:a.id}).filter(A)),i=new Set(b(t.views).map(o=>{var a;return(a=y(o))==null?void 0:a.id}).filter(A));return b(t.filterContracts).forEach((o,a)=>{const s=y(o),c=s==null?void 0:s.inputId;(!A(c)||!r.has(c))&&n.push({path:`codegenSummary.filterContracts.${a}.inputId`,message:`codegenSummary.filterContracts.${a}.inputId must reference a generated input.`,repairHint:"Regenerate the generated contract from a valid planner output."}),Array.isArray(s==null?void 0:s.bindings)&&s.bindings.forEach((u,f)=>{const p=y(u),m=p==null?void 0:p.viewId;(!A(m)||!i.has(m))&&n.push({path:`codegenSummary.filterContracts.${a}.bindings.${f}.viewId`,message:`codegenSummary.filterContracts.${a}.bindings.${f}.viewId must reference a generated view.`,repairHint:"Regenerate the generated contract from a valid planner output."});const h=y(p==null?void 0:p.fieldRef);A(h==null?void 0:h.name)||n.push({path:`codegenSummary.filterContracts.${a}.bindings.${f}.fieldRef`,message:`codegenSummary.filterContracts.${a}.bindings.${f}.fieldRef is required.`,repairHint:"Regenerate the generated contract from a valid planner output."})})}),n}async function ue(e){const t=Object.keys(e).filter(r=>r.endsWith(".ts")).sort();let n="";for(const r of t)n+=`${r}\0${e[r]}\0`;return`sha256:${await Q(n)}`}async function fe(e){return`sha256:${await Q(M(e))}`}function M(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>M(r)).join(",")}]`;const t=e;return`{${Object.keys(t).sort().filter(r=>t[r]!==void 0).map(r=>`${JSON.stringify(r)}:${M(t[r])}`).join(",")}}`}async function Q(e){var r;if(!((r=globalThis.crypto)!=null&&r.subtle))throw new Error("SHA-256 digest support is required for generated contract validation.");const t=new TextEncoder().encode(e),n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}function y(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function b(e){return Array.isArray(e)?e:[]}function A(e){return typeof e=="string"&&e.length>0}function pe(e){const t=d(e),n=V(t),r=[],i=[];return I(t==null?void 0:t.views).filter(o=>{var s;const a=d((s=d(o))==null?void 0:s.sdkSpec);return!!(a!=null&&a.builder&&(a!=null&&a.spec))}).forEach((o,a)=>{var u;const s=String(((u=d(o))==null?void 0:u.id)||`view_${a}`),c=W(o,n);if(c){r.push({viewId:s,...c});return}i.push({viewId:s,path:`views.${s}.sdkSpec`,message:`Generated view execution validation could not build intent for "${s}".`})}),{requests:r,issues:i}}function W(e,t){const n=d(e),r=d(n==null?void 0:n.sdkSpec),i=d(r==null?void 0:r.spec);if(!n||!(r!=null&&r.builder)||!i)return null;const o=me(t)?t:V(d(t)),a=be(r.builder),s=d(w(i,o))||{},c=ye({view:n,builder:a,rawSpec:i,spec:{...s,id:n.id,label:Ne(n,i)},context:o});try{if(a==="analysis"){const u=c;return{intent:S.toSemaphorAnalysisIntent(u),resultShape:"analysis",analysisOptions:S.toSemaphorAnalysisQueryOptions(u)}}if(a==="metric")return{intent:S.toSemaphorMetricIntent(c),resultShape:"metric"};if(a==="records")return{intent:S.toSemaphorRecordsIntent(c),resultShape:"records"};if(a==="matrix")return{intent:S.toSemaphorMatrixIntent(c),resultShape:"matrix"};if(a==="sql")return{intent:S.toSemaphorSqlIntent(c),resultShape:"sql"}}catch{return null}return null}function ge({input:e,filterContract:t,codegenSummary:n}){const r=d(e),i=d(t),o=d(r==null?void 0:r.optionQuery)||d(i==null?void 0:i.optionQuery);if(!r||!o)return null;const a=V(d(n)),s=d(o.spec),c=he(o,s,a),u=o.valueFieldRef||o.valueField||(s==null?void 0:s.valueField),f=o.labelFieldRef||o.labelField||(s==null?void 0:s.labelField);if(!c||!u||!f)return null;const m={...d(w(s||{},a))||{},id:o.id||(s==null?void 0:s.id)||`${r.id}-options`,inputId:r.id,source:c,valueField:u,labelField:f,population:o.population||(s==null?void 0:s.population),dependencies:o.dependencies||(s==null?void 0:s.dependencies),limit:o.limit||(s==null?void 0:s.limit)||100};try{return S.toSemaphorInputOptionsIntent(w(m,a))}catch{return null}}function le({input:e,filterContract:t,binding:n,option:r,codegenSummary:i}){const o=V(d(i)),a=d(e),s=d(t),c=d(n),u=w((c==null?void 0:c.fieldRef)||(s==null?void 0:s.fieldRef)||(a==null?void 0:a.fieldRef),o),f=String((s==null?void 0:s.operator)||(a==null?void 0:a.operator)||"in"),p=Fe(c);return{inputId:String((s==null?void 0:s.inputId)||(a==null?void 0:a.id)||""),kind:"filter",operator:f,value:He(f,r.value),isActive:!0,...u?{field:u}:{},...p?{relationshipHint:p}:{}}}function V(e){return{sourcesByKey:new Map(I(e==null?void 0:e.sources).map(d).filter(Me).filter(t=>typeof t.sourceKey=="string").map(t=>[String(t.sourceKey),Z(t)]))}}function me(e){var t;return e instanceof Object&&((t=d(e))==null?void 0:t.sourcesByKey)instanceof Map}function he(e,t,n){if(typeof e.sourceKey=="string")return n.sourcesByKey.get(e.sourceKey)||{sourceKey:e.sourceKey};if(e.source)return e.source;if(t!=null&&t.source)return t.source;if(typeof(t==null?void 0:t.sourceKey)=="string")return n.sourcesByKey.get(t.sourceKey)||{sourceKey:t.sourceKey}}function ye({view:e,builder:t,rawSpec:n,spec:r,context:i}){var s;if(t!=="records"&&t!=="sql")return r;const o=d((s=d(e.visualSpec))==null?void 0:s.tableBehavior);if(!o)return r;const a={...r};if(Oe(o)==="server"&&(a.pagination={page:1,pageSize:Se({tableBehavior:o,spec:r})}),t==="records"&&Ve(o)==="server"){const c=Ae({view:e,rawSpec:n,tableBehavior:o,context:i});c&&(a.orderBy=c)}return a}function Se({tableBehavior:e,spec:t}){const n=d(e.pagination),r=d(t.pagination);return F(n==null?void 0:n.pageSize)||F(r==null?void 0:r.pageSize)||F(t.limit)||100}function Ae({view:e,rawSpec:t,tableBehavior:n,context:r}){const i=d(n.sorting),o=g(i==null?void 0:i.defaultField);if(!o)return;const s=_e({view:e,rawSpec:t,context:r}).filter(c=>we(c.lookup).includes(o));if(s.length===1)return{field:s[0].field,direction:(i==null?void 0:i.defaultDirection)==="desc"?"desc":"asc"}}function _e({view:e,rawSpec:t,context:n}){var i;const r=[];for(const o of I(t.fields))$(r,o,n);$(r,t.dateField,n),$(r,(i=d(t.orderBy))==null?void 0:i.field,n);for(const o of I(e.fields))$(r,o,n);return Te(r,o=>Ee(o.lookup))}function $(e,t,n){const r=d(t);if(typeof(r==null?void 0:r.name)!="string"||r.name.length===0)return;const i=d(w(r,n))||r;e.push({lookup:r,field:i})}function we(e){return ke([g(e.name),X(e),Ie(e)])}function Ee(e){return[X(e),g(e.name),g(e.role),g(e.aggregate)].join("|")}function X(e){return[g(e.sourceKey)||Re(e.source),g(e.name),g(e.aggregate)].filter(Boolean).join(":")}function Re(e){const t=d(e);if(!t)return"";if(typeof t.kind=="string"&&typeof t.domainId=="string"){if(typeof t.datasetId=="string")return`${t.kind}:${t.domainId}:datasetId:${t.datasetId}`;if(typeof t.datasetName=="string")return`${t.kind}:${t.domainId}:datasetName:${t.datasetName}`}return JSON.stringify(t)}function Ie(e){return Ge([ve(e),g(e.aggregate).toLowerCase(),g(e.label)||g(e.name)].filter(Boolean))}function ve(e){return typeof e.sourceKey=="string"?Ce(e.sourceKey):$e(e.source)}function $e(e){const t=d(e);return t?g(t.datasetName)||g(t.datasetId)||g(t.name)||g(t.kind):""}function Ce(e){const t=String(e).split(":");return t[t.length-1]||String(e)}function Oe(e){var t;return g((t=d(e.pagination))==null?void 0:t.mode)}function Ve(e){var t;return g((t=d(e.sorting))==null?void 0:t.mode)}function w(e,t){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(i=>w(i,t));const n=e;if(typeof n.sourceKey=="string"&&typeof n.kind=="string"&&(typeof n.datasetName=="string"||typeof n.datasetId=="string"))return Z(n);const r={};for(const[i,o]of Object.entries(n))i!=="sourceKey"&&(r[i]=w(o,t));if(typeof n.sourceKey=="string"){const i=t.sourcesByKey.get(n.sourceKey);i&&!r.source&&(r.source=i)}return r}function Z(e){const{sourceKey:t,...n}=e;return n}function Ne(e,t){const n=d(e.visualSpec);return(n==null?void 0:n.title)||e.title||t.label}function be(e){const t=String(e||"").replace(/^semaphor\./,"");return["metric","records","analysis","matrix","sql"].includes(t)?t:""}function Fe(e){if(e!=null&&e.relationshipHint)return e.relationshipHint;const t=I(e==null?void 0:e.relationshipsUsed).map(n=>{var r;return(r=d(n))==null?void 0:r.id}).filter(n=>typeof n=="string"&&n.length>0);return t.length>0?{relationshipIds:t}:void 0}function He(e,t){return e==="in"||e==="not_in"?[t]:e==="between"?Array.isArray(t)?t:[t,t]:t}function F(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function g(e){return typeof e=="string"?e:""}function Te(e,t){const n=new Set,r=[];for(const i of e){const o=t(i);!o||n.has(o)||(n.add(o),r.push(i))}return r}function ke(e){return Array.from(new Set(e.filter(Boolean)))}function Ge(e){return(Array.isArray(e)?e.join(" "):e).replace(/[^a-zA-Z0-9]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,r)=>{const i=n.toLowerCase();return r===0?i:i.charAt(0).toUpperCase()+i.slice(1)}).join("")}function d(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function I(e){return Array.isArray(e)?e:[]}function Me(e){return e!==void 0}const De=new Set(["diagnostic_fix","fix_diagnostics","fix_inspector_warnings","fix_runtime_warnings","fix_warnings"]),Ke=new Set(["add","edit","mixed","remove"]),j=new Set(["fields","metricBindingKeys","sdkSpec"]);function xe({beforeSummary:e,afterSummary:t,migrationReport:n,operationIntent:r,constraints:i,preferences:o}){const a=l(r),s=typeof(a==null?void 0:a.kind)=="string"?a.kind.trim():"";return Ke.has(s)?{ok:!1,policy:{kind:s,mode:"invalid_operation_kind",reason:"Retired Data App operation aliases are not accepted. Use the hard-migrated analytics/layout/style operationIntent kinds."},violations:[{path:"operationIntent.kind",reason:"Use analytics_add, analytics_edit, analytics_remove, input_add, input_edit, layout_only, style_only, runtime_debug, semantic_model_repair, save_or_publish, or greenfield_create."}]}:B(o)?{ok:!1,policy:{kind:s,mode:"invalid_update_constraints",reason:"Metric aggregate override updates must use operationIntent.measureAggregateOverrides so deterministic update policy can guard the targeted edit."},violations:[{path:"preferences.measureAggregateOverrides",reason:"preferences is retired. Move measureAggregateOverrides to operationIntent.measureAggregateOverrides for update calls."}]}:B(i)?{ok:!1,policy:{kind:s,mode:"invalid_update_constraints",reason:"Metric aggregate override updates must use operationIntent.measureAggregateOverrides so deterministic update policy can guard the targeted edit."},violations:[{path:"constraints.measureAggregateOverrides",reason:"Move measureAggregateOverrides to operationIntent.measureAggregateOverrides for update calls."}]}:De.has(s)?U({beforeSummary:e,afterSummary:t,migrationReport:n,operationIntent:a,mode:"diagnostic_warning_fix",allowedViewChangeReasons:j,label:"Diagnostic warning fixes",reason:"Diagnostic warning fixes are preserve-by-default and may not add/remove views, inputs, or filter contracts."}):s==="analytics_edit"&&Array.isArray(a==null?void 0:a.measureAggregateOverrides)&&a.measureAggregateOverrides.length>0?U({beforeSummary:e,afterSummary:t,migrationReport:n,operationIntent:a,mode:"metric_aggregate_override_edit",allowedViewChangeReasons:j,label:"Metric aggregate override edits",reason:"Metric aggregate override edits are preserve-by-default and may only adjust fields/sdkSpec on targeted views."}):{ok:!0,policy:{kind:s,mode:"general_iterative_update",reason:"General generated-contract edits are allowed to change the requested contract shape. Review the migration report for expected UI work."},violations:[]}}function B(e){var t;return Array.isArray((t=l(e))==null?void 0:t.measureAggregateOverrides)}function U({beforeSummary:e,afterSummary:t,migrationReport:n,operationIntent:r,mode:i,allowedViewChangeReasons:o,label:a,reason:s}){const c=[],u=je(r==null?void 0:r.targetViewIds),f=l(n)||{};u.size===0&&c.push({path:"operationIntent.targetViewIds",reason:`${a} must declare targetViewIds so the update cannot broaden to unrelated views.`}),H({bucket:l(f.views),label:"views",operationLabel:a,violations:c}),H({bucket:l(f.inputs),label:"inputs",operationLabel:a,violations:c}),L({bucket:l(f.inputs),label:"inputs",operationLabel:a,violations:c}),H({bucket:l(f.filterContracts),label:"filterContracts",operationLabel:a,violations:c}),L({bucket:l(f.filterContracts),label:"filterContracts",operationLabel:a,violations:c});for(const m of ee(l(f.views))){u.size>0&&!u.has(_(m.id))&&c.push({path:`views.${_(m.id)||"<unknown>"}`,reason:`${a} may only change explicitly targeted views.`});const h=Array.isArray(m.reasons)?m.reasons.filter(R=>typeof R!="string"||!o.has(R)):[];h.length>0&&c.push({path:`views.${_(m.id)||"<unknown>"}`,reason:`${a} may only adjust fields/sdkSpec/metricBindingKeys; changed ${h.join(", ")}.`})}const p=qe({beforeSummary:e,afterSummary:t,targetViewIds:u,label:a});return p&&c.push(p),{ok:c.length===0,policy:{kind:_(r==null?void 0:r.kind)||"diagnostic_fix",mode:i,allowedViewChangeReasons:Array.from(o).sort(),targetViewIds:Array.from(u).sort(),reason:s},violations:c}}function qe({beforeSummary:e,afterSummary:t,targetViewIds:n,label:r}){const i=l(e),o=l(t);if(!i||!o)return{path:"codegenSummary",reason:`${r} require before/after codegen summaries for full-scope verification.`};const a=P(i),s=P(o),c=z(i.views),u=z(o.views),f=Array.isArray(a.views)?a.views:[];a.views=f;for(const p of n){const m=c.get(p),h=u.get(p);if(!m||!h)continue;const R=f.find(te=>{var q;return((q=l(te))==null?void 0:q.id)===p}),v=l(h);if(!R||!v)continue;const N=R;N.fields=C(v.fields),N.metricBindingKeys=C(v.metricBindingKeys),N.sdkSpec=C(v.sdkSpec)}return O(a)===O(s)?null:{path:"codegenSummary",reason:`${r} may only change fields/sdkSpec/metricBindingKeys on targetViewIds; another generated contract section changed.`}}function P(e){const t=C(e);for(const n of["implementationChecklist","assumptions","nextStep","nextRequiredTool","validation"])delete t[n];return Ue(t.unsupportedInsights)&&delete t.unsupportedInsights,t}function H({bucket:e,label:t,operationLabel:n,violations:r}){for(const i of D(e==null?void 0:e.added))r.push({path:`${t}.${_(i.id)||"<unknown>"}`,reason:`${n} may not add ${t}.`});for(const i of D(e==null?void 0:e.removed))r.push({path:`${t}.${_(i.id)||"<unknown>"}`,reason:`${n} may not remove ${t}.`})}function L({bucket:e,label:t,operationLabel:n,violations:r}){for(const i of ee(e))r.push({path:`${t}.${_(i.id)||"<unknown>"}`,reason:`${n} may not change ${t}.`})}function ee(e){return D(e==null?void 0:e.changed)}function D(e){return Array.isArray(e)?e.map(l).filter(Be):[]}function je(e){return Array.isArray(e)?new Set(e.filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim())):new Set}function z(e){var n;const t=new Map;for(const r of Array.isArray(e)?e:[]){const i=(n=l(r))==null?void 0:n.id;typeof i=="string"&&i.trim()&&t.set(i,r)}return t}function C(e){return e===void 0?e:JSON.parse(JSON.stringify(e))}function O(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(n=>O(n)).join(",")}]`;const t=e;return`{${Object.keys(t).sort().filter(n=>t[n]!==void 0).map(n=>`${JSON.stringify(n)}:${O(t[n])}`).join(",")}}`}function l(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Be(e){return e!==void 0}function Ue(e){return Array.isArray(e)&&e.length===0}function _(e){return typeof e=="string"?e:""}exports.CODEGEN_SUMMARY_SCHEMA_VERSION=re;exports.CODEGEN_SUMMARY_VALIDATOR_VERSION=T;exports.CONTRACT_MANIFEST_SCHEMA_VERSION=G;exports.GENERATED_CONTRACT_SCHEMA_VERSION=k;exports.GENERATED_CONTRACT_TYPESCRIPT_FILES=J;exports.REQUIRED_GENERATED_CONTRACT_FILES=Y;exports.assertValidCodegenSummary=ne;exports.buildSemaphorGeneratedActiveInput=le;exports.buildSemaphorGeneratedInputOptionIntent=ge;exports.buildSemaphorGeneratedViewExecutionRequest=W;exports.buildSemaphorGeneratedViewExecutionRequests=pe;exports.evaluateSemaphorDataAppContractUpdatePolicy=xe;exports.validateCodegenSummary=x;exports.validateSemaphorGeneratedContract=se;