@json-to-office/jto 0.1.0 → 0.2.0

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 (40) hide show
  1. package/README.md +20 -5
  2. package/dist/cli.js +234 -49
  3. package/dist/cli.js.map +1 -1
  4. package/dist/client/assets/HomePage-BuV1dGoc.js +99 -0
  5. package/dist/client/assets/HomePage-BuV1dGoc.js.map +1 -0
  6. package/dist/client/assets/JsonEditorPage-y7DXYaWc.js +3 -0
  7. package/dist/client/assets/JsonEditorPage-y7DXYaWc.js.map +1 -0
  8. package/dist/client/assets/MonacoPluginProvider-B4-PgJ0r.js +3 -0
  9. package/dist/client/assets/MonacoPluginProvider-B4-PgJ0r.js.map +1 -0
  10. package/dist/client/assets/{button-B5W5GwSc.js → button-Bf6x7Zjh.js} +2 -2
  11. package/dist/client/assets/{button-B5W5GwSc.js.map → button-Bf6x7Zjh.js.map} +1 -1
  12. package/dist/client/assets/{editor-CH_tiHyn.js → editor-Bwuq290w.js} +2 -2
  13. package/dist/client/assets/{editor-CH_tiHyn.js.map → editor-Bwuq290w.js.map} +1 -1
  14. package/dist/client/assets/editor-monaco-json-BrfKPhHP.js +6 -0
  15. package/dist/client/assets/{editor-monaco-json-8I2epq6g.js.map → editor-monaco-json-BrfKPhHP.js.map} +1 -1
  16. package/dist/client/assets/index-Dmrqj1a7.css +1 -0
  17. package/dist/client/assets/index-uE8YOnrS.js +3 -0
  18. package/dist/client/assets/index-uE8YOnrS.js.map +1 -0
  19. package/dist/client/assets/preview-kcqt_5hb.js +3 -0
  20. package/dist/client/assets/{preview-CJlTPgks.js.map → preview-kcqt_5hb.js.map} +1 -1
  21. package/dist/client/assets/{state-vendor-CAMVKh-F.js → state-vendor-DypmJYNT.js} +2 -2
  22. package/dist/client/assets/{state-vendor-CAMVKh-F.js.map → state-vendor-DypmJYNT.js.map} +1 -1
  23. package/dist/client/assets/{ui-vendor-C6DsfOoA.js → ui-vendor-BFdEgxEg.js} +2 -2
  24. package/dist/client/assets/{ui-vendor-C6DsfOoA.js.map → ui-vendor-BFdEgxEg.js.map} +1 -1
  25. package/dist/client/index.html +3 -4
  26. package/dist/index.d.ts +8 -3
  27. package/dist/index.js +110 -19
  28. package/dist/index.js.map +1 -1
  29. package/package.json +6 -6
  30. package/dist/client/assets/HomePage-CGK1cPFp.js +0 -99
  31. package/dist/client/assets/HomePage-CGK1cPFp.js.map +0 -1
  32. package/dist/client/assets/JsonEditorPage-DKaFqYpM.js +0 -3
  33. package/dist/client/assets/JsonEditorPage-DKaFqYpM.js.map +0 -1
  34. package/dist/client/assets/editor-monaco-json-8I2epq6g.js +0 -6
  35. package/dist/client/assets/index-B9dV-vCI.css +0 -1
  36. package/dist/client/assets/index-DactvF4v.js +0 -3
  37. package/dist/client/assets/index-DactvF4v.js.map +0 -1
  38. package/dist/client/assets/preview-CJlTPgks.js +0 -3
  39. package/dist/client/assets/settings-store-provider-DuCKtwqs.js +0 -2
  40. package/dist/client/assets/settings-store-provider-DuCKtwqs.js.map +0 -1
@@ -1,3 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/docx-preview-CUjVWdSJ.js","assets/react-vendor-DhdcN9D5.js","assets/radix-ui-CXavUarI.js","assets/query-vendor-UL64zsGL.js"])))=>i.map(i=>d[i]);
2
- import{j as e}from"./query-vendor-UL64zsGL.js";import{a as L,r as d,ar as H,as as re}from"./react-vendor-DhdcN9D5.js";import{S as F,c as S,h as W,F as C,_ as ae,j as ne,A as q}from"./index-DactvF4v.js";import{S as E,B as ie,P as oe,b as ce,D as le,c as de,d as me,e as ue}from"./HomePage-CGK1cPFp.js";import{e as xe,T as $,I as fe}from"./ui-vendor-C6DsfOoA.js";import{c as B,b as he,u as G}from"./settings-store-provider-DuCKtwqs.js";import"./radix-ui-CXavUarI.js";import"./monaco-editor-DzeBDgmk.js";import"./state-vendor-CAMVKh-F.js";import"./button-B5W5GwSc.js";function pe({className:r,currentStage:t="parsing",message:a}){const n=["parsing","building","rendering","finalizing"],s={parsing:"Validating JSON",building:"Building structure",rendering:"Rendering content",finalizing:"Finalizing document"},c=n.indexOf(t);return e.jsxs("div",{className:S("p-6 space-y-4",r),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(F,{size:"md"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Generating Document"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a||`${s[t]}...`})]})]}),e.jsx("div",{className:"space-y-3",children:n.map((i,o)=>{const l=o===c,u=o<c;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:S(l?"text-primary font-medium":u?"text-muted-foreground":"text-muted-foreground/60"),children:s[i]}),e.jsx("span",{className:"text-muted-foreground",children:u?"✓":l?"...":"○"})]}),e.jsx("div",{className:"w-full bg-secondary rounded-full h-1.5",children:e.jsx("div",{className:S("h-1.5 rounded-full transition-all duration-300",u?"bg-green-500":l?"bg-primary animate-pulse":"bg-transparent"),style:{width:u||l?"100%":"0%"}})})]},i)})})]})}function ge({renderingLibrary:r,className:t}){const a=c=>{switch(c){case"LibreOffice":return{name:"LibreOffice",description:"Converting PPTX to PDF locally..."};case"Office":return{name:"Microsoft Office",description:"Uploading file and loading Office viewer..."};case"Docs":return{name:"Google Docs",description:"Uploading file and loading Docs viewer..."};default:return{name:"Default",description:"Processing document..."}}},{name:n,description:s}=a(r);return e.jsxs("div",{className:S("flex flex-col items-center justify-center h-full p-8 space-y-4",t),children:[e.jsx(F,{size:"lg"}),e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Rendering Preview"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Using ",n," renderer"]}),e.jsx("p",{className:"text-xs text-muted-foreground/80",children:s})]}),e.jsxs("div",{className:"w-full max-w-md space-y-3",children:[e.jsx(E,{className:"h-16 w-full"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(E,{className:"h-4 w-full"}),e.jsx(E,{className:"h-4 w-3/4"}),e.jsx(E,{className:"h-4 w-1/2"})]}),e.jsx(E,{className:"h-12 w-full"})]})]})}const J=L.forwardRef(({isLoading:r,iframeSrc:t,iframeSrcDoc:a,isGenerating:n,generationProgress:s},c)=>{const[i,o]=d.useState(!1);d.useEffect(()=>{o(!1)},[t,a]);const l=()=>{o(!0)},u=()=>{console.warn("Iframe failed to load content"),o(!1)},g=a?"allow-scripts allow-popups allow-forms":void 0,h=!!(t||a);return n&&!h?e.jsx("div",{className:"grow",children:e.jsx(pe,{currentStage:s==null?void 0:s.stage,message:s==null?void 0:s.message})}):r&&!h?e.jsx("div",{className:"grow",children:e.jsx(ge,{renderingLibrary:"LibreOffice"})}):h?e.jsxs("div",{className:"h-full w-full relative bg-white",children:[!i&&e.jsx("div",{className:"absolute inset-0 bg-muted/80 flex items-center justify-center z-10",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-foreground mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading preview..."})]})}),(n||r)&&e.jsx("div",{className:"absolute inset-0 bg-background/60 backdrop-blur-[2px] flex items-center justify-center z-20 transition-opacity duration-200",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(F,{size:"lg"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n?"Generating...":"Rendering..."})]})}),e.jsx("iframe",{ref:c,className:"w-full h-full border-0",style:{backgroundColor:"white",opacity:i?1:0,transition:"opacity 0.2s ease-in-out"},src:t,srcDoc:a,onLoad:l,onError:u,sandbox:g,title:"Document preview","aria-label":`Preview of rendered ${W.toLowerCase()}`},a?"srcdoc":"src")]}):null});J.displayName="PreviewFrame";const be=L.memo(J);function je({warnings:r,className:t}){const[a,n]=L.useState(!1);return!r||r.length===0?null:e.jsxs("div",{className:t,children:[e.jsxs("button",{type:"button",onClick:()=>n(!a),className:"flex w-full items-center gap-2 rounded-md border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-950/50 px-3 py-1.5 text-left transition-colors hover:bg-amber-100 dark:hover:bg-amber-900/50",children:[e.jsx(xe,{className:`h-3.5 w-3.5 text-amber-600 dark:text-amber-400 transition-transform flex-shrink-0 ${a?"rotate-90":""}`}),e.jsx($,{className:"h-3.5 w-3.5 text-amber-500 flex-shrink-0"}),e.jsxs("span",{className:"text-xs font-medium text-amber-700 dark:text-amber-300",children:[r.length," warning",r.length!==1?"s":""]})]}),a&&e.jsx("div",{className:"mt-1.5 space-y-1.5",children:r.map((s,c)=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-amber-100 dark:border-amber-900 bg-white dark:bg-amber-950/30 px-3 py-2",children:[s.severity==="info"?e.jsx(fe,{className:"h-3.5 w-3.5 mt-0.5 text-blue-500 flex-shrink-0"}):e.jsx($,{className:"h-3.5 w-3.5 mt-0.5 text-amber-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("code",{className:"text-[11px] font-medium text-amber-700 dark:text-amber-300 bg-amber-50 dark:bg-amber-900/40 px-1 py-0.5 rounded",children:s.component}),s.severity==="info"&&e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-blue-500 font-medium",children:"info"})]}),e.jsx("p",{className:"mt-0.5 text-xs text-gray-600 dark:text-gray-400 leading-relaxed",children:s.message}),s.context&&Object.keys(s.context).length>0&&e.jsxs("details",{className:"mt-1.5",children:[e.jsx("summary",{className:"text-[11px] text-gray-400 dark:text-gray-500 cursor-pointer hover:text-gray-600 dark:hover:text-gray-300",children:"Context"}),e.jsx("pre",{className:"mt-1 text-[11px] bg-gray-50 dark:bg-gray-900/50 p-1.5 rounded overflow-x-auto text-gray-600 dark:text-gray-400",children:JSON.stringify(s.context,null,2)})]})]})]},c))})]})}async function we(r){const t=await ae(()=>import("./docx-preview-CUjVWdSJ.js"),__vite__mapDeps([0,1,2,3])),a=document.createElement("body"),n=document.createElement("head"),s=t.renderAsync(r,a,n,{inWrapper:!0}),c=new Promise((l,u)=>{setTimeout(()=>{u(new Error("DocxJS renderAsync timed out after 10 seconds"))},1e4)});await Promise.race([s,c]);const i=document.createElement("link");i.rel="stylesheet",i.href=`${ne.basePath}/css/preview/docxjs.css`,n.appendChild(i);const o=document.createElement("html");return o.appendChild(n),o.appendChild(a),{iframeSrcDoc:o.outerHTML}}async function ve(r,t){const a=new FormData,n=C==="pptx"?".pptx":".docx";a.append("file",t,`${r}${n}`);const s=await fetch(q.preview.libreoffice,{method:"POST",body:a});if(!s.ok){let o=`LibreOffice preview failed (${s.status})`;try{const l=await s.json();l&&typeof l=="object"&&typeof l.error=="string"&&(o=l.error)}catch{}throw new Error(o)}const c=await s.blob();if(!c.size)throw new Error("LibreOffice preview returned an empty PDF");const i=URL.createObjectURL(c);return{iframeSrc:i,cleanup:()=>URL.revokeObjectURL(i)}}async function Ne(r,t,a=C==="docx"?"docxjs":"LibreOffice",n){try{if(!t||t.size===0)throw new Error("Invalid or empty document blob");let s;return C==="docx"&&a==="docxjs"?s=await we(t):s=await ve(r,t),{status:"success",name:r,payload:s}}catch(s){const c=s instanceof Error?s.message:String(s);return{status:"error",name:r,payload:new Error(c)}}}const I=d.forwardRef(({className:r,value:t,...a},n)=>e.jsx(H,{ref:n,className:S("relative h-4 w-full overflow-hidden rounded-full bg-secondary",r),...a,children:e.jsx(re,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));I.displayName=H.displayName;function K(r){if(r===0)return"0 B";const t=1024,a=["B","KB","MB","GB"],n=Math.floor(Math.log(r)/Math.log(t));return parseFloat((r/Math.pow(t,n)).toFixed(2))+" "+a[n]}function ye(){const[r,t]=d.useState(null),[a,n]=d.useState(!0),[s,c]=d.useState(null);if(d.useEffect(()=>{const l=new AbortController,u=async()=>{try{const f=await fetch(q.cacheStats,{signal:l.signal});if(!f.ok)throw new Error("Failed to fetch cache stats");const w=await f.json();l.signal.aborted||(t(w.data),c(null))}catch(f){l.signal.aborted||(f instanceof Error&&f.name!=="AbortError"?c(f.message):(!(f instanceof Error)||f.name!=="AbortError")&&c("Failed to load cache stats"))}finally{l.signal.aborted||n(!1)}};u();const g=setInterval(u,5e3),h=()=>u();return window.addEventListener("cache:cleared",h),()=>{l.abort(),clearInterval(g),window.removeEventListener("cache:cleared",h)}},[]),a)return e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})});if(s)return e.jsxs("div",{className:"text-destructive p-4",children:["Error loading cache metrics: ",s]});if(!r)return null;const{document:i}=r,o=i.hitRate*100;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Hit Rate"})," ",e.jsxs("span",{className:"font-semibold text-base",children:[o.toFixed(1),"%"]}),e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",i.hits," hits / ",i.misses," misses)"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Size"})," ",e.jsx("span",{className:"font-semibold",children:K(i.size)}),e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",i.itemCount," items)"]})]}),e.jsx(ie,{variant:i.enabled?"default":"secondary",children:i.enabled?"Enabled":"Disabled"})]}),e.jsx(I,{value:o,className:"h-2","aria-label":"Cache hit rate"}),C==="docx"&&r.components&&e.jsx(Ee,{data:r.components})]})}function Ee({data:r}){return r.componentStats.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Module Breakdown"}),e.jsx("div",{className:"space-y-1",children:r.componentStats.map(t=>{const a=(t.hitRate||0)*100,n=t.totalRequests||t.hits+t.misses,s=t.memoryUsage||t.entries*t.avgSize||0;return e.jsxs("div",{className:"px-3 py-1.5 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"font-medium",children:t.type}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[a.toFixed(0),"% hit"]}),e.jsxs("span",{children:[n," req"]}),e.jsx("span",{children:K(s)})]})]}),e.jsx(I,{value:a,className:"h-1.5"})]},t.type)})})]})}const Se=d.memo(function({editTimestamp:t,debounceMs:a}){const[n,s]=d.useState(()=>Math.max(0,t+a-Date.now()));if(d.useEffect(()=>{const o=()=>{const u=Math.max(0,t+a-Date.now());s(u),u<=0&&clearInterval(l)};o();const l=setInterval(o,100);return()=>clearInterval(l)},[t,a]),n<=0)return null;const c=(n/1e3).toFixed(1),i=Math.min(100,n/a*100);return e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-amber-600 dark:text-amber-400 tabular-nums",children:[e.jsx("span",{className:"h-1 rounded-full bg-amber-500/60 transition-[width] duration-100",style:{width:`${Math.round(i*.4)}px`}}),c,"s"]})});function Ie(){var U,_;const{autoReload:r,renderingLibrary:t,saveDocumentDebounceWait:a,setSettings:n}=B(m=>m),{name:s,text:c,blob:i,isGenerating:o,generationProgress:l,globalError:u,cacheStatus:g,cacheHitRate:h,warnings:f,isRendering:w,isPreviewStale:V,editSequence:X,lastBuiltSequence:Q,editTimestamp:T,setOutput:j}=he(m=>m),b=G(m=>m.activeTab),A=G(m=>m.documentTypes),[v,Y]=d.useState(void 0),[Z,ee]=d.useState(void 0),[se,D]=d.useState(!1),z=L.useRef(null),R=d.useRef(null),M=d.useRef(!1),k=d.useCallback(()=>{R.current&&(R.current(),R.current=null)},[]),N=d.useCallback(async(m,x)=>{j({isRendering:!0,isPreviewStale:!1,globalError:void 0});try{const{status:y,payload:p}=await Ne(m,x,t);if(y!=="success")throw p instanceof Error?p:new Error(String(p));k(),Y(p.iframeSrc||void 0),ee(p.iframeSrcDoc||void 0),R.current=p.cleanup||null}catch(y){const p=y instanceof Error?y.message:String(y);let O=p;p.includes("Failed to fetch")?O="Network error: Unable to load required resources. Check if the server is running properly.":p.includes("timeout")&&(O="Render timeout: The rendering process took too long."),j({globalError:O})}finally{j({isRendering:!1})}},[j,k,t]),te=d.useRef({name:s,blob:i,doRender:N});d.useEffect(()=>{te.current={name:s,blob:i,doRender:N}});const P=d.useCallback(async()=>{M.current=!0,window.dispatchEvent(new CustomEvent("preview:flushAndBuild"))},[]);return d.useEffect(()=>{i&&s&&r&&t==="docxjs"?N(s,i):i&&s&&M.current?(M.current=!1,N(s,i)):i&&s&&j({isPreviewStale:!0})},[i,s,r,t,N,j]),d.useEffect(()=>()=>{k()},[k]),d.useEffect(()=>{const m=()=>P(),x=()=>D(!0);return window.addEventListener("preview:manualRender",m),window.addEventListener("preview:showCacheMetrics",x),()=>{window.removeEventListener("preview:manualRender",m),window.removeEventListener("preview:showCacheMetrics",x)}},[P]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex h-full flex-col",children:[B&&((_=(U=B).getState)==null?void 0:_.call(U).useGlobalPreviewHeader)===!1&&e.jsx(oe,{iframeRef:z,displayReloadButton:!!v&&!((v==null?void 0:v.startsWith("blob:"))??!1),name:(s==null?void 0:s.trim())||"Preview",blob:i,autoReload:r,onToggleAutoReload:()=>n({autoReload:!r}),onManualRender:P,isGenerating:o,isRendering:w,onShowCacheMetrics:()=>D(!0),documentText:c,warnings:f,renderingLibrary:t,setRenderingLibrary:m=>n({renderingLibrary:m})}),e.jsx(ce,{}),(()=>{const m=(X??0)>(Q??0),x=(V||m)&&!o&&!w;return(g&&g!=="UNKNOWN"||x)&&e.jsxs("div",{className:`px-3 py-1.5 flex items-center justify-between border-b overflow-hidden ${x?"bg-amber-500/10 border-amber-500/30":"bg-muted/30"}`,children:[e.jsx("div",{className:"flex items-center gap-2 min-w-0 truncate",children:g==="HIT"&&!x?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-green-500 flex-shrink-0"}),e.jsx("span",{className:"text-xs text-muted-foreground truncate",children:"Cached"})]}):g==="MISS"&&!x?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-orange-500 flex-shrink-0"}),e.jsxs("span",{className:"text-xs text-muted-foreground truncate",children:["Fresh ",W.toLowerCase()]})]}):x?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-amber-500 flex-shrink-0"}),e.jsx("span",{className:"text-xs text-amber-600 dark:text-amber-400 truncate",children:"Outdated — click Run"}),T&&m&&!o&&r&&t==="docxjs"&&e.jsx(Se,{editTimestamp:T,debounceMs:a+200})]}):null}),!x&&h&&h!=="0.0%"&&e.jsxs("span",{className:"text-xs text-muted-foreground flex-shrink-0 ml-2",children:[h," hit rate"]})]})})(),e.jsx(je,{warnings:f,className:"mx-3 my-2"}),u&&!o?e.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md rounded-lg border border-red-400/50 bg-red-400/10 px-4 py-3 text-sm text-red-400",children:[e.jsx("p",{className:"font-medium mb-1",children:"Generation failed"}),e.jsx("p",{className:"text-xs text-red-400/80 break-words",children:u})]})}):e.jsx(be,{ref:z,isLoading:!!w,iframeSrc:v,iframeSrcDoc:Z,isGenerating:(()=>{const m=r&&t==="docxjs",x=b&&s&&b!==s&&A[b]!=="application/json+theme";return!!o||!!(m&&x)})(),generationProgress:(()=>{const m=r&&t==="docxjs",x=b&&s&&b!==s&&A[b]!=="application/json+theme";return m&&x&&!o?{stage:"parsing",message:`Building preview for ${b}...`}:l})()})]}),e.jsx(le,{open:se,onOpenChange:D,children:e.jsxs(de,{className:"max-w-2xl",children:[e.jsx(me,{children:e.jsx(ue,{children:"Cache Performance"})}),e.jsx(ye,{})]})})]})}export{Ie as Preview};
3
- //# sourceMappingURL=preview-CJlTPgks.js.map
@@ -1,2 +0,0 @@
1
- var F=Object.defineProperty;var G=(r,e,t)=>e in r?F(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var x=(r,e,t)=>G(r,typeof e!="symbol"?e+"":e,t);import{j as f}from"./query-vendor-UL64zsGL.js";import{r as a}from"./react-vendor-DhdcN9D5.js";import{a as l,d as p,p as g,b as C,u as h}from"./state-vendor-CAMVKh-F.js";import{F as J}from"./index-DactvF4v.js";function v(r){return new Promise((e,t)=>{r.oncomplete=r.onsuccess=()=>e(r.result),r.onabort=r.onerror=()=>t(r.error)})}function q(r,e){let t;const n=()=>{if(t)return t;const o=indexedDB.open(r);return o.onupgradeneeded=()=>o.result.createObjectStore(e),t=v(o),t.then(s=>{s.onclose=()=>t=void 0},()=>{}),t};return(o,s)=>n().then(i=>s(i.transaction(e,o).objectStore(e)))}let T;function y(){return T||(T=q("keyval-store","keyval")),T}function z(r,e=y()){return e("readonly",t=>v(t.get(r)))}function $(r,e,t=y()){return t("readwrite",n=>(n.put(e,r),v(n.transaction)))}function H(r,e=y()){return e("readwrite",t=>(t.delete(r),v(t.transaction)))}const O={getItem:async r=>await z(r)??null,setItem:async(r,e)=>{await $(r,e)},removeItem:async r=>{await H(r)}},U=3,E=()=>({documents:[],openTabs:[],activeTab:"",buildErrors:{},documentTypes:{},pendingDiffs:{},acceptedApplyIds:[]}),V={...E()},W=(r=V)=>l()(p(g(e=>({...r,createDocument:(t,n)=>e(o=>{if(o.documents.findIndex(i=>i.name===t)===-1){let i="application/json+report";if(t.toLowerCase().includes("theme")||t.toLowerCase().includes(".theme."))i="application/json+theme";else try{const u=JSON.parse(n);u.colors&&u.fonts&&u.styles&&(i="application/json+theme")}catch{}const c={name:t,type:"application/json",text:n,mtime:new Date,ctime:new Date,atime:new Date};return{documents:[...o.documents,c],documentTypes:{...o.documentTypes,[t]:i}}}return o}),deleteDocument:t=>e(n=>{const o={...n.documentTypes};return delete o[t],{documents:n.documents.filter(s=>s.name!==t),documentTypes:o,pendingDiffs:Object.fromEntries(Object.entries(n.pendingDiffs).filter(([s])=>s!==t))}}),saveDocument:(t,n)=>e(o=>{const s=o.documents.findIndex(c=>c.name===t);return s===-1||o.documents[s].text===n?o:{documents:o.documents.map((c,u)=>u===s?{...c,text:n,mtime:new Date}:c)}}),renameDocument:(t,n)=>e(o=>{const s=o.documents.findIndex(u=>u.name===t);if(s===-1)return o;const i=o.documents.map((u,d)=>d===s?{...u,name:n,ctime:new Date}:u),c=o.documentTypes[t];if(c){const u={...o.documentTypes};return delete u[t],u[n]=c,{documents:i,documentTypes:u}}return{documents:i}}),openDocument:t=>e(n=>{const o=n.documents.findIndex(c=>c.name===t);if(o===-1)return n;const s=n.documents.map((c,u)=>u===o?{...c,atime:new Date}:c);let i=n.openTabs;return i.includes(t)||(i=i.length>=U?[...i.slice(1),t]:[...i,t]),{documents:s,openTabs:i,activeTab:t}}),closeDocument:t=>e(n=>{const o=n.openTabs.indexOf(t);if(o===-1)return n;const s=n.openTabs.filter(c=>c!==t);let i=n.activeTab;return i===t&&(s.length?i=o===0?s[0]:s[o-1]:i=""),{openTabs:s,activeTab:i}}),setActiveTab:t=>e({activeTab:t}),setBuildError:(t,n)=>e(o=>{if(o.buildErrors[t]===n)return o;const s={...o.buildErrors};return n?s[t]=n:delete s[t],{buildErrors:s}}),setPendingDiff:(t,n,o,s)=>e(i=>({pendingDiffs:{...i.pendingDiffs,[t]:{original:n,modified:o,applyId:s}}})),clearPendingDiff:(t,n)=>e(o=>{const s=o.pendingDiffs[t];if(!s)return o;const i={...o.pendingDiffs};delete i[t];const c=o.acceptedApplyIds||[],u=n&&s.applyId?[...c.slice(-199),s.applyId]:c;return{pendingDiffs:i,acceptedApplyIds:u}})}),{name:"documents-storage",version:1,storage:C(()=>O),partialize:e=>({documents:e.documents,openTabs:e.openTabs,activeTab:e.activeTab,documentTypes:e.documentTypes}),onRehydrateStorage:()=>e=>{if(e!=null&&e.documents)for(const t of e.documents)for(const n of["mtime","ctime","atime"])t[n]&&typeof t[n]=="string"&&(t[n]=new Date(t[n]))}}))),I=a.createContext(void 0),ue=({children:r})=>{const e=a.useRef(null);return e.current||(e.current=W(E())),f.jsx(I.Provider,{value:e.current,children:r})},ae=r=>{const e=a.useContext(I);if(!e)throw new Error("useDocumentsStore must be used within DocumentsStoreProvider");return h(e,r)};function X(r){try{const e=JSON.parse(r);return!e||typeof e!="object"?{valid:!1,errors:[{message:"Theme must be a JSON object"}]}:typeof e.name!="string"||!e.name.trim()?{valid:!1,errors:[{message:'Theme must have a non-empty "name" property'}]}:{valid:!0}}catch(e){return{valid:!1,errors:[{message:e instanceof SyntaxError?`Invalid JSON: ${e.message}`:"Failed to parse theme JSON"}]}}}function _(r){try{return r&&typeof r=="object"&&"name"in r&&typeof r.name=="string"?r.name:null}catch{return null}}const m=class m extends EventTarget{constructor(){super()}static getInstance(){return m.instance||(m.instance=new m),m.instance}emitThemeChange(e){this.dispatchEvent(new CustomEvent("themechange",{detail:e}))}onThemeChange(e){const t=n=>{e(n.detail)};return this.addEventListener("themechange",t),this._listenerCount=(this._listenerCount||0)+1,()=>{this.removeEventListener("themechange",t),this._listenerCount=Math.max(0,(this._listenerCount||1)-1)}}};x(m,"instance");let S=m;const w=S.getInstance(),j=()=>({customThemes:{}}),K={...j()},Q=(r=K)=>l()(p(g((e,t)=>({...r,updateTheme:(n,o)=>e(s=>{const i=X(o);let c,u=n;if(i.valid)try{const b=JSON.parse(o);c=b;const D=_(b);D&&(u=D)}catch{}const d=s.customThemes[n],B=!!d,N=(d==null?void 0:d.content)!==o,k={name:u,content:o,parsed:c,valid:i.valid,lastModified:new Date};return(N||!(d!=null&&d.valid)&&i.valid)&&i.valid&&setTimeout(()=>{w.emitThemeChange({themeName:u,timestamp:Date.now(),changeType:B?"update":"create"})},0),{customThemes:{...s.customThemes,[n]:k}}}),removeTheme:n=>e(o=>{const s=o.customThemes[n],i={...o.customThemes};return delete i[n],s&&setTimeout(()=>{w.emitThemeChange({themeName:s.name,timestamp:Date.now(),changeType:"delete"})},0),{customThemes:i}}),getTheme:n=>{const o=t();for(const s of Object.values(o.customThemes))if(s.valid&&s.name===n&&s.parsed)return s.parsed;return null},getAllThemeNames:()=>{const n=t(),o=[];for(const s of Object.values(n.customThemes))s.valid&&s.name&&o.push(s.name);return o},isThemeValid:n=>{const o=t();for(const s of Object.values(o.customThemes))if(s.name===n)return s.valid;return!1}}),{name:"themes-storage",version:4,storage:C(()=>O),partialize:e=>({customThemes:e.customThemes}),onRehydrateStorage:()=>e=>{e&&e.customThemes&&Object.keys(e.customThemes).forEach(t=>{const n=e.customThemes[t];n.lastModified&&typeof n.lastModified=="string"&&(n.lastModified=new Date(n.lastModified))})}}))),P=a.createContext(void 0),de=({children:r})=>{const e=a.useRef(void 0);return e.current||(e.current=Q(j())),f.jsx(P.Provider,{value:e.current,children:r})},me=r=>{const e=a.useContext(P);if(!e)throw new Error("useThemesStore must be used within ThemesStoreProvider");return h(e,r)},R=()=>({name:void 0,text:void 0,blob:void 0,globalError:void 0,isGenerating:!1,generationProgress:void 0,isRendering:!1,isPreviewStale:!1,editSequence:0,lastBuiltSequence:0}),Y={...R()},Z=(r=Y)=>l()(p(e=>({...r,setOutput:t=>e({...t}),bumpEditSequence:()=>e(t=>({editSequence:(t.editSequence??0)+1,editTimestamp:Date.now()}))}))),A=a.createContext(void 0),fe=({children:r})=>{const e=a.useRef(null);return e.current||(e.current=Z(R())),f.jsx(A.Provider,{value:e.current,children:r})},le=r=>{const e=a.useContext(A);if(!e)throw new Error("useOutputStore must be used within OutputStoreProvider");return h(e,r)},M=()=>({saveDocumentDebounceWait:300,autoReload:!0,renderingLibrary:J==="docx"?"docxjs":"LibreOffice",useGlobalPreviewHeader:!0}),ee={...M()},te=(r=ee)=>l()(p(g(e=>({...r,setSettings:t=>e({...t})}),{name:"settings-storage"}))),L=a.createContext(void 0),pe=({children:r})=>{const e=a.useRef(null);return e.current||(e.current=te(M())),f.jsx(L.Provider,{value:e.current,children:r})},he=r=>{const e=a.useContext(L);if(!e)throw new Error("useSettingsStore must be used within SettingsStoreProvider");return h(e,r)};export{ue as D,fe as O,pe as S,de as T,me as a,le as b,he as c,A as d,I as e,P as f,_ as g,O as i,w as t,ae as u,X as v};
2
- //# sourceMappingURL=settings-store-provider-DuCKtwqs.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"settings-store-provider-DuCKtwqs.js","sources":["../../../../../node_modules/.pnpm/idb-keyval@6.2.2/node_modules/idb-keyval/dist/index.js","../../../src/client/lib/idb-storage.ts","../../../src/client/store/documents-store.ts","../../../src/client/store/documents-store-provider.tsx","../../../src/client/lib/theme-validation.ts","../../../src/client/utils/theme-change-emitter.ts","../../../src/client/store/themes-store.ts","../../../src/client/store/themes-store-provider.tsx","../../../src/client/store/output-store.ts","../../../src/client/store/output-store-provider.tsx","../../../src/client/store/settings-store.ts","../../../src/client/store/settings-store-provider.tsx"],"sourcesContent":["function promisifyRequest(request) {\n return new Promise((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\nfunction createStore(dbName, storeName) {\n let dbp;\n const getDB = () => {\n if (dbp)\n return dbp;\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n dbp = promisifyRequest(request);\n dbp.then((db) => {\n // It seems like Safari sometimes likes to just close the connection.\n // It's supposed to fire this event when that happens. Let's hope it does!\n db.onclose = () => (dbp = undefined);\n }, () => { });\n return dbp;\n };\n return (txMode, callback) => getDB().then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Delete multiple keys at once.\n *\n * @param keys List of keys to delete.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction delMany(keys, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n keys.forEach((key) => store.delete(key));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(store, callback) {\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n return customStore('readonly', (store) => {\n // Fast path for modern browsers\n if (store.getAllKeys) {\n return promisifyRequest(store.getAllKeys());\n }\n const items = [];\n return eachCursor(store, (cursor) => items.push(cursor.key)).then(() => items);\n });\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n return customStore('readonly', (store) => {\n // Fast path for modern browsers\n if (store.getAll) {\n return promisifyRequest(store.getAll());\n }\n const items = [];\n return eachCursor(store, (cursor) => items.push(cursor.value)).then(() => items);\n });\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n return customStore('readonly', (store) => {\n // Fast path for modern browsers\n // (although, hopefully we'll get a simpler path some day)\n if (store.getAll && store.getAllKeys) {\n return Promise.all([\n promisifyRequest(store.getAllKeys()),\n promisifyRequest(store.getAll()),\n ]).then(([keys, values]) => keys.map((key, i) => [key, values[i]]));\n }\n const items = [];\n return customStore('readonly', (store) => eachCursor(store, (cursor) => items.push([cursor.key, cursor.value])).then(() => items));\n });\n}\n\nexport { clear, createStore, del, delMany, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","/**\n * IndexedDB storage adapter for Zustand persist middleware using idb-keyval.\n */\nimport { get, set, del } from 'idb-keyval';\nimport type { StateStorage } from 'zustand/middleware';\n\nexport const idbStorage: StateStorage = {\n getItem: async (name: string): Promise<string | null> => {\n return (await get(name)) ?? null;\n },\n setItem: async (name: string, value: string): Promise<void> => {\n await set(name, value);\n },\n removeItem: async (name: string): Promise<void> => {\n await del(name);\n },\n};\n","import { persist, devtools, createJSONStorage } from 'zustand/middleware';\nimport { createStore } from 'zustand/vanilla';\nimport type { TextFile } from '../lib/types';\nimport { idbStorage } from '../lib/idb-storage';\n\nconst MAX_OPEN_TABS = 3;\n\nexport type DocumentType = 'application/json+report' | 'application/json+theme';\n\nexport type DocumentsState = {\n documents: TextFile[];\n openTabs: string[];\n activeTab: string;\n buildErrors: { [key: string]: string };\n documentTypes: { [key: string]: DocumentType };\n pendingDiffs: { [key: string]: { original: string; modified: string; applyId?: string } };\n acceptedApplyIds: string[];\n};\n\nexport type DocumentsActions = {\n createDocument: (name: string, text: string) => void;\n deleteDocument: (name: string) => void;\n saveDocument: (name: string, text: string) => void;\n renameDocument: (oldName: string, newName: string) => void;\n openDocument: (name: string) => void;\n closeDocument: (name: string) => void;\n setActiveTab: (name: string) => void;\n setBuildError: (name: string, buildError?: string) => void;\n setPendingDiff: (name: string, original: string, modified: string, applyId?: string) => void;\n clearPendingDiff: (name: string, accepted?: boolean) => void;\n};\n\nexport type DocumentsStore = DocumentsState & DocumentsActions;\n\nexport const initDocumentsStore = (): DocumentsState => {\n return {\n documents: [],\n openTabs: [],\n activeTab: '',\n buildErrors: {},\n documentTypes: {},\n pendingDiffs: {},\n acceptedApplyIds: [],\n };\n};\n\nexport const defaultInitDocumentsState: DocumentsState = {\n ...initDocumentsStore(),\n};\n\nexport const createDocumentsStore = (\n initState: DocumentsState = defaultInitDocumentsState\n) => {\n return createStore<DocumentsStore>()(\n devtools(\n persist(\n (set) => ({\n ...initState,\n createDocument: (name, text) =>\n set((state) => {\n const docIndex = state.documents.findIndex(\n (doc) => doc.name === name\n );\n if (docIndex === -1) {\n // if the document does not exist\n // Determine document type based on file name and content\n let docType: DocumentType = 'application/json+report';\n if (\n name.toLowerCase().includes('theme') ||\n name.toLowerCase().includes('.theme.')\n ) {\n docType = 'application/json+theme';\n } else {\n // Try to parse JSON to check if it's a theme\n try {\n const parsed = JSON.parse(text);\n if (parsed.colors && parsed.fonts && parsed.styles) {\n docType = 'application/json+theme';\n }\n } catch {\n // If not valid JSON, default to report\n }\n }\n\n const newDoc = {\n name,\n type: 'application/json',\n text,\n mtime: new Date(),\n ctime: new Date(),\n atime: new Date(),\n };\n return {\n documents: [...state.documents, newDoc],\n documentTypes: { ...state.documentTypes, [name]: docType },\n };\n }\n return state;\n }),\n deleteDocument: (name) =>\n set((state) => {\n const newDocumentTypes = { ...state.documentTypes };\n delete newDocumentTypes[name];\n return {\n documents: state.documents.filter((doc) => doc.name !== name),\n documentTypes: newDocumentTypes,\n pendingDiffs: Object.fromEntries(\n Object.entries(state.pendingDiffs).filter(([k]) => k !== name)\n ),\n };\n }),\n saveDocument: (name, text) =>\n set((state) => {\n const docIndex = state.documents.findIndex(\n (doc) => doc.name === name\n );\n if (docIndex === -1) return state;\n // Skip update if text is unchanged to avoid spurious re-renders\n if (state.documents[docIndex].text === text) return state;\n const documents = state.documents.map((doc, i) =>\n i === docIndex ? { ...doc, text, mtime: new Date() } : doc\n );\n return { documents };\n }),\n renameDocument: (oldName, newName) =>\n set((state) => {\n const docIndex = state.documents.findIndex(\n (doc) => doc.name === oldName\n );\n if (docIndex === -1) return state;\n const documents = state.documents.map((doc, i) =>\n i === docIndex ? { ...doc, name: newName, ctime: new Date() } : doc\n );\n const docType = state.documentTypes[oldName];\n if (docType) {\n const newDocumentTypes = { ...state.documentTypes };\n delete newDocumentTypes[oldName];\n newDocumentTypes[newName] = docType;\n return { documents, documentTypes: newDocumentTypes };\n }\n return { documents };\n }),\n openDocument: (name) =>\n set((state) => {\n const docIndex = state.documents.findIndex(\n (doc) => doc.name === name\n );\n if (docIndex === -1) return state;\n const documents = state.documents.map((doc, i) =>\n i === docIndex ? { ...doc, atime: new Date() } : doc\n );\n let openTabs = state.openTabs;\n if (!openTabs.includes(name)) {\n openTabs = openTabs.length >= MAX_OPEN_TABS\n ? [...openTabs.slice(1), name]\n : [...openTabs, name];\n }\n return { documents, openTabs, activeTab: name };\n }),\n closeDocument: (name) =>\n set((state) => {\n const index = state.openTabs.indexOf(name);\n if (index === -1) return state;\n const openTabs = state.openTabs.filter((tab) => tab !== name);\n let activeTab = state.activeTab;\n if (activeTab === name) {\n if (openTabs.length) {\n activeTab = index === 0 ? openTabs[0] : openTabs[index - 1];\n } else {\n activeTab = '';\n }\n }\n return { openTabs, activeTab };\n }),\n setActiveTab: (name) => set({ activeTab: name }),\n setBuildError: (name, buildError) =>\n set((state) => {\n if (state.buildErrors[name] === buildError) return state;\n const buildErrors = { ...state.buildErrors };\n if (buildError) buildErrors[name] = buildError;\n else delete buildErrors[name];\n return { buildErrors };\n }),\n setPendingDiff: (name, original, modified, applyId) =>\n set((state) => {\n return {\n pendingDiffs: {\n ...state.pendingDiffs,\n [name]: { original, modified, applyId },\n },\n };\n }),\n clearPendingDiff: (name, accepted) =>\n set((state) => {\n const diff = state.pendingDiffs[name];\n if (!diff) return state;\n const next = { ...state.pendingDiffs };\n delete next[name];\n const ids = state.acceptedApplyIds || [];\n const acceptedApplyIds =\n accepted && diff.applyId\n ? [...ids.slice(-(200 - 1)), diff.applyId]\n : ids;\n return { pendingDiffs: next, acceptedApplyIds };\n }),\n }),\n {\n name: 'documents-storage',\n version: 1,\n storage: createJSONStorage(() => idbStorage),\n partialize: (state) => ({\n documents: state.documents,\n openTabs: state.openTabs,\n activeTab: state.activeTab,\n documentTypes: state.documentTypes,\n // buildErrors + pendingDiffs + acceptedApplyIds excluded — transient UI state\n }),\n onRehydrateStorage: () => (state) => {\n if (state?.documents) {\n for (const doc of state.documents) {\n for (const key of ['mtime', 'ctime', 'atime'] as const) {\n if (doc[key] && typeof doc[key] === 'string') {\n (doc as Record<string, unknown>)[key] = new Date(doc[key] as unknown as string);\n }\n }\n }\n }\n },\n }\n )\n )\n );\n};\n","import { type ReactNode, createContext, useRef, useContext } from 'react';\nimport { useStore } from 'zustand';\nimport {\n type DocumentsStore,\n createDocumentsStore,\n initDocumentsStore,\n} from './documents-store';\n\nexport type DocumentsStoreApi = ReturnType<typeof createDocumentsStore>;\n\nexport const DocumentsStoreContext = createContext<\n DocumentsStoreApi | undefined\n>(undefined);\n\nexport interface DocumentsStoreProviderProps {\n children: ReactNode;\n}\n\nexport const DocumentsStoreProvider = ({\n children,\n}: DocumentsStoreProviderProps) => {\n const storeRef = useRef<DocumentsStoreApi | null>(null);\n if (!storeRef.current) {\n storeRef.current = createDocumentsStore(initDocumentsStore());\n }\n\n return (\n <DocumentsStoreContext.Provider value={storeRef.current}>\n {children}\n </DocumentsStoreContext.Provider>\n );\n};\n\nexport const useDocumentsStore = <T,>(\n selector: (store: DocumentsStore) => T\n): T => {\n const documentsStoreContext = useContext(DocumentsStoreContext);\n\n if (!documentsStoreContext) {\n throw new Error(\n 'useDocumentsStore must be used within DocumentsStoreProvider'\n );\n }\n\n return useStore(documentsStoreContext, selector);\n};\n","export interface ThemeValidationError {\n message: string;\n line?: number;\n column?: number;\n path?: string;\n}\n\nexport interface ThemeValidationResult {\n valid: boolean;\n errors?: ThemeValidationError[];\n}\n\n/**\n * Validates a theme JSON string - checks structure without requiring format-specific schemas\n */\nexport function validateThemeJson(jsonString: string): ThemeValidationResult {\n try {\n const parsed = JSON.parse(jsonString);\n\n if (!parsed || typeof parsed !== 'object') {\n return {\n valid: false,\n errors: [{ message: 'Theme must be a JSON object' }],\n };\n }\n\n if (typeof parsed.name !== 'string' || !parsed.name.trim()) {\n return {\n valid: false,\n errors: [{ message: 'Theme must have a non-empty \"name\" property' }],\n };\n }\n\n return { valid: true };\n } catch (e) {\n return {\n valid: false,\n errors: [\n {\n message:\n e instanceof SyntaxError\n ? `Invalid JSON: ${e.message}`\n : 'Failed to parse theme JSON',\n },\n ],\n };\n }\n}\n\n/**\n * Gets theme name from a theme JSON object\n */\nexport function getThemeName(themeJson: unknown): string | null {\n try {\n if (\n themeJson &&\n typeof themeJson === 'object' &&\n 'name' in (themeJson as any) &&\n typeof (themeJson as any).name === 'string'\n ) {\n return (themeJson as any).name as string;\n }\n return null;\n } catch {\n return null;\n }\n}\n","// Theme change event emitter for coordinating theme updates across components\nexport interface ThemeChangeEvent {\n themeName: string;\n timestamp: number;\n changeType: 'create' | 'update' | 'delete';\n}\n\nexport class ThemeChangeEmitter extends EventTarget {\n private static instance: ThemeChangeEmitter;\n\n private constructor() {\n super();\n }\n\n static getInstance(): ThemeChangeEmitter {\n if (!ThemeChangeEmitter.instance) {\n ThemeChangeEmitter.instance = new ThemeChangeEmitter();\n }\n return ThemeChangeEmitter.instance;\n }\n\n emitThemeChange(event: ThemeChangeEvent): void {\n this.dispatchEvent(new CustomEvent('themechange', { detail: event }));\n }\n\n onThemeChange(callback: (event: ThemeChangeEvent) => void): () => void {\n const handler = (e: Event) => {\n const customEvent = e as CustomEvent<ThemeChangeEvent>;\n callback(customEvent.detail);\n };\n\n this.addEventListener('themechange', handler);\n\n // Track listener count\n (this as any)._listenerCount = ((this as any)._listenerCount || 0) + 1;\n\n // Return unsubscribe function\n return () => {\n this.removeEventListener('themechange', handler);\n (this as any)._listenerCount = Math.max(\n 0,\n ((this as any)._listenerCount || 1) - 1\n );\n };\n }\n}\n\nexport const themeChangeEmitter = ThemeChangeEmitter.getInstance();\n","import { persist, devtools, createJSONStorage } from 'zustand/middleware';\nimport { createStore } from 'zustand/vanilla';\nimport type { ThemeConfigJson } from '@json-to-office/shared-pptx';\nimport { validateThemeJson, getThemeName } from '../lib/theme-validation';\nimport { themeChangeEmitter } from '../utils/theme-change-emitter';\nimport { idbStorage } from '../lib/idb-storage';\n\nexport type CustomTheme = {\n name: string;\n content: string;\n parsed?: ThemeConfigJson;\n valid: boolean;\n lastModified: Date;\n};\n\nexport type ThemesState = {\n customThemes: { [name: string]: CustomTheme };\n};\n\nexport type ThemesActions = {\n updateTheme: (documentName: string, content: string) => void;\n removeTheme: (documentName: string) => void;\n getTheme: (themeName: string) => ThemeConfigJson | null;\n getAllThemeNames: () => string[];\n isThemeValid: (themeName: string) => boolean;\n};\n\nexport type ThemesStore = ThemesState & ThemesActions;\n\nexport const initThemesStore = (): ThemesState => {\n return {\n customThemes: {},\n };\n};\n\nexport const defaultInitThemesState: ThemesState = {\n ...initThemesStore(),\n};\n\nexport const createThemesStore = (\n initState: ThemesState = defaultInitThemesState\n) => {\n return createStore<ThemesStore>()(\n devtools(\n persist(\n (set, get) => ({\n ...initState,\n\n updateTheme: (documentName, content) =>\n set((state) => {\n const validation = validateThemeJson(content);\n\n let parsed: ThemeConfigJson | undefined;\n let themeName = documentName;\n\n if (validation.valid) {\n try {\n const parsedContent = JSON.parse(content);\n parsed = parsedContent;\n const extractedName = getThemeName(parsedContent);\n if (extractedName) {\n themeName = extractedName;\n }\n } catch {\n // Keep the document name if parsing fails\n }\n }\n\n const existingTheme = state.customThemes[documentName];\n const isUpdate = !!existingTheme;\n const hasContentChanged = existingTheme?.content !== content;\n\n const customTheme: CustomTheme = {\n name: themeName,\n content,\n parsed,\n valid: validation.valid,\n lastModified: new Date(),\n };\n\n // Emit theme change if content changed OR if this is a newly valid theme\n const shouldEmitEvent =\n (hasContentChanged ||\n (!existingTheme?.valid && validation.valid)) &&\n validation.valid;\n\n if (shouldEmitEvent) {\n // Use setTimeout to ensure state is updated before event is processed\n setTimeout(() => {\n themeChangeEmitter.emitThemeChange({\n themeName,\n timestamp: Date.now(),\n changeType: isUpdate ? 'update' : 'create',\n });\n }, 0);\n }\n\n return {\n customThemes: {\n ...state.customThemes,\n [documentName]: customTheme,\n },\n };\n }),\n\n removeTheme: (documentName) =>\n set((state) => {\n const removedTheme = state.customThemes[documentName];\n const newCustomThemes = { ...state.customThemes };\n delete newCustomThemes[documentName];\n\n // Emit theme deletion event\n if (removedTheme) {\n setTimeout(() => {\n themeChangeEmitter.emitThemeChange({\n themeName: removedTheme.name,\n timestamp: Date.now(),\n changeType: 'delete',\n });\n }, 0);\n }\n\n return {\n customThemes: newCustomThemes,\n };\n }),\n\n getTheme: (themeName) => {\n const state = get();\n\n // First check custom themes by theme name\n for (const customTheme of Object.values(state.customThemes)) {\n if (\n customTheme.valid &&\n customTheme.name === themeName &&\n customTheme.parsed\n ) {\n return customTheme.parsed;\n }\n }\n\n // Theme not found in custom themes\n return null;\n },\n\n getAllThemeNames: () => {\n const state = get();\n const names: string[] = [];\n\n // Add custom theme names\n for (const customTheme of Object.values(state.customThemes)) {\n if (customTheme.valid && customTheme.name) {\n names.push(customTheme.name);\n }\n }\n\n return names;\n },\n\n isThemeValid: (themeName) => {\n const state = get();\n\n // Check custom themes\n for (const customTheme of Object.values(state.customThemes)) {\n if (customTheme.name === themeName) {\n return customTheme.valid;\n }\n }\n\n return false;\n },\n }),\n {\n name: 'themes-storage',\n version: 4, // v4: migrate from localStorage to IndexedDB\n storage: createJSONStorage(() => idbStorage),\n // Only persist the themes data, not the functions\n partialize: (state) => ({ customThemes: state.customThemes }),\n // Handle date deserialization when loading from storage\n onRehydrateStorage: () => (state) => {\n if (state && state.customThemes) {\n // Convert lastModified strings back to Date objects\n Object.keys(state.customThemes).forEach((key) => {\n const theme = state.customThemes[key];\n if (\n theme.lastModified &&\n typeof theme.lastModified === 'string'\n ) {\n theme.lastModified = new Date(theme.lastModified);\n }\n });\n }\n },\n }\n )\n )\n );\n};\n","import { type ReactNode, createContext, useRef, useContext } from 'react';\nimport { useStore } from 'zustand';\n\nimport {\n type ThemesStore,\n createThemesStore,\n initThemesStore,\n} from './themes-store';\n\nexport type ThemesStoreApi = ReturnType<typeof createThemesStore>;\n\nexport const ThemesStoreContext = createContext<ThemesStoreApi | undefined>(\n undefined\n);\n\nexport interface ThemesStoreProviderProps {\n children: ReactNode;\n}\n\nexport const ThemesStoreProvider = ({ children }: ThemesStoreProviderProps) => {\n const storeRef = useRef<ThemesStoreApi>(undefined);\n if (!storeRef.current) {\n storeRef.current = createThemesStore(initThemesStore());\n }\n\n return (\n <ThemesStoreContext.Provider value={storeRef.current}>\n {children}\n </ThemesStoreContext.Provider>\n );\n};\n\nexport const useThemesStore = <T,>(selector: (store: ThemesStore) => T): T => {\n const themesStoreContext = useContext(ThemesStoreContext);\n\n if (!themesStoreContext) {\n throw new Error('useThemesStore must be used within ThemesStoreProvider');\n }\n\n return useStore(themesStoreContext, selector);\n};\n","import { devtools } from 'zustand/middleware';\nimport { createStore } from 'zustand/vanilla';\n\nexport interface GenerationWarning {\n component: string;\n message: string;\n severity?: 'warning' | 'info';\n context?: Record<string, unknown>;\n}\n\nexport type OutputState = {\n name?: string; // last success => document name\n text?: string; // last success => code used to generate the pptx\n blob?: Blob; // last success => generated pptx\n globalError?: string; // last failed => global error message\n isGenerating?: boolean; // presentation generation in progress\n generationProgress?: {\n stage: 'parsing' | 'building' | 'rendering' | 'finalizing';\n message?: string;\n };\n cacheStatus?: 'HIT' | 'MISS' | 'UNKNOWN'; // cache hit/miss status\n cacheHitRate?: string; // cache hit rate percentage\n warnings?: GenerationWarning[] | null; // warnings from custom component processing\n isRendering?: boolean; // preview rendering in progress (iframe/LibreOffice)\n isPreviewStale?: boolean; // preview outdated (new blob generated but not yet rendered)\n editSequence?: number; // incremented on every Monaco keystroke (init 0)\n lastBuiltSequence?: number; // stamped when generation completes (init 0)\n editTimestamp?: number; // Date.now() of the last edit (for debounce countdown)\n // ⚠️ name doesn't necessarily correspond to the global error message\n};\n\nexport type OutputActions = {\n setOutput: (partialState: OutputState) => void;\n bumpEditSequence: () => void;\n};\n\nexport type OutputStore = OutputState & OutputActions;\n\nexport const initOutputStore = (): OutputState => {\n return {\n name: undefined,\n text: undefined,\n blob: undefined,\n globalError: undefined,\n isGenerating: false,\n generationProgress: undefined,\n isRendering: false,\n isPreviewStale: false,\n editSequence: 0,\n lastBuiltSequence: 0,\n };\n};\n\nexport const defaultInitOutputState: OutputState = {\n ...initOutputStore(),\n};\n\nexport const createOutputStore = (\n initState: OutputState = defaultInitOutputState\n) => {\n return createStore<OutputStore>()(\n devtools((set) => ({\n ...initState,\n setOutput: (partialState) => set({ ...partialState }),\n bumpEditSequence: () =>\n set((s) => ({\n editSequence: (s.editSequence ?? 0) + 1,\n editTimestamp: Date.now(),\n })),\n }))\n );\n};\n","import { type ReactNode, createContext, useRef, useContext } from 'react';\nimport { useStore } from 'zustand';\nimport {\n type OutputStore,\n createOutputStore,\n initOutputStore,\n} from './output-store';\n\nexport type OutputStoreApi = ReturnType<typeof createOutputStore>;\n\nexport const OutputStoreContext = createContext<OutputStoreApi | undefined>(\n undefined\n);\n\nexport interface OutputStoreProviderProps {\n children: ReactNode;\n}\n\nexport const OutputStoreProvider = ({ children }: OutputStoreProviderProps) => {\n const storeRef = useRef<OutputStoreApi | null>(null);\n if (!storeRef.current) {\n storeRef.current = createOutputStore(initOutputStore());\n }\n\n return (\n <OutputStoreContext.Provider value={storeRef.current}>\n {children}\n </OutputStoreContext.Provider>\n );\n};\n\nexport const useOutputStore = <T,>(selector: (store: OutputStore) => T): T => {\n const outputStoreContext = useContext(OutputStoreContext);\n\n if (!outputStoreContext) {\n throw new Error('useOutputStore must be used within OutputStoreProvider');\n }\n\n return useStore(outputStoreContext, selector);\n};\n","import { devtools, persist } from 'zustand/middleware';\nimport { createStore } from 'zustand/vanilla';\nimport type { Settings } from '../lib/types';\nimport { FORMAT } from '../lib/env';\n\nexport type SettingsState = Settings;\n\nexport type SettingsActions = {\n setSettings: (settings: Partial<Settings>) => void;\n};\n\nexport type SettingsStore = SettingsState & SettingsActions;\n\nexport const initSettingsStore = (): SettingsState => {\n return {\n saveDocumentDebounceWait: 300,\n autoReload: true,\n renderingLibrary: FORMAT === 'docx' ? 'docxjs' : 'LibreOffice',\n // UI preference to use a single preview header spanning editor + preview\n useGlobalPreviewHeader: true,\n };\n};\n\nexport const defaultInitSettingsState: SettingsState = {\n ...initSettingsStore(),\n};\n\nexport const createSettingsStore = (\n initState: SettingsState = defaultInitSettingsState\n) => {\n return createStore<SettingsStore>()(\n devtools(\n persist(\n (set) => ({\n ...initState,\n setSettings: (settings) => set({ ...settings }),\n }),\n {\n name: 'settings-storage', // name of the item in the storage (must be unique)\n // (optional) by default, 'localStorage' is used as storage\n }\n )\n )\n );\n};\n","import { type ReactNode, createContext, useRef, useContext } from 'react';\nimport { useStore } from 'zustand';\nimport {\n type SettingsStore,\n createSettingsStore,\n initSettingsStore,\n} from './settings-store';\n\nexport type SettingsStoreApi = ReturnType<typeof createSettingsStore>;\n\nexport const SettingsStoreContext = createContext<SettingsStoreApi | undefined>(\n undefined\n);\n\nexport interface SettingsStoreProviderProps {\n children: ReactNode;\n}\n\nexport const SettingsStoreProvider = ({\n children,\n}: SettingsStoreProviderProps) => {\n const storeRef = useRef<SettingsStoreApi | null>(null);\n if (!storeRef.current) {\n storeRef.current = createSettingsStore(initSettingsStore());\n }\n\n return (\n <SettingsStoreContext.Provider value={storeRef.current}>\n {children}\n </SettingsStoreContext.Provider>\n );\n};\n\nexport const useSettingsStore = <T,>(\n selector: (store: SettingsStore) => T\n): T => {\n const settingsStoreContext = useContext(SettingsStoreContext);\n\n if (!settingsStoreContext) {\n throw new Error(\n 'useSettingsStore must be used within SettingsStoreProvider'\n );\n }\n\n return useStore(settingsStoreContext, selector);\n};\n"],"names":["promisifyRequest","request","resolve","reject","createStore","dbName","storeName","dbp","getDB","db","txMode","callback","defaultGetStoreFunc","defaultGetStore","get","key","customStore","store","set","value","del","idbStorage","name","MAX_OPEN_TABS","initDocumentsStore","defaultInitDocumentsState","createDocumentsStore","initState","devtools","persist","text","state","doc","docType","parsed","newDoc","newDocumentTypes","k","docIndex","i","oldName","newName","documents","openTabs","index","tab","activeTab","buildError","buildErrors","original","modified","applyId","accepted","diff","next","ids","acceptedApplyIds","createJSONStorage","DocumentsStoreContext","createContext","DocumentsStoreProvider","children","storeRef","useRef","useDocumentsStore","selector","documentsStoreContext","useContext","useStore","validateThemeJson","jsonString","getThemeName","themeJson","_ThemeChangeEmitter","event","handler","e","__publicField","ThemeChangeEmitter","themeChangeEmitter","initThemesStore","defaultInitThemesState","createThemesStore","documentName","content","validation","themeName","parsedContent","extractedName","existingTheme","isUpdate","hasContentChanged","customTheme","removedTheme","newCustomThemes","names","theme","ThemesStoreContext","ThemesStoreProvider","useThemesStore","themesStoreContext","initOutputStore","defaultInitOutputState","createOutputStore","partialState","s","OutputStoreContext","OutputStoreProvider","useOutputStore","outputStoreContext","initSettingsStore","FORMAT","defaultInitSettingsState","createSettingsStore","settings","SettingsStoreContext","SettingsStoreProvider","useSettingsStore","settingsStoreContext"],"mappings":"qXAAA,SAASA,EAAiBC,EAAS,CAC/B,OAAO,IAAI,QAAQ,CAACC,EAASC,IAAW,CAEpCF,EAAQ,WAAaA,EAAQ,UAAY,IAAMC,EAAQD,EAAQ,MAAM,EAErEA,EAAQ,QAAUA,EAAQ,QAAU,IAAME,EAAOF,EAAQ,KAAK,CAClE,CAAC,CACL,CACA,SAASG,EAAYC,EAAQC,EAAW,CACpC,IAAIC,EACJ,MAAMC,EAAQ,IAAM,CAChB,GAAID,EACA,OAAOA,EACX,MAAMN,EAAU,UAAU,KAAKI,CAAM,EACrC,OAAAJ,EAAQ,gBAAkB,IAAMA,EAAQ,OAAO,kBAAkBK,CAAS,EAC1EC,EAAMP,EAAiBC,CAAO,EAC9BM,EAAI,KAAME,GAAO,CAGbA,EAAG,QAAU,IAAOF,EAAM,MAC9B,EAAG,IAAM,CAAE,CAAC,EACLA,CACX,EACA,MAAO,CAACG,EAAQC,IAAaH,EAAK,EAAG,KAAMC,GAAOE,EAASF,EAAG,YAAYH,EAAWI,CAAM,EAAE,YAAYJ,CAAS,CAAC,CAAC,CACxH,CACA,IAAIM,EACJ,SAASC,GAAkB,CACvB,OAAKD,IACDA,EAAsBR,EAAY,eAAgB,QAAQ,GAEvDQ,CACX,CAOA,SAASE,EAAIC,EAAKC,EAAcH,IAAmB,CAC/C,OAAOG,EAAY,WAAaC,GAAUjB,EAAiBiB,EAAM,IAAIF,CAAG,CAAC,CAAC,CAC9E,CAQA,SAASG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