react-semaphor 0.1.424 → 0.1.425

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/analytics-protocol/index.cjs +1 -1
  2. package/dist/analytics-protocol/index.js +243 -91
  3. package/dist/appearance/index.cjs +1 -1
  4. package/dist/appearance/index.js +1 -1
  5. package/dist/brand-studio/index.cjs +2 -2
  6. package/dist/brand-studio/index.js +8 -8
  7. package/dist/chunks/{analyze-result-contract-D7pjjYPy.js → analyze-result-contract-DnfF8kBb.js} +434 -427
  8. package/dist/chunks/analyze-result-contract-ege_u6Nl.js +1 -0
  9. package/dist/chunks/{braces-8TRlDwDw.js → braces-BdbUk_r9.js} +1 -1
  10. package/dist/chunks/{braces-D2tStQjF.js → braces-CbO-aIwH.js} +1 -1
  11. package/dist/chunks/calendar-preferences-dialog-BLaSWhLl.js +1 -0
  12. package/dist/chunks/{calendar-preferences-dialog-D5mABNDT.js → calendar-preferences-dialog-DJwV0aqn.js} +4 -4
  13. package/dist/chunks/{catalog-field-grounding-CJKAqtiC.js → catalog-field-grounding-DcxPLns0.js} +10 -10
  14. package/dist/chunks/{switch-2bh3Hka1.js → code-editor-Bkk7s8hI.js} +7382 -6809
  15. package/dist/chunks/code-editor-CkXyNgYc.js +138 -0
  16. package/dist/chunks/{common-types-4bjoIgvm.js → common-types-ClkOI-3O.js} +4 -4
  17. package/dist/chunks/comparison-document-migration-CQJ0DZlL.js +414 -0
  18. package/dist/chunks/comparison-document-migration-Db64RWYD.js +1 -0
  19. package/dist/chunks/{index-Dzz6jXSY.js → dashboard-5agU0G_D.js} +57458 -56183
  20. package/dist/chunks/dashboard-MKIqgGDp.js +1402 -0
  21. package/dist/chunks/{dashboard-briefing-launcher-DuWgwtxX.js → dashboard-briefing-launcher-CII8-4qo.js} +11 -6
  22. package/dist/chunks/{dashboard-briefing-launcher-BNDzMjjt.js → dashboard-briefing-launcher-qyEVfuOm.js} +226 -209
  23. package/dist/chunks/dashboard-controls-PJpeYZHw.js +36 -0
  24. package/dist/chunks/dashboard-controls-aJY0FNPP.js +2196 -0
  25. package/dist/chunks/dashboard-input-contract-BFpERluO.js +18 -0
  26. package/dist/chunks/dashboard-input-contract-DV3cshjz.js +1 -0
  27. package/dist/chunks/{dashboard-json-CkTEDNtH.js → dashboard-json-CzHSP6Fa.js} +16 -15
  28. package/dist/chunks/dashboard-json-DtmR5yCf.js +1 -0
  29. package/dist/chunks/date-formatter-BTTYdAik.js +1 -0
  30. package/dist/chunks/date-formatter-D-89jTjG.js +514 -0
  31. package/dist/chunks/{edit-dashboard-visual-CRjVRZLk.js → edit-dashboard-visual-AkZzwBCV.js} +8892 -8996
  32. package/dist/chunks/edit-dashboard-visual-Cif6uDqN.js +182 -0
  33. package/dist/chunks/{index-CjzRe2su.js → index-CnujJ3fa.js} +3 -3
  34. package/dist/chunks/{index-DRlMUglg.js → index-Dpm_VET4.js} +2 -2
  35. package/dist/chunks/{index-CJdxSyQq.js → index-If0wlXGi.js} +308 -308
  36. package/dist/chunks/index-jSrCwPQz.js +31 -0
  37. package/dist/chunks/{x-CXDkqdur.js → index-xHCrHprY.js} +59 -59
  38. package/dist/chunks/{layout-grid-C0OI-MRn.js → layout-grid-B08pP7v6.js} +1 -1
  39. package/dist/chunks/{layout-grid-CiubineE.js → layout-grid-D5tYJg1-.js} +1 -1
  40. package/dist/chunks/metric-comparison-4oA4ouU9.js +354 -0
  41. package/dist/chunks/metric-comparison-nQKquVnx.js +1 -0
  42. package/dist/chunks/{palette-C4KTXOug.js → palette-C0yjT5Tv.js} +1 -1
  43. package/dist/chunks/{palette-Cp1hqZtm.js → palette-jqaAcwiQ.js} +1 -1
  44. package/dist/chunks/{save-DgMfP0j8.js → save-HCJjjzdX.js} +1 -1
  45. package/dist/chunks/{save-C__QggEE.js → save-Xdc4pnys.js} +1 -1
  46. package/dist/chunks/{search-BHsQIWBV.js → search-DHZCro8B.js} +1 -1
  47. package/dist/chunks/{search-DNCejM7Z.js → search-Dcud9ajy.js} +1 -1
  48. package/dist/chunks/{update-policy-C1pmhLz9.js → update-policy-BgONreNd.js} +1 -1
  49. package/dist/chunks/{update-policy-BCJc0oI5.js → update-policy-CY2k-pJP.js} +9 -9
  50. package/dist/chunks/{use-create-flow-overlay-state-B9vArrvr.js → use-create-flow-overlay-state-ByOKVV2K.js} +62 -62
  51. package/dist/chunks/{use-create-flow-overlay-state-B-bYbtix.js → use-create-flow-overlay-state-DmuReEnk.js} +2 -2
  52. package/dist/chunks/validators-B4VMLX3_.js +1 -0
  53. package/dist/chunks/{validators-PXkij33j.js → validators-Cz-XuORM.js} +123 -119
  54. package/dist/dashboard/index.cjs +1 -1
  55. package/dist/dashboard/index.js +2 -2
  56. package/dist/dashboard-authoring/index.cjs +2 -2
  57. package/dist/dashboard-authoring/index.js +6 -4
  58. package/dist/data-app-builder/index.cjs +6 -6
  59. package/dist/data-app-builder/index.js +5 -5
  60. package/dist/data-app-codegen/index.cjs +1 -1
  61. package/dist/data-app-codegen/index.js +2 -2
  62. package/dist/data-app-codegen-node/index.cjs +1 -1
  63. package/dist/data-app-codegen-node/index.js +3 -3
  64. package/dist/data-app-sdk/index.cjs +1 -1
  65. package/dist/data-app-sdk/index.js +6 -6
  66. package/dist/data-app-sdk-adapters/index.cjs +1 -1
  67. package/dist/data-app-sdk-adapters/index.js +1 -1
  68. package/dist/data-app-sdk-validation/index.cjs +1 -1
  69. package/dist/data-app-sdk-validation/index.js +65 -68
  70. package/dist/format-utils/index.cjs +2 -2
  71. package/dist/format-utils/index.js +59 -58
  72. package/dist/index.cjs +1 -1
  73. package/dist/index.js +19 -19
  74. package/dist/style.css +1 -1
  75. package/dist/surfboard/index.cjs +1 -1
  76. package/dist/surfboard/index.js +3 -3
  77. package/dist/types/analytics-protocol.d.ts +299 -3
  78. package/dist/types/brand-studio.d.ts +2 -2
  79. package/dist/types/briefings.d.ts +65 -41
  80. package/dist/types/dashboard-assistant.d.ts +28 -7
  81. package/dist/types/dashboard-authoring.d.ts +123 -43
  82. package/dist/types/dashboard.d.ts +97 -48
  83. package/dist/types/data-app-builder.d.ts +2 -2
  84. package/dist/types/data-app-sdk.d.ts +1 -1
  85. package/dist/types/format-utils.d.ts +98 -10
  86. package/dist/types/index.js +1 -1
  87. package/dist/types/main.d.ts +229 -95
  88. package/dist/types/shared.d.ts +84 -43
  89. package/dist/types/surfboard.d.ts +99 -49
  90. package/dist/types/types.d.ts +110 -50
  91. package/package.json +2 -1
  92. package/dist/chunks/analyze-result-contract-DpDcImgk.js +0 -1
  93. package/dist/chunks/calendar-preferences-dialog-iokD3HbE.js +0 -1
  94. package/dist/chunks/contracts-CoCOpd_i.js +0 -11
  95. package/dist/chunks/contracts-CtB2VONT.js +0 -1
  96. package/dist/chunks/dashboard-controls-bbEF-AbK.js +0 -52
  97. package/dist/chunks/dashboard-controls-id39vb7G.js +0 -2322
  98. package/dist/chunks/dashboard-json-DVoqS1ks.js +0 -1
  99. package/dist/chunks/date-formatter-B4EBSe9C.js +0 -1
  100. package/dist/chunks/date-formatter-BlhBftA9.js +0 -416
  101. package/dist/chunks/edit-dashboard-visual-CkrxZCcp.js +0 -178
  102. package/dist/chunks/index-S1CGUcSz.js +0 -1406
  103. package/dist/chunks/switch-DMT7qf_R.js +0 -138
  104. package/dist/chunks/validators-DMlVbd1p.js +0 -1
  105. package/dist/chunks/x-B6ghREd2.js +0 -31
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),p=require("react"),An=require("react-dom/client"),k=require("../chunks/index-S1CGUcSz.js"),w=require("../chunks/switch-DMT7qf_R.js"),Ze=require("../data-app-builder-browser-runtime/index.cjs"),Q=require("../chunks/x-B6ghREd2.js"),Cn=require("../chunks/save-C__QggEE.js"),tt=require("../chunks/search-DNCejM7Z.js");function Tr(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 Rn=Tr(p),Bn=Tr(An);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),p=require("react"),An=require("react-dom/client"),k=require("../chunks/dashboard-MKIqgGDp.js"),w=require("../chunks/code-editor-CkXyNgYc.js"),Ze=require("../data-app-builder-browser-runtime/index.cjs"),Q=require("../chunks/index-jSrCwPQz.js"),Cn=require("../chunks/save-Xdc4pnys.js"),tt=require("../chunks/search-Dcud9ajy.js");function Tr(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 Rn=Tr(p),Bn=Tr(An);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -34,7 +34,7 @@
34
34
 
35
35
  `);for(;g>=0;){const E=l.slice(0,g).trim();l=l.slice(g+2),E&&h(E),g=l.indexOf(`
36
36
 
37
- `)}}const x=l.trim();if(x&&h(x),!u.ok||!((m=u.result)!=null&&m.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 Jn(t,{apiServiceUrl:s,accessToken:a,signal:d}){var R,v,B;const l=t.dataAppId,u=l?ge(s,`/${l}/draft`):ge(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},x=await fetch(u,{method:"POST",credentials:Ne(a),signal:d,headers:{"Content-Type":"application/json",...ke(a)},body:JSON.stringify(h)}),N=await O(x,"Data App save draft");if(!x.ok)throw new Error(N.error||"Data App draft could not be saved.");const m=l||((R=N.dataApp)==null?void 0:R.id);if(!m)throw new Error("Data App save draft response did not include an app id.");return{dataAppId:m,draftId:(v=N.draft)==null?void 0:v.id,savedAt:((B=N.draft)==null?void 0:B.updatedAt)||new Date().toISOString()}}async function _n(t,{apiServiceUrl:s,accessToken:a,signal:d}){var h;const l=await fetch(ge(s,`/${t.dataAppId}`),{cache:"no-store",credentials:Ne(a),signal:d,headers:ke(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 Vn(t,{apiServiceUrl:s,accessToken:a,signal:d,onProgress:l}){var m,R,v,B;if(!t.draftId||!((m=t.sourceRevision)!=null&&m.snapshotHash))throw new Error("Data App publish requires a saved draft and matching source revision.");const u=Oe(t.validationStatus);l==null||l({phase:"start",label:"Starting publish session",detail:"Creating a versioned publish record in Semaphor."});const h=await fetch(ge(s,`/${t.dataAppId}/publish/start`),{method:"POST",credentials:Ne(a),signal:d,headers:{"Content-Type":"application/json",...ke(a)},body:JSON.stringify({draftId:t.draftId,sourceRevisionSnapshotHash:(R=t.sourceRevision)==null?void 0:R.snapshotHash,validationStatus:u})}),x=await O(h,"Data App publish start");if(!h.ok||!((v=x.publishSession)!=null&&v.versionId))throw new Error(x.error||"Data App publish session could not be started.");const N=x.publishSession.versionId;try{l==null||l({phase:"build",label:"Building app locally",detail:"The local bridge is running the app build."});const g=await t.buildArtifacts({signal:d,onProgress:l}),E=Oe(g.validationStatus);for(const[F,W]of g.assets.entries()){l==null||l({phase:"upload",label:`Uploading asset ${F+1} of ${g.assets.length}`,detail:W.path,assetIndex:F+1,assetCount:g.assets.length});const be=await fetch(ge(s,`/${t.dataAppId}/publish/upload`),{method:"POST",credentials:Ne(a),signal:d,headers:{"Content-Type":"application/json",...ke(a)},body:JSON.stringify({versionId:N,assetPath:W.path,contentsBase64:W.contentsBase64,contentType:W.contentType})}),X=await O(be,"Data App publish upload");if(!be.ok)throw new Error(X.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(ge(s,`/${t.dataAppId}/publish/complete`),{method:"POST",credentials:Ne(a),signal:d,headers:{"Content-Type":"application/json",...ke(a)},body:JSON.stringify({versionId:N,manifest:g.manifest,entryFile:g.entryFile,styleFiles:g.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(g){throw await fetch(ge(s,`/${t.dataAppId}/publish/fail`),{method:"POST",credentials:Ne(a),signal:d,headers:{"Content-Type":"application/json",...ke(a)},body:JSON.stringify({versionId:N,validationStatus:{ok:!1,error:g instanceof Error?g.message:String(g)}})}).catch(()=>{}),g}}function Dr(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>=Ln)break;d.includes(l)||d.push(l)}return d}function Pr(t,s,a=""){const d=Array.from(new Set(t)),l=Un(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(x=>!!x),h=[];for(const x of u){if(h.length>=Dt)break;d.includes(x)&&!h.includes(x)&&h.push(x)}for(const x of d){if(h.length>=Dt)break;h.includes(x)||/^src\/components\/ui\//.test(x)||/^src\/data-app\//.test(x)&&h.push(x)}return h.length>0?h:d.slice(0,Dt)}function Un(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 Gn(){return On.map(t=>({...t}))}function Pt(t){var a,d,l,u,h;return[t.error,(a=t.writePolicyValidation)==null?void 0:a.diagnostics.join(`
37
+ `)}}const x=l.trim();if(x&&h(x),!u.ok||!((m=u.result)!=null&&m.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 Jn(t,{apiServiceUrl:s,accessToken:a,signal:d}){var R,v,B;const l=t.dataAppId,u=l?ge(s,`/${l}/draft`):ge(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},x=await fetch(u,{method:"POST",credentials:Ne(a),signal:d,headers:{"Content-Type":"application/json",...ke(a)},body:JSON.stringify(h)}),N=await O(x,"Data App save draft");if(!x.ok)throw new Error(N.error||"Data App draft could not be saved.");const m=l||((R=N.dataApp)==null?void 0:R.id);if(!m)throw new Error("Data App save draft response did not include an app id.");return{dataAppId:m,draftId:(v=N.draft)==null?void 0:v.id,savedAt:((B=N.draft)==null?void 0:B.updatedAt)||new Date().toISOString()}}async function Vn(t,{apiServiceUrl:s,accessToken:a,signal:d}){var h;const l=await fetch(ge(s,`/${t.dataAppId}`),{cache:"no-store",credentials:Ne(a),signal:d,headers:ke(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 _n(t,{apiServiceUrl:s,accessToken:a,signal:d,onProgress:l}){var m,R,v,B;if(!t.draftId||!((m=t.sourceRevision)!=null&&m.snapshotHash))throw new Error("Data App publish requires a saved draft and matching source revision.");const u=Oe(t.validationStatus);l==null||l({phase:"start",label:"Starting publish session",detail:"Creating a versioned publish record in Semaphor."});const h=await fetch(ge(s,`/${t.dataAppId}/publish/start`),{method:"POST",credentials:Ne(a),signal:d,headers:{"Content-Type":"application/json",...ke(a)},body:JSON.stringify({draftId:t.draftId,sourceRevisionSnapshotHash:(R=t.sourceRevision)==null?void 0:R.snapshotHash,validationStatus:u})}),x=await O(h,"Data App publish start");if(!h.ok||!((v=x.publishSession)!=null&&v.versionId))throw new Error(x.error||"Data App publish session could not be started.");const N=x.publishSession.versionId;try{l==null||l({phase:"build",label:"Building app locally",detail:"The local bridge is running the app build."});const g=await t.buildArtifacts({signal:d,onProgress:l}),E=Oe(g.validationStatus);for(const[F,W]of g.assets.entries()){l==null||l({phase:"upload",label:`Uploading asset ${F+1} of ${g.assets.length}`,detail:W.path,assetIndex:F+1,assetCount:g.assets.length});const be=await fetch(ge(s,`/${t.dataAppId}/publish/upload`),{method:"POST",credentials:Ne(a),signal:d,headers:{"Content-Type":"application/json",...ke(a)},body:JSON.stringify({versionId:N,assetPath:W.path,contentsBase64:W.contentsBase64,contentType:W.contentType})}),X=await O(be,"Data App publish upload");if(!be.ok)throw new Error(X.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(ge(s,`/${t.dataAppId}/publish/complete`),{method:"POST",credentials:Ne(a),signal:d,headers:{"Content-Type":"application/json",...ke(a)},body:JSON.stringify({versionId:N,manifest:g.manifest,entryFile:g.entryFile,styleFiles:g.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(g){throw await fetch(ge(s,`/${t.dataAppId}/publish/fail`),{method:"POST",credentials:Ne(a),signal:d,headers:{"Content-Type":"application/json",...ke(a)},body:JSON.stringify({versionId:N,validationStatus:{ok:!1,error:g instanceof Error?g.message:String(g)}})}).catch(()=>{}),g}}function Dr(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>=Ln)break;d.includes(l)||d.push(l)}return d}function Pr(t,s,a=""){const d=Array.from(new Set(t)),l=Un(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(x=>!!x),h=[];for(const x of u){if(h.length>=Dt)break;d.includes(x)&&!h.includes(x)&&h.push(x)}for(const x of d){if(h.length>=Dt)break;h.includes(x)||/^src\/components\/ui\//.test(x)||/^src\/data-app\//.test(x)&&h.push(x)}return h.length>0?h:d.slice(0,Dt)}function Un(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 Gn(){return On.map(t=>({...t}))}function Pt(t){var a,d,l,u,h;return[t.error,(a=t.writePolicyValidation)==null?void 0:a.diagnostics.join(`
38
38
  `),(d=t.importValidation)==null?void 0:d.diagnostics.join(`
39
39
  `),(l=t.dataApiValidation)==null?void 0:l.diagnostics.join(`
40
40
  `),(u=t.command)==null?void 0:u.stdout,(h=t.command)==null?void 0:h.stderr,...(t.attempts||[]).flatMap(x=>[x.command.stdout,x.command.stderr])].filter(Boolean).join(`
@@ -48,9 +48,9 @@
48
48
  `).slice(0,2e3)}}function Le(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 ts(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 rs(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 ns(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 ss(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 $r(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 Fr(t){return t.replace(/\\/g,"/").split("/").filter(Boolean).pop()}async function as({snapshot:t,workspaceContext:s,projectDir:a,adapter:d}){const l=s.projectRoot||a;return{schemaVersion:"data-app-source-revision/v1",snapshotHash:await $r(ss(t)),workspace:{adapter:d,...Fr(l)?{rootName:Fr(l)}:{},pathHash:await $r(l)},collectedAt:new Date().toISOString()}}function et(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 os(t,s){return!s||!Le(s)?t:!t||!Le(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:et(t.sources,s.sources),inputs:et(t.inputs,s.inputs),views:et(t.views,s.views),interactions:t.interactions||s.interactions?et(t.interactions||[],s.interactions||[]):void 0,layout:s.layout||t.layout}}function Mr(t,s){var N,m,R,v,B,g,E,z,L;const a=t.slice(-12).map(es),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=(Le(s)?s:void 0)||((m=t.slice().reverse().find(F=>F.type==="assistant"&&Le(F.intentManifest)))==null?void 0:m.intentManifest),x=[(R=l==null?void 0:l.attachments)!=null&&R.length?["Most recent selected/attached target:",...l.attachments.map(Or)].join(`
49
49
  `):"",(B=(v=d==null?void 0:d.result)==null?void 0:v.changedFiles)!=null&&B.length?`Last successful edit changed: ${d.result.changedFiles.join(", ")}`:"",u?`Last app-builder operation: ${u.type}${(g=u.target)!=null&&g.label?` on ${u.target.label}`:""}`:""].filter(Boolean);return{messages:a,activeTarget:x.join(`
50
50
 
51
- `)||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 is({files:t,selectedPath:s,onSelect:a}){const d=p.useMemo(()=>qn(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(Lr,{node:l,depth:0,selectedPath:s,onSelect:a},l.path||l.name))})}function Lr({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(tt.ChevronRight,{className:"h-3 w-3 rotate-90 text-muted-foreground"}),e.jsx(Pn,{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(k.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(Lr,{node:h,depth:s+1,selectedPath:a,onSelect:d},h.path))]})}function ls({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 ds({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 cs({projectId:t,projectName:s,dataAppId:a,apiServiceUrl:d,adapters:l}){var v,B;const u=p.useContext(k.SemaphorContext),h=typeof window>"u"?void 0:window.location.origin,x=d||((v=u.tokenProps)==null?void 0:v.apiServiceUrl)||h,N=(B=u.authToken)==null?void 0:B.accessToken,[m,R]=p.useState(()=>pe("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(us,{adapters:l,apiServiceUrl:x,accessToken:N,initialDataAppId:a||null,initialPrompt:"",path:"bridge",projectId:t,projectName:s,onRestart:()=>R(pe("builder-session"))},m)})}function us({adapters:t,apiServiceUrl:s,accessToken:a,initialDataAppId:d,initialPrompt:l,path:u,projectId:h,projectName:x,onRestart:N}){var Sr,kr;const[m,R]=p.useState(Rt),[v,B]=p.useState(Br),[g,E]=p.useState(Bt),[z,L]=p.useState(!1),[F,W]=p.useState(Rt),[be,X]=p.useState(0),[A]=p.useState(u),[Ie,rt]=p.useState(l||""),[nt,ze]=p.useState([]),[Ae,Ce]=p.useState([]),[Y,he]=p.useState([]),[Et,We]=p.useState(null),[Z,He]=p.useState(!1),[ee,Ot]=p.useState(!1),[Re,Ir]=p.useState(!0),[zr,se]=p.useState("idle"),[Wr,ae]=p.useState(null),[Lt,It]=p.useState(null),[zt,Je]=p.useState(()=>Date.now()),[Be,Wt]=p.useState(null),[st,Hr]=p.useState("gpt-5.5-low"),q=p.useRef(null),U=p.useRef(null),at=p.useRef([]),ot=p.useRef(null),it=p.useRef(null),Ht=p.useRef(null),[fe,we]=p.useState(!1),[Jt,oe]=p.useState(null),[_t,lt]=p.useState(!1),[Vt,Ut]=p.useState(!1),[De,dt]=p.useState("idle"),[Gt,Kt]=p.useState(null),[Jr,qt]=p.useState(""),[_r,Qt]=p.useState([]),[ct,Xt]=p.useState([]),[ut,Yt]=p.useState(null),[Zt,Vr]=p.useState([]),[Ur,Gr]=p.useState(null),[pt,er]=p.useState(null),[ht,tr]=p.useState(null),[me,_e]=p.useState(d||null),[Ve,ft]=p.useState("idle"),[rr,mt]=p.useState("idle"),[nr,sr]=p.useState(null),[ar,or]=p.useState(null),[xt,ye]=p.useState(null),[ie,H]=p.useState(null),[ir,Ue]=p.useState(null),[Ge,gt]=p.useState(null),[bt,Ke]=p.useState(!1),[wt,lr]=p.useState(""),[dr,yt]=p.useState(null),[cr,ur]=p.useState(!1),Pe=p.useRef(null),vt=p.useRef(null),ve=p.useRef(null),pr=(t==null?void 0:t.readStatus)||zn,qe=(t==null?void 0:t.runTurn)||Wn,jt=(t==null?void 0:t.saveDraft)||Jn,Kr=(t==null?void 0:t.loadApp)||_n,St=(t==null?void 0:t.publish)||Vn,J=p.useMemo(()=>In(st),[st]),qr=p.useMemo(()=>Y.find(r=>r.type==="run"&&r.id===Et),[Et,Y]),kt=p.useMemo(()=>[...Y].reverse().find(r=>r.type==="run"),[Y]),Nt=p.useMemo(()=>{const r=F.includes("?")?"&":"?";return`${F}${r}dataAppBuilderRefresh=${be}`},[F,be]);p.useEffect(()=>{const r=window.setInterval(()=>Je(Date.now()),500);return()=>window.clearInterval(r)},[]),p.useEffect(()=>{at.current=Y},[Y]),p.useEffect(()=>{if(!bt)return;const r=()=>{Ke(!1)};return window.addEventListener("blur",r),()=>{window.removeEventListener("blur",r)}},[bt]),p.useEffect(()=>{L(!1);const r=window.localStorage.getItem(ue(Ar,h))||Rt,n=window.localStorage.getItem(ue(Cr,h))||Br,i=window.localStorage.getItem(ue(Rr,h))||Bt,o=window.localStorage.getItem(ue(Nr,h));if(R(r),W(r),B(n),E(i),L(!0),o)try{he(JSON.parse(o))}catch{he([])}},[h]),p.useEffect(()=>{window.localStorage.setItem(ue(Ar,h),m)},[m,h]),p.useEffect(()=>{window.localStorage.setItem(ue(Cr,h),v)},[v,h]),p.useEffect(()=>{window.localStorage.setItem(ue(Rr,h),g)},[g,h]),p.useEffect(()=>{var r;window.localStorage.setItem(ue(Nr,h),JSON.stringify(Y.map(ws))),(r=ot.current)==null||r.scrollTo({top:ot.current.scrollHeight,behavior:"smooth"})},[Y,h]),p.useEffect(()=>{ve.current=pt},[pt]);const At=p.useCallback(async r=>{if(A!=="bridge"||!s)return;const n=v.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,v,me,h,A]);p.useEffect(()=>{if(A!=="bridge"||!s)return;const r=new AbortController;return At(r.signal).then(()=>{X(n=>n+1)}).catch(n=>{r.signal.aborted||(lt(!1),oe(n instanceof Error?n.message:"Bridge could not sync runtime context."))}),()=>r.abort()},[s,A,At]),p.useEffect(()=>{_e(d||null)},[d]),p.useEffect(()=>{if(!d||!z||vt.current===`${d}:${A}:${g}`)return;const r=new AbortController;return vt.current=`${d}:${A}:${g}`,ye(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 Kr({dataAppId:d},{apiServiceUrl:s,accessToken:a,signal:r.signal});if(r.signal.aborted)return;_e(o.id);const c=rs(o);if(!c){H({state:"done",label:"Data App opened",detail:"No saved source snapshot exists yet."});return}const f=ts(c.manifest);f&&gt(f),c.status==="draft"?sr(c.updatedAt||null):c.status==="ready"&&or(c.updatedAt||null);const j=ns(c,g);let b=!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."}),b=await wn({snapshot:c.sourceSnapshot,targetProjectDir:j,signal:r.signal}),b&&X(C=>C+1)),A==="bridge"&&j!==g&&E(j),r.signal.aborted)return;H({state:"done",label:"Data App opened",detail:b?"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);vt.current=null,ye(c),H({state:"failed",label:"Open Data App failed",detail:c}),M(`Open Data App failed: ${c}`,"blocked")}})(),()=>r.abort()},[z,d,g,A]),p.useEffect(()=>{function r(n){var c;if(n.source!==((c=it.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"&&fe){Ye("inspect-enable");return}if(i.type==="enabled"){oe("Click an element in the preview. Press Esc to cancel.");return}if(i.type==="disabled"){we(!1);return}if(i.type!=="selection"||!i.payload)return;const o=ln(i.payload);ze(f=>[...f,o]),we(!1),oe(`Selected ${o.name}. Add a message and send it.`)}return window.addEventListener("message",r),()=>window.removeEventListener("message",r)},[fe]),p.useEffect(()=>{we(!1),lt(!1),oe(null)},[v,g,A]),p.useEffect(()=>{if(Z||ee||Ae.length===0)return;const[r,...n]=Ae;Ce(n),mr(r)},[Z,ee,Ae]),p.useEffect(()=>{let r=!1;const n=new AbortController;async function i(){try{const o=await pr({apiServiceUrl:s,accessToken:a,signal:n.signal});r||Wt(o)}catch(o){r||Wt({ok:!1,error:o instanceof Error?o.message:String(o)})}}return i(),()=>{r=!0}},[a,s,pr]);const Qe=p.useCallback(async(r=U.current)=>{if(!r)return;const n=await r.compileBrowserSandboxPreviewHtml();qt(n.html),Qt(n.diagnostics),Xt(n.warnings||[]),Yt(n.cssMode||null),X(i=>i+1)},[]),$e=p.useCallback((r=U.current,n=ve.current)=>{var f;if(!r)return;const i=r.listBrowserSandboxFiles(),o=r.readBrowserSandboxWorkspaceContext(),c=n&&i.some(j=>j.path===n)?n:((f=i[0])==null?void 0:f.path)||null;Vr(i),Gr(o.runtimeManifest||null),er(c),ve.current=c,tr(c&&r.readBrowserSandboxFiles([c])[0]||null)},[]);p.useEffect(()=>{if(A!=="browser")return;let r=!1;async function n(){dt("loading"),Kt(null),window.__SEMAPHOR_BROWSER_SANDBOX_VENDOR__={React:Rn,ReactDOMClient:Bn};try{const i=await Ze.loadSemaphorBrowserRuntime();if(r)return;U.current=i,dt("ready"),await Qe(i),$e(i)}catch(i){if(r)return;dt("failed"),Kt(i instanceof Error?i.message:String(i))}}return n(),()=>{r=!0}},[A,$e,Qe]);function Qr(r){const n=U.current;er(r),ve.current=r,tr(n&&n.readBrowserSandboxFiles([r])[0]||null)}async function hr(){const r=U.current;!r||Z||(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 Xr(){if(Z||ee)return;if(gt(null),Ue(null),lr(""),yt(null),A==="browser"){await hr();return}const r=new AbortController,n=v.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(m),X(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 Yr(r){const n=r.durationMs??0;return r.state!=="running"||!r.startedAt?n:n+Math.max(0,zt-r.startedAt)}function Zr(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 en(r,n,i){const o=Date.now();Je(o),he(c=>c.map(f=>{if(f.type!=="run"||f.id!==r)return f;const j=n(f.steps),b=new Map(f.steps.map(C=>[C.id,C]));return{...f,...i,steps:j.map(C=>{const y=b.get(C.id);return y?Zr(y,C,o):C})}}))}function Xe(r,n){he(i=>i.map(o=>o.type==="run"&&o.id===r?{...o,...n}:o))}function M(r,n="default",i){const o=Le(i==null?void 0:i.intentManifest)?i==null?void 0:i.intentManifest:void 0;he(c=>[...c,{id:pe("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 tn(r){var i;r.intentManifest&&gt(o=>os(o,r.intentManifest));const n=(i=r.artifacts)==null?void 0:i.find(o=>o.type==="dataset_inspector");n&&Ue(n)}function fr(r){se({received:"context",authenticating:"context",routing:"thinking",inspecting_data:"inspecting-data",reading_files:"reading-files",planning_revision:"planning",generating_code:"generating",done:"thinking"}[r.phase]),ae(r.detail||r.label)}function mr(r){const n=r.prompt.trim();if(!n)return;const i=Date.now();he(o=>[...o,{id:pe("user"),type:"user",content:n,createdAt:i,attachments:r.attachments}]),It(i),se("context"),ae("Preparing app context and available files."),Sn({...r,prompt:n})}async function rn(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)});ze(i=>[...i,{id:pe("attachment"),type:"screenshot",name:r.name||"Screenshot",imageUrl:n,mediaType:r.type,createdAt:Date.now()}])}function nn(r){ze(n=>n.filter(i=>i.id!==r))}function Ye(r){var i,o;let n="*";try{n=new URL(Nt).origin}catch{n="*"}(o=(i=it.current)==null?void 0:i.contentWindow)==null||o.postMessage({source:"semaphor-data-app-builder",type:r},n)}async function sn(){const r=v.replace(/\/$/,""),n=await fetch(`${r}/inspect/install`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:g})}),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 an(){if(A!=="bridge"){M("Element inspection is only available in Local Bridge mode right now.","blocked");return}try{Ut(!0),oe(_t?null:"Preparing element inspector…");let r=!1;if(!_t){const n=await sn();lt(!!n.installed),r=!!n.changed}we(!0),oe(r?"Loading inspector in the preview…":"Click an element in the preview. Press Esc to cancel."),r?(W(m),X(n=>n+1)):window.setTimeout(()=>Ye("inspect-enable"),50)}catch(r){we(!1),oe(null),M(r instanceof Error?r.message:String(r),"blocked")}finally{Ut(!1)}}function on(){we(!1),oe(null),Ye("inspect-disable")}function ln(r){const n=(y,S="")=>typeof y=="string"&&y.trim()?y.trim():S,i=y=>Array.isArray(y)?y.map(S=>typeof S=="string"?S:S&&typeof S=="object"?JSON.stringify(S):"").filter(Boolean):[],o=n(r.elementLabel)||n(r.name),c=n(r.component),f=o&&c&&o!==c?`${o} in ${c}`:o||c||n(r.tagName,"Selected element"),j=i(r.reactOwners),b=i(r.sourceHints),C=[`Clicked element: ${o||f}`,`Nearest component: ${c||"unavailable"}`,`Tag: ${n(r.tagName,"unknown")}`,`Role: ${n(r.role,"none")}`,`Selector: ${n(r.selector,"none")}`,j.length?`React owner stack: ${j.join(" > ")}`:"React owner stack: unavailable",b.length?`Source hints: ${b.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(`
52
- `);return{id:pe("attachment"),type:"dom-selection",name:f,text:C,createdAt:Date.now()}}function dn(r,n){Ce(i=>i.map(o=>o.id===r?{...o,prompt:n}:o))}function cn(r){Ce(n=>n.filter(i=>i.id!==r))}function un(r,n){Ce(i=>i.map(o=>o.id===r?{...o,attachments:o.attachments.filter(c=>c.id!==n)}:o))}async function xr(r){for(const n of Array.from(r))await rn(n)}function gr(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){en(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"]},j={reading:"context",generating:"generate",writing:"edit",typechecking:"typecheck",repairing:"repair"}[n];return{...o,state:c[n].includes(o.id)?"done":j===o.id?"running":o.state==="done"?"done":"idle"}}))}async function pn(r,n,i){var j,b,C,y;(j=q.current)==null||j.abort();const o=new AbortController,c=Date.now();q.current=o,He(!0),We(n),Je(c),G(n,"reading");const f=window.setTimeout(()=>{o.abort()},18e4);try{let S=U.current;S||(S=await Ze.loadSemaphorBrowserRuntime(),U.current=S);const I=S.readBrowserSandboxWorkspaceContext(),D=(C=(b=I.files)==null?void 0:b.editable)!=null&&C.length?Pr(I.files.editable,ve.current,r):["src/App.tsx"],le=S.readBrowserSandboxFiles(D),je=le.reduce((re,te)=>re+te.contents.length,0);let Se=le,Fe=[],de=i,K=null;const ce=[];for(let re=0;re<Ee;re+=1){const te=Fe.length>0||re>0,Me=te?`repair-${re+1}`:"initial";G(n,te?"repairing":"generating");const _=de||(await qe({projectId:h,message:r,currentFiles:Se,workspaceContext:I,diagnostics:Fe,repair:te,generationModel:J.model,generationReasoningEffort:J.reasoningEffort,repairModel:J.model,repairReasoningEffort:J.reasoningEffort},{accessToken:a,apiServiceUrl:s,signal:o.signal})).revision;if(de=void 0,!_)throw new Error("Data App Builder did not return a revision.");G(n,"writing");const xe=S.applyBrowserSandboxRevision({..._,attemptLabel:Me});ce.push(...xe.attempts||[]),G(n,"typechecking");let P={...xe,attempts:[...ce],filePlan:_.plan,telemetry:{contextFileCount:le.length,contextChars:je,generatedFileCount:_.files.length,generatedChars:_.files.reduce(($,V)=>$+V.contents.length,0),repairAttempts:ce.filter($=>$.label.startsWith("repair")).length}};if(xe.ok){const $=await S.compileBrowserSandboxPreviewHtml();if(qt($.html),Qt($.diagnostics),Xt($.warnings||[]),Yt($.cssMode||null),X(V=>V+1),$e(S),$.diagnostics.length>0){const V={command:"browser sandbox preview compile",durationMs:0,exitCode:1,ok:!1,stdout:"",stderr:$.diagnostics.join(`
53
- `)};P={...P,ok:!1,validation:"typecheck",command:V,attempts:[...ce,{label:Me,ok:!1,command:V}],error:"Generated files failed Browser Sandbox preview compile."}}}if(K=P,P.ok||re===Ee-1)break;const T=(y=P.changedFiles)!=null&&y.length?P.changedFiles:_.files.map($=>$.path);Se=S.readBrowserSandboxFiles(Array.from(new Set([...D,...T]))),Fe=[Pt(P)]}if(!K)throw new Error("The browser runtime loop ended without a validation result.");G(n,K.ok?"complete":"failed"),Xe(n,{status:K.ok?"done":"failed",result:K,error:K.error,finishedAt:Date.now()}),M(gr(K,"browser"),K.ok?"default":"blocked")}catch(S){const I=S instanceof DOMException&&S.name==="AbortError",D=I?"Timed out waiting for the browser runtime loop.":S instanceof Error?S.message:String(S);Xe(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{He(!1),We(null),q.current=null,window.clearTimeout(f)}}async function hn(r,n,i){var j,b,C,y;(j=q.current)==null||j.abort();const o=new AbortController,c=Date.now();q.current=o,He(!0),We(n),Je(c),G(n,"reading");const f=window.setTimeout(()=>{o.abort()},18e4);try{const S=v.replace(/\/$/,""),I=async P=>{const T=await fetch(`${S}/read-files`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:P,projectDir:g})}),$=await O(T,"Local bridge /read-files");if(!T.ok||!$.ok||!$.files)throw new Error($.error||"Bridge could not read target files.");return $.files},D=async()=>{const P=await fetch(`${S}/workspace-context`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:g})}),T=await O(P,"Local bridge /workspace-context");if(!P.ok||!T.ok||!T.workspaceContext)throw new Error(T.error||"Bridge could not read workspace context.");return T.workspaceContext};let le=i;const je=async({currentFiles:P,workspaceContext:T,diagnostics:$=[],repair:V=!1})=>{const ne=le||(await qe({projectId:h,message:r,currentFiles:P,workspaceContext:T,diagnostics:$,repair:V,generationModel:J.model,generationReasoningEffort:J.reasoningEffort,repairModel:J.model,repairReasoningEffort:J.reasoningEffort},{accessToken:a,apiServiceUrl:s,signal:o.signal})).revision;if(le=void 0,!ne)throw new Error("Data App Builder did not return a revision.");return ne},Se=async P=>{const T=await fetch(`${S}/apply-files`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({revision:P,projectDir:g})}),$=await O(T,"Local bridge /apply-files");if(!T.ok&&!$.command&&!$.writePolicyValidation&&!$.importValidation&&!$.dataApiValidation)throw new Error($.error||"Bridge could not apply generated files.");return $},Fe=async()=>{const P=await fetch(`${S}/validate-typecheck`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:g})}),T=await O(P,"Local bridge /validate-typecheck");if(!P.ok&&!T.command)throw new Error(T.error||"Bridge could not typecheck the target app.");return T},de=await D();de.projectRoot&&E(de.projectRoot);let K=(C=(b=de.files)==null?void 0:b.editable)!=null&&C.length?Dr(de.files.editable):["src/App.tsx"];const ce=await I(K),re=ce.reduce((P,T)=>P+T.contents.length,0);let te=[];if(Kn(r)){const P=await Fe();P.ok||(te=[Pt(P)])}let Me=ce,_=null;const xe=[];for(let P=0;P<Ee;P+=1){const T=te.length>0||P>0,$=T?`repair-${P+1}`:"initial";G(n,T?"repairing":"generating");const V=await je({currentFiles:Me,workspaceContext:de,diagnostics:te,repair:T});G(n,"writing");const ne=await Se({...V,attemptLabel:$});if(W(m),X(Te=>Te+1),xe.push(...ne.attempts||[]),_={...ne,attempts:[...xe],filePlan:V.plan,telemetry:{contextFileCount:ce.length,contextChars:re,generatedFileCount:V.files.length,generatedChars:V.files.reduce((Te,Nn)=>Te+Nn.contents.length,0),repairAttempts:xe.filter(Te=>Te.label.startsWith("repair")).length}},G(n,"typechecking"),ne.ok||P===Ee-1)break;Me=(((y=ne.changedFiles)==null?void 0:y.length)||0)>0?await I(K=Array.from(new Set([...K,...ne.changedFiles||[]]))):V.files,te=[Pt(ne)]}if(!_)throw new Error("The app-builder loop ended without a validation result.");G(n,_.ok?"complete":"failed"),Xe(n,{status:_.ok?"done":"failed",result:_,error:_.error,finishedAt:Date.now()}),M(gr(_,"bridge"),_.ok?"default":"blocked")}catch(S){const I=S instanceof DOMException&&S.name==="AbortError",D=I?"Timed out waiting for the app-builder/bridge loop. The target app may still have updated through HMR.":S instanceof Error?S.message:String(S);Xe(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{He(!1),We(null),q.current=null,window.clearTimeout(f)}}async function fn(r){var c,f;let n=U.current;n||(n=await Ze.loadSemaphorBrowserRuntime(),U.current=n);const i=n.readBrowserSandboxWorkspaceContext(),o=(f=(c=i.files)==null?void 0:c.editable)!=null&&f.length?Pr(i.files.editable,ve.current,r):["src/App.tsx"];return{currentFiles:n.readBrowserSandboxFiles(o),workspaceContext:i}}async function mn(r){const n=U.current;return n?n.readBrowserSandboxFiles(r):[]}async function Ct(r,n){const i=v.replace(/\/$/,""),o=await fetch(`${i}/read-files`,{method:"POST",signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r,projectDir:g})}),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 xn(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 br(r){var j,b;await At(r);const n=v.replace(/\/$/,""),i=await fetch(`${n}/workspace-context`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:g})}),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 f=(b=(j=c.files)==null?void 0:j.editable)!=null&&b.length?Dr(c.files.editable):["src/App.tsx"];return{currentFiles:await Ct(f,r),workspaceContext:c}}function wr(r,n){return{schemaVersion:"data-app/v1",app:{id:me||void 0,name:`${x} Data App`,createdWith:"semaphor-app-builder"},runtime:{framework:r.framework,bundler:r.framework==="vite-react"?"vite":void 0},semaphor:{projectId:h,runtime:A,intentManifest:Ge||void 0},build:{sourceFileCount:n.files.length,validation:r.validation}}}async function yr(r){var j,b,C,y,S,I;const{workspaceContext:n}=await br(r),i=v.replace(/\/$/,""),o=await fetch(`${i}/source-snapshot`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:g})});if(o.ok){const D=await O(o,"Local bridge /source-snapshot");if(!D.ok||!((j=D.files)!=null&&j.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((b=D.metadata)==null?void 0:b.capturedAt)=="string"?D.metadata.capturedAt:new Date().toISOString(),projectRoot:n.projectRoot||g,runtime:A}}}}const c=(y=(C=n.files)==null?void 0:C.snapshot)!=null&&y.length?n.files.snapshot:[...((S=n.files)==null?void 0:S.source)||[],...((I=n.files)==null?void 0:I.root)||[]],f=await Ct([...new Set(c.length?c:["src/App.tsx"])],r);return{workspaceContext:n,snapshot:{schemaVersion:"data-app-source-snapshot/v1",files:f,metadata:{capturedAt:new Date().toISOString(),projectRoot:n.projectRoot||g,runtime:A}}}}async function gn(r,n){var f,j;const i=v.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||!((f=c.files)!=null&&f.length)?null:{schemaVersion:"data-app-source-snapshot/v1",files:c.files,metadata:{...c.metadata,capturedAt:typeof((j=c.metadata)==null?void 0:j.capturedAt)=="string"?c.metadata.capturedAt:new Date().toISOString(),projectRoot:r,runtime:A}}}async function bn(r,n,i){const o=v.replace(/\/$/,""),c=await fetch(`${o}/apply-files`,{method:"POST",signal:i,headers:{"Content-Type":"application/json"},body:JSON.stringify({revision:r,projectDir:n})}),f=await O(c,"Local bridge /apply-files");if(!c.ok||!f.ok)throw new Error(f.error||"Bridge could not restore saved files.");return f}async function wn({snapshot:r,targetProjectDir:n,signal:i}){const o=await gn(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])),f=r.files.filter(C=>c.get(C.path)!==C.contents),j=Math.max(0,o.files.length-r.files.length);return o&&f.length===0||!window.confirm(["Restore this saved Data App source snapshot into the bridge workspace?","",`Target workspace: ${n}`,"",`${f.length||r.files.length} saved file${(f.length||r.files.length)===1?"":"s"} will be written. Extra local files are left unchanged.`,j?`${j} extra local file${j===1?"":"s"} may remain in the workspace.`:""].filter(Boolean).join(`
54
- `))?!1:(await bn({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 yn(){var c,f,j,b;let r=U.current;r||(r=await Ze.loadSemaphorBrowserRuntime(),U.current=r);const n=r.readBrowserSandboxWorkspaceContext(),i=(f=(c=n.files)==null?void 0:c.snapshot)!=null&&f.length?n.files.snapshot:[...((j=n.files)==null?void 0:j.source)||[],...((b=n.files)==null?void 0:b.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 vr(){const r=new AbortController;ur(!0),yt(null);try{const{workspaceContext:n,snapshot:i}=A==="browser"?await yn():await yr(r.signal),o=wr(n,i);lr(JSON.stringify(o,null,2))}catch(n){yt(n instanceof Error?n.message:String(n))}finally{ur(!1)}}async function jr(){if(Pe.current)return Pe.current;if(!jt)return M("Save draft is not configured in this host yet.","blocked"),null;const r=new AbortController;ft("saving"),ye(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 yr(r.signal),f=wr(c,o),j=await as({snapshot:o,workspaceContext:c,projectDir:g,adapter:"bridge"}),b=await jt({projectId:h,dataAppId:me,title:me?void 0:((i=f.app)==null?void 0:i.name)||`${x} Data App`,description:me?void 0:null,manifest:f,sourceSnapshot:o,sourceRevision:j,validationStatus:(kt==null?void 0:kt.result)||null,bridgeWorkspaceHint:c.projectRoot||g},{apiServiceUrl:s,accessToken:a,signal:r.signal});return _e(b.dataAppId),sr(b.savedAt||new Date().toISOString()),ft("saved"),H({state:"done",label:"Draft saved",detail:"Semaphor has the latest source snapshot."}),M("Draft saved to Semaphor.","default"),{dataAppId:b.dataAppId,draftId:b.draftId,manifest:f,snapshot:o,sourceRevision:j,workspaceContext:c}}catch(o){const c=o instanceof Error?o.message:String(o);return ye(c),ft("failed"),H({state:"failed",label:"Save draft failed",detail:c}),M(`Save draft failed: ${c}`,"blocked"),null}finally{Pe.current=null}})();return Pe.current=n,n}async function vn(r){var c;const n=v.replace(/\/$/,""),i=await fetch(`${n}/publish-build`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:g})}),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 jn(){if(!St){M("Publish is not configured in this host yet.","blocked");return}if(Ve==="saving"&&!Pe.current){M("Save draft is already in progress.","blocked");return}const r=await jr(),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;mt("publishing"),ye(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 St({projectId:h,dataAppId:n,draftId:r.draftId,title:`${x} Data App`,description:null,sourceSnapshot:r.snapshot,sourceRevision:r.sourceRevision,bridgeWorkspaceHint:r.workspaceContext.projectRoot||g,buildArtifacts:async({signal:c})=>{const f=await vn(c),j=f.assets;return{manifest:{...f.manifest,semaphor:{...f.manifest.semaphor||{},projectId:h,runtime:A,intentManifest:Ge||void 0}},validationStatus:f,bridgeWorkspaceHint:r.workspaceContext.projectRoot||g,assets:j,entryFile:f.entryFile,styleFiles:f.styleFiles||[]}}},{apiServiceUrl:s,accessToken:a,signal:i.signal,onProgress:c=>{H({state:"running",label:c.label,detail:c.detail})}});_e(o.dataAppId),or(o.publishedAt||new Date().toISOString()),mt("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);ye(c),mt("failed"),H({state:"failed",label:"Publish failed",detail:c}),M(`Publish failed: ${c}`,"blocked")}}async function Sn(r){var f,j;const{attachments:n,prompt:i}=r,o=new AbortController;q.current=o,Ot(!0);const c=window.setTimeout(()=>{o.abort()},18e4);try{se("context"),ae("Reading the app manifest and starter context.");let b=A==="browser"?await fn(i):await br(o.signal);const C=[];let y=null;for(;se("thinking"),ae(b.currentFiles.length>0?"Reviewing the app context and deciding the next step.":"Deciding whether this needs an answer, file inspection, or edits."),y=await qe({projectId:h,message:i,currentFiles:b.currentFiles,workspaceContext:b.workspaceContext,conversationContext:Mr(at.current,Ge),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:fr}),!(!y||y.mode!=="read_files");){const D=(y.requestedFiles||[]).filter(je=>typeof je=="string"&&!b.currentFiles.some(Se=>Se.path===je));if(D.length===0){se("thinking"),ae("No additional source files are needed; preparing the response."),y=await qe({projectId:h,message:i,currentFiles:b.currentFiles,workspaceContext:b.workspaceContext,conversationContext:Mr(at.current,Ge),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:fr});break}se("reading-files"),ae(`Reading ${D.length} requested file${D.length===1?"":"s"}: ${Zn(D)}.`),C.push({tool:"read_files",status:"done",detail:D.join(", ")});const le=A==="browser"?await mn(D):await Ct(D,o.signal);b={...b,currentFiles:xn(b.currentFiles,le)}}if(!y)throw new Error("Data App Builder did not return a turn.");if(C.length>0&&(y={...y,toolEvents:[...C,...y.toolEvents||[]]}),tn(y),y.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(y.mode!=="edit"){M(y.message,y.mode==="clarify"?"guidance":"default",{artifacts:y.artifacts,operation:y.operation,intentManifest:y.intentManifest});return}if(!y.revision)throw new Error("Data App Builder chose an edit but returned no revision.");M(Yn(y),"guidance",{operation:y.operation,intentManifest:y.intentManifest}),se("planning"),ae((j=(f=y.revision.plan)==null?void 0:f.files)!=null&&j.length?`Preparing edits for ${y.revision.plan.files.length} file${y.revision.plan.files.length===1?"":"s"}.`:"Preparing the file edit and validation run.");const S=pe("run"),I=Date.now();he(D=>[...D,{id:S,type:"run",prompt:i,status:"running",steps:Gn(),createdAt:I,startedAt:I}]),q.current=null,A==="browser"?pn(i,S,y.revision):hn(i,S,y.revision)}catch(b){const C=b instanceof DOMException&&b.name==="AbortError";M(C?"The app-builder turn timed out before a response was produced.":b instanceof Error?b.message:String(b),"blocked")}finally{Ot(!1),se("idle"),ae(null),It(null),q.current===o&&(q.current=null),window.clearTimeout(c)}}function kn(r){r.preventDefault();const n=Ie.trim();if(!n)return;const i=Date.now(),o=nt,c={id:pe("turn"),prompt:n,attachments:o,createdAt:i};if(rt(""),ze([]),Z||ee){Ce(f=>[...f,c]);return}mr(c)}return e.jsxs(k.ResizablePanelGroup,{autoSaveId:`semaphor-data-app-builder-${h}`,className:"h-full min-h-0 flex-1",direction:"horizontal",children:[Re?e.jsxs(e.Fragment,{children:[e.jsx(k.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(k.AlertDialog,{children:[e.jsx(k.AlertDialogTrigger,{asChild:!0,children:e.jsxs(w.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 px-1.5 text-muted-foreground",title:"Discard this conversation",children:[e.jsx(k.SquarePen,{className:"h-3.5 w-3.5"}),"New session"]})}),e.jsxs(k.AlertDialogContent,{children:[e.jsxs(k.AlertDialogHeader,{children:[e.jsx(k.AlertDialogTitle,{children:"Discard this conversation?"}),e.jsx(k.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(k.AlertDialogFooter,{children:[e.jsx(k.AlertDialogCancel,{children:"Cancel"}),e.jsx(k.AlertDialogAction,{onClick:N,children:"Discard"})]})]})]}):null})]}),e.jsx("div",{ref:ot,className:"min-h-0 flex-1 overflow-y-auto px-3 py-4",children:e.jsxs("div",{className:"space-y-4",children:[Y.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:En.slice(0,3).map(r=>e.jsxs("button",{type:"button",onClick:()=>rt(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))})]}),Y.map(r=>r.type==="user"?e.jsx(bs,{message:r},r.id):r.type==="assistant"?e.jsx(ys,{message:r,onOpenDatasetInspector:Ue},r.id):e.jsx(ks,{getStepDuration:Yr,run:r},r.id)),ee&&!qr&&e.jsx(Ss,{phase:zr,detail:Wr,elapsedMs:Lt?Math.max(0,zt-Lt):0})]})}),e.jsxs("form",{onSubmit:kn,className:"border-t border-border p-3",children:[Ae.length>0?e.jsx(gs,{turns:Ae,onDelete:cn,onRemoveAttachment:un,onUpdatePrompt:dn}):null,e.jsxs("div",{className:"rounded-[6px] border border-border focus-within:border-ring",children:[e.jsx("textarea",{value:Ie,onChange:r=>rt(r.target.value),onPaste:r=>{const n=Array.from(r.clipboardData.files).filter(i=>i.type.startsWith("image/"));n.length!==0&&(r.preventDefault(),xr(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"}),nt.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5 border-t border-border px-2 py-2",children:nt.map(r=>e.jsx(Tt,{attachment:r,onRemove:nn},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:Ht,type:"file",accept:"image/*",className:"hidden",multiple:!0,onChange:r=>{r.target.files&&xr(r.target.files),r.target.value=""}}),e.jsxs(w.Popover,{children:[e.jsx(w.PopoverTrigger,{asChild:!0,children:e.jsx(w.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(k.Plus,{className:"h-3.5 w-3.5"})})}),e.jsx(w.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=Ht.current)==null?void 0:r.click()},children:[e.jsx($n,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Screenshot"]})})]}),e.jsxs(w.Select,{value:st,onValueChange:Hr,children:[e.jsx(w.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(w.SelectValue,{placeholder:"Model"})}),e.jsx(w.SelectContent,{align:"start",children:Ft.map(r=>e.jsx(w.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:Z||ee?e.jsxs(e.Fragment,{children:[e.jsx(w.Button,{type:"submit",size:"xs",variant:"outline",className:"gap-1.5",disabled:!Ie.trim(),children:"Queue"}),e.jsxs(w.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(Q.X,{className:"h-3 w-3"}),"Stop"]})]}):e.jsxs(w.Button,{type:"submit",size:"xs",className:"gap-1.5",disabled:!Ie.trim(),children:[e.jsx(k.Send,{className:"h-3 w-3"}),"Send"]})})]})]})]})]})}),e.jsx(k.ResizableHandle,{className:"w-px bg-border/60 transition-colors hover:bg-border"})]}):null,e.jsx(k.ResizablePanel,{className:"min-w-0",defaultSize:Re?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(w.Button,{type:"button",variant:"ghost",size:"xs",className:"-ml-1 gap-1.5 px-1.5 text-muted-foreground",title:Re?"Hide chat":"Show chat","aria-label":Re?"Hide chat":"Show chat",onClick:()=>Ir(r=>!r),children:Re?e.jsx(Mn,{className:"h-3.5 w-3.5"}):e.jsx(Tn,{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"&&ut&&e.jsxs("span",{className:`text-[10.5px] ${ut==="tailwind"?"text-emerald-700 dark:text-emerald-400":"text-amber-700 dark:text-amber-400"}`,children:["CSS: ",ut]}),Jt?e.jsx("span",{className:"min-w-0 truncate text-[11px] text-blue-700 dark:text-blue-400",children:Jt}):null,xt?e.jsx("span",{className:"min-w-0 truncate text-[11px] text-destructive",title:xt,children:xt}):ar?e.jsxs("span",{className:"min-w-0 truncate text-[11px] text-emerald-700 dark:text-emerald-400",children:["Published ",new Date(ar).toLocaleTimeString()]}):nr?e.jsxs("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:["Saved ",new Date(nr).toLocaleTimeString()]}):null,e.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[e.jsxs(w.Popover,{open:bt,onOpenChange:r=>{Ke(r),r&&vr()},children:[e.jsx(w.PopoverTrigger,{asChild:!0,children:e.jsxs(w.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",title:"Inspect the current Data App manifest",children:[cr?e.jsx(w.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(k.FileCode,{className:"h-3.5 w-3.5"}),"Manifest"]})}),e.jsxs(w.PopoverContent,{align:"end",sideOffset:6,className:"w-[520px] p-0",onInteractOutside:()=>Ke(!1),onEscapeKeyDown:()=>Ke(!1),children:[e.jsxs("div",{className:"flex h-10 items-center gap-2 border-b border-border px-3",children:[e.jsx(k.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(w.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",disabled:!wt,title:"Copy manifest JSON","aria-label":"Copy manifest JSON",onClick:()=>{var r;(r=navigator.clipboard)==null||r.writeText(wt)},children:e.jsx(k.Copy,{className:"h-3.5 w-3.5"})}),e.jsx(w.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",title:"Refresh manifest","aria-label":"Refresh manifest",onClick:()=>void vr(),children:e.jsx(k.RefreshCw,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"max-h-[520px] overflow-auto bg-muted/30 p-3",children:cr?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(w.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Reading current runtime manifest..."]}):dr?e.jsx("div",{className:"rounded-[5px] border border-destructive/30 bg-destructive/10 px-3 py-2 text-[12px] text-destructive",children:dr}):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:wt||"Open or refresh to inspect the manifest."})})]})]}),e.jsxs(k.AlertDialog,{children:[e.jsx(k.AlertDialogTrigger,{asChild:!0,children:e.jsxs(w.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",disabled:Z||ee,title:"Reset the app to a blank development template",children:[e.jsx(w.RotateCcw,{className:"h-3.5 w-3.5"}),"Reset app"]})}),e.jsxs(k.AlertDialogContent,{children:[e.jsxs(k.AlertDialogHeader,{children:[e.jsx(k.AlertDialogTitle,{children:"Reset this app?"}),e.jsx(k.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(k.AlertDialogFooter,{children:[e.jsx(k.AlertDialogCancel,{children:"Cancel"}),e.jsx(k.AlertDialogAction,{onClick:()=>void Xr(),children:"Reset app"})]})]})]}),e.jsxs(w.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",disabled:Z||ee||Ve==="saving"||A!=="bridge"||!jt,title:"Save the current local source snapshot as a Semaphor draft",onClick:()=>void jr(),children:[Ve==="saving"?e.jsx(w.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Cn.Save,{className:"h-3.5 w-3.5"}),"Save draft"]}),e.jsxs(w.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",disabled:Z||ee||Ve==="saving"||rr==="publishing"||A!=="bridge"||!St,title:"Build, upload, and publish the current Data App",onClick:()=>void jn(),children:[rr==="publishing"?e.jsx(w.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Dn,{className:"h-3.5 w-3.5"}),"Publish"]}),A==="bridge"?e.jsxs(w.Button,{type:"button",variant:fe?"default":"ghost",size:"xs",disabled:Vt,className:fe?"gap-1.5":"gap-1.5 text-muted-foreground",title:"Select an element in the preview and attach its DOM/React context",onClick:()=>fe?on():void an(),children:[Vt?e.jsx(w.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Fn,{className:"h-3.5 w-3.5"}),fe?"Cancel inspect":"Inspect"]}):null,e.jsxs(w.Popover,{children:[e.jsx(w.PopoverTrigger,{asChild:!0,children:e.jsxs(w.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",children:[e.jsx(k.Settings2,{className:"h-3.5 w-3.5"}),"Runtime",A==="browser"&&ct.length>0?e.jsx("span",{className:"text-[10px] text-amber-600",children:"CSS fallback"}):null]})}),e.jsx(w.PopoverContent,{align:"end",sideOffset:6,className:"w-[380px] p-3",children:A==="bridge"?e.jsxs("div",{className:"space-y-2.5",children:[e.jsx($t,{label:"App Directory",value:g,placeholder:Bt,onChange:E}),e.jsx($t,{label:"App Local URL",value:m,onChange:R}),e.jsx($t,{label:"Bridge URL",value:v,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(w.Button,{type:"button",variant:"outline",size:"xs",className:"h-6 shrink-0 text-[10.5px]",disabled:Z||ee||De!=="ready",onClick:()=>void hr(),children:"Reset"})]}),ct[0]?e.jsx("div",{className:"mt-2 rounded-[5px] border border-border bg-muted/40 px-2 py-1.5 text-muted-foreground",children:ct[0]}):null,e.jsx(ls,{manifest:Ur})]})})]}),e.jsx(w.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(m),X(r=>r+1))},children:e.jsx(k.RefreshCw,{className:"h-3.5 w-3.5"})})]})]}),ie?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 ${ie.state==="failed"?"border-destructive/30 bg-destructive/10 text-destructive":ie.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:[ie.state==="running"?e.jsx(w.LoaderCircle,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin"}):ie.state==="done"?e.jsx(w.Check,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}):e.jsx(Q.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:ie.label}),ie.detail?e.jsx("div",{className:"mt-0.5 truncate opacity-80",children:ie.detail}):null]})]})}):null,(A==="browser"&&(De==="loading"||De==="failed")||Be&&!((Sr=Be.appBuilder)!=null&&Sr.hasOpenAiKey))&&e.jsxs("div",{className:"shrink-0 border-b border-border px-3 py-2",children:[A==="browser"&&De==="loading"&&e.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:"Loading the in-browser runtime…"}),A==="browser"&&De==="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.",Gt?e.jsx("pre",{className:"mt-1.5 whitespace-pre-wrap font-mono text-[10.5px] text-muted-foreground",children:Gt}):null]}),Be&&!((kr=Be.appBuilder)!=null&&kr.hasOpenAiKey)&&e.jsx("div",{className:"rounded-[5px] border border-destructive/30 bg-destructive/10 px-2 py-1.5 text-[11px] text-destructive",children:Be.error||"OPENAI_API_KEY is not configured."})]}),A==="browser"&&_r.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(k.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:Zt.length})]}),e.jsx("div",{className:"max-h-72 shrink-0 overflow-y-auto border-b border-border p-2",children:e.jsx(is,{files:Zt,selectedPath:pt,onSelect:Qr})}),e.jsx("pre",{className:"min-h-0 flex-1 overflow-auto p-3 font-mono text-[11px] leading-relaxed text-muted-foreground",children:(ht==null?void 0:ht.contents)||"Select a file to inspect its source."})]}),e.jsx("iframe",{ref:it,className:"min-h-0 flex-1 bg-background",onLoad:()=>{fe&&window.setTimeout(()=>Ye("inspect-enable"),100)},src:A==="browser"?void 0:Nt,srcDoc:A==="browser"?Jr:void 0,title:"Data app preview"},A==="browser"?`browser-${be}`:Nt),ir?e.jsx(js,{artifact:ir,onClose:()=>Ue(null)}):null]})]})})]})}function $t({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 ps({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(w.Check,{className:"h-3 w-3"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(k.Copy,{className:"h-3 w-3"}),"Copy"]})})]}),e.jsx("div",{className:"overflow-x-auto bg-background",children:e.jsx(k.CodeHighlighter,{code:t,language:s||"tsx"})})]})}const hs=/(\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 fs(t,s){return t.split(hs).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(k.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 ms(t,s){return t.split(`
51
+ `)||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 is({files:t,selectedPath:s,onSelect:a}){const d=p.useMemo(()=>qn(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(Lr,{node:l,depth:0,selectedPath:s,onSelect:a},l.path||l.name))})}function Lr({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(tt.ChevronRight,{className:"h-3 w-3 rotate-90 text-muted-foreground"}),e.jsx(Pn,{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(k.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(Lr,{node:h,depth:s+1,selectedPath:a,onSelect:d},h.path))]})}function ls({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 ds({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 cs({projectId:t,projectName:s,dataAppId:a,apiServiceUrl:d,adapters:l}){var v,B;const u=p.useContext(k.SemaphorContext),h=typeof window>"u"?void 0:window.location.origin,x=d||((v=u.tokenProps)==null?void 0:v.apiServiceUrl)||h,N=(B=u.authToken)==null?void 0:B.accessToken,[m,R]=p.useState(()=>pe("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(us,{adapters:l,apiServiceUrl:x,accessToken:N,initialDataAppId:a||null,initialPrompt:"",path:"bridge",projectId:t,projectName:s,onRestart:()=>R(pe("builder-session"))},m)})}function us({adapters:t,apiServiceUrl:s,accessToken:a,initialDataAppId:d,initialPrompt:l,path:u,projectId:h,projectName:x,onRestart:N}){var Sr,kr;const[m,R]=p.useState(Rt),[v,B]=p.useState(Br),[g,E]=p.useState(Bt),[z,L]=p.useState(!1),[F,W]=p.useState(Rt),[be,X]=p.useState(0),[A]=p.useState(u),[Ie,rt]=p.useState(l||""),[nt,ze]=p.useState([]),[Ae,Ce]=p.useState([]),[Y,he]=p.useState([]),[Et,We]=p.useState(null),[Z,He]=p.useState(!1),[ee,Ot]=p.useState(!1),[Re,Ir]=p.useState(!0),[zr,se]=p.useState("idle"),[Wr,ae]=p.useState(null),[Lt,It]=p.useState(null),[zt,Je]=p.useState(()=>Date.now()),[Be,Wt]=p.useState(null),[st,Hr]=p.useState("gpt-5.5-low"),q=p.useRef(null),U=p.useRef(null),at=p.useRef([]),ot=p.useRef(null),it=p.useRef(null),Ht=p.useRef(null),[fe,we]=p.useState(!1),[Jt,oe]=p.useState(null),[Vt,lt]=p.useState(!1),[_t,Ut]=p.useState(!1),[De,dt]=p.useState("idle"),[Gt,Kt]=p.useState(null),[Jr,qt]=p.useState(""),[Vr,Qt]=p.useState([]),[ct,Xt]=p.useState([]),[ut,Yt]=p.useState(null),[Zt,_r]=p.useState([]),[Ur,Gr]=p.useState(null),[pt,er]=p.useState(null),[ht,tr]=p.useState(null),[me,Ve]=p.useState(d||null),[_e,ft]=p.useState("idle"),[rr,mt]=p.useState("idle"),[nr,sr]=p.useState(null),[ar,or]=p.useState(null),[xt,ye]=p.useState(null),[ie,H]=p.useState(null),[ir,Ue]=p.useState(null),[Ge,gt]=p.useState(null),[bt,Ke]=p.useState(!1),[wt,lr]=p.useState(""),[dr,yt]=p.useState(null),[cr,ur]=p.useState(!1),Pe=p.useRef(null),vt=p.useRef(null),ve=p.useRef(null),pr=(t==null?void 0:t.readStatus)||zn,qe=(t==null?void 0:t.runTurn)||Wn,jt=(t==null?void 0:t.saveDraft)||Jn,Kr=(t==null?void 0:t.loadApp)||Vn,St=(t==null?void 0:t.publish)||_n,J=p.useMemo(()=>In(st),[st]),qr=p.useMemo(()=>Y.find(r=>r.type==="run"&&r.id===Et),[Et,Y]),kt=p.useMemo(()=>[...Y].reverse().find(r=>r.type==="run"),[Y]),Nt=p.useMemo(()=>{const r=F.includes("?")?"&":"?";return`${F}${r}dataAppBuilderRefresh=${be}`},[F,be]);p.useEffect(()=>{const r=window.setInterval(()=>Je(Date.now()),500);return()=>window.clearInterval(r)},[]),p.useEffect(()=>{at.current=Y},[Y]),p.useEffect(()=>{if(!bt)return;const r=()=>{Ke(!1)};return window.addEventListener("blur",r),()=>{window.removeEventListener("blur",r)}},[bt]),p.useEffect(()=>{L(!1);const r=window.localStorage.getItem(ue(Ar,h))||Rt,n=window.localStorage.getItem(ue(Cr,h))||Br,i=window.localStorage.getItem(ue(Rr,h))||Bt,o=window.localStorage.getItem(ue(Nr,h));if(R(r),W(r),B(n),E(i),L(!0),o)try{he(JSON.parse(o))}catch{he([])}},[h]),p.useEffect(()=>{window.localStorage.setItem(ue(Ar,h),m)},[m,h]),p.useEffect(()=>{window.localStorage.setItem(ue(Cr,h),v)},[v,h]),p.useEffect(()=>{window.localStorage.setItem(ue(Rr,h),g)},[g,h]),p.useEffect(()=>{var r;window.localStorage.setItem(ue(Nr,h),JSON.stringify(Y.map(ws))),(r=ot.current)==null||r.scrollTo({top:ot.current.scrollHeight,behavior:"smooth"})},[Y,h]),p.useEffect(()=>{ve.current=pt},[pt]);const At=p.useCallback(async r=>{if(A!=="bridge"||!s)return;const n=v.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,v,me,h,A]);p.useEffect(()=>{if(A!=="bridge"||!s)return;const r=new AbortController;return At(r.signal).then(()=>{X(n=>n+1)}).catch(n=>{r.signal.aborted||(lt(!1),oe(n instanceof Error?n.message:"Bridge could not sync runtime context."))}),()=>r.abort()},[s,A,At]),p.useEffect(()=>{Ve(d||null)},[d]),p.useEffect(()=>{if(!d||!z||vt.current===`${d}:${A}:${g}`)return;const r=new AbortController;return vt.current=`${d}:${A}:${g}`,ye(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 Kr({dataAppId:d},{apiServiceUrl:s,accessToken:a,signal:r.signal});if(r.signal.aborted)return;Ve(o.id);const c=rs(o);if(!c){H({state:"done",label:"Data App opened",detail:"No saved source snapshot exists yet."});return}const f=ts(c.manifest);f&&gt(f),c.status==="draft"?sr(c.updatedAt||null):c.status==="ready"&&or(c.updatedAt||null);const j=ns(c,g);let b=!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."}),b=await wn({snapshot:c.sourceSnapshot,targetProjectDir:j,signal:r.signal}),b&&X(C=>C+1)),A==="bridge"&&j!==g&&E(j),r.signal.aborted)return;H({state:"done",label:"Data App opened",detail:b?"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);vt.current=null,ye(c),H({state:"failed",label:"Open Data App failed",detail:c}),M(`Open Data App failed: ${c}`,"blocked")}})(),()=>r.abort()},[z,d,g,A]),p.useEffect(()=>{function r(n){var c;if(n.source!==((c=it.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"&&fe){Ye("inspect-enable");return}if(i.type==="enabled"){oe("Click an element in the preview. Press Esc to cancel.");return}if(i.type==="disabled"){we(!1);return}if(i.type!=="selection"||!i.payload)return;const o=ln(i.payload);ze(f=>[...f,o]),we(!1),oe(`Selected ${o.name}. Add a message and send it.`)}return window.addEventListener("message",r),()=>window.removeEventListener("message",r)},[fe]),p.useEffect(()=>{we(!1),lt(!1),oe(null)},[v,g,A]),p.useEffect(()=>{if(Z||ee||Ae.length===0)return;const[r,...n]=Ae;Ce(n),mr(r)},[Z,ee,Ae]),p.useEffect(()=>{let r=!1;const n=new AbortController;async function i(){try{const o=await pr({apiServiceUrl:s,accessToken:a,signal:n.signal});r||Wt(o)}catch(o){r||Wt({ok:!1,error:o instanceof Error?o.message:String(o)})}}return i(),()=>{r=!0}},[a,s,pr]);const Qe=p.useCallback(async(r=U.current)=>{if(!r)return;const n=await r.compileBrowserSandboxPreviewHtml();qt(n.html),Qt(n.diagnostics),Xt(n.warnings||[]),Yt(n.cssMode||null),X(i=>i+1)},[]),$e=p.useCallback((r=U.current,n=ve.current)=>{var f;if(!r)return;const i=r.listBrowserSandboxFiles(),o=r.readBrowserSandboxWorkspaceContext(),c=n&&i.some(j=>j.path===n)?n:((f=i[0])==null?void 0:f.path)||null;_r(i),Gr(o.runtimeManifest||null),er(c),ve.current=c,tr(c&&r.readBrowserSandboxFiles([c])[0]||null)},[]);p.useEffect(()=>{if(A!=="browser")return;let r=!1;async function n(){dt("loading"),Kt(null),window.__SEMAPHOR_BROWSER_SANDBOX_VENDOR__={React:Rn,ReactDOMClient:Bn};try{const i=await Ze.loadSemaphorBrowserRuntime();if(r)return;U.current=i,dt("ready"),await Qe(i),$e(i)}catch(i){if(r)return;dt("failed"),Kt(i instanceof Error?i.message:String(i))}}return n(),()=>{r=!0}},[A,$e,Qe]);function Qr(r){const n=U.current;er(r),ve.current=r,tr(n&&n.readBrowserSandboxFiles([r])[0]||null)}async function hr(){const r=U.current;!r||Z||(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 Xr(){if(Z||ee)return;if(gt(null),Ue(null),lr(""),yt(null),A==="browser"){await hr();return}const r=new AbortController,n=v.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(m),X(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 Yr(r){const n=r.durationMs??0;return r.state!=="running"||!r.startedAt?n:n+Math.max(0,zt-r.startedAt)}function Zr(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 en(r,n,i){const o=Date.now();Je(o),he(c=>c.map(f=>{if(f.type!=="run"||f.id!==r)return f;const j=n(f.steps),b=new Map(f.steps.map(C=>[C.id,C]));return{...f,...i,steps:j.map(C=>{const y=b.get(C.id);return y?Zr(y,C,o):C})}}))}function Xe(r,n){he(i=>i.map(o=>o.type==="run"&&o.id===r?{...o,...n}:o))}function M(r,n="default",i){const o=Le(i==null?void 0:i.intentManifest)?i==null?void 0:i.intentManifest:void 0;he(c=>[...c,{id:pe("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 tn(r){var i;r.intentManifest&&gt(o=>os(o,r.intentManifest));const n=(i=r.artifacts)==null?void 0:i.find(o=>o.type==="dataset_inspector");n&&Ue(n)}function fr(r){se({received:"context",authenticating:"context",routing:"thinking",inspecting_data:"inspecting-data",reading_files:"reading-files",planning_revision:"planning",generating_code:"generating",done:"thinking"}[r.phase]),ae(r.detail||r.label)}function mr(r){const n=r.prompt.trim();if(!n)return;const i=Date.now();he(o=>[...o,{id:pe("user"),type:"user",content:n,createdAt:i,attachments:r.attachments}]),It(i),se("context"),ae("Preparing app context and available files."),Sn({...r,prompt:n})}async function rn(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)});ze(i=>[...i,{id:pe("attachment"),type:"screenshot",name:r.name||"Screenshot",imageUrl:n,mediaType:r.type,createdAt:Date.now()}])}function nn(r){ze(n=>n.filter(i=>i.id!==r))}function Ye(r){var i,o;let n="*";try{n=new URL(Nt).origin}catch{n="*"}(o=(i=it.current)==null?void 0:i.contentWindow)==null||o.postMessage({source:"semaphor-data-app-builder",type:r},n)}async function sn(){const r=v.replace(/\/$/,""),n=await fetch(`${r}/inspect/install`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:g})}),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 an(){if(A!=="bridge"){M("Element inspection is only available in Local Bridge mode right now.","blocked");return}try{Ut(!0),oe(Vt?null:"Preparing element inspector…");let r=!1;if(!Vt){const n=await sn();lt(!!n.installed),r=!!n.changed}we(!0),oe(r?"Loading inspector in the preview…":"Click an element in the preview. Press Esc to cancel."),r?(W(m),X(n=>n+1)):window.setTimeout(()=>Ye("inspect-enable"),50)}catch(r){we(!1),oe(null),M(r instanceof Error?r.message:String(r),"blocked")}finally{Ut(!1)}}function on(){we(!1),oe(null),Ye("inspect-disable")}function ln(r){const n=(y,S="")=>typeof y=="string"&&y.trim()?y.trim():S,i=y=>Array.isArray(y)?y.map(S=>typeof S=="string"?S:S&&typeof S=="object"?JSON.stringify(S):"").filter(Boolean):[],o=n(r.elementLabel)||n(r.name),c=n(r.component),f=o&&c&&o!==c?`${o} in ${c}`:o||c||n(r.tagName,"Selected element"),j=i(r.reactOwners),b=i(r.sourceHints),C=[`Clicked element: ${o||f}`,`Nearest component: ${c||"unavailable"}`,`Tag: ${n(r.tagName,"unknown")}`,`Role: ${n(r.role,"none")}`,`Selector: ${n(r.selector,"none")}`,j.length?`React owner stack: ${j.join(" > ")}`:"React owner stack: unavailable",b.length?`Source hints: ${b.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(`
52
+ `);return{id:pe("attachment"),type:"dom-selection",name:f,text:C,createdAt:Date.now()}}function dn(r,n){Ce(i=>i.map(o=>o.id===r?{...o,prompt:n}:o))}function cn(r){Ce(n=>n.filter(i=>i.id!==r))}function un(r,n){Ce(i=>i.map(o=>o.id===r?{...o,attachments:o.attachments.filter(c=>c.id!==n)}:o))}async function xr(r){for(const n of Array.from(r))await rn(n)}function gr(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){en(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"]},j={reading:"context",generating:"generate",writing:"edit",typechecking:"typecheck",repairing:"repair"}[n];return{...o,state:c[n].includes(o.id)?"done":j===o.id?"running":o.state==="done"?"done":"idle"}}))}async function pn(r,n,i){var j,b,C,y;(j=q.current)==null||j.abort();const o=new AbortController,c=Date.now();q.current=o,He(!0),We(n),Je(c),G(n,"reading");const f=window.setTimeout(()=>{o.abort()},18e4);try{let S=U.current;S||(S=await Ze.loadSemaphorBrowserRuntime(),U.current=S);const I=S.readBrowserSandboxWorkspaceContext(),D=(C=(b=I.files)==null?void 0:b.editable)!=null&&C.length?Pr(I.files.editable,ve.current,r):["src/App.tsx"],le=S.readBrowserSandboxFiles(D),je=le.reduce((re,te)=>re+te.contents.length,0);let Se=le,Fe=[],de=i,K=null;const ce=[];for(let re=0;re<Ee;re+=1){const te=Fe.length>0||re>0,Me=te?`repair-${re+1}`:"initial";G(n,te?"repairing":"generating");const V=de||(await qe({projectId:h,message:r,currentFiles:Se,workspaceContext:I,diagnostics:Fe,repair:te,generationModel:J.model,generationReasoningEffort:J.reasoningEffort,repairModel:J.model,repairReasoningEffort:J.reasoningEffort},{accessToken:a,apiServiceUrl:s,signal:o.signal})).revision;if(de=void 0,!V)throw new Error("Data App Builder did not return a revision.");G(n,"writing");const xe=S.applyBrowserSandboxRevision({...V,attemptLabel:Me});ce.push(...xe.attempts||[]),G(n,"typechecking");let P={...xe,attempts:[...ce],filePlan:V.plan,telemetry:{contextFileCount:le.length,contextChars:je,generatedFileCount:V.files.length,generatedChars:V.files.reduce(($,_)=>$+_.contents.length,0),repairAttempts:ce.filter($=>$.label.startsWith("repair")).length}};if(xe.ok){const $=await S.compileBrowserSandboxPreviewHtml();if(qt($.html),Qt($.diagnostics),Xt($.warnings||[]),Yt($.cssMode||null),X(_=>_+1),$e(S),$.diagnostics.length>0){const _={command:"browser sandbox preview compile",durationMs:0,exitCode:1,ok:!1,stdout:"",stderr:$.diagnostics.join(`
53
+ `)};P={...P,ok:!1,validation:"typecheck",command:_,attempts:[...ce,{label:Me,ok:!1,command:_}],error:"Generated files failed Browser Sandbox preview compile."}}}if(K=P,P.ok||re===Ee-1)break;const T=(y=P.changedFiles)!=null&&y.length?P.changedFiles:V.files.map($=>$.path);Se=S.readBrowserSandboxFiles(Array.from(new Set([...D,...T]))),Fe=[Pt(P)]}if(!K)throw new Error("The browser runtime loop ended without a validation result.");G(n,K.ok?"complete":"failed"),Xe(n,{status:K.ok?"done":"failed",result:K,error:K.error,finishedAt:Date.now()}),M(gr(K,"browser"),K.ok?"default":"blocked")}catch(S){const I=S instanceof DOMException&&S.name==="AbortError",D=I?"Timed out waiting for the browser runtime loop.":S instanceof Error?S.message:String(S);Xe(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{He(!1),We(null),q.current=null,window.clearTimeout(f)}}async function hn(r,n,i){var j,b,C,y;(j=q.current)==null||j.abort();const o=new AbortController,c=Date.now();q.current=o,He(!0),We(n),Je(c),G(n,"reading");const f=window.setTimeout(()=>{o.abort()},18e4);try{const S=v.replace(/\/$/,""),I=async P=>{const T=await fetch(`${S}/read-files`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:P,projectDir:g})}),$=await O(T,"Local bridge /read-files");if(!T.ok||!$.ok||!$.files)throw new Error($.error||"Bridge could not read target files.");return $.files},D=async()=>{const P=await fetch(`${S}/workspace-context`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:g})}),T=await O(P,"Local bridge /workspace-context");if(!P.ok||!T.ok||!T.workspaceContext)throw new Error(T.error||"Bridge could not read workspace context.");return T.workspaceContext};let le=i;const je=async({currentFiles:P,workspaceContext:T,diagnostics:$=[],repair:_=!1})=>{const ne=le||(await qe({projectId:h,message:r,currentFiles:P,workspaceContext:T,diagnostics:$,repair:_,generationModel:J.model,generationReasoningEffort:J.reasoningEffort,repairModel:J.model,repairReasoningEffort:J.reasoningEffort},{accessToken:a,apiServiceUrl:s,signal:o.signal})).revision;if(le=void 0,!ne)throw new Error("Data App Builder did not return a revision.");return ne},Se=async P=>{const T=await fetch(`${S}/apply-files`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({revision:P,projectDir:g})}),$=await O(T,"Local bridge /apply-files");if(!T.ok&&!$.command&&!$.writePolicyValidation&&!$.importValidation&&!$.dataApiValidation)throw new Error($.error||"Bridge could not apply generated files.");return $},Fe=async()=>{const P=await fetch(`${S}/validate-typecheck`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:g})}),T=await O(P,"Local bridge /validate-typecheck");if(!P.ok&&!T.command)throw new Error(T.error||"Bridge could not typecheck the target app.");return T},de=await D();de.projectRoot&&E(de.projectRoot);let K=(C=(b=de.files)==null?void 0:b.editable)!=null&&C.length?Dr(de.files.editable):["src/App.tsx"];const ce=await I(K),re=ce.reduce((P,T)=>P+T.contents.length,0);let te=[];if(Kn(r)){const P=await Fe();P.ok||(te=[Pt(P)])}let Me=ce,V=null;const xe=[];for(let P=0;P<Ee;P+=1){const T=te.length>0||P>0,$=T?`repair-${P+1}`:"initial";G(n,T?"repairing":"generating");const _=await je({currentFiles:Me,workspaceContext:de,diagnostics:te,repair:T});G(n,"writing");const ne=await Se({..._,attemptLabel:$});if(W(m),X(Te=>Te+1),xe.push(...ne.attempts||[]),V={...ne,attempts:[...xe],filePlan:_.plan,telemetry:{contextFileCount:ce.length,contextChars:re,generatedFileCount:_.files.length,generatedChars:_.files.reduce((Te,Nn)=>Te+Nn.contents.length,0),repairAttempts:xe.filter(Te=>Te.label.startsWith("repair")).length}},G(n,"typechecking"),ne.ok||P===Ee-1)break;Me=(((y=ne.changedFiles)==null?void 0:y.length)||0)>0?await I(K=Array.from(new Set([...K,...ne.changedFiles||[]]))):_.files,te=[Pt(ne)]}if(!V)throw new Error("The app-builder loop ended without a validation result.");G(n,V.ok?"complete":"failed"),Xe(n,{status:V.ok?"done":"failed",result:V,error:V.error,finishedAt:Date.now()}),M(gr(V,"bridge"),V.ok?"default":"blocked")}catch(S){const I=S instanceof DOMException&&S.name==="AbortError",D=I?"Timed out waiting for the app-builder/bridge loop. The target app may still have updated through HMR.":S instanceof Error?S.message:String(S);Xe(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{He(!1),We(null),q.current=null,window.clearTimeout(f)}}async function fn(r){var c,f;let n=U.current;n||(n=await Ze.loadSemaphorBrowserRuntime(),U.current=n);const i=n.readBrowserSandboxWorkspaceContext(),o=(f=(c=i.files)==null?void 0:c.editable)!=null&&f.length?Pr(i.files.editable,ve.current,r):["src/App.tsx"];return{currentFiles:n.readBrowserSandboxFiles(o),workspaceContext:i}}async function mn(r){const n=U.current;return n?n.readBrowserSandboxFiles(r):[]}async function Ct(r,n){const i=v.replace(/\/$/,""),o=await fetch(`${i}/read-files`,{method:"POST",signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r,projectDir:g})}),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 xn(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 br(r){var j,b;await At(r);const n=v.replace(/\/$/,""),i=await fetch(`${n}/workspace-context`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:g})}),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 f=(b=(j=c.files)==null?void 0:j.editable)!=null&&b.length?Dr(c.files.editable):["src/App.tsx"];return{currentFiles:await Ct(f,r),workspaceContext:c}}function wr(r,n){return{schemaVersion:"data-app/v1",app:{id:me||void 0,name:`${x} Data App`,createdWith:"semaphor-app-builder"},runtime:{framework:r.framework,bundler:r.framework==="vite-react"?"vite":void 0},semaphor:{projectId:h,runtime:A,intentManifest:Ge||void 0},build:{sourceFileCount:n.files.length,validation:r.validation}}}async function yr(r){var j,b,C,y,S,I;const{workspaceContext:n}=await br(r),i=v.replace(/\/$/,""),o=await fetch(`${i}/source-snapshot`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:g})});if(o.ok){const D=await O(o,"Local bridge /source-snapshot");if(!D.ok||!((j=D.files)!=null&&j.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((b=D.metadata)==null?void 0:b.capturedAt)=="string"?D.metadata.capturedAt:new Date().toISOString(),projectRoot:n.projectRoot||g,runtime:A}}}}const c=(y=(C=n.files)==null?void 0:C.snapshot)!=null&&y.length?n.files.snapshot:[...((S=n.files)==null?void 0:S.source)||[],...((I=n.files)==null?void 0:I.root)||[]],f=await Ct([...new Set(c.length?c:["src/App.tsx"])],r);return{workspaceContext:n,snapshot:{schemaVersion:"data-app-source-snapshot/v1",files:f,metadata:{capturedAt:new Date().toISOString(),projectRoot:n.projectRoot||g,runtime:A}}}}async function gn(r,n){var f,j;const i=v.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||!((f=c.files)!=null&&f.length)?null:{schemaVersion:"data-app-source-snapshot/v1",files:c.files,metadata:{...c.metadata,capturedAt:typeof((j=c.metadata)==null?void 0:j.capturedAt)=="string"?c.metadata.capturedAt:new Date().toISOString(),projectRoot:r,runtime:A}}}async function bn(r,n,i){const o=v.replace(/\/$/,""),c=await fetch(`${o}/apply-files`,{method:"POST",signal:i,headers:{"Content-Type":"application/json"},body:JSON.stringify({revision:r,projectDir:n})}),f=await O(c,"Local bridge /apply-files");if(!c.ok||!f.ok)throw new Error(f.error||"Bridge could not restore saved files.");return f}async function wn({snapshot:r,targetProjectDir:n,signal:i}){const o=await gn(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])),f=r.files.filter(C=>c.get(C.path)!==C.contents),j=Math.max(0,o.files.length-r.files.length);return o&&f.length===0||!window.confirm(["Restore this saved Data App source snapshot into the bridge workspace?","",`Target workspace: ${n}`,"",`${f.length||r.files.length} saved file${(f.length||r.files.length)===1?"":"s"} will be written. Extra local files are left unchanged.`,j?`${j} extra local file${j===1?"":"s"} may remain in the workspace.`:""].filter(Boolean).join(`
54
+ `))?!1:(await bn({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 yn(){var c,f,j,b;let r=U.current;r||(r=await Ze.loadSemaphorBrowserRuntime(),U.current=r);const n=r.readBrowserSandboxWorkspaceContext(),i=(f=(c=n.files)==null?void 0:c.snapshot)!=null&&f.length?n.files.snapshot:[...((j=n.files)==null?void 0:j.source)||[],...((b=n.files)==null?void 0:b.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 vr(){const r=new AbortController;ur(!0),yt(null);try{const{workspaceContext:n,snapshot:i}=A==="browser"?await yn():await yr(r.signal),o=wr(n,i);lr(JSON.stringify(o,null,2))}catch(n){yt(n instanceof Error?n.message:String(n))}finally{ur(!1)}}async function jr(){if(Pe.current)return Pe.current;if(!jt)return M("Save draft is not configured in this host yet.","blocked"),null;const r=new AbortController;ft("saving"),ye(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 yr(r.signal),f=wr(c,o),j=await as({snapshot:o,workspaceContext:c,projectDir:g,adapter:"bridge"}),b=await jt({projectId:h,dataAppId:me,title:me?void 0:((i=f.app)==null?void 0:i.name)||`${x} Data App`,description:me?void 0:null,manifest:f,sourceSnapshot:o,sourceRevision:j,validationStatus:(kt==null?void 0:kt.result)||null,bridgeWorkspaceHint:c.projectRoot||g},{apiServiceUrl:s,accessToken:a,signal:r.signal});return Ve(b.dataAppId),sr(b.savedAt||new Date().toISOString()),ft("saved"),H({state:"done",label:"Draft saved",detail:"Semaphor has the latest source snapshot."}),M("Draft saved to Semaphor.","default"),{dataAppId:b.dataAppId,draftId:b.draftId,manifest:f,snapshot:o,sourceRevision:j,workspaceContext:c}}catch(o){const c=o instanceof Error?o.message:String(o);return ye(c),ft("failed"),H({state:"failed",label:"Save draft failed",detail:c}),M(`Save draft failed: ${c}`,"blocked"),null}finally{Pe.current=null}})();return Pe.current=n,n}async function vn(r){var c;const n=v.replace(/\/$/,""),i=await fetch(`${n}/publish-build`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:g})}),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 jn(){if(!St){M("Publish is not configured in this host yet.","blocked");return}if(_e==="saving"&&!Pe.current){M("Save draft is already in progress.","blocked");return}const r=await jr(),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;mt("publishing"),ye(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 St({projectId:h,dataAppId:n,draftId:r.draftId,title:`${x} Data App`,description:null,sourceSnapshot:r.snapshot,sourceRevision:r.sourceRevision,bridgeWorkspaceHint:r.workspaceContext.projectRoot||g,buildArtifacts:async({signal:c})=>{const f=await vn(c),j=f.assets;return{manifest:{...f.manifest,semaphor:{...f.manifest.semaphor||{},projectId:h,runtime:A,intentManifest:Ge||void 0}},validationStatus:f,bridgeWorkspaceHint:r.workspaceContext.projectRoot||g,assets:j,entryFile:f.entryFile,styleFiles:f.styleFiles||[]}}},{apiServiceUrl:s,accessToken:a,signal:i.signal,onProgress:c=>{H({state:"running",label:c.label,detail:c.detail})}});Ve(o.dataAppId),or(o.publishedAt||new Date().toISOString()),mt("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);ye(c),mt("failed"),H({state:"failed",label:"Publish failed",detail:c}),M(`Publish failed: ${c}`,"blocked")}}async function Sn(r){var f,j;const{attachments:n,prompt:i}=r,o=new AbortController;q.current=o,Ot(!0);const c=window.setTimeout(()=>{o.abort()},18e4);try{se("context"),ae("Reading the app manifest and starter context.");let b=A==="browser"?await fn(i):await br(o.signal);const C=[];let y=null;for(;se("thinking"),ae(b.currentFiles.length>0?"Reviewing the app context and deciding the next step.":"Deciding whether this needs an answer, file inspection, or edits."),y=await qe({projectId:h,message:i,currentFiles:b.currentFiles,workspaceContext:b.workspaceContext,conversationContext:Mr(at.current,Ge),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:fr}),!(!y||y.mode!=="read_files");){const D=(y.requestedFiles||[]).filter(je=>typeof je=="string"&&!b.currentFiles.some(Se=>Se.path===je));if(D.length===0){se("thinking"),ae("No additional source files are needed; preparing the response."),y=await qe({projectId:h,message:i,currentFiles:b.currentFiles,workspaceContext:b.workspaceContext,conversationContext:Mr(at.current,Ge),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:fr});break}se("reading-files"),ae(`Reading ${D.length} requested file${D.length===1?"":"s"}: ${Zn(D)}.`),C.push({tool:"read_files",status:"done",detail:D.join(", ")});const le=A==="browser"?await mn(D):await Ct(D,o.signal);b={...b,currentFiles:xn(b.currentFiles,le)}}if(!y)throw new Error("Data App Builder did not return a turn.");if(C.length>0&&(y={...y,toolEvents:[...C,...y.toolEvents||[]]}),tn(y),y.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(y.mode!=="edit"){M(y.message,y.mode==="clarify"?"guidance":"default",{artifacts:y.artifacts,operation:y.operation,intentManifest:y.intentManifest});return}if(!y.revision)throw new Error("Data App Builder chose an edit but returned no revision.");M(Yn(y),"guidance",{operation:y.operation,intentManifest:y.intentManifest}),se("planning"),ae((j=(f=y.revision.plan)==null?void 0:f.files)!=null&&j.length?`Preparing edits for ${y.revision.plan.files.length} file${y.revision.plan.files.length===1?"":"s"}.`:"Preparing the file edit and validation run.");const S=pe("run"),I=Date.now();he(D=>[...D,{id:S,type:"run",prompt:i,status:"running",steps:Gn(),createdAt:I,startedAt:I}]),q.current=null,A==="browser"?pn(i,S,y.revision):hn(i,S,y.revision)}catch(b){const C=b instanceof DOMException&&b.name==="AbortError";M(C?"The app-builder turn timed out before a response was produced.":b instanceof Error?b.message:String(b),"blocked")}finally{Ot(!1),se("idle"),ae(null),It(null),q.current===o&&(q.current=null),window.clearTimeout(c)}}function kn(r){r.preventDefault();const n=Ie.trim();if(!n)return;const i=Date.now(),o=nt,c={id:pe("turn"),prompt:n,attachments:o,createdAt:i};if(rt(""),ze([]),Z||ee){Ce(f=>[...f,c]);return}mr(c)}return e.jsxs(k.ResizablePanelGroup,{autoSaveId:`semaphor-data-app-builder-${h}`,className:"h-full min-h-0 flex-1",direction:"horizontal",children:[Re?e.jsxs(e.Fragment,{children:[e.jsx(k.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(k.AlertDialog,{children:[e.jsx(k.AlertDialogTrigger,{asChild:!0,children:e.jsxs(w.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 px-1.5 text-muted-foreground",title:"Discard this conversation",children:[e.jsx(k.SquarePen,{className:"h-3.5 w-3.5"}),"New session"]})}),e.jsxs(k.AlertDialogContent,{children:[e.jsxs(k.AlertDialogHeader,{children:[e.jsx(k.AlertDialogTitle,{children:"Discard this conversation?"}),e.jsx(k.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(k.AlertDialogFooter,{children:[e.jsx(k.AlertDialogCancel,{children:"Cancel"}),e.jsx(k.AlertDialogAction,{onClick:N,children:"Discard"})]})]})]}):null})]}),e.jsx("div",{ref:ot,className:"min-h-0 flex-1 overflow-y-auto px-3 py-4",children:e.jsxs("div",{className:"space-y-4",children:[Y.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:En.slice(0,3).map(r=>e.jsxs("button",{type:"button",onClick:()=>rt(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))})]}),Y.map(r=>r.type==="user"?e.jsx(bs,{message:r},r.id):r.type==="assistant"?e.jsx(ys,{message:r,onOpenDatasetInspector:Ue},r.id):e.jsx(ks,{getStepDuration:Yr,run:r},r.id)),ee&&!qr&&e.jsx(Ss,{phase:zr,detail:Wr,elapsedMs:Lt?Math.max(0,zt-Lt):0})]})}),e.jsxs("form",{onSubmit:kn,className:"border-t border-border p-3",children:[Ae.length>0?e.jsx(gs,{turns:Ae,onDelete:cn,onRemoveAttachment:un,onUpdatePrompt:dn}):null,e.jsxs("div",{className:"rounded-[6px] border border-border focus-within:border-ring",children:[e.jsx("textarea",{value:Ie,onChange:r=>rt(r.target.value),onPaste:r=>{const n=Array.from(r.clipboardData.files).filter(i=>i.type.startsWith("image/"));n.length!==0&&(r.preventDefault(),xr(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"}),nt.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5 border-t border-border px-2 py-2",children:nt.map(r=>e.jsx(Tt,{attachment:r,onRemove:nn},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:Ht,type:"file",accept:"image/*",className:"hidden",multiple:!0,onChange:r=>{r.target.files&&xr(r.target.files),r.target.value=""}}),e.jsxs(w.Popover,{children:[e.jsx(w.PopoverTrigger,{asChild:!0,children:e.jsx(w.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(k.Plus,{className:"h-3.5 w-3.5"})})}),e.jsx(w.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=Ht.current)==null?void 0:r.click()},children:[e.jsx($n,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Screenshot"]})})]}),e.jsxs(w.Select,{value:st,onValueChange:Hr,children:[e.jsx(w.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(w.SelectValue,{placeholder:"Model"})}),e.jsx(w.SelectContent,{align:"start",children:Ft.map(r=>e.jsx(w.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:Z||ee?e.jsxs(e.Fragment,{children:[e.jsx(w.Button,{type:"submit",size:"xs",variant:"outline",className:"gap-1.5",disabled:!Ie.trim(),children:"Queue"}),e.jsxs(w.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(Q.X,{className:"h-3 w-3"}),"Stop"]})]}):e.jsxs(w.Button,{type:"submit",size:"xs",className:"gap-1.5",disabled:!Ie.trim(),children:[e.jsx(k.Send,{className:"h-3 w-3"}),"Send"]})})]})]})]})]})}),e.jsx(k.ResizableHandle,{className:"w-px bg-border/60 transition-colors hover:bg-border"})]}):null,e.jsx(k.ResizablePanel,{className:"min-w-0",defaultSize:Re?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(w.Button,{type:"button",variant:"ghost",size:"xs",className:"-ml-1 gap-1.5 px-1.5 text-muted-foreground",title:Re?"Hide chat":"Show chat","aria-label":Re?"Hide chat":"Show chat",onClick:()=>Ir(r=>!r),children:Re?e.jsx(Mn,{className:"h-3.5 w-3.5"}):e.jsx(Tn,{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"&&ut&&e.jsxs("span",{className:`text-[10.5px] ${ut==="tailwind"?"text-emerald-700 dark:text-emerald-400":"text-amber-700 dark:text-amber-400"}`,children:["CSS: ",ut]}),Jt?e.jsx("span",{className:"min-w-0 truncate text-[11px] text-blue-700 dark:text-blue-400",children:Jt}):null,xt?e.jsx("span",{className:"min-w-0 truncate text-[11px] text-destructive",title:xt,children:xt}):ar?e.jsxs("span",{className:"min-w-0 truncate text-[11px] text-emerald-700 dark:text-emerald-400",children:["Published ",new Date(ar).toLocaleTimeString()]}):nr?e.jsxs("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:["Saved ",new Date(nr).toLocaleTimeString()]}):null,e.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[e.jsxs(w.Popover,{open:bt,onOpenChange:r=>{Ke(r),r&&vr()},children:[e.jsx(w.PopoverTrigger,{asChild:!0,children:e.jsxs(w.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",title:"Inspect the current Data App manifest",children:[cr?e.jsx(w.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(k.FileCode,{className:"h-3.5 w-3.5"}),"Manifest"]})}),e.jsxs(w.PopoverContent,{align:"end",sideOffset:6,className:"w-[520px] p-0",onInteractOutside:()=>Ke(!1),onEscapeKeyDown:()=>Ke(!1),children:[e.jsxs("div",{className:"flex h-10 items-center gap-2 border-b border-border px-3",children:[e.jsx(k.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(w.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",disabled:!wt,title:"Copy manifest JSON","aria-label":"Copy manifest JSON",onClick:()=>{var r;(r=navigator.clipboard)==null||r.writeText(wt)},children:e.jsx(k.Copy,{className:"h-3.5 w-3.5"})}),e.jsx(w.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",title:"Refresh manifest","aria-label":"Refresh manifest",onClick:()=>void vr(),children:e.jsx(k.RefreshCw,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"max-h-[520px] overflow-auto bg-muted/30 p-3",children:cr?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(w.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Reading current runtime manifest..."]}):dr?e.jsx("div",{className:"rounded-[5px] border border-destructive/30 bg-destructive/10 px-3 py-2 text-[12px] text-destructive",children:dr}):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:wt||"Open or refresh to inspect the manifest."})})]})]}),e.jsxs(k.AlertDialog,{children:[e.jsx(k.AlertDialogTrigger,{asChild:!0,children:e.jsxs(w.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",disabled:Z||ee,title:"Reset the app to a blank development template",children:[e.jsx(w.RotateCcw,{className:"h-3.5 w-3.5"}),"Reset app"]})}),e.jsxs(k.AlertDialogContent,{children:[e.jsxs(k.AlertDialogHeader,{children:[e.jsx(k.AlertDialogTitle,{children:"Reset this app?"}),e.jsx(k.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(k.AlertDialogFooter,{children:[e.jsx(k.AlertDialogCancel,{children:"Cancel"}),e.jsx(k.AlertDialogAction,{onClick:()=>void Xr(),children:"Reset app"})]})]})]}),e.jsxs(w.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",disabled:Z||ee||_e==="saving"||A!=="bridge"||!jt,title:"Save the current local source snapshot as a Semaphor draft",onClick:()=>void jr(),children:[_e==="saving"?e.jsx(w.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Cn.Save,{className:"h-3.5 w-3.5"}),"Save draft"]}),e.jsxs(w.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",disabled:Z||ee||_e==="saving"||rr==="publishing"||A!=="bridge"||!St,title:"Build, upload, and publish the current Data App",onClick:()=>void jn(),children:[rr==="publishing"?e.jsx(w.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Dn,{className:"h-3.5 w-3.5"}),"Publish"]}),A==="bridge"?e.jsxs(w.Button,{type:"button",variant:fe?"default":"ghost",size:"xs",disabled:_t,className:fe?"gap-1.5":"gap-1.5 text-muted-foreground",title:"Select an element in the preview and attach its DOM/React context",onClick:()=>fe?on():void an(),children:[_t?e.jsx(w.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Fn,{className:"h-3.5 w-3.5"}),fe?"Cancel inspect":"Inspect"]}):null,e.jsxs(w.Popover,{children:[e.jsx(w.PopoverTrigger,{asChild:!0,children:e.jsxs(w.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",children:[e.jsx(k.Settings2,{className:"h-3.5 w-3.5"}),"Runtime",A==="browser"&&ct.length>0?e.jsx("span",{className:"text-[10px] text-amber-600",children:"CSS fallback"}):null]})}),e.jsx(w.PopoverContent,{align:"end",sideOffset:6,className:"w-[380px] p-3",children:A==="bridge"?e.jsxs("div",{className:"space-y-2.5",children:[e.jsx($t,{label:"App Directory",value:g,placeholder:Bt,onChange:E}),e.jsx($t,{label:"App Local URL",value:m,onChange:R}),e.jsx($t,{label:"Bridge URL",value:v,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(w.Button,{type:"button",variant:"outline",size:"xs",className:"h-6 shrink-0 text-[10.5px]",disabled:Z||ee||De!=="ready",onClick:()=>void hr(),children:"Reset"})]}),ct[0]?e.jsx("div",{className:"mt-2 rounded-[5px] border border-border bg-muted/40 px-2 py-1.5 text-muted-foreground",children:ct[0]}):null,e.jsx(ls,{manifest:Ur})]})})]}),e.jsx(w.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(m),X(r=>r+1))},children:e.jsx(k.RefreshCw,{className:"h-3.5 w-3.5"})})]})]}),ie?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 ${ie.state==="failed"?"border-destructive/30 bg-destructive/10 text-destructive":ie.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:[ie.state==="running"?e.jsx(w.LoaderCircle,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin"}):ie.state==="done"?e.jsx(w.Check,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}):e.jsx(Q.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:ie.label}),ie.detail?e.jsx("div",{className:"mt-0.5 truncate opacity-80",children:ie.detail}):null]})]})}):null,(A==="browser"&&(De==="loading"||De==="failed")||Be&&!((Sr=Be.appBuilder)!=null&&Sr.hasOpenAiKey))&&e.jsxs("div",{className:"shrink-0 border-b border-border px-3 py-2",children:[A==="browser"&&De==="loading"&&e.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:"Loading the in-browser runtime…"}),A==="browser"&&De==="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.",Gt?e.jsx("pre",{className:"mt-1.5 whitespace-pre-wrap font-mono text-[10.5px] text-muted-foreground",children:Gt}):null]}),Be&&!((kr=Be.appBuilder)!=null&&kr.hasOpenAiKey)&&e.jsx("div",{className:"rounded-[5px] border border-destructive/30 bg-destructive/10 px-2 py-1.5 text-[11px] text-destructive",children:Be.error||"OPENAI_API_KEY is not configured."})]}),A==="browser"&&Vr.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(k.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:Zt.length})]}),e.jsx("div",{className:"max-h-72 shrink-0 overflow-y-auto border-b border-border p-2",children:e.jsx(is,{files:Zt,selectedPath:pt,onSelect:Qr})}),e.jsx("pre",{className:"min-h-0 flex-1 overflow-auto p-3 font-mono text-[11px] leading-relaxed text-muted-foreground",children:(ht==null?void 0:ht.contents)||"Select a file to inspect its source."})]}),e.jsx("iframe",{ref:it,className:"min-h-0 flex-1 bg-background",onLoad:()=>{fe&&window.setTimeout(()=>Ye("inspect-enable"),100)},src:A==="browser"?void 0:Nt,srcDoc:A==="browser"?Jr:void 0,title:"Data app preview"},A==="browser"?`browser-${be}`:Nt),ir?e.jsx(js,{artifact:ir,onClose:()=>Ue(null)}):null]})]})})]})}function $t({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 ps({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(w.Check,{className:"h-3 w-3"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(k.Copy,{className:"h-3 w-3"}),"Copy"]})})]}),e.jsx("div",{className:"overflow-x-auto bg-background",children:e.jsx(k.CodeHighlighter,{code:t,language:s||"tsx"})})]})}const hs=/(\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 fs(t,s){return t.split(hs).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(k.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 ms(t,s){return t.split(`
55
55
  `).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:fs(l,`${s}-${d}-${u}`)},u))]},`${s}-${d}`))}function xs(t){return t.split("```").map((s,a)=>{if(a%2===1){let d="",l=s;const u=s.indexOf(`
56
56
  `);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(ps,{code:l,lang:d},a)}return e.jsx("span",{children:ms(s,a)},a)})}function gs({turns:t,onDelete:s,onRemoveAttachment:a,onUpdatePrompt:d}){var x;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(tt.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:["· ",((x=t[0])==null?void 0:x.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,m)=>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 ",m+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(Tt,{attachment:R,onRemove:v=>a(N.id,v)},R.id))}):null]},N.id))}):null]})}function bs({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(Tt,{attachment:a},a.id))}):null]})}function Tt({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(k.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(Q.X,{className:"h-3 w-3"})}):null]});return t.type==="dom-selection"?e.jsxs(w.Popover,{children:[e.jsx(w.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(w.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 ws(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 ys({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"}),xs(t.content),(d=t.artifacts)==null?void 0:d.map(l=>l.type==="dataset_inspector"?e.jsx(vs,{artifact:l,onOpen:()=>s(l)},l.id):null)]})}function vs({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(k.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 js({artifact:t,onClose:s}){const[a,d]=p.useState(""),[l,u]=p.useState("all"),h=a.trim().toLowerCase(),x=t.fields.filter(m=>{var E,z;const R=(E=m.role)==null?void 0:E.toLowerCase(),v=(z=m.dataType)==null?void 0:z.toLowerCase(),B=l==="all"||l==="measures"&&(R==="measure"||R==="metric")||l==="dimensions"&&R==="dimension"||l==="dates"&&(R==="date"||v==="date"||v==="timestamp")||l==="identifiers"&&R==="identifier"||l==="calculated"&&m.source==="calculated",g=!h||[m.name,m.label,m.role,m.dataType].filter(L=>typeof L=="string").some(L=>L.toLowerCase().includes(h));return B&&g}),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(k.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(w.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(Q.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(tt.Search,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("input",{value:a,onChange:m=>d(m.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(m=>e.jsxs("button",{type:"button",onClick:()=>u(m.id),className:`rounded-[5px] px-2 py-1 text-[10.5px] ${l===m.id?"bg-foreground text-background":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[m.label," ",m.count]},m.id))})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-2",children:x.length>0?e.jsx("div",{className:"space-y-1",children:x.map(m=>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:m.label||m.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:m.name}),m.role?e.jsxs("span",{children:["· ",m.role]}):null,m.dataType?e.jsxs("span",{children:["· ",m.dataType]}):null,m.source==="calculated"?e.jsx("span",{children:"· calculated"}):null]})]},`${m.source}:${m.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 Ss({phase:t,detail:s,elapsedMs:a}){const d=Qn(t),l=s||Xn(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(w.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:Mt(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 ks({run:t,getStepDuration:s}){var m,R,v;const a=t.steps.filter(B=>B.state==="done").length,d=t.steps.length,l=(R=(m=t.result)==null?void 0:m.generationMeta)==null?void 0:R.durationMs,u=B=>B.id==="generate"&&typeof l=="number"?l:s(B),h=t.steps.reduce((B,g)=>B+u(g),0),x=t.status==="running",N=x?"running":t.result?t.result.ok?"passed":"failed":t.status;return e.jsxs("details",{open:x,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(tt.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 ${x?"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," ·"," ",Mt(h)]})]}),e.jsxs("div",{className:"space-y-2.5 border-t border-border/60 px-2.5 py-2",children:[x?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 g,E;return e.jsx(Ns,{duration:u(B),repairAttempts:(E=(g=t.result)==null?void 0:g.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"]})]}),(v=t.result.changedFiles)!=null&&v.length?e.jsxs("div",{children:["Changed ",t.result.changedFiles.join(", ")]}):null,e.jsx(ds,{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 Ns({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(As,{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," / ",Ee]}):e.jsx("span",{children:Mt(t)})})]})}function As({state:t}){return t==="done"?e.jsx(w.Check,{className:"h-3.5 w-3.5 text-emerald-600"}):t==="running"?e.jsx(w.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-blue-600"}):t==="blocked"?e.jsx(Q.X,{className:"h-3.5 w-3.5 text-destructive"}):e.jsx(k.Circle,{className:"h-2.5 w-2.5 fill-zinc-300 stroke-none"})}exports.DataAppBuilder=cs;
@@ -2,12 +2,12 @@ import { jsx as r, jsxs as c, Fragment as re } from "react/jsx-runtime";
2
2
  import * as Zn from "react";
3
3
  import { useContext as qn, useState as x, useRef as oe, useMemo as ze, useEffect as W, useCallback as Ot } from "react";
4
4
  import * as Xn from "react-dom/client";
5
- import { aK as ea, aL as ta, aM as Ir, aN as jr, aO as zr, aP as ra, aQ as Wr, aR as Hr, aS as Jr, aT as Vr, aU as _r, aV as Ur, aW as Kr, aX as na, aY as aa, aZ as oa, a_ as Ht, a$ as on, x as Gr, b0 as sa, b1 as Vt, b2 as sn, b3 as ia, b4 as la } from "../chunks/index-Dzz6jXSY.js";
6
- import { B as H, P as it, a as lt, b as dt, _ as da, $ as ca, a0 as ua, a1 as pa, a2 as ha, e as me, R as ma, d as _t } from "../chunks/switch-2bh3Hka1.js";
5
+ import { aK as ea, aL as ta, aM as Ir, aN as jr, aO as zr, aP as ra, aQ as Wr, aR as Hr, aS as Jr, aT as Vr, aU as _r, aV as Ur, aW as Kr, aX as na, aY as aa, aZ as oa, a_ as Ht, a$ as on, x as Gr, b0 as sa, b1 as Vt, b2 as sn, b3 as ia, b4 as la } from "../chunks/dashboard-5agU0G_D.js";
6
+ import { B as H, P as it, a as lt, b as dt, _ as da, $ as ca, a0 as ua, a1 as pa, a2 as ha, e as me, R as ma, d as _t } from "../chunks/code-editor-Bkk7s8hI.js";
7
7
  import { loadSemaphorBrowserRuntime as ot } from "../data-app-builder-browser-runtime/index.js";
8
- import { c as $e, X as Je } from "../chunks/x-CXDkqdur.js";
9
- import { S as fa } from "../chunks/save-DgMfP0j8.js";
10
- import { C as Ut, S as ga } from "../chunks/search-BHsQIWBV.js";
8
+ import { c as $e, X as Je } from "../chunks/index-xHCrHprY.js";
9
+ import { S as fa } from "../chunks/save-HCJjjzdX.js";
10
+ import { C as Ut, S as ga } from "../chunks/search-DHZCro8B.js";
11
11
  /**
12
12
  * @license lucide-react v0.453.0 - ISC
13
13
  *
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("../chunks/analyze-result-contract-DpDcImgk.js"),e=require("../chunks/update-policy-C1pmhLz9.js");exports.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION=a.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION;exports.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION=a.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION;exports.isSemaphorDataAppCodegenSummary=a.isSemaphorDataAppCodegenSummary;exports.validateSemaphorDataAppCodegenSummary=a.validateSemaphorDataAppCodegenSummary;exports.CODEGEN_SUMMARY_SCHEMA_VERSION=e.CODEGEN_SUMMARY_SCHEMA_VERSION;exports.CODEGEN_SUMMARY_VALIDATOR_VERSION=e.CODEGEN_SUMMARY_VALIDATOR_VERSION;exports.CONTRACT_MANIFEST_SCHEMA_VERSION=e.CONTRACT_MANIFEST_SCHEMA_VERSION;exports.GENERATED_CONTRACT_SCHEMA_VERSION=e.GENERATED_CONTRACT_SCHEMA_VERSION;exports.GENERATED_CONTRACT_TYPESCRIPT_FILES=e.GENERATED_CONTRACT_TYPESCRIPT_FILES;exports.REQUIRED_GENERATED_CONTRACT_FILES=e.REQUIRED_GENERATED_CONTRACT_FILES;exports.assertValidCodegenSummary=e.assertValidCodegenSummary;exports.buildSemaphorGeneratedActiveInput=e.buildSemaphorGeneratedActiveInput;exports.buildSemaphorGeneratedInputOptionIntent=e.buildSemaphorGeneratedInputOptionIntent;exports.buildSemaphorGeneratedViewExecutionRequest=e.buildSemaphorGeneratedViewExecutionRequest;exports.buildSemaphorGeneratedViewExecutionRequests=e.buildSemaphorGeneratedViewExecutionRequests;exports.evaluateSemaphorDataAppContractUpdatePolicy=e.evaluateSemaphorDataAppContractUpdatePolicy;exports.validateCodegenSummary=e.validateCodegenSummary;exports.validateSemaphorGeneratedContract=e.validateSemaphorGeneratedContract;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("../chunks/analyze-result-contract-ege_u6Nl.js"),e=require("../chunks/update-policy-BgONreNd.js");exports.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION=a.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_SCHEMA_VERSION;exports.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION=a.SEMAPHOR_DATA_APP_CODEGEN_SUMMARY_VALIDATOR_VERSION;exports.isSemaphorDataAppCodegenSummary=a.isSemaphorDataAppCodegenSummary;exports.validateSemaphorDataAppCodegenSummary=a.validateSemaphorDataAppCodegenSummary;exports.CODEGEN_SUMMARY_SCHEMA_VERSION=e.CODEGEN_SUMMARY_SCHEMA_VERSION;exports.CODEGEN_SUMMARY_VALIDATOR_VERSION=e.CODEGEN_SUMMARY_VALIDATOR_VERSION;exports.CONTRACT_MANIFEST_SCHEMA_VERSION=e.CONTRACT_MANIFEST_SCHEMA_VERSION;exports.GENERATED_CONTRACT_SCHEMA_VERSION=e.GENERATED_CONTRACT_SCHEMA_VERSION;exports.GENERATED_CONTRACT_TYPESCRIPT_FILES=e.GENERATED_CONTRACT_TYPESCRIPT_FILES;exports.REQUIRED_GENERATED_CONTRACT_FILES=e.REQUIRED_GENERATED_CONTRACT_FILES;exports.assertValidCodegenSummary=e.assertValidCodegenSummary;exports.buildSemaphorGeneratedActiveInput=e.buildSemaphorGeneratedActiveInput;exports.buildSemaphorGeneratedInputOptionIntent=e.buildSemaphorGeneratedInputOptionIntent;exports.buildSemaphorGeneratedViewExecutionRequest=e.buildSemaphorGeneratedViewExecutionRequest;exports.buildSemaphorGeneratedViewExecutionRequests=e.buildSemaphorGeneratedViewExecutionRequests;exports.evaluateSemaphorDataAppContractUpdatePolicy=e.evaluateSemaphorDataAppContractUpdatePolicy;exports.validateCodegenSummary=e.validateCodegenSummary;exports.validateSemaphorGeneratedContract=e.validateSemaphorGeneratedContract;
@@ -1,5 +1,5 @@
1
- import { S as E, a as S, i as A, v as t } from "../chunks/analyze-result-contract-D7pjjYPy.js";
2
- import { C as R, a as r, b as s, G as C, e as o, R as p, c as d, f as O, g as i, h as m, i as n, j as N, v as T, d as I } from "../chunks/update-policy-BCJc0oI5.js";
1
+ import { S as E, a as S, i as A, v as t } from "../chunks/analyze-result-contract-DnfF8kBb.js";
2
+ import { C as R, a as r, b as s, G as C, c as o, R as p, d, e as O, f as i, g as m, h as n, i as N, v as T, j as I } from "../chunks/update-policy-CY2k-pJP.js";
3
3
  export {
4
4
  R as CODEGEN_SUMMARY_SCHEMA_VERSION,
5
5
  r as CODEGEN_SUMMARY_VALIDATOR_VERSION,
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Y=require("../chunks/analyze-result-contract-DpDcImgk.js"),R=require("../chunks/update-policy-C1pmhLz9.js"),he=require("node:crypto"),Ce="src/semaphor/generated",H=`// Generated by Semaphor Agent Plugin. Do not hand-edit analytics wiring here.
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Y=require("../chunks/analyze-result-contract-ege_u6Nl.js"),R=require("../chunks/update-policy-BgONreNd.js"),he=require("node:crypto"),Ce="src/semaphor/generated",H=`// Generated by Semaphor Agent Plugin. Do not hand-edit analytics wiring here.
2
2
  // Regenerate from the accepted semaphor_plan_data_app codegenSummary when the plan changes.
3
3
  `;function Oe(e,n={}){R.assertValidCodegenSummary(e);const r=Me(e);if(r.views.length===0&&!n.allowEmpty)throw new Error("Contract generation produced zero executable views. Stop and ask for a different domain/goal or semantic model improvement; pass --allow-empty only for an explicit model-gap report.");const t=ke(r),o=Ne({contract:r,files:t,generatorName:n.generatorName||"react-semaphor/data-app-codegen/node",generatorVersion:n.generatorVersion||"unknown"}),a={...t,"contract.manifest.json":`${JSON.stringify(o,null,2)}
4
4
  `};return{schemaVersion:R.GENERATED_CONTRACT_SCHEMA_VERSION,files:a,manifest:o,contentHash:String(o.generatedContentHash||""),usageExample:Te(r),warnings:r.warnings,stats:{inputCount:r.inputs.length,executableViewCount:r.views.length,presentationViewCount:r.presentationViews.length,queryCount:r.views.length,optionQueryCount:r.optionQueries.length}}}function Me(e){var d,p,m,i,l,g,h,I,$,M,b,E;const n=[],r=[];for(const s of e.inputs){S(r,s.fieldRef);for(const V of s.bindings||[])S(r,V.fieldRef);S(r,(d=s.optionQuery)==null?void 0:d.valueFieldRef),S(r,(p=s.optionQuery)==null?void 0:p.labelFieldRef),S(r,(m=s.optionQuery)==null?void 0:m.filterFieldRef),D(r,(i=s.optionQuery)==null?void 0:i.spec)}for(const s of e.filterContracts){S(r,s.fieldRef),S(r,(l=s.optionQuery)==null?void 0:l.valueFieldRef),S(r,(g=s.optionQuery)==null?void 0:g.labelFieldRef),S(r,(h=s.optionQuery)==null?void 0:h.filterFieldRef),D(r,(I=s.optionQuery)==null?void 0:I.spec);for(const V of s.bindings||[])S(r,V.fieldRef)}for(const s of e.views){for(const V of s.fields||[])S(r,V);D(r,($=s.sdkSpec)==null?void 0:$.spec),D(r,s.visualSpec)}const t=e.implementationChecklist||{};for(const s of Object.values(t.bindingsByView||{}))for(const V of Array.isArray(s)?s:[])S(r,V.fieldRef),S(r,V.optionValueField),S(r,V.optionLabelField);for(const s of t.requiredInputOptions||[])S(r,s.visibleLabelField),S(r,s.optionValueField),S(r,s.runtimeFilterField);const o=pn([...e.sources.map(s=>({raw:s,key:Ie(s),aliases:Ve(s),name:""})),...r.map(s=>an(s)).filter(x)]);P(o,s=>{const V=F(s.raw);return j(s.raw.label||(V==null?void 0:V.datasetName)||(V==null?void 0:V.datasetId)||(V==null?void 0:V.name)||s.raw.kind||"source")});const a=ln(o),u=ne(r.filter(s=>s.name).map(s=>({raw:s,key:X(s),name:""})),s=>s.key);P(u,s=>j([s.raw.sourceKey?yn(s.raw.sourceKey):"",s.raw.aggregate?s.raw.aggregate.toLowerCase():"",s.raw.name].filter(Boolean).join("_")));const c=new Map(u.map(s=>[s.key,s.name])),w=e.inputs.map(s=>({raw:s,name:j(s.id||s.label||"input")}));P(w,s=>s.name);const f=w.filter(s=>!!s.raw.optionQuery).map(s=>({input:s,name:`${s.name}Options`,raw:s.raw.optionQuery}));P(f,s=>s.name);for(const s of f)un(s.raw.labelFieldRef,s.raw.valueFieldRef)&&dn(s.raw.valueFieldRef)&&n.push(`Input option query ${((M=s.raw.spec)==null?void 0:M.inputId)||s.input.raw.id||s.name} uses identifier field ${s.raw.valueFieldRef.name} as both label and value. It can execute, but the UI will show key values unless the semantic model exposes a human-readable label through a modeled relationship.`);const y=e.views.filter(s=>{var V,K;return!!((V=s.sdkSpec)!=null&&V.builder&&((K=s.sdkSpec)!=null&&K.spec))}).map(s=>({raw:s,name:j(s.id||s.title||"query")}));P(y,s=>s.name);const k=e.views.filter(s=>fe(s)&&!("sdkSpec"in s)).map(s=>sn(s));for(const s of e.views)(!("sdkSpec"in s)||!((b=s.sdkSpec)!=null&&b.builder)||!((E=s.sdkSpec)!=null&&E.spec))&&!fe(s)&&n.push(`Skipped view ${s.id||s.title||"unknown"} because it has no sdkSpec.`);return Ee({inputs:w,views:y,filterContracts:e.filterContracts}),{summary:e,title:e.title||"Semaphor Data App",sources:o,fields:u,inputs:w,optionQueries:f,views:y,presentationViews:k,filterContracts:e.filterContracts,checklist:t,sourceNameByKey:a,fieldNameByKey:c,warnings:n}}function Ee({inputs:e,views:n,filterContracts:r}){const t=new Set(e.map(a=>a.raw.id).filter(Boolean)),o=new Set(n.map(a=>a.raw.id).filter(Boolean));for(const[a,u]of r.entries()){if(!t.has(u.inputId))throw new Error(`filterContracts.${a}.inputId must reference a generated input.`);const c=new Set(u.appliesToViewIds||[]),w=new Set(u.notAppliedToViewIds||[]);for(const[f,y]of(u.appliesToViewIds||[]).entries())if(!o.has(y))throw new Error(`filterContracts.${a}.appliesToViewIds.${f} must reference an executable generated view.`);for(const[f,y]of(u.notAppliedToViewIds||[]).entries())if(!o.has(y))throw new Error(`filterContracts.${a}.notAppliedToViewIds.${f} must reference an executable generated view.`);for(const[f,y]of(u.bindings||[]).entries()){if(!o.has(y.viewId))throw new Error(`filterContracts.${a}.bindings.${f}.viewId must reference an executable generated view.`);if(!c.has(y.viewId))throw new Error(`filterContracts.${a}.bindings.${f}.viewId must be included in appliesToViewIds.`);if(w.has(y.viewId))throw new Error(`filterContracts.${a}.bindings.${f}.viewId must not be listed in notAppliedToViewIds.`)}}}function ke(e){return{"sources.ts":ve(e),"fields.ts":qe(e),"inputs.ts":De(e),"queries.ts":Pe(e),"bindings.ts":Le(e),"accessors.ts":Ye(e),"metadata.ts":We(e),"index.ts":Xe(),"USAGE.md":Ae(e)}}function Ne({contract:e,files:n,generatorName:r,generatorVersion:t}){return{schemaVersion:R.CONTRACT_MANIFEST_SCHEMA_VERSION,generatedContractSchemaVersion:R.GENERATED_CONTRACT_SCHEMA_VERSION,generator:{name:r,version:t},generatedContentHash:Ge(n),codegenSummaryValidatorVersion:R.CODEGEN_SUMMARY_VALIDATOR_VERSION,codegenSummaryHash:xe(e.summary),codegenSummary:e.summary}}function Ge(e){const n=he.createHash("sha256");for(const r of Object.keys(e).filter(t=>t.endsWith(".ts")).sort())n.update(r),n.update("\0"),n.update(e[r]),n.update("\0");return`sha256:${n.digest("hex")}`}function Ae(e){const n=["# Semaphor Generated Data App Contract","","Generated files in this directory are governed Semaphor analytics wiring. Do not hand-edit them.","","Use the app-facing exports from `index.ts`:","","- `queries`: generated governed query factories.","- `queryOptionsForView`: active-input wiring for each generated view.","- `rowsForView`: table/records row readers.","- `rowValuesForView`: friendly row object readers for chart/table views.","- `metricValuesForView`: friendly metric-value readers.","- `kpiPropsForView`: KPI component props derived from runtime metric results.","- `roleValuesForView`: canonical dimension/measure/date/id role readers.","- `appInputSpecs`: generated input/filter specs.","- `inputOptionQueries`: option-list query factories for generated inputs.","- `semaphorGeneratedContractMetadata`: generated view/input metadata and presentation-only views.","","Start with these exports before opening large generated internals such as `metadata.ts`.",""];return e.views.length>0&&(n.push("Generated executable views:"),e.views.forEach(r=>{n.push(`- \`${r.raw.id}\`: ${r.raw.title||r.name}`)}),n.push("")),e.inputs.length>0&&(n.push("Generated inputs:"),e.inputs.forEach(r=>{n.push(`- \`${r.raw.id}\`: ${r.raw.label||r.name}`)}),n.push("")),`${n.join(`
@@ -1,6 +1,6 @@
1
- import { S as Vn, a as Fn, i as bn, v as kn } from "../chunks/analyze-result-contract-D7pjjYPy.js";
2
- import { c as ke, G as fe, a as Re, b as Me } from "../chunks/update-policy-BCJc0oI5.js";
3
- import { C as Mn, e as Cn, R as On, f as xn, g as Gn, h as Nn, i as En, j as An, v as jn, d as vn } from "../chunks/update-policy-BCJc0oI5.js";
1
+ import { S as Vn, a as Fn, i as bn, v as kn } from "../chunks/analyze-result-contract-DnfF8kBb.js";
2
+ import { d as ke, G as fe, a as Re, b as Me } from "../chunks/update-policy-CY2k-pJP.js";
3
+ import { C as Mn, c as Cn, R as On, e as xn, f as Gn, g as Nn, h as En, i as An, v as jn, j as vn } from "../chunks/update-policy-CY2k-pJP.js";
4
4
  import { createHash as ye } from "node:crypto";
5
5
  const wn = "src/semaphor/generated", v = `// Generated by Semaphor Agent Plugin. Do not hand-edit analytics wiring here.
6
6
  // Regenerate from the accepted semaphor_plan_data_app codegenSummary when the plan changes.
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("../data-app-sdk-adapters/index.cjs"),i=require("react/jsx-runtime"),c=require("react"),ye=require("../chunks/analyze-result-contract-DpDcImgk.js"),se=require("../chunks/search-DNCejM7Z.js"),Ke=require("../chunks/x-B6ghREd2.js"),Mr=require("../chunks/validators-DMlVbd1p.js");function de(e,r,t={}){return{...t,name:e,role:r}}function Kr(e){return e}function Wr(e){return e}const _r={source:{semantic(e){return{...e,kind:"semantic"}},sql(e){return{...e,kind:"sql"}}},field:{measure(e,r){return de(e,"measure",r)},dimension(e,r){return de(e,"dimension",r)},date(e,r){return de(e,"date",r)},id(e,r){return de(e,"id",r)}},filter(e){return{...e,kind:"filter"}},bindInput(e,r){return{toAnalyticsInput(){const[t]=w.toSemaphorInputSnapshots([e]),n=w.toSemaphorInputBinding({...r,inputId:r.inputId||t.inputId});return{...t,inputId:n.inputId,...n.kind?{kind:n.kind}:{},...n.controlRole?{controlRole:n.controlRole}:{},...n.operator?{operator:n.operator}:{},...n.field?{field:n.field}:{},...n.relationshipHint?{relationshipHint:n.relationshipHint}:{}}}}},control(e){return{...e,kind:"control"}},sqlParam(e){return{...e,kind:"control",role:"sqlParam"}},derivedField(e){return{...e,kind:"derived_field",expressionLanguage:e.expressionLanguage||"semaphor_sql_template"}},metric(e){return{...e,queryKind:"metric"}},analysis(e){return{...e,queryKind:"analysis"}},records(e){return{...e,queryKind:"records"}},inputOptions(e){return{...e,queryKind:"inputOptions"}},sql(e){return{...e,queryKind:"sql"}},matrix(e){return{...e,queryKind:"matrix"}}},ie=10,Le=8;function We(e,r){const t=e==null?void 0:e.result;if(t)switch(t.kind){case"records":return te({title:"Records",rowNoun:"rows",records:t.records,columns:t.columns,rowCount:t.rowCount});case"sql":return te({title:"SQL Rows",rowNoun:"rows",records:t.records,columns:t.columns,rowCount:t.rowCount});case"inputOptions":return te({title:"Options",rowNoun:"options",records:t.options.slice(0,ie).map(n=>{var s;return{label:n.label,value:n.value,count:n.count,disambiguation:(s=n.disambiguation)==null?void 0:s.join(" / ")}}),columns:[{key:"label",label:"Label"},{key:"value",label:"Value"},{key:"count",label:"Count"},{key:"disambiguation",label:"Disambiguation"}],rowCount:t.rowCount??t.options.length});case"metric":return Nr(t,r);case"matrix":return te({title:"Matrix Cells",rowNoun:"cells",records:t.cells.slice(0,ie).map(n=>{const s=t.nodesById[n.rowId],o=n.columnId?t.nodesById[n.columnId]:void 0,u=t.measuresById[n.measureId];return{row:(s==null?void 0:s.label)||n.rowId,column:(o==null?void 0:o.label)||n.columnId||"Total",measure:(u==null?void 0:u.label)||n.measureId,value:n.formattedValue??n.value,role:n.role}}),columns:[{key:"row",label:"Row"},{key:"column",label:"Column"},{key:"measure",label:"Measure"},{key:"value",label:"Value"},{key:"role",label:"Role"}],rowCount:t.rowCount??t.cells.length});default:return Fr(t)}}function Nr(e,r){var o,u,p,d,f;const t=[{metric:"primaryValue",value:(r==null?void 0:r.primaryValue)??e.primaryValue}],n=(r==null?void 0:r.comparisonKind)??((o=e.comparison)==null?void 0:o.kind);return n&&t.push({metric:`${n} value`,value:(r==null?void 0:r.comparisonValue)??((u=e.comparison)==null?void 0:u.value)},{metric:"delta",value:(r==null?void 0:r.delta)??((p=e.comparison)==null?void 0:p.delta)},{metric:"deltaPercent",value:(r==null?void 0:r.deltaPercent)??((d=e.comparison)==null?void 0:d.deltaPercent)}),(((f=r==null?void 0:r.missingMeasures)==null?void 0:f.filter(Boolean))??[]).forEach(g=>{t.push({metric:`missing:${g}`,value:"missing"})}),Object.entries((r==null?void 0:r.measures)??{}).sort(([g],[m])=>g.localeCompare(m)).forEach(([g,m])=>{t.push({metric:`measure:${g}`,value:m})}),Object.entries((r==null?void 0:r.measureBindings)??{}).sort(([g],[m])=>g.localeCompare(m)).forEach(([g,m])=>{t.push({metric:`binding:${g}`,value:m})}),te({title:"Metric",rowNoun:"values",records:t,columns:[{key:"metric",label:"Metric"},{key:"value",label:"Value"}],rowCount:t.length})}function te({title:e,rowNoun:r,records:t,columns:n,rowCount:s}){const o=zr(n,t);if(!o.length)return;const u=s??t.length,p=t.slice(0,ie);return{title:e,summary:`${Hr(u)} ${r}`,columns:o.slice(0,Le),rows:p,truncatedRows:u>p.length,truncatedColumns:o.length>Le}}function zr(e,r){if(e!=null&&e.length)return e.filter(n=>n.key).map(n=>({key:n.key,label:n.label||n.key}));const t=new Set;return r.slice(0,ie).forEach(n=>{Object.keys(n).forEach(s=>t.add(s))}),[...t].map(n=>({key:n,label:n}))}function Fr(e){throw new Error(`Unhandled Semaphor result kind: ${pr(e)}`)}function Pr(e){return e===null?"null":e===void 0?"":typeof e=="string"?rr(e):typeof e=="number"||typeof e=="boolean"?String(e):rr(pr(e))}function Hr(e){return typeof e=="number"?e.toLocaleString():"-"}function pr(e){return JSON.stringify(e,null,2)??"undefined"}function rr(e){return e.length>80?`${e.slice(0,77)}...`:e}function he(e){return e.viewTitle||e.queryLabel||e.viewId||e.queryId}function Vr(e){if(e.label)return e.label;if(e.queryKind!=="inputOptions")return;const t=e.labelField.label||e.valueField.label||e.labelField.name||e.valueField.name||e.inputId;return`${Qr(t)} Options`}function Qr(e){return(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\bfilter\b/gi," ").replace(/\boptions?\b/gi," ").replace(/\bid\b/gi," ").replace(/\s+/g," ").trim()||e).split(" ").filter(Boolean).map(n=>n===n.toUpperCase()&&n.length>1?n:`${n.slice(0,1).toUpperCase()}${n.slice(1)}`).join(" ")}function _e(e){return e.flatMap(r=>{var g,m,v,y;const t=r.latestAttempt,n=t==null?void 0:t.executionResult,s=Se((g=n==null?void 0:n.validation)==null?void 0:g.warnings),o=Se((m=n==null?void 0:n.validation)==null?void 0:m.errors),u=Yr((v=n==null?void 0:n.coverage)==null?void 0:v.missingObligations),p=Se((y=n==null?void 0:n.coverage)==null?void 0:y.warnings),d=[],f=he(r);(t==null?void 0:t.status)==="error"&&d.push({trace:r,tone:"error",title:f,message:t.errorMessage||"Query attempt failed."});for(const h of r.clientWarnings)d.push({trace:r,tone:"warning",title:f,message:h});for(const h of s)d.push({trace:r,tone:"warning",title:f,...h});for(const h of o)d.push({trace:r,tone:"error",title:f,...h});for(const h of u)d.push({trace:r,tone:"warning",title:f,message:h});for(const h of p)d.push({trace:r,tone:"warning",title:f,...h});return d})}function Ur(e){return{traceId:e.trace.traceId,queryId:e.trace.queryId,viewId:e.trace.viewId,viewTitle:e.trace.viewTitle,queryLabel:e.trace.queryLabel,severity:e.tone,title:e.title,message:e.message,code:e.code,path:e.path}}function Gr(e,r){return e.filter(t=>t.trace.traceId===r.traceId).length}function Jr(e){const r=_e(e),t=e.filter(u=>{var p;return((p=u.latestAttempt)==null?void 0:p.status)==="error"}).length,n=e.filter(u=>{var p;return((p=u.latestAttempt)==null?void 0:p.status)==="loading"}).length,s=r.filter(u=>u.tone==="error").length,o=r.filter(u=>u.tone==="warning").length;return{total:e.length,failed:t,loading:n,errorCount:s,warningCount:o,issueCount:r.length,severity:t||s?"error":o?"warning":n?"loading":"ok"}}function Yr(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}function Se(e){return Array.isArray(e)?e.map(Xr).filter(r=>!!r):[]}function Xr(e){if(typeof e=="string")return{message:e};if(!e||typeof e!="object"||Array.isArray(e))return;const r=e,t=typeof r.message=="string"?r.message:"",n=typeof r.code=="string"?r.code:"",s=typeof r.path=="string"?r.path:"";return t&&n?{message:s?`${t} (${n}, ${s})`:`${t} (${n})`,code:n,...s?{path:s}:{}}:t?{message:t,...s?{path:s}:{}}:n?{message:n,code:n}:void 0}function Zr(e){if(!e.enabled)return e;const r=e.queries.map(gr);return{enabled:e.enabled,queries:r,issues:e.issues,getQuery:t=>r.find(n=>n.queryId===t),getQueries:t=>r.filter(n=>n.queryId===t)}}function tr(e){return e?gr(e):void 0}function gr(e){var r;return(r=e==null?void 0:e.latestAttempt)!=null&&r.executionResult?{...e,latestAttempt:{...e.latestAttempt,resultPreview:e.latestAttempt.resultPreview||We(e.latestAttempt.executionResult),executionResult:et(e.latestAttempt.executionResult)}}:e}function et(e){const{compiledQuery:r,intent:t,result:n,...s}=e,o=rt(s.metadata);return{...s,...o?{metadata:o}:{}}}function rt(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const r=e.dataAppDebug;if(!r||typeof r!="object"||Array.isArray(r))return e;const{compiledSql:t,...n}=r;return{...e,dataAppDebug:n}}function tt(e){return e==="relative"?{position:"relative",top:"auto",right:"auto",bottom:"auto",left:"auto"}:{top:e.startsWith("top")?20:"auto",right:e.endsWith("right")?20:"auto",bottom:e.startsWith("bottom")?20:"auto",left:e.endsWith("left")?20:"auto"}}function nt(e){return e==="error"?{borderColor:"var(--sd-error-border)",background:"var(--sd-error-bg)",color:"var(--sd-error-fg)"}:e==="warning"?{borderColor:"var(--sd-warning-border)",background:"var(--sd-warning-bg)",color:"var(--sd-warning-fg)"}:e==="loading"?{borderColor:"var(--sd-loading-border)",background:"var(--sd-loading-bg)",color:"var(--sd-loading-fg)"}:{borderColor:"var(--sd-success-border)",background:"var(--sd-success-bg)",color:"var(--sd-success-fg)"}}function st(e){return e==="right"?{top:16,right:16,bottom:16,left:"auto",width:"min(720px, calc(100vw - 32px))",height:"auto",borderRadius:6}:{top:"auto",right:16,bottom:16,left:16,width:"auto",height:"min(420px, 45vh)",borderRadius:6}}function it(e){return e==="right"?{gridTemplateColumns:"minmax(210px, 280px) minmax(0, 1fr)"}:{gridTemplateColumns:"minmax(260px, 340px) minmax(0, 1fr)"}}function ot(e){return{borderRight:"1px solid var(--sd-border)",borderBottom:0}}function mr(e){return e==="error"?{background:"var(--sd-error-dot)"}:e==="success"?{background:"var(--sd-success-dot)"}:e==="loading"?{background:"var(--sd-loading-dot)"}:{background:"var(--sd-idle-dot)"}}function at(e){return e==="error"?{borderColor:"var(--sd-error-border)",color:"var(--sd-error-fg)"}:e==="success"?{borderColor:"var(--sd-success-border)",color:"var(--sd-success-fg)"}:e==="loading"?{borderColor:"var(--sd-loading-border)",color:"var(--sd-loading-fg)"}:{borderColor:"var(--sd-border)",color:"var(--sd-fg-muted)"}}const nr="semaphor-devtools-stylesheet",T="semaphor-devtools",lt=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("../data-app-sdk-adapters/index.cjs"),i=require("react/jsx-runtime"),c=require("react"),ye=require("../chunks/analyze-result-contract-ege_u6Nl.js"),se=require("../chunks/search-Dcud9ajy.js"),Ke=require("../chunks/index-jSrCwPQz.js"),Mr=require("../chunks/validators-B4VMLX3_.js");function de(e,r,t={}){return{...t,name:e,role:r}}function Kr(e){return e}function Wr(e){return e}const _r={source:{semantic(e){return{...e,kind:"semantic"}},sql(e){return{...e,kind:"sql"}}},field:{measure(e,r){return de(e,"measure",r)},dimension(e,r){return de(e,"dimension",r)},date(e,r){return de(e,"date",r)},id(e,r){return de(e,"id",r)}},filter(e){return{...e,kind:"filter"}},bindInput(e,r){return{toAnalyticsInput(){const[t]=w.toSemaphorInputSnapshots([e]),n=w.toSemaphorInputBinding({...r,inputId:r.inputId||t.inputId});return{...t,inputId:n.inputId,...n.kind?{kind:n.kind}:{},...n.controlRole?{controlRole:n.controlRole}:{},...n.operator?{operator:n.operator}:{},...n.field?{field:n.field}:{},...n.relationshipHint?{relationshipHint:n.relationshipHint}:{}}}}},control(e){return{...e,kind:"control"}},sqlParam(e){return{...e,kind:"control",role:"sqlParam"}},derivedField(e){return{...e,kind:"derived_field",expressionLanguage:e.expressionLanguage||"semaphor_sql_template"}},metric(e){return{...e,queryKind:"metric"}},analysis(e){return{...e,queryKind:"analysis"}},records(e){return{...e,queryKind:"records"}},inputOptions(e){return{...e,queryKind:"inputOptions"}},sql(e){return{...e,queryKind:"sql"}},matrix(e){return{...e,queryKind:"matrix"}}},ie=10,Le=8;function We(e,r){const t=e==null?void 0:e.result;if(t)switch(t.kind){case"records":return te({title:"Records",rowNoun:"rows",records:t.records,columns:t.columns,rowCount:t.rowCount});case"sql":return te({title:"SQL Rows",rowNoun:"rows",records:t.records,columns:t.columns,rowCount:t.rowCount});case"inputOptions":return te({title:"Options",rowNoun:"options",records:t.options.slice(0,ie).map(n=>{var s;return{label:n.label,value:n.value,count:n.count,disambiguation:(s=n.disambiguation)==null?void 0:s.join(" / ")}}),columns:[{key:"label",label:"Label"},{key:"value",label:"Value"},{key:"count",label:"Count"},{key:"disambiguation",label:"Disambiguation"}],rowCount:t.rowCount??t.options.length});case"metric":return Nr(t,r);case"matrix":return te({title:"Matrix Cells",rowNoun:"cells",records:t.cells.slice(0,ie).map(n=>{const s=t.nodesById[n.rowId],o=n.columnId?t.nodesById[n.columnId]:void 0,u=t.measuresById[n.measureId];return{row:(s==null?void 0:s.label)||n.rowId,column:(o==null?void 0:o.label)||n.columnId||"Total",measure:(u==null?void 0:u.label)||n.measureId,value:n.formattedValue??n.value,role:n.role}}),columns:[{key:"row",label:"Row"},{key:"column",label:"Column"},{key:"measure",label:"Measure"},{key:"value",label:"Value"},{key:"role",label:"Role"}],rowCount:t.rowCount??t.cells.length});default:return Fr(t)}}function Nr(e,r){var o,u,p,d,f;const t=[{metric:"primaryValue",value:(r==null?void 0:r.primaryValue)??e.primaryValue}],n=(r==null?void 0:r.comparisonKind)??((o=e.comparison)==null?void 0:o.kind);return n&&t.push({metric:`${n} value`,value:(r==null?void 0:r.comparisonValue)??((u=e.comparison)==null?void 0:u.value)},{metric:"delta",value:(r==null?void 0:r.delta)??((p=e.comparison)==null?void 0:p.delta)},{metric:"deltaPercent",value:(r==null?void 0:r.deltaPercent)??((d=e.comparison)==null?void 0:d.deltaPercent)}),(((f=r==null?void 0:r.missingMeasures)==null?void 0:f.filter(Boolean))??[]).forEach(g=>{t.push({metric:`missing:${g}`,value:"missing"})}),Object.entries((r==null?void 0:r.measures)??{}).sort(([g],[m])=>g.localeCompare(m)).forEach(([g,m])=>{t.push({metric:`measure:${g}`,value:m})}),Object.entries((r==null?void 0:r.measureBindings)??{}).sort(([g],[m])=>g.localeCompare(m)).forEach(([g,m])=>{t.push({metric:`binding:${g}`,value:m})}),te({title:"Metric",rowNoun:"values",records:t,columns:[{key:"metric",label:"Metric"},{key:"value",label:"Value"}],rowCount:t.length})}function te({title:e,rowNoun:r,records:t,columns:n,rowCount:s}){const o=zr(n,t);if(!o.length)return;const u=s??t.length,p=t.slice(0,ie);return{title:e,summary:`${Hr(u)} ${r}`,columns:o.slice(0,Le),rows:p,truncatedRows:u>p.length,truncatedColumns:o.length>Le}}function zr(e,r){if(e!=null&&e.length)return e.filter(n=>n.key).map(n=>({key:n.key,label:n.label||n.key}));const t=new Set;return r.slice(0,ie).forEach(n=>{Object.keys(n).forEach(s=>t.add(s))}),[...t].map(n=>({key:n,label:n}))}function Fr(e){throw new Error(`Unhandled Semaphor result kind: ${pr(e)}`)}function Pr(e){return e===null?"null":e===void 0?"":typeof e=="string"?rr(e):typeof e=="number"||typeof e=="boolean"?String(e):rr(pr(e))}function Hr(e){return typeof e=="number"?e.toLocaleString():"-"}function pr(e){return JSON.stringify(e,null,2)??"undefined"}function rr(e){return e.length>80?`${e.slice(0,77)}...`:e}function he(e){return e.viewTitle||e.queryLabel||e.viewId||e.queryId}function Vr(e){if(e.label)return e.label;if(e.queryKind!=="inputOptions")return;const t=e.labelField.label||e.valueField.label||e.labelField.name||e.valueField.name||e.inputId;return`${Qr(t)} Options`}function Qr(e){return(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\bfilter\b/gi," ").replace(/\boptions?\b/gi," ").replace(/\bid\b/gi," ").replace(/\s+/g," ").trim()||e).split(" ").filter(Boolean).map(n=>n===n.toUpperCase()&&n.length>1?n:`${n.slice(0,1).toUpperCase()}${n.slice(1)}`).join(" ")}function _e(e){return e.flatMap(r=>{var g,m,v,y;const t=r.latestAttempt,n=t==null?void 0:t.executionResult,s=Se((g=n==null?void 0:n.validation)==null?void 0:g.warnings),o=Se((m=n==null?void 0:n.validation)==null?void 0:m.errors),u=Yr((v=n==null?void 0:n.coverage)==null?void 0:v.missingObligations),p=Se((y=n==null?void 0:n.coverage)==null?void 0:y.warnings),d=[],f=he(r);(t==null?void 0:t.status)==="error"&&d.push({trace:r,tone:"error",title:f,message:t.errorMessage||"Query attempt failed."});for(const h of r.clientWarnings)d.push({trace:r,tone:"warning",title:f,message:h});for(const h of s)d.push({trace:r,tone:"warning",title:f,...h});for(const h of o)d.push({trace:r,tone:"error",title:f,...h});for(const h of u)d.push({trace:r,tone:"warning",title:f,message:h});for(const h of p)d.push({trace:r,tone:"warning",title:f,...h});return d})}function Ur(e){return{traceId:e.trace.traceId,queryId:e.trace.queryId,viewId:e.trace.viewId,viewTitle:e.trace.viewTitle,queryLabel:e.trace.queryLabel,severity:e.tone,title:e.title,message:e.message,code:e.code,path:e.path}}function Gr(e,r){return e.filter(t=>t.trace.traceId===r.traceId).length}function Jr(e){const r=_e(e),t=e.filter(u=>{var p;return((p=u.latestAttempt)==null?void 0:p.status)==="error"}).length,n=e.filter(u=>{var p;return((p=u.latestAttempt)==null?void 0:p.status)==="loading"}).length,s=r.filter(u=>u.tone==="error").length,o=r.filter(u=>u.tone==="warning").length;return{total:e.length,failed:t,loading:n,errorCount:s,warningCount:o,issueCount:r.length,severity:t||s?"error":o?"warning":n?"loading":"ok"}}function Yr(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}function Se(e){return Array.isArray(e)?e.map(Xr).filter(r=>!!r):[]}function Xr(e){if(typeof e=="string")return{message:e};if(!e||typeof e!="object"||Array.isArray(e))return;const r=e,t=typeof r.message=="string"?r.message:"",n=typeof r.code=="string"?r.code:"",s=typeof r.path=="string"?r.path:"";return t&&n?{message:s?`${t} (${n}, ${s})`:`${t} (${n})`,code:n,...s?{path:s}:{}}:t?{message:t,...s?{path:s}:{}}:n?{message:n,code:n}:void 0}function Zr(e){if(!e.enabled)return e;const r=e.queries.map(gr);return{enabled:e.enabled,queries:r,issues:e.issues,getQuery:t=>r.find(n=>n.queryId===t),getQueries:t=>r.filter(n=>n.queryId===t)}}function tr(e){return e?gr(e):void 0}function gr(e){var r;return(r=e==null?void 0:e.latestAttempt)!=null&&r.executionResult?{...e,latestAttempt:{...e.latestAttempt,resultPreview:e.latestAttempt.resultPreview||We(e.latestAttempt.executionResult),executionResult:et(e.latestAttempt.executionResult)}}:e}function et(e){const{compiledQuery:r,intent:t,result:n,...s}=e,o=rt(s.metadata);return{...s,...o?{metadata:o}:{}}}function rt(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const r=e.dataAppDebug;if(!r||typeof r!="object"||Array.isArray(r))return e;const{compiledSql:t,...n}=r;return{...e,dataAppDebug:n}}function tt(e){return e==="relative"?{position:"relative",top:"auto",right:"auto",bottom:"auto",left:"auto"}:{top:e.startsWith("top")?20:"auto",right:e.endsWith("right")?20:"auto",bottom:e.startsWith("bottom")?20:"auto",left:e.endsWith("left")?20:"auto"}}function nt(e){return e==="error"?{borderColor:"var(--sd-error-border)",background:"var(--sd-error-bg)",color:"var(--sd-error-fg)"}:e==="warning"?{borderColor:"var(--sd-warning-border)",background:"var(--sd-warning-bg)",color:"var(--sd-warning-fg)"}:e==="loading"?{borderColor:"var(--sd-loading-border)",background:"var(--sd-loading-bg)",color:"var(--sd-loading-fg)"}:{borderColor:"var(--sd-success-border)",background:"var(--sd-success-bg)",color:"var(--sd-success-fg)"}}function st(e){return e==="right"?{top:16,right:16,bottom:16,left:"auto",width:"min(720px, calc(100vw - 32px))",height:"auto",borderRadius:6}:{top:"auto",right:16,bottom:16,left:16,width:"auto",height:"min(420px, 45vh)",borderRadius:6}}function it(e){return e==="right"?{gridTemplateColumns:"minmax(210px, 280px) minmax(0, 1fr)"}:{gridTemplateColumns:"minmax(260px, 340px) minmax(0, 1fr)"}}function ot(e){return{borderRight:"1px solid var(--sd-border)",borderBottom:0}}function mr(e){return e==="error"?{background:"var(--sd-error-dot)"}:e==="success"?{background:"var(--sd-success-dot)"}:e==="loading"?{background:"var(--sd-loading-dot)"}:{background:"var(--sd-idle-dot)"}}function at(e){return e==="error"?{borderColor:"var(--sd-error-border)",color:"var(--sd-error-fg)"}:e==="success"?{borderColor:"var(--sd-success-border)",color:"var(--sd-success-fg)"}:e==="loading"?{borderColor:"var(--sd-loading-border)",color:"var(--sd-loading-fg)"}:{borderColor:"var(--sd-border)",color:"var(--sd-fg-muted)"}}const nr="semaphor-devtools-stylesheet",T="semaphor-devtools",lt=`
2
2
  .${T} {
3
3
  --sd-bg: #ffffff;
4
4
  --sd-bg-muted: #fafafa;
@@ -1,11 +1,11 @@
1
1
  import { toSemaphorInputSnapshots as jr, toSemaphorInputBinding as Hr, toSemaphorActiveInputSnapshots as X, toSemaphorMatrixIntent as Pr, toSemaphorSqlIntent as Vr, toSemaphorInputOptionsIntent as Qr, toSemaphorRecordsIntent as Ur, toSemaphorAnalysisQueryOptions as Gr, toSemaphorAnalysisIntent as Jr, toSemaphorMetricIntent as Yr, hasSemaphorInputValue as ue, normalizeSemaphorInputOptions as hr, toSemaphorInputSpec as br } from "../data-app-sdk-adapters/index.js";
2
2
  import { jsxs as p, Fragment as vr, jsx as a } from "react/jsx-runtime";
3
- import { createContext as Ie, useContext as Q, useState as z, useRef as E, useEffect as B, useMemo as I, Fragment as Xr, useId as Sr, useCallback as D, useReducer as Zr } from "react";
4
- import { I as et, L as rt } from "../chunks/analyze-result-contract-D7pjjYPy.js";
5
- import { b as ao, M as lo } from "../chunks/analyze-result-contract-D7pjjYPy.js";
6
- import { M as tt, a as nt, S as it, E as ot, C as st } from "../chunks/search-BHsQIWBV.js";
7
- import { X as at, C as lt, j as dt } from "../chunks/x-CXDkqdur.js";
8
- import { b as ut } from "../chunks/validators-PXkij33j.js";
3
+ import { createContext as Ie, useContext as Q, useState as z, useRef as E, useEffect as B, useMemo as I, Fragment as Xr, useReducer as Zr, useId as Sr, useCallback as D } from "react";
4
+ import { d as et, m as rt } from "../chunks/analyze-result-contract-DnfF8kBb.js";
5
+ import { b as ao, E as lo } from "../chunks/analyze-result-contract-DnfF8kBb.js";
6
+ import { M as tt, a as nt, S as it, E as ot, C as st } from "../chunks/search-DHZCro8B.js";
7
+ import { X as at, C as lt, j as dt } from "../chunks/index-xHCrHprY.js";
8
+ import { v as ut } from "../chunks/validators-Cz-XuORM.js";
9
9
  function me(e, r, t = {}) {
10
10
  return {
11
11
  ...t,