react-semaphor 0.1.368 → 0.1.369
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/brand-studio/index.cjs +5 -5
- package/dist/brand-studio/index.js +24 -23
- package/dist/chunks/{braces-Cc86y9Ov.js → braces-C3-w6xDL.js} +1 -1
- package/dist/chunks/{braces-CXvY9MwQ.js → braces-C8QqW4wu.js} +1 -1
- package/dist/chunks/{calendar-preferences-dialog-BOFlzOJg.js → calendar-preferences-dialog-6q51A6XC.js} +3 -3
- package/dist/chunks/{calendar-preferences-dialog-ZzwfJv2J.js → calendar-preferences-dialog-CUGzkNcE.js} +1 -1
- package/dist/chunks/{chevrons-up-down-CUZL1zaU.js → chevrons-up-down-CnCSGY02.js} +1 -1
- package/dist/chunks/{chevrons-up-down-qQMadOWA.js → chevrons-up-down-DSvLu4Ye.js} +1 -1
- package/dist/chunks/{dashboard-briefing-launcher-9-PCYMjR.js → dashboard-briefing-launcher-BEZnvIla.js} +1 -1
- package/dist/chunks/{dashboard-briefing-launcher-D2lBFqAd.js → dashboard-briefing-launcher-ptERmNJr.js} +176 -177
- package/dist/chunks/{dashboard-controls-D4bUHAjX.js → dashboard-controls-CGt6_hMf.js} +11 -11
- package/dist/chunks/{dashboard-controls-BIk094Ah.js → dashboard-controls-CqKC5oEk.js} +77 -77
- package/dist/chunks/{dashboard-json-DImOf512.js → dashboard-json-6SgPm_QW.js} +13 -14
- package/dist/chunks/dashboard-json-CYSbOdmE.js +1 -0
- package/dist/chunks/{edit-dashboard-visual-DTxkV6Fl.js → edit-dashboard-visual-ByQx_M2i.js} +8 -9
- package/dist/chunks/{edit-dashboard-visual-BHKlcqQR.js → edit-dashboard-visual-w6hKbjlw.js} +1 -1
- package/dist/chunks/index-BtqYNH_S.js +1361 -0
- package/dist/chunks/{index-BVEIk-rB.js → index-CPyEi9gS.js} +72498 -76193
- package/dist/chunks/{palette-DPuAc82h.js → palette-D-f4-82S.js} +1 -1
- package/dist/chunks/{palette-C1k347Tb.js → palette-DUGktM-M.js} +1 -1
- package/dist/chunks/{resource-management-panel-BeHceP2D.js → resource-management-panel-Bf8-3eUf.js} +1 -1
- package/dist/chunks/{resource-management-panel-BOfbSf48.js → resource-management-panel-mJ84NxzC.js} +152 -152
- package/dist/chunks/save-D3YYinDz.js +6 -0
- package/dist/chunks/save-kkBEBeLg.js +21 -0
- package/dist/chunks/{switch-xcWLtWs0.js → switch-Dkx2qEOr.js} +758 -776
- package/dist/chunks/{switch-C0S63HAv.js → switch-fIkmwzUt.js} +27 -32
- package/dist/chunks/{use-create-flow-overlay-state-B5FygfQL.js → use-create-flow-overlay-state-BfoXDDrd.js} +190 -189
- package/dist/chunks/use-create-flow-overlay-state-c6rCm36x.js +26 -0
- package/dist/chunks/{use-visual-utils-DxDE8S8M.js → use-visual-utils-C_c-aiqi.js} +1 -1
- package/dist/chunks/{use-visual-utils-CszWnFBW.js → use-visual-utils-NN0e3fBP.js} +13 -13
- package/dist/chunks/validation-Dsf7PydY.js +1 -0
- package/dist/chunks/validation-nOPr0mTk.js +803 -0
- package/dist/chunks/{validators-L0xEXtjf.js → validators-CVuWOHYv.js} +225 -158
- package/dist/chunks/validators-oc8qtP4q.js +1 -0
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/dashboard-authoring/index.cjs +1 -1
- package/dist/dashboard-authoring/index.js +1 -1
- package/dist/data-app-builder/index.cjs +51 -1
- package/dist/data-app-builder/index.js +3666 -2
- package/dist/data-app-sdk/index.cjs +1 -1
- package/dist/data-app-sdk/index.js +589 -388
- package/dist/data-app-sdk-validation/index.cjs +1 -1
- package/dist/data-app-sdk-validation/index.js +4 -4
- package/dist/index.cjs +1 -1
- package/dist/index.js +14 -14
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/dist/types/analytics-protocol.d.ts +21 -1
- package/dist/types/dashboard-assistant.d.ts +21 -1
- package/dist/types/dashboard-authoring.d.ts +11 -1
- package/dist/types/data-app-builder.d.ts +11 -1
- package/dist/types/data-app-sdk-validation.d.ts +107 -23
- package/dist/types/data-app-sdk.d.ts +168 -35
- package/dist/types/main.d.ts +11 -1
- package/package.json +1 -1
- package/dist/chunks/dashboard-json-Bo1kX6W1.js +0 -1
- package/dist/chunks/index-HjDeEytV.js +0 -1411
- package/dist/chunks/use-create-flow-overlay-state-DOXTbTcQ.js +0 -26
- package/dist/chunks/validation-CrUjNWby.js +0 -689
- package/dist/chunks/validation-DGl8wnTt.js +0 -1
- package/dist/chunks/validators-Dq5X4mp0.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const j=require("./source-identity-C-xaeE_I.js");function P(e){const i=R(e);return F(i)?i:void 0}function R(e){if(typeof e!="string"||e.trim().length===0)return;const i=e.trim().toLowerCase().replace(/_/g," ");switch(i){case"eq":case"equals":case"=":return"=";case"neq":case"not equals":case"not equal":case"!=":return"!=";case"in":return"in";case"not in":return"not_in";case"contains":case"like":return"contains";case"not contains":case"not like":return"not_contains";case"between":return"between";case"not between":return"not_between";case">":case">=":case"<":case"<=":return i;case"is null":return"is_null";case"is not null":return"is_not_null";default:return E(e)?e:void 0}}function F(e){return e==="="||e==="!="||e==="in"||e==="not_in"||e==="contains"||e==="not_contains"||e==="between"||e==="not_between"||e===">"||e===">="||e==="<"||e==="<="}function E(e){return F(e)||e==="not_contains"||e==="is_null"||e==="is_not_null"}function t(e,i,n){return n?{code:e,message:i,path:n}:{code:e,message:i}}function C(e){for(let i=0;i<e.length;i+=1){const n=e[i];if(e.some((o,r)=>r!==i&&T(o,n)))return!1}return!0}function x(e,i){return j.semaphorFieldRefsMatch(e,i)}function T(e,i){return x(e,i)&&y(e)===y(i)}function U(e){return`Metric intent has duplicate metric "${e.name}" with the same aggregate (${y(e)}). Use different aggregates to request both, or remove one entry.`}function I(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null}function L(e,i,n){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e)){n.push(t("invalid_sql_default_parameters","SQL defaultParameters must be an object keyed by parameter name.",i));return}Object.entries(e).forEach(([o,r])=>{if(!o.trim()){n.push(t("invalid_sql_default_parameter_name","SQL defaultParameters names must be non-empty strings.",`${i}.${o}`));return}(Array.isArray(r)?r.every(I):I(r))||n.push(t("invalid_sql_default_parameter_value","SQL defaultParameters values must be strings, numbers, booleans, nulls, or arrays of those scalar values.",`${i}.${o}`))})}}function z(e,i){return w(e,i).length===1}function G(e,i){return w(e,i).length===1}function w(e,i){return i.filter(o=>Q(e,o))}function Q(e,i){return V(e,i)?e.source?x(i,e):!0:!1}function V(e,i){return!(i.name!==e.name||e.role!==void 0&&i.role!==void 0&&i.role!==e.role||H(e,i)&&y(i)!==y(e))}function H(e,i){return e.role==="measure"||i.role==="measure"||e.aggregate!==void 0||i.aggregate!==void 0}function y(e){return(e.aggregate||"SUM").toUpperCase()}const X=/^(\d{4})-(\d{2})-(\d{2})$/,Y=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})$/;function v(e){if(typeof e!="string")return null;const i=e.trim(),n=X.exec(i);if(n){const[,h,S,$]=n;return M(h,S,$)?new Date(Date.UTC(Number(h),Number(S)-1,Number($))):null}const o=Y.exec(i);if(!o)return null;const[,r,a,s,m,u,l="00",,f]=o;if(!M(r,a,s)||!_(m,0,23)||!_(u,0,59)||!_(l,0,59)||!Z(f))return null;const g=new Date(i);return Number.isFinite(g.getTime())?g:null}function M(e,i,n){const o=Number(e),r=Number(i),a=Number(n);if(!Number.isInteger(o)||!Number.isInteger(r)||!Number.isInteger(a)||r<1||r>12)return!1;const s=new Date(Date.UTC(o,r-1,a));return s.getUTCFullYear()===o&&s.getUTCMonth()===r-1&&s.getUTCDate()===a}function _(e,i,n){const o=Number(e);return Number.isInteger(o)&&o>=i&&o<=n}function Z(e){if(e==="Z")return!0;const i=/^([+-])(\d{2}):(\d{2})$/.exec(e);return!!(i&&_(i[2],0,23)&&_(i[3],0,59))}function d(e){return typeof e=="string"&&e.trim().length>0}function c(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function k(e,i,n){if(e!==void 0){if(!c(e)){n.push(t("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)&&n.push(t("invalid_pagination_page","Pagination page must be a positive integer.",`${i}.page`)),(!Number.isInteger(e.pageSize)||typeof e.pageSize!="number"||e.pageSize<1)&&n.push(t("invalid_pagination_page_size","Pagination pageSize must be a positive integer.",`${i}.pageSize`))}}function N(e){const i=new Set;for(const n of e){if(i.has(n))return n;i.add(n)}return null}const J=new Set(["SUM","COUNT","AVG","MIN","MAX","MEDIAN","DISTINCT"]);function D(e,i,n){if(!e||typeof e!="object"){n.push(t("missing_source","Analytics intent needs a source.",i));return}if(e.kind==="semantic"){d(e.domainId)||n.push(t("missing_semantic_domain","Semantic source needs a domainId.",`${i}.domainId`)),d(e.datasetName)||n.push(t("missing_dataset_name","Semantic source needs a datasetName.",`${i}.datasetName`));return}if(e.kind==="physical"){d(e.connectionId)||n.push(t("missing_connection_id","Physical source needs a connectionId.",`${i}.connectionId`)),d(e.tableName)||n.push(t("missing_table_name","Physical source needs a tableName.",`${i}.tableName`));return}if(e.kind==="sql"){d(e.connectionId)||n.push(t("missing_connection_id","SQL source needs a connectionId.",`${i}.connectionId`));return}n.push(t("invalid_source_kind","Source kind is not supported.",i))}function p(e,i,n,o={}){if(!e||!c(e)){o.required&&n.push(t("missing_field_ref","Field reference needs a name.",i));return}d(e.name)||n.push(t("missing_field_ref","Field reference needs a name.",`${i}.name`)),e.source!==void 0&&D(e.source,`${i}.source`,n),K(e.aggregate,`${i}.aggregate`,n)}function K(e,i,n){e!==void 0&&(typeof e!="string"||!J.has(e))&&n.push(t("invalid_aggregate","Field aggregate must be SUM, COUNT, AVG, MIN, MAX, MEDIAN, or DISTINCT.",i))}function W(e,i){if(e.analysis===void 0)return;if(!c(e.analysis)){i.push(t("invalid_metric_analysis","Metric analysis must be a structured object.","analysis"));return}if(e.analysis.kind!=="period_change"){i.push(t("invalid_metric_analysis","Metric analysis kind is not supported.","analysis.kind"));return}e.dateField||i.push(t("missing_analysis_date_field","Period-change analysis needs a dateField.","dateField")),e.timeGrain||i.push(t("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(t("invalid_metric_analysis","Period-change analysis orderBy must be absolute_change, positive_change, negative_change, or period.","analysis.orderBy"));const{timeWindow:n}=e.analysis;n!==void 0&&b(n,"analysis.timeWindow",i)}function b(e,i,n){if(!c(e)){n.push(t("invalid_time_window","Time window must be a structured object.",i));return}if(e.kind!==void 0&&e.kind!=="relative"&&e.kind!=="absolute"&&n.push(t("invalid_time_window","Time window kind must be relative or absolute.",`${i}.kind`)),e.kind==="absolute"){if(d(e.start)||n.push(t("invalid_time_window","Absolute time window start must be a non-empty ISO date or timestamp string.",`${i}.start`)),d(e.end)||n.push(t("invalid_time_window","Absolute time window end must be a non-empty ISO date or timestamp string.",`${i}.end`)),d(e.start)&&d(e.end)){const o=v(e.start),r=v(e.end);o||n.push(t("invalid_time_window","Absolute time window start must be a valid ISO date or timestamp.",`${i}.start`)),r||n.push(t("invalid_time_window","Absolute time window end must be a valid ISO date or timestamp.",`${i}.end`)),o&&r&&o.getTime()>r.getTime()&&n.push(t("invalid_time_window","Absolute time window start must be before or equal to end.",i))}return}e.unit!=="second"&&e.unit!=="minute"&&e.unit!=="hour"&&e.unit!=="day"&&e.unit!=="week"&&e.unit!=="month"&&e.unit!=="quarter"&&e.unit!=="year"&&n.push(t("invalid_time_window","Time window unit must be second, minute, hour, day, week, month, quarter, or year.",`${i}.unit`)),(typeof e.value!="number"||!Number.isFinite(e.value)||e.value<=0)&&n.push(t("invalid_time_window","Time window value must be a positive number.",`${i}.value`)),e.anchor!==void 0&&e.anchor!=="now"&&e.anchor!=="latest_available"&&n.push(t("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"&&n.push(t("invalid_time_window","Time window completeness must be include_partial or complete_periods.",`${i}.completeness`))}function B(e,i,n){if(e!==void 0){if(!Array.isArray(e)){n.push(t("invalid_analytics_filters","Analytics filters must be an array.",i));return}e.forEach((o,r)=>{var u;const a=`${i}.${r}`;if(!c(o)){n.push(t("invalid_analytics_filter","Analytics filter must be a structured object.",a));return}const s=o;p(s.field,`${a}.field`,n,{required:!0}),s.scope!==void 0&&s.scope!=="row"&&s.scope!=="aggregate"&&n.push(t("invalid_analytics_filter_scope","Analytics filter scope must be row or aggregate.",`${a}.scope`)),s.scope==="aggregate"&&((u=s.field)==null?void 0:u.role)!==void 0&&s.field.role!=="measure"&&n.push(t("invalid_analytics_filter_scope","Aggregate-scope analytics filters must target a measure field.",`${a}.scope`));const m=s.operator==="is_null"||s.operator==="is_not_null";if(s.operator!==void 0&&s.operator!=="="&&s.operator!=="!="&&s.operator!=="in"&&s.operator!=="not_in"&&s.operator!=="contains"&&s.operator!=="not_contains"&&s.operator!=="between"&&s.operator!=="not_between"&&s.operator!==">"&&s.operator!==">="&&s.operator!=="<"&&s.operator!=="<="&&s.operator!=="is_null"&&s.operator!=="is_not_null"&&n.push(t("invalid_analytics_filter_operator","Analytics filter operator is not supported.",`${a}.operator`)),s.values===void 0&&!m&&n.push(t("missing_analytics_filter_value","Analytics filter needs values unless it is a null check.",a)),m&&s.values!==void 0){n.push(t("invalid_analytics_filter_values","Null-check analytics filters must not include values.",`${a}.values`));return}if(s.values!==void 0&&!Array.isArray(s.values)){n.push(t("invalid_analytics_filter_values","Analytics filter values must be an array when provided.",`${a}.values`));return}if(s.values!==void 0){const l=s.values.length;if(s.operator==="between"||s.operator==="not_between"){l!==2&&n.push(t("invalid_analytics_filter_values","Between analytics filters must include exactly two values.",`${a}.values`));return}(s.operator==="contains"||s.operator==="not_contains"||s.operator==="="||s.operator==="!="||s.operator===">"||s.operator===">="||s.operator==="<"||s.operator==="<="||s.operator===void 0)&&l!==1&&n.push(t("invalid_analytics_filter_values","Scalar analytics filters must include exactly one value. Use in/not_in for multiple values.",`${a}.values`))}})}}function A(e){var o;const i=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:[t("invalid_analytics_intent","Analytics intent must be a structured object.")],warnings:n,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(t("invalid_version","Analytics intent version must be 1.","version")),D(e.source,"source",i),e.kind==="metric"){const r=Array.isArray(e.metrics)?e.metrics.filter(a=>c(a)&&d(a.name)):[];if(!Array.isArray(e.metrics)||e.metrics.length===0?i.push(t("missing_metric","Metric intent needs at least one metric.","metrics")):e.metrics.some(a=>!c(a)||!d(a.name))&&i.push(t("invalid_metric_list","Metric intent metrics must be an array of field references with names.","metrics")),r.forEach((a,s)=>{p(a,`metrics.${s}`,i,{required:!0})}),r.length>0&&!C(r)){const a=r.find((s,m)=>r.some((u,l)=>l!==m&&T(u,s)));a&&i.push(t("duplicate_metric",U(a),"metrics"))}if(c(e.primaryMetric)&&d(e.primaryMetric.name)&&w(e.primaryMetric,r).length>1&&i.push(t("ambiguous_primary_metric","Metric intent primaryMetric must identify exactly one selected metric.","primaryMetric")),e.primaryMetric!==void 0&&(p(e.primaryMetric,"primaryMetric",i,{required:!0}),c(e.primaryMetric)&&d(e.primaryMetric.name)&&r.length>0&&!z(e.primaryMetric,r)&&i.push(t("invalid_primary_metric","Metric intent primaryMetric must match one metric field reference.","primaryMetric"))),e.dimensions!==void 0&&!Array.isArray(e.dimensions)?i.push(t("invalid_metric_dimensions","Metric intent dimensions must be an array of field references.","dimensions")):Array.isArray(e.dimensions)&&e.dimensions.some(a=>!c(a)||!d(a.name))&&i.push(t("invalid_metric_dimensions","Metric intent dimensions must be an array of field references with names.","dimensions")),e.dateField!==void 0&&p(e.dateField,"dateField",i),e.timeWindow!==void 0&&(b(e.timeWindow,"timeWindow",i),e.dateField||i.push(t("missing_time_window_date_field","Metric timeWindow needs a dateField.","dateField"))),B(e.filters,"filters",i),Array.isArray(e.dimensions)&&e.dimensions.forEach((a,s)=>{p(a,`dimensions.${s}`,i)}),e.orderBy!==void 0){if(!c(e.orderBy))i.push(t("invalid_metric_order_by","Metric intent orderBy must be a structured object.","orderBy"));else if(p(e.orderBy.field,"orderBy.field",i,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&i.push(t("invalid_metric_order_direction","Metric intent orderBy direction must be asc or desc.","orderBy.direction")),c(e.orderBy.field)&&d(e.orderBy.field.name)){const a=[...r,...e.timeGrain&&e.dateField&&c(e.dateField)?[e.dateField]:[],...Array.isArray(e.dimensions)?e.dimensions.filter(s=>c(s)&&d(s.name)):[]];a.length>0&&!G(e.orderBy.field,a)&&i.push(t("invalid_metric_order_by","Metric intent orderBy.field must match one selected metric, grouped dateField, or dimension.","orderBy.field"))}}W(e,i)}else e.kind==="records"?(!Array.isArray(e.fields)||e.fields.length===0?i.push(t("missing_record_fields","Records intent needs at least one field.","fields")):e.fields.some(r=>!c(r)||!d(r.name))&&i.push(t("invalid_record_fields","Records intent fields must be field references with names.","fields")),Array.isArray(e.fields)&&e.fields.forEach((r,a)=>{p(r,`fields.${a}`,i)}),e.dateField!==void 0&&p(e.dateField,"dateField",i),k(e.pagination,"pagination",i),e.timeWindow!==void 0&&(b(e.timeWindow,"timeWindow",i),e.dateField||i.push(t("missing_time_window_date_field","Records timeWindow needs a dateField.","dateField"))),B(e.filters,"filters",i),Array.isArray(e.filters)&&e.filters.forEach((r,a)=>{c(r)&&r.scope==="aggregate"&&i.push(t("unsupported_record_filter_scope","Records intents support row-scope filters only. Use a metric intent for aggregate-scope filters.",`filters.${a}.scope`))}),e.orderBy!==void 0&&(c(e.orderBy)?(p(e.orderBy.field,"orderBy.field",i,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&i.push(t("invalid_record_order_direction","Records intent orderBy direction must be asc or desc.","orderBy.direction"))):i.push(t("invalid_record_order_by","Records intent orderBy must be a structured object.","orderBy")))):e.kind==="inputOptions"?((!e.field||!d(e.field.name))&&i.push(t("missing_input_options_field","Input options intent needs a field.","field")),p(e.field,"field",i,{required:!0})):e.kind==="sql"?(((o=e.source)==null?void 0:o.kind)!=="sql"&&i.push(t("invalid_sql_source","SQL analytics intent must use a SQL execution source.","source")),d(e.sql)||i.push(t("missing_sql","SQL analytics intent needs SQL text.","sql")),L(e.defaultParameters,"defaultParameters",i),Array.isArray(e.fields)&&e.fields.forEach((r,a)=>{p(r,`fields.${a}`,i)}),k(e.pagination,"pagination",i)):i.push(t("invalid_analytics_kind","Analytics kind is not supported.","kind"));return{ok:i.length===0,errors:i,warnings:n,repairHints:ie(i)}}function q(e){const i=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:[t("invalid_operation_intent","Operation intent must be a structured object.")],warnings:n,repairHints:[{code:"invalid_operation_intent",recommendedNextStep:"Send one typed operation intent with version, kind, and required operation fields."}]};if(e.version!==1&&i.push(t("invalid_version","Operation intent version must be 1.","version")),e.kind==="answer_obligations")!Array.isArray(e.obligations)||e.obligations.length===0?i.push(t("missing_obligations","Answer-obligations operation intent needs at least one obligation.","obligations")):e.obligations.forEach((o,r)=>{d(o.id)||i.push(t("missing_obligation_id","Each analytics obligation needs an id.",`obligations.${r}.id`)),d(o.prompt)||i.push(t("missing_obligation_prompt","Each analytics obligation needs a prompt.",`obligations.${r}.prompt`))});else if(e.kind==="dashboard_change"||e.kind==="data_app_change"){if(d(e.instruction)||i.push(t("missing_instruction","Change operation intent needs an instruction.","instruction")),e.analyticsIntent){const o=A(e.analyticsIntent);i.push(...o.errors),n.push(...o.warnings)}}else i.push(t("invalid_operation_kind","Operation intent kind is not supported.","kind"));return{ok:i.length===0,errors:i,warnings:n,repairHints:O(i)}}function ee(e){const i=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:[t("invalid_recovery_plan","Analytics recovery plan must be a structured object.")],warnings:n,repairHints:[{code:"invalid_recovery_plan",recommendedNextStep:"Return a typed recovery plan with operationIntent and plannedToolCalls."}]};e.version!==1&&i.push(t("invalid_version","Recovery plan version must be 1.","version")),e.kind!=="analytics_recovery_plan"&&i.push(t("invalid_recovery_plan_kind","Recovery plan kind must be analytics_recovery_plan.","kind"));const o=q(e.operationIntent);return i.push(...o.errors),n.push(...o.warnings),Array.isArray(e.plannedToolCalls)||i.push(t("invalid_planned_tool_calls","Recovery plan plannedToolCalls must be an array.","plannedToolCalls")),{ok:i.length===0,errors:i,warnings:n,repairHints:O(i)}}function O(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 ie(e){return e.map(i=>{switch(i.code){case"missing_source":return{code:i.code,fieldRole:"source",recommendedNextStep:"Provide a semantic, physical, or SQL source before executing analytics."};case"missing_metric":return{code:i.code,fieldRole:"metric",recommendedNextStep:"Choose one exact metric from the grounded schema candidates."};case"missing_record_fields":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Provide at least one field for the records intent."};case"missing_input_options_field":return{code:i.code,fieldRole:"input",recommendedNextStep:"Provide the exact field whose option values should be listed."};case"missing_sql":return{code:i.code,fieldRole:"sql",recommendedNextStep:"Provide bounded read-only SQL with an explicit outer LIMIT."};case"conflicting_sql":return{code:i.code,fieldRole:"sql",recommendedNextStep:"Use one canonical SQL text location for the intent; prefer top-level sql."};case"missing_semantic_domain":case"missing_dataset_name":case"missing_connection_id":case"missing_table_name":return{code:i.code,fieldRole:"source",recommendedNextStep:"Use grounded catalog metadata to fill the missing source reference."};default:return}}).filter(i=>!!i)}function te(e,i,n,o){if(!e||typeof e!="object"){n.push(t("invalid_view","Dashboard view must be an object.",i));return}if(d(e.title)||n.push(t("missing_view_title","Dashboard view needs a title.",i)),!e.presentation||typeof e.presentation!="object"){n.push(t("missing_presentation","Dashboard view needs a presentation.",`${i}.presentation`));return}if(e.presentation.kind==="text"){d(e.text)||o.push(t("missing_text_content","Text views should include text content.",`${i}.text`));return}if(!e.analytics){n.push(t("missing_view_analytics","Non-text dashboard views need analytics intent.",`${i}.analytics`));return}const r=A(e.analytics);for(const a of r.errors)n.push(t(a.code,a.message,`${i}.analytics${a.path?`.${a.path}`:""}`));for(const a of r.warnings)o.push(t(a.code,a.message,`${i}.analytics${a.path?`.${a.path}`:""}`))}function ne(e){const i=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:[t("invalid_dashboard_intent","Dashboard intent must be a structured object.")],warnings:n};e.version!==1&&i.push(t("invalid_version","Dashboard intent version must be 1.")),e.kind!=="dashboard"&&i.push(t("invalid_kind","Experience intent kind must be dashboard.")),d(e.title)||i.push(t("missing_title","Dashboard intent needs a title.","title"));const o=Array.isArray(e.inputs)?e.inputs:[],r=N(o.filter(c).map(u=>u.id).filter(u=>typeof u=="string"));r&&i.push(t("duplicate_input_id",`Duplicate input id: ${r}.`,"inputs"));for(const[u,l]of o.entries()){const f=`inputs.${u}`;if(!c(l)){i.push(t("invalid_input","Dashboard input must be an object.",f));continue}d(l.id)||i.push(t("missing_input_id","Input needs an id.",`${f}.id`)),d(l.label)||i.push(t("missing_input_label","Input needs a label.",`${f}.label`)),!l.field||!d(l.field.name)?i.push(t("missing_input_field","Input needs a field.",`${f}.field`)):p(l.field,`${f}.field`,i)}const a=Array.isArray(e.sections)?e.sections:[];a.length===0&&i.push(t("missing_sections","Dashboard intent needs at least one section.","sections"));const s=a.flatMap(u=>u&&typeof u=="object"&&Array.isArray(u.views)?u.views.filter(c).map(l=>l.id).filter(l=>!!l):[]),m=N(s);m&&i.push(t("duplicate_view_id",`Duplicate dashboard view id: ${m}.`,"sections"));for(const[u,l]of a.entries()){const f=`sections.${u}`;if(!l||typeof l!="object"){i.push(t("invalid_section","Dashboard section must be an object.",f));continue}if(d(l.title)||i.push(t("missing_section_title","Dashboard section needs a title.",f)),!Array.isArray(l.views)||l.views.length===0){i.push(t("missing_section_views","Dashboard section needs at least one view.",`${f}.views`));continue}for(const[g,h]of l.views.entries())te(h,`${f}.views.${g}`,i,n)}return{ok:i.length===0,errors:i,warnings:n}}exports.normalizeSemaphorAnalyticsFilterOperator=R;exports.normalizeSemaphorInputOperator=P;exports.parseSemaphorIsoTimeWindowBoundary=v;exports.validateSemaphorAnalyticsIntent=A;exports.validateSemaphorAnalyticsRecoveryPlan=ee;exports.validateSemaphorDashboardIntent=ne;exports.validateSemaphorOperationIntent=q;
|
package/dist/dashboard/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("../chunks/index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("../chunks/index-BtqYNH_S.js"),e=require("../chunks/common-types-C73-Ud1-.js");exports.Dashboard=o.Dashboard;exports.CONTROL_CARD_DEFAULT_VALUE=e.CONTROL_CARD_DEFAULT_VALUE;exports.EMPTY_SELECTION=e.EMPTY_SELECTION;
|
package/dist/dashboard/index.js
CHANGED
|
@@ -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-Dq5X4mp0.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-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(`
|
|
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-CVuWOHYv.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,51 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../chunks/index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),p=require("react"),kn=require("react-dom/client"),y=require("../chunks/index-BtqYNH_S.js"),x=require("../chunks/switch-fIkmwzUt.js"),Ye=require("../data-app-builder-browser-runtime/index.cjs"),Nn=require("../chunks/save-D3YYinDz.js");function Fr(t){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const d=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(s,a,d.get?d:{enumerable:!0,get:()=>t[a]})}}return s.default=t,Object.freeze(s)}const An=Fr(p),Cn=Fr(kn);/**
|
|
2
|
+
* @license lucide-react v0.453.0 - ISC
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the ISC license.
|
|
5
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/const Rn=x.createLucideIcon("CloudUpload",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]]);/**
|
|
7
|
+
* @license lucide-react v0.453.0 - ISC
|
|
8
|
+
*
|
|
9
|
+
* This source code is licensed under the ISC license.
|
|
10
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
+
*/const Bn=x.createLucideIcon("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/**
|
|
12
|
+
* @license lucide-react v0.453.0 - ISC
|
|
13
|
+
*
|
|
14
|
+
* This source code is licensed under the ISC license.
|
|
15
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
+
*/const Dn=x.createLucideIcon("ImagePlus",[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/**
|
|
17
|
+
* @license lucide-react v0.453.0 - ISC
|
|
18
|
+
*
|
|
19
|
+
* This source code is licensed under the ISC license.
|
|
20
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
+
*/const $n=x.createLucideIcon("MousePointer2",[["path",{d:"M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z",key:"edeuup"}]]);/**
|
|
22
|
+
* @license lucide-react v0.453.0 - ISC
|
|
23
|
+
*
|
|
24
|
+
* This source code is licensed under the ISC license.
|
|
25
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
+
*/const Pn=x.createLucideIcon("PanelLeftClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]),Fn=[{id:"customer-health",title:"Customer health workspace",description:"KPI cards, customer table, and segment filters for account health review.",datasets:["customers","orders"],prompt:"Build a customer health data app with KPI cards, segment and region filters, a revenue trend, and a customer health table."},{id:"revenue-command",title:"Revenue command center",description:"Revenue, margin, and order trends with top accounts and category drilldowns.",datasets:["orders","customers"],prompt:"Create a revenue command center with revenue and margin KPIs, a monthly trend chart, a segment performance section, and a top customers table."},{id:"operations-overview",title:"Operations overview",description:"Operational throughput, exceptions, and detail tables for daily review.",datasets:["orders","inventory"],prompt:"Create an operations dashboard with throughput KPIs, exception tables, trend charts, and filters for date, region, and status."}],Mn=[{id:"context",label:"Context",detail:"Read the current app files and workspace capabilities.",state:"idle"},{id:"generate",label:"Generate",detail:"Call the hosted model to produce the next React revision.",state:"idle"},{id:"edit",label:"Edit",detail:"Apply source changes through the local bridge.",state:"idle"},{id:"typecheck",label:"Typecheck",detail:"Run the local workspace validation command.",state:"idle"},{id:"repair",label:"Repair",detail:"Use diagnostics for a bounded repair pass if needed.",state:"idle"},{id:"preview",label:"Preview",detail:"Refresh the iframe once the dev server has updated.",state:"idle"}],$t=[{id:"gpt-5.5-low",label:"GPT-5.5 fast",model:"gpt-5.5",reasoningEffort:"low"},{id:"gpt-5.5-medium",label:"GPT-5.5 balanced",model:"gpt-5.5",reasoningEffort:"medium"},{id:"gpt-5.4-mini-minimal",label:"GPT-5.4 mini fast",model:"gpt-5.4-mini",reasoningEffort:"low"},{id:"gpt-4.1-mini",label:"GPT-4.1 mini",model:"gpt-4.1-mini"}],Sr="semaphor-data-app-builder-transcript",kr="semaphor-data-app-builder-preview-url",Nr="semaphor-data-app-builder-bridge-url",Ar="semaphor-data-app-builder-project-dir",At="http://semaphor-data-app.localhost:8088",Cr="http://localhost:8787",Ct="/Users/rohit/code/sandbox/semaphor-data-apps/data-app",Te=3,Tn=18,Rt=12;function ce(t,s){return`${t}:${s}`}function ue(t){return`${t}-${Date.now()}-${Math.random().toString(16).slice(2)}`}function En(t){return $t.find(s=>s.id===t)||$t[0]}async function O(t,s){const a=await t.text();if(!a.trim())return{};try{return JSON.parse(a)}catch{const d=a.replace(/\s+/g," ").trim().slice(0,500);throw new Error(`${s} returned ${t.status} ${t.statusText} with non-JSON response: ${d}`)}}function Mr(t,s){const a=t==null?void 0:t.trim().replace(/\/$/,"");return a?`${a.endsWith("/api")?a:`${a}/api`}/data-app-builder${s}`:`/api/data-app-builder${s}`}function xe(t,s){const a=t==null?void 0:t.trim().replace(/\/$/,"");return a?`${a.endsWith("/api")?a:`${a}/api`}/data-apps${s}`:`/api/data-apps${s}`}function Se(t){return t?{Authorization:`Bearer ${t}`}:{}}function ke(t){return t?"omit":"include"}function Ee(t){if(Array.isArray(t))return t.map(Ee);if(!t||typeof t!="object")return t;const s={};return Object.entries(t).forEach(([a,d])=>{if(a!=="contentsBase64"){if(a==="assets"&&Array.isArray(d)){s.assets=d.map(l=>{if(!l||typeof l!="object")return l;const{contentsBase64:u,...h}=l;return Ee(h)});return}s[a]=Ee(d)}}),s}async function On({apiServiceUrl:t,accessToken:s,signal:a}){const d=await fetch(Mr(t,"/status"),{cache:"no-store",headers:s?{Authorization:`Bearer ${s}`}:void 0,signal:a}),l=await O(d,"Data App Builder status");return d.ok?l:{ok:!1,error:l.error||d.statusText}}async function Ln(t,{apiServiceUrl:s,accessToken:a,signal:d,onProgress:l}){const u=await fetch(Mr(s,"/turn"),{method:"POST",signal:d,headers:{"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{}},body:JSON.stringify({...t,stream:!0})}),h=u.headers.get("content-type")||"";if(u.body&&h.includes("text/event-stream"))return In(u,l);const g=await O(u,"Data App Builder turn");if(!u.ok||!g.ok||!g.turn)throw new Error(g.error||"Data App Builder could not run the turn.");return g.turn}async function In(t,s){var N,f,R;const a=(N=t.body)==null?void 0:N.getReader();if(!a)throw new Error("Data App Builder turn stream was empty.");const d=new TextDecoder;let l="";const u={status:t.status,ok:t.ok},h=j=>{var L;const B=j.split(`
|
|
27
|
+
`),b=((L=B.find(F=>F.startsWith("event:")))==null?void 0:L.slice(6).trim())||"message",E=B.filter(F=>F.startsWith("data:")).map(F=>F.slice(5).trim()).join(`
|
|
28
|
+
`);if(!E)return;const z=JSON.parse(E);if(b==="progress"){s==null||s(z);return}b==="result"&&(u.status=typeof z.status=="number"?z.status:u.status,u.ok=z.ok===!0,u.result=z.body)};for(;;){const{done:j,value:B}=await a.read();if(j)break;l+=d.decode(B,{stream:!0});let b=l.indexOf(`
|
|
29
|
+
|
|
30
|
+
`);for(;b>=0;){const E=l.slice(0,b).trim();l=l.slice(b+2),E&&h(E),b=l.indexOf(`
|
|
31
|
+
|
|
32
|
+
`)}}const g=l.trim();if(g&&h(g),!u.ok||!((f=u.result)!=null&&f.ok)||!u.result.turn)throw new Error(((R=u.result)==null?void 0:R.error)||`Data App Builder could not run the turn (${u.status}).`);return u.result.turn}async function zn(t,{apiServiceUrl:s,accessToken:a,signal:d}){var R,j,B;const l=t.dataAppId,u=l?xe(s,`/${l}/draft`):xe(s,""),h=l?{title:t.title,description:t.description,manifest:t.manifest,sourceSnapshot:t.sourceSnapshot,sourceRevision:t.sourceRevision,validationStatus:t.validationStatus,bridgeWorkspaceHint:t.bridgeWorkspaceHint}:{projectId:t.projectId,title:t.title,description:t.description,manifest:t.manifest,sourceSnapshot:t.sourceSnapshot,sourceRevision:t.sourceRevision,validationStatus:t.validationStatus,bridgeWorkspaceHint:t.bridgeWorkspaceHint},g=await fetch(u,{method:"POST",credentials:ke(a),signal:d,headers:{"Content-Type":"application/json",...Se(a)},body:JSON.stringify(h)}),N=await O(g,"Data App save draft");if(!g.ok)throw new Error(N.error||"Data App draft could not be saved.");const f=l||((R=N.dataApp)==null?void 0:R.id);if(!f)throw new Error("Data App save draft response did not include an app id.");return{dataAppId:f,draftId:(j=N.draft)==null?void 0:j.id,savedAt:((B=N.draft)==null?void 0:B.updatedAt)||new Date().toISOString()}}async function Wn(t,{apiServiceUrl:s,accessToken:a,signal:d}){var h;const l=await fetch(xe(s,`/${t.dataAppId}`),{cache:"no-store",credentials:ke(a),signal:d,headers:Se(a)}),u=await O(l,"Data App load");if(!l.ok||!((h=u.dataApp)!=null&&h.id))throw new Error(u.error||"Data App could not be loaded.");return u.dataApp}async function Hn(t,{apiServiceUrl:s,accessToken:a,signal:d,onProgress:l}){var f,R,j,B;if(!t.draftId||!((f=t.sourceRevision)!=null&&f.snapshotHash))throw new Error("Data App publish requires a saved draft and matching source revision.");const u=Ee(t.validationStatus);l==null||l({phase:"start",label:"Starting publish session",detail:"Creating a versioned publish record in Semaphor."});const h=await fetch(xe(s,`/${t.dataAppId}/publish/start`),{method:"POST",credentials:ke(a),signal:d,headers:{"Content-Type":"application/json",...Se(a)},body:JSON.stringify({draftId:t.draftId,sourceRevisionSnapshotHash:(R=t.sourceRevision)==null?void 0:R.snapshotHash,validationStatus:u})}),g=await O(h,"Data App publish start");if(!h.ok||!((j=g.publishSession)!=null&&j.versionId))throw new Error(g.error||"Data App publish session could not be started.");const N=g.publishSession.versionId;try{l==null||l({phase:"build",label:"Building app locally",detail:"The local bridge is running the app build."});const b=await t.buildArtifacts({signal:d,onProgress:l}),E=Ee(b.validationStatus);for(const[F,W]of b.assets.entries()){l==null||l({phase:"upload",label:`Uploading asset ${F+1} of ${b.assets.length}`,detail:W.path,assetIndex:F+1,assetCount:b.assets.length});const ge=await fetch(xe(s,`/${t.dataAppId}/publish/upload`),{method:"POST",credentials:ke(a),signal:d,headers:{"Content-Type":"application/json",...Se(a)},body:JSON.stringify({versionId:N,assetPath:W.path,contentsBase64:W.contentsBase64,contentType:W.contentType})}),q=await O(ge,"Data App publish upload");if(!ge.ok)throw new Error(q.error||`Upload failed for ${W.path}.`)}l==null||l({phase:"complete",label:"Finalizing published version",detail:"Validating manifest and marking the version ready."});const z=await fetch(xe(s,`/${t.dataAppId}/publish/complete`),{method:"POST",credentials:ke(a),signal:d,headers:{"Content-Type":"application/json",...Se(a)},body:JSON.stringify({versionId:N,manifest:b.manifest,entryFile:b.entryFile,styleFiles:b.styleFiles,validationStatus:E})}),L=await O(z,"Data App publish complete");if(!z.ok||!((B=L.version)!=null&&B.id))throw new Error(L.error||"Data App publish could not be completed.");return{dataAppId:t.dataAppId,versionId:L.version.id,version:L.version.version,publishedAt:L.version.updatedAt||new Date().toISOString()}}catch(b){throw await fetch(xe(s,`/${t.dataAppId}/publish/fail`),{method:"POST",credentials:ke(a),signal:d,headers:{"Content-Type":"application/json",...Se(a)},body:JSON.stringify({versionId:N,validationStatus:{ok:!1,error:b instanceof Error?b.message:String(b)}})}).catch(()=>{}),b}}function Rr(t){const s=Array.from(new Set(t)),a=["src/App.tsx","src/data-app/index.tsx","src/data-app/styles.css","src/data-app/format.ts","src/data-app/types.ts","src/index.css","src/main.tsx"],d=[];for(const l of a)s.includes(l)&&d.push(l);for(const l of s){if(d.length>=Tn)break;d.includes(l)||d.push(l)}return d}function Br(t,s,a=""){const d=Array.from(new Set(t)),l=Jn(a,d),u=[s,"src/data-app/index.tsx","src/data-app/styles.css","src/data-app/format.ts","src/data-app/types.ts",...l,"src/App.tsx","src/index.css","src/lib/utils.ts"].filter(g=>!!g),h=[];for(const g of u){if(h.length>=Rt)break;d.includes(g)&&!h.includes(g)&&h.push(g)}for(const g of d){if(h.length>=Rt)break;h.includes(g)||/^src\/components\/ui\//.test(g)||/^src\/data-app\//.test(g)&&h.push(g)}return h.length>0?h:d.slice(0,Rt)}function Jn(t,s){const a=t.toLowerCase(),d=s.filter(u=>u.startsWith("src/components/ui/"));if(/\b(shadcn|component|components|ui)\b/.test(a))return d;const l=[["select","src/components/ui/select.tsx"],["dropdown","src/components/ui/select.tsx"],["filter","src/components/ui/select.tsx"],["progress","src/components/ui/progress.tsx"],["calendar","src/components/ui/calendar.tsx"],["date picker","src/components/ui/calendar.tsx"],["datepicker","src/components/ui/calendar.tsx"],["card","src/components/ui/card.tsx"],["table","src/components/ui/table.tsx"],["chart","src/components/ui/chart.tsx"],["badge","src/components/ui/badge.tsx"],["button","src/components/ui/button.tsx"]].filter(([u])=>a.includes(u)).map(([,u])=>u);return Array.from(new Set(l)).filter(u=>s.includes(u))}function _n(){return Mn.map(t=>({...t}))}function Bt(t){var a,d,l,u,h;return[t.error,(a=t.writePolicyValidation)==null?void 0:a.diagnostics.join(`
|
|
33
|
+
`),(d=t.importValidation)==null?void 0:d.diagnostics.join(`
|
|
34
|
+
`),(l=t.dataApiValidation)==null?void 0:l.diagnostics.join(`
|
|
35
|
+
`),(u=t.command)==null?void 0:u.stdout,(h=t.command)==null?void 0:h.stderr,...(t.attempts||[]).flatMap(g=>[g.command.stdout,g.command.stderr])].filter(Boolean).join(`
|
|
36
|
+
|
|
37
|
+
`).trim()||"Validation failed without diagnostics."}function Vn(t){return/\b(type\s*script|typescript|tsc|typecheck|compile|compiler)\b/i.test(t)}function Pt(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}function Un(t){const s={children:[]};for(const d of t){const l=d.path.split("/").filter(Boolean);let u=s,h="";l.forEach((g,N)=>{h=h?`${h}/${g}`:g;const f=N===l.length-1;let R=u.children.find(j=>j.name===g&&j.type===(f?"file":"directory"));R||(R={name:g,path:h,type:f?"file":"directory",size:f?d.size:void 0,children:[]},u.children.push(R)),u=R})}function a(d){d.children.sort((l,u)=>l.type!==u.type?l.type==="directory"?-1:1:l.name.localeCompare(u.name)),d.children.forEach(a)}return a(s),s.children}function Gn(t){return{idle:"Working through your request",context:"Reading app context",thinking:"Thinking through the request","inspecting-data":"Inspecting Semaphor data","reading-files":"Reading requested files",generating:"Generating source changes",planning:"Planning the changes"}[t]}function Kn(t){return{idle:"Preparing the next step.",context:"Reading the app and figuring out what to change.",thinking:"Deciding whether this needs an answer, file inspection, or edits.","inspecting-data":"Reading project data and dataset fields.","reading-files":"Loading source files the model asked to inspect.",generating:"Writing a bounded source revision.",planning:"Mapping your request to file edits."}[t]}function Qn(t){var d,l,u;const s=typeof t.message=="string"?t.message.trim():"";if(s)return s;const a=(u=(l=(d=t.revision)==null?void 0:d.plan)==null?void 0:l.files)==null?void 0:u.length;return a?`Yes - I'll make that change across ${a} file${a===1?"":"s"}, then run validation so you can review it.`:"Yes - I'll inspect the app context, make the change, and run validation so you can review it."}function Tr(t){return t.type==="screenshot"?`Screenshot attachment: ${t.name}`:[`DOM selection attachment: ${t.name}`,t.text.slice(0,1600)].join(`
|
|
38
|
+
`)}function qn(t){const s=t.slice(0,3).map(d=>d.split("/").pop()||d),a=t.length>s.length?` +${t.length-s.length} more`:"";return`${s.join(", ")}${a}`}function Xn(t){var d,l,u,h,g;if(t.type==="user"){const N=(t.attachments||[]).map(Tr).join(`
|
|
39
|
+
|
|
40
|
+
`);return{role:"user",content:[t.content,N].filter(Boolean).join(`
|
|
41
|
+
|
|
42
|
+
`).slice(0,2200)}}if(t.type==="assistant")return{role:"assistant",content:t.content.slice(0,1800)};const s=(l=(d=t.result)==null?void 0:d.changedFiles)!=null&&l.length?t.result.changedFiles.join(", "):"none",a=(g=(h=(u=t.result)==null?void 0:u.filePlan)==null?void 0:h.files)==null?void 0:g.map(N=>`${N.action}:${N.path}`).join(", ");return{role:"system",content:[`Build run ${t.status} for: ${t.prompt}`,`Changed files: ${s}`,a?`File plan: ${a}`:"",t.error?`Error: ${t.error}`:""].filter(Boolean).join(`
|
|
43
|
+
`).slice(0,2e3)}}function Oe(t){var h;const s=Array.isArray(t==null?void 0:t.sources)?t.sources:[],a=Array.isArray(t==null?void 0:t.inputs)?t.inputs:[],d=Array.isArray(t==null?void 0:t.views)?t.views:[],l=Array.isArray(t==null?void 0:t.interactions)?t.interactions:[],u=Array.isArray((h=t==null?void 0:t.layout)==null?void 0:h.sections)?t.layout.sections:[];return!!(t&&(s.length>0||a.length>0||d.length>0||l.length>0||u.length>0))}function Yn(t){var d;const s=(d=t==null?void 0:t.semaphor)==null?void 0:d.intentManifest;if(!s||typeof s!="object")return null;const a=s;return a.schemaVersion==="data-app-intent/v1"&&a.app&&Array.isArray(a.sources)&&Array.isArray(a.inputs)&&Array.isArray(a.views)?a:null}function Zn(t){const s=t.dataAppVersions||[];return s.find(a=>a.version===0&&a.status==="draft")||t.currentDataAppVersion||s.find(a=>a.status==="ready")||null}function es(t,s){var l,u,h;const a=(l=t.bridgeWorkspaceHint)==null?void 0:l.trim();if(a)return a;const d=(h=(u=t.sourceSnapshot)==null?void 0:u.metadata)==null?void 0:h.projectRoot;return typeof d=="string"&&d.trim()?d.trim():s}function ts(t){return JSON.stringify({schemaVersion:t.schemaVersion,files:[...t.files].map(s=>({path:s.path,contents:s.contents,hash:s.hash??null})).sort((s,a)=>s.path.localeCompare(a.path))})}async function Dr(t){const s=await window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(s)).map(a=>a.toString(16).padStart(2,"0")).join("")}function $r(t){return t.replace(/\\/g,"/").split("/").filter(Boolean).pop()}async function rs({snapshot:t,workspaceContext:s,projectDir:a,adapter:d}){const l=s.projectRoot||a;return{schemaVersion:"data-app-source-revision/v1",snapshotHash:await Dr(ts(t)),workspace:{adapter:d,...$r(l)?{rootName:$r(l)}:{},pathHash:await Dr(l)},collectedAt:new Date().toISOString()}}function Ze(t,s){const a=new Map;for(const d of t)a.set(d.id,d);for(const d of s)a.set(d.id,d);return Array.from(a.values())}function ns(t,s){return!s||!Oe(s)?t:!t||!Oe(t)?s:{schemaVersion:"data-app-intent/v1",app:{title:s.app.title||t.app.title,description:s.app.description||t.app.description,goal:s.app.goal||t.app.goal},sources:Ze(t.sources,s.sources),inputs:Ze(t.inputs,s.inputs),views:Ze(t.views,s.views),interactions:t.interactions||s.interactions?Ze(t.interactions||[],s.interactions||[]):void 0,layout:s.layout||t.layout}}function Pr(t,s){var N,f,R,j,B,b,E,z,L;const a=t.slice(-12).map(Xn),d=t.slice().reverse().find(F=>{var W;return F.type==="run"&&F.status==="done"&&((W=F.result)==null?void 0:W.ok)===!0}),l=t.slice().reverse().find(F=>{var W;return F.type==="user"&&!!((W=F.attachments)!=null&&W.length)}),u=(N=t.slice().reverse().find(F=>F.type==="assistant"&&!!F.operation))==null?void 0:N.operation,h=(Oe(s)?s:void 0)||((f=t.slice().reverse().find(F=>F.type==="assistant"&&Oe(F.intentManifest)))==null?void 0:f.intentManifest),g=[(R=l==null?void 0:l.attachments)!=null&&R.length?["Most recent selected/attached target:",...l.attachments.map(Tr)].join(`
|
|
44
|
+
`):"",(B=(j=d==null?void 0:d.result)==null?void 0:j.changedFiles)!=null&&B.length?`Last successful edit changed: ${d.result.changedFiles.join(", ")}`:"",u?`Last app-builder operation: ${u.type}${(b=u.target)!=null&&b.label?` on ${u.target.label}`:""}`:""].filter(Boolean);return{messages:a,activeTarget:g.join(`
|
|
45
|
+
|
|
46
|
+
`)||void 0,lastSuccessfulRun:d?{prompt:d.prompt,changedFiles:((E=d.result)==null?void 0:E.changedFiles)||[],summary:(z=d.result)==null?void 0:z.summary,filePlan:(L=d.result)==null?void 0:L.filePlan}:void 0,lastOperation:u,intentManifest:h||void 0}}function ss({files:t,selectedPath:s,onSelect:a}){const d=p.useMemo(()=>Un(t),[t]);return d.length===0?e.jsx("div",{className:"rounded-[5px] border border-border bg-background p-2 text-[11px] text-muted-foreground",children:"No browser files loaded yet."}):e.jsx("div",{className:"space-y-0.5",children:d.map(l=>e.jsx(Er,{node:l,depth:0,selectedPath:s,onSelect:a},l.path||l.name))})}function Er({node:t,depth:s,selectedPath:a,onSelect:d}){const l=t.type==="directory",u=a===t.path;return e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:l,onClick:()=>d(t.path),className:`flex w-full items-center gap-1.5 rounded-[4px] py-1.5 pr-2 text-left font-mono text-[11px] ${u?"bg-background text-foreground":l?"cursor-default text-foreground":"text-muted-foreground hover:bg-background hover:text-foreground"}`,style:{paddingLeft:`${8+s*14}px`},children:[l?e.jsxs(e.Fragment,{children:[e.jsx(y.ChevronRight,{className:"h-3 w-3 rotate-90 text-muted-foreground"}),e.jsx(Bn,{className:"h-3.5 w-3.5 text-muted-foreground"})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-3 w-3"}),e.jsx(y.CodeXml,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.name}),!l&&e.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:t.size})]}),l&&t.children.map(h=>e.jsx(Er,{node:h,depth:s+1,selectedPath:a,onSelect:d},h.path))]})}function as({manifest:t}){if(!t)return null;const s=t.packages.filter(d=>d.status==="supported").length,a=t.packages.length-s;return e.jsxs("div",{className:"mt-2 rounded-[5px] border border-border bg-background px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:t.name}),e.jsxs("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:[t.moduleSystem," · ",t.cssPipeline.status]})]}),e.jsx("span",{className:"rounded-[4px] bg-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-[0.06em] text-muted-foreground",children:t.execution})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5 text-[10.5px] text-muted-foreground",children:[e.jsxs("span",{className:"rounded-[4px] bg-muted px-1.5 py-0.5",children:[t.components.length," components"]}),e.jsxs("span",{className:"rounded-[4px] bg-muted px-1.5 py-0.5",children:[s," packages"]}),a>0?e.jsxs("span",{className:"rounded-[4px] bg-amber-50 px-1.5 py-0.5 text-amber-700",children:[a," partial"]}):null]})]})}function os({plan:t,changedFiles:s}){const a=new Set(s||[]),d=(t==null?void 0:t.files)||[],l=(s||[]).filter(u=>!d.some(h=>h.path===u));return d.length===0&&l.length===0?null:e.jsxs("div",{className:"mt-2 rounded-[5px] border border-white/70 bg-background/60 p-2",children:[t!=null&&t.intent?e.jsx("div",{className:"mb-1.5 text-[11px] font-medium text-foreground",children:t.intent}):null,e.jsxs("div",{className:"space-y-1",children:[d.map(u=>e.jsxs("div",{className:"flex items-start justify-between gap-2 rounded-[4px] bg-background/70 px-2 py-1",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-mono text-[11px] text-foreground",children:u.path}),e.jsx("div",{className:"mt-0.5 line-clamp-2 text-[10.5px] text-muted-foreground",children:u.purpose})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx("span",{className:"rounded-[4px] bg-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-[0.04em] text-muted-foreground",children:u.action}),a.has(u.path)?e.jsx("span",{className:"rounded-[4px] bg-emerald-50 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-[0.04em] text-emerald-700",children:"changed"}):null]})]},u.path)),l.map(u=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-[4px] bg-background/70 px-2 py-1",children:[e.jsx("span",{className:"min-w-0 truncate font-mono text-[11px] text-foreground",children:u}),e.jsx("span",{className:"rounded-[4px] bg-emerald-50 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-[0.04em] text-emerald-700",children:"changed"})]},u))]})]})}function is({projectId:t,projectName:s,dataAppId:a,apiServiceUrl:d,adapters:l}){var j,B;const u=p.useContext(y.SemaphorContext),h=typeof window>"u"?void 0:window.location.origin,g=d||((j=u.tokenProps)==null?void 0:j.apiServiceUrl)||h,N=(B=u.authToken)==null?void 0:B.accessToken,[f,R]=p.useState(()=>ue("builder-session"));return e.jsx("main",{className:"flex h-full min-h-0 w-full min-w-0 flex-1 flex-col self-stretch bg-muted/40 text-foreground",children:e.jsx(ls,{adapters:l,apiServiceUrl:g,accessToken:N,initialDataAppId:a||null,initialPrompt:"",path:"bridge",projectId:t,projectName:s,onRestart:()=>R(ue("builder-session"))},f)})}function ls({adapters:t,apiServiceUrl:s,accessToken:a,initialDataAppId:d,initialPrompt:l,path:u,projectId:h,projectName:g,onRestart:N}){var vr,jr;const[f,R]=p.useState(At),[j,B]=p.useState(Cr),[b,E]=p.useState(Ct),[z,L]=p.useState(!1),[F,W]=p.useState(At),[ge,q]=p.useState(0),[A]=p.useState(u),[Le,et]=p.useState(l||""),[tt,Ie]=p.useState([]),[Ne,Ae]=p.useState([]),[X,pe]=p.useState([]),[Mt,ze]=p.useState(null),[Y,We]=p.useState(!1),[Z,Tt]=p.useState(!1),[Ce,Or]=p.useState(!0),[Lr,ne]=p.useState("idle"),[Ir,se]=p.useState(null),[Et,Ot]=p.useState(null),[Lt,He]=p.useState(()=>Date.now()),[Re,It]=p.useState(null),[rt,zr]=p.useState("gpt-5.5-low"),Q=p.useRef(null),U=p.useRef(null),nt=p.useRef([]),st=p.useRef(null),at=p.useRef(null),zt=p.useRef(null),[he,be]=p.useState(!1),[Wt,ae]=p.useState(null),[Ht,ot]=p.useState(!1),[Jt,_t]=p.useState(!1),[Be,it]=p.useState("idle"),[Vt,Ut]=p.useState(null),[Wr,Gt]=p.useState(""),[Hr,Kt]=p.useState([]),[lt,Qt]=p.useState([]),[dt,qt]=p.useState(null),[Xt,Jr]=p.useState([]),[_r,Vr]=p.useState(null),[ct,Yt]=p.useState(null),[ut,Zt]=p.useState(null),[me,Je]=p.useState(d||null),[_e,pt]=p.useState("idle"),[er,ht]=p.useState("idle"),[tr,rr]=p.useState(null),[nr,sr]=p.useState(null),[mt,we]=p.useState(null),[oe,H]=p.useState(null),[ar,Ve]=p.useState(null),[Ue,ft]=p.useState(null),[xt,Ge]=p.useState(!1),[gt,or]=p.useState(""),[ir,bt]=p.useState(null),[lr,dr]=p.useState(!1),De=p.useRef(null),wt=p.useRef(null),ye=p.useRef(null),cr=(t==null?void 0:t.readStatus)||On,Ke=(t==null?void 0:t.runTurn)||Ln,yt=(t==null?void 0:t.saveDraft)||zn,Ur=(t==null?void 0:t.loadApp)||Wn,vt=(t==null?void 0:t.publish)||Hn,J=p.useMemo(()=>En(rt),[rt]),Gr=p.useMemo(()=>X.find(r=>r.type==="run"&&r.id===Mt),[Mt,X]),jt=p.useMemo(()=>[...X].reverse().find(r=>r.type==="run"),[X]),St=p.useMemo(()=>{const r=F.includes("?")?"&":"?";return`${F}${r}dataAppBuilderRefresh=${ge}`},[F,ge]);p.useEffect(()=>{const r=window.setInterval(()=>He(Date.now()),500);return()=>window.clearInterval(r)},[]),p.useEffect(()=>{nt.current=X},[X]),p.useEffect(()=>{if(!xt)return;const r=()=>{Ge(!1)};return window.addEventListener("blur",r),()=>{window.removeEventListener("blur",r)}},[xt]),p.useEffect(()=>{L(!1);const r=window.localStorage.getItem(ce(kr,h))||At,n=window.localStorage.getItem(ce(Nr,h))||Cr,i=window.localStorage.getItem(ce(Ar,h))||Ct,o=window.localStorage.getItem(ce(Sr,h));if(R(r),W(r),B(n),E(i),L(!0),o)try{pe(JSON.parse(o))}catch{pe([])}},[h]),p.useEffect(()=>{window.localStorage.setItem(ce(kr,h),f)},[f,h]),p.useEffect(()=>{window.localStorage.setItem(ce(Nr,h),j)},[j,h]),p.useEffect(()=>{window.localStorage.setItem(ce(Ar,h),b)},[b,h]),p.useEffect(()=>{var r;window.localStorage.setItem(ce(Sr,h),JSON.stringify(X.map(xs))),(r=st.current)==null||r.scrollTo({top:st.current.scrollHeight,behavior:"smooth"})},[X,h]),p.useEffect(()=>{ye.current=ct},[ct]);const kt=p.useCallback(async r=>{if(A!=="bridge"||!s)return;const n=j.replace(/\/$/,""),i=await fetch(`${n}/runtime-context`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({accessToken:a||null,apiBaseUrl:s,dataApiBaseUrl:s,dataAppId:me,projectId:h})}),o=await O(i,"Local bridge /runtime-context");if(!i.ok||!o.ok)throw new Error(o.error||"Bridge could not sync runtime context.")},[a,s,j,me,h,A]);p.useEffect(()=>{if(A!=="bridge"||!s)return;const r=new AbortController;return kt(r.signal).then(()=>{q(n=>n+1)}).catch(n=>{r.signal.aborted||(ot(!1),ae(n instanceof Error?n.message:"Bridge could not sync runtime context."))}),()=>r.abort()},[s,A,kt]),p.useEffect(()=>{Je(d||null)},[d]),p.useEffect(()=>{if(!d||!z||wt.current===`${d}:${A}:${b}`)return;const r=new AbortController;return wt.current=`${d}:${A}:${b}`,we(null),H({state:"running",label:"Opening Data App",detail:"Loading the saved Data App draft from Semaphor."}),(async()=>{var n,i;try{const o=await Ur({dataAppId:d},{apiServiceUrl:s,accessToken:a,signal:r.signal});if(r.signal.aborted)return;Je(o.id);const c=Zn(o);if(!c){H({state:"done",label:"Data App opened",detail:"No saved source snapshot exists yet."});return}const m=Yn(c.manifest);m&&ft(m),c.status==="draft"?rr(c.updatedAt||null):c.status==="ready"&&sr(c.updatedAt||null);const S=es(c,b);let w=!1;if(A==="bridge"&&((i=(n=c.sourceSnapshot)==null?void 0:n.files)!=null&&i.length)&&(H({state:"running",label:"Restore saved source",detail:"Comparing the saved source snapshot with the bridge workspace."}),w=await gn({snapshot:c.sourceSnapshot,targetProjectDir:S,signal:r.signal}),w&&q(C=>C+1)),A==="bridge"&&S!==b&&E(S),r.signal.aborted)return;H({state:"done",label:"Data App opened",detail:w?"Saved source was restored into the bridge workspace.":"Saved draft metadata was loaded."})}catch(o){if(r.signal.aborted)return;const c=o instanceof Error?o.message:String(o);wt.current=null,we(c),H({state:"failed",label:"Open Data App failed",detail:c}),M(`Open Data App failed: ${c}`,"blocked")}})(),()=>r.abort()},[z,d,b,A]),p.useEffect(()=>{function r(n){var c;if(n.source!==((c=at.current)==null?void 0:c.contentWindow))return;const i=n.data;if((i==null?void 0:i.source)!=="semaphor-dev-bridge-inspector")return;if(i.type==="ready"&&he){Xe("inspect-enable");return}if(i.type==="enabled"){ae("Click an element in the preview. Press Esc to cancel.");return}if(i.type==="disabled"){be(!1);return}if(i.type!=="selection"||!i.payload)return;const o=an(i.payload);Ie(m=>[...m,o]),be(!1),ae(`Selected ${o.name}. Add a message and send it.`)}return window.addEventListener("message",r),()=>window.removeEventListener("message",r)},[he]),p.useEffect(()=>{be(!1),ot(!1),ae(null)},[j,b,A]),p.useEffect(()=>{if(Y||Z||Ne.length===0)return;const[r,...n]=Ne;Ae(n),hr(r)},[Y,Z,Ne]),p.useEffect(()=>{let r=!1;const n=new AbortController;async function i(){try{const o=await cr({apiServiceUrl:s,accessToken:a,signal:n.signal});r||It(o)}catch(o){r||It({ok:!1,error:o instanceof Error?o.message:String(o)})}}return i(),()=>{r=!0}},[a,s,cr]);const Qe=p.useCallback(async(r=U.current)=>{if(!r)return;const n=await r.compileBrowserSandboxPreviewHtml();Gt(n.html),Kt(n.diagnostics),Qt(n.warnings||[]),qt(n.cssMode||null),q(i=>i+1)},[]),$e=p.useCallback((r=U.current,n=ye.current)=>{var m;if(!r)return;const i=r.listBrowserSandboxFiles(),o=r.readBrowserSandboxWorkspaceContext(),c=n&&i.some(S=>S.path===n)?n:((m=i[0])==null?void 0:m.path)||null;Jr(i),Vr(o.runtimeManifest||null),Yt(c),ye.current=c,Zt(c&&r.readBrowserSandboxFiles([c])[0]||null)},[]);p.useEffect(()=>{if(A!=="browser")return;let r=!1;async function n(){it("loading"),Ut(null),window.__SEMAPHOR_BROWSER_SANDBOX_VENDOR__={React:An,ReactDOMClient:Cn};try{const i=await Ye.loadSemaphorBrowserRuntime();if(r)return;U.current=i,it("ready"),await Qe(i),$e(i)}catch(i){if(r)return;it("failed"),Ut(i instanceof Error?i.message:String(i))}}return n(),()=>{r=!0}},[A,$e,Qe]);function Kr(r){const n=U.current;Yt(r),ye.current=r,Zt(n&&n.readBrowserSandboxFiles([r])[0]||null)}async function ur(){const r=U.current;!r||Y||(r.resetBrowserSandbox(),await Qe(r),$e(r),M("Browser Sandbox reset to the approved starter template. Existing generated browser files were replaced in local browser storage.","guidance"))}async function Qr(){if(Y||Z)return;if(ft(null),Ve(null),or(""),bt(null),A==="browser"){await ur();return}const r=new AbortController,n=j.replace(/\/$/,"");try{H({state:"running",label:"Resetting app",detail:"Restoring the local workspace to the blank Data App template."});const i=await fetch(`${n}/reset-app`,{method:"POST",signal:r.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({})}),o=await O(i,"Local bridge /reset-app");if(!i.ok||!o.ok)throw new Error(o.error||"Bridge could not reset the app.");W(f),q(c=>c+1),H({state:"done",label:"App reset",detail:"Blank template restored and typecheck passed."}),M("Reset the local app to the blank Data App template. You can start a new build from here.","guidance")}catch(i){const o=i instanceof Error?i.message:String(i);H({state:"failed",label:"Reset failed",detail:o}),M(`Reset failed: ${o}`,"blocked")}}function qr(r){const n=r.durationMs??0;return r.state!=="running"||!r.startedAt?n:n+Math.max(0,Lt-r.startedAt)}function Xr(r,n,i){const o=r.durationMs??0;return r.state!=="running"&&n.state==="running"?{...n,startedAt:i,durationMs:o}:r.state==="running"&&n.state!=="running"?{...n,startedAt:void 0,durationMs:o+Math.max(0,i-(r.startedAt??i))}:{...n,startedAt:r.startedAt,durationMs:o}}function Yr(r,n,i){const o=Date.now();He(o),pe(c=>c.map(m=>{if(m.type!=="run"||m.id!==r)return m;const S=n(m.steps),w=new Map(m.steps.map(C=>[C.id,C]));return{...m,...i,steps:S.map(C=>{const v=w.get(C.id);return v?Xr(v,C,o):C})}}))}function qe(r,n){pe(i=>i.map(o=>o.type==="run"&&o.id===r?{...o,...n}:o))}function M(r,n="default",i){const o=Oe(i==null?void 0:i.intentManifest)?i==null?void 0:i.intentManifest:void 0;pe(c=>[...c,{id:ue("assistant"),type:"assistant",content:r,createdAt:Date.now(),tone:n,artifacts:i==null?void 0:i.artifacts,operation:i==null?void 0:i.operation,intentManifest:o}])}function Zr(r){var i;r.intentManifest&&ft(o=>ns(o,r.intentManifest));const n=(i=r.artifacts)==null?void 0:i.find(o=>o.type==="dataset_inspector");n&&Ve(n)}function pr(r){ne({received:"context",authenticating:"context",routing:"thinking",inspecting_data:"inspecting-data",reading_files:"reading-files",planning_revision:"planning",generating_code:"generating",done:"thinking"}[r.phase]),se(r.detail||r.label)}function hr(r){const n=r.prompt.trim();if(!n)return;const i=Date.now();pe(o=>[...o,{id:ue("user"),type:"user",content:n,createdAt:i,attachments:r.attachments}]),Ot(i),ne("context"),se("Preparing app context and available files."),vn({...r,prompt:n})}async function en(r){if(!r.type.startsWith("image/")){M("Only image attachments are supported right now.","blocked");return}if(r.size>6*1024*1024){M("That screenshot is larger than 6MB. Please attach a smaller image.","blocked");return}const n=await new Promise((i,o)=>{const c=new FileReader;c.onload=()=>{typeof c.result=="string"?i(c.result):o(new Error("Could not read image attachment."))},c.onerror=()=>o(c.error||new Error("Could not read image attachment.")),c.readAsDataURL(r)});Ie(i=>[...i,{id:ue("attachment"),type:"screenshot",name:r.name||"Screenshot",imageUrl:n,mediaType:r.type,createdAt:Date.now()}])}function tn(r){Ie(n=>n.filter(i=>i.id!==r))}function Xe(r){var i,o;let n="*";try{n=new URL(St).origin}catch{n="*"}(o=(i=at.current)==null?void 0:i.contentWindow)==null||o.postMessage({source:"semaphor-data-app-builder",type:r},n)}async function rn(){const r=j.replace(/\/$/,""),n=await fetch(`${r}/inspect/install`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:b})}),i=await O(n,"Local bridge /inspect/install");if(!n.ok||!i.ok)throw new Error(i.error||"Bridge could not install inspector.");return i}async function nn(){if(A!=="bridge"){M("Element inspection is only available in Local Bridge mode right now.","blocked");return}try{_t(!0),ae(Ht?null:"Preparing element inspector…");let r=!1;if(!Ht){const n=await rn();ot(!!n.installed),r=!!n.changed}be(!0),ae(r?"Loading inspector in the preview…":"Click an element in the preview. Press Esc to cancel."),r?(W(f),q(n=>n+1)):window.setTimeout(()=>Xe("inspect-enable"),50)}catch(r){be(!1),ae(null),M(r instanceof Error?r.message:String(r),"blocked")}finally{_t(!1)}}function sn(){be(!1),ae(null),Xe("inspect-disable")}function an(r){const n=(v,k="")=>typeof v=="string"&&v.trim()?v.trim():k,i=v=>Array.isArray(v)?v.map(k=>typeof k=="string"?k:k&&typeof k=="object"?JSON.stringify(k):"").filter(Boolean):[],o=n(r.elementLabel)||n(r.name),c=n(r.component),m=o&&c&&o!==c?`${o} in ${c}`:o||c||n(r.tagName,"Selected element"),S=i(r.reactOwners),w=i(r.sourceHints),C=[`Clicked element: ${o||m}`,`Nearest component: ${c||"unavailable"}`,`Tag: ${n(r.tagName,"unknown")}`,`Role: ${n(r.role,"none")}`,`Selector: ${n(r.selector,"none")}`,S.length?`React owner stack: ${S.join(" > ")}`:"React owner stack: unavailable",w.length?`Source hints: ${w.join(" | ")}`:"Source hints: unavailable",`Bounds: ${JSON.stringify(r.bounds||{})}`,`Ancestors: ${i(r.ancestorSummary).join(" > ")||"none"}`,`Classes: ${n(r.classes,"none")}`,"","Visible text:",n(r.text,"(no visible text)"),"","HTML excerpt:",n(r.htmlExcerpt,"(no HTML excerpt)")].join(`
|
|
47
|
+
`);return{id:ue("attachment"),type:"dom-selection",name:m,text:C,createdAt:Date.now()}}function on(r,n){Ae(i=>i.map(o=>o.id===r?{...o,prompt:n}:o))}function ln(r){Ae(n=>n.filter(i=>i.id!==r))}function dn(r,n){Ae(i=>i.map(o=>o.id===r?{...o,attachments:o.attachments.filter(c=>c.id!==n)}:o))}async function mr(r){for(const n of Array.from(r))await en(n)}function fr(r,n){var c;const i=n==="browser"?"Browser Sandbox":"Local Bridge",o=(c=r.changedFiles)!=null&&c.length?r.changedFiles.join(", "):"no files";return r.ok?`${i} applied the revision and validation passed. Changed files: ${o}. The preview has been refreshed; inspect the file tree and run card for the exact file plan.`:`${i} could not finish the revision cleanly. Changed files: ${o}. The run card includes the validation output so you can ask a follow-up repair question or switch runtimes.`}function G(r,n){Yr(r,i=>i.map(o=>{if(n==="failed")return{...o,state:o.state==="running"?"blocked":o.state};const c={reading:[],generating:["context"],writing:["context","generate"],typechecking:["context","generate","edit"],repairing:["context","generate","edit","typecheck"],complete:["context","generate","edit","typecheck","repair","preview"]},S={reading:"context",generating:"generate",writing:"edit",typechecking:"typecheck",repairing:"repair"}[n];return{...o,state:c[n].includes(o.id)?"done":S===o.id?"running":o.state==="done"?"done":"idle"}}))}async function cn(r,n,i){var S,w,C,v;(S=Q.current)==null||S.abort();const o=new AbortController,c=Date.now();Q.current=o,We(!0),ze(n),He(c),G(n,"reading");const m=window.setTimeout(()=>{o.abort()},18e4);try{let k=U.current;k||(k=await Ye.loadSemaphorBrowserRuntime(),U.current=k);const I=k.readBrowserSandboxWorkspaceContext(),D=(C=(w=I.files)==null?void 0:w.editable)!=null&&C.length?Br(I.files.editable,ye.current,r):["src/App.tsx"],ie=k.readBrowserSandboxFiles(D),ve=ie.reduce((te,ee)=>te+ee.contents.length,0);let je=ie,Pe=[],le=i,K=null;const de=[];for(let te=0;te<Te;te+=1){const ee=Pe.length>0||te>0,Fe=ee?`repair-${te+1}`:"initial";G(n,ee?"repairing":"generating");const _=le||(await Ke({projectId:h,message:r,currentFiles:je,workspaceContext:I,diagnostics:Pe,repair:ee,generationModel:J.model,generationReasoningEffort:J.reasoningEffort,repairModel:J.model,repairReasoningEffort:J.reasoningEffort},{accessToken:a,apiServiceUrl:s,signal:o.signal})).revision;if(le=void 0,!_)throw new Error("Data App Builder did not return a revision.");G(n,"writing");const fe=k.applyBrowserSandboxRevision({..._,attemptLabel:Fe});de.push(...fe.attempts||[]),G(n,"typechecking");let $={...fe,attempts:[...de],filePlan:_.plan,telemetry:{contextFileCount:ie.length,contextChars:ve,generatedFileCount:_.files.length,generatedChars:_.files.reduce((P,V)=>P+V.contents.length,0),repairAttempts:de.filter(P=>P.label.startsWith("repair")).length}};if(fe.ok){const P=await k.compileBrowserSandboxPreviewHtml();if(Gt(P.html),Kt(P.diagnostics),Qt(P.warnings||[]),qt(P.cssMode||null),q(V=>V+1),$e(k),P.diagnostics.length>0){const V={command:"browser sandbox preview compile",durationMs:0,exitCode:1,ok:!1,stdout:"",stderr:P.diagnostics.join(`
|
|
48
|
+
`)};$={...$,ok:!1,validation:"typecheck",command:V,attempts:[...de,{label:Fe,ok:!1,command:V}],error:"Generated files failed Browser Sandbox preview compile."}}}if(K=$,$.ok||te===Te-1)break;const T=(v=$.changedFiles)!=null&&v.length?$.changedFiles:_.files.map(P=>P.path);je=k.readBrowserSandboxFiles(Array.from(new Set([...D,...T]))),Pe=[Bt($)]}if(!K)throw new Error("The browser runtime loop ended without a validation result.");G(n,K.ok?"complete":"failed"),qe(n,{status:K.ok?"done":"failed",result:K,error:K.error,finishedAt:Date.now()}),M(fr(K,"browser"),K.ok?"default":"blocked")}catch(k){const I=k instanceof DOMException&&k.name==="AbortError",D=I?"Timed out waiting for the browser runtime loop.":k instanceof Error?k.message:String(k);qe(n,{status:I?"cancelled":"failed",error:D,result:{ok:!1,error:D,summary:"The app-builder/browser runtime loop stopped before validation completed."},finishedAt:Date.now()}),M(`Browser Sandbox stopped before it could validate the app: ${D}`,"blocked"),G(n,"failed")}finally{We(!1),ze(null),Q.current=null,window.clearTimeout(m)}}async function un(r,n,i){var S,w,C,v;(S=Q.current)==null||S.abort();const o=new AbortController,c=Date.now();Q.current=o,We(!0),ze(n),He(c),G(n,"reading");const m=window.setTimeout(()=>{o.abort()},18e4);try{const k=j.replace(/\/$/,""),I=async $=>{const T=await fetch(`${k}/read-files`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:$,projectDir:b})}),P=await O(T,"Local bridge /read-files");if(!T.ok||!P.ok||!P.files)throw new Error(P.error||"Bridge could not read target files.");return P.files},D=async()=>{const $=await fetch(`${k}/workspace-context`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:b})}),T=await O($,"Local bridge /workspace-context");if(!$.ok||!T.ok||!T.workspaceContext)throw new Error(T.error||"Bridge could not read workspace context.");return T.workspaceContext};let ie=i;const ve=async({currentFiles:$,workspaceContext:T,diagnostics:P=[],repair:V=!1})=>{const re=ie||(await Ke({projectId:h,message:r,currentFiles:$,workspaceContext:T,diagnostics:P,repair:V,generationModel:J.model,generationReasoningEffort:J.reasoningEffort,repairModel:J.model,repairReasoningEffort:J.reasoningEffort},{accessToken:a,apiServiceUrl:s,signal:o.signal})).revision;if(ie=void 0,!re)throw new Error("Data App Builder did not return a revision.");return re},je=async $=>{const T=await fetch(`${k}/apply-files`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({revision:$,projectDir:b})}),P=await O(T,"Local bridge /apply-files");if(!T.ok&&!P.command&&!P.writePolicyValidation&&!P.importValidation&&!P.dataApiValidation)throw new Error(P.error||"Bridge could not apply generated files.");return P},Pe=async()=>{const $=await fetch(`${k}/validate-typecheck`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:b})}),T=await O($,"Local bridge /validate-typecheck");if(!$.ok&&!T.command)throw new Error(T.error||"Bridge could not typecheck the target app.");return T},le=await D();le.projectRoot&&E(le.projectRoot);let K=(C=(w=le.files)==null?void 0:w.editable)!=null&&C.length?Rr(le.files.editable):["src/App.tsx"];const de=await I(K),te=de.reduce(($,T)=>$+T.contents.length,0);let ee=[];if(Vn(r)){const $=await Pe();$.ok||(ee=[Bt($)])}let Fe=de,_=null;const fe=[];for(let $=0;$<Te;$+=1){const T=ee.length>0||$>0,P=T?`repair-${$+1}`:"initial";G(n,T?"repairing":"generating");const V=await ve({currentFiles:Fe,workspaceContext:le,diagnostics:ee,repair:T});G(n,"writing");const re=await je({...V,attemptLabel:P});if(W(f),q(Me=>Me+1),fe.push(...re.attempts||[]),_={...re,attempts:[...fe],filePlan:V.plan,telemetry:{contextFileCount:de.length,contextChars:te,generatedFileCount:V.files.length,generatedChars:V.files.reduce((Me,Sn)=>Me+Sn.contents.length,0),repairAttempts:fe.filter(Me=>Me.label.startsWith("repair")).length}},G(n,"typechecking"),re.ok||$===Te-1)break;Fe=(((v=re.changedFiles)==null?void 0:v.length)||0)>0?await I(K=Array.from(new Set([...K,...re.changedFiles||[]]))):V.files,ee=[Bt(re)]}if(!_)throw new Error("The app-builder loop ended without a validation result.");G(n,_.ok?"complete":"failed"),qe(n,{status:_.ok?"done":"failed",result:_,error:_.error,finishedAt:Date.now()}),M(fr(_,"bridge"),_.ok?"default":"blocked")}catch(k){const I=k instanceof DOMException&&k.name==="AbortError",D=I?"Timed out waiting for the app-builder/bridge loop. The target app may still have updated through HMR.":k instanceof Error?k.message:String(k);qe(n,{status:I?"cancelled":"failed",error:D,result:{ok:!1,error:D,summary:"The app-builder/bridge loop stopped before validation completed."},finishedAt:Date.now()}),M(`Local Bridge stopped before it could validate the app: ${D}`,"blocked"),G(n,"failed")}finally{We(!1),ze(null),Q.current=null,window.clearTimeout(m)}}async function pn(r){var c,m;let n=U.current;n||(n=await Ye.loadSemaphorBrowserRuntime(),U.current=n);const i=n.readBrowserSandboxWorkspaceContext(),o=(m=(c=i.files)==null?void 0:c.editable)!=null&&m.length?Br(i.files.editable,ye.current,r):["src/App.tsx"];return{currentFiles:n.readBrowserSandboxFiles(o),workspaceContext:i}}async function hn(r){const n=U.current;return n?n.readBrowserSandboxFiles(r):[]}async function Nt(r,n){const i=j.replace(/\/$/,""),o=await fetch(`${i}/read-files`,{method:"POST",signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r,projectDir:b})}),c=await O(o,"Local bridge /read-files");if(!o.ok||!c.ok||!c.files)throw new Error(c.error||"Bridge could not read requested files.");return c.files}function mn(r,n){const i=new Map;for(const o of r)i.set(o.path,o);for(const o of n)i.set(o.path,o);return Array.from(i.values())}async function xr(r){var S,w;await kt(r);const n=j.replace(/\/$/,""),i=await fetch(`${n}/workspace-context`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:b})}),o=await O(i,"Local bridge /workspace-context");if(!i.ok||!o.ok||!o.workspaceContext)throw new Error(o.error||"Bridge could not read workspace context.");const c=o.workspaceContext;c.projectRoot&&E(c.projectRoot);const m=(w=(S=c.files)==null?void 0:S.editable)!=null&&w.length?Rr(c.files.editable):["src/App.tsx"];return{currentFiles:await Nt(m,r),workspaceContext:c}}function gr(r,n){return{schemaVersion:"data-app/v1",app:{id:me||void 0,name:`${g} Data App`,createdWith:"semaphor-app-builder"},runtime:{framework:r.framework,bundler:r.framework==="vite-react"?"vite":void 0},semaphor:{projectId:h,runtime:A,intentManifest:Ue||void 0},build:{sourceFileCount:n.files.length,validation:r.validation}}}async function br(r){var S,w,C,v,k,I;const{workspaceContext:n}=await xr(r),i=j.replace(/\/$/,""),o=await fetch(`${i}/source-snapshot`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:b})});if(o.ok){const D=await O(o,"Local bridge /source-snapshot");if(!D.ok||!((S=D.files)!=null&&S.length))throw new Error(D.error||"Bridge did not return source snapshot files.");return{workspaceContext:n,snapshot:{schemaVersion:"data-app-source-snapshot/v1",files:D.files,metadata:{...D.metadata,capturedAt:typeof((w=D.metadata)==null?void 0:w.capturedAt)=="string"?D.metadata.capturedAt:new Date().toISOString(),projectRoot:n.projectRoot||b,runtime:A}}}}const c=(v=(C=n.files)==null?void 0:C.snapshot)!=null&&v.length?n.files.snapshot:[...((k=n.files)==null?void 0:k.source)||[],...((I=n.files)==null?void 0:I.root)||[]],m=await Nt([...new Set(c.length?c:["src/App.tsx"])],r);return{workspaceContext:n,snapshot:{schemaVersion:"data-app-source-snapshot/v1",files:m,metadata:{capturedAt:new Date().toISOString(),projectRoot:n.projectRoot||b,runtime:A}}}}async function fn(r,n){var m,S;const i=j.replace(/\/$/,""),o=await fetch(`${i}/source-snapshot`,{method:"POST",signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:r})});if(!o.ok)return null;const c=await O(o,"Local bridge /source-snapshot");return!c.ok||!((m=c.files)!=null&&m.length)?null:{schemaVersion:"data-app-source-snapshot/v1",files:c.files,metadata:{...c.metadata,capturedAt:typeof((S=c.metadata)==null?void 0:S.capturedAt)=="string"?c.metadata.capturedAt:new Date().toISOString(),projectRoot:r,runtime:A}}}async function xn(r,n,i){const o=j.replace(/\/$/,""),c=await fetch(`${o}/apply-files`,{method:"POST",signal:i,headers:{"Content-Type":"application/json"},body:JSON.stringify({revision:r,projectDir:n})}),m=await O(c,"Local bridge /apply-files");if(!c.ok||!m.ok)throw new Error(m.error||"Bridge could not restore saved files.");return m}async function gn({snapshot:r,targetProjectDir:n,signal:i}){const o=await fn(n,i);if(!o)throw new Error(`Bridge could not compare the current workspace before restore: ${n}`);const c=new Map(o.files.map(C=>[C.path,C.contents])),m=r.files.filter(C=>c.get(C.path)!==C.contents),S=Math.max(0,o.files.length-r.files.length);return o&&m.length===0||!window.confirm(["Restore this saved Data App source snapshot into the bridge workspace?","",`Target workspace: ${n}`,"",`${m.length||r.files.length} saved file${(m.length||r.files.length)===1?"":"s"} will be written. Extra local files are left unchanged.`,S?`${S} extra local file${S===1?"":"s"} may remain in the workspace.`:""].filter(Boolean).join(`
|
|
49
|
+
`))?!1:(await xn({provider:"semaphor",summary:"Restore saved Data App source snapshot",files:r.files.map(C=>({path:C.path,contents:C.contents})),changes:r.files.map(C=>({kind:"edit",label:C.path}))},n,i),!0)}async function bn(){var c,m,S,w;let r=U.current;r||(r=await Ye.loadSemaphorBrowserRuntime(),U.current=r);const n=r.readBrowserSandboxWorkspaceContext(),i=(m=(c=n.files)==null?void 0:c.snapshot)!=null&&m.length?n.files.snapshot:[...((S=n.files)==null?void 0:S.source)||[],...((w=n.files)==null?void 0:w.root)||[]],o=r.readBrowserSandboxFiles([...new Set(i.length?i:["src/App.tsx"])]);return{workspaceContext:n,snapshot:{schemaVersion:"data-app-source-snapshot/v1",files:o,metadata:{capturedAt:new Date().toISOString(),projectRoot:"browser-sandbox",runtime:A}}}}async function wr(){const r=new AbortController;dr(!0),bt(null);try{const{workspaceContext:n,snapshot:i}=A==="browser"?await bn():await br(r.signal),o=gr(n,i);or(JSON.stringify(o,null,2))}catch(n){bt(n instanceof Error?n.message:String(n))}finally{dr(!1)}}async function yr(){if(De.current)return De.current;if(!yt)return M("Save draft is not configured in this host yet.","blocked"),null;const r=new AbortController;pt("saving"),we(null),H({state:"running",label:"Saving draft",detail:"Reading the bridge source snapshot."});const n=(async()=>{var i;try{const{snapshot:o,workspaceContext:c}=await br(r.signal),m=gr(c,o),S=await rs({snapshot:o,workspaceContext:c,projectDir:b,adapter:"bridge"}),w=await yt({projectId:h,dataAppId:me,title:me?void 0:((i=m.app)==null?void 0:i.name)||`${g} Data App`,description:me?void 0:null,manifest:m,sourceSnapshot:o,sourceRevision:S,validationStatus:(jt==null?void 0:jt.result)||null,bridgeWorkspaceHint:c.projectRoot||b},{apiServiceUrl:s,accessToken:a,signal:r.signal});return Je(w.dataAppId),rr(w.savedAt||new Date().toISOString()),pt("saved"),H({state:"done",label:"Draft saved",detail:"Semaphor has the latest source snapshot."}),M("Draft saved to Semaphor.","default"),{dataAppId:w.dataAppId,draftId:w.draftId,manifest:m,snapshot:o,sourceRevision:S,workspaceContext:c}}catch(o){const c=o instanceof Error?o.message:String(o);return we(c),pt("failed"),H({state:"failed",label:"Save draft failed",detail:c}),M(`Save draft failed: ${c}`,"blocked"),null}finally{De.current=null}})();return De.current=n,n}async function wn(r){var c;const n=j.replace(/\/$/,""),i=await fetch(`${n}/publish-build`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:b})}),o=await O(i,"Local bridge /publish-build");if(!i.ok||!o.ok||!o.manifest||!o.entryFile||!((c=o.assets)!=null&&c.length))throw new Error(o.error||"Bridge could not build publish artifacts.");return o}async function yn(){if(!vt){M("Publish is not configured in this host yet.","blocked");return}if(_e==="saving"&&!De.current){M("Save draft is already in progress.","blocked");return}const r=await yr(),n=(r==null?void 0:r.dataAppId)||me;if(!r||!n||!r.draftId){M("Save the Data App before publishing.","blocked");return}const i=new AbortController;ht("publishing"),we(null),H({state:"running",label:"Preparing publish",detail:"Checking draft state before the local build."});try{H({state:"running",label:"Starting publish",detail:"Creating a publish session from the saved draft."});const o=await vt({projectId:h,dataAppId:n,draftId:r.draftId,title:`${g} Data App`,description:null,sourceSnapshot:r.snapshot,sourceRevision:r.sourceRevision,bridgeWorkspaceHint:r.workspaceContext.projectRoot||b,buildArtifacts:async({signal:c})=>{const m=await wn(c),S=m.assets;return{manifest:{...m.manifest,semaphor:{...m.manifest.semaphor||{},projectId:h,runtime:A,intentManifest:Ue||void 0}},validationStatus:m,bridgeWorkspaceHint:r.workspaceContext.projectRoot||b,assets:S,entryFile:m.entryFile,styleFiles:m.styleFiles||[]}}},{apiServiceUrl:s,accessToken:a,signal:i.signal,onProgress:c=>{H({state:"running",label:c.label,detail:c.detail})}});Je(o.dataAppId),sr(o.publishedAt||new Date().toISOString()),ht("published"),H({state:"done",label:"Published",detail:`Version ${o.version??o.versionId} is ready.`}),M(`Published Data App version ${o.version??o.versionId}.`,"default")}catch(o){const c=o instanceof Error?o.message:String(o);we(c),ht("failed"),H({state:"failed",label:"Publish failed",detail:c}),M(`Publish failed: ${c}`,"blocked")}}async function vn(r){var m,S;const{attachments:n,prompt:i}=r,o=new AbortController;Q.current=o,Tt(!0);const c=window.setTimeout(()=>{o.abort()},18e4);try{ne("context"),se("Reading the app manifest and starter context.");let w=A==="browser"?await pn(i):await xr(o.signal);const C=[];let v=null;for(;ne("thinking"),se(w.currentFiles.length>0?"Reviewing the app context and deciding the next step.":"Deciding whether this needs an answer, file inspection, or edits."),v=await Ke({projectId:h,message:i,currentFiles:w.currentFiles,workspaceContext:w.workspaceContext,conversationContext:Pr(nt.current,Ue),attachments:n,repair:!1,allowFileReads:!0,generationModel:J.model,generationReasoningEffort:J.reasoningEffort,repairModel:J.model,repairReasoningEffort:J.reasoningEffort},{accessToken:a,apiServiceUrl:s,signal:o.signal,onProgress:pr}),!(!v||v.mode!=="read_files");){const D=(v.requestedFiles||[]).filter(ve=>typeof ve=="string"&&!w.currentFiles.some(je=>je.path===ve));if(D.length===0){ne("thinking"),se("No additional source files are needed; preparing the response."),v=await Ke({projectId:h,message:i,currentFiles:w.currentFiles,workspaceContext:w.workspaceContext,conversationContext:Pr(nt.current,Ue),attachments:n,repair:!1,allowFileReads:!1,generationModel:J.model,generationReasoningEffort:J.reasoningEffort,repairModel:J.model,repairReasoningEffort:J.reasoningEffort},{accessToken:a,apiServiceUrl:s,signal:o.signal,onProgress:pr});break}ne("reading-files"),se(`Reading ${D.length} requested file${D.length===1?"":"s"}: ${qn(D)}.`),C.push({tool:"read_files",status:"done",detail:D.join(", ")});const ie=A==="browser"?await hn(D):await Nt(D,o.signal);w={...w,currentFiles:mn(w.currentFiles,ie)}}if(!v)throw new Error("Data App Builder did not return a turn.");if(C.length>0&&(v={...v,toolEvents:[...C,...v.toolEvents||[]]}),Zr(v),v.mode==="read_files"){M("I could not gather enough additional source context for that change. Please point me at the component or file you want to change, or try a narrower instruction.","guidance");return}if(v.mode!=="edit"){M(v.message,v.mode==="clarify"?"guidance":"default",{artifacts:v.artifacts,operation:v.operation,intentManifest:v.intentManifest});return}if(!v.revision)throw new Error("Data App Builder chose an edit but returned no revision.");M(Qn(v),"guidance",{operation:v.operation,intentManifest:v.intentManifest}),ne("planning"),se((S=(m=v.revision.plan)==null?void 0:m.files)!=null&&S.length?`Preparing edits for ${v.revision.plan.files.length} file${v.revision.plan.files.length===1?"":"s"}.`:"Preparing the file edit and validation run.");const k=ue("run"),I=Date.now();pe(D=>[...D,{id:k,type:"run",prompt:i,status:"running",steps:_n(),createdAt:I,startedAt:I}]),Q.current=null,A==="browser"?cn(i,k,v.revision):un(i,k,v.revision)}catch(w){const C=w instanceof DOMException&&w.name==="AbortError";M(C?"The app-builder turn timed out before a response was produced.":w instanceof Error?w.message:String(w),"blocked")}finally{Tt(!1),ne("idle"),se(null),Ot(null),Q.current===o&&(Q.current=null),window.clearTimeout(c)}}function jn(r){r.preventDefault();const n=Le.trim();if(!n)return;const i=Date.now(),o=tt,c={id:ue("turn"),prompt:n,attachments:o,createdAt:i};if(et(""),Ie([]),Y||Z){Ae(m=>[...m,c]);return}hr(c)}return e.jsxs(y.ResizablePanelGroup,{autoSaveId:`semaphor-data-app-builder-${h}`,className:"h-full min-h-0 flex-1",direction:"horizontal",children:[Ce?e.jsxs(e.Fragment,{children:[e.jsx(y.ResizablePanel,{className:"min-w-[320px] max-w-[760px]",defaultSize:28,maxSize:55,minSize:18,order:1,children:e.jsxs("aside",{className:"flex h-full min-h-0 flex-col border-r border-border",children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-2 border-b border-border px-3",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Chat"}),e.jsx("div",{className:"ml-auto flex min-w-0 items-center gap-2",children:N?e.jsxs(y.AlertDialog,{children:[e.jsx(y.AlertDialogTrigger,{asChild:!0,children:e.jsxs(x.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 px-1.5 text-muted-foreground",title:"Discard this conversation",children:[e.jsx(y.SquarePen,{className:"h-3.5 w-3.5"}),"New session"]})}),e.jsxs(y.AlertDialogContent,{children:[e.jsxs(y.AlertDialogHeader,{children:[e.jsx(y.AlertDialogTitle,{children:"Discard this conversation?"}),e.jsx(y.AlertDialogDescription,{children:"This clears the chat and run history in the builder and starts a new session. Generated files in your project are not affected."})]}),e.jsxs(y.AlertDialogFooter,{children:[e.jsx(y.AlertDialogCancel,{children:"Cancel"}),e.jsx(y.AlertDialogAction,{onClick:N,children:"Discard"})]})]})]}):null})]}),e.jsx("div",{ref:st,className:"min-h-0 flex-1 overflow-y-auto px-3 py-4",children:e.jsxs("div",{className:"space-y-4",children:[X.length===0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[12.5px] font-medium text-foreground",children:"Start with a question or a build instruction"}),e.jsx("p",{className:"mt-1 text-[11.5px] leading-relaxed text-muted-foreground",children:"Ask about the current files, or describe the app you want."}),e.jsx("div",{className:"mt-3 grid gap-1.5",children:Fn.slice(0,3).map(r=>e.jsxs("button",{type:"button",onClick:()=>et(r.prompt),className:"rounded-[5px] border border-border px-2.5 py-2 text-left transition-colors hover:border-foreground/40",children:[e.jsx("div",{className:"truncate text-[11.5px] font-medium text-foreground",children:r.title}),e.jsx("div",{className:"mt-0.5 line-clamp-2 text-[10.5px] leading-relaxed text-muted-foreground",children:r.description})]},r.id))})]}),X.map(r=>r.type==="user"?e.jsx(fs,{message:r},r.id):r.type==="assistant"?e.jsx(gs,{message:r,onOpenDatasetInspector:Ve},r.id):e.jsx(vs,{getStepDuration:qr,run:r},r.id)),Z&&!Gr&&e.jsx(ys,{phase:Lr,detail:Ir,elapsedMs:Et?Math.max(0,Lt-Et):0})]})}),e.jsxs("form",{onSubmit:jn,className:"border-t border-border p-3",children:[Ne.length>0?e.jsx(ms,{turns:Ne,onDelete:ln,onRemoveAttachment:dn,onUpdatePrompt:on}):null,e.jsxs("div",{className:"rounded-[6px] border border-border focus-within:border-ring",children:[e.jsx("textarea",{value:Le,onChange:r=>et(r.target.value),onPaste:r=>{const n=Array.from(r.clipboardData.files).filter(i=>i.type.startsWith("image/"));n.length!==0&&(r.preventDefault(),mr(n))},onKeyDown:r=>{var n;r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),(n=r.currentTarget.form)==null||n.requestSubmit())},placeholder:"Ask a question, or write a build instruction like “Add a select filter for region”",className:"block min-h-[64px] w-full resize-none bg-transparent px-2.5 py-2 text-[13px] leading-relaxed text-foreground placeholder:text-muted-foreground focus:outline-none"}),tt.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5 border-t border-border px-2 py-2",children:tt.map(r=>e.jsx(Ft,{attachment:r,onRemove:tn},r.id))}):null,e.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border px-2 py-1.5",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx("input",{ref:zt,type:"file",accept:"image/*",className:"hidden",multiple:!0,onChange:r=>{r.target.files&&mr(r.target.files),r.target.value=""}}),e.jsxs(x.Popover,{children:[e.jsx(x.PopoverTrigger,{asChild:!0,children:e.jsx(x.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",title:"Add context","aria-label":"Add context",children:e.jsx(y.Plus,{className:"h-3.5 w-3.5"})})}),e.jsx(x.PopoverContent,{align:"start",side:"top",className:"w-44 p-1",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left text-[12px] text-foreground hover:bg-muted",onClick:()=>{var r;return(r=zt.current)==null?void 0:r.click()},children:[e.jsx(Dn,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Screenshot"]})})]}),e.jsxs(x.Select,{value:rt,onValueChange:zr,children:[e.jsx(x.SelectTrigger,{"aria-label":"Generation model",title:"Model used to generate changes",className:"h-7 w-auto gap-1.5 border-0 bg-transparent px-1.5 text-[11px] text-muted-foreground shadow-none hover:text-foreground focus:ring-0",children:e.jsx(x.SelectValue,{placeholder:"Model"})}),e.jsx(x.SelectContent,{align:"start",children:$t.map(r=>e.jsx(x.SelectItem,{value:r.id,className:"text-[12px]",children:r.label},r.id))})]})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:Y||Z?e.jsxs(e.Fragment,{children:[e.jsx(x.Button,{type:"submit",size:"xs",variant:"outline",className:"gap-1.5",disabled:!Le.trim(),children:"Queue"}),e.jsxs(x.Button,{type:"button",variant:"outline",size:"xs",className:"gap-1.5",title:"Stop the current run",onClick:()=>{var r;return(r=Q.current)==null?void 0:r.abort()},children:[e.jsx(x.X,{className:"h-3 w-3"}),"Stop"]})]}):e.jsxs(x.Button,{type:"submit",size:"xs",className:"gap-1.5",disabled:!Le.trim(),children:[e.jsx(y.Send,{className:"h-3 w-3"}),"Send"]})})]})]})]})]})}),e.jsx(y.ResizableHandle,{className:"w-px bg-border/60 transition-colors hover:bg-border"})]}):null,e.jsx(y.ResizablePanel,{className:"min-w-0",defaultSize:Ce?72:100,minSize:35,order:2,children:e.jsxs("main",{className:"flex h-full min-w-0 flex-col bg-muted/40",children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-3 border-b border-border px-3",children:[e.jsx(x.Button,{type:"button",variant:"ghost",size:"xs",className:"-ml-1 gap-1.5 px-1.5 text-muted-foreground",title:Ce?"Hide chat":"Show chat","aria-label":Ce?"Hide chat":"Show chat",onClick:()=>Or(r=>!r),children:Ce?e.jsx(Pn,{className:"h-3.5 w-3.5"}):e.jsx(y.PanelLeft,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[e.jsx("span",{className:"shrink-0 text-[12px] font-medium text-foreground",children:"Live preview"}),e.jsx("span",{className:"min-w-0 truncate font-mono text-[11px] text-muted-foreground",children:A==="browser"?"browser sandbox":F})]}),A==="browser"&&dt&&e.jsxs("span",{className:`text-[10.5px] ${dt==="tailwind"?"text-emerald-700 dark:text-emerald-400":"text-amber-700 dark:text-amber-400"}`,children:["CSS: ",dt]}),Wt?e.jsx("span",{className:"min-w-0 truncate text-[11px] text-blue-700 dark:text-blue-400",children:Wt}):null,mt?e.jsx("span",{className:"min-w-0 truncate text-[11px] text-destructive",title:mt,children:mt}):nr?e.jsxs("span",{className:"min-w-0 truncate text-[11px] text-emerald-700 dark:text-emerald-400",children:["Published ",new Date(nr).toLocaleTimeString()]}):tr?e.jsxs("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:["Saved ",new Date(tr).toLocaleTimeString()]}):null,e.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[e.jsxs(x.Popover,{open:xt,onOpenChange:r=>{Ge(r),r&&wr()},children:[e.jsx(x.PopoverTrigger,{asChild:!0,children:e.jsxs(x.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",title:"Inspect the current Data App manifest",children:[lr?e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(y.FileCode,{className:"h-3.5 w-3.5"}),"Manifest"]})}),e.jsxs(x.PopoverContent,{align:"end",sideOffset:6,className:"w-[520px] p-0",onInteractOutside:()=>Ge(!1),onEscapeKeyDown:()=>Ge(!1),children:[e.jsxs("div",{className:"flex h-10 items-center gap-2 border-b border-border px-3",children:[e.jsx(y.FileCode,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[12px] font-medium text-foreground",children:"App manifest"}),e.jsx("div",{className:"truncate text-[10.5px] text-muted-foreground",children:"Current draft shape generated from the active runtime context"})]}),e.jsx(x.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",disabled:!gt,title:"Copy manifest JSON","aria-label":"Copy manifest JSON",onClick:()=>{var r;(r=navigator.clipboard)==null||r.writeText(gt)},children:e.jsx(y.Copy,{className:"h-3.5 w-3.5"})}),e.jsx(x.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",title:"Refresh manifest","aria-label":"Refresh manifest",onClick:()=>void wr(),children:e.jsx(y.RefreshCw,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"max-h-[520px] overflow-auto bg-muted/30 p-3",children:lr?e.jsxs("div",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-3 py-2 text-[12px] text-muted-foreground",children:[e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Reading current runtime manifest..."]}):ir?e.jsx("div",{className:"rounded-[5px] border border-destructive/30 bg-destructive/10 px-3 py-2 text-[12px] text-destructive",children:ir}):e.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-[5px] border border-border bg-background p-3 font-mono text-[11px] leading-relaxed text-muted-foreground",children:gt||"Open or refresh to inspect the manifest."})})]})]}),e.jsxs(y.AlertDialog,{children:[e.jsx(y.AlertDialogTrigger,{asChild:!0,children:e.jsxs(x.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",disabled:Y||Z,title:"Reset the app to a blank development template",children:[e.jsx(x.RotateCcw,{className:"h-3.5 w-3.5"}),"Reset app"]})}),e.jsxs(y.AlertDialogContent,{children:[e.jsxs(y.AlertDialogHeader,{children:[e.jsx(y.AlertDialogTitle,{children:"Reset this app?"}),e.jsx(y.AlertDialogDescription,{children:"This restores the active Data App workspace to the blank starter template and clears the builder's current app memory. Saved or published versions in Semaphor are not changed."})]}),e.jsxs(y.AlertDialogFooter,{children:[e.jsx(y.AlertDialogCancel,{children:"Cancel"}),e.jsx(y.AlertDialogAction,{onClick:()=>void Qr(),children:"Reset app"})]})]})]}),e.jsxs(x.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",disabled:Y||Z||_e==="saving"||A!=="bridge"||!yt,title:"Save the current local source snapshot as a Semaphor draft",onClick:()=>void yr(),children:[_e==="saving"?e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Nn.Save,{className:"h-3.5 w-3.5"}),"Save draft"]}),e.jsxs(x.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",disabled:Y||Z||_e==="saving"||er==="publishing"||A!=="bridge"||!vt,title:"Build, upload, and publish the current Data App",onClick:()=>void yn(),children:[er==="publishing"?e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Rn,{className:"h-3.5 w-3.5"}),"Publish"]}),A==="bridge"?e.jsxs(x.Button,{type:"button",variant:he?"default":"ghost",size:"xs",disabled:Jt,className:he?"gap-1.5":"gap-1.5 text-muted-foreground",title:"Select an element in the preview and attach its DOM/React context",onClick:()=>he?sn():void nn(),children:[Jt?e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx($n,{className:"h-3.5 w-3.5"}),he?"Cancel inspect":"Inspect"]}):null,e.jsxs(x.Popover,{children:[e.jsx(x.PopoverTrigger,{asChild:!0,children:e.jsxs(x.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",children:[e.jsx(y.Settings2,{className:"h-3.5 w-3.5"}),"Runtime",A==="browser"&<.length>0?e.jsx("span",{className:"text-[10px] text-amber-600",children:"CSS fallback"}):null]})}),e.jsx(x.PopoverContent,{align:"end",sideOffset:6,className:"w-[380px] p-3",children:A==="bridge"?e.jsxs("div",{className:"space-y-2.5",children:[e.jsx(Dt,{label:"App Directory",value:b,placeholder:Ct,onChange:E}),e.jsx(Dt,{label:"App Local URL",value:f,onChange:R}),e.jsx(Dt,{label:"Bridge URL",value:j,onChange:B})]}):e.jsxs("div",{className:"text-[11px] leading-relaxed text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"min-w-0",children:"Browser files are stored locally in this browser."}),e.jsx(x.Button,{type:"button",variant:"outline",size:"xs",className:"h-6 shrink-0 text-[10.5px]",disabled:Y||Z||Be!=="ready",onClick:()=>void ur(),children:"Reset"})]}),lt[0]?e.jsx("div",{className:"mt-2 rounded-[5px] border border-border bg-muted/40 px-2 py-1.5 text-muted-foreground",children:lt[0]}):null,e.jsx(as,{manifest:_r})]})})]}),e.jsx(x.Button,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0 text-muted-foreground",title:"Reload the live preview","aria-label":"Reload the live preview",onClick:()=>{A==="browser"?(Qe(),$e()):(W(f),q(r=>r+1))},children:e.jsx(y.RefreshCw,{className:"h-3.5 w-3.5"})})]})]}),oe?e.jsx("div",{className:"shrink-0 border-b border-border bg-background px-3 py-2",children:e.jsxs("div",{className:`flex items-start gap-2 rounded-[6px] border px-2.5 py-2 text-[11.5px] leading-relaxed ${oe.state==="failed"?"border-destructive/30 bg-destructive/10 text-destructive":oe.state==="done"?"border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-300":"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-900/60 dark:bg-blue-950/30 dark:text-blue-300"}`,children:[oe.state==="running"?e.jsx(x.LoaderCircle,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin"}):oe.state==="done"?e.jsx(x.Check,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}):e.jsx(x.X,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:oe.label}),oe.detail?e.jsx("div",{className:"mt-0.5 truncate opacity-80",children:oe.detail}):null]})]})}):null,(A==="browser"&&(Be==="loading"||Be==="failed")||Re&&!((vr=Re.appBuilder)!=null&&vr.hasOpenAiKey))&&e.jsxs("div",{className:"shrink-0 border-b border-border px-3 py-2",children:[A==="browser"&&Be==="loading"&&e.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:"Loading the in-browser runtime…"}),A==="browser"&&Be==="failed"&&e.jsxs("div",{className:"rounded-[5px] border border-border bg-muted/40 px-2 py-1.5 text-[11px] leading-relaxed text-muted-foreground",children:["Browser runtime is unavailable. Link or install semaphor-browser-runtime, or use the local bridge path.",Vt?e.jsx("pre",{className:"mt-1.5 whitespace-pre-wrap font-mono text-[10.5px] text-muted-foreground",children:Vt}):null]}),Re&&!((jr=Re.appBuilder)!=null&&jr.hasOpenAiKey)&&e.jsx("div",{className:"rounded-[5px] border border-destructive/30 bg-destructive/10 px-2 py-1.5 text-[11px] text-destructive",children:Re.error||"OPENAI_API_KEY is not configured."})]}),A==="browser"&&Hr.length>0&&e.jsx("div",{className:"shrink-0 border-b border-border px-3 py-1.5 text-[11px] text-amber-700 dark:text-amber-400",children:"Preview compiled with diagnostics. The next prompt can use them for repair."}),e.jsxs("div",{className:"flex min-h-0 flex-1",children:[A==="browser"&&e.jsxs("aside",{className:"flex w-[300px] shrink-0 flex-col border-r border-border",children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-2 border-b border-border px-3",children:[e.jsx(y.CodeXml,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11.5px] font-medium text-foreground",children:"Files"}),e.jsx("span",{className:"ml-auto font-mono text-[10px] text-muted-foreground",children:Xt.length})]}),e.jsx("div",{className:"max-h-72 shrink-0 overflow-y-auto border-b border-border p-2",children:e.jsx(ss,{files:Xt,selectedPath:ct,onSelect:Kr})}),e.jsx("pre",{className:"min-h-0 flex-1 overflow-auto p-3 font-mono text-[11px] leading-relaxed text-muted-foreground",children:(ut==null?void 0:ut.contents)||"Select a file to inspect its source."})]}),e.jsx("iframe",{ref:at,className:"min-h-0 flex-1 bg-background",onLoad:()=>{he&&window.setTimeout(()=>Xe("inspect-enable"),100)},src:A==="browser"?void 0:St,srcDoc:A==="browser"?Wr:void 0,title:"Data app preview"},A==="browser"?`browser-${ge}`:St),ar?e.jsx(ws,{artifact:ar,onClose:()=>Ve(null)}):null]})]})})]})}function Dt({label:t,value:s,placeholder:a,onChange:d}){return e.jsxs("label",{className:"grid min-w-0 gap-1",children:[e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:t}),e.jsx("input",{value:s,placeholder:a,spellCheck:!1,autoComplete:"off",onChange:l=>d(l.target.value),onFocus:l=>l.target.select(),className:"h-8 w-full min-w-0 rounded-[5px] border border-border bg-background px-2 font-mono text-[12px] text-foreground outline-none focus:border-ring"})]})}function ds({code:t,lang:s}){const[a,d]=p.useState(!1);return e.jsxs("div",{className:"my-2 overflow-hidden rounded-[6px] border border-border",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border bg-muted/40 px-2.5 py-1",children:[e.jsx("span",{className:"font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground",children:s||"code"}),e.jsx("button",{type:"button",onClick:()=>{var l;(l=navigator.clipboard)==null||l.writeText(t),d(!0),window.setTimeout(()=>d(!1),1500)},className:"inline-flex items-center gap-1 rounded-[4px] px-1.5 py-0.5 text-[10.5px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground",children:a?e.jsxs(e.Fragment,{children:[e.jsx(x.Check,{className:"h-3 w-3"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(y.Copy,{className:"h-3 w-3"}),"Copy"]})})]}),e.jsx("div",{className:"overflow-x-auto bg-background",children:e.jsx(y.CodeHighlighter,{code:t,language:s||"tsx"})})]})}const cs=/(\b[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*\.(?:tsx?|jsx?|mjs|cjs|css|scss|json|mdx?|html?|ya?ml|toml|sql|sh|py|rb|go|rs)\b)/g;function us(t,s){return t.split(cs).map((a,d)=>d%2===1?e.jsxs("span",{className:"mx-px inline-flex items-baseline gap-1 rounded-[4px] border border-border bg-muted/60 px-1 font-mono text-[0.82em] text-foreground",children:[e.jsx(y.FileCode,{className:"h-3 w-3 shrink-0 translate-y-[1px] text-muted-foreground"}),a]},`${s}-f${d}`):e.jsx("span",{children:a},`${s}-t${d}`))}function ps(t,s){return t.split(`
|
|
50
|
+
`).map((a,d)=>e.jsxs("span",{children:[d>0?e.jsx("br",{}):null,a.split(/(`[^`]+`|\*\*[^*]+\*\*)/g).map((l,u)=>l.length>1&&l.startsWith("`")&&l.endsWith("`")?e.jsx("code",{className:"mx-px rounded-[4px] bg-foreground/10 px-1 font-mono text-[0.85em] text-foreground",children:l.slice(1,-1)},u):l.length>4&&l.startsWith("**")&&l.endsWith("**")?e.jsx("strong",{className:"font-semibold text-foreground",children:l.slice(2,-2)},u):e.jsx("span",{children:us(l,`${s}-${d}-${u}`)},u))]},`${s}-${d}`))}function hs(t){return t.split("```").map((s,a)=>{if(a%2===1){let d="",l=s;const u=s.indexOf(`
|
|
51
|
+
`);if(u!==-1){const h=s.slice(0,u).trim();h&&/^[A-Za-z0-9_.+-]{1,16}$/.test(h)&&(d=h,l=s.slice(u+1))}return l=l.replace(/^\n/,"").replace(/\s+$/,""),e.jsx(ds,{code:l,lang:d},a)}return e.jsx("span",{children:ps(s,a)},a)})}function ms({turns:t,onDelete:s,onRemoveAttachment:a,onUpdatePrompt:d}){var g;const[l,u]=p.useState(!1),h=t.length;return e.jsxs("div",{className:"mb-2 overflow-hidden rounded-[6px] border border-border bg-muted/40",children:[e.jsxs("button",{type:"button",onClick:()=>u(N=>!N),"aria-expanded":l,className:"flex w-full items-center gap-2 px-2.5 py-1.5 text-left",children:[e.jsx(y.ChevronRight,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform ${l?"rotate-90":""}`}),e.jsxs("span",{className:"shrink-0 text-[12px] font-medium text-foreground",children:[h," queued"]}),l?null:e.jsxs("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:["· ",((g=t[0])==null?void 0:g.prompt.trim())||"Queued instruction"]}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:l?"Hide":"Show"})]}),l?e.jsx("div",{className:"max-h-[200px] space-y-1.5 overflow-y-auto border-t border-border p-2",children:t.map((N,f)=>e.jsxs("div",{className:"rounded-[5px] border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1.5 flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:["Next ",f+1]}),e.jsx("button",{type:"button",className:"rounded-[4px] px-1.5 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>s(N.id),children:"Remove"})]}),e.jsx("textarea",{value:N.prompt,onChange:R=>d(N.id,R.target.value),className:"block min-h-[44px] w-full resize-none rounded-[4px] border border-border bg-transparent px-2 py-1.5 text-[12px] leading-relaxed text-foreground focus:border-ring focus:outline-none",placeholder:"Queued instruction"}),N.attachments.length>0?e.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:N.attachments.map(R=>e.jsx(Ft,{attachment:R,onRemove:j=>a(N.id,j)},R.id))}):null]},N.id))}):null]})}function fs({message:t}){var s;return e.jsxs("div",{className:"ml-auto max-w-[88%] rounded-[6px] rounded-br-[2px] bg-foreground/10 px-3 py-2 text-[13px] leading-relaxed text-foreground",children:[e.jsx("div",{children:t.content}),(s=t.attachments)!=null&&s.length?e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.attachments.map(a=>e.jsx(Ft,{attachment:a},a.id))}):null]})}function Ft({attachment:t,onRemove:s}){const a=e.jsxs(e.Fragment,{children:[t.type==="screenshot"?e.jsxs(e.Fragment,{children:[e.jsx("img",{alt:"",className:"h-5 w-7 rounded-[3px] border border-border object-cover",src:t.imageUrl}),e.jsx("span",{className:"max-w-[140px] truncate",children:t.name})]}):e.jsxs(e.Fragment,{children:[e.jsx(y.CodeXml,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate",children:t.name})]}),s?e.jsx("button",{type:"button",className:"rounded-[3px] p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>s(t.id),"aria-label":`Remove ${t.name}`,children:e.jsx(x.X,{className:"h-3 w-3"})}):null]});return t.type==="dom-selection"?e.jsxs(x.Popover,{children:[e.jsx(x.PopoverTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex max-w-full items-center gap-1.5 rounded-[5px] border border-border bg-background px-1.5 py-1 text-[11px] text-muted-foreground hover:border-ring hover:text-foreground",title:"View captured DOM context",children:a})}),e.jsxs(x.PopoverContent,{align:"start",sideOffset:6,className:"w-[420px] p-0",children:[e.jsxs("div",{className:"border-b border-border px-3 py-2",children:[e.jsx("div",{className:"text-[12px] font-medium text-foreground",children:"Captured DOM context"}),e.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:t.name})]}),e.jsx("pre",{className:"max-h-[360px] overflow-auto whitespace-pre-wrap p-3 font-mono text-[11px] leading-relaxed text-muted-foreground",children:t.text})]})]}):e.jsx("span",{className:"inline-flex max-w-full items-center gap-1.5 rounded-[5px] border border-border bg-background px-1.5 py-1 text-[11px] text-muted-foreground",children:a})}function xs(t){var s;if(t.type==="assistant"){const{artifacts:a,...d}=t;return d}return t.type==="user"&&((s=t.attachments)!=null&&s.length)?{...t,attachments:t.attachments.filter(a=>a.type!=="screenshot")}:t}function gs({message:t,onOpenDatasetInspector:s}){var d;const a=t.tone==="blocked"?"border-destructive/30 bg-destructive/10 text-destructive":t.tone==="guidance"?"border-blue-100 bg-blue-50/60 text-blue-950":"border-border bg-background text-foreground";return e.jsxs("div",{className:`max-w-[92%] rounded-[6px] rounded-bl-[2px] border px-3 py-2 text-[13px] leading-relaxed ${a}`,children:[e.jsx("div",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Assistant"}),hs(t.content),(d=t.artifacts)==null?void 0:d.map(l=>l.type==="dataset_inspector"?e.jsx(bs,{artifact:l,onOpen:()=>s(l)},l.id):null)]})}function bs({artifact:t,onOpen:s}){return e.jsxs("button",{type:"button",onClick:s,className:"mt-2 flex w-full items-center gap-2 rounded-[5px] border border-border bg-background px-2.5 py-2 text-left transition-colors hover:border-foreground/40",children:[e.jsx(y.Database,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[12px] font-medium text-foreground",children:t.title}),e.jsxs("span",{className:"block truncate text-[10.5px] text-muted-foreground",children:[t.counts.total," fields · ",t.counts.measures," measures ·"," ",t.counts.dimensions," dimensions"]})]}),e.jsx("span",{className:"shrink-0 text-[10.5px] font-medium text-muted-foreground",children:"Open"})]})}function ws({artifact:t,onClose:s}){const[a,d]=p.useState(""),[l,u]=p.useState("all"),h=a.trim().toLowerCase(),g=t.fields.filter(f=>{var E,z;const R=(E=f.role)==null?void 0:E.toLowerCase(),j=(z=f.dataType)==null?void 0:z.toLowerCase(),B=l==="all"||l==="measures"&&(R==="measure"||R==="metric")||l==="dimensions"&&R==="dimension"||l==="dates"&&(R==="date"||j==="date"||j==="timestamp")||l==="identifiers"&&R==="identifier"||l==="calculated"&&f.source==="calculated",b=!h||[f.name,f.label,f.role,f.dataType].filter(L=>typeof L=="string").some(L=>L.toLowerCase().includes(h));return B&&b}),N=[{id:"all",label:"All",count:t.counts.total},{id:"measures",label:"Measures",count:t.counts.measures},{id:"dimensions",label:"Dimensions",count:t.counts.dimensions},{id:"dates",label:"Dates",count:t.counts.dates},{id:"identifiers",label:"IDs",count:t.counts.identifiers},{id:"calculated",label:"Calc",count:t.counts.calculated}];return e.jsxs("aside",{className:"flex w-[360px] shrink-0 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-2 border-b border-border px-3",children:[e.jsx(y.Database,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:"Field inspector"})}),e.jsx(x.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground","aria-label":"Close field inspector",onClick:s,children:e.jsx(x.X,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"shrink-0 border-b border-border p-3",children:[e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:t.title}),e.jsxs("div",{className:"mt-0.5 truncate font-mono text-[10.5px] text-muted-foreground",children:[t.domain.label," · ",t.dataset.name]}),t.dataset.primaryDateField?e.jsxs("div",{className:"mt-2 rounded-[5px] bg-muted px-2 py-1 text-[11px] text-muted-foreground",children:["Primary date: ",t.dataset.primaryDateField]}):null,e.jsxs("label",{className:"mt-3 flex h-8 items-center gap-2 rounded-[5px] border border-border bg-background px-2",children:[e.jsx(y.Search,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("input",{value:a,onChange:f=>d(f.target.value),placeholder:"Search fields",className:"min-w-0 flex-1 bg-transparent text-[12px] outline-none placeholder:text-muted-foreground"})]}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1",children:N.map(f=>e.jsxs("button",{type:"button",onClick:()=>u(f.id),className:`rounded-[5px] px-2 py-1 text-[10.5px] ${l===f.id?"bg-foreground text-background":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[f.label," ",f.count]},f.id))})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-2",children:g.length>0?e.jsx("div",{className:"space-y-1",children:g.map(f=>e.jsxs("div",{className:"rounded-[5px] border border-border px-2 py-1.5",children:[e.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:f.label||f.name}),e.jsxs("div",{className:"mt-0.5 flex min-w-0 items-center gap-1.5 text-[10.5px] text-muted-foreground",children:[e.jsx("span",{className:"truncate font-mono",children:f.name}),f.role?e.jsxs("span",{children:["· ",f.role]}):null,f.dataType?e.jsxs("span",{children:["· ",f.dataType]}):null,f.source==="calculated"?e.jsx("span",{children:"· calculated"}):null]})]},`${f.source}:${f.name}`))}):e.jsx("div",{className:"rounded-[5px] border border-dashed border-border px-3 py-6 text-center text-[12px] text-muted-foreground",children:"No fields match this search."})})]})}function ys({phase:t,detail:s,elapsedMs:a}){const d=Gn(t),l=s||Kn(t);return e.jsxs("div",{className:"max-w-[92%] rounded-[6px] rounded-bl-[2px] border border-border bg-background px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}),e.jsx("span",{className:"text-[12.5px] font-medium text-foreground",children:d}),e.jsx("span",{className:"ml-auto shrink-0 font-mono text-[11px] tabular-nums text-muted-foreground",children:Pt(a)})]}),e.jsx("div",{className:"mt-1 flex items-center justify-between gap-3",children:e.jsx("span",{className:"text-[11px] leading-relaxed text-muted-foreground",children:l})})]})}function vs({run:t,getStepDuration:s}){var f,R,j;const a=t.steps.filter(B=>B.state==="done").length,d=t.steps.length,l=(R=(f=t.result)==null?void 0:f.generationMeta)==null?void 0:R.durationMs,u=B=>B.id==="generate"&&typeof l=="number"?l:s(B),h=t.steps.reduce((B,b)=>B+u(b),0),g=t.status==="running",N=g?"running":t.result?t.result.ok?"passed":"failed":t.status;return e.jsxs("details",{open:g,className:"group rounded-[6px] border border-border/60 bg-muted/20",children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center gap-2 px-2.5 py-1.5 text-[12px] marker:hidden",children:[e.jsx(y.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform group-open:rotate-90"}),e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${g?"animate-pulse bg-amber-500":t.status==="done"?"bg-emerald-500":"bg-destructive"}`}),e.jsx("span",{className:"shrink-0 font-medium text-foreground",children:"Build"}),e.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:["· ",t.prompt]}),e.jsxs("span",{className:"ml-auto shrink-0 font-mono text-[11px] text-muted-foreground",children:[N," · ",a,"/",d," ·"," ",Pt(h)]})]}),e.jsxs("div",{className:"space-y-2.5 border-t border-border/60 px-2.5 py-2",children:[g?e.jsx("div",{className:"h-1 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-foreground",style:{width:`${Math.round(a/Math.max(1,d)*100)}%`}})}):null,e.jsx("div",{className:"space-y-0.5",children:t.steps.map(B=>{var b,E;return e.jsx(js,{duration:u(B),repairAttempts:(E=(b=t.result)==null?void 0:b.telemetry)==null?void 0:E.repairAttempts,step:B},B.id)})}),t.result&&e.jsxs("div",{className:"space-y-1.5 border-t border-border pt-2.5 text-[12px] leading-relaxed text-muted-foreground",children:[e.jsxs("div",{className:"font-medium text-foreground",children:["Runtime result:"," ",e.jsx("span",{className:t.result.ok?"text-emerald-600":"text-destructive",children:t.result.ok?"passed":"failed"})]}),t.result.telemetry&&e.jsxs("div",{className:"grid gap-1 font-mono text-[11px] sm:grid-cols-2",children:[e.jsxs("span",{children:["context: ",t.result.telemetry.contextFileCount??0," ","files · ",t.result.telemetry.contextChars??0," chars"]}),e.jsxs("span",{children:["generated:"," ",t.result.telemetry.generatedFileCount??0," files ·"," ",t.result.telemetry.generatedChars??0," chars"]})]}),(j=t.result.changedFiles)!=null&&j.length?e.jsxs("div",{children:["Changed ",t.result.changedFiles.join(", ")]}):null,e.jsx(os,{plan:t.result.filePlan,changedFiles:t.result.changedFiles}),t.result.generationMeta&&e.jsxs("div",{children:["Model: ",t.result.generationMeta.model]}),t.result.error&&e.jsx("pre",{className:"mt-1 max-h-44 overflow-auto whitespace-pre-wrap rounded-[4px] border border-border bg-muted/40 p-2 font-mono text-[11px] text-foreground",children:t.result.error})]})]})]})}function js({duration:t,repairAttempts:s,step:a}){return e.jsxs("div",{className:"grid grid-cols-[16px_minmax(0,1fr)_auto] items-center gap-2 rounded-[4px] px-1.5 py-1 text-[11.5px]",children:[e.jsx(Ss,{state:a.state}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:`truncate font-mono ${a.state==="idle"?"text-muted-foreground":"text-foreground"}`,children:a.label}),a.state==="running"&&e.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:a.detail})]}),e.jsx("div",{className:"flex items-center gap-2 font-mono text-[11px] text-muted-foreground",children:a.id==="repair"&&a.state==="running"?e.jsxs("span",{children:["attempt ",(s||0)+1," / ",Te]}):e.jsx("span",{children:Pt(t)})})]})}function Ss({state:t}){return t==="done"?e.jsx(x.Check,{className:"h-3.5 w-3.5 text-emerald-600"}):t==="running"?e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-blue-600"}):t==="blocked"?e.jsx(x.X,{className:"h-3.5 w-3.5 text-destructive"}):e.jsx(y.Circle,{className:"h-2.5 w-2.5 fill-zinc-300 stroke-none"})}exports.DataAppBuilder=is;
|