react-semaphor 0.1.449 → 0.1.454

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 (147) hide show
  1. package/dist/analytics-protocol/index.cjs +1 -1
  2. package/dist/analytics-protocol/index.js +119 -112
  3. package/dist/appearance/index.cjs +1 -1
  4. package/dist/appearance/index.js +1 -1
  5. package/dist/brand-studio/index.cjs +4 -4
  6. package/dist/brand-studio/index.js +15 -13
  7. package/dist/briefings/index.cjs +1 -1
  8. package/dist/briefings/index.js +39 -2131
  9. package/dist/chunks/{analyze-result-contract-T-0Ntzys.js → analyze-result-contract-BbRJ-C06.js} +1 -1
  10. package/dist/chunks/{analyze-result-contract-BHb7sUUW.cjs → analyze-result-contract-LPDNldic.cjs} +1 -1
  11. package/dist/chunks/canonical-result-keys-BA0HCP4e.cjs +1 -0
  12. package/dist/chunks/canonical-result-keys-D6avdjpA.js +467 -0
  13. package/dist/chunks/color-CJvdlFM_.js +2162 -0
  14. package/dist/chunks/color-CyB5o13F.cjs +4 -0
  15. package/dist/chunks/{common-types-CQ6SHfLk.cjs → common-types-C57kJ59w.cjs} +1 -1
  16. package/dist/chunks/{common-types-B7Jk3Rtj.js → common-types-H51FLKB7.js} +1 -1
  17. package/dist/chunks/contracts-CoCOpd_i.js +11 -0
  18. package/dist/chunks/contracts-CtB2VONT.cjs +1 -0
  19. package/dist/chunks/dashboard-briefing-launcher-Dwj1i7lr.cjs +26 -0
  20. package/dist/chunks/{dashboard-briefing-launcher-DCHiEkLE.js → dashboard-briefing-launcher-SYroFdae.js} +86 -84
  21. package/dist/chunks/{dashboard-controls-DwRFCcHV.js → dashboard-controls-1LpeU2sz.js} +15 -13
  22. package/dist/chunks/{dashboard-controls-CaFioayc.cjs → dashboard-controls-CpFoh7-A.cjs} +1 -1
  23. package/dist/chunks/dashboard-date-comparison-definition-Ces4alFm.cjs +1 -0
  24. package/dist/chunks/{dashboard-date-comparison-definition-Ba-clViK.js → dashboard-date-comparison-definition-DC3ekV2S.js} +1 -1
  25. package/dist/chunks/{dashboard-json-WoILbfTe.js → dashboard-json-D-T-sQxU.js} +25 -23
  26. package/dist/chunks/dashboard-json-DwSQopc_.cjs +1 -0
  27. package/dist/chunks/edit-dashboard-visual-BEmoQAET.cjs +172 -0
  28. package/dist/chunks/{edit-dashboard-visual-ciFhxqaI.js → edit-dashboard-visual-DqxUq4Bs.js} +6925 -6947
  29. package/dist/chunks/editor-action-buttons-18r2xwei.cjs +16 -0
  30. package/dist/chunks/{editor-action-buttons-BPo_45pM.js → editor-action-buttons-B2l3WIRC.js} +41 -39
  31. package/dist/chunks/format-types-CFHQoIuk.js +1350 -0
  32. package/dist/chunks/format-types-PSZZ7hG8.cjs +1 -0
  33. package/dist/chunks/index-Bn5wlkHt.cjs +4 -0
  34. package/dist/chunks/index-ByFbacH7.cjs +1 -0
  35. package/dist/chunks/index-CACdoqu3.js +318 -0
  36. package/dist/chunks/index-CLB_NGZ8.cjs +1392 -0
  37. package/dist/chunks/index-Ca784dpx.js +3714 -0
  38. package/dist/chunks/{index-CPuawpXJ.js → index-DAoS4BNU.js} +48514 -48484
  39. package/dist/chunks/index-DSKR3nKn.js +421 -0
  40. package/dist/chunks/index-F25jnH0p.cjs +1 -0
  41. package/dist/chunks/matrix-result-contract-CofATICL.js +437 -0
  42. package/dist/chunks/matrix-result-contract-zamd9euI.cjs +1 -0
  43. package/dist/chunks/pivot-header-presentation-DhyQXxKq.cjs +4 -0
  44. package/dist/chunks/pivot-header-presentation-ckYOQ4aZ.js +557 -0
  45. package/dist/chunks/{pivot-result-identity-CDLRT-YG.cjs → pivot-result-identity-Bb4EixVN.cjs} +1 -1
  46. package/dist/chunks/{pivot-result-identity-CwJWpKI7.js → pivot-result-identity-DU1v-5Xk.js} +1 -1
  47. package/dist/chunks/pivot-result-lifecycle-DmcF1ris.cjs +1 -0
  48. package/dist/chunks/pivot-result-lifecycle-sjzIOpvp.js +1641 -0
  49. package/dist/chunks/raw-temporal-contract-BtjH_G-d.cjs +1 -0
  50. package/dist/chunks/raw-temporal-contract-CxncLze5.js +64 -0
  51. package/dist/chunks/report-preferences-dialog-BgSvlDXa.cjs +1 -0
  52. package/dist/chunks/report-preferences-dialog-DDc2WUa0.js +723 -0
  53. package/dist/chunks/{report-runtime-context-C8LZFsqV.cjs → report-runtime-context-DqxS4wbi.cjs} +1 -1
  54. package/dist/chunks/{report-runtime-context-bCy3CVzK.js → report-runtime-context-SM6YO61_.js} +5 -5
  55. package/dist/chunks/saved-temporal-bucket-format-CFfWXRl9.cjs +1 -0
  56. package/dist/chunks/saved-temporal-bucket-format-SGAV0ivR.js +922 -0
  57. package/dist/chunks/{switch-BXet-Sno.js → switch-BeZW-HnS.js} +4350 -5249
  58. package/dist/chunks/switch-D-CCcfhc.cjs +138 -0
  59. package/dist/chunks/temporal-bucket-5UYEotyQ.js +810 -0
  60. package/dist/chunks/temporal-bucket-DHY1y9lq.cjs +1 -0
  61. package/dist/chunks/temporal-bucket-authoring-K1kE6R_z.js +222 -0
  62. package/dist/chunks/temporal-bucket-authoring-o3Emn05L.cjs +1 -0
  63. package/dist/chunks/{temporal-bucket-contract-ChDBWX8I.cjs → temporal-bucket-contract-D2-93DGr.cjs} +1 -1
  64. package/dist/chunks/{temporal-bucket-contract-_F6vNhhH.js → temporal-bucket-contract-D5d-xEl3.js} +1 -1
  65. package/dist/chunks/{token-types-BdQ8kHBm.cjs → token-types-D7CaaI80.cjs} +1 -1
  66. package/dist/chunks/{token-types-BHR58aTy.js → token-types-GbxRUozo.js} +1 -1
  67. package/dist/chunks/{update-policy-BxvYMYz0.cjs → update-policy-BmiOd0PB.cjs} +1 -1
  68. package/dist/chunks/{update-policy-g0rCQ9BM.js → update-policy-hednMF-0.js} +1 -1
  69. package/dist/chunks/validators-BDYprKI9.cjs +1 -0
  70. package/dist/chunks/{validators-Cs74WVie.js → validators-DEmd8Sin.js} +1561 -1197
  71. package/dist/dashboard/index.cjs +1 -1
  72. package/dist/dashboard/index.js +2 -2
  73. package/dist/dashboard-authoring/index.cjs +3 -3
  74. package/dist/dashboard-authoring/index.js +35 -32
  75. package/dist/data-app-builder/index.cjs +1 -1
  76. package/dist/data-app-builder/index.js +2 -2
  77. package/dist/data-app-codegen/index.cjs +1 -1
  78. package/dist/data-app-codegen/index.js +2 -2
  79. package/dist/data-app-codegen-node/index.cjs +1 -1
  80. package/dist/data-app-codegen-node/index.js +3 -3
  81. package/dist/data-app-sdk/index.cjs +1 -1
  82. package/dist/data-app-sdk/index.js +78 -77
  83. package/dist/data-app-sdk-adapters/index.cjs +1 -1
  84. package/dist/data-app-sdk-adapters/index.js +29 -30
  85. package/dist/data-app-sdk-validation/index.cjs +1 -1
  86. package/dist/data-app-sdk-validation/index.js +21 -21
  87. package/dist/format-utils/index.cjs +3 -3
  88. package/dist/format-utils/index.js +156 -140
  89. package/dist/index.cjs +1 -1
  90. package/dist/index.js +157 -155
  91. package/dist/report-runtime-context/index.cjs +1 -1
  92. package/dist/report-runtime-context/index.js +2 -2
  93. package/dist/style.css +1 -1
  94. package/dist/surfboard/index.cjs +1 -1
  95. package/dist/surfboard/index.js +3 -3
  96. package/dist/types/analytics-protocol.d.ts +81 -11
  97. package/dist/types/briefings.d.ts +727 -19
  98. package/dist/types/dashboard-assistant.d.ts +37 -17
  99. package/dist/types/dashboard-authoring.d.ts +61 -14
  100. package/dist/types/dashboard.d.ts +137 -12
  101. package/dist/types/data-app-builder.d.ts +28 -2
  102. package/dist/types/data-app-codegen-node.d.ts +29 -3
  103. package/dist/types/data-app-codegen.d.ts +29 -3
  104. package/dist/types/data-app-sdk-adapters.d.ts +28 -2
  105. package/dist/types/data-app-sdk-validation.d.ts +51 -7
  106. package/dist/types/data-app-sdk.d.ts +55 -10
  107. package/dist/types/format-utils.d.ts +190 -3
  108. package/dist/types/index.cjs +1 -1
  109. package/dist/types/index.js +4 -4
  110. package/dist/types/main.d.ts +128 -33
  111. package/dist/types/shared.d.ts +14 -12
  112. package/dist/types/surfboard.d.ts +138 -13
  113. package/dist/types/types.d.ts +117 -23
  114. package/dist/types/value-format-preferences.d.ts +3 -0
  115. package/package.json +2 -1
  116. package/dist/chunks/card-config-utils-15sRtebL.cjs +0 -1
  117. package/dist/chunks/card-config-utils-BYZ5MJOh.js +0 -16
  118. package/dist/chunks/catalog-field-grounding-Bnx-3tE0.cjs +0 -1
  119. package/dist/chunks/catalog-field-grounding-S2jKwKGD.js +0 -100
  120. package/dist/chunks/dashboard-briefing-launcher-DDgDr2s3.cjs +0 -26
  121. package/dist/chunks/dashboard-date-comparison-definition-DZq0htjG.cjs +0 -1
  122. package/dist/chunks/dashboard-input-contract-DSt8dGzP.js +0 -18
  123. package/dist/chunks/dashboard-input-contract-DV3cshjz.cjs +0 -1
  124. package/dist/chunks/dashboard-json-CYtvwtvj.cjs +0 -1
  125. package/dist/chunks/edit-dashboard-visual-DwKcvlsF.cjs +0 -177
  126. package/dist/chunks/editor-action-buttons-BVmsk0Aj.cjs +0 -16
  127. package/dist/chunks/format-types-CSv0V7mm.cjs +0 -1
  128. package/dist/chunks/format-types-DZGgYj39.js +0 -1663
  129. package/dist/chunks/index-CJdxSyQq.js +0 -2578
  130. package/dist/chunks/index-DPv8_Ild.cjs +0 -1395
  131. package/dist/chunks/index-DRlMUglg.cjs +0 -4
  132. package/dist/chunks/metric-comparison-97zHGEx5.js +0 -387
  133. package/dist/chunks/metric-comparison-CUAJ8n4y.cjs +0 -1
  134. package/dist/chunks/pivot-result-lifecycle-BBabQ_da.js +0 -914
  135. package/dist/chunks/pivot-result-lifecycle-DPc0ANwk.cjs +0 -4
  136. package/dist/chunks/presentation-execution-BLfPTGX_.js +0 -637
  137. package/dist/chunks/presentation-execution-BTV-Q43g.cjs +0 -1
  138. package/dist/chunks/report-preferences-dialog-D9ZCGh9l.js +0 -691
  139. package/dist/chunks/report-preferences-dialog-DaqTEcac.cjs +0 -1
  140. package/dist/chunks/switch-Cjk6G06r.cjs +0 -138
  141. package/dist/chunks/temporal-bucket-BnPxGrAi.js +0 -446
  142. package/dist/chunks/temporal-bucket-authoring-CPTwHzvs.cjs +0 -1
  143. package/dist/chunks/temporal-bucket-authoring-CgOuakGW.js +0 -205
  144. package/dist/chunks/temporal-bucket-pMnV-4Nj.cjs +0 -1
  145. package/dist/chunks/temporal-result-owner-6peubmhU.js +0 -443
  146. package/dist/chunks/temporal-result-owner-f6-i65Fb.cjs +0 -1
  147. package/dist/chunks/validators-9D4KBqKD.cjs +0 -1
@@ -1 +0,0 @@
1
- "use strict";const a=require("zod"),R=["second","minute","hour","day","week","month","quarter","year"];function Ve(e){return typeof e=="string"&&R.includes(e)}const[,,...Y]=R;function Le(e){return Ve(e)&&Y.includes(e)}const Ge=["week_of_short","week_of_long","quarter_short","quarter_long","fiscal_quarter_short","fiscal_year"];function Ue(e){return e==="second"||e==="minute"||e==="hour"?"datetime":"date"}const Ci={missingMetadata:"missing_temporal_bucket_metadata",invalidMetadata:"invalid_temporal_bucket_metadata",invalidValue:"invalid_temporal_bucket_value"},Fi="__auto_count__";function He(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}const Qe={answerSummary:"string",responseDetail:"responseDetail",mode:"string",comparisonKind:"string",executionResult:"executionResult",compiledQuery:"unknown",data:"unknown",resultSets:"record",analysisWarnings:"unknownArray",columns:"unknownArray",records:"recordArray",rowCount:"number",rowLimitExceeded:"boolean",output:"string",querySpec:"unknown",metadata:"record",validation:"validationResult",coverage:"coverage",diagnosticFeedback:"diagnosticFeedback",missingFields:"stringArray",warnings:"unknownArray",comparison:"unknown",population:"population",comparisons:"recordArray",fieldsUsed:"compactExecutionFieldArray",primary:"recordArray",contributors:"recordArray",segments:"recordArray",periodChanges:"recordArray",changes:"recordArray",largestNegativeChanges:"recordArray",largestPositiveChanges:"recordArray",drivers:"recordArray",absoluteDeltaDrivers:"recordArray",largestNegativeDrivers:"recordArray",largestPositiveDrivers:"recordArray",periodRows:"recordArray",sql:"unknown",omitted:"stringArray"},Di="SUM";function I(e){return typeof e=="string"&&e.trim().length>0}function Ni(e){return e?e.kind==="semantic"?!!(I(e.domainId)&&(I(e.datasetId)||I(e.datasetName))):e.kind==="physical"?I(e.connectionId)&&I(e.tableName):I(e.connectionId):!1}function L(e){return e?e.kind==="semantic"?[e.kind,e.domainId,e.datasetId?`datasetId:${e.datasetId}`:`datasetName:${e.datasetName}`].join(":"):e.kind==="physical"?[e.kind,e.connectionId,e.databaseName||"",e.schemaName||"",e.tableName].join(":"):[e.kind,e.connectionId,e.dialect||"",e.label||""].join(":"):""}function pe(e,i){return!e||!i?e===i:e.kind!==i.kind?!1:e.kind==="semantic"&&i.kind==="semantic"?e.domainId!==i.domainId?!1:e.datasetId&&i.datasetId?e.datasetId===i.datasetId:e.datasetName===i.datasetName:L(e)===L(i)}function me(e,i){return e.kind!=="semantic"||i.kind!=="semantic"?e:{...e,datasetName:e.datasetName||i.datasetName,datasetId:e.datasetId||i.datasetId,label:e.label||i.label,connectionId:e.connectionId||i.connectionId}}function qi(e){const i=[];for(const t of e){const s=i.findIndex(n=>pe(n,t));if(s===-1){i.push(t);continue}i[s]=me(i[s],t)}return i}function Ye(e,i){return e.name===i.name&&pe(e.source,i.source)}function Ze(e){return[e.source?L(e.source):"unknown",Z(e),e.name].filter(Boolean).join(":")}function Z(e){return Oi(e.aggregate||Di)}function Oi(e){return e.trim().toUpperCase()}function Pi(e,i){return{...e,label:e.label||i.label,role:e.role||i.role,dataType:e.dataType||i.dataType,source:e.source&&i.source?me(e.source,i.source):e.source||i.source}}const G="semaphor-data-app-codegen-summary/v1",Bi="semaphor-data-app-codegen-summary-validator/v2",Ki=new Set(["metric","records","matrix","analysis","sql_fallback"]),Vi=new Set(["semaphor.metric","semaphor.records","semaphor.matrix","semaphor.analysis","semaphor.sql"]),Li=new Set(["SUM","COUNT","AVG","MIN","MAX","MEDIAN","DISTINCT"]),Gi=new Set(["absolute_delta","largest_negative","largest_positive","positive_and_negative","all"]),Xe=new Set(["source","id","label","measures","primaryMeasure","dateField","timeGrain","dimensions","comparison","orderBy","filters","relationshipHint","limit","derivedFields"]),Ui=new Set([...Xe,"analysis","timeWindow","filters","driverMode","includePopulation","calendarContext","chartTitle","chartType"]),Hi=new Set(["source","id","label","fields","dateField","timeGrain","timeWindow","filters","orderBy","relationshipHint","limit","pagination","totals","derivedFields"]),Qi=new Set(["source","id","label","filters","relationshipHint","rows","columns","values","totals","sort","expansion","layout","displayLimits"]),Yi=new Set(["source","id","label","sql","defaultParameters","pythonCode","fields","limit","pagination","rationale"]),Zi=new Set(["kpi","line_chart","bar_chart","stacked_bar_chart","pie_chart","donut_chart","area_chart","table","matrix","narrative","text_block","custom"]),Xi=new Set(["missing_measure","missing_dimension","missing_date","missing_relationship","missing_semantic_role","missing_current_app_state","raw_identifier_filter_options","unsupported_change_intent","ambiguous_field_grounding","bounded_intent_unavailable","invalid_bounded_intent_output","latest_snapshot_selector_not_modeled","unsupported_grain","requires_sql_escape_hatch","unsupported_sdk_capability"]);function Ji(e){return fe(e).ok}function fe(e){const i=[];if(!e||typeof e!="object")return{ok:!1,issues:["Summary must be an object."]};const t=e;return t.schemaVersion!==G&&i.push(`schemaVersion must be ${G}.`),(typeof t.title!="string"||!t.title.trim())&&i.push("title is required."),Array.isArray(t.sources)||i.push("sources must be an array."),Array.isArray(t.inputs)||i.push("inputs must be an array."),Array.isArray(t.views)||i.push("views must be an array."),Array.isArray(t.filterContracts)||i.push("filterContracts must be an array."),(!t.implementationChecklist||typeof t.implementationChecklist!="object")&&i.push("implementationChecklist must be an object."),t.implementationChecklist&&typeof t.implementationChecklist=="object"&&i.push(...et(t.implementationChecklist)),Array.isArray(t.sources)&&t.sources.forEach((s,n)=>{i.push(...F(s,`sources.${n}`))}),Array.isArray(t.inputs)&&t.inputs.forEach((s,n)=>{i.push(...it(s,`inputs.${n}`))}),Array.isArray(t.views)&&t.views.forEach((s,n)=>{i.push(...tt(s,`views.${n}`))}),Array.isArray(t.filterContracts)&&t.filterContracts.forEach((s,n)=>{i.push(...pt(s,`filterContracts.${n}`))}),t.unsupportedInsights!==void 0&&(Array.isArray(t.unsupportedInsights)?t.unsupportedInsights.forEach((s,n)=>{i.push(...jt(s,`unsupportedInsights.${n}`))}):i.push("unsupportedInsights must be an array.")),i.push(...Wi(t)),{ok:i.length===0,issues:i}}function Wi(e){const i=Array.isArray(e.unsupportedInsights)&&e.unsupportedInsights.some(l=>{var d;return Re.has((d=c(l))==null?void 0:d.reason)}),t=Array.isArray(e.views)&&e.views.some(l=>{var u;const d=c((u=c(l))==null?void 0:u.computation);return(d==null?void 0:d.kind)==="unsupported"&&Re.has(d.reason)});if(!i&&!t)return[];const s=[],n=c(e.validation);(n==null?void 0:n.status)!=="blocked"&&s.push("validation.status must be blocked when semantic model repair gaps are present.");const r=c(e.nextRequiredTool);return(r==null?void 0:r.name)!=="semaphor_propose_semantic_model_change"&&s.push("nextRequiredTool.name must be semaphor_propose_semantic_model_change when semantic model repair gaps are present."),s}const Re=new Set(["missing_relationship","raw_identifier_filter_options"]);function F(e,i){const t=c(e);return t?t.kind==="semantic"?typeof t.domainId=="string"&&t.domainId.trim()&&typeof t.datasetName=="string"&&t.datasetName.trim()?[]:[`${i} must include sourceKey or a supported source identity.`]:typeof t.sourceKey=="string"&&t.sourceKey.trim()?[]:t.kind==="physical"&&typeof t.tableName=="string"&&t.tableName.trim()&&typeof t.connectionId=="string"&&t.connectionId.trim()?[]:t.kind==="sql"&&typeof t.connectionId=="string"&&t.connectionId.trim()?[]:[`${i} must include sourceKey or a supported source identity.`]:[`${i} must be an object.`]}function et(e){const i=c(e);if(!i)return["implementationChecklist must be an object."];const t=[],s=["requiredDevtools","requiredInputOptions","filterScopeByInput","bindingsByView","validationCommands","browserSmokeChecks"];for(const r of s)r in i||t.push(`implementationChecklist.${r} is required.`);const n=c(i.requiredDevtools);return n?typeof n.mountRootDevtools!="boolean"&&t.push("implementationChecklist.requiredDevtools.mountRootDevtools must be a boolean."):t.push("implementationChecklist.requiredDevtools must be an object."),Array.isArray(i.requiredInputOptions)||t.push("implementationChecklist.requiredInputOptions must be an array."),Array.isArray(i.filterScopeByInput)||t.push("implementationChecklist.filterScopeByInput must be an array."),c(i.bindingsByView)||t.push("implementationChecklist.bindingsByView must be an object."),v(i.validationCommands)||t.push("implementationChecklist.validationCommands must be an array of strings."),v(i.browserSmokeChecks)||t.push("implementationChecklist.browserSmokeChecks must be an array of strings."),t}function it(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];return(typeof t.id!="string"||!t.id.trim())&&s.push(`${i}.id is required.`),t.fieldRef&&s.push(...h(t.fieldRef,`${i}.fieldRef`)),s.push(...We(t.optionQuery,`${i}.optionQuery`)),v(t.appliesToViewIds)||s.push(`${i}.appliesToViewIds must be an array of strings.`),t.bindings!==void 0&&!Array.isArray(t.bindings)&&s.push(`${i}.bindings must be an array.`),Array.isArray(t.bindings)&&t.bindings.forEach((n,r)=>{const l=c(n);if(!l){s.push(`${i}.bindings.${r} must be an object.`);return}v(l.appliesToViewIds)||s.push(`${i}.bindings.${r}.appliesToViewIds must be an array of strings.`),s.push(...h(l.fieldRef,`${i}.bindings.${r}.fieldRef`))}),s}function tt(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];if((typeof t.id!="string"||!t.id.trim())&&s.push(`${i}.id is required.`),t.visualSpec!==void 0&&s.push(...It(t.visualSpec,`${i}.visualSpec`)),t.computation!==void 0&&s.push(...Et(t.computation,`${i}.computation`)),wt(t))return s.push(...ie(t,`${i}`)),t.fields!==void 0&&(Array.isArray(t.fields)?t.fields.forEach((u,f)=>{s.push(...h(u,`${i}.fields.${f}`))}):s.push(`${i}.fields must be an array.`)),t.queryKind!==void 0&&s.push(`${i}.queryKind is not allowed for non-executable views.`),t.sdkBuilder!==void 0&&s.push(`${i}.sdkBuilder is not allowed for non-executable views.`),t.sdkSpec!==void 0&&s.push(`${i}.sdkSpec is not allowed for non-executable views.`),s;if(!Array.isArray(t.fields))return s.push(`${i}.fields must be an array.`),(t.sdkSpec!==void 0||t.sdkBuilder!==void 0)&&s.push(`${i}.fields must be an array for executable views.`),s.push(...ie(t,`${i}`)),s;t.fields.forEach((u,f)=>{s.push(...h(u,`${i}.fields.${f}`))}),j(t.queryKind)||s.push(`${i}.queryKind must be a supported codegen query kind.`),t.sdkBuilder!==void 0&&!ti(t.sdkBuilder)&&s.push(`${i}.sdkBuilder must be a supported SDK builder.`),t.metricBindingKeys!==void 0&&(Array.isArray(t.metricBindingKeys)?t.metricBindingKeys.some(u=>typeof u!="string"||u.trim().length===0)&&s.push(`${i}.metricBindingKeys must be an array of strings.`):s.push(`${i}.metricBindingKeys must be an array of strings.`));const n=c(t.sdkSpec),r=(n==null?void 0:n.builder)==="semaphor.metric";r&&(!Array.isArray(t.metricBindingKeys)||t.metricBindingKeys.length===0)&&s.push(`${i}.metricBindingKeys is required for metric views.`);const l=at(t);r&&Array.isArray(t.metricBindingKeys)&&l&&JSON.stringify(t.metricBindingKeys)!==JSON.stringify(l)&&s.push(`${i}.metricBindingKeys must match the generated metric field binding keys in order.`);const d=c(t.computation);return(d==null?void 0:d.kind)==="server_query"&&j(t.queryKind)&&j(d.queryKind)&&d.queryKind!==t.queryKind&&s.push(`${i}.computation.queryKind must match queryKind.`),s.push(...mt({value:t.sdkSpec,path:`${i}.sdkSpec`,queryKind:typeof t.queryKind=="string"?t.queryKind:void 0,sdkBuilder:typeof t.sdkBuilder=="string"?t.sdkBuilder:void 0}),...ie(t,`${i}`)),s}function at(e){const i=c(e.sdkSpec);if((i==null?void 0:i.builder)!=="semaphor.metric")return;const t=c(i.spec);if(!t)return;const n=[t.primaryMeasure,...Array.isArray(t.measures)?t.measures:[]].map(st).filter(r=>!!r);return Array.from(new Map(n.map(r=>[r.identity,r.bindingKey])).values())}function st(e){const i=c(e);if(!i||typeof i.name!="string"||!i.name.trim())return;const t=nt(i);return t?{identity:JSON.stringify({source:t,name:i.name,aggregate:Je(i)}),bindingKey:ot(i)}:void 0}function nt(e){if(typeof e.sourceKey=="string"&&e.sourceKey.trim())return{sourceKey:e.sourceKey};const i=c(e.source);if(i)return{kind:i.kind,domainId:i.domainId,datasetId:i.datasetId,datasetName:i.datasetName,name:i.name}}function ot(e){return typeof e.sourceKey=="string"&&e.sourceKey.trim()?[e.sourceKey,Je(e),e.name].filter(Boolean).join(":"):Ze(e)}function Je(e){return Z(e)}function ie(e,i){var f;const t=c((f=c(e.visualSpec))==null?void 0:f.tableBehavior),s=c(e.sdkSpec),n=c(s==null?void 0:s.spec),r=typeof(s==null?void 0:s.builder)=="string"?s.builder:void 0,l=r==="semaphor.records"?c(n==null?void 0:n.totals):void 0,d=[];if(!t)return l&&d.push(`${i}.sdkSpec.spec.totals is only allowed when tableBehavior.totals.mode is server.`),d;const u=c(t.totals);return u?(u.mode==="server"&&(r!=="semaphor.records"&&d.push(`${i}.visualSpec.tableBehavior.totals.mode server is only supported for semaphor.records views.`),!l||l.mode!=="server"?d.push(`${i}.sdkSpec.spec.totals.mode must be server when tableBehavior.totals.mode is server.`):d.push(...rt({left:u.measures,right:l.measures,leftPath:`${i}.visualSpec.tableBehavior.totals.measures`,rightPath:`${i}.sdkSpec.spec.totals.measures`}))),u.mode!=="server"&&l&&d.push(`${i}.sdkSpec.spec.totals is only allowed when tableBehavior.totals.mode is server.`),r==="semaphor.sql"&&u.mode!=="none"&&d.push(`${i}.visualSpec.tableBehavior.totals.mode must be none for semaphor.sql views.`),r==="semaphor.sql"&&c(n==null?void 0:n.totals)&&d.push(`${i}.sdkSpec.spec.totals is not supported for semaphor.sql.`),d):(l&&d.push(`${i}.sdkSpec.spec.totals is only allowed when tableBehavior.totals.mode is server.`),d)}function rt({left:e,right:i,leftPath:t,rightPath:s}){if(!Array.isArray(e)||!Array.isArray(i))return[`${s} must match ${t}.`];const n=[];return e.length!==i.length?(n.push(`${s} must match ${t}.`),n):(e.forEach((r,l)=>{lt(c(r),c(i[l]))||n.push(`${s}.${l} must match ${t}.${l}.`)}),n)}function lt(e,i){return!e||!i?!1:e.name===i.name&&(e.role||"measure")===(i.role||"measure")&&Me(e)===Me(i)&&dt(e,i)}function Me(e){return typeof e.aggregate=="string"?e.aggregate.toUpperCase():"SUM"}function dt(e,i){const t=c(e.source),s=c(i.source);if(ut(t,s))return!1;const n=Ee(e),r=Ee(i);if(n.size>0||r.size>0){for(const l of n)if(r.has(l))return!0;return!1}return!t||!s||t.kind!==s.kind?!1:t.kind==="semantic"?t.domainId===s.domainId&&t.datasetName===s.datasetName&&(t.datasetId===void 0||s.datasetId===void 0||t.datasetId===s.datasetId):t.kind==="physical"?t.connectionId===s.connectionId&&t.tableName===s.tableName:t.kind==="sql"?t.connectionId===s.connectionId:!1}function ut(e,i){if(!e||!i||e.kind!=="semantic"||i.kind!=="semantic")return!1;const t=typeof e.datasetId=="string"?e.datasetId.trim():"",s=typeof i.datasetId=="string"?i.datasetId.trim():"";return!!(t&&s&&t!==s)}function Ee(e){const i=typeof e.sourceKey=="string"?e.sourceKey.trim():"";return i?new Set([i]):ct(c(e.source))}function ct(e){const i=new Set;if(!e)return i;const t=typeof e.sourceKey=="string"?e.sourceKey.trim():"";if(t&&i.add(t),e.kind==="semantic"){const s=typeof e.domainId=="string"?e.domainId:"",n=typeof e.datasetName=="string"?e.datasetName:"",r=typeof e.datasetId=="string"?e.datasetId:"";s&&r&&i.add(`semantic:${s}:datasetId:${r}`),s&&n&&i.add(`semantic:${s}:datasetName:${n}`)}if(e.kind==="physical"){const s=typeof e.connectionId=="string"?e.connectionId:"",n=typeof e.tableName=="string"?e.tableName:"",r=typeof e.databaseName=="string"?e.databaseName:"",l=typeof e.schemaName=="string"?e.schemaName:"";s&&n&&(i.add(["physical",s,r,l,n].join(":")),i.add(`physical:${s}:${n}`))}if(e.kind==="sql"){const s=typeof e.connectionId=="string"?e.connectionId:"",n=typeof e.dialect=="string"?e.dialect:"",r=typeof e.label=="string"?e.label:"";s&&(i.add(["sql",s,n,r].join(":")),i.add(`sql:${s}`))}return i}function pt(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];if(t.fieldRef&&s.push(...h(t.fieldRef,`${i}.fieldRef`)),(typeof t.inputId!="string"||!t.inputId.trim())&&s.push(`${i}.inputId is required.`),s.push(...We(t.optionQuery,`${i}.optionQuery`)),v(t.appliesToViewIds)||s.push(`${i}.appliesToViewIds must be an array of strings.`),v(t.notAppliedToViewIds)||s.push(`${i}.notAppliedToViewIds must be an array of strings.`),!Array.isArray(t.bindings))s.push(`${i}.bindings must be an array.`);else{const n=v(t.appliesToViewIds)?new Set(t.appliesToViewIds):void 0,r=v(t.notAppliedToViewIds)?new Set(t.notAppliedToViewIds):void 0;t.bindings.forEach((l,d)=>{const u=c(l);if(!u){s.push(`${i}.bindings.${d} must be an object.`);return}typeof u.viewId!="string"||!u.viewId?s.push(`${i}.bindings.${d}.viewId is required.`):(n&&!n.has(u.viewId)&&s.push(`${i}.bindings.${d}.viewId must be included in appliesToViewIds.`),r!=null&&r.has(u.viewId)&&s.push(`${i}.bindings.${d}.viewId must not be listed in notAppliedToViewIds.`)),s.push(...h(u.fieldRef,`${i}.bindings.${d}.fieldRef`))})}return s}function We(e,i){if(e===void 0)return[];const t=c(e);if(!t)return[`${i} must be an object.`];const s=[...z(t.valueFieldRef,`${i}.valueFieldRef`),...z(t.labelFieldRef,`${i}.labelFieldRef`),...z(t.filterFieldRef,`${i}.filterFieldRef`)];return t.builder!=="semaphor.inputOptions"&&s.push(`${i}.builder must be semaphor.inputOptions.`),typeof t.sourceKey!="string"&&t.source===void 0&&s.push(`${i} must include source or sourceKey.`),t.source!==void 0&&s.push(...F(t.source,`${i}.source`)),c(t.valueFieldRef)||s.push(`${i}.valueFieldRef is required.`),c(t.labelFieldRef)||s.push(`${i}.labelFieldRef is required.`),t.limit!==void 0&&(typeof t.limit!="number"||!Number.isInteger(t.limit)||t.limit<=0)&&s.push(`${i}.limit must be a positive integer.`),s}function mt(e){var n;const i=c(e.value);if(!i)return[`${e.path} is required for executable views.`];const t=[];if(!ti(i.builder))return t.push(`${e.path}.builder must be a supported SDK builder.`),t;e.sdkBuilder&&i.builder!==e.sdkBuilder&&t.push(`${e.path}.builder must match sdkBuilder.`),e.queryKind&&j(e.queryKind)&&i.builder!==$t(e.queryKind)&&t.push(`${e.path}.builder must match queryKind.`);const s=c(i.spec);if(!s)return t.push(`${e.path}.spec must be an object.`),t;switch(i.builder){case"semaphor.metric":t.push(...E(s,Xe,`${e.path}.spec`),...P(s,e.path),...te(s.measures,`${e.path}.spec.measures`),...z(s.primaryMeasure,`${e.path}.spec.primaryMeasure`),...z(s.dateField,`${e.path}.spec.dateField`),...ae(s.dimensions,`${e.path}.spec.dimensions`),...se(s.orderBy,`${e.path}.spec.orderBy`),...B(s.filters,`${e.path}.spec.filters`));break;case"semaphor.analysis":t.push(...E(s,Ui,`${e.path}.spec`),...P(s,e.path),...te(s.measures,`${e.path}.spec.measures`),...z(s.primaryMeasure,`${e.path}.spec.primaryMeasure`),...z(s.dateField,`${e.path}.spec.dateField`),...ae(s.dimensions,`${e.path}.spec.dimensions`),...se(s.orderBy,`${e.path}.spec.orderBy`),...B(s.filters,`${e.path}.spec.filters`),...gt(s,`${e.path}.spec`));break;case"semaphor.records":t.push(...E(s,Hi,`${e.path}.spec`),...P(s,e.path),...te(s.fields,`${e.path}.spec.fields`),...z(s.dateField,`${e.path}.spec.dateField`),...se(s.orderBy,`${e.path}.spec.orderBy`),...B(s.filters,`${e.path}.spec.filters`),...ht(s.totals,`${e.path}.spec.totals`));break;case"semaphor.matrix":t.push(...E(s,Qi,`${e.path}.spec`),...yt(s,e.path),...bt(s.rows,`${e.path}.spec.rows`),..._t(s.columns,`${e.path}.spec.columns`),...vt(s.values,`${e.path}.spec.values`),...zt(s.sort,`${e.path}.spec.sort`),...B(s.filters,`${e.path}.spec.filters`),...ft(s.displayLimits,`${e.path}.spec.displayLimits`));break;case"semaphor.sql":t.push(...E(s,Yi,`${e.path}.spec`),...P(s,e.path)),((n=c(s.source))==null?void 0:n.kind)!=="sql"&&t.push(`${e.path}.spec.source.kind must be sql.`),(typeof s.sql!="string"||!s.sql.trim())&&t.push(`${e.path}.spec.sql is required.`),t.push(...ae(s.fields,`${e.path}.spec.fields`));break}return t}function ft(e,i){if(e===void 0)return[];const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];s.push(...je(t.rows,`${i}.rows`),...je(t.columns,`${i}.columns`));for(const n of Object.keys(t))n==="rows"||n==="columns"||s.push(`${i}.${n} is not supported.`);return s}function je(e,i){if(e===void 0)return[];const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];(typeof t.limit!="number"||!Number.isInteger(t.limit)||t.limit<1)&&s.push(`${i}.limit must be a positive integer.`);for(const n of Object.keys(t))n!=="limit"&&s.push(`${i}.${n} is not supported; matrix display limits are count-only in v1.`);return s}function gt(e,i){const t=[];if(e.driverMode!==void 0&&!Gi.has(e.driverMode)&&t.push(`${i}.driverMode must be a supported analysis driver mode.`),e.includePopulation!==void 0&&typeof e.includePopulation!="boolean"&&t.push(`${i}.includePopulation must be a boolean.`),e.calendarContext!==void 0){const s=c(e.calendarContext);if(!s)t.push(`${i}.calendarContext must be an object.`);else{s.tz!==void 0&&typeof s.tz!="string"&&t.push(`${i}.calendarContext.tz must be a string.`),s.weekStart!==void 0&&(typeof s.weekStart!="number"||!Number.isInteger(s.weekStart)||s.weekStart<0||s.weekStart>6)&&t.push(`${i}.calendarContext.weekStart must be an integer between 0 and 6.`);const n=s.anchor;if(n!==void 0&&n!=="now"){const r=c(n);(!r||typeof r.iso!="string"||!r.iso.trim())&&t.push(`${i}.calendarContext.anchor must be now or { iso }.`)}}}return t}function ht(e,i){if(e===void 0)return[];const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];return t.mode!=="server"&&s.push(`${i}.mode must be server.`),!Array.isArray(t.measures)||t.measures.length===0?s.push(`${i}.measures must include at least one measure.`):t.measures.forEach((n,r)=>{var l;s.push(...ai(n,`${i}.measures.${r}`)),((l=c(n))==null?void 0:l.role)!=="measure"&&s.push(`${i}.measures.${r}.role must be measure.`)}),s}function E(e,i,t){const s=[];return Object.keys(e).forEach(n=>{i.has(n)||s.push(`${t}.${n} is not supported for this SDK builder.`)}),s}function P(e,i){return c(e.source)?F(e.source,`${i}.spec.source`):[`${i}.spec.source must be an object.`]}function yt(e,i){const t=c(e.source);if(!t)return[`${i}.spec.source must be an object.`];const s=F(e.source,`${i}.spec.source`);return t.kind!=="semantic"&&t.kind!=="physical"&&s.push(`${i}.spec.source.kind must be semantic or physical.`),s}function te(e,i){const t=ge(e,i);return Array.isArray(e)&&e.forEach((s,n)=>{t.push(...h(s,`${i}.${n}`))}),t}function ae(e,i){if(e===void 0)return[];if(!Array.isArray(e))return[`${i} must be an array.`];const t=[];return e.forEach((s,n)=>{t.push(...h(s,`${i}.${n}`))}),t}function se(e,i){if(e===void 0)return[];const t=c(e);return t?[...h(t.field,`${i}.field`),...ei(t.direction,`${i}.direction`)]:[`${i} must be an object.`]}function bt(e,i){const t=ge(e,i);return Array.isArray(e)&&e.forEach((s,n)=>{const r=c(s);if(!r){t.push(`${i}.${n} must be an object.`);return}t.push(...h(r.field,`${i}.${n}.field`))}),t}function _t(e,i){if(e===void 0)return[];const t=[];return Array.isArray(e)?(e.forEach((s,n)=>{const r=c(s);if(!r){t.push(`${i}.${n} must be an object.`);return}t.push(...h(r.field,`${i}.${n}.field`))}),t):[`${i} must be an array.`]}function vt(e,i){const t=ge(e,i);return Array.isArray(e)&&e.forEach((s,n)=>{const r=c(s);if(!r){t.push(`${i}.${n} must be an object.`);return}t.push(...h(r.field,`${i}.${n}.field`))}),t}function zt(e,i){if(e===void 0)return[];if(!Array.isArray(e))return[`${i} must be an array.`];const t=[];return e.forEach((s,n)=>{const r=c(s);if(!r){t.push(`${i}.${n} must be an object.`);return}r.axis!=="row"&&r.axis!=="column"&&t.push(`${i}.${n}.axis must be row or column.`),t.push(...ei(r.direction,`${i}.${n}.direction`),...St(r.by,`${i}.${n}.by`))}),t}function St(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];switch(t.kind){case"label":return[];case"field":return h(t.field,`${i}.field`);case"value":return typeof t.valueId!="string"||!t.valueId.trim()?[`${i}.valueId is required.`]:[];default:return[`${i}.kind must be label, field, or value.`]}}function ei(e,i){return e==="asc"||e==="desc"?[]:[`${i} must be asc or desc.`]}function B(e,i){if(e===void 0)return[];if(!Array.isArray(e))return[`${i} must be an array.`];const t=[];return e.forEach((s,n)=>{const r=c(s);if(!r){t.push(`${i}.${n} must be an object.`);return}t.push(...h(r.field,`${i}.${n}.field`))}),t}function ge(e,i){return!Array.isArray(e)||e.length===0?[`${i} must be a non-empty array.`]:[]}function $t(e){switch(e){case"metric":return"semaphor.metric";case"records":return"semaphor.records";case"matrix":return"semaphor.matrix";case"analysis":return"semaphor.analysis";case"sql_fallback":return"semaphor.sql"}}function wt(e){const i=c(e.computation),t=c(e.visualSpec);return(i==null?void 0:i.kind)==="presentation_only"||(i==null?void 0:i.kind)==="derived"||(i==null?void 0:i.kind)==="unsupported"||e.visual==="text_block"||(t==null?void 0:t.visualType)==="text_block"}function It(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];return Zi.has(t.visualType)||s.push(`${i}.visualType must be a supported visual type.`),t.limit!==void 0&&(typeof t.limit!="number"||!Number.isInteger(t.limit)||t.limit<=0)&&s.push(`${i}.limit must be a positive integer.`),t.tableBehavior!==void 0&&s.push(...kt(t.tableBehavior,`${i}.tableBehavior`)),s}function kt(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];return t.tableMode!=="bounded"&&t.tableMode!=="server_paginated"&&t.tableMode!=="server_windowed"&&s.push(`${i}.tableMode must be a supported table mode.`),s.push(...At(t.height,`${i}.height`),...xt(t.pagination,`${i}.pagination`),...Rt(t.sorting,`${i}.sorting`),...Mt(t.totals,`${i}.totals`)),typeof t.serverSideRequired!="boolean"&&s.push(`${i}.serverSideRequired must be a boolean.`),s}function At(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];return(typeof t.maxPx!="number"||!Number.isInteger(t.maxPx)||t.maxPx<=0)&&s.push(`${i}.maxPx must be a positive integer.`),t.scroll!=="vertical"&&t.scroll!=="both"&&s.push(`${i}.scroll must be vertical or both.`),typeof t.stickyHeader!="boolean"&&s.push(`${i}.stickyHeader must be a boolean.`),s}function xt(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];return t.mode!=="none"&&t.mode!=="server"&&t.mode!=="client_for_bounded_rows"&&s.push(`${i}.mode must be a supported pagination mode.`),t.pageSize!==void 0&&(typeof t.pageSize!="number"||!Number.isInteger(t.pageSize)||t.pageSize<=0)&&s.push(`${i}.pageSize must be a positive integer.`),t.readsFrom!==void 0&&t.readsFrom!=="result.pagination"&&s.push(`${i}.readsFrom must be result.pagination.`),s}function Rt(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];return t.mode!=="server"&&t.mode!=="client_for_bounded_rows"&&s.push(`${i}.mode must be a supported sorting mode.`),t.defaultField!==void 0&&(typeof t.defaultField!="string"||!t.defaultField.trim())&&s.push(`${i}.defaultField must be a non-empty string.`),t.defaultDirection!==void 0&&t.defaultDirection!=="asc"&&t.defaultDirection!=="desc"&&s.push(`${i}.defaultDirection must be asc or desc.`),t.resetPageOnChange!==void 0&&typeof t.resetPageOnChange!="boolean"&&s.push(`${i}.resetPageOnChange must be a boolean.`),s}function Mt(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];return t.mode!=="none"&&t.mode!=="server"&&t.mode!=="local"?(s.push(`${i}.mode must be none, server, or local.`),s):t.mode==="none"?(t.measures!==void 0&&s.push(`${i}.measures is not allowed when mode is none.`),t.label!==void 0&&s.push(`${i}.label is not allowed when mode is none.`),s):t.mode==="server"?(!Array.isArray(t.measures)||t.measures.length===0?s.push(`${i}.measures must include at least one measure when mode is server.`):t.measures.forEach((n,r)=>{var l;s.push(...ai(n,`${i}.measures.${r}`)),((l=c(n))==null?void 0:l.role)!=="measure"&&s.push(`${i}.measures.${r}.role must be measure.`)}),t.label!==void 0&&s.push(`${i}.label is not allowed when mode is server.`),s):(t.mode==="local"&&(t.label!=="Displayed rows"&&t.label!=="Current page"&&s.push(`${i}.label must be Displayed rows or Current page when mode is local.`),t.measures!==void 0&&s.push(`${i}.measures is not allowed when mode is local.`)),s)}function Et(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];switch(t.kind){case"server_query":j(t.queryKind)||s.push(`${i}.queryKind must be a supported codegen query kind.`),t.queryOwnership!==void 0&&t.queryOwnership!=="view_owned"&&t.queryOwnership!=="shared_query"&&s.push(`${i}.queryOwnership must be view_owned or shared_query.`),t.sourceKeys!==void 0&&!v(t.sourceKeys)&&s.push(`${i}.sourceKeys must be an array of strings.`),t.fieldNames!==void 0&&!v(t.fieldNames)&&s.push(`${i}.fieldNames must be an array of strings.`);break;case"derived":(typeof t.upstreamViewId!="string"||!t.upstreamViewId.trim())&&s.push(`${i}.upstreamViewId is required.`),(typeof t.derivation!="string"||!t.derivation.trim())&&s.push(`${i}.derivation is required.`);break;case"presentation_only":break;case"unsupported":(typeof t.reason!="string"||!t.reason.trim())&&s.push(`${i}.reason is required.`),(typeof t.suggestedModelingFix!="string"||!t.suggestedModelingFix.trim())&&s.push(`${i}.suggestedModelingFix is required.`);break;default:s.push(`${i}.kind must be a supported computation kind.`)}return s}function jt(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];for(const r of["title","requestedQuestion","suggestedModelingFix"])(typeof t[r]!="string"||!t[r].trim())&&s.push(`${i}.${r} is required.`);return Xi.has(t.reason)||s.push(`${i}.reason must be a supported unsupported insight reason.`),(t.relationshipCandidate!==void 0||t.nextRepairAction!==void 0)&&t.reason!=="missing_relationship"&&s.push(`${i} relationship repair metadata is only valid for missing_relationship unsupported insights.`),t.diagnostic!==void 0&&s.push(...Tt(t.diagnostic,`${i}.diagnostic`,t.reason)),t.relationshipCandidate!==void 0&&s.push(...Ft(t.relationshipCandidate,`${i}.relationshipCandidate`)),t.nextRepairAction!==void 0&&s.push(...Ct(t.nextRepairAction,`${i}.nextRepairAction`)),s}function Tt(e,i,t){const s=c(e);if(!s)return[`${i} must be an object.`];const n=[],r=new Set(["kind","inputId","inputLabel","optionSource","optionField","missingEvidence"]);Object.keys(s).forEach(d=>{r.has(d)||n.push(`${i}.${d} is not supported; raw identifier diagnostics support only kind, inputId, inputLabel, optionSource, optionField, and missingEvidence.`)}),t!=="raw_identifier_filter_options"&&n.push(`${i} is only valid for raw_identifier_filter_options unsupported insights.`),s.kind!=="raw_identifier_filter_options"&&n.push(`${i}.kind must be raw_identifier_filter_options.`);for(const d of["inputId","inputLabel"])(typeof s[d]!="string"||!s[d].trim())&&n.push(`${i}.${d} must be a non-empty string.`);n.push(...re(s.optionSource,`${i}.optionSource`)),n.push(...ii(s.optionField,`${i}.optionField`));const l=new Set(["display_field","relationship_display_path"]);return!Array.isArray(s.missingEvidence)||s.missingEvidence.length===0?n.push(`${i}.missingEvidence must be a non-empty evidence array.`):s.missingEvidence.forEach((d,u)=>{l.has(d)||n.push(`${i}.missingEvidence.${u} must be display_field or relationship_display_path.`)}),n}function Ct(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[],n=new Set(["tool","reason"]);return Object.keys(t).forEach(r=>{n.has(r)||s.push(`${i}.${r} is not supported; repair actions support only tool and reason.`)}),t.tool!=="semaphor_propose_semantic_model_change"&&s.push(`${i}.tool must be semaphor_propose_semantic_model_change.`),t.reason!=="missing_relationship"&&s.push(`${i}.reason must be missing_relationship.`),s}function Ft(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[],n=new Set(["source","sourceFields","target","targetFields"]);Object.keys(t).forEach(r=>{n.has(r)||s.push(`${i}.${r} is not supported; relationship candidates support only source, sourceFields, target, and targetFields.`)}),s.push(...re(t.source,`${i}.source`)),s.push(...re(t.target,`${i}.target`));for(const r of["sourceFields","targetFields"]){const l=t[r];if(!Array.isArray(l)||l.length===0){s.push(`${i}.${r} must be a non-empty endpoint field array.`);continue}l.forEach((d,u)=>{s.push(...ii(d,`${i}.${r}.${u}`))})}return s}function ii(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[],n=new Set(["name","label","role","dataType"]);return Object.keys(t).forEach(r=>{n.has(r)||s.push(`${i}.${r} is not supported; relationship candidate fields are scoped by their endpoint and support only name, label, role, and dataType.`)}),(typeof t.name!="string"||!t.name.trim())&&s.push(`${i}.name must be a non-empty string.`),t.role!==void 0&&(typeof t.role!="string"||!["dimension","measure","date","id","unknown"].includes(t.role))&&s.push(`${i}.role must be dimension, measure, date, id, or unknown.`),t.dataType!==void 0&&(typeof t.dataType!="string"||!["string","number","boolean","date","datetime","unknown"].includes(t.dataType))&&s.push(`${i}.dataType must be string, number, boolean, date, datetime, or unknown.`),s}function re(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[],n=new Set(["kind","domainId","datasetName","datasetId","label","sourceKey"]);return Object.keys(t).forEach(r=>{n.has(r)||s.push(`${i}.${r} is not supported; relationship candidate sources support only semantic identity fields.`)}),t.kind!=="semantic"&&s.push(`${i} must use semantic source identity.`),(typeof t.domainId!="string"||!t.domainId.trim()||typeof t.datasetName!="string"||!t.datasetName.trim())&&s.push(`${i} must include semantic domainId and datasetName.`),s}function j(e){return Ki.has(e)}function ti(e){return Vi.has(e)}function z(e,i){return e===void 0?[]:h(e,i)}function h(e,i){const t=c(e);if(!t)return[`${i} must be an object.`];const s=[];return(typeof t.name!="string"||!t.name.trim())&&s.push(`${i}.name is required.`),!t.source&&typeof t.sourceKey!="string"&&s.push(`${i} must include source or sourceKey.`),t.aggregate!==void 0&&!Li.has(t.aggregate)&&s.push(`${i}.aggregate must be a supported aggregate function.`),s}function ai(e,i){const t=c(e),s=h(e,i);if(!t||typeof t.sourceKey=="string"&&t.sourceKey.trim())return s;if(t.source!==void 0){const r=F(t.source,`${i}.source`);return r.length===0||s.push(...r),s}return s.includes(`${i} must include source or sourceKey.`)||s.push(`${i} must include source or sourceKey.`),s}function c(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function v(e){return Array.isArray(e)&&e.every(i=>typeof i=="string")}const y=a.z.record(a.z.string(),a.z.unknown()),M=a.z.array(y),b=a.z.enum(["SUM","COUNT","AVG","MIN","MAX","MEDIAN","DISTINCT"]),X=a.z.enum(["postgres","mysql","mssql","snowflake","clickhouse","bigquery","redshift","duckdb","sqlite","unknown"]),si=a.z.enum(R),ni=a.z.enum(Y),J=a.z.enum(["dimension","measure","date","id","unknown"]),W=a.z.enum(["string","number","boolean","date","datetime","unknown"]),V=a.z.union([a.z.number(),a.z.string(),a.z.null()]),ne=a.z.enum(["millisecond","second","minute","hour","day"]),Dt=a.z.enum(Ge),Nt=a.z.discriminatedUnion("mode",[a.z.object({mode:a.z.literal("auto")}).strict(),a.z.object({mode:a.z.literal("preset"),preset:Dt}).strict(),a.z.object({mode:a.z.literal("pattern"),pattern:a.z.string().min(1)}).strict()]),oi=a.z.object({type:a.z.literal("temporal_bucket"),presentation:Nt}).strict(),qt=a.z.object({tz:a.z.string().min(1).refine(He,{message:"tz must be a valid IANA timezone"}),weekStart:a.z.number().int().min(0).max(6),fiscalCalendar:a.z.object({kind:a.z.literal("month_aligned"),yearStartMonth:a.z.number().int().min(1).max(12)}).strict().optional()}).strict(),le=a.z.object({kind:a.z.literal("temporal_bucket"),granularity:si,calendar:qt}).strict(),ri=a.z.union([a.z.object({type:a.z.enum(["number","currency","percent","percentage","scientific"]),locale:a.z.string().optional(),minimumFractionDigits:a.z.number().optional(),maximumFractionDigits:a.z.number().optional(),useGrouping:a.z.boolean().optional(),prefix:a.z.string().optional(),suffix:a.z.string().optional(),negativeStyle:a.z.enum(["minus","parentheses"]).optional(),compact:a.z.boolean().optional(),scale:a.z.number().optional(),currency:a.z.string().optional(),percentValueMode:a.z.enum(["fraction","whole"]).optional()}).passthrough().superRefine((e,i)=>{"locale"in e&&i.addIssue({code:a.z.ZodIssueCode.custom,path:["locale"],message:"Numeric semantic formats inherit locale from viewer preferences."})}),a.z.object({type:a.z.enum(["date","datetime"]),locale:a.z.string().optional(),pattern:a.z.string().optional(),relative:a.z.boolean().optional(),timezone:a.z.string().optional(),sourceTimezone:a.z.string().optional(),prefix:a.z.string().optional(),suffix:a.z.string().optional()}).passthrough(),a.z.object({type:a.z.literal("duration"),inputUnit:ne.optional(),outputStyle:a.z.enum(["compact","digital","long"]).optional(),largestUnit:ne.optional(),smallestUnit:ne.optional(),maxUnits:a.z.number().optional(),prefix:a.z.string().optional(),suffix:a.z.string().optional(),negativeStyle:a.z.enum(["minus","parentheses"]).optional()}).passthrough(),a.z.object({type:a.z.literal("string"),prefix:a.z.string().optional(),suffix:a.z.string().optional()}).passthrough()]),Ot=a.z.union([a.z.object({kind:a.z.literal("defaultAggregate")}).passthrough(),a.z.object({kind:a.z.literal("blank")}).passthrough(),a.z.object({kind:a.z.literal("labelOnly"),label:a.z.string().optional()}).passthrough(),a.z.object({kind:a.z.literal("customAggregate"),aggregate:b}).passthrough(),a.z.object({kind:a.z.literal("percentOfParent")}).passthrough(),a.z.object({kind:a.z.literal("percentOfGrandTotal")}).passthrough(),a.z.object({kind:a.z.literal("customExpression"),expressionId:a.z.string()}).passthrough()]);function D(e,i){return a.z.object(e).passthrough().superRefine((t,s)=>{for(const n of i)Object.prototype.hasOwnProperty.call(t,n)||s.addIssue({code:"custom",path:[n],message:`Required field "${n}" is missing.`})})}const he=a.z.object({kind:a.z.literal("semantic"),domainId:a.z.string(),datasetName:a.z.string(),datasetId:a.z.string().optional(),label:a.z.string().optional(),connectionId:a.z.string().optional()}).passthrough(),li=a.z.object({kind:a.z.literal("physical"),connectionId:a.z.string(),connectionType:a.z.string().optional(),tableName:a.z.string(),databaseName:a.z.string().optional(),schemaName:a.z.string().optional(),label:a.z.string().optional(),dialect:X.optional()}).passthrough(),di=a.z.object({kind:a.z.literal("sql"),connectionId:a.z.string(),dialect:X.optional(),label:a.z.string().optional()}).passthrough(),k=a.z.union([he,li,di]),$=a.z.object({name:a.z.string(),label:a.z.string().optional(),role:J.optional(),dataType:W.optional(),source:k.optional(),aggregate:b.optional()}).passthrough(),Pt=a.z.object({kind:a.z.literal("field"),field:$,aggregate:b.optional()}).passthrough(),ye=a.z.object({kind:a.z.literal("derived_field"),name:a.z.string(),label:a.z.string(),description:a.z.string().optional(),resultRole:J,dataType:W,computeStage:a.z.enum(["row","aggregate"]),expression:a.z.string(),expressionLanguage:a.z.literal("semaphor_sql_template").optional(),inputs:a.z.record(Pt),defaultAggregate:b.optional(),aggregationBehavior:a.z.enum(["additive","non_additive","ratio_of_sums","weighted","pre_aggregated","snapshot"]).optional(),aggregationStrategy:a.z.enum(["default","symmetric_aggregate","aggregate_then_join","weighted"]).optional(),format:ri.optional(),tags:a.z.array(a.z.string()).optional()}).passthrough(),ee=$.and(a.z.object({derivedField:ye.optional()}).passthrough()),Bt=he,Kt=a.z.object({kind:a.z.literal("physical"),connectionId:a.z.string().optional(),connectionType:a.z.string().optional(),tableName:a.z.string(),databaseName:a.z.string().optional(),schemaName:a.z.string().optional(),label:a.z.string().optional(),dialect:X.optional()}).passthrough(),Vt=a.z.object({kind:a.z.literal("sql"),connectionId:a.z.string().optional(),dialect:X.optional(),label:a.z.string().optional()}).passthrough(),Lt=a.z.union([Bt,Kt,Vt]),Gt=a.z.object({key:a.z.string().optional(),name:a.z.string(),label:a.z.string().optional(),role:J.optional(),dataType:W.optional(),source:Lt.optional(),aggregate:b.optional(),derivedField:a.z.never().optional()}).passthrough(),A=a.z.object({key:a.z.string(),name:a.z.string(),label:a.z.string(),role:J.optional(),dataType:W.optional(),aggregate:b.optional(),source:k.optional(),derivedField:ye.optional(),temporalBucket:le.optional(),pivotIdentity:a.z.object({metricId:a.z.string().min(1),metricAlias:a.z.string().min(1),members:a.z.array(a.z.object({fieldId:a.z.string().min(1),value:a.z.string().nullable(),temporalBucket:le.optional()}).strict())}).strict().optional()}).passthrough().superRefine((e,i)=>{if(e.temporalBucket){const t=Ue(e.temporalBucket.granularity);e.dataType!==t&&i.addIssue({code:a.z.ZodIssueCode.custom,path:["dataType"],message:`${e.temporalBucket.granularity} temporal buckets require dataType ${t}.`})}}),Ut=a.z.object({records:M,columns:a.z.array(A).optional()}).passthrough(),Ht=a.z.object({records:M,columns:a.z.array(A)}).passthrough(),ui=a.z.object({code:a.z.string(),message:a.z.string().optional(),invalidField:a.z.string().optional(),fieldRole:a.z.enum(["measure","date","dimension","input","source","sql"]).optional(),validMeasureCandidates:a.z.array(a.z.string()).optional(),validDateCandidates:a.z.array(a.z.string()).optional(),validDimensionCandidates:a.z.array(a.z.string()).optional(),recommendedNextStep:a.z.string()}).passthrough(),U=a.z.object({code:a.z.string(),message:a.z.string(),path:a.z.string().optional(),fieldRole:a.z.enum(["measure","date","dimension","input","source","sql"]).optional(),repairHint:ui.optional()}).passthrough(),be=a.z.object({ok:a.z.boolean(),errors:a.z.array(U),warnings:a.z.array(U),repairHints:a.z.array(ui)}).passthrough(),Qt=a.z.object({page:a.z.number(),pageSize:a.z.number(),pageCount:a.z.number(),totalCount:a.z.number(),hasNextPage:a.z.boolean(),hasPrevPage:a.z.boolean()}).passthrough(),N={intentId:a.z.string().optional(),queryPath:a.z.enum(["query_spec","sql","sql_python"]),warnings:a.z.array(a.z.string()).optional(),rowCount:a.z.number().optional(),rowLimitExceeded:a.z.boolean().optional(),limit:a.z.number().optional(),pagination:Qt.optional()},ci=a.z.object({...N,kind:a.z.literal("metric"),primaryValue:V,measures:a.z.record(V).optional(),missingMeasures:a.z.array(a.z.string()).optional(),comparison:a.z.object({kind:a.z.enum(["previous_period","previous_year","target"]),value:V.optional(),delta:a.z.union([a.z.number(),a.z.null()]).optional(),deltaPercent:a.z.union([a.z.number(),a.z.null()]).optional()}).passthrough().optional(),records:M.optional()}).passthrough(),pi=a.z.object({...N,kind:a.z.literal("records"),columns:a.z.array(A),records:M,totals:a.z.object({mode:a.z.literal("server"),scope:a.z.literal("filtered_result"),row:a.z.record(a.z.string(),a.z.unknown()),columns:a.z.array(A).optional()}).passthrough().optional()}).passthrough(),mi=a.z.object({...N,kind:a.z.literal("inputOptions"),options:a.z.array(D({label:a.z.string(),value:a.z.unknown(),count:a.z.number().optional(),disambiguation:a.z.array(a.z.string()).optional()},["value"]))}).passthrough(),fi=a.z.object({...N,kind:a.z.literal("sql"),columns:a.z.array(A),records:M,sqlShape:a.z.object({statementType:a.z.string().optional(),explicitLimit:a.z.number().optional(),hasPythonCode:a.z.boolean().optional()}).passthrough().optional()}).passthrough(),Yt=a.z.object({enabled:a.z.boolean().optional(),position:a.z.enum(["before","after"]).optional(),label:a.z.string().optional()}).passthrough(),Te=a.z.object({id:a.z.enum(["rows","columns"]),levels:a.z.array(a.z.object({instanceId:a.z.string(),fieldKey:a.z.string(),label:a.z.string(),field:$,grain:ni.optional(),subtotal:Yt.optional()}).passthrough()),nodeIds:a.z.array(a.z.string())}).passthrough(),x=D({instanceId:a.z.string(),fieldKey:a.z.string(),value:a.z.unknown(),label:a.z.string()},["value"]),Zt=a.z.union([a.z.object({kind:a.z.literal("label")}).passthrough(),a.z.object({kind:a.z.literal("field"),field:$,aggregate:b.optional()}).passthrough(),a.z.object({kind:a.z.literal("value"),valueId:a.z.string(),rowPath:a.z.array(x).optional(),columnPath:a.z.array(x).optional()}).passthrough()]),Xt=a.z.enum(["present","presentNull","missing","densified"]),Jt=a.z.enum(["value","rowSubtotal","columnSubtotal","subtotalIntersection","rowGrandTotal","columnGrandTotal","matrixGrandTotal"]),Wt=a.z.object({instanceId:a.z.string(),fieldKey:a.z.string(),field:$,role:a.z.enum(["row","column","measure","sort","filter"]),label:a.z.string().optional()}).passthrough(),ea=a.z.union([a.z.object({kind:a.z.literal("additive"),aggregate:b.optional()}).passthrough(),a.z.object({kind:a.z.literal("semiAdditive"),aggregate:b.optional(),grain:ni.optional()}).passthrough(),a.z.object({kind:a.z.literal("nonAdditive"),aggregate:b.optional()}).passthrough(),a.z.object({kind:a.z.literal("ratio"),numeratorMeasureInstanceId:a.z.string().optional(),denominatorMeasureInstanceId:a.z.string().optional()}).passthrough(),a.z.object({kind:a.z.literal("custom"),expressionId:a.z.string().optional()}).passthrough()]),ia=a.z.object({instanceId:a.z.string(),fieldKey:a.z.string(),label:a.z.string(),field:$,aggregate:b.optional(),format:ri.optional(),totalBehavior:Ot.optional(),semantics:ea}).passthrough(),ta=a.z.object({id:a.z.string(),measureId:a.z.string(),aggregate:b.optional(),label:a.z.string().optional(),source:a.z.enum(["measureDefault","rowSubtotal","columnSubtotal","subtotalIntersection","rowGrandTotal","columnGrandTotal","matrixGrandTotal","custom"]),scope:a.z.object({rowLevelId:a.z.string().optional(),columnLevelId:a.z.string().optional(),rowNodeId:a.z.string().optional(),columnNodeId:a.z.string().optional()}).passthrough().optional()}).passthrough(),aa=a.z.object({kind:a.z.string(),label:a.z.string().optional(),payload:a.z.record(a.z.string(),a.z.unknown()).optional()}).passthrough(),sa=D({id:a.z.string(),axis:a.z.enum(["row","column"]),path:a.z.array(x),level:a.z.number(),label:a.z.string(),value:a.z.unknown(),parentId:a.z.string().optional(),hasChildren:a.z.boolean(),isExpanded:a.z.boolean().optional(),isSubtotal:a.z.boolean().optional(),isGrandTotal:a.z.boolean().optional(),subtotalFunction:b.optional(),childCount:a.z.number().optional(),actions:a.z.array(aa).optional()},["value"]),na=a.z.object({rowHeaderLevels:a.z.array(a.z.object({id:a.z.string(),label:a.z.string(),fieldInstanceId:a.z.string()}).passthrough()),columnHeaderRows:a.z.array(a.z.object({id:a.z.string(),cells:a.z.array(a.z.object({id:a.z.string(),label:a.z.string(),role:a.z.enum(["rowHeader","columnHeader","measureHeader","subtotal","grandTotal"]),colSpan:a.z.number(),rowSpan:a.z.number(),columnPath:a.z.array(x),measureInstanceId:a.z.string().optional()}).passthrough())}).passthrough()),columns:a.z.array(a.z.object({id:a.z.string(),label:a.z.string(),columnNodeId:a.z.string().optional(),columnPath:a.z.array(x),measureInstanceId:a.z.string(),role:a.z.enum(["value","columnSubtotal","columnGrandTotal"])}).passthrough())}).passthrough(),oa=D({rowId:a.z.string(),columnId:a.z.string().optional(),measureId:a.z.string(),value:a.z.unknown(),presence:Xt,role:Jt,calculationId:a.z.string().optional()},["value"]).superRefine((e,i)=>{Object.prototype.hasOwnProperty.call(e,"formattedValue")&&i.addIssue({code:"custom",path:["formattedValue"],message:"Matrix result cells carry typed values; formattedValue is not supported."})}),ra=a.z.object({rows:a.z.boolean().optional(),columns:a.z.boolean().optional(),grandTotal:a.z.union([a.z.boolean(),a.z.object({rows:a.z.boolean().optional(),columns:a.z.boolean().optional()}).passthrough()]).optional()}).passthrough(),la=D({id:a.z.string(),axis:a.z.enum(["row","column"]),targetInstanceId:a.z.string().optional(),direction:a.z.enum(["asc","desc"]),nulls:a.z.enum(["warehouseDefault","first","last"]).optional(),scope:a.z.enum(["global","withinParent"]).optional(),by:Zt},["by"]),da=a.z.object({rowOffset:a.z.number().optional(),rowLimit:a.z.number().optional(),columnOffset:a.z.number().optional(),columnLimit:a.z.number().optional(),hasMoreRows:a.z.boolean().optional(),hasMoreColumns:a.z.boolean().optional()}).passthrough(),ua=a.z.object({axis:a.z.enum(["row","column"]),path:a.z.array(x),depth:a.z.number().optional()}).passthrough(),ca=a.z.object({rowLazyLoading:a.z.boolean().optional(),columnLazyLoading:a.z.boolean().optional(),expandableRowNodeIds:a.z.array(a.z.string()).optional(),expandableColumnNodeIds:a.z.array(a.z.string()).optional(),nextRequests:a.z.array(ua).optional()}).passthrough(),pa=a.z.object({domains:a.z.record(a.z.object({min:a.z.number().optional(),max:a.z.number().optional()}).passthrough()).optional(),rules:a.z.array(a.z.record(a.z.string(),a.z.unknown())).optional()}).passthrough(),gi=a.z.object({...N,kind:a.z.literal("matrix"),schemaVersion:a.z.literal(1),shape:a.z.enum(["hierarchical","pivot"]),capabilities:a.z.array(a.z.string()),executionMetadata:a.z.record(a.z.string(),a.z.unknown()),fieldsById:a.z.record(a.z.string(),Wt),measuresById:a.z.record(a.z.string(),ia),calculationsById:a.z.record(a.z.string(),ta).optional(),axes:a.z.object({rows:Te,columns:Te}).passthrough(),nodesById:a.z.record(a.z.string(),sa),layout:na,cells:a.z.array(oa),totals:ra,sort:a.z.array(la),formattingContext:pa,pageInfo:da.optional(),expansion:ca.optional()}).passthrough(),hi=a.z.union([ci,pi,mi,fi,gi]),yi=a.z.object({status:a.z.enum(["not_required","resolved","missing","ambiguous","fanout_risk","unknown"]),requiredSources:a.z.array(k).optional(),relationshipsUsed:a.z.array(a.z.string()).optional(),missingSources:a.z.array(a.z.string()).optional(),warnings:a.z.array(a.z.string()).optional(),message:a.z.string().optional(),recommendedNextStep:a.z.string().optional(),joinPlanSummary:a.z.object({baseSource:k.optional(),joinedSources:a.z.array(k).optional(),joinCount:a.z.number().optional()}).passthrough().optional(),fanoutRisk:a.z.object({status:a.z.enum(["none","warning","error","unknown"]),message:a.z.string().optional()}).passthrough().optional()}).passthrough(),Ce=a.z.enum(["ambiguous_fields","empty_result","missing_grounded_fields","missing_relationship","no_grounded_query","partial_result","presentation_incomplete","query_validation_failed","unsafe_join"]),_e=a.z.object({version:a.z.literal(1),status:a.z.enum(["answered","partial","blocked"]),summary:a.z.string(),answered:a.z.array(a.z.object({slotId:a.z.string().optional(),queryId:a.z.string().optional(),summary:a.z.string(),evidenceIds:a.z.array(a.z.string()).optional(),fieldsUsed:a.z.array(ee).optional()}).passthrough()),blocked:a.z.array(a.z.object({slotId:a.z.string().optional(),queryId:a.z.string().optional(),reasonCode:Ce,message:a.z.string(),missingFields:a.z.array(a.z.string()).optional(),availableFields:a.z.array(a.z.string()).optional(),ambiguousFields:a.z.array(a.z.string()).optional(),missingRelationships:a.z.array(a.z.string()).optional(),evidenceIds:a.z.array(a.z.string()).optional(),neededFromUser:a.z.array(a.z.string()).optional(),recommendedNextStep:a.z.string().optional()}).passthrough()),semanticModelRecommendations:a.z.array(a.z.object({reasonCode:Ce,message:a.z.string(),recommendedNextStep:a.z.string().optional()}).passthrough()).optional()}).passthrough(),ve=a.z.object({scope:a.z.literal("filtered_query"),measures:a.z.record(V)}).passthrough(),ze=a.z.object({answeredObligations:a.z.array(a.z.string()),missingObligations:a.z.array(a.z.string()),warnings:a.z.array(U).optional()}).passthrough(),bi=a.z.object({intentId:a.z.string().optional(),queryId:a.z.string().optional(),status:a.z.enum(["answered","partial","failed"]),resultShape:a.z.enum(["metric","records","inputOptions","sql","matrix","period_change","analysis"]).optional(),intent:a.z.unknown().optional(),compiledQuery:a.z.unknown().optional(),fieldsUsed:a.z.array(ee).optional(),result:hi.optional(),validation:be,coverage:ze.optional(),missingFields:a.z.array(a.z.string()).optional(),warnings:a.z.array(a.z.string()).optional(),relationshipDiagnostics:yi.optional(),diagnosticFeedback:_e.optional(),population:ve.optional(),metadata:a.z.record(a.z.string(),a.z.unknown()).optional()}).passthrough();function ma(e){switch(e){case"boolean":return a.z.boolean().optional();case"compactExecutionFieldArray":return a.z.array(Gt).optional();case"coverage":return ze.optional();case"diagnosticFeedback":return _e.optional();case"executionFieldArray":return a.z.array(ee).optional();case"executionResult":return bi.optional();case"number":return a.z.number().finite().optional();case"population":return ve.optional();case"record":return y.optional();case"recordArray":return M.optional();case"responseDetail":return a.z.enum(["compact","standard","debug"]).optional();case"string":return a.z.string().optional();case"stringArray":return a.z.array(a.z.string()).optional();case"unknown":return a.z.unknown().optional();case"unknownArray":return a.z.array(a.z.unknown()).optional();case"validationResult":return be.optional()}}const _i=Object.fromEntries(Object.entries(Qe).map(([e,i])=>[e,ma(i)])),fa=a.z.object(_i).strict(),Se=a.z.object({sourceKey:a.z.string().optional(),kind:a.z.enum(["semantic","physical","sql"]).optional(),domainId:a.z.string().optional(),datasetName:a.z.string().optional(),datasetId:a.z.string().optional(),connectionId:a.z.string().optional(),tableName:a.z.string().optional(),label:a.z.string().optional()}).passthrough(),S=a.z.object({name:a.z.string(),label:a.z.string().optional(),role:a.z.enum(["dimension","measure","date","id","unknown"]).optional(),dataType:a.z.enum(["string","number","boolean","date","datetime","unknown"]).optional(),aggregate:b.optional(),sourceKey:a.z.string().optional(),source:Se.optional()}).passthrough(),vi=a.z.object({id:a.z.string().optional(),builder:a.z.literal("semaphor.inputOptions"),source:Se.optional(),sourceKey:a.z.string().optional(),valueFieldRef:S,labelFieldRef:S,filterFieldRef:S.optional(),population:a.z.unknown().optional(),dependencies:a.z.unknown().optional(),limit:a.z.number().int().positive().optional(),spec:y.optional()}).passthrough(),zi=a.z.object({appliesToViewIds:a.z.array(a.z.string()).optional(),viewId:a.z.string().optional(),fieldRef:S,relationshipHint:a.z.unknown().optional(),relationshipsUsed:a.z.array(y).optional()}).passthrough(),ga=a.z.object({id:a.z.string(),label:a.z.string().optional(),type:a.z.string().optional(),serverSide:a.z.boolean().optional(),fieldRef:S.optional(),optionQuery:vi.optional(),bindings:a.z.array(zi).optional(),appliesToViewIds:a.z.array(a.z.string()),relationshipHint:a.z.unknown().optional(),relationshipsUsed:a.z.array(y).optional()}).passthrough(),ha=a.z.object({builder:a.z.enum(["semaphor.metric","semaphor.records","semaphor.matrix","semaphor.analysis","semaphor.sql"]),spec:y,fallbackReason:y.optional()}).passthrough(),ya=a.z.object({id:a.z.string(),title:a.z.string().optional(),purpose:a.z.string().optional(),sourcePresentation:a.z.object({sourceKeys:a.z.array(a.z.string()).optional(),sourceLabels:a.z.array(a.z.string()).optional()}).passthrough().optional(),visual:a.z.string().optional(),visualSpec:y.optional(),queryKind:a.z.enum(["metric","records","matrix","analysis","sql_fallback"]).optional(),sdkBuilder:a.z.enum(["semaphor.metric","semaphor.records","semaphor.matrix","semaphor.analysis","semaphor.sql"]).optional(),sdkSpec:ha.optional(),fields:a.z.array(S).optional(),computation:y.optional(),uxExpectations:a.z.array(a.z.string()).optional(),validation:y.optional()}).passthrough(),ba=a.z.object({inputId:a.z.string(),label:a.z.string().optional(),type:a.z.string().optional(),serverSide:a.z.boolean().optional(),fieldRef:S.optional(),optionQuery:vi.optional(),bindings:a.z.array(zi),appliesToViewIds:a.z.array(a.z.string()),notAppliedToViewIds:a.z.array(a.z.string())}).passthrough(),_a=a.z.object({schemaVersion:a.z.literal(G),title:a.z.string(),purpose:a.z.string().optional(),userGoal:a.z.string().optional(),nextStep:a.z.string().optional(),sources:a.z.array(Se),inputs:a.z.array(ga),views:a.z.array(ya),filterContracts:a.z.array(ba),implementationChecklist:a.z.object({schemaVersion:a.z.string().optional(),requiredDevtools:a.z.object({mountRootDevtools:a.z.boolean(),providerDebugBridge:a.z.string().optional(),panelPosition:a.z.string().optional(),forbidden:a.z.array(a.z.string()).optional()}).passthrough(),requiredInputOptions:a.z.array(y),filterScopeByInput:a.z.array(y),bindingsByView:a.z.record(a.z.string(),a.z.array(y)),validationCommands:a.z.array(a.z.string()),browserSmokeChecks:a.z.array(a.z.string())}).passthrough(),nextRequiredTool:a.z.object({name:a.z.string(),reason:a.z.string().optional()}).optional(),unsupportedInsights:a.z.array(a.z.object({title:a.z.string(),requestedQuestion:a.z.string(),reason:a.z.string(),suggestedModelingFix:a.z.string()}).passthrough()).optional(),assumptions:a.z.array(a.z.string()).optional(),validation:y.optional()}).passthrough().superRefine((e,i)=>{const t=fe(e);for(const s of t.issues)i.addIssue({code:a.z.ZodIssueCode.custom,message:s})});function o(e,i,t){return t?{code:e,message:i,path:t}:{code:e,message:i}}function va(e){for(let i=0;i<e.length;i+=1){const t=e[i];if(e.some((s,n)=>n!==i&&$i(s,t)))return!1}return!0}function Si(e,i){return Ye(e,i)}function $i(e,i){return Si(e,i)&&C(e)===C(i)}function za(e){return`Metric intent has duplicate measure "${e.name}" with the same aggregate (${C(e)}). Use different aggregates to request both, or remove one entry.`}function Fe(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null}function Sa(e,i,t){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e)){t.push(o("invalid_sql_default_parameters","SQL defaultParameters must be an object keyed by parameter name.",i));return}Object.entries(e).forEach(([s,n])=>{if(!s.trim()){t.push(o("invalid_sql_default_parameter_name","SQL defaultParameters names must be non-empty strings.",`${i}.${s}`));return}(Array.isArray(n)?n.every(Fe):Fe(n))||t.push(o("invalid_sql_default_parameter_value","SQL defaultParameters values must be strings, numbers, booleans, nulls, or arrays of those scalar values.",`${i}.${s}`))})}}function $a(e,i){return $e(e,i).length===1}function wa(e,i){return $e(e,i).length===1}function $e(e,i){return i.filter(s=>Ia(e,s))}function Ia(e,i){return ka(e,i)?e.source?Si(i,e):!0:!1}function ka(e,i){return!(i.name!==e.name||e.role!==void 0&&i.role!==void 0&&i.role!==e.role||Aa(e,i)&&C(i)!==C(e))}function Aa(e,i){return e.role==="measure"||i.role==="measure"||e.aggregate!==void 0||i.aggregate!==void 0}function C(e){return Z(e)}const xa=/^(\d{4})-(\d{2})-(\d{2})$/,wi=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|[+-]\d{2}:\d{2})$/;function H(e){if(typeof e!="string")return null;const i=e.trim(),t=xa.exec(i);if(t){const[,O,Ae,xe]=t;return De(O,Ae,xe)?new Date(Date.UTC(Number(O),Number(Ae)-1,Number(xe))):null}const s=wi.exec(i);if(!s)return null;const[,n,r,l,d,u,f="00",,_]=s;if(!De(n,r,l)||!T(d,0,23)||!T(u,0,59)||!T(f,0,59)||!Ma(_))return null;const q=new Date(i);return Number.isFinite(q.getTime())?q:null}function Ra(e){return typeof e!="string"||!wi.test(e.trim())?null:H(e)}function De(e,i,t){const s=Number(e),n=Number(i),r=Number(t);if(!Number.isInteger(s)||!Number.isInteger(n)||!Number.isInteger(r)||n<1||n>12)return!1;const l=new Date(Date.UTC(s,n-1,r));return l.getUTCFullYear()===s&&l.getUTCMonth()===n-1&&l.getUTCDate()===r}function T(e,i,t){const s=Number(e);return Number.isInteger(s)&&s>=i&&s<=t}function Ma(e){if(e==="Z")return!0;const i=/^([+-])(\d{2}):(\d{2})$/.exec(e);return!!(i&&T(i[2],0,23)&&T(i[3],0,59))}function m(e){return typeof e=="string"&&e.trim().length>0}function Ea(e){const i=new Set;let t=0;for(;t<e.length;){const s=e[t];if(s==="'"||s==='"'){t=ja(e,t);continue}if(s==="{"){const n=e.indexOf("}",t+1);if(n===-1){t+=1;continue}const r=e.slice(t+1,n);/^[A-Za-z_][A-Za-z0-9_]*$/.test(r)&&i.add(r),t=n+1;continue}t+=1}return Array.from(i)}function ja(e,i){const t=e[i];let s=i+1;for(;s<e.length;){if(e[s]===t){if(e[s+1]===t){s+=2;continue}return s+1}s+=1}return e.length}function p(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Ne(e,i,t){if(e!==void 0){if(!p(e)){t.push(o("invalid_pagination","Pagination must be an object with positive integer page and pageSize.",i));return}(!Number.isInteger(e.page)||typeof e.page!="number"||e.page<1)&&t.push(o("invalid_pagination_page","Pagination page must be a positive integer.",`${i}.page`)),(!Number.isInteger(e.pageSize)||typeof e.pageSize!="number"||e.pageSize<1)&&t.push(o("invalid_pagination_page_size","Pagination pageSize must be a positive integer.",`${i}.pageSize`))}}function de(e){const i=new Set;for(const t of e){if(i.has(t))return t;i.add(t)}return null}function oe(e,i,t,s){de(e.filter(r=>m(r)))&&s.push(o("duplicate_matrix_public_id",`Matrix ${t} ids must be unique so sort and expansion references are unambiguous.`,i))}const Ta=new Set(["SUM","COUNT","AVG","MIN","MAX","MEDIAN","DISTINCT"]);function we(e,i,t){if(!e||typeof e!="object"){t.push(o("missing_source","Analytics intent needs a source.",i));return}if(e.kind==="semantic"){m(e.domainId)||t.push(o("missing_semantic_domain","Semantic source needs a domainId.",`${i}.domainId`)),m(e.datasetName)||t.push(o("missing_dataset_name","Semantic source needs a datasetName.",`${i}.datasetName`));return}if(e.kind==="physical"){m(e.connectionId)||t.push(o("missing_connection_id","Physical source needs a connectionId.",`${i}.connectionId`)),m(e.tableName)||t.push(o("missing_table_name","Physical source needs a tableName.",`${i}.tableName`));return}if(e.kind==="sql"){m(e.connectionId)||t.push(o("missing_connection_id","SQL source needs a connectionId.",`${i}.connectionId`));return}t.push(o("invalid_source_kind","Source kind is not supported.",i))}function g(e,i,t,s={}){if(!e||!p(e)){s.required&&t.push(o("missing_field_ref","Field reference needs a name.",i));return}m(e.name)||t.push(o("missing_field_ref","Field reference needs a name.",`${i}.name`)),e.source!==void 0&&we(e.source,`${i}.source`,t),w(e.aggregate,`${i}.aggregate`,t)}function Ca(e,i,t){if(!p(e)){t.push(o("invalid_input_binding","Input bindings must be structured objects.",i));return}m(e.inputId)||t.push(o("invalid_input_binding","Input bindings need a non-empty inputId.",`${i}.inputId`)),e.kind!==void 0&&e.kind!=="filter"&&e.kind!=="control"&&t.push(o("invalid_input_binding","Input binding kind must be filter or control.",`${i}.kind`)),e.field!==void 0&&g(e.field,`${i}.field`,t),e.relationshipHint!==void 0&&Ie(e.relationshipHint,`${i}.relationshipHint`,t)}function Ie(e,i,t){if(!p(e)){t.push(o("invalid_relationship_hint","Relationship hints must be structured objects.",i));return}e.relationshipIds!==void 0&&(!Array.isArray(e.relationshipIds)||e.relationshipIds.some(s=>!m(s)))&&t.push(o("invalid_relationship_hint","Relationship hint relationshipIds must be non-empty strings.",`${i}.relationshipIds`))}function Fa(e,i){if(m(e.inputId)||i.push(o("missing_input_options_input_id","Input options intent needs the inputId it populates.","inputId")),(!e.labelField||!m(e.labelField.name))&&i.push(o("missing_input_options_label_field","Input options intent needs a labelField.","labelField")),g(e.labelField,"labelField",i,{required:!0}),(!e.valueField||!m(e.valueField.name))&&i.push(o("missing_input_options_value_field","Input options intent needs a valueField.","valueField")),g(e.valueField,"valueField",i,{required:!0}),e.searchField!==void 0&&g(e.searchField,"searchField",i,{required:!0}),e.disambiguationFields!==void 0&&(Array.isArray(e.disambiguationFields)?e.disambiguationFields.forEach((t,s)=>{g(t,`disambiguationFields.${s}`,i,{required:!0})}):i.push(o("invalid_input_options_disambiguation_fields","Input options disambiguationFields must be an array of field refs.","disambiguationFields"))),e.dependencies!==void 0){const t=e.dependencies;if(!p(t))i.push(o("invalid_input_options_dependencies","Input options dependencies must be a structured object.","dependencies"));else{const s=t.mode;s!==void 0&&s!=="independent"&&s!=="explicit"&&i.push(o("invalid_input_options_dependencies","Input options dependencies mode must be independent or explicit.","dependencies.mode")),qe(t.includeInputIds,"dependencies.includeInputIds",i,"Input options includeInputIds must be non-empty strings."),qe(t.excludeInputIds,"dependencies.excludeInputIds",i,"Input options excludeInputIds must be non-empty strings."),Na(e,i)}}if(e.population!==void 0){const t=e.population;if(!p(t))i.push(o("invalid_input_options_population","Input options population must be a structured object.","population"));else{const s=t.kind;s!=="option_source"&&s!=="related_population"&&i.push(o("invalid_input_options_population","Input options population kind must be option_source or related_population.","population.kind")),s==="option_source"&&t.baseSource!==void 0&&i.push(o("invalid_input_options_population","Input options population baseSource is only valid for related_population.","population.baseSource")),s==="option_source"&&t.relationshipHint!==void 0&&i.push(o("invalid_input_options_population","Input options population relationshipHint is only valid for related_population.","population.relationshipHint")),s==="related_population"&&(we(t.baseSource,"population.baseSource",i),t.relationshipHint!==void 0&&Ie(t.relationshipHint,"population.relationshipHint",i))}}}function Da(e,i){if(!(!("inputs"in e)||e.inputs===void 0)){if(!Array.isArray(e.inputs)){i.push(o("invalid_input_binding","Analytics intent inputs must be an array of input bindings.","inputs"));return}e.inputs.forEach((t,s)=>Ca(t,`inputs.${s}`,i))}}function Na(e,i){var s,n;const t=new Set(Array.isArray(e.inputs)?e.inputs.map(r=>p(r)?r.inputId:void 0).filter(r=>typeof r=="string"):[]);for(const r of((s=e.dependencies)==null?void 0:s.includeInputIds)||[])t.has(r)||i.push(o("invalid_input_options_dependencies",`Input options dependency "${r}" is not declared in inputs.`,"dependencies.includeInputIds"));for(const r of((n=e.dependencies)==null?void 0:n.excludeInputIds)||[])r!==e.inputId&&!t.has(r)&&i.push(o("invalid_input_options_dependencies",`Input options dependency exclusion "${r}" is not the populated inputId and is not declared in inputs.`,"dependencies.excludeInputIds"))}function qe(e,i,t,s){e!==void 0&&(!Array.isArray(e)||e.some(n=>!m(n)))&&t.push(o("invalid_input_options_dependencies",s,i))}function w(e,i,t){e!==void 0&&(typeof e!="string"||!Ta.has(e))&&t.push(o("invalid_aggregate","Field aggregate must be SUM, COUNT, AVG, MIN, MAX, MEDIAN, or DISTINCT.",i))}const qa=new Set(["measure","dimension","date","id","unknown"]),Oa=new Set(["row","aggregate"]),Ii=new Set(["string","number","boolean","date","datetime","unknown"]),Pa=new Set(["number","currency","percent","percentage","scientific","date","datetime","duration","string","temporal_bucket"]),Ba=new Set(R),Ka=new Set(["millisecond","second","minute","hour","day"]),Va=new Set(["compact","digital","long"]);function ki(e,i,t){if(e===void 0)return;if(!p(e)){t.push(o("invalid_value_format","Value format must be a structured object.",i));return}const s=e;(typeof s.type!="string"||!Pa.has(s.type))&&t.push(o("invalid_value_format_type","Value format type must be number, currency, percent, percentage, scientific, date, datetime, duration, string, or temporal_bucket.",`${i}.type`)),s.type==="temporal_bucket"&&!oi.safeParse(e).success&&t.push(o("invalid_temporal_bucket_format","Temporal bucket format must contain a valid auto, preset, or pattern presentation.",i)),(s.type==="number"||s.type==="currency"||s.type==="percent"||s.type==="percentage"||s.type==="scientific")&&Object.prototype.hasOwnProperty.call(e,"locale")&&t.push(o("invalid_value_format","Numeric value formats cannot define viewer locale.",`${i}.locale`)),K(e.minimumFractionDigits,`${i}.minimumFractionDigits`,t),K(e.maximumFractionDigits,`${i}.maximumFractionDigits`,t),K(e.scale,`${i}.scale`,t),K(e.maxUnits,`${i}.maxUnits`,t),e.useGrouping!==void 0&&typeof e.useGrouping!="boolean"&&t.push(o("invalid_value_format_use_grouping","Value format useGrouping must be boolean.",`${i}.useGrouping`)),e.negativeStyle!==void 0&&e.negativeStyle!=="minus"&&e.negativeStyle!=="parentheses"&&t.push(o("invalid_value_format_negative_style","Value format negativeStyle must be minus or parentheses.",`${i}.negativeStyle`)),e.percentValueMode!==void 0&&e.percentValueMode!=="fraction"&&e.percentValueMode!=="whole"&&t.push(o("invalid_value_format_percent_mode","Value format percentValueMode must be fraction or whole.",`${i}.percentValueMode`));for(const n of["inputUnit","largestUnit","smallestUnit"]){const r=e[n];r!==void 0&&(typeof r!="string"||!Ka.has(r))&&t.push(o("invalid_value_format_duration_unit","Duration format units must be millisecond, second, minute, hour, or day.",`${i}.${n}`))}e.outputStyle!==void 0&&(typeof e.outputStyle!="string"||!Va.has(e.outputStyle))&&t.push(o("invalid_value_format_duration_style","Duration format outputStyle must be compact, digital, or long.",`${i}.outputStyle`))}function Ai(e,i,t){if(p(e)&&e.type==="temporal_bucket"){t.push(o("invalid_scalar_value_format","Scalar and measure slots cannot own temporal bucket presentation; declare it with grain on a grouped field or axis.",i));return}ki(e,i,t)}function K(e,i,t){e!==void 0&&(typeof e!="number"||!Number.isFinite(e))&&t.push(o("invalid_value_format_number","Value format numeric options must be finite numbers.",i))}const La=new Set(["additive","non_additive","ratio_of_sums","weighted","pre_aggregated","snapshot"]),Ga=new Set(["default","symmetric_aggregate","aggregate_then_join","weighted"]);function Ua(e,i,t){if(!e||!p(e)){t.push(o("invalid_derived_field_input","Derived field inputs must be structured input references.",i));return}if(e.kind==="field"){g(e.field,`${i}.field`,t,{required:!0}),w(e.aggregate,`${i}.aggregate`,t);return}t.push(o("invalid_derived_field_input","Derived field input kind must be field.",`${i}.kind`))}function Oe(e,i,t){if(!p(e)){t.push(o("invalid_result_column_ref","Result calculation references must use columnKey or field.",i));return}const s=m(e.columnKey),n=p(e.field);if(s===n){t.push(o("invalid_result_column_ref","Result calculation references must identify exactly one of columnKey or field.",i));return}n&&g(e.field,`${i}.field`,t,{required:!0})}function Ha(e,i,t){if(!p(e)){t.push(o("invalid_result_calculation_output","Result calculation output must be a structured object.",i));return}m(e.key)||t.push(o("invalid_result_calculation_output","Result calculation output needs a stable key.",`${i}.key`)),e.dataType!==void 0&&(typeof e.dataType!="string"||!Ii.has(e.dataType))&&t.push(o("invalid_result_calculation_output","Result calculation output dataType must be string, number, boolean, date, datetime, or unknown.",`${i}.dataType`)),Ai(e.format,`${i}.format`,t)}function Qa(e,i,t){e!==void 0&&(Le(e)||t.push(o("invalid_time_grain",`Matrix time grain must be one of: ${Y.join(", ")}.`,i)))}function xi(e,i,t,s){e!=="asc"&&e!=="desc"&&t.push(o(s,"Sort direction must be asc or desc.",i))}function Ri(e,i,t,s){e!==void 0&&e!=="warehouseDefault"&&e!=="first"&&e!=="last"&&t.push(o(s,"Null ordering must be warehouseDefault, first, or last.",i))}function Mi(e,i,t,s){e!==void 0&&e!=="global"&&e!=="withinParent"&&t.push(o(s,"Sort scope must be global or withinParent.",i))}function Ya(e,i,t){e.enabled!==void 0&&typeof e.enabled!="boolean"&&t.push(o("invalid_matrix_subtotal","Matrix subtotal enabled must be a boolean.",`${i}.enabled`)),e.position!==void 0&&e.position!=="before"&&e.position!=="after"&&t.push(o("invalid_matrix_subtotal","Matrix subtotal position must be before or after.",`${i}.position`)),e.label!==void 0&&typeof e.label!="string"&&t.push(o("invalid_matrix_subtotal","Matrix subtotal label must be a string.",`${i}.label`))}function Za(e,i,t){if(xi(e.direction,`${i}.direction`,t,"invalid_matrix_sort_direction"),Ri(e.nulls,`${i}.nulls`,t,"invalid_matrix_sort_nulls"),Mi(e.scope,`${i}.scope`,t,"invalid_matrix_sort_scope"),!p(e.by)){t.push(o("invalid_matrix_sort_by","Matrix sort by must be a structured object.",`${i}.by`));return}if(e.by.kind!=="label"){if(e.by.kind==="field"){g(e.by.field,`${i}.by.field`,t,{required:!0}),w(e.by.aggregate,`${i}.by.aggregate`,t);return}t.push(o("invalid_matrix_sort_by","Matrix axis sort by must be label or field.",`${i}.by.kind`))}}function Pe(e,i,t,s){if(!Array.isArray(e))return s.required?t.push(o("missing_matrix_rows","Matrix intent needs at least one row axis level.",i)):e!==void 0&&t.push(o("invalid_matrix_columns","Matrix columns must be an array of axis levels.",i)),[];s.required&&e.length===0&&t.push(o("missing_matrix_rows","Matrix intent needs at least one row axis level.",i));const n=[];return e.forEach((r,l)=>{const d=`${i}.${l}`;if(!p(r)){t.push(o("invalid_matrix_axis_level","Matrix axis levels must be structured objects.",d));return}const u=r;n.push(u),u.id!==void 0&&!m(u.id)&&t.push(o("invalid_matrix_axis_level_id","Matrix axis level id must be a non-empty string.",`${d}.id`)),g(u.field,`${d}.field`,t,{required:!0}),Qa(u.grain,`${d}.grain`,t),u.label!==void 0&&typeof u.label!="string"&&t.push(o("invalid_matrix_axis_label","Matrix axis level label must be a string.",`${d}.label`)),u.subtotal!==void 0&&typeof u.subtotal!="boolean"&&(p(u.subtotal)?Ya(u.subtotal,`${d}.subtotal`,t):t.push(o("invalid_matrix_subtotal","Matrix subtotal must be a boolean or structured options object.",`${d}.subtotal`))),u.sortBy!==void 0&&(p(u.sortBy)?Za(u.sortBy,`${d}.sortBy`,t):t.push(o("invalid_matrix_sort_by","Matrix axis sortBy must be a structured object.",`${d}.sortBy`)))}),n}function Xa(e,i,t){if(!p(e)){t.push(o("invalid_matrix_total_behavior","Matrix total behavior must be a structured object.",i));return}if(e.kind!=="defaultAggregate"&&e.kind!=="blank"&&e.kind!=="labelOnly"&&e.kind!=="customAggregate"&&e.kind!=="percentOfParent"&&e.kind!=="percentOfGrandTotal"&&e.kind!=="customExpression"){t.push(o("invalid_matrix_total_behavior","Matrix total behavior kind is not supported.",`${i}.kind`));return}e.kind==="customAggregate"&&(Object.prototype.hasOwnProperty.call(e,"aggregate")?w(e.aggregate,`${i}.aggregate`,t):t.push(o("invalid_matrix_total_behavior","Custom matrix total behavior needs an aggregate.",`${i}.aggregate`))),e.kind==="customExpression"&&!m(e.expressionId)&&t.push(o("invalid_matrix_total_behavior","Custom matrix total behavior needs an expressionId.",`${i}.expressionId`)),e.kind==="labelOnly"&&e.label!==void 0&&typeof e.label!="string"&&t.push(o("invalid_matrix_total_behavior","Matrix label-only total behavior label must be a string.",`${i}.label`))}function Ja(e,i,t){if(!Array.isArray(e)||e.length===0)return t.push(o("missing_matrix_values","Matrix intent needs at least one value field.",i)),[];const s=[];return e.forEach((n,r)=>{const l=`${i}.${r}`;if(!p(n)){t.push(o("invalid_matrix_value","Matrix values must be structured objects.",l));return}const d=n;s.push(d),d.id!==void 0&&!m(d.id)&&t.push(o("invalid_matrix_value_id","Matrix value id must be a non-empty string.",`${l}.id`)),g(d.field,`${l}.field`,t,{required:!0}),w(d.aggregate,`${l}.aggregate`,t),Ai(d.format,`${l}.format`,t),d.label!==void 0&&typeof d.label!="string"&&t.push(o("invalid_matrix_value_label","Matrix value label must be a string.",`${l}.label`)),d.totalBehavior!==void 0&&Xa(d.totalBehavior,`${l}.totalBehavior`,t)}),s}function Wa(e,i,t){if(!p(e)){t.push(o("invalid_matrix_totals","Matrix totals must be a structured object.",i));return}for(const s of["rows","columns"]){const n=e[s];n!==void 0&&n!==!0&&n!==!1&&n!=="perLevel"&&t.push(o("invalid_matrix_totals","Matrix total axis setting must be a boolean or perLevel.",`${i}.${s}`))}if(e.grandTotal!==void 0&&typeof e.grandTotal!="boolean")if(!p(e.grandTotal))t.push(o("invalid_matrix_totals","Matrix grandTotal must be a boolean or structured object.",`${i}.grandTotal`));else for(const s of["rows","columns"]){const n=e.grandTotal[s];n!==void 0&&typeof n!="boolean"&&t.push(o("invalid_matrix_totals","Matrix grandTotal rows/columns must be booleans.",`${i}.grandTotal.${s}`))}e.rowPosition!==void 0&&e.rowPosition!=="top"&&e.rowPosition!=="bottom"&&t.push(o("invalid_matrix_totals","Matrix row total position must be top or bottom.",`${i}.rowPosition`)),e.columnPosition!==void 0&&e.columnPosition!=="left"&&e.columnPosition!=="right"&&t.push(o("invalid_matrix_totals","Matrix column total position must be left or right.",`${i}.columnPosition`))}function ue(e,i,t,s){if(!Array.isArray(e)){s.push(o("invalid_matrix_path","Matrix member path must be an array of path segments.",i));return}e.forEach((n,r)=>{const l=`${i}.${r}`;if(!p(n)){s.push(o("invalid_matrix_path","Matrix path segment must be a structured object.",l));return}const d=n;if(!m(d.levelId)){s.push(o("stable_id_required","Matrix path segments must reference an explicit public axis level id.",`${l}.levelId`));return}Object.prototype.hasOwnProperty.call(n,"value")||s.push(o("invalid_matrix_path","Matrix path segments must include a value property; use explicit null for null members.",`${l}.value`)),t.has(d.levelId)||s.push(o("stable_id_required","Matrix path segment levelId must match an explicit public axis level id.",`${l}.levelId`))})}function Be(e,i,t,s){if(!p(e)){s.push(o("invalid_matrix_expansion","Matrix expansion axis options must be structured objects.",i));return}e.defaultDepth!==void 0&&(typeof e.defaultDepth!="number"||!Number.isInteger(e.defaultDepth)||e.defaultDepth<0)&&s.push(o("invalid_matrix_expansion","Matrix expansion defaultDepth must be a non-negative integer.",`${i}.defaultDepth`)),e.lazy!==void 0&&typeof e.lazy!="boolean"&&s.push(o("invalid_matrix_expansion","Matrix expansion lazy must be a boolean.",`${i}.lazy`)),e.expandedPaths!==void 0&&(Array.isArray(e.expandedPaths)?e.expandedPaths.forEach((n,r)=>{ue(n,`${i}.expandedPaths.${r}`,t,s)}):s.push(o("invalid_matrix_expansion","Matrix expandedPaths must be an array of member paths.",`${i}.expandedPaths`)))}function es(e,i,t,s){if(e!==void 0){if(!p(e)){s.push(o("invalid_matrix_expansion","Matrix expansion must be a structured object.","expansion"));return}e.rows!==void 0&&Be(e.rows,"expansion.rows",i,s),e.columns!==void 0&&Be(e.columns,"expansion.columns",t,s)}}function is(e,i,t,s,n){if(e!==void 0){if(!Array.isArray(e)){n.push(o("invalid_matrix_sort","Matrix sort must be an array of sort rules.","sort"));return}e.forEach((r,l)=>{const d=`sort.${l}`;if(!p(r)){n.push(o("invalid_matrix_sort","Matrix sort rule must be a structured object.",d));return}const u=r;u.axis!=="row"&&u.axis!=="column"&&n.push(o("invalid_matrix_sort","Matrix sort axis must be row or column.",`${d}.axis`));const f=u.axis==="column"?t:i;if(u.targetId!==void 0&&!f.has(u.targetId)&&n.push(o("stable_id_required","Matrix sort targetId must reference an explicit public axis level id.",`${d}.targetId`)),xi(u.direction,`${d}.direction`,n,"invalid_matrix_sort_direction"),Ri(u.nulls,`${d}.nulls`,n,"invalid_matrix_sort_nulls"),Mi(u.scope,`${d}.scope`,n,"invalid_matrix_sort_scope"),!p(u.by)){n.push(o("invalid_matrix_sort_by","Matrix sort by must be a structured object.",`${d}.by`));return}if(u.by.kind!=="label"){if(u.by.kind==="field"){g(u.by.field,`${d}.by.field`,n,{required:!0}),w(u.by.aggregate,`${d}.by.aggregate`,n);return}if(u.by.kind==="value"){(!m(u.by.valueId)||!s.has(u.by.valueId))&&n.push(o("stable_id_required","Matrix value sort must reference an explicit public value id.",`${d}.by.valueId`)),u.by.rowPath!==void 0&&ue(u.by.rowPath,`${d}.by.rowPath`,i,n),u.by.columnPath!==void 0&&ue(u.by.columnPath,`${d}.by.columnPath`,t,n);return}n.push(o("invalid_matrix_sort_by","Matrix sort by must be label, field, or value.",`${d}.by.kind`))}})}}function ts(e,i){if(e!==void 0){if(!p(e)){i.push(o("invalid_matrix_layout","Matrix layout must be a structured object.","layout"));return}e.hierarchy!==void 0&&e.hierarchy!=="compact"&&e.hierarchy!=="tabular"&&e.hierarchy!=="outline"&&i.push(o("invalid_matrix_layout","Matrix hierarchy layout must be compact, tabular, or outline.","layout.hierarchy")),e.valuesPlacement!==void 0&&e.valuesPlacement!=="columns"&&e.valuesPlacement!=="rows"&&i.push(o("invalid_matrix_layout","Matrix valuesPlacement must be columns or rows.","layout.valuesPlacement")),e.stickyRowHeaders!==void 0&&typeof e.stickyRowHeaders!="boolean"&&i.push(o("invalid_matrix_layout","Matrix stickyRowHeaders must be a boolean.","layout.stickyRowHeaders")),e.stickyColumnHeaders!==void 0&&typeof e.stickyColumnHeaders!="boolean"&&i.push(o("invalid_matrix_layout","Matrix stickyColumnHeaders must be a boolean.","layout.stickyColumnHeaders"))}}function Ke(e,i,t){if(!p(e)){t.push(o("invalid_matrix_display_limits","Matrix display limit must be a structured object.",i));return}(typeof e.limit!="number"||!Number.isInteger(e.limit)||e.limit<1)&&t.push(o("invalid_matrix_display_limits","Matrix display limit must be a positive integer.",`${i}.limit`));for(const s of Object.keys(e))s!=="limit"&&t.push(o("invalid_matrix_display_limits",`Matrix display limit ${s} is not supported in v1; use count-only { limit } display limits.`,`${i}.${s}`))}function as(e,i){if(e!==void 0){if(!p(e)){i.push(o("invalid_matrix_display_limits","Matrix displayLimits must be a structured object.","displayLimits"));return}e.rows!==void 0&&Ke(e.rows,"displayLimits.rows",i),e.columns!==void 0&&Ke(e.columns,"displayLimits.columns",i);for(const t of Object.keys(e))t==="rows"||t==="columns"||i.push(o("invalid_matrix_display_limits",`Matrix displayLimits ${t} is not supported in v1; use rows and columns count limits only.`,`displayLimits.${t}`))}}function ss(e,i){var u;((u=e.source)==null?void 0:u.kind)==="sql"&&i.push(o("unsupported_matrix_sql_source","Matrix analytics intent does not support raw SQL sources.","source.kind"));const t=Pe(e.rows,"rows",i,{required:!0}),s=Pe(e.columns,"columns",i,{required:!1}),n=Ja(e.values,"values",i);Q(e.filters,"filters",i),e.totals!==void 0&&Wa(e.totals,"totals",i),oe(t.map(f=>f.id),"rows","row axis level",i),oe(s.map(f=>f.id),"columns","column axis level",i),oe(n.map(f=>f.id),"values","value",i);const r=new Set(t.map(f=>f.id).filter(f=>m(f))),l=new Set(s.map(f=>f.id).filter(f=>m(f))),d=new Set(n.map(f=>f.id).filter(f=>m(f)));is(e.sort,r,l,d,i),es(e.expansion,r,l,i),ts(e.layout,i),as(e.displayLimits,i)}function ns(e,i){if(e.analysis===void 0)return;if(!p(e.analysis)){i.push(o("invalid_measure_analysis","Metric analysis must be a structured object.","analysis"));return}if(e.analysis.kind!=="period_change"){i.push(o("invalid_measure_analysis","Metric analysis kind is not supported.","analysis.kind"));return}e.dateField||i.push(o("missing_analysis_date_field","Period-change analysis needs a dateField.","dateField")),e.timeGrain||i.push(o("missing_analysis_time_grain","Period-change analysis needs a timeGrain.","timeGrain")),e.analysis.orderBy!==void 0&&e.analysis.orderBy!=="absolute_change"&&e.analysis.orderBy!=="positive_change"&&e.analysis.orderBy!=="negative_change"&&e.analysis.orderBy!=="period"&&i.push(o("invalid_measure_analysis","Period-change analysis orderBy must be absolute_change, positive_change, negative_change, or period.","analysis.orderBy"));const{timeWindow:t}=e.analysis;t!==void 0&&ce(t,"analysis.timeWindow",i)}function ce(e,i,t){if(!p(e)){t.push(o("invalid_time_window","Time window must be a structured object.",i));return}if(e.kind!==void 0&&e.kind!=="relative"&&e.kind!=="absolute"&&t.push(o("invalid_time_window","Time window kind must be relative or absolute.",`${i}.kind`)),e.kind==="absolute"){if(m(e.start)||t.push(o("invalid_time_window","Absolute time window start must be a non-empty ISO date or timestamp string.",`${i}.start`)),m(e.end)||t.push(o("invalid_time_window","Absolute time window end must be a non-empty ISO date or timestamp string.",`${i}.end`)),m(e.start)&&m(e.end)){const s=H(e.start),n=H(e.end);s||t.push(o("invalid_time_window","Absolute time window start must be a valid ISO date or timestamp.",`${i}.start`)),n||t.push(o("invalid_time_window","Absolute time window end must be a valid ISO date or timestamp.",`${i}.end`)),s&&n&&s.getTime()>n.getTime()&&t.push(o("invalid_time_window","Absolute time window start must be before or equal to end.",i))}return}(typeof e.unit!="string"||!Ba.has(e.unit))&&t.push(o("invalid_time_window",`Time window unit must be one of: ${R.join(", ")}.`,`${i}.unit`)),(typeof e.value!="number"||!Number.isFinite(e.value)||e.value<=0)&&t.push(o("invalid_time_window","Time window value must be a positive number.",`${i}.value`)),e.anchor!==void 0&&e.anchor!=="now"&&e.anchor!=="latest_available"&&t.push(o("invalid_time_window","Time window anchor must be now or latest_available.",`${i}.anchor`)),e.completeness!==void 0&&e.completeness!=="include_partial"&&e.completeness!=="complete_periods"&&t.push(o("invalid_time_window","Time window completeness must be include_partial or complete_periods.",`${i}.completeness`))}function Q(e,i,t){if(e!==void 0){if(!Array.isArray(e)){t.push(o("invalid_analytics_filters","Analytics filters must be an array.",i));return}e.forEach((s,n)=>{var u;const r=`${i}.${n}`;if(!p(s)){t.push(o("invalid_analytics_filter","Analytics filter must be a structured object.",r));return}const l=s;g(l.field,`${r}.field`,t,{required:!0}),l.scope!==void 0&&l.scope!=="row"&&l.scope!=="aggregate"&&t.push(o("invalid_analytics_filter_scope","Analytics filter scope must be row or aggregate.",`${r}.scope`)),l.scope==="aggregate"&&((u=l.field)==null?void 0:u.role)!==void 0&&l.field.role!=="measure"&&t.push(o("invalid_analytics_filter_scope","Aggregate-scope analytics filters must target a measure field.",`${r}.scope`));const d=l.operator==="is_null"||l.operator==="is_not_null";if(l.operator!==void 0&&l.operator!=="="&&l.operator!=="!="&&l.operator!=="in"&&l.operator!=="not_in"&&l.operator!=="contains"&&l.operator!=="not_contains"&&l.operator!=="between"&&l.operator!=="not_between"&&l.operator!==">"&&l.operator!==">="&&l.operator!=="<"&&l.operator!=="<="&&l.operator!=="is_null"&&l.operator!=="is_not_null"&&t.push(o("invalid_analytics_filter_operator","Analytics filter operator is not supported.",`${r}.operator`)),l.values===void 0&&!d&&t.push(o("missing_analytics_filter_value","Analytics filter needs values unless it is a null check.",r)),d&&l.values!==void 0){t.push(o("invalid_analytics_filter_values","Null-check analytics filters must not include values.",`${r}.values`));return}if(l.values!==void 0&&!Array.isArray(l.values)){t.push(o("invalid_analytics_filter_values","Analytics filter values must be an array when provided.",`${r}.values`));return}if(l.values!==void 0){const f=l.values.length;if(l.operator==="between"||l.operator==="not_between"){f!==2&&t.push(o("invalid_analytics_filter_values","Between analytics filters must include exactly two values.",`${r}.values`));return}(l.operator==="contains"||l.operator==="not_contains"||l.operator==="="||l.operator==="!="||l.operator===">"||l.operator===">="||l.operator==="<"||l.operator==="<="||l.operator===void 0)&&f!==1&&t.push(o("invalid_analytics_filter_values","Scalar analytics filters must include exactly one value. Use in/not_in for multiple values.",`${r}.values`))}})}}function Ei(e){const i=[];if(!p(e))return i.push(o("invalid_derived_field","Derived field definition must be a structured object.")),{ok:!1,errors:i,warnings:[]};if(e.kind!=="derived_field"&&i.push(o("invalid_derived_field_kind","Derived field kind must be derived_field.","kind")),m(e.name)||i.push(o("invalid_derived_field_name","Derived field needs a name.","name")),m(e.label)||i.push(o("invalid_derived_field_label","Derived field needs a label.","label")),qa.has(e.resultRole)||i.push(o("invalid_derived_field_role","Derived field resultRole must be measure, dimension, date, id, or unknown.","resultRole")),Ii.has(e.dataType)||i.push(o("invalid_derived_field_data_type","Derived field dataType must be string, number, boolean, date, datetime, or unknown.","dataType")),Oa.has(e.computeStage)||i.push(o("invalid_derived_field_compute_stage","Derived field computeStage must be row or aggregate.","computeStage")),e.computeStage==="aggregate"&&e.resultRole!=="measure"&&i.push(o("invalid_derived_field_compute_stage","Aggregate-stage derived fields must have resultRole measure.","computeStage")),e.resultRole!=="measure"&&e.defaultAggregate!==void 0&&i.push(o("invalid_derived_field_aggregate","Only measure derived fields may declare defaultAggregate.","defaultAggregate")),e.computeStage==="row"&&e.resultRole==="measure"&&e.defaultAggregate===void 0&&i.push(o("missing_derived_field_default_aggregate","Row-stage measure derived fields must declare defaultAggregate so row results have explicit rollup semantics.","defaultAggregate")),w(e.defaultAggregate,"defaultAggregate",i),e.aggregationBehavior!==void 0&&!La.has(e.aggregationBehavior)&&i.push(o("invalid_derived_field_aggregation_behavior","Derived field aggregationBehavior is not supported.","aggregationBehavior")),e.aggregationStrategy!==void 0&&!Ga.has(e.aggregationStrategy)&&i.push(o("invalid_derived_field_aggregation_strategy","Derived field aggregationStrategy is not supported.","aggregationStrategy")),m(e.expression)||i.push(o("invalid_derived_field_expression","Derived field needs a named-token expression.","expression")),e.expressionLanguage!==void 0&&e.expressionLanguage!=="semaphor_sql_template"&&i.push(o("invalid_derived_field_expression_language","Derived field expressionLanguage must be semaphor_sql_template.","expressionLanguage")),!p(e.inputs)||Object.keys(e.inputs).length===0?i.push(o("invalid_derived_field_inputs","Derived field needs at least one typed input.","inputs")):Object.entries(e.inputs).forEach(([s,n])=>{if(!m(s)){i.push(o("invalid_derived_field_input_name","Derived field input names must be non-empty strings.","inputs"));return}Ua(n,`inputs.${s}`,i)}),m(e.expression)&&p(e.inputs)){const s=Ea(e.expression),n=new Set(s),r=Object.keys(e.inputs).filter(l=>m(l));s.forEach(l=>{Object.prototype.hasOwnProperty.call(e.inputs,l)||i.push(o("invalid_derived_field_expression_token",`Derived field expression token "{${l}}" needs a matching inputs.${l} entry.`,"expression"))}),r.forEach(l=>{n.has(l)||i.push(o("unused_derived_field_input",`Derived field input "${l}" is not referenced by expression.`,`inputs.${l}`))})}const t=e.format;return p(t)&&t.type==="temporal_bucket"?i.push(o("invalid_derived_field_format","Derived field computation metadata cannot own temporal bucket presentation; declare grain and format on the grouped field.","format")):ki(t,"format",i),e.tags!==void 0&&(!Array.isArray(e.tags)||e.tags.some(s=>!m(s)))&&i.push(o("invalid_derived_field_tags","Derived field tags must be non-empty strings.","tags")),{ok:i.length===0,errors:i,warnings:[]}}function os(e){const i=[];if(!p(e))return i.push(o("invalid_result_calculation","Result calculation must be a structured object.")),{ok:!1,errors:i,warnings:[]};if(m(e.id)||i.push(o("invalid_result_calculation_id","Result calculation needs an id.","id")),m(e.label)||i.push(o("invalid_result_calculation_label","Result calculation needs a label.","label")),e.kind!=="percent_of_total"&&e.kind!=="rank"&&e.kind!=="running_total"&&e.kind!=="previous_row_delta"&&i.push(o("invalid_result_calculation_kind","Result calculation kind must be percent_of_total, rank, running_total, or previous_row_delta.","kind")),Oe(e.input,"input",i),Ha(e.output,"output",i),e.kind==="percent_of_total"){const t=e.denominator;t!==void 0&&(p(t)?t.scope==="population"?(g(t.metric,"denominator.metric",i,{required:!0}),Q(t.filters,"denominator.filters",i)):t.scope!=="returned_result"&&i.push(o("invalid_result_calculation_denominator","Percent-of-total denominator scope must be returned_result or population.","denominator.scope")):i.push(o("invalid_result_calculation_denominator","Percent-of-total denominator must be a structured object.","denominator")))}return e.kind==="rank"&&e.order!==void 0&&e.order!=="asc"&&e.order!=="desc"&&i.push(o("invalid_result_calculation_order","Rank result calculation order must be asc or desc.","order")),(e.kind==="running_total"||e.kind==="previous_row_delta")&&e.orderBy!==void 0&&Oe(e.orderBy,"orderBy",i),{ok:i.length===0,errors:i,warnings:[]}}function ke(e){var s;const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[o("invalid_analytics_intent","Analytics intent must be a structured object.")],warnings:t,repairHints:[{code:"invalid_analytics_intent",recommendedNextStep:"Send one structured analytics intent object with kind, source, and required fields."}]};if(e.version!==void 0&&e.version!==1&&i.push(o("invalid_version","Analytics intent version must be 1.","version")),we(e.source,"source",i),rs(e,i),Da(e,i),"relationshipHint"in e&&e.relationshipHint!==void 0&&Ie(e.relationshipHint,"relationshipHint",i),e.kind==="metric"){const n=Array.isArray(e.measures)?e.measures.filter(r=>p(r)&&m(r.name)):[];if(!Array.isArray(e.measures)||e.measures.length===0?i.push(o("missing_measure","Metric intent needs at least one measure.","measures")):e.measures.some(r=>!p(r)||!m(r.name))&&i.push(o("invalid_measure_list","Metric intent measures must be an array of field references with names.","measures")),n.forEach((r,l)=>{g(r,`measures.${l}`,i,{required:!0})}),n.length>0&&!va(n)){const r=n.find((l,d)=>n.some((u,f)=>f!==d&&$i(u,l)));r&&i.push(o("duplicate_measure",za(r),"measures"))}if(p(e.primaryMeasure)&&m(e.primaryMeasure.name)&&$e(e.primaryMeasure,n).length>1&&i.push(o("ambiguous_primary_measure","Metric intent primaryMeasure must identify exactly one selected measure.","primaryMeasure")),e.primaryMeasure!==void 0&&(g(e.primaryMeasure,"primaryMeasure",i,{required:!0}),p(e.primaryMeasure)&&m(e.primaryMeasure.name)&&n.length>0&&!$a(e.primaryMeasure,n)&&i.push(o("invalid_primary_measure","Metric intent primaryMeasure must match one measure field reference.","primaryMeasure"))),e.dimensions!==void 0&&!Array.isArray(e.dimensions)?i.push(o("invalid_measure_dimensions","Metric intent dimensions must be an array of field references.","dimensions")):Array.isArray(e.dimensions)&&e.dimensions.some(r=>!p(r)||!m(r.name))&&i.push(o("invalid_measure_dimensions","Metric intent dimensions must be an array of field references with names.","dimensions")),e.dateField!==void 0&&g(e.dateField,"dateField",i),e.timeWindow!==void 0&&(ce(e.timeWindow,"timeWindow",i),e.dateField||i.push(o("missing_time_window_date_field","Metric timeWindow needs a dateField.","dateField"))),Q(e.filters,"filters",i),Array.isArray(e.dimensions)&&e.dimensions.forEach((r,l)=>{g(r,`dimensions.${l}`,i)}),e.orderBy!==void 0){if(!p(e.orderBy))i.push(o("invalid_measure_order_by","Metric intent orderBy must be a structured object.","orderBy"));else if(g(e.orderBy.field,"orderBy.field",i,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&i.push(o("invalid_measure_order_direction","Metric intent orderBy direction must be asc or desc.","orderBy.direction")),p(e.orderBy.field)&&m(e.orderBy.field.name)){const r=[...n,...e.timeGrain&&e.dateField&&p(e.dateField)?[e.dateField]:[],...Array.isArray(e.dimensions)?e.dimensions.filter(l=>p(l)&&m(l.name)):[]];r.length>0&&!wa(e.orderBy.field,r)&&i.push(o("invalid_measure_order_by","Metric intent orderBy.field must match one selected measure, grouped dateField, or dimension.","orderBy.field"))}}ns(e,i)}else if(e.kind==="records"){if(!Array.isArray(e.fields)||e.fields.length===0?i.push(o("missing_record_fields","Records intent needs at least one field.","fields")):e.fields.some(n=>!p(n)||!m(n.name))&&i.push(o("invalid_record_fields","Records intent fields must be field references with names.","fields")),Array.isArray(e.fields)&&e.fields.forEach((n,r)=>{g(n,`fields.${r}`,i)}),e.dateField!==void 0&&g(e.dateField,"dateField",i),Ne(e.pagination,"pagination",i),e.timeWindow!==void 0&&(ce(e.timeWindow,"timeWindow",i),e.dateField||i.push(o("missing_time_window_date_field","Records timeWindow needs a dateField.","dateField"))),Q(e.filters,"filters",i),Array.isArray(e.filters)&&e.filters.forEach((n,r)=>{p(n)&&n.scope==="aggregate"&&i.push(o("unsupported_record_filter_scope","Records intents support row-scope filters only. Use a metric intent for aggregate-scope filters.",`filters.${r}.scope`))}),e.orderBy!==void 0&&(p(e.orderBy)?(g(e.orderBy.field,"orderBy.field",i,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&i.push(o("invalid_record_order_direction","Records intent orderBy direction must be asc or desc.","orderBy.direction"))):i.push(o("invalid_record_order_by","Records intent orderBy must be a structured object.","orderBy"))),e.totals!==void 0)if(!p(e.totals))i.push(o("invalid_records_totals","Records totals must be a structured server totals request.","totals"));else{e.totals.mode!=="server"&&i.push(o("invalid_records_totals","Records totals mode must be server.","totals.mode"));const n=e.totals.measures;!Array.isArray(n)||n.length===0?i.push(o("missing_records_totals_measures","Records server totals need at least one measure.","totals.measures")):n.forEach((r,l)=>{g(r,`totals.measures.${l}`,i,{required:!0}),(!p(r)||r.role!=="measure")&&i.push(o("invalid_records_totals_measure","Records server totals measures must be measure field references.",`totals.measures.${l}.role`))})}}else e.kind==="inputOptions"?Fa(e,i):e.kind==="matrix"?ss(e,i):e.kind==="sql"?(((s=e.source)==null?void 0:s.kind)!=="sql"&&i.push(o("invalid_sql_source","SQL analytics intent must use a SQL execution source.","source")),m(e.sql)||i.push(o("missing_sql","SQL analytics intent needs SQL text.","sql")),Sa(e.defaultParameters,"defaultParameters",i),Array.isArray(e.fields)&&e.fields.forEach((n,r)=>{g(n,`fields.${r}`,i)}),Ne(e.pagination,"pagination",i)):i.push(o("invalid_analytics_kind","Analytics kind is not supported.","kind"));return{ok:i.length===0,errors:i,warnings:t,repairHints:ds(i)}}function rs(e,i){if(!(!("derivedFields"in e)||e.derivedFields===void 0)){if(!Array.isArray(e.derivedFields)){i.push(o("invalid_derived_fields","Analytics intent derivedFields must be an array of derived field definitions.","derivedFields"));return}e.derivedFields.forEach((t,s)=>{Ei(t).errors.forEach(r=>{i.push({...r,path:r.path?`derivedFields.${s}.${r.path}`:`derivedFields.${s}`})})})}}function ji(e){const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[o("invalid_operation_intent","Operation intent must be a structured object.")],warnings:t,repairHints:[{code:"invalid_operation_intent",recommendedNextStep:"Send one typed operation intent with version, kind, and required operation fields."}]};if(e.version!==1&&i.push(o("invalid_version","Operation intent version must be 1.","version")),e.kind==="answer_obligations")!Array.isArray(e.obligations)||e.obligations.length===0?i.push(o("missing_obligations","Answer-obligations operation intent needs at least one obligation.","obligations")):e.obligations.forEach((s,n)=>{m(s.id)||i.push(o("missing_obligation_id","Each analytics obligation needs an id.",`obligations.${n}.id`)),m(s.prompt)||i.push(o("missing_obligation_prompt","Each analytics obligation needs a prompt.",`obligations.${n}.prompt`))});else if(e.kind==="dashboard_change"||e.kind==="data_app_change"){if(m(e.instruction)||i.push(o("missing_instruction","Change operation intent needs an instruction.","instruction")),e.analyticsIntent){const s=ke(e.analyticsIntent);i.push(...s.errors),t.push(...s.warnings)}}else i.push(o("invalid_operation_kind","Operation intent kind is not supported.","kind"));return{ok:i.length===0,errors:i,warnings:t,repairHints:Ti(i)}}function ls(e){const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[o("invalid_recovery_plan","Analytics recovery plan must be a structured object.")],warnings:t,repairHints:[{code:"invalid_recovery_plan",recommendedNextStep:"Return a typed recovery plan with operationIntent and plannedToolCalls."}]};e.version!==1&&i.push(o("invalid_version","Recovery plan version must be 1.","version")),e.kind!=="analytics_recovery_plan"&&i.push(o("invalid_recovery_plan_kind","Recovery plan kind must be analytics_recovery_plan.","kind"));const s=ji(e.operationIntent);return i.push(...s.errors),t.push(...s.warnings),Array.isArray(e.plannedToolCalls)||i.push(o("invalid_planned_tool_calls","Recovery plan plannedToolCalls must be an array.","plannedToolCalls")),{ok:i.length===0,errors:i,warnings:t,repairHints:Ti(i)}}function Ti(e){return e.map(i=>({code:i.code,recommendedNextStep:i.code==="missing_obligations"?"Normalize the user request into one or more typed analytics obligations before recovery planning.":"Correct the operation/recovery contract shape before planning execution."}))}function ds(e){return e.map(i=>{switch(i.code){case"missing_source":return{code:i.code,fieldRole:"source",recommendedNextStep:"Provide a semantic, physical, or SQL source before executing analytics."};case"missing_measure":return{code:i.code,fieldRole:"measure",recommendedNextStep:"Choose one exact measure from the grounded schema candidates."};case"missing_record_fields":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Provide at least one field for the records intent."};case"missing_matrix_rows":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Choose at least one row axis level for the matrix table."};case"missing_matrix_values":return{code:i.code,fieldRole:"measure",recommendedNextStep:"Choose at least one value field for the matrix table."};case"unsupported_matrix_sql_source":return{code:i.code,fieldRole:"source",recommendedNextStep:"Use a semantic or explorer-backed source for matrix tables; raw SQL matrix tables are not supported."};case"missing_input_options_input_id":return{code:i.code,fieldRole:"input",recommendedNextStep:"Provide the inputId that these option values populate."};case"missing_input_options_label_field":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Provide the human-readable field used as option labels."};case"missing_input_options_value_field":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Provide the stable field used as option values."};case"missing_sql":return{code:i.code,fieldRole:"sql",recommendedNextStep:"Provide bounded read-only SQL with an explicit outer LIMIT."};case"conflicting_sql":return{code:i.code,fieldRole:"sql",recommendedNextStep:"Use one canonical SQL text location for the intent; prefer top-level sql."};case"missing_semantic_domain":case"missing_dataset_name":case"missing_connection_id":case"missing_table_name":return{code:i.code,fieldRole:"source",recommendedNextStep:"Use grounded catalog metadata to fill the missing source reference."};default:return}}).filter(i=>!!i)}function us(e,i,t,s){if(!e||typeof e!="object"){t.push(o("invalid_view","Dashboard view must be an object.",i));return}if(m(e.title)||t.push(o("missing_view_title","Dashboard view needs a title.",i)),!e.presentation||typeof e.presentation!="object"){t.push(o("missing_presentation","Dashboard view needs a presentation.",`${i}.presentation`));return}if(e.presentation.kind==="text"){m(e.text)||s.push(o("missing_text_content","Text views should include text content.",`${i}.text`));return}if(!e.analytics){t.push(o("missing_view_analytics","Non-text dashboard views need analytics intent.",`${i}.analytics`));return}e.presentation.kind==="matrixTable"&&e.analytics.kind!=="matrix"&&t.push(o("invalid_matrix_view_analytics","Matrix table views need matrix analytics intent.",`${i}.analytics.kind`));const n=ke(e.analytics);for(const r of n.errors)t.push(o(r.code,r.message,`${i}.analytics${r.path?`.${r.path}`:""}`));for(const r of n.warnings)s.push(o(r.code,r.message,`${i}.analytics${r.path?`.${r.path}`:""}`))}function cs(e){const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[o("invalid_dashboard_intent","Dashboard intent must be a structured object.")],warnings:t};e.version!==1&&i.push(o("invalid_version","Dashboard intent version must be 1.")),e.kind!=="dashboard"&&i.push(o("invalid_kind","Experience intent kind must be dashboard.")),m(e.title)||i.push(o("missing_title","Dashboard intent needs a title.","title"));const s=Array.isArray(e.inputs)?e.inputs:[],n=de(s.filter(p).map(u=>u.id).filter(u=>typeof u=="string"));n&&i.push(o("duplicate_input_id",`Duplicate input id: ${n}.`,"inputs"));for(const[u,f]of s.entries()){const _=`inputs.${u}`;if(!p(f)){i.push(o("invalid_input","Dashboard input must be an object.",_));continue}m(f.id)||i.push(o("missing_input_id","Input needs an id.",`${_}.id`)),m(f.label)||i.push(o("missing_input_label","Input needs a label.",`${_}.label`)),!f.field||!m(f.field.name)?i.push(o("missing_input_field","Input needs a field.",`${_}.field`)):g(f.field,`${_}.field`,i)}const r=Array.isArray(e.sections)?e.sections:[];r.length===0&&i.push(o("missing_sections","Dashboard intent needs at least one section.","sections"));const l=r.flatMap(u=>u&&typeof u=="object"&&Array.isArray(u.views)?u.views.filter(p).map(f=>f.id).filter(f=>!!f):[]),d=de(l);d&&i.push(o("duplicate_view_id",`Duplicate dashboard view id: ${d}.`,"sections"));for(const[u,f]of r.entries()){const _=`sections.${u}`;if(!f||typeof f!="object"){i.push(o("invalid_section","Dashboard section must be an object.",_));continue}if(m(f.title)||i.push(o("missing_section_title","Dashboard section needs a title.",_)),!Array.isArray(f.views)||f.views.length===0){i.push(o("missing_section_views","Dashboard section needs at least one view.",`${_}.views`));continue}for(const[q,O]of f.views.entries())us(O,`${_}.views.${q}`,i,t)}return{ok:i.length===0,errors:i,warnings:t}}exports.SEMAPHOR_ANALYZE_RESULT_FIELD_CONTRACT=Qe;exports.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION=G;exports.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION=Bi;exports.SEMAPHOR_GENERATED_COUNT_METRIC_ID=Fi;exports.SEMAPHOR_MATRIX_TIME_GRAINS=Y;exports.SEMAPHOR_TIME_GRAINS=R;exports.TEMPORAL_BUCKET_CONTRACT_ERROR_CODES=Ci;exports.TEMPORAL_BUCKET_PRESETS=Ge;exports.canonicalDashboardRecordsPayloadSchema=Ht;exports.dashboardRecordsPayloadSchema=Ut;exports.hasCompleteSemaphorSourceIdentity=Ni;exports.isSemaphorDataAppCodegenSummary=Ji;exports.isSemaphorMatrixTimeGrain=Le;exports.isSemaphorTimeGrain=Ve;exports.isValidIanaTimeZone=He;exports.mergeSemaphorSourcesByIdentity=qi;exports.parseSemaphorIsoInstant=Ra;exports.parseSemaphorIsoTimeWindowBoundary=H;exports.preferSemaphorFieldRefMetadata=Pi;exports.preferSemaphorSourceMetadata=me;exports.semaphorAnalyticsCoverageSchema=ze;exports.semaphorAnalyticsDiagnosticFeedbackSchema=_e;exports.semaphorAnalyticsExecutionResultSchema=bi;exports.semaphorAnalyticsPopulationSchema=ve;exports.semaphorAnalyticsResultSchema=hi;exports.semaphorAnalyticsValidationIssueSchema=U;exports.semaphorAnalyticsValidationResultSchema=be;exports.semaphorAnalyzeResultSchema=fa;exports.semaphorAnalyzeResultShape=_i;exports.semaphorDataAppCodegenSummarySchema=_a;exports.semaphorDerivedFieldDefinitionSchema=ye;exports.semaphorExecutionFieldRefSchema=ee;exports.semaphorFieldRefSchema=$;exports.semaphorFieldRefsMatch=Ye;exports.semaphorInputOptionsResultSchema=mi;exports.semaphorMatrixResultSchema=gi;exports.semaphorMetricAggregate=Z;exports.semaphorMetricMeasureBindingKey=Ze;exports.semaphorMetricResultSchema=ci;exports.semaphorPhysicalSourceRefSchema=li;exports.semaphorRecordsResultSchema=pi;exports.semaphorRelationshipDiagnosticsSchema=yi;exports.semaphorResultColumnSchema=A;exports.semaphorSemanticSourceRefSchema=he;exports.semaphorSourceIdentityKey=L;exports.semaphorSourceRefSchema=k;exports.semaphorSourcesReferToSameDataset=pe;exports.semaphorSqlResultSchema=fi;exports.semaphorSqlSourceRefSchema=di;exports.semaphorTimeGrainSchema=si;exports.temporalBucketDataTypeForGrain=Ue;exports.temporalBucketFormatSchema=oi;exports.temporalBucketMetadataSchema=le;exports.validateSemaphorAnalyticsIntent=ke;exports.validateSemaphorAnalyticsRecoveryPlan=ls;exports.validateSemaphorDashboardIntent=cs;exports.validateSemaphorDataAppCodegenSummary=fe;exports.validateSemaphorDerivedFieldDefinition=Ei;exports.validateSemaphorOperationIntent=ji;exports.validateSemaphorResultCalculation=os;