react-semaphor 0.1.369 → 0.1.370
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/analytics-protocol/index.cjs +1 -1
- package/dist/analytics-protocol/index.js +1 -1
- package/dist/chunks/validation-DYL3ArlL.js +1 -0
- package/dist/chunks/{validation-nOPr0mTk.js → validation-PPSpYtVf.js} +304 -207
- package/dist/chunks/validators-CgxWT8UX.js +1 -0
- package/dist/chunks/validators-DBNa-eb1.js +1799 -0
- package/dist/dashboard-authoring/index.cjs +1 -1
- package/dist/dashboard-authoring/index.js +1 -1
- package/dist/data-app-sdk/index.cjs +1 -1
- package/dist/data-app-sdk/index.js +251 -180
- package/dist/data-app-sdk-validation/index.cjs +1 -1
- package/dist/data-app-sdk-validation/index.js +3 -3
- package/dist/types/analytics-protocol.d.ts +451 -2
- package/dist/types/dashboard-assistant.d.ts +448 -2
- package/dist/types/dashboard-authoring.d.ts +159 -1
- package/dist/types/data-app-builder.d.ts +156 -1
- package/dist/types/data-app-sdk-validation.d.ts +470 -3
- package/dist/types/data-app-sdk.d.ts +490 -5
- package/dist/types/main.d.ts +156 -1
- package/package.json +1 -1
- package/dist/chunks/validation-Dsf7PydY.js +0 -1
- package/dist/chunks/validators-CVuWOHYv.js +0 -1032
- package/dist/chunks/validators-oc8qtP4q.js +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("../chunks/contracts-CtB2VONT.js"),N=require("../chunks/source-identity-C-xaeE_I.js"),z=require("../chunks/validators-oc8qtP4q.js"),De=require("../chunks/catalog-field-grounding-Du6mKDcF.js");function _(e){return e&&typeof e=="object"?e:null}function D(e){return typeof e=="string"?e:null}function oe(e){var t,r,n;return!!(e&&typeof e=="object")&&(((t=_(e))==null?void 0:t.kind)==="semantic"||((r=_(e))==null?void 0:r.kind)==="physical"||((n=_(e))==null?void 0:n.kind)==="sql")}function M(e){return oe(e)?e.kind==="semantic"?!!(e.domainId&&e.datasetName):e.kind==="physical"?!!(e.connectionId&&e.tableName):!1:!1}function ve(e){return N.semaphorSourceIdentityKey(e)}function K(e,t){return N.semaphorSourcesReferToSameDataset(e,t)}function se(e,t){return N.preferSemaphorSourceMetadata(e,t)}function R(e){const t=[];for(const r of e){const n=t.findIndex(o=>K(o,r));n===-1?t.push(r):t[n]=se(t[n],r)}return t}function Ce(e){return R(e)[0]}function G(e,t){return e.kind!=="semantic"||e.connectionId||(t==null?void 0:t.kind)!=="semantic"||!N.semaphorSourcesReferToSameDataset(e,t)||!t.connectionId?e:{...e,connectionId:t.connectionId}}function W(e){return M(e)?e:void 0}function ae(e,t){if(!(e.kind!=="semantic"||e.connectionId))return t.find(r=>(r==null?void 0:r.kind)==="semantic"&&N.semaphorSourcesReferToSameDataset(e,r)&&!!r.connectionId)}function S(e,t){const r=W(e==null?void 0:e.source);return r?G(r,t):void 0}function de({explicitSource:e,field:t,defaultSource:r,fallbackSources:n}){const o=[r,...n||[]],a=W(e),i=a?G(a,ae(a,o)):void 0;if(i)return i;if(e!==void 0)return;const d=S(t,r),s=d?G(d,ae(d,o)):void 0;if(s)return s;if((t==null?void 0:t.source)===void 0)return W(r)}function ke(e,t){if(!(e!=null&&e.name)||!(t!=null&&t.name)||e.name!==t.name)return!1;const r=S(e),n=S(t);return!r||!n?!0:K(r,n)}function C(e){var t;return D((t=_(e))==null?void 0:t.kind)}function ce(e){var t,r;return C(e)!=="semantic"?null:((r=D((t=_(e))==null?void 0:t.domainId))==null?void 0:r.trim())||null}function xe(e){var t;return C(e)!=="semantic"?null:D((t=_(e))==null?void 0:t.datasetName)}function Te(e){var t;return C(e)!=="semantic"?null:D((t=_(e))==null?void 0:t.datasetId)}function Fe(e){var t;return C(e)!=="physical"?null:D((t=_(e))==null?void 0:t.connectionId)}function Re(e){var t;return C(e)!=="physical"?null:D((t=_(e))==null?void 0:t.tableName)}function Ne(e){var t;return C(e)!=="physical"?"":D((t=_(e))==null?void 0:t.databaseName)||""}function Me(e){var t;return C(e)!=="physical"?"":D((t=_(e))==null?void 0:t.schemaName)||""}function le(e){if(e.analyticsIntent&&typeof e.analyticsIntent=="object"&&"source"in e.analyticsIntent)return e.analyticsIntent.source}function ue({datasets:e,requireAtLeastOne:t}){if(t&&e.length<1)return{ok:!1,issue:"invalid_dataset_count"};if(e.length<=1)return{ok:!0};const r=e.map(ce),n=new Set(r.filter(Boolean));return r.some(o=>!o)||n.size!==1?{ok:!1,issue:"invalid_multi_dataset_scope"}:{ok:!0}}function E(e,t){if(!t)return!1;if(t.kind==="semantic"){const r=Te(e);return ce(e)===t.domainId?r&&t.datasetId?r===t.datasetId:xe(e)===t.datasetName:!1}return t.kind==="physical"?Fe(e)===t.connectionId&&Re(e)===t.tableName&&Ne(e)===(t.databaseName||"")&&Me(e)===(t.schemaName||""):!1}function $e(e,t){return e.find(r=>E(r,t))}function p(e,t,r){return r?{code:e,message:t,cardId:r}:{code:e,message:t}}function B(e){const t=new Set;for(const r of e){if(t.has(r))return r;t.add(r)}return null}function fe({card:e,datasets:t,errors:r}){if(e.type==="text")return;const n=le(e);if(!n){if(t.length<=1)return;r.push(p("missing_card_analytics_source","Multi-dataset dashboard cards must include analytics intent with a source so the materializer can choose the correct dataset.",e.id));return}t.some(o=>E(o,n))||r.push(p("invalid_card_analytics_source","Dashboard cards with an explicit analytics source must use one of the selected datasets.",e.id))}function P(e){return e.map(t=>t==null?void 0:t.source).filter(t=>!!t)}function H(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object")):[]}function ie(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object")):[]}function Oe(e){var r;if(!e)return[];const t=[e.source];return e.kind==="metric"?t.push(...P([...H(e.metrics),e.primaryMetric,e.dateField,...H(e.dimensions),...ie(e.filters).map(n=>n.field)])):e.kind==="records"?t.push(...P([...H(e.fields),e.dateField,(r=e.orderBy)==null?void 0:r.field,...ie(e.filters).map(n=>n.field)])):e.kind==="inputOptions"?t.push(...P([e.field])):e.kind==="sql"&&t.push(...P(e.fields||[])),t}function pe({card:e,datasets:t,errors:r}){if(e.type!=="text"){for(const n of Oe(e.analyticsIntent))if(n&&!t.some(o=>E(o,n))){r.push(p("invalid_card_query_source","Dashboard card query field references must use one of the selected datasets.",e.id));return}}}function he({card:e,errors:t}){if(e.type==="text"||!e.analyticsIntent)return;const r=z.validateSemaphorAnalyticsIntent(e.analyticsIntent);if(!r.ok)for(const n of r.errors)t.push(p(n.code,n.path?`${n.path}: ${n.message}`:n.message,e.id))}function me({datasets:e,errors:t,requireAtLeastOne:r}){const n=ue({datasets:e,requireAtLeastOne:r});if(!n.ok){if(n.issue==="invalid_dataset_count"){t.push(p("invalid_dataset_count","Dashboard authoring requires at least one selected dataset."));return}t.push(p("invalid_multi_dataset_scope","Multi-dataset dashboard authoring is limited to semantic datasets from one domain."))}}function ge(e){var f,g;const t=[];if(!e||typeof e!="object")return{ok:!1,errors:[p("invalid_plan","Dashboard plan must be a structured object.")],warnings:[]};const r=e,n=[...r.warnings||[]];r.version!==1&&t.push(p("invalid_version","Dashboard plan version must be 1.")),(f=r.title)!=null&&f.trim()||t.push(p("missing_title","Dashboard plan needs a title."));const o=Array.isArray(r.datasets)?r.datasets:[],a=Array.isArray(r.sheets)?r.sheets:[];me({datasets:o,errors:t,requireAtLeastOne:!0}),a.length!==1&&t.push(p("invalid_sheet_count","MVP dashboard authoring creates exactly one dashboard sheet."));const i=a[0];i&&i.kind!=="dashboard"&&t.push(p("invalid_sheet_kind",'Generated sheet must use kind "dashboard".'));const d=(i==null?void 0:i.cards)||[];d.length>v.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS&&t.push(p("too_many_cards",`Generated dashboards can contain at most ${v.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS} cards.`));const s=B(d.map(l=>l.id));s&&t.push(p("duplicate_card_id",`Duplicate generated card id: ${s}.`));const u=B(d.map(l=>l.frameId));u&&t.push(p("duplicate_frame_id",`Duplicate generated frame id: ${u}.`));for(const l of d)(g=l.title)!=null&&g.trim()||t.push(p("missing_card_title","Card title is required.",l.id)),l.type==="custom"&&t.push(p("custom_visual_out_of_scope","Whole-dashboard authoring supports built-in visual types only.",l.id)),l.type!=="text"&&!l.analyticsIntent&&n.push(p("missing_analytics_intent","Non-text card has no analytics intent and may be skipped by the app layer.",l.id)),fe({card:l,datasets:o,errors:t}),he({card:l,errors:t}),pe({card:l,datasets:o,errors:t});const h=Array.isArray(r.filterInputs)?r.filterInputs:[],I=h.map(l=>l.id),A=B(I);A&&t.push(p("duplicate_input_id",`Duplicate dashboard input id: ${A}.`));const w=h.map(l=>l.variableName).filter(Boolean)||[],y=B(w);y&&t.push(p("duplicate_input_variable",`Duplicate dashboard input variable name: ${y}.`));const c=Array.isArray(r.calculatedFields)?r.calculatedFields:[];for(const l of c)l.scope==="domain"&&l.reuseOnly!==!0&&t.push(p("domain_calculated_field_create_out_of_scope",`Creating domain calculated field "${l.name}" is outside MVP.`));return{ok:t.length===0,errors:t,warnings:n}}function be(e){var i;const t=[];if(!e||typeof e!="object")return{ok:!1,errors:[p("invalid_change_plan","Dashboard change plan must be a structured object.")],warnings:[]};const r=e,n=[...r.warnings||[]];r.version!==1&&t.push(p("invalid_version","Dashboard change plan version must be 1.")),(i=r.dashboardId)!=null&&i.trim()||t.push(p("missing_dashboard_id","Dashboard change plan needs a dashboard id."));const o=Array.isArray(r.datasets)?r.datasets:[],a=Array.isArray(r.operations)?r.operations:[];me({datasets:o,errors:t,requireAtLeastOne:!1});for(const d of a){if(d.kind==="unsupported"){n.push(p("unsupported_operation",d.reason||d.requestedAction));continue}d.kind==="addCard"&&d.card.type==="custom"&&t.push(p("custom_visual_out_of_scope","Whole-dashboard authoring supports built-in visual types only.",d.card.id)),d.kind==="addCard"&&(fe({card:d.card,datasets:o,errors:t}),he({card:d.card,errors:t}),pe({card:d.card,datasets:o,errors:t})),d.kind==="addCalculatedField"&&d.field.scope==="domain"&&d.field.reuseOnly!==!0&&t.push(p("domain_calculated_field_create_out_of_scope",`Creating domain calculated field "${d.field.name}" is outside MVP.`))}return{ok:t.length===0,errors:t,warnings:n}}const Be={lg:48,md:36,sm:24,xs:12,xxs:6};function Pe(e,t){let r=0,n=0,o=0;return e.map(a=>{const i=Math.min(a.w,t);r>0&&r+i>t&&(r=0,n+=o,o=0);const d={i:a.frameId,x:r,y:n,w:i,h:a.h,minW:Math.min(a.minW,t),minH:a.minH,static:!1};return r+=i,o=Math.max(o,a.h),d})}function ze(e){const t=[...e].sort((s,u)=>s.priority-u.priority),r=t.filter(s=>s.role==="kpi"),n=t.filter(s=>s.role==="chart"),o=t.filter(s=>s.role==="table"),a=t.filter(s=>s.role==="text"),i=a.slice(0,1),d=a.slice(i.length);return{kpis:r,introText:i,charts:n,tables:o,supportingText:d}}function Ee(e,t,r){return t==="xxs"||t==="xs"?r:t==="sm"?Math.min(12,r):t==="md"?e<=1||e===2?18:12:e<=1||e===2?24:e===3?16:12}function qe(e,t,r,n){return r==="xxs"||r==="xs"||r==="sm"||r==="md"||t===1||t%2===1&&e===0?n:n/2}function Ve(e){const{item:t,band:r,index:n,bandCount:o,breakpoint:a,columns:i}=e;return r==="kpi"?{...t,band:r,w:Ee(o,a,i),h:15,minW:Math.min(6,i),minH:12}:r==="table"?{...t,band:r,w:i,h:a==="xxs"||a==="xs"?34:38,minW:Math.min(12,i),minH:18}:r==="introText"?{...t,band:r,w:i,h:a==="xxs"||a==="xs"?12:10,minW:Math.min(12,i),minH:8}:r==="supportingText"?{...t,band:r,w:a==="lg"?i/2:i,h:a==="xxs"||a==="xs"?12:10,minW:Math.min(12,i),minH:8}:{...t,band:r,w:qe(n,o,a,i),h:a==="xxs"||a==="xs"?28:30,minW:Math.min(12,i),minH:16}}function T(e,t,r,n){return e.map((o,a)=>Ve({item:o,band:t,index:a,bandCount:e.length,breakpoint:r,columns:n}))}function q(e){const t=ze(e);return Object.fromEntries(v.DASHBOARD_AUTHORING_BREAKPOINTS.map(r=>{const n=Be[r],o=[...T(t.introText,"introText",r,n),...T(t.kpis,"kpi",r,n),...T(t.charts,"chart",r,n),...T(t.tables,"table",r,n),...T(t.supportingText,"supportingText",r,n)];return[r,Pe(o,n)]}))}function He(e){const t=De.normalizeAnalyticsCatalogDataType(e);return t==="datetime"?"date":t==="unknown"?"string":t}function Le(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function je(e){return Le(e)&&typeof e.filterId=="string"&&typeof e.operation=="string"&&Array.isArray(e.values)}function Ge(e){return e.filter(t=>typeof t=="string"||typeof t=="number")}function We(e){return e.filter(t=>t instanceof Date||typeof t=="string")}function X(e,t){if(t===void 0)return;const r=He(e.dataType),n=e.operation||"in";if(je(t))return{...t,filterId:e.id,name:t.name||e.column,valueType:r,dataType:e.dataType,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext};if(n==="is null"||n==="is not null")return{filterId:e.id,name:e.column,operation:n,valueType:r,values:[],dataType:e.dataType,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext};const o=Array.isArray(t)?t:[t],a=r==="date"?We(o):Ge(o);if(a.length!==0&&!((n==="between"||n==="not between")&&a.length<2))return{filterId:e.id,name:e.column,operation:n,valueType:r,values:a,dataType:e.dataType,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext}}function Ie(e,t,r){return r?{code:e,message:t,cardId:r}:{code:e,message:t}}function Ue(e,t,r){const n=(t||[]).filter(o=>o.scope==="card"&&o.targetCardId===r).map(o=>o.field).filter(Boolean);return n.length===0?e:{...e,calculatedFields:[...e.calculatedFields||[],...n]}}function U(e,t){return Array.from(new Set((e||[]).map(r=>t.get(r)).filter(r=>!!r)))}function Ke(e,t){if((e==null?void 0:e.kind)!=="cards")return e;const r=U(e.cardIds,t);return r.length>0?{...e,cardIds:r}:null}function Xe(e,t){return!e.applyToCardIds&&!e.excludeCardIds?e:{...e,...e.applyToCardIds?{applyToCardIds:U(e.applyToCardIds,t)}:{},...e.excludeCardIds?{excludeCardIds:U(e.excludeCardIds,t)}:{}}}function Je(e,t){const r={},n=[];return{inputs:(e.filterInputs||[]).flatMap((a,i)=>{const d=Ke(a.scope,t);if(d===null)return n.push(Ie("filter_input_scope_empty",`Filter input "${a.label}" was skipped because all scoped cards were skipped during query validation.`)),[];const s=X(a.filter,a.defaultValue);return s&&(r.shared??(r.shared={}),r.shared[a.id]={status:"set",value:{kind:"filter",filterValue:s}}),[{id:a.id,kind:"filter",label:a.label,variableName:a.variableName,scope:d||{kind:"allSheets",sheetKinds:["dashboard"]},runtimeScope:"shared",presentation:{placement:"toolbar",order:i},exports:["label","value","start","end","range"],filter:Xe(a.filter,t)}]}),warnings:n,defaultInputValues:r.shared&&Object.keys(r.shared).length>0?r:void 0}}function Qe(e){var w,y;const t=ge(e.plan);if(!t.ok)throw new Error(t.errors.map(c=>c.message).join(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("../chunks/contracts-CtB2VONT.js"),N=require("../chunks/source-identity-C-xaeE_I.js"),z=require("../chunks/validators-CgxWT8UX.js"),De=require("../chunks/catalog-field-grounding-Du6mKDcF.js");function _(e){return e&&typeof e=="object"?e:null}function D(e){return typeof e=="string"?e:null}function oe(e){var t,r,n;return!!(e&&typeof e=="object")&&(((t=_(e))==null?void 0:t.kind)==="semantic"||((r=_(e))==null?void 0:r.kind)==="physical"||((n=_(e))==null?void 0:n.kind)==="sql")}function M(e){return oe(e)?e.kind==="semantic"?!!(e.domainId&&e.datasetName):e.kind==="physical"?!!(e.connectionId&&e.tableName):!1:!1}function ve(e){return N.semaphorSourceIdentityKey(e)}function K(e,t){return N.semaphorSourcesReferToSameDataset(e,t)}function se(e,t){return N.preferSemaphorSourceMetadata(e,t)}function R(e){const t=[];for(const r of e){const n=t.findIndex(o=>K(o,r));n===-1?t.push(r):t[n]=se(t[n],r)}return t}function Ce(e){return R(e)[0]}function G(e,t){return e.kind!=="semantic"||e.connectionId||(t==null?void 0:t.kind)!=="semantic"||!N.semaphorSourcesReferToSameDataset(e,t)||!t.connectionId?e:{...e,connectionId:t.connectionId}}function W(e){return M(e)?e:void 0}function ae(e,t){if(!(e.kind!=="semantic"||e.connectionId))return t.find(r=>(r==null?void 0:r.kind)==="semantic"&&N.semaphorSourcesReferToSameDataset(e,r)&&!!r.connectionId)}function S(e,t){const r=W(e==null?void 0:e.source);return r?G(r,t):void 0}function de({explicitSource:e,field:t,defaultSource:r,fallbackSources:n}){const o=[r,...n||[]],a=W(e),i=a?G(a,ae(a,o)):void 0;if(i)return i;if(e!==void 0)return;const d=S(t,r),s=d?G(d,ae(d,o)):void 0;if(s)return s;if((t==null?void 0:t.source)===void 0)return W(r)}function ke(e,t){if(!(e!=null&&e.name)||!(t!=null&&t.name)||e.name!==t.name)return!1;const r=S(e),n=S(t);return!r||!n?!0:K(r,n)}function C(e){var t;return D((t=_(e))==null?void 0:t.kind)}function ce(e){var t,r;return C(e)!=="semantic"?null:((r=D((t=_(e))==null?void 0:t.domainId))==null?void 0:r.trim())||null}function xe(e){var t;return C(e)!=="semantic"?null:D((t=_(e))==null?void 0:t.datasetName)}function Te(e){var t;return C(e)!=="semantic"?null:D((t=_(e))==null?void 0:t.datasetId)}function Fe(e){var t;return C(e)!=="physical"?null:D((t=_(e))==null?void 0:t.connectionId)}function Re(e){var t;return C(e)!=="physical"?null:D((t=_(e))==null?void 0:t.tableName)}function Ne(e){var t;return C(e)!=="physical"?"":D((t=_(e))==null?void 0:t.databaseName)||""}function Me(e){var t;return C(e)!=="physical"?"":D((t=_(e))==null?void 0:t.schemaName)||""}function le(e){if(e.analyticsIntent&&typeof e.analyticsIntent=="object"&&"source"in e.analyticsIntent)return e.analyticsIntent.source}function ue({datasets:e,requireAtLeastOne:t}){if(t&&e.length<1)return{ok:!1,issue:"invalid_dataset_count"};if(e.length<=1)return{ok:!0};const r=e.map(ce),n=new Set(r.filter(Boolean));return r.some(o=>!o)||n.size!==1?{ok:!1,issue:"invalid_multi_dataset_scope"}:{ok:!0}}function E(e,t){if(!t)return!1;if(t.kind==="semantic"){const r=Te(e);return ce(e)===t.domainId?r&&t.datasetId?r===t.datasetId:xe(e)===t.datasetName:!1}return t.kind==="physical"?Fe(e)===t.connectionId&&Re(e)===t.tableName&&Ne(e)===(t.databaseName||"")&&Me(e)===(t.schemaName||""):!1}function $e(e,t){return e.find(r=>E(r,t))}function p(e,t,r){return r?{code:e,message:t,cardId:r}:{code:e,message:t}}function B(e){const t=new Set;for(const r of e){if(t.has(r))return r;t.add(r)}return null}function fe({card:e,datasets:t,errors:r}){if(e.type==="text")return;const n=le(e);if(!n){if(t.length<=1)return;r.push(p("missing_card_analytics_source","Multi-dataset dashboard cards must include analytics intent with a source so the materializer can choose the correct dataset.",e.id));return}t.some(o=>E(o,n))||r.push(p("invalid_card_analytics_source","Dashboard cards with an explicit analytics source must use one of the selected datasets.",e.id))}function P(e){return e.map(t=>t==null?void 0:t.source).filter(t=>!!t)}function H(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object")):[]}function ie(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object")):[]}function Oe(e){var r;if(!e)return[];const t=[e.source];return e.kind==="metric"?t.push(...P([...H(e.metrics),e.primaryMetric,e.dateField,...H(e.dimensions),...ie(e.filters).map(n=>n.field)])):e.kind==="records"?t.push(...P([...H(e.fields),e.dateField,(r=e.orderBy)==null?void 0:r.field,...ie(e.filters).map(n=>n.field)])):e.kind==="inputOptions"?t.push(...P([e.field])):e.kind==="sql"&&t.push(...P(e.fields||[])),t}function pe({card:e,datasets:t,errors:r}){if(e.type!=="text"){for(const n of Oe(e.analyticsIntent))if(n&&!t.some(o=>E(o,n))){r.push(p("invalid_card_query_source","Dashboard card query field references must use one of the selected datasets.",e.id));return}}}function he({card:e,errors:t}){if(e.type==="text"||!e.analyticsIntent)return;const r=z.validateSemaphorAnalyticsIntent(e.analyticsIntent);if(!r.ok)for(const n of r.errors)t.push(p(n.code,n.path?`${n.path}: ${n.message}`:n.message,e.id))}function me({datasets:e,errors:t,requireAtLeastOne:r}){const n=ue({datasets:e,requireAtLeastOne:r});if(!n.ok){if(n.issue==="invalid_dataset_count"){t.push(p("invalid_dataset_count","Dashboard authoring requires at least one selected dataset."));return}t.push(p("invalid_multi_dataset_scope","Multi-dataset dashboard authoring is limited to semantic datasets from one domain."))}}function ge(e){var f,g;const t=[];if(!e||typeof e!="object")return{ok:!1,errors:[p("invalid_plan","Dashboard plan must be a structured object.")],warnings:[]};const r=e,n=[...r.warnings||[]];r.version!==1&&t.push(p("invalid_version","Dashboard plan version must be 1.")),(f=r.title)!=null&&f.trim()||t.push(p("missing_title","Dashboard plan needs a title."));const o=Array.isArray(r.datasets)?r.datasets:[],a=Array.isArray(r.sheets)?r.sheets:[];me({datasets:o,errors:t,requireAtLeastOne:!0}),a.length!==1&&t.push(p("invalid_sheet_count","MVP dashboard authoring creates exactly one dashboard sheet."));const i=a[0];i&&i.kind!=="dashboard"&&t.push(p("invalid_sheet_kind",'Generated sheet must use kind "dashboard".'));const d=(i==null?void 0:i.cards)||[];d.length>v.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS&&t.push(p("too_many_cards",`Generated dashboards can contain at most ${v.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS} cards.`));const s=B(d.map(l=>l.id));s&&t.push(p("duplicate_card_id",`Duplicate generated card id: ${s}.`));const u=B(d.map(l=>l.frameId));u&&t.push(p("duplicate_frame_id",`Duplicate generated frame id: ${u}.`));for(const l of d)(g=l.title)!=null&&g.trim()||t.push(p("missing_card_title","Card title is required.",l.id)),l.type==="custom"&&t.push(p("custom_visual_out_of_scope","Whole-dashboard authoring supports built-in visual types only.",l.id)),l.type!=="text"&&!l.analyticsIntent&&n.push(p("missing_analytics_intent","Non-text card has no analytics intent and may be skipped by the app layer.",l.id)),fe({card:l,datasets:o,errors:t}),he({card:l,errors:t}),pe({card:l,datasets:o,errors:t});const h=Array.isArray(r.filterInputs)?r.filterInputs:[],I=h.map(l=>l.id),A=B(I);A&&t.push(p("duplicate_input_id",`Duplicate dashboard input id: ${A}.`));const w=h.map(l=>l.variableName).filter(Boolean)||[],y=B(w);y&&t.push(p("duplicate_input_variable",`Duplicate dashboard input variable name: ${y}.`));const c=Array.isArray(r.calculatedFields)?r.calculatedFields:[];for(const l of c)l.scope==="domain"&&l.reuseOnly!==!0&&t.push(p("domain_calculated_field_create_out_of_scope",`Creating domain calculated field "${l.name}" is outside MVP.`));return{ok:t.length===0,errors:t,warnings:n}}function be(e){var i;const t=[];if(!e||typeof e!="object")return{ok:!1,errors:[p("invalid_change_plan","Dashboard change plan must be a structured object.")],warnings:[]};const r=e,n=[...r.warnings||[]];r.version!==1&&t.push(p("invalid_version","Dashboard change plan version must be 1.")),(i=r.dashboardId)!=null&&i.trim()||t.push(p("missing_dashboard_id","Dashboard change plan needs a dashboard id."));const o=Array.isArray(r.datasets)?r.datasets:[],a=Array.isArray(r.operations)?r.operations:[];me({datasets:o,errors:t,requireAtLeastOne:!1});for(const d of a){if(d.kind==="unsupported"){n.push(p("unsupported_operation",d.reason||d.requestedAction));continue}d.kind==="addCard"&&d.card.type==="custom"&&t.push(p("custom_visual_out_of_scope","Whole-dashboard authoring supports built-in visual types only.",d.card.id)),d.kind==="addCard"&&(fe({card:d.card,datasets:o,errors:t}),he({card:d.card,errors:t}),pe({card:d.card,datasets:o,errors:t})),d.kind==="addCalculatedField"&&d.field.scope==="domain"&&d.field.reuseOnly!==!0&&t.push(p("domain_calculated_field_create_out_of_scope",`Creating domain calculated field "${d.field.name}" is outside MVP.`))}return{ok:t.length===0,errors:t,warnings:n}}const Be={lg:48,md:36,sm:24,xs:12,xxs:6};function Pe(e,t){let r=0,n=0,o=0;return e.map(a=>{const i=Math.min(a.w,t);r>0&&r+i>t&&(r=0,n+=o,o=0);const d={i:a.frameId,x:r,y:n,w:i,h:a.h,minW:Math.min(a.minW,t),minH:a.minH,static:!1};return r+=i,o=Math.max(o,a.h),d})}function ze(e){const t=[...e].sort((s,u)=>s.priority-u.priority),r=t.filter(s=>s.role==="kpi"),n=t.filter(s=>s.role==="chart"),o=t.filter(s=>s.role==="table"),a=t.filter(s=>s.role==="text"),i=a.slice(0,1),d=a.slice(i.length);return{kpis:r,introText:i,charts:n,tables:o,supportingText:d}}function Ee(e,t,r){return t==="xxs"||t==="xs"?r:t==="sm"?Math.min(12,r):t==="md"?e<=1||e===2?18:12:e<=1||e===2?24:e===3?16:12}function qe(e,t,r,n){return r==="xxs"||r==="xs"||r==="sm"||r==="md"||t===1||t%2===1&&e===0?n:n/2}function Ve(e){const{item:t,band:r,index:n,bandCount:o,breakpoint:a,columns:i}=e;return r==="kpi"?{...t,band:r,w:Ee(o,a,i),h:15,minW:Math.min(6,i),minH:12}:r==="table"?{...t,band:r,w:i,h:a==="xxs"||a==="xs"?34:38,minW:Math.min(12,i),minH:18}:r==="introText"?{...t,band:r,w:i,h:a==="xxs"||a==="xs"?12:10,minW:Math.min(12,i),minH:8}:r==="supportingText"?{...t,band:r,w:a==="lg"?i/2:i,h:a==="xxs"||a==="xs"?12:10,minW:Math.min(12,i),minH:8}:{...t,band:r,w:qe(n,o,a,i),h:a==="xxs"||a==="xs"?28:30,minW:Math.min(12,i),minH:16}}function T(e,t,r,n){return e.map((o,a)=>Ve({item:o,band:t,index:a,bandCount:e.length,breakpoint:r,columns:n}))}function q(e){const t=ze(e);return Object.fromEntries(v.DASHBOARD_AUTHORING_BREAKPOINTS.map(r=>{const n=Be[r],o=[...T(t.introText,"introText",r,n),...T(t.kpis,"kpi",r,n),...T(t.charts,"chart",r,n),...T(t.tables,"table",r,n),...T(t.supportingText,"supportingText",r,n)];return[r,Pe(o,n)]}))}function He(e){const t=De.normalizeAnalyticsCatalogDataType(e);return t==="datetime"?"date":t==="unknown"?"string":t}function Le(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function je(e){return Le(e)&&typeof e.filterId=="string"&&typeof e.operation=="string"&&Array.isArray(e.values)}function Ge(e){return e.filter(t=>typeof t=="string"||typeof t=="number")}function We(e){return e.filter(t=>t instanceof Date||typeof t=="string")}function X(e,t){if(t===void 0)return;const r=He(e.dataType),n=e.operation||"in";if(je(t))return{...t,filterId:e.id,name:t.name||e.column,valueType:r,dataType:e.dataType,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext};if(n==="is null"||n==="is not null")return{filterId:e.id,name:e.column,operation:n,valueType:r,values:[],dataType:e.dataType,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext};const o=Array.isArray(t)?t:[t],a=r==="date"?We(o):Ge(o);if(a.length!==0&&!((n==="between"||n==="not between")&&a.length<2))return{filterId:e.id,name:e.column,operation:n,valueType:r,values:a,dataType:e.dataType,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext}}function Ie(e,t,r){return r?{code:e,message:t,cardId:r}:{code:e,message:t}}function Ue(e,t,r){const n=(t||[]).filter(o=>o.scope==="card"&&o.targetCardId===r).map(o=>o.field).filter(Boolean);return n.length===0?e:{...e,calculatedFields:[...e.calculatedFields||[],...n]}}function U(e,t){return Array.from(new Set((e||[]).map(r=>t.get(r)).filter(r=>!!r)))}function Ke(e,t){if((e==null?void 0:e.kind)!=="cards")return e;const r=U(e.cardIds,t);return r.length>0?{...e,cardIds:r}:null}function Xe(e,t){return!e.applyToCardIds&&!e.excludeCardIds?e:{...e,...e.applyToCardIds?{applyToCardIds:U(e.applyToCardIds,t)}:{},...e.excludeCardIds?{excludeCardIds:U(e.excludeCardIds,t)}:{}}}function Je(e,t){const r={},n=[];return{inputs:(e.filterInputs||[]).flatMap((a,i)=>{const d=Ke(a.scope,t);if(d===null)return n.push(Ie("filter_input_scope_empty",`Filter input "${a.label}" was skipped because all scoped cards were skipped during query validation.`)),[];const s=X(a.filter,a.defaultValue);return s&&(r.shared??(r.shared={}),r.shared[a.id]={status:"set",value:{kind:"filter",filterValue:s}}),[{id:a.id,kind:"filter",label:a.label,variableName:a.variableName,scope:d||{kind:"allSheets",sheetKinds:["dashboard"]},runtimeScope:"shared",presentation:{placement:"toolbar",order:i},exports:["label","value","start","end","range"],filter:Xe(a.filter,t)}]}),warnings:n,defaultInputValues:r.shared&&Object.keys(r.shared).length>0?r:void 0}}function Qe(e){var w,y;const t=ge(e.plan);if(!t.ok)throw new Error(t.errors.map(c=>c.message).join(`
|
|
2
2
|
`)||"Dashboard plan is invalid.");const r=e.plan.sheets[0],n=[...t.warnings],o=[],a=new Map(e.cardArtifacts.map(c=>[c.planCardId,c])),i=new Map(e.cardArtifacts.map(c=>[c.planCardId,c.card.id])),d=[];for(const c of r.cards){const f=a.get(c.id);if(!f){const l=Ie("missing_card_artifact",`Card "${c.title}" was skipped because no generated artifact was supplied.`,c.id);o.push(l);continue}n.push(...f.warnings||[]);const g=Ue(f.card,e.plan.calculatedFields,c.id);d.push({id:c.frameId,cards:[g],activeCardId:g.id})}if(d.length===0)throw new Error("Dashboard plan did not produce any persistable cards.");const{inputs:s,defaultInputValues:u,warnings:h}=Je(e.plan,i);n.push(...h);const I=q(r.cards.filter(c=>d.some(f=>f.id===c.frameId)).map(c=>({frameId:c.frameId,priority:c.priority,role:c.role})));return{dashboard:{id:e.dashboardId,title:e.plan.title,description:e.plan.description||"",sheets:[{id:r.id,kind:"dashboard",title:r.title,description:r.description,frames:d,layouts:I,calculatedFields:(w=e.plan.calculatedFields)==null?void 0:w.filter(c=>c.scope==="sheet"&&c.field).map(c=>c.field)}],calculatedFields:(y=e.plan.calculatedFields)==null?void 0:y.filter(c=>c.scope==="dashboard"&&c.field).map(c=>c.field),inputs:s,...u?{defaultInputValues:u}:{}},warnings:n,skippedOperations:o}}function k(e,t,r){return r?{code:e,message:t,cardId:r}:{code:e,message:t}}function Ye(e){return JSON.parse(JSON.stringify(e))}function Ze(e){var t;return(t=e.sheets)==null?void 0:t.find(r=>(r.kind||"dashboard")==="dashboard")}function L(e,t){var r;for(const n of e.sheets||[])for(const o of n.frames||[]){const a=(r=o.cards)==null?void 0:r.find(i=>i.id===t);if(a)return{sheet:n,frame:o,card:a}}return null}function ye(e){var r,n;const t=(n=(r=e.cards)==null?void 0:r[0])==null?void 0:n.type;return t==="kpi"?"kpi":t==="table"||t==="detailTable"||t==="pivotTable"?"table":t==="text"?"text":"chart"}function et(e){var t;return new Map((((t=e.layouts)==null?void 0:t.lg)||[]).map((r,n)=>[r.i,n]))}function _e(e,t=new Map){const r=et(e),n=Math.max(r.size,t.size),o=(e.frames||[]).map((a,i)=>({frameId:a.id,role:ye(a),priority:t.get(a.id)??r.get(a.id)??n+i}));e.layouts=q(o)}function tt(e){return Object.values(e.layouts||{}).some(t=>t.length>0)}function rt(e,t){if(!tt(e)){_e(e);return}const r=q([{frameId:t.id,role:ye(t),priority:0}]);e.layouts??(e.layouts={});for(const[n,o]of Object.entries(r)){const a=e.layouts[n]||[];if(a.some(s=>s.i===t.id))continue;const i=o[0];if(!i)continue;const d=a.reduce((s,u)=>Math.max(s,u.y+u.h),0);e.layouts[n]=[...a,{...i,y:d}]}}function nt(e,t){var n;const r=X(t.filter,t.defaultValue);r&&(e.defaultInputValues??(e.defaultInputValues={}),(n=e.defaultInputValues).shared??(n.shared={}),e.defaultInputValues.shared[t.id]={status:"set",value:{kind:"filter",filterValue:r}})}function at(e){var d;const t=be(e.changePlan);if(!t.ok)throw new Error(t.errors.map(s=>s.message).join(`
|
|
3
3
|
`)||"Dashboard change plan is invalid.");const r=Ye(e.dashboard),n=[...t.warnings],o=[],a=new Map(e.cardArtifacts.map(s=>[s.planCardId,s])),i=Ze(r);if(!i)throw new Error("Dashboard has no editable dashboard sheet.");i.frames??(i.frames=[]);for(const s of e.changePlan.operations)switch(s.kind){case"addCard":{if((i.frames||[]).reduce((A,w)=>{var y;return A+(((y=w.cards)==null?void 0:y.length)||0)},0)>=v.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS){o.push(k("generated_card_limit_reached",`AI refinement is capped at ${v.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS} cards.`,s.card.id));break}const h=a.get(s.card.id);if(!h){o.push(k("missing_card_artifact",`Card "${s.card.title}" was skipped because no generated artifact was supplied.`,s.card.id));break}const I={id:s.card.frameId,cards:[h.card],activeCardId:h.card.id};i.frames.push(I),rt(i,I);break}case"addFilterInput":{r.inputs??(r.inputs=[]);const u={id:s.input.id,kind:"filter",label:s.input.label,variableName:s.input.variableName,scope:s.input.scope||{kind:"allSheets",sheetKinds:["dashboard"]},runtimeScope:"shared",presentation:{placement:"toolbar",order:r.inputs.length},exports:["label","value","start","end","range"],filter:s.input.filter};r.inputs.push(u),nt(r,s.input);break}case"addCalculatedField":{if(s.field.scope==="dashboard"&&s.field.field)r.calculatedFields??(r.calculatedFields=[]),r.calculatedFields.push(s.field.field);else if(s.field.scope==="sheet"&&s.field.field)i.calculatedFields??(i.calculatedFields=[]),i.calculatedFields.push(s.field.field);else if(s.field.scope==="card"&&s.field.field){const u=s.field.targetCardId?L(r,s.field.targetCardId):null;u?((d=u.card).calculatedFields??(d.calculatedFields=[]),u.card.calculatedFields.push(s.field.field)):o.push(k("missing_calculated_field_target",`Calculated field "${s.field.name}" needs a valid target card.`))}break}case"renameCard":{const u=L(r,s.cardId);if(!u){o.push(k("card_not_found",`Card "${s.cardId}" could not be renamed because it was not found.`,s.cardId));break}u.card.title=s.title,s.description!==void 0&&(u.card.description=s.description);break}case"reorderCards":{const u=new Map;for(let h=0;h<s.cardIds.length;h+=1){const I=s.cardIds[h],A=L(r,I);A&&u.set(A.frame.id,h)}_e(i,u);break}case"reuseCalculatedField":n.push(k("reused_calculated_field",`Calculated field "${s.fieldId}" is reused by reference.`));break;case"unsupported":o.push(k("unsupported_operation",s.reason||s.requestedAction));break}return{dashboard:r,warnings:n,skippedOperations:o}}function b(e,t,r){return r?{code:e,message:t,cardId:r}:{code:e,message:t}}function F(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Se(e,t){if(!t.has(e))return t.add(e),e;let r=2,n=`${e}-${r}`;for(;t.has(n);)r+=1,n=`${e}-${r}`;return t.add(n),n}function $(e){return!!(e&&typeof e=="object")}function Ae(e){return Array.isArray(e.inputs)?e.inputs.filter(t=>$(t)&&typeof t.id=="string"):[]}function J(e){return Array.isArray(e.sections)?e.sections.filter(t=>$(t)):[]}function Q(e){return Array.isArray(e.views)?e.views.filter(t=>$(t)):[]}function x(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){const n=S(r);n&&t.push(n)}return t}function it(e){var n,o;if(!e)return[];const t=[];if(M(e.source)&&t.push(e.source),e.kind==="metric"){t.push(...x(e.metrics));const a=S(e.dateField);a&&t.push(a),t.push(...x(e.dimensions)),t.push(...x((n=e.filters)==null?void 0:n.map(i=>i.field)))}else if(e.kind==="records"){const a=S(e.dateField);a&&t.push(a),t.push(...x(e.fields)),t.push(...x((o=e.filters)==null?void 0:o.map(i=>i.field)))}else if(e.kind==="inputOptions"){const a=S(e.field);a&&t.push(a)}else e.kind==="sql"&&t.push(...x(e.fields));const r="inputs"in e&&Array.isArray(e.inputs)?e.inputs:[];for(const a of r){const i=S(a.field);i&&t.push(i)}return t}function ot(e){const t=[];for(const r of Ae(e)){const n=S(r.field);n&&t.push(n)}for(const r of J(e))for(const n of Q(r))t.push(...it(n.analytics));return t}function st(e){var r;const t=[];for(const n of J(e))for(const o of Q(n))M((r=o.analytics)==null?void 0:r.source)&&t.push(o.analytics.source);return t}function dt(e,t){const r=R(e).filter(M);if(r.length===0)return t.push(b("missing_materializable_dataset","No semantic or physical source could be converted into the current dashboard authoring dataset reference.")),[];const n=r.every(a=>a.kind==="semantic"),o=Array.from(new Set(r.filter(a=>a.kind==="semantic").map(a=>a.domainId)));return r.length>1&&(!n||o.length!==1)?(t.push(b("multiple_datasets_out_of_scope","The dashboard authoring compiler supports multiple datasets only within one semantic domain; using the first source and deferring the rest.")),[r[0]]):r}function ct(e,t){const r=J(e),n=Ae(e),o=R(ot(e)),a=R(st(e));return{sections:r,inputs:n,sources:o,primarySources:a,defaultSource:a.length===1?a[0]:void 0,datasets:dt(o,t)}}function lt(e){return e&&z.validateSemaphorAnalyticsIntent(e).ok?e:void 0}function ut(e){var t;switch((t=e.presentation)==null?void 0:t.kind){case"kpi":return"kpi";case"lineChart":return"line";case"barChart":return"bar";case"areaChart":return"area";case"table":return"table";case"text":return"text";default:return null}}function ft(e){var t,r,n;return((t=e.presentation)==null?void 0:t.kind)==="kpi"?"kpi":((r=e.presentation)==null?void 0:r.kind)==="table"?"table":((n=e.presentation)==null?void 0:n.kind)==="text"?"text":"chart"}function pt(e){const t=z.normalizeSemaphorInputOperator(e);switch(t){case"not_in":return"not in";case"not_between":return"not between";case"contains":return"like";case"not_contains":return"not like";default:return t||"in"}}function ht(e){return $(e.field)?e.field.dataType==="datetime"?"date":e.field.dataType||"string":"string"}function mt(e){if(!(!e||e.kind!=="physical"))return[e.databaseName,e.schemaName,e.tableName].filter(Boolean).join(".")}function gt(e,t,r,n,o,a){if(e.kind!=="filter")return a.push(b("control_inputs_deferred",`Control input "${e.label}" is represented in the protocol but not yet materialized by the dashboard authoring adapter.`)),null;if(!$(e.field)||typeof e.field.name!="string")return a.push(b("filter_requires_field",`Filter "${e.label||e.id}" needs a field before the dashboard compiler can materialize it.`)),null;const i=de({explicitSource:void 0,field:e.field,defaultSource:t,fallbackSources:r}),d=(i==null?void 0:i.kind)==="semantic"||(i==null?void 0:i.kind)==="physical"?i.connectionId:void 0;if(!d)return a.push(b("filter_requires_connection_id",`Filter "${e.label}" needs a source connectionId before the dashboard compiler can materialize it.`)),null;const h={id:`filter-${Se(F(e.id,e.field.name),o)}`,variableName:e.id,connectionId:d,title:e.label,column:e.field.name,dataType:ht(e),qualifiedTableName:mt(i),sql:"",operation:pt(e.operator),type:e.multi===!1?"single":"multiple",location:"dashboard",displayMode:"toolbar",fieldMeta:(i==null?void 0:i.kind)==="semantic"?{name:e.field.name,qualifiedFieldName:e.field.name,dataType:e.field.dataType,role:e.field.role==="measure"?"metric":"groupby"}:void 0,semanticContext:(i==null?void 0:i.kind)==="semantic"?{semanticDomainId:i.domainId,connectionId:i.connectionId}:void 0};return{id:e.id,label:e.label,variableName:e.id,scope:n,filter:h,defaultValue:X(h,e.defaultValue)}}function j(e){const t=[],r=[];for(const n of e.viewIds){const o=e.viewIdToCardId.get(n);o?t.push(o):r.push(n)}return r.length>0&&e.warnings.push(b("input_scope_view_not_found",`Filter "${e.inputLabel}" referenced unknown view ids: ${r.join(", ")}.`)),Array.from(new Set(t))}function bt(e){var n,o;if(!e.protocolScope){const a=Array.from(new Set(e.boundCardIds));return a.length>0&&a.length<e.allCardIds.length?{kind:"cards",cardIds:a}:void 0}if(e.protocolScope.level==="dashboard"){if(!((n=e.protocolScope.excludeViewIds)!=null&&n.length))return;const a=new Set(j({inputLabel:e.inputLabel,viewIds:e.protocolScope.excludeViewIds,viewIdToCardId:e.viewIdToCardId,warnings:e.warnings}));return{kind:"cards",cardIds:e.allCardIds.filter(i=>!a.has(i))}}if(e.protocolScope.level==="view"){const a=j({inputLabel:e.inputLabel,viewIds:e.protocolScope.viewIds,viewIdToCardId:e.viewIdToCardId,warnings:e.warnings});return a.length===0?(e.warnings.push(b("input_scope_has_no_materialized_cards",`Filter "${e.inputLabel}" was deferred because its view scope does not match any materialized cards.`)),null):{kind:"cards",cardIds:a}}const t=e.sectionIdToCardIds.get(e.protocolScope.sectionId)||[];if(t.length===0)return e.warnings.push(b("input_scope_section_not_found",`Filter "${e.inputLabel}" was deferred because section "${e.protocolScope.sectionId}" does not match any materialized cards.`)),null;if(!((o=e.protocolScope.excludeViewIds)!=null&&o.length))return{kind:"cards",cardIds:t};const r=new Set(j({inputLabel:e.inputLabel,viewIds:e.protocolScope.excludeViewIds,viewIdToCardId:e.viewIdToCardId,warnings:e.warnings}));return{kind:"cards",cardIds:t.filter(a=>!r.has(a))}}function It(e){var w,y,c;const t=[],r=z.validateSemaphorDashboardIntent(e);for(const f of r.warnings)t.push(b(f.code,f.message));for(const f of r.errors)t.push(b(f.code,f.message));const n=ct(e,t),o=[],a=new Map,i=new Map,d=new Map,s=new Set,u=new Set;let h=0;for(const[f,g]of n.sections.entries()){const l=typeof g.title=="string"?g.title:`Section ${f+1}`,Y=g.id||F(l,`section-${f+1}`);i.set(Y,[]);for(const[Z,m]of Q(g).entries()){const ee=ut(m),V=F(m.id||`${l}-${m.title||`View ${Z+1}`}`,`card-${f+1}-${Z+1}`);if(!ee){t.push(b("unsupported_presentation",`Dashboard presentation "${((w=m.presentation)==null?void 0:w.kind)||"unknown"}" is not supported by the dashboard authoring adapter.`,`card-${V}`));continue}if(((y=m.analytics)==null?void 0:y.kind)==="sql"){t.push(b("sql_intent_deferred","SQL analytics intent is valid protocol, but the current dashboard authoring adapter only materializes semantic and physical config-card intents.",`card-${V}`));continue}const te=Se(V,s),O=`card-${te}`;m.id&&a.set(m.id,O),(c=i.get(Y))==null||c.push(O);const we=m.analytics&&"inputs"in m.analytics?m.analytics.inputs:void 0;for(const re of we||[]){const ne=d.get(re.inputId)||[];ne.push(O),d.set(re.inputId,ne)}o.push({id:O,frameId:`frame-${te}`,title:m.title,description:m.description,type:ee,role:ft(m),priority:h,section:l,analyticsIntent:lt(m.analytics),text:m.text}),h+=1}}const I=n.inputs.map(f=>{const g=bt({protocolScope:f.scope,inputLabel:f.label,allCardIds:o.map(l=>l.id),boundCardIds:d.get(f.id)||[],viewIdToCardId:a,sectionIdToCardIds:i,warnings:t});return g===null?null:gt(f,n.defaultSource,n.sources,g,u,t)}).filter(f=>!!f);return{plan:{version:1,id:`plan-${F(e.title,"dashboard")}`,title:e.title,description:e.description,datasets:n.datasets,sheets:[{id:`sheet-${F(e.title,"dashboard")}`,title:e.title,description:e.description,kind:"dashboard",cards:o}],filterInputs:I.length?I:void 0,warnings:t.length?t:void 0,unresolvedRequests:r.ok?void 0:r.errors.map(f=>f.message)},warnings:t}}exports.DASHBOARD_AUTHORING_BREAKPOINTS=v.DASHBOARD_AUTHORING_BREAKPOINTS;exports.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS=v.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS;exports.applyDashboardChangePlan=at;exports.compileDashboardFromPlan=Qe;exports.compileResponsiveDashboardLayouts=q;exports.dashboardAuthoringDatasetMatchesSource=E;exports.dashboardAuthoringFieldsReferToSameTarget=ke;exports.dashboardAuthoringSourceFromField=S;exports.dashboardAuthoringSourceKey=ve;exports.dashboardAuthoringSourcesReferToSameDataset=K;exports.dashboardPlanFromSemaphorDashboardIntent=It;exports.findDashboardAuthoringDatasetForSource=$e;exports.getDashboardAuthoringCardSource=le;exports.isMaterializableDashboardAuthoringSource=M;exports.isSemaphorSourceRef=oe;exports.mergeDashboardAuthoringSources=R;exports.preferDashboardAuthoringSourceMetadata=se;exports.preferredDashboardAuthoringSource=Ce;exports.resolveDashboardAuthoringSource=de;exports.validateDashboardAuthoringDatasetScope=ue;exports.validateDashboardChangePlan=be;exports.validateDashboardPlan=ge;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { D as B, a as be } from "../chunks/contracts-CoCOpd_i.js";
|
|
2
2
|
import { s as Ie, a as E, p as ye } from "../chunks/source-identity-Dj3dryN9.js";
|
|
3
|
-
import { v as ae, d as _e, n as we } from "../chunks/validators-
|
|
3
|
+
import { v as ae, d as _e, n as we } from "../chunks/validators-DBNa-eb1.js";
|
|
4
4
|
import { b as ve } from "../chunks/catalog-field-grounding-DoEBOXQd.js";
|
|
5
5
|
function _(e) {
|
|
6
6
|
return e && typeof e == "object" ? e : null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("../chunks/validation-Dsf7PydY.js"),T=require("../chunks/index-BxM99sFL.js"),d=require("react"),j=require("react/jsx-runtime"),z=require("../chunks/validators-oc8qtP4q.js"),M=["records","changes","drivers","largestNegativeChanges","largestPositiveChanges","largestNegativeDrivers","largestPositiveDrivers"],Q=["records","changes","drivers","largestNegativeChanges","largestPositiveChanges","largestNegativeDrivers","largestPositiveDrivers"];function O(e){if(!e)return{};const t=L(e.executionResult),n=$(e,t),r=U(n);return{...e,...Object.keys(n).length?{resultSets:n}:{},...r?{columns:r.columns,records:r.records,rowCount:r.rowCount}:{}}}function $(e,t){const n=N(e.resultSets);for(const u of M){if(n[u]){n[u]=C(n[u]);continue}const s=J(e[u]);if(!s.length)continue;const a=t.length?t:Y(s);n[u]={records:E(s,a),columns:a,rowCount:s.length}}const r=B(e.executionResult);return r&&r.records.length>0&&!n.records&&(n.records=r),n}function N(e){return Object.fromEntries(Object.entries(e||{}).map(([t,n])=>[t,C(n)]))}function C(e){var t;return{...e,records:E(e.records||[],e.columns||[]),rowCount:e.rowCount??((t=e.records)==null?void 0:t.length)??0}}function U(e){var t;for(const n of Q)if((t=e[n])!=null&&t.records.length)return e[n];return Object.values(e).find(n=>n.records.length)||Object.values(e)[0]}function B(e){const t=e==null?void 0:e.result;if(!(!t||t.kind!=="records"&&t.kind!=="sql"))return{records:E(t.records,t.columns),columns:t.columns,rowCount:t.rowCount??t.records.length}}function L(e){const t=e==null?void 0:e.result;return!t||t.kind!=="records"&&t.kind!=="sql"?[]:t.columns}function J(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object"&&!Array.isArray(t))):[]}function E(e,t){return t.length?e.map(n=>{const r={};return t.forEach((u,s)=>{const a=W(n,{name:u.key,label:u.label,fallbackNames:[u.name,Object.keys(n)[s]]});a!==void 0&&(r[u.key]=a)}),Object.keys(r).length?r:n}):e}function Y(e){return Array.from(new Set(e.flatMap(n=>Object.keys(n)))).map(n=>({key:n,name:n,label:n}))}function W(e,t){const n=[t.name,t.label,...t.fallbackNames||[]].filter(r=>!!r);for(const r of n)if(Object.prototype.hasOwnProperty.call(e,r))return e[r]}function H(e){return e}function F(e){return e}const G={filter(e){return{...e,kind:"filter"}},control(e){return{...e,kind:"control"}},sqlParam(e){return{...e,kind:"control",role:"sqlParam"}},metric(e){return{...e,queryKind:"metric"}},analysis(e){return{...e,queryKind:"analysis"}},records(e){return{...e,queryKind:"records"}},inputOptions(e){return{...e,queryKind:"inputOptions"}},sql(e){return{...e,queryKind:"sql"}}};function P(){return{executeAnalysis:(e,t,n)=>S(e,t,n??{}).then(O),executeMetric:(e,t)=>S(e,t),executeRecords:(e,t)=>S(e,t),executeInputOptions:(e,t)=>S(e,t),executeSql:(e,t)=>S(e,t)}}async function S(e,t,n){if(!t.token)throw new Error("SemaphorDataAppProvider needs a token to execute queries.");const r=await fetch(ee(t),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.token}`},body:JSON.stringify({intent:e,activeInputs:t.activeInputs,...n?{analysisOptions:n}:{},resultShape:e.kind})}),u=await X(r);if(!r.ok||u.error)throw new Error(u.error||`Semaphor Data App execution failed with status ${r.status}.`);return u}async function X(e){const t=await e.text().catch(()=>"");if(!t.trim())return e.ok?{error:"Semaphor Data App execution returned an empty response."}:{};try{return JSON.parse(t)}catch{return e.ok?{error:"Semaphor Data App execution returned invalid JSON.",details:t}:{error:Z(e,t),details:t}}}function Z(e,t){const n=e.statusText?` ${e.statusText}`:"",r=t.replace(/\s+/g," ").trim();return r?`Semaphor Data App execution failed with status ${e.status}${n}: ${r.slice(0,240)}`:`Semaphor Data App execution failed with status ${e.status}${n}.`}function ee(e){const t=te(e).replace(/\/+$/,"");return t?t.endsWith("/api")?`${t}/v1/data-app/execute`:`${t}/api/v1/data-app/execute`:"/api/v1/data-app/execute"}function te(e){if(e.apiBaseUrl)return e.apiBaseUrl;if(!e.token)return"";try{return T.jwtDecode(e.token).apiServiceUrl||""}catch{return""}}const R=d.createContext({});function V(){if(!(typeof window>"u"))return window.__SEMAPHOR_DATA_APP_RUNTIME__}function _(){return d.useContext(R)}function re({token:e,apiBaseUrl:t,executor:n,children:r}){var o;const u=V(),s=((o=u==null?void 0:u.authToken)==null?void 0:o.accessToken)||e,a=(u==null?void 0:u.dataApiBaseUrl)||(u==null?void 0:u.apiBaseUrl)||t,m=d.useMemo(()=>P(),[]),c=n||m,l=d.useMemo(()=>({token:s,apiBaseUrl:a,executor:c}),[a,c,s]);return j.jsx(R.Provider,{value:l,children:r})}const I={value:null},g={},ne={records:[]},k={options:[]},oe={records:[]};function ue(e){const t=i.toSemaphorActiveInputSnapshots(e.inputs),n=i.toSemaphorAnalysisQueryOptions(e);try{const r=i.toSemaphorAnalysisIntent(e),u=y(r);return u?{error:u,activeInputs:t,analysisOptions:n,queryKey:h(void 0,t,u,n),idleData:g}:{intent:r,error:null,activeInputs:t,analysisOptions:n,queryKey:h(r,t,void 0,n),idleData:g}}catch(r){const u=f(r);return{error:u,activeInputs:t,analysisOptions:n,queryKey:h(void 0,t,u,n),idleData:g}}}function ie(e){const t=i.toSemaphorActiveInputSnapshots(e.inputs);try{const n=i.toSemaphorMetricIntent(e),r=y(n);return r?{error:r,activeInputs:t,queryKey:h(void 0,t,r),idleData:I}:{intent:n,error:null,activeInputs:t,queryKey:h(n,t),idleData:I}}catch(n){const r=f(n);return{error:r,activeInputs:t,queryKey:h(void 0,t,r),idleData:I}}}function se(e){const t=i.toSemaphorActiveInputSnapshots(e.inputs),n=ne;try{const r=i.toSemaphorRecordsIntent(e),u=y(r);return u?{error:u,activeInputs:t,queryKey:h(void 0,t,u),idleData:n}:{intent:r,error:null,activeInputs:t,queryKey:h(r,t),idleData:n}}catch(r){const u=f(r);return{error:u,activeInputs:t,queryKey:h(void 0,t,u),idleData:n}}}function ae(e){try{const t=i.toSemaphorInputOptionsIntent(e),n=y(t);return n?{error:n,queryKey:h(void 0,void 0,n),idleData:k}:{intent:t,error:null,queryKey:h(t),idleData:k}}catch(t){const n=f(t);return{error:n,queryKey:h(void 0,void 0,n),idleData:k}}}function ce(e){const t=i.toSemaphorActiveInputSnapshots(e.inputs),n=oe;try{const r=i.toSemaphorSqlIntent(e),u=y(r);return u?{error:u,activeInputs:t,queryKey:h(void 0,t,u),idleData:n}:{intent:r,error:null,activeInputs:t,queryKey:h(r,t),idleData:n}}catch(r){const u=f(r);return{error:u,activeInputs:t,queryKey:h(void 0,t,u),idleData:n}}}function f(e){return e instanceof Error?e:new Error(String(e))}function y(e){const t=z.validateSemaphorAnalyticsIntent(e);if(t.ok)return null;const n=t.errors.map(r=>r.path?`${r.code} at ${r.path}: ${r.message}`:`${r.code}: ${r.message}`).join("; ");return new Error(`Invalid Semaphor analytics intent. ${n}`)}function h(e,t,n,r){return JSON.stringify({intent:e,activeInputs:t,analysisOptions:r,error:n==null?void 0:n.message})}function le(e){const[t,n]=d.useState(e.defaultValue),r=Object.prototype.hasOwnProperty.call(e,"value"),u=r?e.value:t,s=d.useMemo(()=>i.normalizeSemaphorInputOptions(e.options),[e.options]),a=d.useCallback(c=>{var o;const l=c;(o=e.onValueChange)==null||o.call(e,l),r||n(l)},[r,e]),m=d.useCallback(()=>a(void 0),[a]);return d.useMemo(()=>{const c=i.toSemaphorInputSpec(e);return{id:e.id,kind:e.kind,label:e.label,field:c.field,operator:c.operator,controlRole:e.kind==="control"?e.role:void 0,value:u,options:s,isActive:i.hasSemaphorInputValue(u),setValue:a,clear:m,toAnalyticsInput:()=>({inputId:c.inputId,field:c.field,kind:e.kind,label:e.label,value:u,isActive:i.hasSemaphorInputValue(u),operator:c.operator,controlRole:e.kind==="control"?e.role:void 0})}},[m,s,a,e,u])}function de(e){const[t,n]=d.useState(()=>he(e));return d.useEffect(()=>{n(r=>{let u=r;for(const s of e)!Object.prototype.hasOwnProperty.call(u,s.id)&&s.defaultValue!==void 0&&(u={...u,[s.id]:s.defaultValue});return u})},[e]),d.useMemo(()=>e.map(r=>{const u=Object.prototype.hasOwnProperty.call(r,"value"),s=u?r.value:t[r.id],a=i.normalizeSemaphorInputOptions(r.options),m=o=>{var p;(p=r.onValueChange)==null||p.call(r,o),u||n(v=>({...v,[r.id]:o}))},c=()=>m(void 0),l=i.toSemaphorInputSpec(r);return{id:r.id,kind:r.kind,label:r.label,field:l.field,operator:l.operator,controlRole:r.kind==="control"?r.role:void 0,value:s,options:a,isActive:i.hasSemaphorInputValue(s),setValue:m,clear:c,toAnalyticsInput:()=>({inputId:l.inputId,field:l.field,kind:r.kind,label:r.label,value:s,isActive:i.hasSemaphorInputValue(s),operator:l.operator,controlRole:r.kind==="control"?r.role:void 0})}}),[e,t])}function pe(e,t={}){const n=d.useMemo(()=>t.inputs?{...e,inputs:t.inputs}:e,[t.inputs,e]),r=d.useMemo(()=>{switch(n.queryKind){case"metric":return{queryKind:n.queryKind,request:ie(n)};case"analysis":return{queryKind:n.queryKind,request:ue(n)};case"records":return{queryKind:n.queryKind,request:se(n)};case"inputOptions":return{queryKind:n.queryKind,request:ae(n)};case"sql":return{queryKind:n.queryKind,request:ce(n)};default:return D(n)}},[n]),u=d.useCallback(o=>{var v,q,b,K,x,A,w;const p=r.request;if(p.intent)switch(r.queryKind){case"metric":return(v=o.executor)==null?void 0:v.executeMetric(p.intent,o);case"analysis":return(b=(q=o.executor)==null?void 0:q.executeAnalysis)==null?void 0:b.call(q,p.intent,o,p.analysisOptions);case"records":return(K=o.executor)==null?void 0:K.executeRecords(p.intent,o);case"inputOptions":return(x=o.executor)==null?void 0:x.executeInputOptions(p.intent,o);case"sql":return(w=(A=o.executor)==null?void 0:A.executeSql)==null?void 0:w.call(A,p.intent,o);default:return D(r)}},[r]),s=me(r.request.queryKey,u,r.request.idleData,r.request.activeInputs),a=r.request.error?r.request.idleData:s.data,m=r.request.error?"error":s.status,c=!r.request.error&&s.status==="loading",l=r.request.error||s.error;switch(r.queryKind){case"metric":{const o=a;return{id:n.id,intent:r.request.intent,value:(o==null?void 0:o.value)??null,metrics:o==null?void 0:o.metrics,comparisonValue:o==null?void 0:o.comparisonValue,delta:o==null?void 0:o.delta,deltaPercent:o==null?void 0:o.deltaPercent,records:o==null?void 0:o.records,executionResult:o==null?void 0:o.executionResult,status:m,isLoading:c,error:l}}case"analysis":{const o=O(a);return{id:n.id,intent:r.request.intent,...o||{},status:m,isLoading:c,error:l}}case"records":{const o=a;return{id:n.id,intent:r.request.intent,records:(o==null?void 0:o.records)||[],columns:o==null?void 0:o.columns,rowCount:o==null?void 0:o.rowCount,pagination:o==null?void 0:o.pagination,executionResult:o==null?void 0:o.executionResult,status:m,isLoading:c,error:l}}case"inputOptions":{const o=a;return{id:n.id,intent:r.request.intent,options:(o==null?void 0:o.options)||[],executionResult:o==null?void 0:o.executionResult,status:m,isLoading:c,error:l}}case"sql":{const o=a;return{id:n.id,intent:r.request.intent,records:(o==null?void 0:o.records)||[],columns:o==null?void 0:o.columns,rowCount:o==null?void 0:o.rowCount,pagination:o==null?void 0:o.pagination,output:o==null?void 0:o.output,rowLimitExceeded:o==null?void 0:o.rowLimitExceeded,executionResult:o==null?void 0:o.executionResult,status:m,isLoading:c,error:l}}default:return D(r)}}function me(e,t,n,r){const u=_(),s=d.useRef(t),a=d.useRef(r),[m,c]=d.useState({status:"idle",data:n,error:null});return s.current=t,a.current=r,d.useEffect(()=>{let l;try{l=s.current({...u,activeInputs:a.current})}catch(p){c({status:"error",data:n,error:f(p)});return}if(!l){c({status:"idle",data:n,error:null});return}let o=!1;return c(p=>({status:"loading",data:p.data,error:null})),l.then(p=>{o||c({status:"success",data:p,error:null})}).catch(p=>{o||c({status:"error",data:n,error:f(p)})}),()=>{o=!0}},[n,e,u]),m}function he(e){return Object.fromEntries(e.filter(t=>t.defaultValue!==void 0).map(t=>[t.id,t.defaultValue]))}function D(e){throw new Error(`Unsupported Semaphor query kind: ${JSON.stringify(e)}`)}exports.hasSemaphorInputValue=i.hasSemaphorInputValue;exports.normalizeSemaphorAnalysisQueryOptions=i.normalizeSemaphorAnalysisQueryOptions;exports.normalizeSemaphorInputOptions=i.normalizeSemaphorInputOptions;exports.toSemaphorActiveInputSnapshots=i.toSemaphorActiveInputSnapshots;exports.toSemaphorAnalysisIntent=i.toSemaphorAnalysisIntent;exports.toSemaphorAnalysisQueryOptions=i.toSemaphorAnalysisQueryOptions;exports.toSemaphorInputBinding=i.toSemaphorInputBinding;exports.toSemaphorInputBindings=i.toSemaphorInputBindings;exports.toSemaphorInputOptionsIntent=i.toSemaphorInputOptionsIntent;exports.toSemaphorInputSnapshots=i.toSemaphorInputSnapshots;exports.toSemaphorInputSpec=i.toSemaphorInputSpec;exports.toSemaphorMetricIntent=i.toSemaphorMetricIntent;exports.toSemaphorRecordsIntent=i.toSemaphorRecordsIntent;exports.toSemaphorSqlIntent=i.toSemaphorSqlIntent;exports.validateSemaphorDataAppQuerySpecs=i.validateSemaphorDataAppQuerySpecs;exports.SemaphorDataAppContext=R;exports.SemaphorDataAppProvider=re;exports.createSemaphorQueryExecutor=P;exports.defineSemaphorDataApp=H;exports.defineSemaphorInput=F;exports.normalizeSemaphorAnalysisPayload=O;exports.readWindowRuntime=V;exports.semaphor=G;exports.useSemaphorDataAppRuntime=_;exports.useSemaphorInput=le;exports.useSemaphorInputs=de;exports.useSemaphorQuery=pe;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("../chunks/validation-DYL3ArlL.js"),z=require("../chunks/index-BxM99sFL.js"),p=require("react"),Q=require("react/jsx-runtime"),$=require("../chunks/validators-CgxWT8UX.js"),N=["records","changes","drivers","largestNegativeChanges","largestPositiveChanges","largestNegativeDrivers","largestPositiveDrivers"],U=["records","changes","drivers","largestNegativeChanges","largestPositiveChanges","largestNegativeDrivers","largestPositiveDrivers"];function O(e){if(!e)return{};const t=W(e.executionResult),n=B(e,t),r=J(n);return{...e,...Object.keys(n).length?{resultSets:n}:{},...r?{columns:r.columns,records:r.records,rowCount:r.rowCount}:{}}}function B(e,t){const n=L(e.resultSets);for(const i of N){if(n[i]){n[i]=_(n[i]);continue}const a=H(e[i]);if(!a.length)continue;const s=t.length?t:F(a);n[i]={records:R(a,s),columns:s,rowCount:a.length}}const r=Y(e.executionResult);return r&&r.records.length>0&&!n.records&&(n.records=r),n}function L(e){return Object.fromEntries(Object.entries(e||{}).map(([t,n])=>[t,_(n)]))}function _(e){var t;return{...e,records:R(e.records||[],e.columns||[]),rowCount:e.rowCount??((t=e.records)==null?void 0:t.length)??0}}function J(e){var t;for(const n of U)if((t=e[n])!=null&&t.records.length)return e[n];return Object.values(e).find(n=>n.records.length)||Object.values(e)[0]}function Y(e){const t=e==null?void 0:e.result;if(!(!t||t.kind!=="records"&&t.kind!=="sql"))return{records:R(t.records,t.columns),columns:t.columns,rowCount:t.rowCount??t.records.length}}function W(e){const t=e==null?void 0:e.result;return!t||t.kind!=="records"&&t.kind!=="sql"?[]:t.columns}function H(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object"&&!Array.isArray(t))):[]}function R(e,t){return t.length?e.map(n=>{const r={};return t.forEach((i,a)=>{const s=X(n,{name:i.key,label:i.label,fallbackNames:[i.name,Object.keys(n)[a]]});s!==void 0&&(r[i.key]=s)}),Object.keys(r).length?r:n}):e}function F(e){return Array.from(new Set(e.flatMap(n=>Object.keys(n)))).map(n=>({key:n,name:n,label:n}))}function X(e,t){const n=[t.name,t.label,...t.fallbackNames||[]].filter(r=>!!r);for(const r of n)if(Object.prototype.hasOwnProperty.call(e,r))return e[r]}function G(e){return e}function Z(e){return e}const ee={filter(e){return{...e,kind:"filter"}},control(e){return{...e,kind:"control"}},sqlParam(e){return{...e,kind:"control",role:"sqlParam"}},metric(e){return{...e,queryKind:"metric"}},analysis(e){return{...e,queryKind:"analysis"}},records(e){return{...e,queryKind:"records"}},inputOptions(e){return{...e,queryKind:"inputOptions"}},sql(e){return{...e,queryKind:"sql"}},matrix(e){return{...e,queryKind:"matrix"}}};function T(){return{executeAnalysis:(e,t,n)=>S(e,t,n??{}).then(O),executeMetric:(e,t)=>S(e,t),executeRecords:(e,t)=>S(e,t),executeInputOptions:(e,t)=>S(e,t),executeSql:(e,t)=>S(e,t),executeMatrix:(e,t)=>S(e,t)}}async function S(e,t,n){if(!t.token)throw new Error("SemaphorDataAppProvider needs a token to execute queries.");const r=await fetch(ne(t),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.token}`},body:JSON.stringify({intent:e,activeInputs:t.activeInputs,...n?{analysisOptions:n}:{},resultShape:e.kind})}),i=await te(r);if(!r.ok||i.error)throw new Error(i.error||`Semaphor Data App execution failed with status ${r.status}.`);return i}async function te(e){const t=await e.text().catch(()=>"");if(!t.trim())return e.ok?{error:"Semaphor Data App execution returned an empty response."}:{};try{return JSON.parse(t)}catch{return e.ok?{error:"Semaphor Data App execution returned invalid JSON.",details:t}:{error:re(e,t),details:t}}}function re(e,t){const n=e.statusText?` ${e.statusText}`:"",r=t.replace(/\s+/g," ").trim();return r?`Semaphor Data App execution failed with status ${e.status}${n}: ${r.slice(0,240)}`:`Semaphor Data App execution failed with status ${e.status}${n}.`}function ne(e){const t=oe(e).replace(/\/+$/,"");return t?t.endsWith("/api")?`${t}/v1/data-app/execute`:`${t}/api/v1/data-app/execute`:"/api/v1/data-app/execute"}function oe(e){if(e.apiBaseUrl)return e.apiBaseUrl;if(!e.token)return"";try{return z.jwtDecode(e.token).apiServiceUrl||""}catch{return""}}const K=p.createContext({});function V(){if(!(typeof window>"u"))return window.__SEMAPHOR_DATA_APP_RUNTIME__}function j(){return p.useContext(K)}function ie({token:e,apiBaseUrl:t,executor:n,children:r}){var o;const i=V(),a=((o=i==null?void 0:i.authToken)==null?void 0:o.accessToken)||e,s=(i==null?void 0:i.dataApiBaseUrl)||(i==null?void 0:i.apiBaseUrl)||t,h=p.useMemo(()=>T(),[]),c=n||h,l=p.useMemo(()=>({token:a,apiBaseUrl:s,executor:c}),[s,c,a]);return Q.jsx(K.Provider,{value:l,children:r})}const g={value:null},D={},ue={records:[]},k={options:[]},ae={records:[]},x={};function se(e){const t=u.toSemaphorActiveInputSnapshots(e.inputs),n=u.toSemaphorAnalysisQueryOptions(e);try{const r=u.toSemaphorAnalysisIntent(e),i=y(r);return i?{error:i,activeInputs:t,analysisOptions:n,queryKey:m(void 0,t,i,n),idleData:D}:{intent:r,error:null,activeInputs:t,analysisOptions:n,queryKey:m(r,t,void 0,n),idleData:D}}catch(r){const i=f(r);return{error:i,activeInputs:t,analysisOptions:n,queryKey:m(void 0,t,i,n),idleData:D}}}function ce(e){const t=u.toSemaphorActiveInputSnapshots(e.inputs);try{const n=u.toSemaphorMetricIntent(e),r=y(n);return r?{error:r,activeInputs:t,queryKey:m(void 0,t,r),idleData:g}:{intent:n,error:null,activeInputs:t,queryKey:m(n,t),idleData:g}}catch(n){const r=f(n);return{error:r,activeInputs:t,queryKey:m(void 0,t,r),idleData:g}}}function le(e){const t=u.toSemaphorActiveInputSnapshots(e.inputs),n=ue;try{const r=u.toSemaphorRecordsIntent(e),i=y(r);return i?{error:i,activeInputs:t,queryKey:m(void 0,t,i),idleData:n}:{intent:r,error:null,activeInputs:t,queryKey:m(r,t),idleData:n}}catch(r){const i=f(r);return{error:i,activeInputs:t,queryKey:m(void 0,t,i),idleData:n}}}function de(e){try{const t=u.toSemaphorInputOptionsIntent(e),n=y(t);return n?{error:n,queryKey:m(void 0,void 0,n),idleData:k}:{intent:t,error:null,queryKey:m(t),idleData:k}}catch(t){const n=f(t);return{error:n,queryKey:m(void 0,void 0,n),idleData:k}}}function pe(e){const t=u.toSemaphorActiveInputSnapshots(e.inputs),n=ae;try{const r=u.toSemaphorSqlIntent(e),i=y(r);return i?{error:i,activeInputs:t,queryKey:m(void 0,t,i),idleData:n}:{intent:r,error:null,activeInputs:t,queryKey:m(r,t),idleData:n}}catch(r){const i=f(r);return{error:i,activeInputs:t,queryKey:m(void 0,t,i),idleData:n}}}function me(e){const t=u.toSemaphorActiveInputSnapshots(e.inputs);try{const n=u.toSemaphorMatrixIntent(e),r=y(n);return r?{error:r,activeInputs:t,queryKey:m(void 0,t,r),idleData:x}:{intent:n,error:null,activeInputs:t,queryKey:m(n,t),idleData:x}}catch(n){const r=f(n);return{error:r,activeInputs:t,queryKey:m(void 0,t,r),idleData:x}}}function f(e){return e instanceof Error?e:new Error(String(e))}function y(e){const t=$.validateSemaphorAnalyticsIntent(e);if(t.ok)return null;const n=t.errors.map(r=>r.path?`${r.code} at ${r.path}: ${r.message}`:`${r.code}: ${r.message}`).join("; ");return new Error(`Invalid Semaphor analytics intent. ${n}`)}function m(e,t,n,r){return JSON.stringify({intent:e,activeInputs:t,analysisOptions:r,error:n==null?void 0:n.message})}function he(e){const[t,n]=p.useState(e.defaultValue),r=Object.prototype.hasOwnProperty.call(e,"value"),i=r?e.value:t,a=p.useMemo(()=>u.normalizeSemaphorInputOptions(e.options),[e.options]),s=p.useCallback(c=>{var o;const l=c;(o=e.onValueChange)==null||o.call(e,l),r||n(l)},[r,e]),h=p.useCallback(()=>s(void 0),[s]);return p.useMemo(()=>{const c=u.toSemaphorInputSpec(e);return{id:e.id,kind:e.kind,label:e.label,field:c.field,operator:c.operator,controlRole:e.kind==="control"?e.role:void 0,value:i,options:a,isActive:u.hasSemaphorInputValue(i),setValue:s,clear:h,toAnalyticsInput:()=>({inputId:c.inputId,field:c.field,kind:e.kind,label:e.label,value:i,isActive:u.hasSemaphorInputValue(i),operator:c.operator,controlRole:e.kind==="control"?e.role:void 0})}},[h,a,s,e,i])}function fe(e){const[t,n]=p.useState(()=>ve(e));return p.useEffect(()=>{n(r=>{let i=r;for(const a of e)!Object.prototype.hasOwnProperty.call(i,a.id)&&a.defaultValue!==void 0&&(i={...i,[a.id]:a.defaultValue});return i})},[e]),p.useMemo(()=>e.map(r=>{const i=Object.prototype.hasOwnProperty.call(r,"value"),a=i?r.value:t[r.id],s=u.normalizeSemaphorInputOptions(r.options),h=o=>{var d;(d=r.onValueChange)==null||d.call(r,o),i||n(v=>({...v,[r.id]:o}))},c=()=>h(void 0),l=u.toSemaphorInputSpec(r);return{id:r.id,kind:r.kind,label:r.label,field:l.field,operator:l.operator,controlRole:r.kind==="control"?r.role:void 0,value:a,options:s,isActive:u.hasSemaphorInputValue(a),setValue:h,clear:c,toAnalyticsInput:()=>({inputId:l.inputId,field:l.field,kind:r.kind,label:r.label,value:a,isActive:u.hasSemaphorInputValue(a),operator:l.operator,controlRole:r.kind==="control"?r.role:void 0})}}),[e,t])}function Se(e,t={}){const n=p.useMemo(()=>t.inputs?{...e,inputs:t.inputs}:e,[t.inputs,e]),r=p.useMemo(()=>{switch(n.queryKind){case"metric":return{queryKind:n.queryKind,request:ce(n)};case"analysis":return{queryKind:n.queryKind,request:se(n)};case"records":return{queryKind:n.queryKind,request:le(n)};case"inputOptions":return{queryKind:n.queryKind,request:de(n)};case"sql":return{queryKind:n.queryKind,request:pe(n)};case"matrix":return{queryKind:n.queryKind,request:me(n)};default:return E(n)}},[n]),i=p.useCallback(o=>{var v,q,b,w,C,I,M,A,P;const d=r.request;if(d.intent)switch(r.queryKind){case"metric":return(v=o.executor)==null?void 0:v.executeMetric(d.intent,o);case"analysis":return(b=(q=o.executor)==null?void 0:q.executeAnalysis)==null?void 0:b.call(q,d.intent,o,d.analysisOptions);case"records":return(w=o.executor)==null?void 0:w.executeRecords(d.intent,o);case"inputOptions":return(C=o.executor)==null?void 0:C.executeInputOptions(d.intent,o);case"sql":return(M=(I=o.executor)==null?void 0:I.executeSql)==null?void 0:M.call(I,d.intent,o);case"matrix":return(P=(A=o.executor)==null?void 0:A.executeMatrix)==null?void 0:P.call(A,d.intent,o);default:return E(r)}},[r]),a=ye(r.request.queryKey,i,r.request.idleData,r.request.activeInputs),s=r.request.error?r.request.idleData:a.data,h=r.request.error?"error":a.status,c=!r.request.error&&a.status==="loading",l=r.request.error||a.error;switch(r.queryKind){case"metric":{const o=s;return{id:n.id,intent:r.request.intent,value:(o==null?void 0:o.value)??null,metrics:o==null?void 0:o.metrics,comparisonValue:o==null?void 0:o.comparisonValue,delta:o==null?void 0:o.delta,deltaPercent:o==null?void 0:o.deltaPercent,records:o==null?void 0:o.records,executionResult:o==null?void 0:o.executionResult,status:h,isLoading:c,error:l}}case"analysis":{const o=O(s);return{id:n.id,intent:r.request.intent,...o||{},status:h,isLoading:c,error:l}}case"records":{const o=s;return{id:n.id,intent:r.request.intent,records:(o==null?void 0:o.records)||[],columns:o==null?void 0:o.columns,rowCount:o==null?void 0:o.rowCount,pagination:o==null?void 0:o.pagination,executionResult:o==null?void 0:o.executionResult,status:h,isLoading:c,error:l}}case"inputOptions":{const o=s;return{id:n.id,intent:r.request.intent,options:(o==null?void 0:o.options)||[],executionResult:o==null?void 0:o.executionResult,status:h,isLoading:c,error:l}}case"sql":{const o=s;return{id:n.id,intent:r.request.intent,records:(o==null?void 0:o.records)||[],columns:o==null?void 0:o.columns,rowCount:o==null?void 0:o.rowCount,pagination:o==null?void 0:o.pagination,output:o==null?void 0:o.output,rowLimitExceeded:o==null?void 0:o.rowLimitExceeded,executionResult:o==null?void 0:o.executionResult,status:h,isLoading:c,error:l}}case"matrix":{const o=s;return{id:n.id,intent:r.request.intent,payload:o==null?void 0:o.payload,grid:o==null?void 0:o.grid,expansion:o==null?void 0:o.expansion,executionResult:o==null?void 0:o.executionResult,status:h,isLoading:c,error:l}}default:return E(r)}}function ye(e,t,n,r){const i=j(),a=p.useRef(t),s=p.useRef(r),[h,c]=p.useState({status:"idle",data:n,error:null});return a.current=t,s.current=r,p.useEffect(()=>{let l;try{l=a.current({...i,activeInputs:s.current})}catch(d){c({status:"error",data:n,error:f(d)});return}if(!l){c({status:"idle",data:n,error:null});return}let o=!1;return c(d=>({status:"loading",data:d.data,error:null})),l.then(d=>{o||c({status:"success",data:d,error:null})}).catch(d=>{o||c({status:"error",data:n,error:f(d)})}),()=>{o=!0}},[n,e,i]),h}function ve(e){return Object.fromEntries(e.filter(t=>t.defaultValue!==void 0).map(t=>[t.id,t.defaultValue]))}function E(e){throw new Error(`Unsupported Semaphor query kind: ${JSON.stringify(e)}`)}exports.hasSemaphorInputValue=u.hasSemaphorInputValue;exports.normalizeSemaphorAnalysisQueryOptions=u.normalizeSemaphorAnalysisQueryOptions;exports.normalizeSemaphorInputOptions=u.normalizeSemaphorInputOptions;exports.toSemaphorActiveInputSnapshots=u.toSemaphorActiveInputSnapshots;exports.toSemaphorAnalysisIntent=u.toSemaphorAnalysisIntent;exports.toSemaphorAnalysisQueryOptions=u.toSemaphorAnalysisQueryOptions;exports.toSemaphorInputBinding=u.toSemaphorInputBinding;exports.toSemaphorInputBindings=u.toSemaphorInputBindings;exports.toSemaphorInputOptionsIntent=u.toSemaphorInputOptionsIntent;exports.toSemaphorInputSnapshots=u.toSemaphorInputSnapshots;exports.toSemaphorInputSpec=u.toSemaphorInputSpec;exports.toSemaphorMatrixIntent=u.toSemaphorMatrixIntent;exports.toSemaphorMetricIntent=u.toSemaphorMetricIntent;exports.toSemaphorRecordsIntent=u.toSemaphorRecordsIntent;exports.toSemaphorSqlIntent=u.toSemaphorSqlIntent;exports.validateSemaphorDataAppQuerySpecs=u.validateSemaphorDataAppQuerySpecs;exports.SemaphorDataAppContext=K;exports.SemaphorDataAppProvider=ie;exports.createSemaphorQueryExecutor=T;exports.defineSemaphorDataApp=G;exports.defineSemaphorInput=Z;exports.normalizeSemaphorAnalysisPayload=O;exports.readWindowRuntime=V;exports.semaphor=ee;exports.useSemaphorDataAppRuntime=j;exports.useSemaphorInput=he;exports.useSemaphorInputs=fe;exports.useSemaphorQuery=Se;
|