codicent-app-sdk 0.4.29 → 0.5.1

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 (34) hide show
  1. package/dist/cjs/components/ListView.d.ts +10 -2
  2. package/dist/cjs/components/ListView.d.ts.map +1 -1
  3. package/dist/cjs/components/ListView.js +1 -1
  4. package/dist/cjs/components/RecordModal.d.ts.map +1 -1
  5. package/dist/cjs/components/RecordModal.js +1 -1
  6. package/dist/cjs/hooks/useAppState.d.ts +81 -0
  7. package/dist/cjs/hooks/useAppState.d.ts.map +1 -0
  8. package/dist/cjs/hooks/useAppState.js +1 -0
  9. package/dist/cjs/hooks/useAuthState.d.ts.map +1 -1
  10. package/dist/cjs/hooks/useAuthState.js +1 -1
  11. package/dist/cjs/hooks/useCodicentApp.d.ts +1 -1
  12. package/dist/cjs/hooks/useCodicentApp.d.ts.map +1 -1
  13. package/dist/cjs/hooks/useCodicentApp.js +1 -1
  14. package/dist/cjs/services/codicent.d.ts +6 -0
  15. package/dist/cjs/services/codicent.d.ts.map +1 -1
  16. package/dist/cjs/services/codicent.js +1 -1
  17. package/dist/esm/components/ListView.d.ts +10 -2
  18. package/dist/esm/components/ListView.d.ts.map +1 -1
  19. package/dist/esm/components/ListView.js +1 -1
  20. package/dist/esm/components/RecordModal.d.ts.map +1 -1
  21. package/dist/esm/components/RecordModal.js +1 -1
  22. package/dist/esm/hooks/useAppState.d.ts +81 -0
  23. package/dist/esm/hooks/useAppState.d.ts.map +1 -0
  24. package/dist/esm/hooks/useAppState.js +1 -0
  25. package/dist/esm/hooks/useAuthState.d.ts.map +1 -1
  26. package/dist/esm/hooks/useAuthState.js +1 -1
  27. package/dist/esm/hooks/useCodicentApp.d.ts +1 -1
  28. package/dist/esm/hooks/useCodicentApp.d.ts.map +1 -1
  29. package/dist/esm/hooks/useCodicentApp.js +1 -1
  30. package/dist/esm/services/codicent.d.ts +6 -0
  31. package/dist/esm/services/codicent.d.ts.map +1 -1
  32. package/dist/esm/services/codicent.js +1 -1
  33. package/dist/index.d.ts +16 -2
  34. package/package.json +1 -1
@@ -7,6 +7,8 @@ export interface ColumnAction {
7
7
  tooltip?: string;
8
8
  /** Callback when the action icon is clicked, receives the row data as context */
9
9
  onClick: (rowData: Record<string, unknown>) => void;
10
+ /** When true, renders the icon to the left of the cell text instead of the right */
11
+ iconLeft?: boolean;
10
12
  }
11
13
  export interface ColumnDefinition {
12
14
  key: string | string[];
@@ -14,11 +16,17 @@ export interface ColumnDefinition {
14
16
  hidden?: boolean;
15
17
  hideOnMobile?: boolean;
16
18
  maxWidth?: number;
17
- type?: "file" | "checkbox" | "textarea" | "enum" | undefined;
19
+ type?: "file" | "checkbox" | "textarea" | "enum" | "combobox" | undefined;
18
20
  /** Number of rows for textarea type (default: 3) */
19
21
  rows?: number;
20
- /** Options for enum type columns */
22
+ /** Options for enum type columns (static, small lists) */
21
23
  enumOptions?: string[];
24
+ /** Async loader for combobox options (e.g. 15k+ customers). Receives the current search text, returns matching options. */
25
+ enumOptionsLoader?: (searchText: string) => Promise<string[]>;
26
+ /** Minimum number of characters typed before the async loader is called (default: 2) */
27
+ enumOptionsLoaderMinChars?: number;
28
+ /** Maximum number of options to display in the combobox dropdown (default: 50) */
29
+ enumOptionsLoaderMaxResults?: number;
22
30
  editable?: boolean;
23
31
  filterable?: boolean;
24
32
  /** Default sort direction for this column. If multiple columns have defaultSort, only the first one is used. */
@@ -1 +1 @@
1
- {"version":3,"file":"ListView.d.ts","sourceRoot":"","sources":["../../../src/components/ListView.tsx"],"names":[],"mappings":"AAWA,OAAO,KAAuC,MAAM,OAAO,CAAC;AAiB5D,uEAAuE;AACvE,MAAM,WAAW,YAAY;IAC3B,kHAAkH;IAClH,IAAI,EAAE,KAAK,CAAC,aAAa,CAAC;IAC1B,uCAAuC;IACvC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,iFAAiF;IACjF,OAAO,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM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E,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAChH,oBAAoB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,IAAI,CAAC;CAC1E;AA2GD,eAAO,MAAM,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,aAAa,CA0gB5C,CAAC;;AAGF,wBAAoC"}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("react"),n=require("@fluentui/react-components"),i=require("@fluentui/react-icons"),r=require("../services/codicent.js"),o=require("../hooks/useLocalization.js");const l=n.makeStyles({container:{width:"100%",overflowX:"auto",userSelect:"text"},table:{width:"100%",borderCollapse:"collapse",backgroundColor:"#ffffff",fontSize:"14px",tableLayout:"fixed",userSelect:"text"},th:{textAlign:"left",padding:"12px 8px",borderBottom:"2px solid #e0e0e0",fontWeight:"600",backgroundColor:"#f5f5f5",position:"sticky",top:0,zIndex:1,cursor:"pointer",userSelect:"none","&:hover":{backgroundColor:"#e8e8e8"}},td:{padding:"12px 8px",borderBottom:"1px solid #e0e0e0",verticalAlign:"top",wordWrap:"break-word",overflow:"hidden",userSelect:"text"},tdTruncated:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap","@media (hover: none)":{cursor:"pointer"}},tr:{"&:hover":{backgroundColor:"#f9f9f9"}},emptyState:{padding:"20px",textAlign:"center",color:"#666"},sortIndicator:{marginLeft:"4px",fontSize:"10px"},hideOnMobile:{"@media (max-width: 768px)":{display:"none"}},dialogContent:{wordWrap:"break-word",whiteSpace:"pre-wrap",maxHeight:"60vh",overflowY:"auto"},thumbnail:{maxWidth:"50px",maxHeight:"50px",objectFit:"cover"},tooltip:{maxWidth:"600px",whiteSpace:"normal",wordWrap:"break-word"},editButton:{minWidth:"auto",padding:"4px 8px"},actionsColumn:{width:"100px",textAlign:"center"},filterInput:{width:"100%",padding:"4px 8px",fontSize:"14px",border:"1px solid #e0e0e0",borderRadius:"4px",paddingRight:"28px"},filterWrapper:{position:"relative"},clearFilterButton:{position:"absolute",right:"6px",top:"50%",transform:"translateY(-50%)",minWidth:"auto",height:"20px",padding:"0 6px",lineHeight:"18px"},filterToolbar:{display:"flex",justifyContent:"flex-end",padding:"8px",gap:"8px"},cellWithAction:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},actionIcon:{minWidth:"auto",padding:"2px",marginLeft:"4px",flexShrink:0,cursor:"pointer",opacity:.7,"&:hover":{opacity:1}},cellText:{flex:1,overflow:"hidden",textOverflow:"ellipsis"}}),a=e=>{if(/^\d{4}-\d{2}-\d{2}/.test(e)){const t=new Date(e);if(!isNaN(t.getTime()))return t.getTime()}const t=e.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})/);if(t){const e=parseInt(t[1],10),n=parseInt(t[2],10)-1,i=parseInt(t[3],10),r=new Date(i,n,e);if(r.getFullYear()===i&&r.getMonth()===n&&r.getDate()===e)return r.getTime()}return null},s=(e,t)=>{if("string"==typeof t)return e[t];for(const n of t)if(void 0!==e[n])return e[n]},c=({data:c,columns:d,canEdit:p,onEdit:h,onDelete:u,onToggleCheckbox:x,onEnumChange:m,onFilteredDataChange:f})=>{const g=l(),{visibleColumns:y,defaultSortIndex:j,defaultSortDirection:b}=t.useMemo((()=>{const e=c&&c.length>0?Array.from(new Set(c.flatMap((e=>Object.keys(e))))):[],t=(d||e.map((e=>({key:e})))).filter((e=>!e.hidden)),n=t.findIndex((e=>e.defaultSort));return{visibleColumns:t,defaultSortIndex:n,defaultSortDirection:n>=0&&t[n].defaultSort||null}}),[c,d]),[w,k]=t.useState(j>=0?j:null),[C,S]=t.useState(b),[v,N]=t.useState(!1),[W,$]=t.useState({title:"",text:""}),[D,I]=t.useState({}),[M,T]=t.useState(0),{t:A}=o.default(),O=e=>e.title?A(e.title):Array.isArray(e.key)?e.key[0]:e.key,B=e=>{const t=[];return e.hideOnMobile&&t.push(g.hideOnMobile),t.join(" ")},F=e=>null==e||"string"==typeof e&&e.startsWith("[")&&e.endsWith("]")?"":"object"==typeof e?JSON.stringify(e):String(e),L=t.useMemo((()=>{const e=[...c];if(null!==w&&C){const t=y[w];e.sort(((e,n)=>{const i=s(e,t.key),r=s(n,t.key);if(null==i)return 1;if(null==r)return-1;let o=0;if("string"==typeof i&&"string"==typeof r){const e=a(i),t=a(r);if(null!==e&&null!==t)o=e-t;else{const e=i.trim().replace(/[\s\u00a0]/g,"").replace(/,/g,""),t=r.trim().replace(/[\s\u00a0]/g,"").replace(/,/g,""),n=Number(e),l=Number(t);o=""!==e&&""!==t&&isFinite(n)&&isFinite(l)?n-l:i.localeCompare(r)}}else o="number"==typeof i&&"number"==typeof r?i-r:String(i).localeCompare(String(r));return"asc"===C?o:-o}))}return e}),[c,w,C,y]),q=t.useMemo((()=>L.filter((e=>{for(const[t,n]of Object.entries(D)){const i=parseInt(t),r=y[i],o=s(e,r.key),l=F(o).toLowerCase(),a=n.toLowerCase();if(!l.includes(a))return!1}return!0}))),[L,D,y]);t.useEffect((()=>{f&&f(q)}),[q,f]);const z="undefined"!=typeof window?window.innerHeight-250:600,E=Math.max(0,Math.floor(M/49)-5),H=Math.min(q.length,Math.ceil((M+z)/49)+5),P=q.slice(E,H),R=49*q.length,Y=49*E,_=(e,t)=>{if(void 0!==e.id)return String(e.id);return`row-${t}-${(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)})(y.slice(0,3).map((t=>String(s(e,t.key)??""))).join("-"))}`};return c&&0!==c.length?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:g.container,onScroll:e=>{T(e.currentTarget.scrollTop)},style:{maxHeight:"calc(100vh - 200px)",overflowY:"auto"},children:e.jsxs("table",{className:g.table,children:[e.jsxs("thead",{children:[e.jsxs("tr",{children:[y.map(((t,n)=>{const i=t.maxWidth?{width:`${t.maxWidth}px`,maxWidth:`${t.maxWidth}px`}:{};return e.jsxs("th",{className:`${g.th} ${B(t)}`.trim(),style:i,onClick:()=>(e=>{w===e?"asc"===C?S("desc"):"desc"===C&&(k(null),S(null)):(k(e),S("asc"))})(n),children:[O(t),w===n&&e.jsx("span",{className:g.sortIndicator,children:"asc"===C?"▲":"▼"})]},n)})),p&&e.jsx("th",{className:`${g.th} ${g.actionsColumn}`,style:{width:"100px"},children:A("Actions")})]}),e.jsxs("tr",{children:[y.map(((t,i)=>{const r=t.maxWidth?{width:`${t.maxWidth}px`,maxWidth:`${t.maxWidth}px`}:{};return e.jsx("th",{className:B(t),style:r,children:t.filterable&&e.jsxs("div",{className:g.filterWrapper,children:[e.jsx("input",{type:"text",className:g.filterInput,placeholder:A("Filter")+"...",value:D[i]||"",onChange:e=>((e,t)=>{I((n=>{const i={...n};return""===t.trim()?delete i[e]:i[e]=t,i}))})(i,e.target.value),onClick:e=>e.stopPropagation()}),(D[i]||"").length>0&&e.jsx(n.Button,{appearance:"subtle",className:g.clearFilterButton,onClick:e=>{e.stopPropagation(),(e=>{I((t=>{const n={...t};return delete n[e],n}))})(i)},children:"×"})]})},i)})),p&&e.jsx("th",{className:g.actionsColumn})]})]}),e.jsxs("tbody",{children:[E>0&&e.jsx("tr",{style:{height:`${Y}px`},children:e.jsx("td",{colSpan:y.length+(p?1:0),style:{padding:0,border:"none"}})}),P.map(((t,o)=>{const l=t._index,a="number"==typeof l?l:E+o;return e.jsxs("tr",{className:g.tr,children:[y.map(((i,o)=>{const l=s(t,i.key),c=i.format?i.format(l):F(l),d=i.maxWidth?`${g.td} ${g.tdTruncated} ${B(i)}`.trim():`${g.td} ${B(i)}`.trim(),p=()=>{window.matchMedia("(hover: hover)").matches||i.maxWidth&&c.length>0&&($({title:O(i),text:c}),N(!0))};if("file"===i.type&&c)return e.jsx("td",{className:d,onClick:p,children:e.jsx("a",{href:r.CodicentService.getFileUrl(c),target:"_blank",rel:"noopener noreferrer",children:A("Download")})},o);if("checkbox"===i.type){const r=!0===l||"true"===l||"yes"===l||"1"===l;return e.jsx("td",{className:d,children:e.jsx(n.Checkbox,{checked:r,onChange:(e,n)=>{x&&x(t,i.key,!0===n.checked,a)}})},o)}if("enum"===i.type&&i.enumOptions&&i.editable)return e.jsx("td",{className:d,children:e.jsxs(n.Select,{value:c,"aria-label":i.title?A(i.title):Array.isArray(i.key)?i.key[0]:i.key,onChange:(e,n)=>{m&&m(t,i.key,n.value,a)},style:{width:"100%"},children:[!i.enumOptions.includes(c)&&c&&e.jsx("option",{value:c,children:c}),i.enumOptions.map((t=>e.jsx("option",{value:t,children:A(t)},t)))]})},o);const h=()=>i.maxWidth&&c.length>0?e.jsx(n.Tooltip,{content:{children:c,style:{maxWidth:"600px",whiteSpace:"normal"}},relationship:"description",children:e.jsx("span",{children:c})}):c;return e.jsx("td",{className:d,onClick:p,children:i.action?e.jsxs("div",{className:g.cellWithAction,children:[e.jsx("span",{className:g.cellText,children:h()}),(()=>{if(!i.action)return null;const r=i.action,o=i.action.icon,l=e.jsx(n.Button,{appearance:"subtle",icon:e.jsx(o,{}),className:g.actionIcon,onClick:e=>{e.stopPropagation(),r.onClick(t)},size:"small"});return r.tooltip?e.jsx(n.Tooltip,{content:A(r.tooltip),relationship:"label",children:l}):l})()]}):h()},o)})),p&&(h||u)&&e.jsx("td",{className:`${g.td} ${g.actionsColumn}`,children:e.jsxs("div",{style:{display:"flex",gap:"4px",justifyContent:"center"},children:[h&&e.jsx(n.Button,{appearance:"subtle",icon:e.jsx(i.Edit24Regular,{}),className:g.editButton,onClick:()=>h(t,a),title:A("Edit")}),u&&e.jsx(n.Button,{appearance:"subtle",icon:e.jsx(i.Delete24Regular,{}),className:g.editButton,onClick:()=>u(t,a),title:A("Delete")})]})})]},_(t,a))})),H<q.length&&e.jsx("tr",{style:{height:R-Y-49*P.length+"px"},children:e.jsx("td",{colSpan:y.length+(p?1:0),style:{padding:0,border:"none"}})})]})]})}),e.jsx(n.Dialog,{open:v,onOpenChange:(e,t)=>N(t.open),children:e.jsx(n.DialogSurface,{children:e.jsxs(n.DialogBody,{children:[e.jsx(n.DialogTitle,{children:W.title}),e.jsx(n.DialogContent,{className:g.dialogContent,children:W.text})]})})})]}):e.jsx("div",{className:g.emptyState,children:A("No data to display")})};var d=t.memo(c);exports.ListView=c,exports.default=d;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("react"),n=require("@fluentui/react-components"),i=require("@fluentui/react-icons"),r=require("../services/codicent.js"),o=require("../hooks/useLocalization.js");const a=n.makeStyles({container:{width:"100%",overflowX:"auto",userSelect:"text"},table:{width:"100%",borderCollapse:"collapse",backgroundColor:"#ffffff",fontSize:"14px",tableLayout:"fixed",userSelect:"text"},th:{textAlign:"left",padding:"12px 8px",borderBottom:"2px solid #e0e0e0",fontWeight:"600",backgroundColor:"#f5f5f5",position:"sticky",top:0,zIndex:1,cursor:"pointer",userSelect:"none","&:hover":{backgroundColor:"#e8e8e8"}},td:{padding:"12px 8px",borderBottom:"1px solid #e0e0e0",verticalAlign:"top",wordWrap:"break-word",overflow:"hidden",userSelect:"text"},tdTruncated:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap","@media (hover: none)":{cursor:"pointer"}},tr:{"&:hover":{backgroundColor:"#f9f9f9"}},emptyState:{padding:"20px",textAlign:"center",color:"#666"},sortIndicator:{marginLeft:"4px",fontSize:"10px"},hideOnMobile:{"@media (max-width: 768px)":{display:"none"}},dialogContent:{wordWrap:"break-word",whiteSpace:"pre-wrap",maxHeight:"60vh",overflowY:"auto"},thumbnail:{maxWidth:"50px",maxHeight:"50px",objectFit:"cover"},tooltip:{maxWidth:"600px",whiteSpace:"normal",wordWrap:"break-word"},editButton:{minWidth:"auto",padding:"4px 8px"},actionsColumn:{width:"100px",textAlign:"center"},filterInput:{width:"100%",padding:"4px 8px",fontSize:"14px",border:"1px solid #e0e0e0",borderRadius:"4px",paddingRight:"28px"},filterWrapper:{position:"relative"},clearFilterButton:{position:"absolute",right:"6px",top:"50%",transform:"translateY(-50%)",minWidth:"auto",height:"20px",padding:"0 6px",lineHeight:"18px"},filterToolbar:{display:"flex",justifyContent:"flex-end",padding:"8px",gap:"8px"},cellWithAction:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},actionIcon:{minWidth:"auto",padding:"2px",marginLeft:"4px",flexShrink:0,cursor:"pointer",opacity:.7,"&:hover":{opacity:1}},cellText:{flex:1,overflow:"hidden",textOverflow:"ellipsis"}}),l=e=>{if(/^\d{4}-\d{2}-\d{2}/.test(e)){const t=new Date(e);if(!isNaN(t.getTime()))return t.getTime()}const t=e.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})/);if(t){const e=parseInt(t[1],10),n=parseInt(t[2],10)-1,i=parseInt(t[3],10),r=new Date(i,n,e);if(r.getFullYear()===i&&r.getMonth()===n&&r.getDate()===e)return r.getTime()}return null},s=(e,t)=>{if("string"==typeof t)return e[t];for(const n of t)if(void 0!==e[n])return e[n]},c=({value:i,options:r,optionsLoader:o,minChars:a=2,maxResults:l=50,columnKey:s,item:c,actualIndex:d,onEnumChange:u,label:p,t:h})=>{const[x,m]=t.useState(i),[f,g]=t.useState([]),[y,j]=t.useState(!1),b=t.useRef(null);t.useEffect((()=>{m(i)}),[i]),t.useEffect((()=>{if(o){if(!(x.length<a))return b.current&&clearTimeout(b.current),b.current=setTimeout((async()=>{j(!0);try{const e=await o(x);g(e.slice(0,l))}finally{j(!1)}}),250),()=>{b.current&&clearTimeout(b.current)};g([])}}),[x,o,a,l]);const C=t.useMemo((()=>(r??[]).filter((e=>e.toLowerCase().includes(x.toLowerCase()))).slice(0,l)),[r,x,l]),w=o?f:C;return e.jsx(n.Combobox,{value:x,freeform:!0,"aria-label":p,placeholder:y?h("Loading..."):o&&x.length<a?h(`Type ${a}+ characters to search...`):void 0,onChange:e=>m(e.target.value),onOptionSelect:(e,t)=>{t.optionValue&&(m(t.optionValue),u&&u(c,s,t.optionValue,d))},onBlur:()=>{u&&u(c,s,x,d)},style:{width:"100%"},children:w.map((t=>e.jsx(n.Option,{value:t,children:t},t)))})},d=({data:d,columns:u,canEdit:p,onEdit:h,onDelete:x,onToggleCheckbox:m,onEnumChange:f,onFilteredDataChange:g})=>{const y=a(),{visibleColumns:j,defaultSortIndex:b,defaultSortDirection:C}=t.useMemo((()=>{const e=d&&d.length>0?Array.from(new Set(d.flatMap((e=>Object.keys(e))))):[],t=(u||e.map((e=>({key:e})))).filter((e=>!e.hidden)),n=t.findIndex((e=>e.defaultSort));return{visibleColumns:t,defaultSortIndex:n,defaultSortDirection:n>=0&&t[n].defaultSort||null}}),[d,u]),[w,k]=t.useState(b>=0?b:null),[v,S]=t.useState(C),[N,W]=t.useState(!1),[O,$]=t.useState({title:"",text:""}),[L,M]=t.useState({}),[T,I]=t.useState(0),{t:A}=o.default(),D=e=>e.title?A(e.title):Array.isArray(e.key)?e.key[0]:e.key,B=e=>{const t=[];return e.hideOnMobile&&t.push(y.hideOnMobile),t.join(" ")},E=e=>null==e||"string"==typeof e&&e.startsWith("[")&&e.endsWith("]")?"":"object"==typeof e?JSON.stringify(e):String(e),F=t.useMemo((()=>{const e=[...d];if(null!==w&&v){const t=j[w];e.sort(((e,n)=>{const i=s(e,t.key),r=s(n,t.key);if(null==i)return 1;if(null==r)return-1;let o=0;if("string"==typeof i&&"string"==typeof r){const e=l(i),t=l(r);if(null!==e&&null!==t)o=e-t;else{const e=i.trim().replace(/[\s\u00a0]/g,"").replace(/,/g,""),t=r.trim().replace(/[\s\u00a0]/g,"").replace(/,/g,""),n=Number(e),a=Number(t);o=""!==e&&""!==t&&isFinite(n)&&isFinite(a)?n-a:i.localeCompare(r)}}else o="number"==typeof i&&"number"==typeof r?i-r:String(i).localeCompare(String(r));return"asc"===v?o:-o}))}return e}),[d,w,v,j]),R=t.useMemo((()=>F.filter((e=>{for(const[t,n]of Object.entries(L)){const i=parseInt(t),r=j[i],o=s(e,r.key),a=E(o).toLowerCase(),l=n.toLowerCase();if(!a.includes(l))return!1}return!0}))),[F,L,j]);t.useEffect((()=>{g&&g(R)}),[R,g]);const q="undefined"!=typeof window?window.innerHeight-250:600,z=Math.max(0,Math.floor(T/49)-5),H=Math.min(R.length,Math.ceil((T+q)/49)+5),P=R.slice(z,H),V=49*R.length,Y=49*z,_=(e,t)=>{if(void 0!==e.id)return String(e.id);return`row-${t}-${(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)})(j.slice(0,3).map((t=>String(s(e,t.key)??""))).join("-"))}`};return d&&0!==d.length?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:y.container,onScroll:e=>{I(e.currentTarget.scrollTop)},style:{maxHeight:"calc(100vh - 200px)",overflowY:"auto"},children:e.jsxs("table",{className:y.table,children:[e.jsxs("thead",{children:[e.jsxs("tr",{children:[j.map(((t,n)=>{const i=t.maxWidth?{width:`${t.maxWidth}px`,maxWidth:`${t.maxWidth}px`}:{};return e.jsxs("th",{className:`${y.th} ${B(t)}`.trim(),style:i,onClick:()=>(e=>{w===e?"asc"===v?S("desc"):"desc"===v&&(k(null),S(null)):(k(e),S("asc"))})(n),children:[D(t),w===n&&e.jsx("span",{className:y.sortIndicator,children:"asc"===v?"▲":"▼"})]},n)})),p&&e.jsx("th",{className:`${y.th} ${y.actionsColumn}`,style:{width:"100px"},children:A("Actions")})]}),e.jsxs("tr",{children:[j.map(((t,i)=>{const r=t.maxWidth?{width:`${t.maxWidth}px`,maxWidth:`${t.maxWidth}px`}:{};return e.jsx("th",{className:B(t),style:r,children:t.filterable&&e.jsxs("div",{className:y.filterWrapper,children:[e.jsx("input",{type:"text",className:y.filterInput,placeholder:A("Filter")+"...",value:L[i]||"",onChange:e=>((e,t)=>{M((n=>{const i={...n};return""===t.trim()?delete i[e]:i[e]=t,i}))})(i,e.target.value),onClick:e=>e.stopPropagation()}),(L[i]||"").length>0&&e.jsx(n.Button,{appearance:"subtle",className:y.clearFilterButton,onClick:e=>{e.stopPropagation(),(e=>{M((t=>{const n={...t};return delete n[e],n}))})(i)},children:"×"})]})},i)})),p&&e.jsx("th",{className:y.actionsColumn})]})]}),e.jsxs("tbody",{children:[z>0&&e.jsx("tr",{style:{height:`${Y}px`},children:e.jsx("td",{colSpan:j.length+(p?1:0),style:{padding:0,border:"none"}})}),P.map(((t,o)=>{const a=t._index,l="number"==typeof a?a:z+o;return e.jsxs("tr",{className:y.tr,children:[j.map(((i,o)=>{const a=s(t,i.key),d=i.format?i.format(a):E(a),u=i.maxWidth?`${y.td} ${y.tdTruncated} ${B(i)}`.trim():`${y.td} ${B(i)}`.trim(),p=()=>{window.matchMedia("(hover: hover)").matches||i.maxWidth&&d.length>0&&($({title:D(i),text:d}),W(!0))};if("file"===i.type&&d)return e.jsx("td",{className:u,onClick:p,children:e.jsx("a",{href:r.CodicentService.getFileUrl(d),target:"_blank",rel:"noopener noreferrer",children:A("Download")})},o);if("checkbox"===i.type){const r=!0===a||"true"===a||"yes"===a||"1"===a;return e.jsx("td",{className:u,children:e.jsx(n.Checkbox,{checked:r,onChange:(e,n)=>{m&&m(t,i.key,!0===n.checked,l)}})},o)}if("enum"===i.type&&i.enumOptions&&i.editable)return e.jsx("td",{className:u,children:e.jsxs(n.Select,{value:d,"aria-label":i.title?A(i.title):Array.isArray(i.key)?i.key[0]:i.key,onChange:(e,n)=>{f&&f(t,i.key,n.value,l)},style:{width:"100%"},children:[!i.enumOptions.includes(d)&&d&&e.jsx("option",{value:d,children:d}),i.enumOptions.map((t=>e.jsx("option",{value:t,children:A(t)},t)))]})},o);if("combobox"===i.type&&i.editable&&(i.enumOptions||i.enumOptionsLoader))return e.jsx("td",{className:u,children:e.jsx(c,{value:d,options:i.enumOptions,optionsLoader:i.enumOptionsLoader,minChars:i.enumOptionsLoaderMinChars,maxResults:i.enumOptionsLoaderMaxResults,columnKey:i.key,item:t,actualIndex:l,onEnumChange:f,label:i.title?A(i.title):Array.isArray(i.key)?i.key[0]:i.key,t:A})},o);const h=()=>i.maxWidth&&d.length>0?e.jsx(n.Tooltip,{content:{children:d,style:{maxWidth:"600px",whiteSpace:"normal"}},relationship:"description",children:e.jsx("span",{children:d})}):d,x=()=>{if(!i.action)return null;const r=i.action,o=i.action.icon,a=e.jsx(n.Button,{appearance:"subtle",icon:e.jsx(o,{}),className:y.actionIcon,onClick:e=>{e.stopPropagation(),r.onClick(t)},size:"small"});return r.tooltip?e.jsx(n.Tooltip,{content:A(r.tooltip),relationship:"label",children:a}):a};return e.jsx("td",{className:u,onClick:p,children:i.action?e.jsxs("div",{className:y.cellWithAction,children:[i.action.iconLeft&&x(),e.jsx("span",{className:y.cellText,children:h()}),!i.action.iconLeft&&x()]}):h()},o)})),p&&(h||x)&&e.jsx("td",{className:`${y.td} ${y.actionsColumn}`,children:e.jsxs("div",{style:{display:"flex",gap:"4px",justifyContent:"center"},children:[h&&e.jsx(n.Button,{appearance:"subtle",icon:e.jsx(i.Edit24Regular,{}),className:y.editButton,onClick:()=>h(t,l),title:A("Edit")}),x&&e.jsx(n.Button,{appearance:"subtle",icon:e.jsx(i.Delete24Regular,{}),className:y.editButton,onClick:()=>x(t,l),title:A("Delete")})]})})]},_(t,l))})),H<R.length&&e.jsx("tr",{style:{height:V-Y-49*P.length+"px"},children:e.jsx("td",{colSpan:j.length+(p?1:0),style:{padding:0,border:"none"}})})]})]})}),e.jsx(n.Dialog,{open:N,onOpenChange:(e,t)=>W(t.open),children:e.jsx(n.DialogSurface,{children:e.jsxs(n.DialogBody,{children:[e.jsx(n.DialogTitle,{children:O.title}),e.jsx(n.DialogContent,{className:y.dialogContent,children:O.text})]})})})]}):e.jsx("div",{className:y.emptyState,children:A("No data to display")})};var u=t.memo(d);exports.ListView=d,exports.default=u;
@@ -1 +1 @@
1
- {"version":3,"file":"RecordModal.d.ts","sourceRoot":"","sources":["../../../src/components/RecordModal.tsx"],"names":[],"mappings":"AAWA,OAAO,KAA8B,MAAM,OAAO,CAAC;AAkBnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAoB9C,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,OAAO,CAAC;IACd,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD,OAAO,EAAE,gBAAgB,EAAE,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC,gBAAgB,CAsIlD,CAAC;AAEF,eAAe,WAAW,CAAC"}
1
+ {"version":3,"file":"RecordModal.d.ts","sourceRoot":"","sources":["../../../src/components/RecordModal.tsx"],"names":[],"mappings":"AAWA,OAAO,KAAuC,MAAM,OAAO,CAAC;AAoB5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AA6G9C,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,OAAO,CAAC;IACd,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD,OAAO,EAAE,gBAAgB,EAAE,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC,gBAAgB,CAuJlD,CAAC;AAEF,eAAe,WAAW,CAAC"}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),a=require("react"),r=require("@fluentui/react-components"),l=require("../hooks/useLocalization.js");const n=r.makeStyles({surface:{backgroundColor:r.tokens.colorNeutralBackground1},content:{display:"flex",flexDirection:"column",gap:"16px",minWidth:"400px",maxHeight:"60vh",overflowY:"auto"},field:{display:"flex",flexDirection:"column"}}),o=({open:o,onClose:t,onSave:i,columns:s,initialData:c,title:d})=>{const u=n(),{t:p}=l.default(),[x,h]=a.useState({}),[f,y]=a.useState(!1);a.useEffect((()=>{o&&h(c||{})}),[o,c]);const g=e=>Array.isArray(e.key)?e.key[0]:e.key,j=e=>{if(Array.isArray(e.key))for(const a of e.key)if(void 0!==x[a])return a;return g(e)},m=(e,a)=>{const r=j(e);h((e=>({...e,[r]:a})))},k=s.filter((e=>!e.hidden&&"file"!==e.type&&"createdAt"!==g(e)));return e.jsx(r.Dialog,{open:o,onOpenChange:(e,a)=>!f&&!1===a.open&&t(),children:e.jsx(r.DialogSurface,{className:u.surface,backdrop:{style:{backgroundColor:"rgba(0, 0, 0, 0.4)"}},children:e.jsxs(r.DialogBody,{children:[e.jsx(r.DialogTitle,{children:d||p(c?"Edit Record":"Add Record")}),e.jsx(r.DialogContent,{className:u.content,children:k.map(((a,l)=>{const n=g(a),o=(e=>{const a=j(e);return x[a]})(a),t=a.title||n;return"checkbox"===a.type?e.jsx(r.Field,{label:t,className:u.field,children:e.jsx(r.Checkbox,{checked:!0===o||"true"===o||"yes"===o||"1"===o,onChange:(e,r)=>m(a,r.checked)})},l):"textarea"===a.type?e.jsx(r.Field,{label:t,className:u.field,children:e.jsx(r.Textarea,{value:String(o??""),rows:a.rows??3,onChange:(e,r)=>m(a,r.value),placeholder:p("Enter")+" "+t.toLowerCase(),resize:"vertical"})},l):"enum"===a.type&&a.enumOptions?e.jsx(r.Field,{label:t,className:u.field,children:e.jsx(r.Select,{value:String(o??""),onChange:(e,r)=>m(a,r.value),children:a.enumOptions.map((a=>e.jsx("option",{value:a,children:a||p("(None)")},a)))})},l):e.jsx(r.Field,{label:t,className:u.field,children:e.jsx(r.Input,{value:String(o??""),onChange:(e,r)=>m(a,r.value),placeholder:p("Enter")+" "+t.toLowerCase()})},l)}))}),e.jsxs(r.DialogActions,{children:[e.jsx(r.Button,{appearance:"secondary",onClick:t,disabled:f,children:p("Cancel")}),e.jsx(r.Button,{appearance:"primary",onClick:async()=>{y(!0);try{await i(x),t()}catch(e){console.error("Failed to save record:",e)}finally{y(!1)}},disabled:f,children:p(f?"Saving...":"Save")})]})]})})})};exports.RecordModal=o,exports.default=o;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),a=require("react"),t=require("@fluentui/react-components"),o=require("../hooks/useLocalization.js");const n=t.makeStyles({surface:{backgroundColor:t.tokens.colorNeutralBackground1},content:{display:"flex",flexDirection:"column",gap:"16px",minWidth:"400px",maxHeight:"60vh",overflowY:"auto"},field:{display:"flex",flexDirection:"column"}}),r=({value:o,options:n,optionsLoader:r,minChars:l=2,maxResults:s=50,label:i,onChange:c,t:u})=>{const[d,p]=a.useState(o),[h,x]=a.useState([]),[m,f]=a.useState(!1),y=a.useRef(null);a.useEffect((()=>{p(o)}),[o]),a.useEffect((()=>{if(r){if(!(d.length<l))return y.current&&clearTimeout(y.current),y.current=setTimeout((async()=>{f(!0);try{const e=await r(d);x(e.slice(0,s))}finally{f(!1)}}),250),()=>{y.current&&clearTimeout(y.current)};x([])}}),[d,r,l,s]);const g=a.useMemo((()=>(n??[]).filter((e=>e.toLowerCase().includes(d.toLowerCase()))).slice(0,s)),[n,d,s]),j=r?h:g;return e.jsx(t.Combobox,{value:d,freeform:!0,"aria-label":i,placeholder:m?u("Loading..."):r&&d.length<l?u(`Type ${l}+ characters to search...`):void 0,onChange:e=>p(e.target.value),onOptionSelect:(e,a)=>{a.optionValue&&(p(a.optionValue),c(a.optionValue))},onBlur:()=>c(d),style:{width:"100%"},children:j.map((a=>e.jsx(t.Option,{value:a,children:a},a)))})},l=({open:l,onClose:s,onSave:i,columns:c,initialData:u,title:d})=>{const p=n(),{t:h}=o.default(),[x,m]=a.useState({}),[f,y]=a.useState(!1);a.useEffect((()=>{l&&m(u||{})}),[l,u]);const g=e=>Array.isArray(e.key)?e.key[0]:e.key,j=e=>{if(Array.isArray(e.key))for(const a of e.key)if(void 0!==x[a])return a;return g(e)},C=(e,a)=>{const t=j(e);m((e=>({...e,[t]:a})))},v=c.filter((e=>!e.hidden&&"file"!==e.type&&"createdAt"!==g(e)));return e.jsx(t.Dialog,{open:l,onOpenChange:(e,a)=>!f&&!1===a.open&&s(),children:e.jsx(t.DialogSurface,{className:p.surface,backdrop:{style:{backgroundColor:"rgba(0, 0, 0, 0.4)"}},children:e.jsxs(t.DialogBody,{children:[e.jsx(t.DialogTitle,{children:d||h(u?"Edit Record":"Add Record")}),e.jsx(t.DialogContent,{className:p.content,children:v.map(((a,o)=>{const n=g(a),l=(e=>{const a=j(e);return x[a]})(a),s=a.title||n;return"checkbox"===a.type?e.jsx(t.Field,{label:s,className:p.field,children:e.jsx(t.Checkbox,{checked:!0===l||"true"===l||"yes"===l||"1"===l,onChange:(e,t)=>C(a,t.checked)})},o):"textarea"===a.type?e.jsx(t.Field,{label:s,className:p.field,children:e.jsx(t.Textarea,{value:String(l??""),rows:a.rows??3,onChange:(e,t)=>C(a,t.value),placeholder:h("Enter")+" "+s.toLowerCase(),resize:"vertical"})},o):"enum"===a.type&&a.enumOptions?e.jsx(t.Field,{label:s,className:p.field,children:e.jsx(t.Select,{value:String(l??""),onChange:(e,t)=>C(a,t.value),children:a.enumOptions.map((a=>e.jsx("option",{value:a,children:a||h("(None)")},a)))})},o):"combobox"===a.type&&(a.enumOptions||a.enumOptionsLoader)?e.jsx(t.Field,{label:s,className:p.field,children:e.jsx(r,{value:String(l??""),options:a.enumOptions,optionsLoader:a.enumOptionsLoader,minChars:a.enumOptionsLoaderMinChars,maxResults:a.enumOptionsLoaderMaxResults,label:s,onChange:e=>C(a,e),t:h})},o):e.jsx(t.Field,{label:s,className:p.field,children:e.jsx(t.Input,{value:String(l??""),onChange:(e,t)=>C(a,t.value),placeholder:h("Enter")+" "+s.toLowerCase()})},o)}))}),e.jsxs(t.DialogActions,{children:[e.jsx(t.Button,{appearance:"secondary",onClick:s,disabled:f,children:h("Cancel")}),e.jsx(t.Button,{appearance:"primary",onClick:async()=>{y(!0);try{await i(x),s()}catch(e){console.error("Failed to save record:",e)}finally{y(!1)}},disabled:f,children:h(f?"Saving...":"Save")})]})]})})})};exports.RecordModal=l,exports.default=l;
@@ -0,0 +1,81 @@
1
+ import { Dispatch } from "react";
2
+ import { AppInfo, CodicentService } from "../services/codicent";
3
+ import { StateContext } from "../utils/appState";
4
+ export type AppPhase = "authenticating" | "notAuthenticated" | "checkingCodicentAccess" | "registering" | "registered" | "loadingUser" | "checkingPurchase" | "needsPurchase" | "gettingApps" | "creatingApp" | "checkingAccess" | "noAccess" | "hasAccess" | "loggingOut" | "error" | "anonymous" | "restoringFromCache" | "validatingCache";
5
+ export type AppAction = {
6
+ type: "LOGOUT";
7
+ } | {
8
+ type: "NOT_AUTHENTICATED";
9
+ } | {
10
+ type: "AUTHENTICATED";
11
+ accessToken: string;
12
+ user: {
13
+ sub: string;
14
+ email: string;
15
+ };
16
+ } | {
17
+ type: "REGISTERED";
18
+ nickname: string;
19
+ } | {
20
+ type: "NOT_REGISTERED";
21
+ } | {
22
+ type: "REGISTER_AUTO_SUCCESS";
23
+ nickname: string;
24
+ } | {
25
+ type: "REGISTER_AUTO_FAIL";
26
+ error: string;
27
+ errorType?: StateContext["errorType"];
28
+ } | {
29
+ type: "USER_LOADED";
30
+ name: string;
31
+ } | {
32
+ type: "PURCHASE_VALID";
33
+ } | {
34
+ type: "PURCHASE_INVALID";
35
+ } | {
36
+ type: "APPS_LOADED";
37
+ apps: AppInfo[];
38
+ } | {
39
+ type: "APPS_FAILED";
40
+ error: string;
41
+ } | {
42
+ type: "APP_CREATED";
43
+ appId: string;
44
+ } | {
45
+ type: "APP_CREATE_FAILED";
46
+ error: string;
47
+ } | {
48
+ type: "SET_ANONYMOUS";
49
+ } | {
50
+ type: "SET_SELECTED_APP";
51
+ appId: string;
52
+ } | {
53
+ type: "UPDATE_CONTEXT";
54
+ updates: Partial<StateContext>;
55
+ } | {
56
+ type: "CACHE_VALIDATED";
57
+ } | {
58
+ type: "CACHE_VALIDATION_FAILED";
59
+ lenient: boolean;
60
+ };
61
+ export interface AppReducerState {
62
+ phase: AppPhase;
63
+ context: StateContext;
64
+ }
65
+ /** Phases where isBusy() should return true */
66
+ export declare const BUSY_PHASES: AppPhase[];
67
+ export declare const isBusyPhase: (phase: AppPhase) => boolean;
68
+ export declare function appStateReducer(state: AppReducerState, action: AppAction): AppReducerState;
69
+ /**
70
+ * Creates the initial reducer state. Reads the cache synchronously so the
71
+ * very first render is already in the correct phase (no flicker).
72
+ */
73
+ export declare function createInitialState(): AppReducerState;
74
+ /** Persist the current session to localStorage cache. */
75
+ export declare function saveSession(context: StateContext): void;
76
+ /**
77
+ * Runs the three background validation checks (registration, purchase, apps)
78
+ * after restoring from cache. Dispatches CACHE_VALIDATED or CACHE_VALIDATION_FAILED.
79
+ */
80
+ export declare function runBackgroundValidation(service: CodicentService, context: StateContext, dispatch: Dispatch<AppAction>): Promise<void>;
81
+ //# sourceMappingURL=useAppState.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAppState.d.ts","sourceRoot":"","sources":["../../../src/hooks/useAppState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACjC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAGhE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGjD,MAAM,MAAM,QAAQ,GAChB,gBAAgB,GAChB,kBAAkB,GAClB,wBAAwB,GACxB,aAAa,GACb,YAAY,GACZ,aAAa,GACb,kBAAkB,GAClB,eAAe,GACf,aAAa,GACb,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EAAE,kBAAkB,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC3C;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,OAAO,EAAE,OAAO,CAAC,YAAY,CAAC,CAAA;CAAE,GAC1D;IAAE,IAAI,EAAE,iBAAiB,CAAA;CAAE,GAC3B;IAAE,IAAI,EAAE,yBAAyB,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC;AAE1D,MAAM,WAAW,eAAe;IAC9B,KAAK,EAAE,QAAQ,CAAC;IAChB,OAAO,EAAE,YAAY,CAAC;CACvB;AAED,+CAA+C;AAC/C,eAAO,MAAM,WAAW,EAAE,QAAQ,EASjC,CAAC;AAEF,eAAO,MAAM,WAAW,UAAW,QAAQ,YAAgC,CAAC;AA+C5E,wBAAgB,eAAe,CAAC,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,SAAS,GAAG,eAAe,CAiM1F;AAcD;;;GAGG;AACH,wBAAgB,kBAAkB,IAAI,eAAe,CA+BpD;AAED,yDAAyD;AACzD,wBAAgB,WAAW,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAkBvD;AAED;;;GAGG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,YAAY,EACrB,QAAQ,EAAE,QAAQ,CAAC,SAAS,CAAC,GAC5B,OAAO,CAAC,IAAI,CAAC,CAqCf"}
@@ -0,0 +1 @@
1
+ "use strict";var e=require("../config/index.js"),t=require("../utils/cacheManager.js");const s=["checkingCodicentAccess","registering","loadingUser","checkingPurchase","gettingApps","creatingApp","checkingAccess","loggingOut"];function a(){const t={isAuthenticated:!1,isRegistered:void 0,hasValidPurchase:void 0,hasAccess:!1,selectedApp:void 0,error:null,errorType:void 0,accessToken:void 0,nickname:void 0,apps:[],hasApps:!1,appsLoaded:!1,user:void 0,name:void 0,isAnonymous:void 0,isFromCache:void 0,needsValidation:void 0};return e.getConfigValue("APP_NAME")?localStorage.removeItem("selectedApp"):t.selectedApp=localStorage.getItem("selectedApp")||void 0,e.getConfigValue("APP_PREFIX")&&t.selectedApp&&!t.selectedApp.startsWith(e.getConfigValue("APP_PREFIX"))&&(t.selectedApp=void 0),t}function n(s){if(!e.getConfigValue("ENABLE_STATE_CACHE"))return;if(!s.nickname||!s.selectedApp)return;const a={nickname:s.nickname,name:s.name||"",selectedApp:s.selectedApp,apps:s.apps||[],hasValidPurchase:s.hasValidPurchase||!1,isRegistered:s.isRegistered||!1,cachedAt:Date.now(),expiresAt:Date.now()+e.getConfigValue("SESSION_CACHE_TTL"),version:"1.0.0"};t.stateMachineCacheManager.set("user_session",a,e.getConfigValue("SESSION_CACHE_TTL")),console.log("AppState: Saved session to cache")}exports.BUSY_PHASES=s,exports.appStateReducer=function(t,s){switch(s.type){case"LOGOUT":return{phase:"loggingOut",context:a()};case"NOT_AUTHENTICATED":return"loggingOut"===t.phase||"anonymous"===t.phase?t:"hasAccess"===t.phase?{phase:"loggingOut",context:a()}:{phase:"notAuthenticated",context:a()};case"AUTHENTICATED":{const{accessToken:e,user:a}=s;return"anonymous"===t.phase?t:"hasAccess"===t.phase&&t.context.isFromCache?{...t,context:{...t.context,accessToken:e,user:a,isAuthenticated:!0}}:"hasAccess"===t.phase?t:{phase:"checkingCodicentAccess",context:{...t.context,isAuthenticated:!0,accessToken:e,user:a}}}case"REGISTERED":case"REGISTER_AUTO_SUCCESS":return localStorage.setItem("nickname",s.nickname),{phase:"loadingUser",context:{...t.context,isRegistered:!0,nickname:s.nickname}};case"NOT_REGISTERED":return{phase:"registering",context:{...t.context,isRegistered:!1}};case"REGISTER_AUTO_FAIL":return{phase:"error",context:{...t.context,error:s.error,errorType:s.errorType}};case"USER_LOADED":return{phase:e.getConfigValue("SUBSCRIPTION_NEEDED")?"checkingPurchase":"gettingApps",context:{...t.context,name:s.name}};case"PURCHASE_VALID":return{phase:"gettingApps",context:{...t.context,hasValidPurchase:!0}};case"PURCHASE_INVALID":return{phase:"needsPurchase",context:{...t.context,hasValidPurchase:!1}};case"APPS_LOADED":{const{apps:a}=s,n=e.getConfigValue("APP_NAME")||void 0,c=e.getConfigValue("APP_PREFIX")||void 0,r=c?a.filter((e=>e.id.startsWith(c))):a;if(0===r.length&&!n)return{phase:"creatingApp",context:{...t.context,apps:r,hasApps:!1,appsLoaded:!0,selectedApp:void 0}};const o=function(e,t,s){return s?e.some((e=>e.id===s))?s:null:t&&e.some((e=>e.id===t))?t:e.length>0?e[0].id:null}(r,t.context.selectedApp,n);return o?{phase:"hasAccess",context:{...t.context,apps:r,hasApps:!0,appsLoaded:!0,selectedApp:o,hasAccess:!0}}:{phase:"noAccess",context:{...t.context,apps:r,hasApps:r.length>0,appsLoaded:!0}}}case"APPS_FAILED":return{phase:"error",context:{...t.context,error:s.error,errorType:"ErrorGettingApps"}};case"APP_CREATED":return{phase:"hasAccess",context:{...t.context,selectedApp:s.appId,apps:[...t.context.apps||[],{id:s.appId,title:s.appId,logo:""}],hasApps:!0,appsLoaded:!0,hasAccess:!0}};case"APP_CREATE_FAILED":return{phase:"error",context:{...t.context,error:s.error,errorType:"ErrorCreatingApp"}};case"SET_ANONYMOUS":return{phase:"anonymous",context:{...t.context,isAnonymous:!0}};case"SET_SELECTED_APP":return localStorage.setItem("selectedApp",s.appId),"hasAccess"===t.phase?{...t,context:{...t.context,selectedApp:s.appId}}:{phase:"gettingApps",context:{...t.context,selectedApp:s.appId,hasApps:!1,appsLoaded:!1}};case"UPDATE_CONTEXT":{const e={...t.context,...s.updates},a=["authenticating","checkingCodicentAccess","registering","loadingUser","checkingPurchase","gettingApps","creatingApp","checkingAccess","notAuthenticated"];if("error"in s.updates&&s.updates.error&&a.includes(t.phase))return{phase:"error",context:e};if("needsPurchase"===t.phase&&"hasValidPurchase"in s.updates&&void 0===s.updates.hasValidPurchase)return{phase:"checkingPurchase",context:{...e,hasValidPurchase:void 0}};if("error"===t.phase&&"error"in s.updates&&null===s.updates.error){const s=t.context.errorType;let a="checkingCodicentAccess";return"ErrorLoadingUser"===s?a="loadingUser":"ErrorCheckingPurchase"===s?a="checkingPurchase":"ErrorGettingApps"===s?a="gettingApps":"ErrorCreatingApp"===s?a="creatingApp":"ErrorCheckingAccess"===s&&(a="checkingAccess"),{phase:a,context:{...e,error:null,errorType:void 0}}}return{...t,context:e}}case"CACHE_VALIDATED":return{...t,context:{...t.context,needsValidation:!1,isFromCache:!1}};case"CACHE_VALIDATION_FAILED":return s.lenient?{...t,context:{...t.context,needsValidation:!0}}:{phase:"authenticating",context:a()};default:return t}},exports.createInitialState=function(){if(e.getConfigValue("ENABLE_STATE_CACHE")){const s=t.stateMachineCacheManager.get("user_session");if(s&&function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.nickname&&"string"==typeof t.selectedApp&&Array.isArray(t.apps)&&"boolean"==typeof t.isRegistered&&"boolean"==typeof t.hasValidPurchase}(s.data)){const t=s.data;return console.log("AppState: Restoring from cache",{nickname:t.nickname,selectedApp:t.selectedApp,appsCount:t.apps.length,age:Math.round((Date.now()-s.cachedAt)/1e3)+"s"}),{phase:"hasAccess",context:{...a(),nickname:t.nickname,name:t.name,selectedApp:t.selectedApp,apps:t.apps,hasValidPurchase:t.hasValidPurchase,isRegistered:t.isRegistered,hasAccess:!0,hasApps:t.apps.length>0,appsLoaded:!0,isFromCache:!0,needsValidation:Boolean(e.getConfigValue("VALIDATE_CACHE_IN_BACKGROUND"))}}}}return{phase:"authenticating",context:a()}},exports.isBusyPhase=e=>s.includes(e),exports.runBackgroundValidation=async function(t,s,a){try{const[c,r,o]=await Promise.all([t.getNickname().then((e=>e===s.nickname)).catch((()=>!1)),e.getConfigValue("SUBSCRIPTION_NEEDED")?t.checkSubscriptionStatus().then((e=>("active"===e||"trialing"===e)===s.hasValidPurchase)).catch((()=>!1)):Promise.resolve(!0),t.getApps().then((t=>{if(!t)return!1;const a=e.getConfigValue("APP_PREFIX")||void 0,n=a?t.filter((e=>e.id.startsWith(a))):t,c=s.apps||[];return n.length===c.length&&n.every((e=>c.some((t=>t.id===e.id))))})).catch((()=>!1))]);if(c&&r&&o)n(s),a({type:"CACHE_VALIDATED"});else{a({type:"CACHE_VALIDATION_FAILED",lenient:"strict"!==e.getConfigValue("CACHE_FAILURE_MODE")})}}catch{}},exports.saveSession=n;
@@ -1 +1 @@
1
- {"version":3,"file":"useAuthState.d.ts","sourceRoot":"","sources":["../../../src/hooks/useAuthState.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,QAAQ,EAAqB,MAAM,oBAAoB,CAAC;AAC9G,OAAO,EAAE,eAAe,EAAE,MAAM,IAAI,CAAC;AAUrC,MAAM,WAAW,YAAY;IAC3B,eAAe,EAAE,OAAO,CAAC;IACzB,YAAY,EAAE,OAAO,GAAG,SAAS,CAAC;IAClC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,OAAO,CAAC;IAInB,IAAI,EAAE,GAAG,CAAC;IACV,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,IAAI,CAAC;IACnB,YAAY,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACpD,eAAe,EAAE,eAAe,CAAC;IACjC,iBAAiB,EAAE,CAAC,OAAO,CAAC,EAAE,oBAAoB,CAAC,QAAQ,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/E,iBAAiB,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACrD;AAED,MAAM,WAAW,gBAAgB;IAC/B,wFAAwF;IACxF,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,EAAE,CAAC,CAAC;IACzG,8FAA8F;IA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W,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,EAAE,CAAC,CAAC;IACzG,8FAA8F;IAC9F,UAAU,CAAC,EAAE,CACX,OAAO,EAAE,eAAe,EACxB,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,KAChB,OAAO,CAAC,MAAM,CAAC,CAAC;CACtB;AAED,QAAA,MAAM,YAAY,UAAW,qBAAqB,YAAY,gBAAgB,KAAG,YA+QhF,CAAC;AAEF,eAAe,YAAY,CAAC"}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),r=require("../services/codicent.js");require("../components/Markdown.js"),require("../components/Textarea.js"),require("../components/Button.js"),require("../components/CompoundButton.js"),require("react/jsx-runtime"),require("@fluentui/react-components"),require("../components/Spinner.js"),require("../components/TextHeader.js"),require("../components/TypingIndicator.js"),require("../components/Dialog.js"),require("../components/ChatInput.js"),require("../components/CombinedPlaceholderDialog.js"),require("../components/ChatMessage.js"),require("../components/Header.js"),require("@fluentui/react-icons");var o=require("../config/index.js");require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("../_virtual/index.js"),require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js"),require("./useLocalization.js"),require("./useAppStyles.js"),require("../components/FileThumbnail.js"),require("../components/MessageInput.js"),require("../components/UploadFile.js"),require("../components/SnapFooter.js"),require("../components/Profile.js"),require("../components/MessageItem.js"),require("../components/Content.js"),require("../components/AiInput.js"),require("../components/SearchBox.js"),require("../components/DataMessagePicker.js"),require("../components/HtmlView.js"),require("../components/Footer.js"),require("../components/Page.js"),require("../components/QrCodeDialog.js"),require("../components/QrScanner.js"),require("../components/OfflineMessage.js"),require("../components/LanguageSelector.js"),require("../components/ListView.js"),require("../components/RecordModal.js"),require("../components/BulkUploadDialog.js"),require("../components/CookieBanner.js"),require("../pages/AppFrame.js"),require("../pages/Chat.js"),require("../pages/Compose.js"),require("../pages/Snap.js"),require("../pages/Search.js"),require("../pages/Login.js"),require("../pages/CrmPage.js"),require("../pages/CrmPagePersistent.js"),require("../pages/ImageView.js"),require("../pages/FormInvite.js"),require("../pages/FormAccept.js"),require("../pages/Sales.js"),require("../pages/Purchase.js"),require("../pages/QrScan.js"),require("react-dom/client"),require("react-router-dom"),require("../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js");exports.default=(s,n)=>{const{isAuthenticated:t,getAccessTokenSilently:i,user:a,isLoading:u,logout:c,getAccessTokenWithPopup:l,loginWithRedirect:g,loginWithPopup:p}=s,[q,m]=e.useState(null),[j,C]=e.useState(void 0),[E,P]=e.useState(null),[d,_]=e.useState(""),T=e.useMemo((()=>new r.CodicentService({API_BASE_URL:o.getConfigValue("API_BASE_URL"),PUBSUB_URL:o.getConfigValue("PUBSUB_URL"),APP_LOG_CODICENT:o.getConfigValue("APP_LOG_CODICENT"),APP_LOG_TOKEN:o.getConfigValue("APP_LOG_TOKEN"),APP_NAME:o.getConfigValue("APP_NAME"),APP_PREFIX:o.getConfigValue("APP_PREFIX"),APP_TEMPLATE:o.getConfigValue("APP_TEMPLATE"),BUTTON_TAG:o.getConfigValue("BUTTON_TAG"),STRIPE_PUBLIC_KEY:o.getConfigValue("STRIPE_PUBLIC_KEY"),STRIPE_SOURCE:o.getConfigValue("STRIPE_SOURCE"),STRIPE_TRIAL_PERIOD_DAYS:o.getConfigValue("STRIPE_TRIAL_PERIOD_DAYS"),SUBSCRIPTION_NEEDED:o.getConfigValue("SUBSCRIPTION_NEEDED"),USER_PREFIX:o.getConfigValue("USER_PREFIX"),ANONYMOUS_TOKEN:o.getConfigValue("ANONYMOUS_TOKEN")})),[]);e.useEffect((()=>{!u&&t&&(async()=>{try{const e=await i({});console.debug("CODICENT: ACCESS TOKEN",e),m(e)}catch(e){console.debug("CODICENT: Failed to get access token",e);const r=e;if(r&&"object"==typeof r&&"error"in r&&"login_required"===r.error)console.warn("CODICENT: Login required"),S();else if(r&&"object"==typeof r&&"error"in r&&"consent_required"===r.error)try{const e=await l();if(!e)return void P("Failed to get access token: no token from auth0 with popup");console.log("CODICENT: GOT ACCESS TOKEN"),m(e)}catch(e){console.warn("CODICENT: Failed to get access token with popup",e),S()}else P("Failed to get access token: "+(r.message?.toString()||r.toString())),console.log("CODICENT: ACCESS TOKEN ERROR",r)}})().then((()=>{}))}),[t,l,i,g,u]),e.useEffect((()=>{if(a&&a.sub&&q&&void 0===j){let e=!0;return(n?.loginFn?n.loginFn(T,a.sub,q):T.loginUser(a.sub,q)).then((r=>{e&&(null===r?C(!1):""===r?P("Kontrollera internetanslutningen och försök igen."):(T.setToken(r),T.getNickname().then(_),C(!0)))})).catch((()=>{e&&(P("Ett fel uppstod. Försök igen senare."),C(!1))})),()=>{e=!1}}}),[a,q,j,T]);const S=e.useCallback((()=>{T.logout(),m(null),P(null),C(void 0),_(""),c({logoutParams:{returnTo:o.getConfigValue("AUTH_REDIRECT_URL")}})}),[T,c]),f=e.useCallback((async e=>{const r=n?.registerFn?await n.registerFn(T,e,a.email,a.sub,q):await T.registerUser(e,a.email,a.sub,q);return r&&(T.setToken(r),C(!0)),r}),[T,a,q]);e.useEffect((()=>{T.onUnauthorized=S}),[T]);const A=e.useCallback((async e=>{try{await p({authorizationParams:{connection:"email",login_hint:e}})}catch(e){console.error("Passwordless login failed:",e),P(`Passwordless login failed: ${e}`)}}),[p]);return e.useMemo((()=>({isAuthenticated:t,isRegistered:j,accessToken:q,authError:E,isLoading:u,user:a,nickname:d,logout:S,registerUser:f,codicentService:T,loginWithRedirect:g,loginPasswordless:A})),[t,j,q,E,u,a,d,S,f,T,g,A])};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),r=require("../services/codicent.js");require("../components/Markdown.js"),require("../components/Textarea.js"),require("../components/Button.js"),require("../components/CompoundButton.js"),require("react/jsx-runtime"),require("@fluentui/react-components"),require("../components/Spinner.js"),require("../components/TextHeader.js"),require("../components/TypingIndicator.js"),require("../components/Dialog.js"),require("../components/ChatInput.js"),require("../components/CombinedPlaceholderDialog.js"),require("../components/ChatMessage.js"),require("../components/Header.js"),require("@fluentui/react-icons");var o=require("../config/index.js");require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("../_virtual/index.js"),require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js"),require("./useLocalization.js"),require("./useAppStyles.js"),require("../components/FileThumbnail.js"),require("../components/MessageInput.js"),require("../components/UploadFile.js"),require("../components/SnapFooter.js"),require("../components/Profile.js"),require("../components/MessageItem.js"),require("../components/Content.js"),require("../components/AiInput.js"),require("../components/SearchBox.js"),require("../components/DataMessagePicker.js"),require("../components/HtmlView.js"),require("../components/Footer.js"),require("../components/Page.js"),require("../components/QrCodeDialog.js"),require("../components/QrScanner.js"),require("../components/OfflineMessage.js"),require("../components/LanguageSelector.js"),require("../components/ListView.js"),require("../components/RecordModal.js"),require("../components/BulkUploadDialog.js"),require("../components/CookieBanner.js"),require("../pages/AppFrame.js"),require("../pages/Chat.js"),require("../pages/Compose.js"),require("../pages/Snap.js"),require("../pages/Search.js"),require("../pages/Login.js"),require("../pages/CrmPage.js"),require("../pages/CrmPagePersistent.js"),require("../pages/ImageView.js"),require("../pages/FormInvite.js"),require("../pages/FormAccept.js"),require("../pages/Sales.js"),require("../pages/Purchase.js"),require("../pages/QrScan.js"),require("react-dom/client"),require("react-router-dom"),require("../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js");exports.default=(s,n)=>{const{isAuthenticated:t,getAccessTokenSilently:i,user:a,isLoading:u,logout:c,getAccessTokenWithPopup:l,loginWithRedirect:g,loginWithPopup:p}=s,[q,m]=e.useState(null),[j,C]=e.useState(void 0),[E,P]=e.useState(null),[d,_]=e.useState(""),S=e.useMemo((()=>new r.CodicentService({API_BASE_URL:o.getConfigValue("API_BASE_URL"),PUBSUB_URL:o.getConfigValue("PUBSUB_URL"),APP_LOG_CODICENT:o.getConfigValue("APP_LOG_CODICENT"),APP_LOG_TOKEN:o.getConfigValue("APP_LOG_TOKEN"),APP_NAME:o.getConfigValue("APP_NAME"),APP_PREFIX:o.getConfigValue("APP_PREFIX"),APP_TEMPLATE:o.getConfigValue("APP_TEMPLATE"),BUTTON_TAG:o.getConfigValue("BUTTON_TAG"),STRIPE_PUBLIC_KEY:o.getConfigValue("STRIPE_PUBLIC_KEY"),STRIPE_SOURCE:o.getConfigValue("STRIPE_SOURCE"),STRIPE_TRIAL_PERIOD_DAYS:o.getConfigValue("STRIPE_TRIAL_PERIOD_DAYS"),SUBSCRIPTION_NEEDED:o.getConfigValue("SUBSCRIPTION_NEEDED"),USER_PREFIX:o.getConfigValue("USER_PREFIX"),ANONYMOUS_TOKEN:o.getConfigValue("ANONYMOUS_TOKEN")})),[]);e.useEffect((()=>{!u&&t&&(async()=>{try{const e=await i({});console.debug("CODICENT: ACCESS TOKEN",e),m(e)}catch(e){console.debug("CODICENT: Failed to get access token",e);const r=e;if(r&&"object"==typeof r&&"error"in r&&"login_required"===r.error)console.warn("CODICENT: Session expired (login_required)"),m(null);else if(r&&"object"==typeof r&&"error"in r&&"consent_required"===r.error)try{const e=await l();if(!e)return void P("Failed to get access token: no token from auth0 with popup");console.log("CODICENT: GOT ACCESS TOKEN"),m(e)}catch(e){console.warn("CODICENT: Failed to get access token with popup",e),P("Samtycke krävs för inloggning. Tillåt popup-fönster och försök igen."),m(null)}else P("Failed to get access token: "+(r.message?.toString()||r.toString())),console.log("CODICENT: ACCESS TOKEN ERROR",r)}})().then((()=>{}))}),[t,l,i,g,u]),e.useEffect((()=>{if(a&&a.sub&&q&&void 0===j){let e=!0;return(n?.loginFn?n.loginFn(S,a.sub,q):S.loginUser(a.sub,q)).then((r=>{e&&(null===r?C(!1):""===r?P("Kontrollera internetanslutningen och försök igen."):(S.setToken(r),S.getNickname().then(_),C(!0)))})).catch((()=>{e&&(P("Ett fel uppstod. Försök igen senare."),C(!1))})),()=>{e=!1}}}),[a,q,j,S]);const T=e.useCallback((()=>{S.logout(),m(null),P(null),C(void 0),_(""),c({logoutParams:{returnTo:o.getConfigValue("AUTH_REDIRECT_URL")}})}),[S,c]),f=e.useCallback((async e=>{const r=n?.registerFn?await n.registerFn(S,e,a.email,a.sub,q):await S.registerUser(e,a.email,a.sub,q);return r&&(S.setToken(r),C(!0)),r}),[S,a,q]);e.useEffect((()=>{S.onUnauthorized=T}),[S]);const A=e.useCallback((async e=>{try{await p({authorizationParams:{connection:"email",login_hint:e}})}catch(e){console.error("Passwordless login failed:",e),P(`Passwordless login failed: ${e}`)}}),[p]);return e.useMemo((()=>({isAuthenticated:t,isRegistered:j,accessToken:q,authError:E,isLoading:u,user:a,nickname:d,logout:T,registerUser:f,codicentService:S,loginWithRedirect:g,loginPasswordless:A})),[t,j,q,E,u,a,d,T,f,S,g,A])};
@@ -1,6 +1,6 @@
1
1
  import { Auth0ContextInterface } from "@auth0/auth0-react";
2
2
  import { CodicentService } from "../services";
3
- import { AppStateMachine, StateContext, AppStateDefinition } from "../utils";
3
+ import AppStateMachine, { StateContext, AppStateDefinition } from "../utils/appState";
4
4
  import { AudioRecorderState } from "./useAudioRecorder";
5
5
  import { AuthStateOptions, UseAuthState } from "./useAuthState";
6
6
  import { RealtimeVoice } from "./useRealtimeVoiceAI";
@@ -1 +1 @@
1
- {"version":3,"file":"useCodicentApp.d.ts","sourceRoot":"","sources":["../../../src/hooks/useCodicentApp.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,eAAe,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CAAC;IAC7B,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,WAAW,CAAC,EAAE,gBAAgB,CAAC;CAChC;AAED,eAAO,MAAM,cAAc,wCAAyC,qBAAqB,KA2WlF,gBACN,CAAC"}
@@ -1 +1 @@
1
- "use strict";var e=require("react");require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime");var t=require("../utils/appState.js");require("../_virtual/index.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js"),require("../utils/cacheManager.js");var r=require("./useAudioRecorder.js"),s=require("./useAuthState.js"),n=require("./useRealtimeVoiceAI.js"),a=require("./useTools.js");exports.useCodicentApp=({auth0:c,toolsConfig:u,authOptions:i})=>{const o=s.default(c,i),l=e.useRef(null);l.current||(l.current=t.createAppStateMachine(o.codicentService,(()=>{})));const[d,m]=e.useState((()=>{let e="",t=l.current.getCurrentStateName(),r=0;for(;t!==e&&r<10;)l.current.update(),e=t,t=l.current.getCurrentStateName(),r++;return t})),{service:p,context:h}=l.current,{nickname:f,name:g,error:A,errorType:k,selectedApp:C}=h,S=e.useCallback(((e,t)=>{const r=e.get("file").name;p.uploadFile(r,e).then((e=>{p.sendMessage(`#transcribe ${""!==t?(t.startsWith("#")?"":"#")+t+" ":""}#file:${e}`).then((()=>{})).catch(console.warn)}))}),[p]),v=r.useAudioRecorder(S),[b,q]=e.useState(),[w,j]=e.useState(),[y,x]=e.useState(!1),N=e.useMemo((()=>new Audio("./notification.mp3")),[]),T=e.useCallback((()=>x(!0)),[]),R=a.default(p,q,j,N,b,T,u),M=n.default(p,R);e.useEffect((()=>{y&&(M?.disconnectConversation(),x(!1))}),[y,M]),e.useEffect((()=>{o.isAuthenticated&&o.user&&o.accessToken&&l.current.updateContext({isAuthenticated:o.isAuthenticated,user:{sub:o.user.sub,email:o.user.email},accessToken:o.accessToken})}),[o.isAuthenticated,o.user,o.accessToken]);const _=e.useRef(o.isAuthenticated);e.useEffect((()=>{const e=!0===_.current,t=!0===o.isAuthenticated;e&&!t&&l.current.logout(),_.current=o.isAuthenticated}),[o.isAuthenticated]),e.useEffect((()=>l.current.updateContext({nickname:o.nickname})),[o.nickname]),e.useEffect((()=>{l.current.update();let e,t=l.current.getCurrentStateName();m(l.current.getCurrentStateName()),JSON.stringify(l.current.context);let r="hasAccess"===l.current.getCurrentStateName();const s=n=>setInterval((()=>{const n=l.current.getCurrentStateName();"hasAccess"!==n||r?"hasAccess"!==n&&r&&(console.log("🚨 Left stable state - switching to fast polling (200ms)"),r=!1,clearInterval(e),e=s(200)):(console.log("🎯 Reached stable state - switching to slower polling (1000ms)"),r=!0,clearInterval(e),e=s(1e3));const a=JSON.stringify(l.current.context);l.current.update();const c=JSON.stringify(l.current.context),u=l.current.getCurrentStateName();u===t&&a===c||(m(u),t=u)}),n);return e=s(r?1e3:200),()=>clearInterval(e)}),[]);const I=e.useCallback((e=>e.replace("{nickname}",f||"unknown").replace("{token}",encodeURIComponent(o.accessToken||"unknown")).replace("{app}",C||"unknown")),[f,o.accessToken,C]),E=e.useCallback((e=>{l.current.updateContext({isAnonymous:e})}),[]),O=e.useCallback((()=>l.current.isBusy()),[]);return e.useMemo((()=>({audio:v,auth:o,currentStateName:d,stateMachine:l.current,service:p,context:h,state:d,nickname:f,name:g,error:A,errorType:k,fixAppUrl:I,setAnonymous:E,allStates:l.current.allStates,isBusy:O,voice:M,html:b,setHtml:q,script:w})),[d,f,g,A,k,b,w,o.isAuthenticated,o.isLoading,v.isRecording,M?.isConnected,I,E,O])};
1
+ "use strict";var e=require("react"),t=require("./useAudioRecorder.js"),r=require("./useAuthState.js"),s=require("./useRealtimeVoiceAI.js"),n=require("./useTools.js"),a=require("../config/index.js"),c=require("../utils/cacheManager.js"),i=require("./useAppState.js");exports.useCodicentApp=({auth0:o,toolsConfig:u,authOptions:p})=>{const l=r.default(o,p),A=l.codicentService,[{phase:E,context:d},f]=e.useReducer(i.appStateReducer,null,i.createInitialState),T=e.useCallback(((e,t)=>{const r=e.get("file").name;A.uploadFile(r,e).then((e=>{A.sendMessage(`#transcribe ${""!==t?(t.startsWith("#")?"":"#")+t+" ":""}#file:${e}`).catch(console.warn)}))}),[A]),g=t.useAudioRecorder(T),[m,h]=e.useState(),[S,k]=e.useState(),[C,y]=e.useState(!1),R=e.useMemo((()=>new Audio("./notification.mp3")),[]),_=e.useCallback((()=>y(!0)),[]),I=n.default(A,h,k,R,m,_,u),U=s.default(A,I);e.useEffect((()=>{C&&(U?.disconnectConversation(),y(!1))}),[C,U]),e.useEffect((()=>{l.isLoading||(l.isAuthenticated&&l.accessToken?f({type:"AUTHENTICATED",accessToken:l.accessToken,user:{sub:l.user?.sub??"",email:l.user?.email??""}}):l.isAuthenticated?l.authError&&f({type:"UPDATE_CONTEXT",updates:{error:l.authError}}):f({type:"NOT_AUTHENTICATED"}))}),[l.isLoading,l.isAuthenticated,l.accessToken,l.authError]),e.useEffect((()=>{"checkingCodicentAccess"===E&&(void 0===l.isRegistered&&l.authError?f({type:"UPDATE_CONTEXT",updates:{error:l.authError,errorType:"CodicentLoginFailed"}}):void 0!==l.isRegistered&&(!0===l.isRegistered&&l.nickname?f({type:"REGISTERED",nickname:l.nickname}):!1===l.isRegistered&&f({type:"NOT_REGISTERED"})))}),[E,l.isRegistered,l.nickname,l.authError]),e.useEffect((()=>{if("registering"!==E)return;if(!d.accessToken||!d.user)return;let e=!1;return A.setToken(d.accessToken),A.findUsername().then((async t=>{if(e)return;if(!t)return void f({type:"REGISTER_AUTO_FAIL",error:"Användarnamn kunde inte hittas.",errorType:"NoUsernameFound"});const r=await A.nicknameExists(t);e||(r?f({type:"REGISTER_AUTO_FAIL",error:"Användarnamnet finns redan.",errorType:"UsernameExists"}):(await A.registerUser(t,d.user.email,d.user.sub,d.accessToken),e||(A.setToken(d.accessToken),f({type:"REGISTER_AUTO_SUCCESS",nickname:t}))))})).catch((t=>{e||f({type:"REGISTER_AUTO_FAIL",error:t instanceof Error?t.message:String(t),errorType:"ErrorRegistering"})})),()=>{e=!0}}),[E]),e.useEffect((()=>{if("loadingUser"!==E||!d.nickname)return;let e=!1;return localStorage.setItem("nickname",d.nickname),A.getUserInfo(d.nickname).then((t=>{e||f({type:"USER_LOADED",name:t?.name||t?.nickname||""})})).catch((()=>{e||f({type:"USER_LOADED",name:""})})),()=>{e=!0}}),[E]),e.useEffect((()=>{if("checkingPurchase"!==E)return;if(!a.getConfigValue("SUBSCRIPTION_NEEDED"))return void f({type:"PURCHASE_VALID"});let e=!1;return A.checkSubscriptionStatus().then((t=>{if(!e){f("active"===t||"trialing"===t?{type:"PURCHASE_VALID"}:{type:"PURCHASE_INVALID"})}})).catch((()=>{e||f({type:"PURCHASE_INVALID"})})),()=>{e=!0}}),[E]),e.useEffect((()=>{if("gettingApps"!==E)return;let e=!1;return A.getApps().then((t=>{e||f(null!==t?{type:"APPS_LOADED",apps:t}:{type:"APPS_FAILED",error:"Failed to fetch apps."})})).catch((t=>{e||f({type:"APPS_FAILED",error:String(t)})})),()=>{e=!0}}),[E]),e.useEffect((()=>{if("creatingApp"!==E)return;let e=!1;return A.createApp().then((t=>{e||f(t?{type:"APP_CREATED",appId:t}:{type:"APP_CREATE_FAILED",error:"Misslyckades att skapa din app. Försök igen senare."})})).catch((t=>{e||f({type:"APP_CREATE_FAILED",error:String(t)})})),()=>{e=!0}}),[E]),e.useEffect((()=>{"hasAccess"===E&&d.selectedApp&&(A.codicent=d.selectedApp,localStorage.setItem("selectedApp",d.selectedApp),d.isFromCache||i.saveSession(d))}),[E,d.selectedApp]);const O=e.useRef(!1);e.useEffect((()=>{"hasAccess"===E&&d.isFromCache&&d.needsValidation&&l.accessToken&&l.isAuthenticated&&(O.current||(O.current=!0,i.runBackgroundValidation(A,d,f)))}),[E,d.isFromCache,d.needsValidation,l.accessToken,l.isAuthenticated]),e.useEffect((()=>{"needsPurchase"===E&&(window.location.href="./#/purchase")}),[E]),e.useEffect((()=>{if("anonymous"!==E)return;const e=a.getConfigValue("ANONYMOUS_TOKEN"),t=a.getConfigValue("ANONYMOUS_CODICENT")||a.getConfigValue("APP_NAME")||"";e&&(A.setToken(e),A.codicent=t)}),[E]),e.useEffect((()=>{"loggingOut"===E&&(a.getConfigValue("ENABLE_STATE_CACHE")&&c.stateMachineCacheManager.clear(),localStorage.removeItem("selectedApp"),localStorage.removeItem("nickname"),localStorage.removeItem("codicent"),sessionStorage.clear(),l.logout())}),[E]);const P=e.useRef(d);P.current=d;const D=e.useRef({}).current,N=e.useRef({}).current,L=e.useMemo((()=>({service:A,get context(){return P.current},current:"hasAccess"===E?D:N,allStates:{hasAccess:D},setSelectedApp:e=>{f({type:"SET_SELECTED_APP",appId:e})},updateContext:e=>{f({type:"UPDATE_CONTEXT",updates:e})},logout:()=>{f({type:"LOGOUT"})},update:()=>{},isBusy:()=>i.isBusyPhase(E)})),[E,A]),v=e.useCallback((e=>e.replace("{nickname}",d.nickname||"unknown").replace("{token}",encodeURIComponent(l.accessToken||"unknown")).replace("{app}",d.selectedApp||"unknown")),[d.nickname,l.accessToken,d.selectedApp]),F=e.useCallback((e=>{e&&a.getConfigValue("ANONYMOUS_TOKEN")&&f({type:"SET_ANONYMOUS"})}),[]),M=e.useCallback((()=>i.isBusyPhase(E)),[E]);return e.useMemo((()=>({audio:g,auth:l,currentStateName:E,stateMachine:L,service:A,context:d,state:E,nickname:d.nickname||"",name:d.name||"",error:d.error||"",errorType:d.errorType||"",fixAppUrl:v,setAnonymous:F,allStates:L.allStates,isBusy:M,voice:U,html:m||"",setHtml:h,script:S||""})),[E,d,m,S,l.isAuthenticated,l.isLoading,g.isRecording,U?.isConnected,v,F,M,L])};
@@ -60,6 +60,12 @@ export declare class CodicentService {
60
60
  [key: string]: string;
61
61
  }) => Promise<DataMessage[]>;
62
62
  readOneDataMessage: (id: string) => Promise<DataMessage | null>;
63
+ /**
64
+ * Fetches the current leaf (latest version) of a data message by its stable originalMessageId.
65
+ * Uses the backend GetLeafMessageByOriginalMessageId endpoint directly.
66
+ * Returns a DataMessage-compatible object with parsed JSON data, or null if not found.
67
+ */
68
+ getLeafDataMessage: (originalMessageId: string, codicent?: string) => Promise<DataMessage | null>;
63
69
  updateDataMessage: (id: string, data: object, codicent?: string) => Promise<string>;
64
70
  deleteDataMessage: (id: string, codicent?: string) => Promise<string>;
65
71
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,UAAU,QAAS,MAAM,SAgBrC,CAAC;AAEF,eAAO,MAAM,cAAc,SAAU,MAAM,SAU1C,CAAC;AA+BF,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE;QAAE,aAAa,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACvC,UAAU,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB;AAED,MAAM,WAAW,OAAO;IACtB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,IAAI;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;CAC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AO,CAAC,MAAM,CAAC;IAwB9F,iBAAiB,CACrB,QAAQ,GAAE,MAAiB,GAC1B,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAoBpE;;;;;;OAMG;IACH,MAAM,CAAC,eAAe,SACd,MAAM,kBACI,MAAM,YACb,MAAM,KACd,OAAO,CAAC,mBAAmB,CAAC,CA0B7B;CACH"}
@@ -1 +1 @@
1
- "use strict";var t,e=require("../node_modules/@stripe/stripe-js/dist/index.js"),o=require("../utils/MessageContent.js");require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("react"),require("../_virtual/index.js"),require("../config/index.js"),require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");let n="https://codicent.com/",a="https://pubsub.codicent.com/hub",s="-";const i=()=>"undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init,r=t=>{t&&"string"==typeof t?(n=t.endsWith("/")?t:t+"/",i()&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a})):console.warn("Invalid base URL provided, using default")},c=t=>{t&&"string"==typeof t&&(a=t,i()&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a}))},h=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:s,baseUrl:n,signalRHost:a}),!0);let d=h();if(!d){const t=setInterval((()=>{d=h(),d&&clearInterval(t)}),100)}class l{constructor(t){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,n,a,s,i,r)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:n,length:a,afterTimestamp:s,beforeTimestamp:i,dataFilters:r}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>[...(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const e=new o.default(t.content).content.split("\n"),n=e[0],a=e.slice(1).join("\n");return{id:t.id,title:n,content:a}})),...(await window.Codicent.getDataMessages({tags:["skill"],codicent:this.codicent})).map((t=>t.data)).filter((t=>t.name&&t.title)).map((t=>({id:t.name,title:t.title,content:t.content||t.description||""})))],this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${n}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,a=void 0,s,i=0)=>{const r=await this.request(`${n}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),a){const t=await this.getPublicFlow(a);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let n=[];const a=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(a)).forEach((t=>{n=n.concat(t)})),e)try{const t=await this.getPublicFlow(e);n=n.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return n=n.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),n.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),n},this.registerUser=async(t,e,o,s)=>{const i=await fetch(`${n}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!i.ok)return"";const r=await i.text();return window.Codicent.init({token:r,baseUrl:n,signalRHost:a}),r},this.loginUser=async(t,e)=>{try{const o=await fetch(`${n}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in user:",t),""}},this.loginMicrosoftUser=async(t,e)=>{try{const o=await fetch(`${n}app/LoginMicrosoftUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in Microsoft user:",t),""}},this.registerMicrosoftUser=async(t,e,o,a)=>{const s=await fetch(`${n}app/RegisterMicrosoftUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${a}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";return await s.text()},this.nicknameExists=async t=>{const e=await fetch(`${n}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${n}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=(await t.json()).filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))));return e}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${n}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${n}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let a=await o.json();if(a){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(a=!1)}catch{a=!1}if(a){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(a=!1)}catch{a=!1}}}return a},this.getNickname=async()=>{try{const t=s.split(".")[1],e=atob(t),o=JSON.parse(e),a=o.sub||o.userId,i=await fetch(`${n}app/GetNickname?userId=${a}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${n}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const a=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=a;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:a})=>{const s=await fetch(`${n}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:a,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${n}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${n}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${n}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{s=t,s&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a})},this.getToken=()=>s,this.checkPurchaseStatus=async()=>{const t=await fetch(`${n}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${n}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o=this.options.STRIPE_TRIAL_PERIOD_DAYS,a={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(a.source=e),o&&o>0&&(a.trialPeriodDays=o);const s=await fetch(`${n}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(a)});if(!s.ok)throw new Error("Failed to create checkout session");const{id:i}=await s.json();return i},this.redirectToCheckout=async t=>{const o=await e.loadStripe(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const n=await this.createCheckoutSession(t),{error:a}=await o.redirectToCheckout({sessionId:n});if(a)throw new Error(a.message)},this.getChatHistory=async t=>{const e=await fetch(`${n}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!(t.content.includes("#function_result")||t.content.includes("#finish_reason_function_call")||t.content.includes("#function_results_batch")||t.content.includes("#finish_reason_tool_calls_batch")))),o},this.getPublicFlow=async t=>{const e=await fetch(`${n}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${n}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},a=await fetch(`${n}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!a.ok)throw new Error(`${a.statusText||"Failed to post log message!"}`);return(await a.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),n=JSON.parse(o).nickname;if(!await this.addFollower(e,n))throw new Error("Failed to add follower: "+n)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${n}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${n}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${n}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${n}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=t,r(t.API_BASE_URL),t.PUBSUB_URL&&c(t.PUBSUB_URL)}async request(t,e,o={}){const n={};o.headers&&o.headers.forEach((([t,e])=>{n[t]=e}));const a=await fetch(t,{...o,method:e,headers:n});if(!a.ok)throw 401===a.status&&this.handleUnauthorized(),new Error(`${a.statusText}`);return a}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${n}realtime/session?voice=${t}&provider=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!a.ok)throw new Error(`Failed to fetch session token: ${a.statusText}`);const s=await a.json(),i=s.client_secret?.value??s.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${n}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}t=l,l.getImageUrl=(t,e)=>`${n}app/GetImage?fileId=${t}&width=${e}`,l.getFileUrl=(t,e)=>`${n}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,l.downloadFile=async e=>{fetch(t.getFileUrl(e.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((t=>{const o=window.URL.createObjectURL(t),n=document.createElement("a");n.style.display="none",n.href=o,n.download=e.filename,document.body.appendChild(n),n.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},l.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let a={project:e,message:t};o&&(a.messageId=o);const i=await fetch(`${n}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify(a)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},l.getMiniChatReply=async(t,e="codicent-mini",o,a=3e5,i=2e3,r)=>{const c={project:e,message:t};let h;o&&(c.messageId=o),r&&(c.previousResponseId=r);try{const t=await fetch(`${n}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify(c)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(h=(await t.json()).promptMessageId,!h)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const d=Date.now();for(;Date.now()-d<a;)try{const t=await fetch(`${n}app/GetAi2ChatReplyStatus?promptMessageId=${h}`,{method:"GET",headers:[["Authorization",`Bearer ${s}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json(),a=o.content??o.content??"";return{content:a.replace(`@${e}`,"").replace("@codicent-mini","").trim(),responseId:o.responseId??void 0}}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},l.getTranslations=async(t,e,o="codicent-mini")=>{if(!s||"-"===s)return{translation:t};const a=await fetch(`${n}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${s}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!a.ok)throw a.status,new Error(`Failed to get translations: ${a.statusText}`);return await a.json()},exports.CodicentService=l,exports.setBaseUrl=r,exports.setSignalRHost=c;
1
+ "use strict";var t,e=require("../node_modules/@stripe/stripe-js/dist/index.js"),o=require("../utils/MessageContent.js");require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("react"),require("../_virtual/index.js"),require("../config/index.js"),require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");let n="https://codicent.com/",a="https://pubsub.codicent.com/hub",s="-";const i=()=>"undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init,r=t=>{t&&"string"==typeof t?(n=t.endsWith("/")?t:t+"/",i()&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a})):console.warn("Invalid base URL provided, using default")},c=t=>{t&&"string"==typeof t&&(a=t,i()&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a}))},h=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:s,baseUrl:n,signalRHost:a}),!0);let d=h();if(!d){const t=setInterval((()=>{d=h(),d&&clearInterval(t)}),100)}class l{constructor(t){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,n,a,s,i,r)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:n,length:a,afterTimestamp:s,beforeTimestamp:i,dataFilters:r}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.getLeafDataMessage=async(t,e)=>{const o=e||this.codicent;try{const e=await fetch(`${this.options.API_BASE_URL}app/GetLeafMessageByOriginalMessageId?project=${encodeURIComponent(o)}&originalMessageId=${encodeURIComponent(t)}`,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!e.ok)return null;const n=await e.json();if(!n||!n.content)return null;const a=n.content.indexOf("{");if(-1===a)return null;const s=JSON.parse(n.content.slice(a));return{id:n.id,fileId:n.fileId??null,fileIds:n.fileIds??[],data:s,createdAt:n.createdAt,tags:n.tags??[],mentions:n.mentions??[]}}catch{return null}},this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>[...(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const e=new o.default(t.content).content.split("\n"),n=e[0],a=e.slice(1).join("\n");return{id:t.id,title:n,content:a}})),...(await window.Codicent.getDataMessages({tags:["skill"],codicent:this.codicent})).map((t=>t.data)).filter((t=>t.name&&t.title)).map((t=>({id:t.name,title:t.title,content:t.content||t.description||""})))],this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${n}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,a=void 0,s,i=0)=>{const r=await this.request(`${n}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),a){const t=await this.getPublicFlow(a);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let n=[];const a=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(a)).forEach((t=>{n=n.concat(t)})),e)try{const t=await this.getPublicFlow(e);n=n.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return n=n.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),n.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),n},this.registerUser=async(t,e,o,s)=>{const i=await fetch(`${n}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!i.ok)return"";const r=await i.text();return window.Codicent.init({token:r,baseUrl:n,signalRHost:a}),r},this.loginUser=async(t,e)=>{try{const o=await fetch(`${n}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in user:",t),""}},this.loginMicrosoftUser=async(t,e)=>{try{const o=await fetch(`${n}app/LoginMicrosoftUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in Microsoft user:",t),""}},this.registerMicrosoftUser=async(t,e,o,a)=>{const s=await fetch(`${n}app/RegisterMicrosoftUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${a}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";return await s.text()},this.nicknameExists=async t=>{const e=await fetch(`${n}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${n}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=(await t.json()).filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))));return e}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${n}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${n}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let a=await o.json();if(a){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(a=!1)}catch{a=!1}if(a){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(a=!1)}catch{a=!1}}}return a},this.getNickname=async()=>{try{const t=s.split(".")[1],e=atob(t),o=JSON.parse(e),a=o.sub||o.userId,i=await fetch(`${n}app/GetNickname?userId=${a}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${n}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const a=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=a;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:a})=>{const s=await fetch(`${n}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:a,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${n}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${n}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${n}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{s=t,s&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a})},this.getToken=()=>s,this.checkPurchaseStatus=async()=>{const t=await fetch(`${n}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${n}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o=this.options.STRIPE_TRIAL_PERIOD_DAYS,a={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(a.source=e),o&&o>0&&(a.trialPeriodDays=o);const s=await fetch(`${n}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(a)});if(!s.ok)throw new Error("Failed to create checkout session");const{id:i}=await s.json();return i},this.redirectToCheckout=async t=>{const o=await e.loadStripe(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const n=await this.createCheckoutSession(t),{error:a}=await o.redirectToCheckout({sessionId:n});if(a)throw new Error(a.message)},this.getChatHistory=async t=>{const e=await fetch(`${n}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!(t.content.includes("#function_result")||t.content.includes("#finish_reason_function_call")||t.content.includes("#function_results_batch")||t.content.includes("#finish_reason_tool_calls_batch")))),o},this.getPublicFlow=async t=>{const e=await fetch(`${n}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${n}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},a=await fetch(`${n}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!a.ok)throw new Error(`${a.statusText||"Failed to post log message!"}`);return(await a.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),n=JSON.parse(o).nickname;if(!await this.addFollower(e,n))throw new Error("Failed to add follower: "+n)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${n}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${n}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${n}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${n}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=t,r(t.API_BASE_URL),t.PUBSUB_URL&&c(t.PUBSUB_URL)}async request(t,e,o={}){const n={};o.headers&&o.headers.forEach((([t,e])=>{n[t]=e}));const a=await fetch(t,{...o,method:e,headers:n});if(!a.ok)throw 401===a.status&&this.handleUnauthorized(),new Error(`${a.statusText}`);return a}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${n}realtime/session?voice=${t}&provider=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!a.ok)throw new Error(`Failed to fetch session token: ${a.statusText}`);const s=await a.json(),i=s.client_secret?.value??s.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${n}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}t=l,l.getImageUrl=(t,e)=>`${n}app/GetImage?fileId=${t}&width=${e}`,l.getFileUrl=(t,e)=>`${n}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,l.downloadFile=async e=>{fetch(t.getFileUrl(e.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((t=>{const o=window.URL.createObjectURL(t),n=document.createElement("a");n.style.display="none",n.href=o,n.download=e.filename,document.body.appendChild(n),n.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},l.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let a={project:e,message:t};o&&(a.messageId=o);const i=await fetch(`${n}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify(a)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},l.getMiniChatReply=async(t,e="codicent-mini",o,a=3e5,i=2e3,r)=>{const c={project:e,message:t};let h;o&&(c.messageId=o),r&&(c.previousResponseId=r);try{const t=await fetch(`${n}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify(c)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(h=(await t.json()).promptMessageId,!h)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const d=Date.now();for(;Date.now()-d<a;)try{const t=await fetch(`${n}app/GetAi2ChatReplyStatus?promptMessageId=${h}`,{method:"GET",headers:[["Authorization",`Bearer ${s}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json(),a=o.content??o.content??"";return{content:a.replace(`@${e}`,"").replace("@codicent-mini","").trim(),responseId:o.responseId??void 0}}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},l.getTranslations=async(t,e,o="codicent-mini")=>{if(!s||"-"===s)return{translation:t};const a=await fetch(`${n}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${s}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!a.ok)throw a.status,new Error(`Failed to get translations: ${a.statusText}`);return await a.json()},exports.CodicentService=l,exports.setBaseUrl=r,exports.setSignalRHost=c;
@@ -7,6 +7,8 @@ export interface ColumnAction {
7
7
  tooltip?: string;
8
8
  /** Callback when the action icon is clicked, receives the row data as context */
9
9
  onClick: (rowData: Record<string, unknown>) => void;
10
+ /** When true, renders the icon to the left of the cell text instead of the right */
11
+ iconLeft?: boolean;
10
12
  }
11
13
  export interface ColumnDefinition {
12
14
  key: string | string[];
@@ -14,11 +16,17 @@ export interface ColumnDefinition {
14
16
  hidden?: boolean;
15
17
  hideOnMobile?: boolean;
16
18
  maxWidth?: number;
17
- type?: "file" | "checkbox" | "textarea" | "enum" | undefined;
19
+ type?: "file" | "checkbox" | "textarea" | "enum" | "combobox" | undefined;
18
20
  /** Number of rows for textarea type (default: 3) */
19
21
  rows?: number;
20
- /** Options for enum type columns */
22
+ /** Options for enum type columns (static, small lists) */
21
23
  enumOptions?: string[];
24
+ /** Async loader for combobox options (e.g. 15k+ customers). Receives the current search text, returns matching options. */
25
+ enumOptionsLoader?: (searchText: string) => Promise<string[]>;
26
+ /** Minimum number of characters typed before the async loader is called (default: 2) */
27
+ enumOptionsLoaderMinChars?: number;
28
+ /** Maximum number of options to display in the combobox dropdown (default: 50) */
29
+ enumOptionsLoaderMaxResults?: number;
22
30
  editable?: boolean;
23
31
  filterable?: boolean;
24
32
  /** Default sort direction for this column. If multiple columns have defaultSort, only the first one is used. */
@@ -1 +1 @@
1
- {"version":3,"file":"ListView.d.ts","sourceRoot":"","sources":["../../../src/components/ListView.tsx"],"names":[],"mappings":"AAWA,OAAO,KAAuC,MAAM,OAAO,CAAC;AAiB5D,uEAAuE;AACvE,MAAM,WAAW,YAAY;IAC3B,kHAAkH;IAClH,IAAI,EAAE,KAAK,CAAC,aAAa,CAAC;IAC1B,uCAAuC;IACvC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,iFAAiF;IACjF,OAAO,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;CACrD;AAqLD,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,UAAU,GAAG,MAAM,GAAG,SAAS,CAAC;IAC7D,oDAAoD;IACpD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,oCAAoC;IACpC,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IACvB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,gHAAgH;IAChH,WAAW,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;IAC7B,2HAA2H;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AED,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;IAChC,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAC;IAC7B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAChE,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClE,gBAAgB,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACrH,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAChH,oBAAoB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,IAAI,CAAC;CAC1E;AA2GD,eAAO,MAAM,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,aAAa,CA0gB5C,CAAC;;AAGF,wBAAoC"}
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import i,{useMemo as r,useState as o,useEffect as l}from"react";import{makeStyles as a,Button as c,Checkbox as d,Select as s,Dialog as p,DialogSurface as h,DialogBody as u,DialogTitle as m,DialogContent as f,Tooltip as x}from"@fluentui/react-components";import{Edit24Regular as g,Delete24Regular as y}from"@fluentui/react-icons";import{CodicentService as b}from"../services/codicent.js";import w from"../hooks/useLocalization.js";const k=a({container:{width:"100%",overflowX:"auto",userSelect:"text"},table:{width:"100%",borderCollapse:"collapse",backgroundColor:"#ffffff",fontSize:"14px",tableLayout:"fixed",userSelect:"text"},th:{textAlign:"left",padding:"12px 8px",borderBottom:"2px solid #e0e0e0",fontWeight:"600",backgroundColor:"#f5f5f5",position:"sticky",top:0,zIndex:1,cursor:"pointer",userSelect:"none","&:hover":{backgroundColor:"#e8e8e8"}},td:{padding:"12px 8px",borderBottom:"1px solid #e0e0e0",verticalAlign:"top",wordWrap:"break-word",overflow:"hidden",userSelect:"text"},tdTruncated:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap","@media (hover: none)":{cursor:"pointer"}},tr:{"&:hover":{backgroundColor:"#f9f9f9"}},emptyState:{padding:"20px",textAlign:"center",color:"#666"},sortIndicator:{marginLeft:"4px",fontSize:"10px"},hideOnMobile:{"@media (max-width: 768px)":{display:"none"}},dialogContent:{wordWrap:"break-word",whiteSpace:"pre-wrap",maxHeight:"60vh",overflowY:"auto"},thumbnail:{maxWidth:"50px",maxHeight:"50px",objectFit:"cover"},tooltip:{maxWidth:"600px",whiteSpace:"normal",wordWrap:"break-word"},editButton:{minWidth:"auto",padding:"4px 8px"},actionsColumn:{width:"100px",textAlign:"center"},filterInput:{width:"100%",padding:"4px 8px",fontSize:"14px",border:"1px solid #e0e0e0",borderRadius:"4px",paddingRight:"28px"},filterWrapper:{position:"relative"},clearFilterButton:{position:"absolute",right:"6px",top:"50%",transform:"translateY(-50%)",minWidth:"auto",height:"20px",padding:"0 6px",lineHeight:"18px"},filterToolbar:{display:"flex",justifyContent:"flex-end",padding:"8px",gap:"8px"},cellWithAction:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},actionIcon:{minWidth:"auto",padding:"2px",marginLeft:"4px",flexShrink:0,cursor:"pointer",opacity:.7,"&:hover":{opacity:1}},cellText:{flex:1,overflow:"hidden",textOverflow:"ellipsis"}}),C=e=>{if(/^\d{4}-\d{2}-\d{2}/.test(e)){const t=new Date(e);if(!isNaN(t.getTime()))return t.getTime()}const t=e.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})/);if(t){const e=parseInt(t[1],10),n=parseInt(t[2],10)-1,i=parseInt(t[3],10),r=new Date(i,n,e);if(r.getFullYear()===i&&r.getMonth()===n&&r.getDate()===e)return r.getTime()}return null},v=(e,t)=>{if("string"==typeof t)return e[t];for(const n of t)if(void 0!==e[n])return e[n]},S=({data:i,columns:a,canEdit:S,onEdit:N,onDelete:W,onToggleCheckbox:$,onEnumChange:I,onFilteredDataChange:A})=>{const j=k(),{visibleColumns:O,defaultSortIndex:M,defaultSortDirection:T}=r((()=>{const e=i&&i.length>0?Array.from(new Set(i.flatMap((e=>Object.keys(e))))):[],t=(a||e.map((e=>({key:e})))).filter((e=>!e.hidden)),n=t.findIndex((e=>e.defaultSort));return{visibleColumns:t,defaultSortIndex:n,defaultSortDirection:n>=0&&t[n].defaultSort||null}}),[i,a]),[D,F]=o(M>=0?M:null),[B,z]=o(T),[L,H]=o(!1),[E,Y]=o({title:"",text:""}),[P,R]=o({}),[_,J]=o(0),{t:U}=w(),X=e=>e.title?U(e.title):Array.isArray(e.key)?e.key[0]:e.key,q=e=>{const t=[];return e.hideOnMobile&&t.push(j.hideOnMobile),t.join(" ")},G=e=>null==e||"string"==typeof e&&e.startsWith("[")&&e.endsWith("]")?"":"object"==typeof e?JSON.stringify(e):String(e),K=r((()=>{const e=[...i];if(null!==D&&B){const t=O[D];e.sort(((e,n)=>{const i=v(e,t.key),r=v(n,t.key);if(null==i)return 1;if(null==r)return-1;let o=0;if("string"==typeof i&&"string"==typeof r){const e=C(i),t=C(r);if(null!==e&&null!==t)o=e-t;else{const e=i.trim().replace(/[\s\u00a0]/g,"").replace(/,/g,""),t=r.trim().replace(/[\s\u00a0]/g,"").replace(/,/g,""),n=Number(e),l=Number(t);o=""!==e&&""!==t&&isFinite(n)&&isFinite(l)?n-l:i.localeCompare(r)}}else o="number"==typeof i&&"number"==typeof r?i-r:String(i).localeCompare(String(r));return"asc"===B?o:-o}))}return e}),[i,D,B,O]),Q=r((()=>K.filter((e=>{for(const[t,n]of Object.entries(P)){const i=parseInt(t),r=O[i],o=v(e,r.key),l=G(o).toLowerCase(),a=n.toLowerCase();if(!l.includes(a))return!1}return!0}))),[K,P,O]);l((()=>{A&&A(Q)}),[Q,A]);const V="undefined"!=typeof window?window.innerHeight-250:600,Z=Math.max(0,Math.floor(_/49)-5),ee=Math.min(Q.length,Math.ceil((_+V)/49)+5),te=Q.slice(Z,ee),ne=49*Q.length,ie=49*Z,re=(e,t)=>{if(void 0!==e.id)return String(e.id);return`row-${t}-${(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)})(O.slice(0,3).map((t=>String(v(e,t.key)??""))).join("-"))}`};return i&&0!==i.length?t(n,{children:[e("div",{className:j.container,onScroll:e=>{J(e.currentTarget.scrollTop)},style:{maxHeight:"calc(100vh - 200px)",overflowY:"auto"},children:t("table",{className:j.table,children:[t("thead",{children:[t("tr",{children:[O.map(((n,i)=>{const r=n.maxWidth?{width:`${n.maxWidth}px`,maxWidth:`${n.maxWidth}px`}:{};return t("th",{className:`${j.th} ${q(n)}`.trim(),style:r,onClick:()=>(e=>{D===e?"asc"===B?z("desc"):"desc"===B&&(F(null),z(null)):(F(e),z("asc"))})(i),children:[X(n),D===i&&e("span",{className:j.sortIndicator,children:"asc"===B?"▲":"▼"})]},i)})),S&&e("th",{className:`${j.th} ${j.actionsColumn}`,style:{width:"100px"},children:U("Actions")})]}),t("tr",{children:[O.map(((n,i)=>{const r=n.maxWidth?{width:`${n.maxWidth}px`,maxWidth:`${n.maxWidth}px`}:{};return e("th",{className:q(n),style:r,children:n.filterable&&t("div",{className:j.filterWrapper,children:[e("input",{type:"text",className:j.filterInput,placeholder:U("Filter")+"...",value:P[i]||"",onChange:e=>((e,t)=>{R((n=>{const i={...n};return""===t.trim()?delete i[e]:i[e]=t,i}))})(i,e.target.value),onClick:e=>e.stopPropagation()}),(P[i]||"").length>0&&e(c,{appearance:"subtle",className:j.clearFilterButton,onClick:e=>{e.stopPropagation(),(e=>{R((t=>{const n={...t};return delete n[e],n}))})(i)},children:"×"})]})},i)})),S&&e("th",{className:j.actionsColumn})]})]}),t("tbody",{children:[Z>0&&e("tr",{style:{height:`${ie}px`},children:e("td",{colSpan:O.length+(S?1:0),style:{padding:0,border:"none"}})}),te.map(((n,i)=>{const r=n._index,o="number"==typeof r?r:Z+i;return t("tr",{className:j.tr,children:[O.map(((i,r)=>{const l=v(n,i.key),a=i.format?i.format(l):G(l),p=i.maxWidth?`${j.td} ${j.tdTruncated} ${q(i)}`.trim():`${j.td} ${q(i)}`.trim(),h=()=>{window.matchMedia("(hover: hover)").matches||i.maxWidth&&a.length>0&&(Y({title:X(i),text:a}),H(!0))};if("file"===i.type&&a)return e("td",{className:p,onClick:h,children:e("a",{href:b.getFileUrl(a),target:"_blank",rel:"noopener noreferrer",children:U("Download")})},r);if("checkbox"===i.type){return e("td",{className:p,children:e(d,{checked:!0===l||"true"===l||"yes"===l||"1"===l,onChange:(e,t)=>{$&&$(n,i.key,!0===t.checked,o)}})},r)}if("enum"===i.type&&i.enumOptions&&i.editable)return e("td",{className:p,children:t(s,{value:a,"aria-label":i.title?U(i.title):Array.isArray(i.key)?i.key[0]:i.key,onChange:(e,t)=>{I&&I(n,i.key,t.value,o)},style:{width:"100%"},children:[!i.enumOptions.includes(a)&&a&&e("option",{value:a,children:a}),i.enumOptions.map((t=>e("option",{value:t,children:U(t)},t)))]})},r);const u=()=>i.maxWidth&&a.length>0?e(x,{content:{children:a,style:{maxWidth:"600px",whiteSpace:"normal"}},relationship:"description",children:e("span",{children:a})}):a;return e("td",{className:p,onClick:h,children:i.action?t("div",{className:j.cellWithAction,children:[e("span",{className:j.cellText,children:u()}),(()=>{if(!i.action)return null;const t=i.action,r=i.action.icon,o=e(c,{appearance:"subtle",icon:e(r,{}),className:j.actionIcon,onClick:e=>{e.stopPropagation(),t.onClick(n)},size:"small"});return t.tooltip?e(x,{content:U(t.tooltip),relationship:"label",children:o}):o})()]}):u()},r)})),S&&(N||W)&&e("td",{className:`${j.td} ${j.actionsColumn}`,children:t("div",{style:{display:"flex",gap:"4px",justifyContent:"center"},children:[N&&e(c,{appearance:"subtle",icon:e(g,{}),className:j.editButton,onClick:()=>N(n,o),title:U("Edit")}),W&&e(c,{appearance:"subtle",icon:e(y,{}),className:j.editButton,onClick:()=>W(n,o),title:U("Delete")})]})})]},re(n,o))})),ee<Q.length&&e("tr",{style:{height:ne-ie-49*te.length+"px"},children:e("td",{colSpan:O.length+(S?1:0),style:{padding:0,border:"none"}})})]})]})}),e(p,{open:L,onOpenChange:(e,t)=>H(t.open),children:e(h,{children:t(u,{children:[e(m,{children:E.title}),e(f,{className:j.dialogContent,children:E.text})]})})})]}):e("div",{className:j.emptyState,children:U("No data to display")})};var N=i.memo(S);export{S as ListView,N as default};
1
+ import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import i,{useMemo as r,useState as o,useEffect as l}from"react";import{makeStyles as a,Button as c,Checkbox as s,Select as d,Dialog as p,DialogSurface as h,DialogBody as u,DialogTitle as m,DialogContent as f,Combobox as x,Option as g,Tooltip as y}from"@fluentui/react-components";import{Edit24Regular as b,Delete24Regular as w}from"@fluentui/react-icons";import{CodicentService as C}from"../services/codicent.js";import k from"../hooks/useLocalization.js";const v=a({container:{width:"100%",overflowX:"auto",userSelect:"text"},table:{width:"100%",borderCollapse:"collapse",backgroundColor:"#ffffff",fontSize:"14px",tableLayout:"fixed",userSelect:"text"},th:{textAlign:"left",padding:"12px 8px",borderBottom:"2px solid #e0e0e0",fontWeight:"600",backgroundColor:"#f5f5f5",position:"sticky",top:0,zIndex:1,cursor:"pointer",userSelect:"none","&:hover":{backgroundColor:"#e8e8e8"}},td:{padding:"12px 8px",borderBottom:"1px solid #e0e0e0",verticalAlign:"top",wordWrap:"break-word",overflow:"hidden",userSelect:"text"},tdTruncated:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap","@media (hover: none)":{cursor:"pointer"}},tr:{"&:hover":{backgroundColor:"#f9f9f9"}},emptyState:{padding:"20px",textAlign:"center",color:"#666"},sortIndicator:{marginLeft:"4px",fontSize:"10px"},hideOnMobile:{"@media (max-width: 768px)":{display:"none"}},dialogContent:{wordWrap:"break-word",whiteSpace:"pre-wrap",maxHeight:"60vh",overflowY:"auto"},thumbnail:{maxWidth:"50px",maxHeight:"50px",objectFit:"cover"},tooltip:{maxWidth:"600px",whiteSpace:"normal",wordWrap:"break-word"},editButton:{minWidth:"auto",padding:"4px 8px"},actionsColumn:{width:"100px",textAlign:"center"},filterInput:{width:"100%",padding:"4px 8px",fontSize:"14px",border:"1px solid #e0e0e0",borderRadius:"4px",paddingRight:"28px"},filterWrapper:{position:"relative"},clearFilterButton:{position:"absolute",right:"6px",top:"50%",transform:"translateY(-50%)",minWidth:"auto",height:"20px",padding:"0 6px",lineHeight:"18px"},filterToolbar:{display:"flex",justifyContent:"flex-end",padding:"8px",gap:"8px"},cellWithAction:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},actionIcon:{minWidth:"auto",padding:"2px",marginLeft:"4px",flexShrink:0,cursor:"pointer",opacity:.7,"&:hover":{opacity:1}},cellText:{flex:1,overflow:"hidden",textOverflow:"ellipsis"}}),S=e=>{if(/^\d{4}-\d{2}-\d{2}/.test(e)){const t=new Date(e);if(!isNaN(t.getTime()))return t.getTime()}const t=e.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})/);if(t){const e=parseInt(t[1],10),n=parseInt(t[2],10)-1,i=parseInt(t[3],10),r=new Date(i,n,e);if(r.getFullYear()===i&&r.getMonth()===n&&r.getDate()===e)return r.getTime()}return null},N=(e,t)=>{if("string"==typeof t)return e[t];for(const n of t)if(void 0!==e[n])return e[n]},W=({value:t,options:n,optionsLoader:a,minChars:c=2,maxResults:s=50,columnKey:d,item:p,actualIndex:h,onEnumChange:u,label:m,t:f})=>{const[y,b]=o(t),[w,C]=o([]),[k,v]=o(!1),S=i.useRef(null);l((()=>{b(t)}),[t]),l((()=>{if(a){if(!(y.length<c))return S.current&&clearTimeout(S.current),S.current=setTimeout((async()=>{v(!0);try{const e=await a(y);C(e.slice(0,s))}finally{v(!1)}}),250),()=>{S.current&&clearTimeout(S.current)};C([])}}),[y,a,c,s]);const N=r((()=>(n??[]).filter((e=>e.toLowerCase().includes(y.toLowerCase()))).slice(0,s)),[n,y,s]),W=a?w:N;return e(x,{value:y,freeform:!0,"aria-label":m,placeholder:k?f("Loading..."):a&&y.length<c?f(`Type ${c}+ characters to search...`):void 0,onChange:e=>b(e.target.value),onOptionSelect:(e,t)=>{t.optionValue&&(b(t.optionValue),u&&u(p,d,t.optionValue,h))},onBlur:()=>{u&&u(p,d,y,h)},style:{width:"100%"},children:W.map((t=>e(g,{value:t,children:t},t)))})},O=({data:i,columns:a,canEdit:x,onEdit:g,onDelete:O,onToggleCheckbox:$,onEnumChange:I,onFilteredDataChange:L})=>{const A=v(),{visibleColumns:T,defaultSortIndex:M,defaultSortDirection:j}=r((()=>{const e=i&&i.length>0?Array.from(new Set(i.flatMap((e=>Object.keys(e))))):[],t=(a||e.map((e=>({key:e})))).filter((e=>!e.hidden)),n=t.findIndex((e=>e.defaultSort));return{visibleColumns:t,defaultSortIndex:n,defaultSortDirection:n>=0&&t[n].defaultSort||null}}),[i,a]),[D,F]=o(M>=0?M:null),[B,z]=o(j),[E,R]=o(!1),[H,Y]=o({title:"",text:""}),[P,V]=o({}),[K,_]=o(0),{t:J}=k(),U=e=>e.title?J(e.title):Array.isArray(e.key)?e.key[0]:e.key,X=e=>{const t=[];return e.hideOnMobile&&t.push(A.hideOnMobile),t.join(" ")},q=e=>null==e||"string"==typeof e&&e.startsWith("[")&&e.endsWith("]")?"":"object"==typeof e?JSON.stringify(e):String(e),G=r((()=>{const e=[...i];if(null!==D&&B){const t=T[D];e.sort(((e,n)=>{const i=N(e,t.key),r=N(n,t.key);if(null==i)return 1;if(null==r)return-1;let o=0;if("string"==typeof i&&"string"==typeof r){const e=S(i),t=S(r);if(null!==e&&null!==t)o=e-t;else{const e=i.trim().replace(/[\s\u00a0]/g,"").replace(/,/g,""),t=r.trim().replace(/[\s\u00a0]/g,"").replace(/,/g,""),n=Number(e),l=Number(t);o=""!==e&&""!==t&&isFinite(n)&&isFinite(l)?n-l:i.localeCompare(r)}}else o="number"==typeof i&&"number"==typeof r?i-r:String(i).localeCompare(String(r));return"asc"===B?o:-o}))}return e}),[i,D,B,T]),Q=r((()=>G.filter((e=>{for(const[t,n]of Object.entries(P)){const i=parseInt(t),r=T[i],o=N(e,r.key),l=q(o).toLowerCase(),a=n.toLowerCase();if(!l.includes(a))return!1}return!0}))),[G,P,T]);l((()=>{L&&L(Q)}),[Q,L]);const Z="undefined"!=typeof window?window.innerHeight-250:600,ee=Math.max(0,Math.floor(K/49)-5),te=Math.min(Q.length,Math.ceil((K+Z)/49)+5),ne=Q.slice(ee,te),ie=49*Q.length,re=49*ee,oe=(e,t)=>{if(void 0!==e.id)return String(e.id);return`row-${t}-${(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)})(T.slice(0,3).map((t=>String(N(e,t.key)??""))).join("-"))}`};return i&&0!==i.length?t(n,{children:[e("div",{className:A.container,onScroll:e=>{_(e.currentTarget.scrollTop)},style:{maxHeight:"calc(100vh - 200px)",overflowY:"auto"},children:t("table",{className:A.table,children:[t("thead",{children:[t("tr",{children:[T.map(((n,i)=>{const r=n.maxWidth?{width:`${n.maxWidth}px`,maxWidth:`${n.maxWidth}px`}:{};return t("th",{className:`${A.th} ${X(n)}`.trim(),style:r,onClick:()=>(e=>{D===e?"asc"===B?z("desc"):"desc"===B&&(F(null),z(null)):(F(e),z("asc"))})(i),children:[U(n),D===i&&e("span",{className:A.sortIndicator,children:"asc"===B?"▲":"▼"})]},i)})),x&&e("th",{className:`${A.th} ${A.actionsColumn}`,style:{width:"100px"},children:J("Actions")})]}),t("tr",{children:[T.map(((n,i)=>{const r=n.maxWidth?{width:`${n.maxWidth}px`,maxWidth:`${n.maxWidth}px`}:{};return e("th",{className:X(n),style:r,children:n.filterable&&t("div",{className:A.filterWrapper,children:[e("input",{type:"text",className:A.filterInput,placeholder:J("Filter")+"...",value:P[i]||"",onChange:e=>((e,t)=>{V((n=>{const i={...n};return""===t.trim()?delete i[e]:i[e]=t,i}))})(i,e.target.value),onClick:e=>e.stopPropagation()}),(P[i]||"").length>0&&e(c,{appearance:"subtle",className:A.clearFilterButton,onClick:e=>{e.stopPropagation(),(e=>{V((t=>{const n={...t};return delete n[e],n}))})(i)},children:"×"})]})},i)})),x&&e("th",{className:A.actionsColumn})]})]}),t("tbody",{children:[ee>0&&e("tr",{style:{height:`${re}px`},children:e("td",{colSpan:T.length+(x?1:0),style:{padding:0,border:"none"}})}),ne.map(((n,i)=>{const r=n._index,o="number"==typeof r?r:ee+i;return t("tr",{className:A.tr,children:[T.map(((i,r)=>{const l=N(n,i.key),a=i.format?i.format(l):q(l),p=i.maxWidth?`${A.td} ${A.tdTruncated} ${X(i)}`.trim():`${A.td} ${X(i)}`.trim(),h=()=>{window.matchMedia("(hover: hover)").matches||i.maxWidth&&a.length>0&&(Y({title:U(i),text:a}),R(!0))};if("file"===i.type&&a)return e("td",{className:p,onClick:h,children:e("a",{href:C.getFileUrl(a),target:"_blank",rel:"noopener noreferrer",children:J("Download")})},r);if("checkbox"===i.type){return e("td",{className:p,children:e(s,{checked:!0===l||"true"===l||"yes"===l||"1"===l,onChange:(e,t)=>{$&&$(n,i.key,!0===t.checked,o)}})},r)}if("enum"===i.type&&i.enumOptions&&i.editable)return e("td",{className:p,children:t(d,{value:a,"aria-label":i.title?J(i.title):Array.isArray(i.key)?i.key[0]:i.key,onChange:(e,t)=>{I&&I(n,i.key,t.value,o)},style:{width:"100%"},children:[!i.enumOptions.includes(a)&&a&&e("option",{value:a,children:a}),i.enumOptions.map((t=>e("option",{value:t,children:J(t)},t)))]})},r);if("combobox"===i.type&&i.editable&&(i.enumOptions||i.enumOptionsLoader))return e("td",{className:p,children:e(W,{value:a,options:i.enumOptions,optionsLoader:i.enumOptionsLoader,minChars:i.enumOptionsLoaderMinChars,maxResults:i.enumOptionsLoaderMaxResults,columnKey:i.key,item:n,actualIndex:o,onEnumChange:I,label:i.title?J(i.title):Array.isArray(i.key)?i.key[0]:i.key,t:J})},r);const u=()=>i.maxWidth&&a.length>0?e(y,{content:{children:a,style:{maxWidth:"600px",whiteSpace:"normal"}},relationship:"description",children:e("span",{children:a})}):a,m=()=>{if(!i.action)return null;const t=i.action,r=i.action.icon,o=e(c,{appearance:"subtle",icon:e(r,{}),className:A.actionIcon,onClick:e=>{e.stopPropagation(),t.onClick(n)},size:"small"});return t.tooltip?e(y,{content:J(t.tooltip),relationship:"label",children:o}):o};return e("td",{className:p,onClick:h,children:i.action?t("div",{className:A.cellWithAction,children:[i.action.iconLeft&&m(),e("span",{className:A.cellText,children:u()}),!i.action.iconLeft&&m()]}):u()},r)})),x&&(g||O)&&e("td",{className:`${A.td} ${A.actionsColumn}`,children:t("div",{style:{display:"flex",gap:"4px",justifyContent:"center"},children:[g&&e(c,{appearance:"subtle",icon:e(b,{}),className:A.editButton,onClick:()=>g(n,o),title:J("Edit")}),O&&e(c,{appearance:"subtle",icon:e(w,{}),className:A.editButton,onClick:()=>O(n,o),title:J("Delete")})]})})]},oe(n,o))})),te<Q.length&&e("tr",{style:{height:ie-re-49*ne.length+"px"},children:e("td",{colSpan:T.length+(x?1:0),style:{padding:0,border:"none"}})})]})]})}),e(p,{open:E,onOpenChange:(e,t)=>R(t.open),children:e(h,{children:t(u,{children:[e(m,{children:H.title}),e(f,{className:A.dialogContent,children:H.text})]})})})]}):e("div",{className:A.emptyState,children:J("No data to display")})};var $=i.memo(O);export{O as ListView,$ as default};
@@ -1 +1 @@
1
- {"version":3,"file":"RecordModal.d.ts","sourceRoot":"","sources":["../../../src/components/RecordModal.tsx"],"names":[],"mappings":"AAWA,OAAO,KAA8B,MAAM,OAAO,CAAC;AAkBnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAoB9C,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,OAAO,CAAC;IACd,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD,OAAO,EAAE,gBAAgB,EAAE,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC,gBAAgB,CAsIlD,CAAC;AAEF,eAAe,WAAW,CAAC"}
1
+ {"version":3,"file":"RecordModal.d.ts","sourceRoot":"","sources":["../../../src/components/RecordModal.tsx"],"names":[],"mappings":"AAWA,OAAO,KAAuC,MAAM,OAAO,CAAC;AAoB5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AA6G9C,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,OAAO,CAAC;IACd,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD,OAAO,EAAE,gBAAgB,EAAE,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC,gBAAgB,CAuJlD,CAAC;AAEF,eAAe,WAAW,CAAC"}
@@ -1 +1 @@
1
- import{jsx as e,jsxs as r}from"react/jsx-runtime";import{useState as a,useEffect as n}from"react";import{makeStyles as o,tokens as l,Dialog as c,DialogSurface as t,DialogBody as i,DialogTitle as s,DialogContent as d,Field as p,Checkbox as u,Textarea as h,Select as m,Input as f,DialogActions as y,Button as g}from"@fluentui/react-components";import k from"../hooks/useLocalization.js";const v=o({surface:{backgroundColor:l.colorNeutralBackground1},content:{display:"flex",flexDirection:"column",gap:"16px",minWidth:"400px",maxHeight:"60vh",overflowY:"auto"},field:{display:"flex",flexDirection:"column"}}),C=({open:o,onClose:l,onSave:C,columns:b,initialData:x,title:N})=>{const w=v(),{t:A}=k(),[S,D]=a({}),[E,L]=a(!1);n((()=>{o&&D(x||{})}),[o,x]);const O=e=>Array.isArray(e.key)?e.key[0]:e.key,j=e=>{if(Array.isArray(e.key))for(const r of e.key)if(void 0!==S[r])return r;return O(e)},z=(e,r)=>{const a=j(e);D((e=>({...e,[a]:r})))},R=b.filter((e=>!e.hidden&&"file"!==e.type&&"createdAt"!==O(e)));return e(c,{open:o,onOpenChange:(e,r)=>!E&&!1===r.open&&l(),children:e(t,{className:w.surface,backdrop:{style:{backgroundColor:"rgba(0, 0, 0, 0.4)"}},children:r(i,{children:[e(s,{children:N||A(x?"Edit Record":"Add Record")}),e(d,{className:w.content,children:R.map(((r,a)=>{const n=O(r),o=(e=>{const r=j(e);return S[r]})(r),l=r.title||n;return"checkbox"===r.type?e(p,{label:l,className:w.field,children:e(u,{checked:!0===o||"true"===o||"yes"===o||"1"===o,onChange:(e,a)=>z(r,a.checked)})},a):"textarea"===r.type?e(p,{label:l,className:w.field,children:e(h,{value:String(o??""),rows:r.rows??3,onChange:(e,a)=>z(r,a.value),placeholder:A("Enter")+" "+l.toLowerCase(),resize:"vertical"})},a):"enum"===r.type&&r.enumOptions?e(p,{label:l,className:w.field,children:e(m,{value:String(o??""),onChange:(e,a)=>z(r,a.value),children:r.enumOptions.map((r=>e("option",{value:r,children:r||A("(None)")},r)))})},a):e(p,{label:l,className:w.field,children:e(f,{value:String(o??""),onChange:(e,a)=>z(r,a.value),placeholder:A("Enter")+" "+l.toLowerCase()})},a)}))}),r(y,{children:[e(g,{appearance:"secondary",onClick:l,disabled:E,children:A("Cancel")}),e(g,{appearance:"primary",onClick:async()=>{L(!0);try{await C(S),l()}catch(e){console.error("Failed to save record:",e)}finally{L(!1)}},disabled:E,children:A(E?"Saving...":"Save")})]})]})})})};export{C as RecordModal,C as default};
1
+ import{jsx as e,jsxs as n}from"react/jsx-runtime";import a,{useState as r,useEffect as o,useMemo as l}from"react";import{makeStyles as t,tokens as i,Dialog as c,DialogSurface as s,DialogBody as d,DialogTitle as u,DialogContent as p,Field as h,Checkbox as m,Textarea as f,Select as y,Input as g,DialogActions as v,Button as C,Combobox as b,Option as k}from"@fluentui/react-components";import x from"../hooks/useLocalization.js";const L=t({surface:{backgroundColor:i.colorNeutralBackground1},content:{display:"flex",flexDirection:"column",gap:"16px",minWidth:"400px",maxHeight:"60vh",overflowY:"auto"},field:{display:"flex",flexDirection:"column"}}),w=({value:n,options:t,optionsLoader:i,minChars:c=2,maxResults:s=50,label:d,onChange:u,t:p})=>{const[h,m]=r(n),[f,y]=r([]),[g,v]=r(!1),C=a.useRef(null);o((()=>{m(n)}),[n]),o((()=>{if(i){if(!(h.length<c))return C.current&&clearTimeout(C.current),C.current=setTimeout((async()=>{v(!0);try{const e=await i(h);y(e.slice(0,s))}finally{v(!1)}}),250),()=>{C.current&&clearTimeout(C.current)};y([])}}),[h,i,c,s]);const x=l((()=>(t??[]).filter((e=>e.toLowerCase().includes(h.toLowerCase()))).slice(0,s)),[t,h,s]),L=i?f:x;return e(b,{value:h,freeform:!0,"aria-label":d,placeholder:g?p("Loading..."):i&&h.length<c?p(`Type ${c}+ characters to search...`):void 0,onChange:e=>m(e.target.value),onOptionSelect:(e,n)=>{n.optionValue&&(m(n.optionValue),u(n.optionValue))},onBlur:()=>u(h),style:{width:"100%"},children:L.map((n=>e(k,{value:n,children:n},n)))})},O=({open:a,onClose:l,onSave:t,columns:i,initialData:b,title:k})=>{const O=L(),{t:N}=x(),[S,A]=r({}),[R,T]=r(!1);o((()=>{a&&A(b||{})}),[a,b]);const D=e=>Array.isArray(e.key)?e.key[0]:e.key,E=e=>{if(Array.isArray(e.key))for(const n of e.key)if(void 0!==S[n])return n;return D(e)},V=(e,n)=>{const a=E(e);A((e=>({...e,[a]:n})))},j=i.filter((e=>!e.hidden&&"file"!==e.type&&"createdAt"!==D(e)));return e(c,{open:a,onOpenChange:(e,n)=>!R&&!1===n.open&&l(),children:e(s,{className:O.surface,backdrop:{style:{backgroundColor:"rgba(0, 0, 0, 0.4)"}},children:n(d,{children:[e(u,{children:k||N(b?"Edit Record":"Add Record")}),e(p,{className:O.content,children:j.map(((n,a)=>{const r=D(n),o=(e=>{const n=E(e);return S[n]})(n),l=n.title||r;return"checkbox"===n.type?e(h,{label:l,className:O.field,children:e(m,{checked:!0===o||"true"===o||"yes"===o||"1"===o,onChange:(e,a)=>V(n,a.checked)})},a):"textarea"===n.type?e(h,{label:l,className:O.field,children:e(f,{value:String(o??""),rows:n.rows??3,onChange:(e,a)=>V(n,a.value),placeholder:N("Enter")+" "+l.toLowerCase(),resize:"vertical"})},a):"enum"===n.type&&n.enumOptions?e(h,{label:l,className:O.field,children:e(y,{value:String(o??""),onChange:(e,a)=>V(n,a.value),children:n.enumOptions.map((n=>e("option",{value:n,children:n||N("(None)")},n)))})},a):"combobox"===n.type&&(n.enumOptions||n.enumOptionsLoader)?e(h,{label:l,className:O.field,children:e(w,{value:String(o??""),options:n.enumOptions,optionsLoader:n.enumOptionsLoader,minChars:n.enumOptionsLoaderMinChars,maxResults:n.enumOptionsLoaderMaxResults,label:l,onChange:e=>V(n,e),t:N})},a):e(h,{label:l,className:O.field,children:e(g,{value:String(o??""),onChange:(e,a)=>V(n,a.value),placeholder:N("Enter")+" "+l.toLowerCase()})},a)}))}),n(v,{children:[e(C,{appearance:"secondary",onClick:l,disabled:R,children:N("Cancel")}),e(C,{appearance:"primary",onClick:async()=>{T(!0);try{await t(S),l()}catch(e){console.error("Failed to save record:",e)}finally{T(!1)}},disabled:R,children:N(R?"Saving...":"Save")})]})]})})})};export{O as RecordModal,O as default};
@@ -0,0 +1,81 @@
1
+ import { Dispatch } from "react";
2
+ import { AppInfo, CodicentService } from "../services/codicent";
3
+ import { StateContext } from "../utils/appState";
4
+ export type AppPhase = "authenticating" | "notAuthenticated" | "checkingCodicentAccess" | "registering" | "registered" | "loadingUser" | "checkingPurchase" | "needsPurchase" | "gettingApps" | "creatingApp" | "checkingAccess" | "noAccess" | "hasAccess" | "loggingOut" | "error" | "anonymous" | "restoringFromCache" | "validatingCache";
5
+ export type AppAction = {
6
+ type: "LOGOUT";
7
+ } | {
8
+ type: "NOT_AUTHENTICATED";
9
+ } | {
10
+ type: "AUTHENTICATED";
11
+ accessToken: string;
12
+ user: {
13
+ sub: string;
14
+ email: string;
15
+ };
16
+ } | {
17
+ type: "REGISTERED";
18
+ nickname: string;
19
+ } | {
20
+ type: "NOT_REGISTERED";
21
+ } | {
22
+ type: "REGISTER_AUTO_SUCCESS";
23
+ nickname: string;
24
+ } | {
25
+ type: "REGISTER_AUTO_FAIL";
26
+ error: string;
27
+ errorType?: StateContext["errorType"];
28
+ } | {
29
+ type: "USER_LOADED";
30
+ name: string;
31
+ } | {
32
+ type: "PURCHASE_VALID";
33
+ } | {
34
+ type: "PURCHASE_INVALID";
35
+ } | {
36
+ type: "APPS_LOADED";
37
+ apps: AppInfo[];
38
+ } | {
39
+ type: "APPS_FAILED";
40
+ error: string;
41
+ } | {
42
+ type: "APP_CREATED";
43
+ appId: string;
44
+ } | {
45
+ type: "APP_CREATE_FAILED";
46
+ error: string;
47
+ } | {
48
+ type: "SET_ANONYMOUS";
49
+ } | {
50
+ type: "SET_SELECTED_APP";
51
+ appId: string;
52
+ } | {
53
+ type: "UPDATE_CONTEXT";
54
+ updates: Partial<StateContext>;
55
+ } | {
56
+ type: "CACHE_VALIDATED";
57
+ } | {
58
+ type: "CACHE_VALIDATION_FAILED";
59
+ lenient: boolean;
60
+ };
61
+ export interface AppReducerState {
62
+ phase: AppPhase;
63
+ context: StateContext;
64
+ }
65
+ /** Phases where isBusy() should return true */
66
+ export declare const BUSY_PHASES: AppPhase[];
67
+ export declare const isBusyPhase: (phase: AppPhase) => boolean;
68
+ export declare function appStateReducer(state: AppReducerState, action: AppAction): AppReducerState;
69
+ /**
70
+ * Creates the initial reducer state. Reads the cache synchronously so the
71
+ * very first render is already in the correct phase (no flicker).
72
+ */
73
+ export declare function createInitialState(): AppReducerState;
74
+ /** Persist the current session to localStorage cache. */
75
+ export declare function saveSession(context: StateContext): void;
76
+ /**
77
+ * Runs the three background validation checks (registration, purchase, apps)
78
+ * after restoring from cache. Dispatches CACHE_VALIDATED or CACHE_VALIDATION_FAILED.
79
+ */
80
+ export declare function runBackgroundValidation(service: CodicentService, context: StateContext, dispatch: Dispatch<AppAction>): Promise<void>;
81
+ //# sourceMappingURL=useAppState.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAppState.d.ts","sourceRoot":"","sources":["../../../src/hooks/useAppState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACjC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAGhE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGjD,MAAM,MAAM,QAAQ,GAChB,gBAAgB,GAChB,kBAAkB,GAClB,wBAAwB,GACxB,aAAa,GACb,YAAY,GACZ,aAAa,GACb,kBAAkB,GAClB,eAAe,GACf,aAAa,GACb,aAAa,GACb,gBAAgB,GAChB,UAAU,GACV,WAAW,GACX,YAAY,GACZ,OAAO,GACP,WAAW,GACX,oBAAoB,GACpB,iBAAiB,CAAC;AAEtB,MAAM,MAAM,SAAS,GACjB;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE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BAAiB,CAAA;CAAE,GAC3B;IAAE,IAAI,EAAE,yBAAyB,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC;AAE1D,MAAM,WAAW,eAAe;IAC9B,KAAK,EAAE,QAAQ,CAAC;IAChB,OAAO,EAAE,YAAY,CAAC;CACvB;AAED,+CAA+C;AAC/C,eAAO,MAAM,WAAW,EAAE,QAAQ,EASjC,CAAC;AAEF,eAAO,MAAM,WAAW,UAAW,QAAQ,YAAgC,CAAC;AA+C5E,wBAAgB,eAAe,CAAC,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,SAAS,GAAG,eAAe,CAiM1F;AAcD;;;GAGG;AACH,wBAAgB,kBAAkB,IAAI,eAAe,CA+BpD;AAED,yDAAyD;AACzD,wBAAgB,WAAW,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAkBvD;AAED;;;GAGG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,YAAY,EACrB,QAAQ,EAAE,QAAQ,CAAC,SAAS,CAAC,GAC5B,OAAO,CAAC,IAAI,CAAC,CAqCf"}
@@ -0,0 +1 @@
1
+ import{getConfigValue as e}from"../config/index.js";import{stateMachineCacheManager as t}from"../utils/cacheManager.js";const s=["checkingCodicentAccess","registering","loadingUser","checkingPurchase","gettingApps","creatingApp","checkingAccess","loggingOut"],n=e=>s.includes(e);function c(){const t={isAuthenticated:!1,isRegistered:void 0,hasValidPurchase:void 0,hasAccess:!1,selectedApp:void 0,error:null,errorType:void 0,accessToken:void 0,nickname:void 0,apps:[],hasApps:!1,appsLoaded:!1,user:void 0,name:void 0,isAnonymous:void 0,isFromCache:void 0,needsValidation:void 0};return e("APP_NAME")?localStorage.removeItem("selectedApp"):t.selectedApp=localStorage.getItem("selectedApp")||void 0,e("APP_PREFIX")&&t.selectedApp&&!t.selectedApp.startsWith(e("APP_PREFIX"))&&(t.selectedApp=void 0),t}function a(t,s){switch(s.type){case"LOGOUT":return{phase:"loggingOut",context:c()};case"NOT_AUTHENTICATED":return"loggingOut"===t.phase||"anonymous"===t.phase?t:"hasAccess"===t.phase?{phase:"loggingOut",context:c()}:{phase:"notAuthenticated",context:c()};case"AUTHENTICATED":{const{accessToken:e,user:n}=s;return"anonymous"===t.phase?t:"hasAccess"===t.phase&&t.context.isFromCache?{...t,context:{...t.context,accessToken:e,user:n,isAuthenticated:!0}}:"hasAccess"===t.phase?t:{phase:"checkingCodicentAccess",context:{...t.context,isAuthenticated:!0,accessToken:e,user:n}}}case"REGISTERED":case"REGISTER_AUTO_SUCCESS":return localStorage.setItem("nickname",s.nickname),{phase:"loadingUser",context:{...t.context,isRegistered:!0,nickname:s.nickname}};case"NOT_REGISTERED":return{phase:"registering",context:{...t.context,isRegistered:!1}};case"REGISTER_AUTO_FAIL":return{phase:"error",context:{...t.context,error:s.error,errorType:s.errorType}};case"USER_LOADED":return{phase:e("SUBSCRIPTION_NEEDED")?"checkingPurchase":"gettingApps",context:{...t.context,name:s.name}};case"PURCHASE_VALID":return{phase:"gettingApps",context:{...t.context,hasValidPurchase:!0}};case"PURCHASE_INVALID":return{phase:"needsPurchase",context:{...t.context,hasValidPurchase:!1}};case"APPS_LOADED":{const{apps:n}=s,c=e("APP_NAME")||void 0,a=e("APP_PREFIX")||void 0,r=a?n.filter((e=>e.id.startsWith(a))):n;if(0===r.length&&!c)return{phase:"creatingApp",context:{...t.context,apps:r,hasApps:!1,appsLoaded:!0,selectedApp:void 0}};const o=function(e,t,s){return s?e.some((e=>e.id===s))?s:null:t&&e.some((e=>e.id===t))?t:e.length>0?e[0].id:null}(r,t.context.selectedApp,c);return o?{phase:"hasAccess",context:{...t.context,apps:r,hasApps:!0,appsLoaded:!0,selectedApp:o,hasAccess:!0}}:{phase:"noAccess",context:{...t.context,apps:r,hasApps:r.length>0,appsLoaded:!0}}}case"APPS_FAILED":return{phase:"error",context:{...t.context,error:s.error,errorType:"ErrorGettingApps"}};case"APP_CREATED":return{phase:"hasAccess",context:{...t.context,selectedApp:s.appId,apps:[...t.context.apps||[],{id:s.appId,title:s.appId,logo:""}],hasApps:!0,appsLoaded:!0,hasAccess:!0}};case"APP_CREATE_FAILED":return{phase:"error",context:{...t.context,error:s.error,errorType:"ErrorCreatingApp"}};case"SET_ANONYMOUS":return{phase:"anonymous",context:{...t.context,isAnonymous:!0}};case"SET_SELECTED_APP":return localStorage.setItem("selectedApp",s.appId),"hasAccess"===t.phase?{...t,context:{...t.context,selectedApp:s.appId}}:{phase:"gettingApps",context:{...t.context,selectedApp:s.appId,hasApps:!1,appsLoaded:!1}};case"UPDATE_CONTEXT":{const e={...t.context,...s.updates},n=["authenticating","checkingCodicentAccess","registering","loadingUser","checkingPurchase","gettingApps","creatingApp","checkingAccess","notAuthenticated"];if("error"in s.updates&&s.updates.error&&n.includes(t.phase))return{phase:"error",context:e};if("needsPurchase"===t.phase&&"hasValidPurchase"in s.updates&&void 0===s.updates.hasValidPurchase)return{phase:"checkingPurchase",context:{...e,hasValidPurchase:void 0}};if("error"===t.phase&&"error"in s.updates&&null===s.updates.error){const s=t.context.errorType;let n="checkingCodicentAccess";return"ErrorLoadingUser"===s?n="loadingUser":"ErrorCheckingPurchase"===s?n="checkingPurchase":"ErrorGettingApps"===s?n="gettingApps":"ErrorCreatingApp"===s?n="creatingApp":"ErrorCheckingAccess"===s&&(n="checkingAccess"),{phase:n,context:{...e,error:null,errorType:void 0}}}return{...t,context:e}}case"CACHE_VALIDATED":return{...t,context:{...t.context,needsValidation:!1,isFromCache:!1}};case"CACHE_VALIDATION_FAILED":return s.lenient?{...t,context:{...t.context,needsValidation:!0}}:{phase:"authenticating",context:c()};default:return t}}function r(){if(e("ENABLE_STATE_CACHE")){const s=t.get("user_session");if(s&&function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.nickname&&"string"==typeof t.selectedApp&&Array.isArray(t.apps)&&"boolean"==typeof t.isRegistered&&"boolean"==typeof t.hasValidPurchase}(s.data)){const t=s.data;return console.log("AppState: Restoring from cache",{nickname:t.nickname,selectedApp:t.selectedApp,appsCount:t.apps.length,age:Math.round((Date.now()-s.cachedAt)/1e3)+"s"}),{phase:"hasAccess",context:{...c(),nickname:t.nickname,name:t.name,selectedApp:t.selectedApp,apps:t.apps,hasValidPurchase:t.hasValidPurchase,isRegistered:t.isRegistered,hasAccess:!0,hasApps:t.apps.length>0,appsLoaded:!0,isFromCache:!0,needsValidation:Boolean(e("VALIDATE_CACHE_IN_BACKGROUND"))}}}}return{phase:"authenticating",context:c()}}function o(s){if(!e("ENABLE_STATE_CACHE"))return;if(!s.nickname||!s.selectedApp)return;const n={nickname:s.nickname,name:s.name||"",selectedApp:s.selectedApp,apps:s.apps||[],hasValidPurchase:s.hasValidPurchase||!1,isRegistered:s.isRegistered||!1,cachedAt:Date.now(),expiresAt:Date.now()+e("SESSION_CACHE_TTL"),version:"1.0.0"};t.set("user_session",n,e("SESSION_CACHE_TTL")),console.log("AppState: Saved session to cache")}async function p(t,s,n){try{const[c,a,r]=await Promise.all([t.getNickname().then((e=>e===s.nickname)).catch((()=>!1)),e("SUBSCRIPTION_NEEDED")?t.checkSubscriptionStatus().then((e=>("active"===e||"trialing"===e)===s.hasValidPurchase)).catch((()=>!1)):Promise.resolve(!0),t.getApps().then((t=>{if(!t)return!1;const n=e("APP_PREFIX")||void 0,c=n?t.filter((e=>e.id.startsWith(n))):t,a=s.apps||[];return c.length===a.length&&c.every((e=>a.some((t=>t.id===e.id))))})).catch((()=>!1))]);if(c&&a&&r)o(s),n({type:"CACHE_VALIDATED"});else{n({type:"CACHE_VALIDATION_FAILED",lenient:"strict"!==e("CACHE_FAILURE_MODE")})}}catch{}}export{s as BUSY_PHASES,a as appStateReducer,r as createInitialState,n as isBusyPhase,p as runBackgroundValidation,o as saveSession};
@@ -1 +1 @@
1
- {"version":3,"file":"useAuthState.d.ts","sourceRoot":"","sources":["../../../src/hooks/useAuthState.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,oBA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AqB,YAAY,gBAAgB,KAAG,YA+QhF,CAAC;AAEF,eAAe,YAAY,CAAC"}
@@ -1 +1 @@
1
- import{useState as o,useMemo as e,useEffect as t,useCallback as s}from"react";import{CodicentService as n}from"../services/codicent.js";import"../components/Markdown.js";import"../components/Textarea.js";import"../components/Button.js";import"../components/CompoundButton.js";import"react/jsx-runtime";import"@fluentui/react-components";import"../components/Spinner.js";import"../components/TextHeader.js";import"../components/TypingIndicator.js";import"../components/Dialog.js";import"../components/ChatInput.js";import"../components/CombinedPlaceholderDialog.js";import"../components/ChatMessage.js";import"../components/Header.js";import"@fluentui/react-icons";import{getConfigValue as i}from"../config/index.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"./useLocalization.js";import"./useAppStyles.js";import"../components/FileThumbnail.js";import"../components/MessageInput.js";import"../components/UploadFile.js";import"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import"../components/Content.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/DataMessagePicker.js";import"../components/HtmlView.js";import"../components/Footer.js";import"../components/Page.js";import"../components/QrCodeDialog.js";import"../components/QrScanner.js";import"../components/OfflineMessage.js";import"../components/LanguageSelector.js";import"../components/ListView.js";import"../components/RecordModal.js";import"../components/BulkUploadDialog.js";import"../components/CookieBanner.js";import"../pages/AppFrame.js";import"../pages/Chat.js";import"../pages/Compose.js";import"../pages/Snap.js";import"../pages/Search.js";import"../pages/Login.js";import"../pages/CrmPage.js";import"../pages/CrmPagePersistent.js";import"../pages/ImageView.js";import"../pages/FormInvite.js";import"../pages/FormAccept.js";import"../pages/Sales.js";import"../pages/Purchase.js";import"../pages/QrScan.js";import"react-dom/client";import"react-router-dom";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";const r=(r,p)=>{const{isAuthenticated:a,getAccessTokenSilently:m,user:c,isLoading:l,logout:g,getAccessTokenWithPopup:u,loginWithRedirect:j,loginWithPopup:P}=r,[E,d]=o(null),[_,T]=o(void 0),[S,C]=o(null),[A,I]=o(""),O=e((()=>new n({API_BASE_URL:i("API_BASE_URL"),PUBSUB_URL:i("PUBSUB_URL"),APP_LOG_CODICENT:i("APP_LOG_CODICENT"),APP_LOG_TOKEN:i("APP_LOG_TOKEN"),APP_NAME:i("APP_NAME"),APP_PREFIX:i("APP_PREFIX"),APP_TEMPLATE:i("APP_TEMPLATE"),BUTTON_TAG:i("BUTTON_TAG"),STRIPE_PUBLIC_KEY:i("STRIPE_PUBLIC_KEY"),STRIPE_SOURCE:i("STRIPE_SOURCE"),STRIPE_TRIAL_PERIOD_DAYS:i("STRIPE_TRIAL_PERIOD_DAYS"),SUBSCRIPTION_NEEDED:i("SUBSCRIPTION_NEEDED"),USER_PREFIX:i("USER_PREFIX"),ANONYMOUS_TOKEN:i("ANONYMOUS_TOKEN")})),[]);t((()=>{!l&&a&&(async()=>{try{const o=await m({});console.debug("CODICENT: ACCESS TOKEN",o),d(o)}catch(o){console.debug("CODICENT: Failed to get access token",o);const e=o;if(e&&"object"==typeof e&&"error"in e&&"login_required"===e.error)console.warn("CODICENT: Login required"),R();else if(e&&"object"==typeof e&&"error"in e&&"consent_required"===e.error)try{const o=await u();if(!o)return void C("Failed to get access token: no token from auth0 with popup");console.log("CODICENT: GOT ACCESS TOKEN"),d(o)}catch(o){console.warn("CODICENT: Failed to get access token with popup",o),R()}else C("Failed to get access token: "+(e.message?.toString()||e.toString())),console.log("CODICENT: ACCESS TOKEN ERROR",e)}})().then((()=>{}))}),[a,u,m,j,l]),t((()=>{if(c&&c.sub&&E&&void 0===_){let o=!0;return(p?.loginFn?p.loginFn(O,c.sub,E):O.loginUser(c.sub,E)).then((e=>{o&&(null===e?T(!1):""===e?C("Kontrollera internetanslutningen och försök igen."):(O.setToken(e),O.getNickname().then(I),T(!0)))})).catch((()=>{o&&(C("Ett fel uppstod. Försök igen senare."),T(!1))})),()=>{o=!1}}}),[c,E,_,O]);const R=s((()=>{O.logout(),d(null),C(null),T(void 0),I(""),g({logoutParams:{returnTo:i("AUTH_REDIRECT_URL")}})}),[O,g]),h=s((async o=>{const e=p?.registerFn?await p.registerFn(O,o,c.email,c.sub,E):await O.registerUser(o,c.email,c.sub,E);return e&&(O.setToken(e),T(!0)),e}),[O,c,E]);t((()=>{O.onUnauthorized=R}),[O]);const N=s((async o=>{try{await P({authorizationParams:{connection:"email",login_hint:o}})}catch(o){console.error("Passwordless login failed:",o),C(`Passwordless login failed: ${o}`)}}),[P]);return e((()=>({isAuthenticated:a,isRegistered:_,accessToken:E,authError:S,isLoading:l,user:c,nickname:A,logout:R,registerUser:h,codicentService:O,loginWithRedirect:j,loginPasswordless:N})),[a,_,E,S,l,c,A,R,h,O,j,N])};export{r as default};
1
+ import{useState as o,useMemo as e,useEffect as t,useCallback as s}from"react";import{CodicentService as n}from"../services/codicent.js";import"../components/Markdown.js";import"../components/Textarea.js";import"../components/Button.js";import"../components/CompoundButton.js";import"react/jsx-runtime";import"@fluentui/react-components";import"../components/Spinner.js";import"../components/TextHeader.js";import"../components/TypingIndicator.js";import"../components/Dialog.js";import"../components/ChatInput.js";import"../components/CombinedPlaceholderDialog.js";import"../components/ChatMessage.js";import"../components/Header.js";import"@fluentui/react-icons";import{getConfigValue as i}from"../config/index.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"./useLocalization.js";import"./useAppStyles.js";import"../components/FileThumbnail.js";import"../components/MessageInput.js";import"../components/UploadFile.js";import"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import"../components/Content.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/DataMessagePicker.js";import"../components/HtmlView.js";import"../components/Footer.js";import"../components/Page.js";import"../components/QrCodeDialog.js";import"../components/QrScanner.js";import"../components/OfflineMessage.js";import"../components/LanguageSelector.js";import"../components/ListView.js";import"../components/RecordModal.js";import"../components/BulkUploadDialog.js";import"../components/CookieBanner.js";import"../pages/AppFrame.js";import"../pages/Chat.js";import"../pages/Compose.js";import"../pages/Snap.js";import"../pages/Search.js";import"../pages/Login.js";import"../pages/CrmPage.js";import"../pages/CrmPagePersistent.js";import"../pages/ImageView.js";import"../pages/FormInvite.js";import"../pages/FormAccept.js";import"../pages/Sales.js";import"../pages/Purchase.js";import"../pages/QrScan.js";import"react-dom/client";import"react-router-dom";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";const r=(r,p)=>{const{isAuthenticated:a,getAccessTokenSilently:m,user:c,isLoading:l,logout:g,getAccessTokenWithPopup:u,loginWithRedirect:j,loginWithPopup:P}=r,[E,d]=o(null),[_,T]=o(void 0),[S,C]=o(null),[A,I]=o(""),h=e((()=>new n({API_BASE_URL:i("API_BASE_URL"),PUBSUB_URL:i("PUBSUB_URL"),APP_LOG_CODICENT:i("APP_LOG_CODICENT"),APP_LOG_TOKEN:i("APP_LOG_TOKEN"),APP_NAME:i("APP_NAME"),APP_PREFIX:i("APP_PREFIX"),APP_TEMPLATE:i("APP_TEMPLATE"),BUTTON_TAG:i("BUTTON_TAG"),STRIPE_PUBLIC_KEY:i("STRIPE_PUBLIC_KEY"),STRIPE_SOURCE:i("STRIPE_SOURCE"),STRIPE_TRIAL_PERIOD_DAYS:i("STRIPE_TRIAL_PERIOD_DAYS"),SUBSCRIPTION_NEEDED:i("SUBSCRIPTION_NEEDED"),USER_PREFIX:i("USER_PREFIX"),ANONYMOUS_TOKEN:i("ANONYMOUS_TOKEN")})),[]);t((()=>{!l&&a&&(async()=>{try{const o=await m({});console.debug("CODICENT: ACCESS TOKEN",o),d(o)}catch(o){console.debug("CODICENT: Failed to get access token",o);const e=o;if(e&&"object"==typeof e&&"error"in e&&"login_required"===e.error)console.warn("CODICENT: Session expired (login_required)"),d(null);else if(e&&"object"==typeof e&&"error"in e&&"consent_required"===e.error)try{const o=await u();if(!o)return void C("Failed to get access token: no token from auth0 with popup");console.log("CODICENT: GOT ACCESS TOKEN"),d(o)}catch(o){console.warn("CODICENT: Failed to get access token with popup",o),C("Samtycke krävs för inloggning. Tillåt popup-fönster och försök igen."),d(null)}else C("Failed to get access token: "+(e.message?.toString()||e.toString())),console.log("CODICENT: ACCESS TOKEN ERROR",e)}})().then((()=>{}))}),[a,u,m,j,l]),t((()=>{if(c&&c.sub&&E&&void 0===_){let o=!0;return(p?.loginFn?p.loginFn(h,c.sub,E):h.loginUser(c.sub,E)).then((e=>{o&&(null===e?T(!1):""===e?C("Kontrollera internetanslutningen och försök igen."):(h.setToken(e),h.getNickname().then(I),T(!0)))})).catch((()=>{o&&(C("Ett fel uppstod. Försök igen senare."),T(!1))})),()=>{o=!1}}}),[c,E,_,h]);const O=s((()=>{h.logout(),d(null),C(null),T(void 0),I(""),g({logoutParams:{returnTo:i("AUTH_REDIRECT_URL")}})}),[h,g]),R=s((async o=>{const e=p?.registerFn?await p.registerFn(h,o,c.email,c.sub,E):await h.registerUser(o,c.email,c.sub,E);return e&&(h.setToken(e),T(!0)),e}),[h,c,E]);t((()=>{h.onUnauthorized=O}),[h]);const N=s((async o=>{try{await P({authorizationParams:{connection:"email",login_hint:o}})}catch(o){console.error("Passwordless login failed:",o),C(`Passwordless login failed: ${o}`)}}),[P]);return e((()=>({isAuthenticated:a,isRegistered:_,accessToken:E,authError:S,isLoading:l,user:c,nickname:A,logout:O,registerUser:R,codicentService:h,loginWithRedirect:j,loginPasswordless:N})),[a,_,E,S,l,c,A,O,R,h,j,N])};export{r as default};
@@ -1,6 +1,6 @@
1
1
  import { Auth0ContextInterface } from "@auth0/auth0-react";
2
2
  import { CodicentService } from "../services";
3
- import { AppStateMachine, StateContext, AppStateDefinition } from "../utils";
3
+ import AppStateMachine, { StateContext, AppStateDefinition } from "../utils/appState";
4
4
  import { AudioRecorderState } from "./useAudioRecorder";
5
5
  import { AuthStateOptions, UseAuthState } from "./useAuthState";
6
6
  import { RealtimeVoice } from "./useRealtimeVoiceAI";
@@ -1 +1 @@
1
- {"version":3,"file":"useCodicentApp.d.ts","sourceRoot":"","sources":["../../../src/hooks/useCodicentApp.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,kBAAkB,EAAyB,MAAM,UAAU,CAAC;AACpG,OAAyB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAqB,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9E,OAA2B,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAiB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAGnD,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,kBAAkB,CAAC;IAC1B,IAAI,EAAE,YAAY,CAAC;IACnB,YAAY,EAAE,eAAe,CAAC;IAC9B,OAAO,EAAE,eAAe,CAAC;IACzB,OAAO,EAAE,YAAY,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,CAAC;IACnC,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IACvC,SAAS,EAAE,kBAAkB,CAAC;IAC9B,MAAM,EAAE,MAAM,OAAO,CAAC;IACtB,KAAK,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AAC,GAAG,EAAE,MAAM,KAAK,MAAM,CAAC;IACnC,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IACvC,SAAS,EAAE,kBAAkB,CAAC;IAC9B,MAAM,EAAE,MAAM,OAAO,CAAC;IACtB,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,qBAAqB;IACpC,KAAK,EAAE,qBAAqB,CAAC;IAC7B,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,WAAW,CAAC,EAAE,gBAAgB,CAAC;CAChC;AAED,eAAO,MAAM,cAAc,wCAAyC,qBAAqB,KA2WlF,gBACN,CAAC"}
@@ -1 +1 @@
1
- import{useRef as e,useState as t,useCallback as r,useMemo as n,useEffect as s}from"react";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import{createAppStateMachine as o}from"../utils/appState.js";import"../_virtual/index.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"../utils/cacheManager.js";import{useAudioRecorder as c}from"./useAudioRecorder.js";import a from"./useAuthState.js";import i from"./useRealtimeVoiceAI.js";import u from"./useTools.js";const l=({auth0:l,toolsConfig:m,authOptions:p})=>{const d=a(l,p),h=e(null);h.current||(h.current=o(d.codicentService,(()=>{})));const[g,A]=t((()=>{let e="",t=h.current.getCurrentStateName(),r=0;for(;t!==e&&r<10;)h.current.update(),e=t,t=h.current.getCurrentStateName(),r++;return t})),{service:f,context:k}=h.current,{nickname:v,name:S,error:w,errorType:C,selectedApp:j}=k,y=r(((e,t)=>{const r=e.get("file").name;f.uploadFile(r,e).then((e=>{f.sendMessage(`#transcribe ${""!==t?(t.startsWith("#")?"":"#")+t+" ":""}#file:${e}`).then((()=>{})).catch(console.warn)}))}),[f]),b=c(y),[x,N]=t(),[T,_]=t(),[I,R]=t(!1),M=n((()=>new Audio("./notification.mp3")),[]),O=r((()=>R(!0)),[]),J=u(f,N,_,M,x,O,m),B=i(f,J);s((()=>{I&&(B?.disconnectConversation(),R(!1))}),[I,B]),s((()=>{d.isAuthenticated&&d.user&&d.accessToken&&h.current.updateContext({isAuthenticated:d.isAuthenticated,user:{sub:d.user.sub,email:d.user.email},accessToken:d.accessToken})}),[d.isAuthenticated,d.user,d.accessToken]);const L=e(d.isAuthenticated);s((()=>{const e=!0===L.current,t=!0===d.isAuthenticated;e&&!t&&h.current.logout(),L.current=d.isAuthenticated}),[d.isAuthenticated]),s((()=>h.current.updateContext({nickname:d.nickname})),[d.nickname]),s((()=>{h.current.update();let e,t=h.current.getCurrentStateName();A(h.current.getCurrentStateName()),JSON.stringify(h.current.context);let r="hasAccess"===h.current.getCurrentStateName();const n=s=>setInterval((()=>{const s=h.current.getCurrentStateName();"hasAccess"!==s||r?"hasAccess"!==s&&r&&(console.log("🚨 Left stable state - switching to fast polling (200ms)"),r=!1,clearInterval(e),e=n(200)):(console.log("🎯 Reached stable state - switching to slower polling (1000ms)"),r=!0,clearInterval(e),e=n(1e3));const o=JSON.stringify(h.current.context);h.current.update();const c=JSON.stringify(h.current.context),a=h.current.getCurrentStateName();a===t&&o===c||(A(a),t=a)}),s);return e=n(r?1e3:200),()=>clearInterval(e)}),[]);const U=r((e=>e.replace("{nickname}",v||"unknown").replace("{token}",encodeURIComponent(d.accessToken||"unknown")).replace("{app}",j||"unknown")),[v,d.accessToken,j]),$=r((e=>{h.current.updateContext({isAnonymous:e})}),[]),F=r((()=>h.current.isBusy()),[]);return n((()=>({audio:b,auth:d,currentStateName:g,stateMachine:h.current,service:f,context:k,state:g,nickname:v,name:S,error:w,errorType:C,fixAppUrl:U,setAnonymous:$,allStates:h.current.allStates,isBusy:F,voice:B,html:x,setHtml:N,script:T})),[g,v,S,w,C,x,T,d.isAuthenticated,d.isLoading,b.isRecording,B?.isConnected,U,$,F])};export{l as useCodicentApp};
1
+ import{useReducer as e,useCallback as t,useState as r,useMemo as n,useEffect as s,useRef as a}from"react";import{useAudioRecorder as c}from"./useAudioRecorder.js";import i from"./useAuthState.js";import o from"./useRealtimeVoiceAI.js";import p from"./useTools.js";import{getConfigValue as u}from"../config/index.js";import{stateMachineCacheManager as A}from"../utils/cacheManager.js";import{appStateReducer as E,createInitialState as d,saveSession as m,runBackgroundValidation as l,isBusyPhase as T}from"./useAppState.js";const h=({auth0:h,toolsConfig:S,authOptions:g})=>{const k=i(h,g),y=k.codicentService,[{phase:_,context:I},R]=e(E,null,d),f=t(((e,t)=>{const r=e.get("file").name;y.uploadFile(r,e).then((e=>{y.sendMessage(`#transcribe ${""!==t?(t.startsWith("#")?"":"#")+t+" ":""}#file:${e}`).catch(console.warn)}))}),[y]),C=c(f),[U,O]=r(),[D,N]=r(),[P,L]=r(!1),v=n((()=>new Audio("./notification.mp3")),[]),F=t((()=>L(!0)),[]),w=p(y,O,N,v,U,F,S),x=o(y,w);s((()=>{P&&(x?.disconnectConversation(),L(!1))}),[P,x]),s((()=>{k.isLoading||(k.isAuthenticated&&k.accessToken?R({type:"AUTHENTICATED",accessToken:k.accessToken,user:{sub:k.user?.sub??"",email:k.user?.email??""}}):k.isAuthenticated?k.authError&&R({type:"UPDATE_CONTEXT",updates:{error:k.authError}}):R({type:"NOT_AUTHENTICATED"}))}),[k.isLoading,k.isAuthenticated,k.accessToken,k.authError]),s((()=>{"checkingCodicentAccess"===_&&(void 0===k.isRegistered&&k.authError?R({type:"UPDATE_CONTEXT",updates:{error:k.authError,errorType:"CodicentLoginFailed"}}):void 0!==k.isRegistered&&(!0===k.isRegistered&&k.nickname?R({type:"REGISTERED",nickname:k.nickname}):!1===k.isRegistered&&R({type:"NOT_REGISTERED"})))}),[_,k.isRegistered,k.nickname,k.authError]),s((()=>{if("registering"!==_)return;if(!I.accessToken||!I.user)return;let e=!1;return y.setToken(I.accessToken),y.findUsername().then((async t=>{if(e)return;if(!t)return void R({type:"REGISTER_AUTO_FAIL",error:"Användarnamn kunde inte hittas.",errorType:"NoUsernameFound"});const r=await y.nicknameExists(t);e||(r?R({type:"REGISTER_AUTO_FAIL",error:"Användarnamnet finns redan.",errorType:"UsernameExists"}):(await y.registerUser(t,I.user.email,I.user.sub,I.accessToken),e||(y.setToken(I.accessToken),R({type:"REGISTER_AUTO_SUCCESS",nickname:t}))))})).catch((t=>{e||R({type:"REGISTER_AUTO_FAIL",error:t instanceof Error?t.message:String(t),errorType:"ErrorRegistering"})})),()=>{e=!0}}),[_]),s((()=>{if("loadingUser"!==_||!I.nickname)return;let e=!1;return localStorage.setItem("nickname",I.nickname),y.getUserInfo(I.nickname).then((t=>{e||R({type:"USER_LOADED",name:t?.name||t?.nickname||""})})).catch((()=>{e||R({type:"USER_LOADED",name:""})})),()=>{e=!0}}),[_]),s((()=>{if("checkingPurchase"!==_)return;if(!u("SUBSCRIPTION_NEEDED"))return void R({type:"PURCHASE_VALID"});let e=!1;return y.checkSubscriptionStatus().then((t=>{if(!e){R("active"===t||"trialing"===t?{type:"PURCHASE_VALID"}:{type:"PURCHASE_INVALID"})}})).catch((()=>{e||R({type:"PURCHASE_INVALID"})})),()=>{e=!0}}),[_]),s((()=>{if("gettingApps"!==_)return;let e=!1;return y.getApps().then((t=>{e||R(null!==t?{type:"APPS_LOADED",apps:t}:{type:"APPS_FAILED",error:"Failed to fetch apps."})})).catch((t=>{e||R({type:"APPS_FAILED",error:String(t)})})),()=>{e=!0}}),[_]),s((()=>{if("creatingApp"!==_)return;let e=!1;return y.createApp().then((t=>{e||R(t?{type:"APP_CREATED",appId:t}:{type:"APP_CREATE_FAILED",error:"Misslyckades att skapa din app. Försök igen senare."})})).catch((t=>{e||R({type:"APP_CREATE_FAILED",error:String(t)})})),()=>{e=!0}}),[_]),s((()=>{"hasAccess"===_&&I.selectedApp&&(y.codicent=I.selectedApp,localStorage.setItem("selectedApp",I.selectedApp),I.isFromCache||m(I))}),[_,I.selectedApp]);const M=a(!1);s((()=>{"hasAccess"===_&&I.isFromCache&&I.needsValidation&&k.accessToken&&k.isAuthenticated&&(M.current||(M.current=!0,l(y,I,R)))}),[_,I.isFromCache,I.needsValidation,k.accessToken,k.isAuthenticated]),s((()=>{"needsPurchase"===_&&(window.location.href="./#/purchase")}),[_]),s((()=>{if("anonymous"!==_)return;const e=u("ANONYMOUS_TOKEN"),t=u("ANONYMOUS_CODICENT")||u("APP_NAME")||"";e&&(y.setToken(e),y.codicent=t)}),[_]),s((()=>{"loggingOut"===_&&(u("ENABLE_STATE_CACHE")&&A.clear(),localStorage.removeItem("selectedApp"),localStorage.removeItem("nickname"),localStorage.removeItem("codicent"),sessionStorage.clear(),k.logout())}),[_]);const H=a(I);H.current=I;const j=a({}).current,G=a({}).current,V=n((()=>({service:y,get context(){return H.current},current:"hasAccess"===_?j:G,allStates:{hasAccess:j},setSelectedApp:e=>{R({type:"SET_SELECTED_APP",appId:e})},updateContext:e=>{R({type:"UPDATE_CONTEXT",updates:e})},logout:()=>{R({type:"LOGOUT"})},update:()=>{},isBusy:()=>T(_)})),[_,y]),b=t((e=>e.replace("{nickname}",I.nickname||"unknown").replace("{token}",encodeURIComponent(k.accessToken||"unknown")).replace("{app}",I.selectedApp||"unknown")),[I.nickname,k.accessToken,I.selectedApp]),B=t((e=>{e&&u("ANONYMOUS_TOKEN")&&R({type:"SET_ANONYMOUS"})}),[]),Y=t((()=>T(_)),[_]);return n((()=>({audio:C,auth:k,currentStateName:_,stateMachine:V,service:y,context:I,state:_,nickname:I.nickname||"",name:I.name||"",error:I.error||"",errorType:I.errorType||"",fixAppUrl:b,setAnonymous:B,allStates:V.allStates,isBusy:Y,voice:x,html:U||"",setHtml:O,script:D||""})),[_,I,U,D,k.isAuthenticated,k.isLoading,C.isRecording,x?.isConnected,b,B,Y,V])};export{h as useCodicentApp};
@@ -60,6 +60,12 @@ export declare class CodicentService {
60
60
  [key: string]: string;
61
61
  }) => Promise<DataMessage[]>;
62
62
  readOneDataMessage: (id: string) => Promise<DataMessage | null>;
63
+ /**
64
+ * Fetches the current leaf (latest version) of a data message by its stable originalMessageId.
65
+ * Uses the backend GetLeafMessageByOriginalMessageId endpoint directly.
66
+ * Returns a DataMessage-compatible object with parsed JSON data, or null if not found.
67
+ */
68
+ getLeafDataMessage: (originalMessageId: string, codicent?: string) => Promise<DataMessage | null>;
63
69
  updateDataMessage: (id: string, data: object, codicent?: string) => Promise<string>;
64
70
  deleteDataMessage: (id: string, codicent?: string) => Promise<string>;
65
71
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,UAAU,QAAS,MAAM,SAgBrC,CAAC;AAEF,eAAO,MAAM,cAAc,SAAU,MAAM,SAU1C,CAAC;AA+BF,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE;QAAE,aAAa,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACvC,UAAU,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB;AAED,MAAM,WAAW,OAAO;IACtB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;CACd;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,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC,CAiB/E;IAEF,gBAAgB,cAAqB,MAAM,UAAU,MAAM,GAAG,QAAQ,sBAcpE;IAEI,uBAAuB,CAAC,KAAK,GAAE,MAAgB,EAAE,QAAQ,GAAE,MAAiB,GAAG,OAAO,CAAC,MAAM,CAAC;IAwB9F,iBAAiB,CACrB,QAAQ,GAAE,MAAiB,GAC1B,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAoBpE;;;;;;OAMG;IACH,MAAM,CAAC,eAAe,SACd,MAAM,kBACI,MAAM,YACb,MAAM,KACd,OAAO,CAAC,mBAAmB,CAAC,CA0B7B;CACH"}
@@ -1 +1 @@
1
- import{loadStripe as t}from"../node_modules/@stripe/stripe-js/dist/index.js";import e from"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import"react";import"../_virtual/index.js";import"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";var o;let n="https://codicent.com/",a="https://pubsub.codicent.com/hub",s="-";const i=()=>"undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init,r=t=>{t&&"string"==typeof t?(n=t.endsWith("/")?t:t+"/",i()&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a})):console.warn("Invalid base URL provided, using default")},c=t=>{t&&"string"==typeof t&&(a=t,i()&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a}))},h=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:s,baseUrl:n,signalRHost:a}),!0);let d=h();if(!d){const t=setInterval((()=>{d=h(),d&&clearInterval(t)}),100)}class l{constructor(o){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,n,a,s,i,r)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:n,length:a,afterTimestamp:s,beforeTimestamp:i,dataFilters:r}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>[...(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const o=new e(t.content).content.split("\n"),n=o[0],a=o.slice(1).join("\n");return{id:t.id,title:n,content:a}})),...(await window.Codicent.getDataMessages({tags:["skill"],codicent:this.codicent})).map((t=>t.data)).filter((t=>t.name&&t.title)).map((t=>({id:t.name,title:t.title,content:t.content||t.description||""})))],this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${n}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,a=void 0,s,i=0)=>{const r=await this.request(`${n}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),a){const t=await this.getPublicFlow(a);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let n=[];const a=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(a)).forEach((t=>{n=n.concat(t)})),e)try{const t=await this.getPublicFlow(e);n=n.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return n=n.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),n.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),n},this.registerUser=async(t,e,o,s)=>{const i=await fetch(`${n}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!i.ok)return"";const r=await i.text();return window.Codicent.init({token:r,baseUrl:n,signalRHost:a}),r},this.loginUser=async(t,e)=>{try{const o=await fetch(`${n}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in user:",t),""}},this.loginMicrosoftUser=async(t,e)=>{try{const o=await fetch(`${n}app/LoginMicrosoftUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in Microsoft user:",t),""}},this.registerMicrosoftUser=async(t,e,o,a)=>{const s=await fetch(`${n}app/RegisterMicrosoftUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${a}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";return await s.text()},this.nicknameExists=async t=>{const e=await fetch(`${n}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${n}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=await t.json();return e.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))))}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${n}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${n}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let a=await o.json();if(a){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(a=!1)}catch{a=!1}if(a){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(a=!1)}catch{a=!1}}}return a},this.getNickname=async()=>{try{const t=s.split(".")[1],e=atob(t),o=JSON.parse(e),a=o.sub||o.userId,i=await fetch(`${n}app/GetNickname?userId=${a}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${n}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const a=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=a;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:a})=>{const s=await fetch(`${n}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:a,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${n}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${n}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${n}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{s=t,s&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a})},this.getToken=()=>s,this.checkPurchaseStatus=async()=>{const t=await fetch(`${n}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${n}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o=this.options.STRIPE_TRIAL_PERIOD_DAYS,a={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(a.source=e),o&&o>0&&(a.trialPeriodDays=o);const s=await fetch(`${n}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(a)});if(!s.ok)throw new Error("Failed to create checkout session");const{id:i}=await s.json();return i},this.redirectToCheckout=async e=>{const o=await t(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const n=await this.createCheckoutSession(e),{error:a}=await o.redirectToCheckout({sessionId:n});if(a)throw new Error(a.message)},this.getChatHistory=async t=>{const e=await fetch(`${n}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!(t.content.includes("#function_result")||t.content.includes("#finish_reason_function_call")||t.content.includes("#function_results_batch")||t.content.includes("#finish_reason_tool_calls_batch")))),o},this.getPublicFlow=async t=>{const e=await fetch(`${n}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${n}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},a=await fetch(`${n}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!a.ok)throw new Error(`${a.statusText||"Failed to post log message!"}`);return(await a.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),n=JSON.parse(o).nickname;if(!await this.addFollower(e,n))throw new Error("Failed to add follower: "+n)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${n}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${n}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${n}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${n}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=o,r(o.API_BASE_URL),o.PUBSUB_URL&&c(o.PUBSUB_URL)}async request(t,e,o={}){const n={};o.headers&&o.headers.forEach((([t,e])=>{n[t]=e}));const a=await fetch(t,{...o,method:e,headers:n});if(!a.ok)throw 401===a.status&&this.handleUnauthorized(),new Error(`${a.statusText}`);return a}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${n}realtime/session?voice=${t}&provider=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!a.ok)throw new Error(`Failed to fetch session token: ${a.statusText}`);const s=await a.json(),i=s.client_secret?.value??s.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${n}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}o=l,l.getImageUrl=(t,e)=>`${n}app/GetImage?fileId=${t}&width=${e}`,l.getFileUrl=(t,e)=>`${n}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,l.downloadFile=async t=>{fetch(o.getFileUrl(t.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((e=>{const o=window.URL.createObjectURL(e),n=document.createElement("a");n.style.display="none",n.href=o,n.download=t.filename,document.body.appendChild(n),n.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},l.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let a={project:e,message:t};o&&(a.messageId=o);const i=await fetch(`${n}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify(a)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},l.getMiniChatReply=async(t,e="codicent-mini",o,a=3e5,i=2e3,r)=>{const c={project:e,message:t};let h;o&&(c.messageId=o),r&&(c.previousResponseId=r);try{const t=await fetch(`${n}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify(c)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(h=(await t.json()).promptMessageId,!h)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const d=Date.now();for(;Date.now()-d<a;)try{const t=await fetch(`${n}app/GetAi2ChatReplyStatus?promptMessageId=${h}`,{method:"GET",headers:[["Authorization",`Bearer ${s}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json(),a=o.content??o.content??"";return{content:a.replace(`@${e}`,"").replace("@codicent-mini","").trim(),responseId:o.responseId??void 0}}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},l.getTranslations=async(t,e,o="codicent-mini")=>{if(!s||"-"===s)return{translation:t};const a=await fetch(`${n}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${s}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!a.ok)throw a.status,new Error(`Failed to get translations: ${a.statusText}`);return await a.json()};export{l as CodicentService,r as setBaseUrl,c as setSignalRHost};
1
+ import{loadStripe as t}from"../node_modules/@stripe/stripe-js/dist/index.js";import e from"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import"react";import"../_virtual/index.js";import"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";var o;let n="https://codicent.com/",a="https://pubsub.codicent.com/hub",s="-";const i=()=>"undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init,r=t=>{t&&"string"==typeof t?(n=t.endsWith("/")?t:t+"/",i()&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a})):console.warn("Invalid base URL provided, using default")},c=t=>{t&&"string"==typeof t&&(a=t,i()&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a}))},h=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:s,baseUrl:n,signalRHost:a}),!0);let d=h();if(!d){const t=setInterval((()=>{d=h(),d&&clearInterval(t)}),100)}class l{constructor(o){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,n,a,s,i,r)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:n,length:a,afterTimestamp:s,beforeTimestamp:i,dataFilters:r}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.getLeafDataMessage=async(t,e)=>{const o=e||this.codicent;try{const e=await fetch(`${this.options.API_BASE_URL}app/GetLeafMessageByOriginalMessageId?project=${encodeURIComponent(o)}&originalMessageId=${encodeURIComponent(t)}`,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!e.ok)return null;const n=await e.json();if(!n||!n.content)return null;const a=n.content.indexOf("{");if(-1===a)return null;const s=JSON.parse(n.content.slice(a));return{id:n.id,fileId:n.fileId??null,fileIds:n.fileIds??[],data:s,createdAt:n.createdAt,tags:n.tags??[],mentions:n.mentions??[]}}catch{return null}},this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>[...(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const o=new e(t.content).content.split("\n"),n=o[0],a=o.slice(1).join("\n");return{id:t.id,title:n,content:a}})),...(await window.Codicent.getDataMessages({tags:["skill"],codicent:this.codicent})).map((t=>t.data)).filter((t=>t.name&&t.title)).map((t=>({id:t.name,title:t.title,content:t.content||t.description||""})))],this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${n}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,a=void 0,s,i=0)=>{const r=await this.request(`${n}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),a){const t=await this.getPublicFlow(a);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let n=[];const a=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(a)).forEach((t=>{n=n.concat(t)})),e)try{const t=await this.getPublicFlow(e);n=n.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return n=n.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),n.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),n},this.registerUser=async(t,e,o,s)=>{const i=await fetch(`${n}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!i.ok)return"";const r=await i.text();return window.Codicent.init({token:r,baseUrl:n,signalRHost:a}),r},this.loginUser=async(t,e)=>{try{const o=await fetch(`${n}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in user:",t),""}},this.loginMicrosoftUser=async(t,e)=>{try{const o=await fetch(`${n}app/LoginMicrosoftUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in Microsoft user:",t),""}},this.registerMicrosoftUser=async(t,e,o,a)=>{const s=await fetch(`${n}app/RegisterMicrosoftUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${a}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";return await s.text()},this.nicknameExists=async t=>{const e=await fetch(`${n}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${n}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=await t.json();return e.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))))}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${n}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${n}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let a=await o.json();if(a){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(a=!1)}catch{a=!1}if(a){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(a=!1)}catch{a=!1}}}return a},this.getNickname=async()=>{try{const t=s.split(".")[1],e=atob(t),o=JSON.parse(e),a=o.sub||o.userId,i=await fetch(`${n}app/GetNickname?userId=${a}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${n}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const a=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=a;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:a})=>{const s=await fetch(`${n}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:a,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${n}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${n}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${n}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{s=t,s&&window.Codicent.init({token:s,baseUrl:n,signalRHost:a})},this.getToken=()=>s,this.checkPurchaseStatus=async()=>{const t=await fetch(`${n}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${n}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o=this.options.STRIPE_TRIAL_PERIOD_DAYS,a={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(a.source=e),o&&o>0&&(a.trialPeriodDays=o);const s=await fetch(`${n}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(a)});if(!s.ok)throw new Error("Failed to create checkout session");const{id:i}=await s.json();return i},this.redirectToCheckout=async e=>{const o=await t(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const n=await this.createCheckoutSession(e),{error:a}=await o.redirectToCheckout({sessionId:n});if(a)throw new Error(a.message)},this.getChatHistory=async t=>{const e=await fetch(`${n}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!(t.content.includes("#function_result")||t.content.includes("#finish_reason_function_call")||t.content.includes("#function_results_batch")||t.content.includes("#finish_reason_tool_calls_batch")))),o},this.getPublicFlow=async t=>{const e=await fetch(`${n}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${n}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},a=await fetch(`${n}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!a.ok)throw new Error(`${a.statusText||"Failed to post log message!"}`);return(await a.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),n=JSON.parse(o).nickname;if(!await this.addFollower(e,n))throw new Error("Failed to add follower: "+n)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${n}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${n}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${n}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${n}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=o,r(o.API_BASE_URL),o.PUBSUB_URL&&c(o.PUBSUB_URL)}async request(t,e,o={}){const n={};o.headers&&o.headers.forEach((([t,e])=>{n[t]=e}));const a=await fetch(t,{...o,method:e,headers:n});if(!a.ok)throw 401===a.status&&this.handleUnauthorized(),new Error(`${a.statusText}`);return a}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${n}realtime/session?voice=${t}&provider=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!a.ok)throw new Error(`Failed to fetch session token: ${a.statusText}`);const s=await a.json(),i=s.client_secret?.value??s.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${n}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}o=l,l.getImageUrl=(t,e)=>`${n}app/GetImage?fileId=${t}&width=${e}`,l.getFileUrl=(t,e)=>`${n}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,l.downloadFile=async t=>{fetch(o.getFileUrl(t.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((e=>{const o=window.URL.createObjectURL(e),n=document.createElement("a");n.style.display="none",n.href=o,n.download=t.filename,document.body.appendChild(n),n.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},l.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let a={project:e,message:t};o&&(a.messageId=o);const i=await fetch(`${n}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify(a)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},l.getMiniChatReply=async(t,e="codicent-mini",o,a=3e5,i=2e3,r)=>{const c={project:e,message:t};let h;o&&(c.messageId=o),r&&(c.previousResponseId=r);try{const t=await fetch(`${n}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${s}`]],body:JSON.stringify(c)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(h=(await t.json()).promptMessageId,!h)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const d=Date.now();for(;Date.now()-d<a;)try{const t=await fetch(`${n}app/GetAi2ChatReplyStatus?promptMessageId=${h}`,{method:"GET",headers:[["Authorization",`Bearer ${s}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json(),a=o.content??o.content??"";return{content:a.replace(`@${e}`,"").replace("@codicent-mini","").trim(),responseId:o.responseId??void 0}}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},l.getTranslations=async(t,e,o="codicent-mini")=>{if(!s||"-"===s)return{translation:t};const a=await fetch(`${n}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${s}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!a.ok)throw a.status,new Error(`Failed to get translations: ${a.statusText}`);return await a.json()};export{l as CodicentService,r as setBaseUrl,c as setSignalRHost};
package/dist/index.d.ts CHANGED
@@ -73,6 +73,12 @@ declare class CodicentService {
73
73
  [key: string]: string;
74
74
  }) => Promise<DataMessage[]>;
75
75
  readOneDataMessage: (id: string) => Promise<DataMessage | null>;
76
+ /**
77
+ * Fetches the current leaf (latest version) of a data message by its stable originalMessageId.
78
+ * Uses the backend GetLeafMessageByOriginalMessageId endpoint directly.
79
+ * Returns a DataMessage-compatible object with parsed JSON data, or null if not found.
80
+ */
81
+ getLeafDataMessage: (originalMessageId: string, codicent?: string) => Promise<DataMessage | null>;
76
82
  updateDataMessage: (id: string, data: object, codicent?: string) => Promise<string>;
77
83
  deleteDataMessage: (id: string, codicent?: string) => Promise<string>;
78
84
  /**
@@ -986,6 +992,8 @@ interface ColumnAction {
986
992
  tooltip?: string;
987
993
  /** Callback when the action icon is clicked, receives the row data as context */
988
994
  onClick: (rowData: Record<string, unknown>) => void;
995
+ /** When true, renders the icon to the left of the cell text instead of the right */
996
+ iconLeft?: boolean;
989
997
  }
990
998
  interface ColumnDefinition {
991
999
  key: string | string[];
@@ -993,11 +1001,17 @@ interface ColumnDefinition {
993
1001
  hidden?: boolean;
994
1002
  hideOnMobile?: boolean;
995
1003
  maxWidth?: number;
996
- type?: "file" | "checkbox" | "textarea" | "enum" | undefined;
1004
+ type?: "file" | "checkbox" | "textarea" | "enum" | "combobox" | undefined;
997
1005
  /** Number of rows for textarea type (default: 3) */
998
1006
  rows?: number;
999
- /** Options for enum type columns */
1007
+ /** Options for enum type columns (static, small lists) */
1000
1008
  enumOptions?: string[];
1009
+ /** Async loader for combobox options (e.g. 15k+ customers). Receives the current search text, returns matching options. */
1010
+ enumOptionsLoader?: (searchText: string) => Promise<string[]>;
1011
+ /** Minimum number of characters typed before the async loader is called (default: 2) */
1012
+ enumOptionsLoaderMinChars?: number;
1013
+ /** Maximum number of options to display in the combobox dropdown (default: 50) */
1014
+ enumOptionsLoaderMaxResults?: number;
1001
1015
  editable?: boolean;
1002
1016
  filterable?: boolean;
1003
1017
  /** Default sort direction for this column. If multiple columns have defaultSort, only the first one is used. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codicent-app-sdk",
3
- "version": "0.4.29",
3
+ "version": "0.5.1",
4
4
  "description": "SDK for building AI-powered applications with Codicent",
5
5
  "type": "module",
6
6
  "main": "dist/cjs/index.js",