@objectstack/console 7.0.0 → 7.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/assets/{AiPendingActionsPage-DLWrcsds.js → AiPendingActionsPage-B6prPdE6.js} +1 -1
  2. package/dist/assets/{ApiConsolePage-BIBykAYj.js → ApiConsolePage-KLlXE_J-.js} +1 -1
  3. package/dist/assets/{AppManagementPage-BKE0rv8B.js → AppManagementPage-CSGa-1u0.js} +1 -1
  4. package/dist/assets/ApprovalsInboxPage-BOY6Xpsn.js +1 -0
  5. package/dist/assets/{AuditLogPage-Bqlhi2ko.js → AuditLogPage-DzIHYkL6.js} +1 -1
  6. package/dist/assets/ComponentNavView-CZkyv2fY.js +1 -0
  7. package/dist/assets/{ConsoleFloatingChatbot-CBIXkoNS.js → ConsoleFloatingChatbot-Dfub90-W.js} +1 -1
  8. package/dist/assets/DeveloperHubPage-lLRr5-aY.js +1 -0
  9. package/dist/assets/FlowRunsPage-DV2m0d1l.js +1 -0
  10. package/dist/assets/MonacoImpl-DcAVOHcx.js +1 -0
  11. package/dist/assets/ProfilePage-B4ZMNend.js +1 -0
  12. package/dist/assets/PublicFormsPage-CHWj3DL5.js +1 -0
  13. package/dist/assets/RecentItemsProvider-Dt0K6V1V.js +1 -0
  14. package/dist/assets/{SettingsHub-BTNCNbjZ.js → SettingsHub-DrmQJKTl.js} +1 -1
  15. package/dist/assets/{SettingsView-BLXf7B7b.js → SettingsView-DQ4mtooC.js} +1 -1
  16. package/dist/assets/{SystemHubPage-CgN-8VKO.js → SystemHubPage-CjV_--P3.js} +1 -1
  17. package/dist/assets/data-adapter-CX0Tq3Q5.js +1 -0
  18. package/dist/assets/dist-Dal4BOHf.js +11 -0
  19. package/dist/assets/{framework-ClI3DbWX.js → framework-DpQcF_QW.js} +4 -4
  20. package/dist/assets/{highlighted-body-OFNGDK62-Dua_6VJ2.js → highlighted-body-OFNGDK62-BcbCsvGi.js} +1 -1
  21. package/dist/assets/index-DUV_YMtu.css +2 -0
  22. package/dist/assets/index-hBFJ6de4.js +33 -0
  23. package/dist/assets/infrastructure-IQKE4Vv8.js +3 -0
  24. package/dist/assets/mermaid-GHXKKRXX-DLb_WlhX.js +1 -0
  25. package/dist/assets/plugin-calendar-BGJsyv_O.js +1 -0
  26. package/dist/assets/{plugin-charts-C11LxM1X.js → plugin-charts-CRlZ01tc.js} +2 -2
  27. package/dist/assets/plugin-chatbot-BhnqfdW0.js +120 -0
  28. package/dist/assets/plugin-dashboard-CUH4Dbo1.js +3 -0
  29. package/dist/assets/{plugin-form-f39dp3V2.js → plugin-form-BzrcwmiI.js} +1 -1
  30. package/dist/assets/plugin-gantt-Dt2juPb1.js +1 -0
  31. package/dist/assets/plugin-grid-BHnAwQNY.js +6 -0
  32. package/dist/assets/plugin-kanban-lsYbj6Vr.js +1 -0
  33. package/dist/assets/plugin-map-BKE-4AVm.js +1 -0
  34. package/dist/assets/plugin-markdown-bkOWrh0-.js +7 -0
  35. package/dist/assets/plugin-report-CqzUFpeK.js +59 -0
  36. package/dist/assets/plugin-timeline-ZI65E7h4.js +1 -0
  37. package/dist/assets/plugin-view-CGR-rgKC.js +1 -0
  38. package/dist/assets/plugins-views-CzwBozRK.js +4 -0
  39. package/dist/assets/src-0fzF-kZX.js +2 -0
  40. package/dist/assets/{types-CuyLcCWX.js → types-C7d65SSU.js} +1 -1
  41. package/dist/assets/ui-components-CXy53m_o.js +41 -0
  42. package/dist/assets/ui-layout-BqvRQUkZ.js +1 -0
  43. package/dist/assets/{vendor-charts-vh1WJI0j.js → vendor-charts-Ba_-W-di.js} +3 -3
  44. package/dist/assets/{vendor-dndkit-0jp7h5ty.js → vendor-dndkit-CucFgdMa.js} +1 -1
  45. package/dist/assets/{vendor-i18n-CnFu8bdi.js → vendor-i18n-DPyFo2xM.js} +1 -1
  46. package/dist/assets/{vendor-icons-core-D5MicM14.js → vendor-icons-core-Cx2WYOuR.js} +1 -1
  47. package/dist/assets/{vendor-markdown-CvMSBmgq.js → vendor-markdown-B0mCB2Nu.js} +2 -2
  48. package/dist/assets/vendor-objectstack-DdIVmQL0.js +65 -0
  49. package/dist/assets/{vendor-radix-BNWIlSsV.js → vendor-radix-thTS_QfF.js} +1 -1
  50. package/dist/assets/vendor-react-CyVA1SE-.js +13 -0
  51. package/dist/assets/{vendor-sentry-D5yZpZ5X.js → vendor-sentry-DjMgMAaz.js} +1 -1
  52. package/dist/assets/{vendor-ui-utils-D3GsyZyi.js → vendor-ui-utils-BbOuugky.js} +1 -1
  53. package/dist/favicon.svg +11 -0
  54. package/dist/index.html +7 -7
  55. package/dist/logo.svg +15 -0
  56. package/dist/manifest.json +2 -2
  57. package/package.json +1 -1
  58. package/dist/assets/ApprovalsInboxPage-D7gF2CM8.js +0 -1
  59. package/dist/assets/ComponentNavView-DBMxrUvH.js +0 -1
  60. package/dist/assets/DeveloperHubPage-C3Ooh2Gg.js +0 -1
  61. package/dist/assets/FlowRunsPage-NjEPPv_e.js +0 -1
  62. package/dist/assets/MonacoImpl-CKoKq1tG.js +0 -11
  63. package/dist/assets/ObjectManagerListPage-DEPokJwV.js +0 -1
  64. package/dist/assets/ProfilePage-zYSeu2-d.js +0 -1
  65. package/dist/assets/PublicFormsPage-BrLPiHf1.js +0 -1
  66. package/dist/assets/data-adapter-Dn6-L_yI.js +0 -1
  67. package/dist/assets/index-Ca4KaljM.js +0 -23
  68. package/dist/assets/index-DsQwZDFr.css +0 -2
  69. package/dist/assets/infrastructure-ezj3FgNE.js +0 -3
  70. package/dist/assets/mermaid-GHXKKRXX-BvEKnLTo.js +0 -1
  71. package/dist/assets/plugin-calendar-Dnr7itgk.js +0 -1
  72. package/dist/assets/plugin-chatbot-COnH_NZC.js +0 -120
  73. package/dist/assets/plugin-dashboard-DvBectcr.js +0 -3
  74. package/dist/assets/plugin-gantt-7ui7uiVc.js +0 -1
  75. package/dist/assets/plugin-grid-DtceFt_J.js +0 -6
  76. package/dist/assets/plugin-kanban-q2UT5MlD.js +0 -1
  77. package/dist/assets/plugin-map-C6vgk2bJ.js +0 -1
  78. package/dist/assets/plugin-markdown-DPzm2nVd.js +0 -7
  79. package/dist/assets/plugin-report-BJM4LH87.js +0 -59
  80. package/dist/assets/plugin-timeline-lCaTr_4i.js +0 -1
  81. package/dist/assets/plugin-view-b7gS6gIn.js +0 -1
  82. package/dist/assets/plugins-views-Dvl7pQvR.js +0 -4
  83. package/dist/assets/src-Con14F4e.js +0 -2
  84. package/dist/assets/ui-components-ZN8XdmwJ.js +0 -41
  85. package/dist/assets/ui-layout-HiDSueut.js +0 -1
  86. package/dist/assets/vendor-objectstack-CwZ3saTl.js +0 -65
  87. package/dist/assets/vendor-react-CIpZOxG3.js +0 -13
@@ -1 +0,0 @@
1
- import{o as e}from"./rolldown-runtime-CMxvf4Kt.js";import{g as t,r as n}from"./vendor-react-CIpZOxG3.js";import{x as r}from"./framework-ClI3DbWX.js";import{Bn as i,Fn as a,In as o,Jn as ee,Kn as te,Ln as s,Qa as ne,Qn as re,Rn as c,Ua as l,Xn as ie,Yn as ae,at as u,ct as d,en as f,in as p,it as m,mr as h,no as oe,ot as g,qn as se,rt as ce,sa as le,si as ue,st as de,vi as fe,wi as pe,xi as me,zn as _}from"./ui-components-ZN8XdmwJ.js";import{o as v}from"./vendor-ui-utils-D3GsyZyi.js";import"./index-Ca4KaljM.js";var y=e(t(),1),b=n();function x(e){return e?e.replace(/^\/+/,``).match(/^forms\/([^/?#]+)/i)?.[1]??null:null}function S(e){return e.trim().toLowerCase().replace(/[^a-z0-9-_]+/g,`-`).replace(/^-+|-+$/g,``)}function C(){let e=r()?.getClient?.(),[t,n]=(0,y.useState)([]),[C,he]=(0,y.useState)([]),[w,T]=(0,y.useState)(!0),[E,D]=(0,y.useState)(null),[ge,O]=(0,y.useState)(!1),[k,A]=(0,y.useState)(``),[j,M]=(0,y.useState)(``),[N,P]=(0,y.useState)(!1),[_e,F]=(0,y.useState)(!1),[I,L]=(0,y.useState)(null),[R,z]=(0,y.useState)(``),[B,V]=(0,y.useState)(`thank-you`),[H,U]=(0,y.useState)(``),[W,G]=(0,y.useState)(``),[K,q]=(0,y.useState)(``),[J,Y]=(0,y.useState)(!1),X=async()=>{if(!e?.meta?.getItems){D(`meta.getItems is not available on this client`),T(!1);return}T(!0),D(null);try{let t=await e.meta.getItems(`view`),r=Array.isArray(t)?t:Array.isArray(t?.items)?t.items:Array.isArray(t?.value)?t.value:[],i=[],a=[];for(let e of r){let t=e?.spec??e;if(!(t?.sections||t?.groups||t?.form||t?.type===`simple`||t?.type===`tabbed`||t?.type===`wizard`||t?.viewType===`form`))continue;let n=t?.sharing,r=n?.publicLink,o=x(r);n?.allowAnonymous&&o&&r?i.push({name:t?.name??e?.name,label:t?.label,object:t?.object,slug:o,publicLink:r,updatedAt:e?.updatedAt??e?.updated_at,spec:t}):a.push({name:t?.name??e?.name,label:t?.label,object:t?.object,spec:t})}n(i),he(a)}catch(e){D(e?.message??String(e))}finally{T(!1)}};(0,y.useEffect)(()=>{X()},[]);let ve=typeof window<`u`?window.location.origin:``,Z=e=>`${ve}/console/f/${e}`,ye=e=>`<iframe src="${Z(e)}" width="100%" height="640" frameborder="0" style="border:0;"></iframe>`,be=e=>`<iframe\n src={\`${Z(e)}\`}\n title="Public form"\n style={{ width: '100%', height: 640, border: 0 }}\n/>`,Q=async(e,t)=>{try{await navigator.clipboard.writeText(t),v.success(`Copied ${e}`)}catch{v.error(`Clipboard unavailable`)}},xe=async()=>{if(!k||!j)return;let t=C.find(e=>e.name===k);if(!t)return;let n=S(j);if(!n){v.error(`Invalid slug`);return}let r={...t.spec,sharing:{...t.spec.sharing??{},enabled:!0,allowAnonymous:!0,publicLink:`/forms/${n}`}};P(!0);try{await e.meta.saveItem(`view`,t.name,r),v.success(`Published ${t.name}`),O(!1),A(``),M(``),await X()}catch(e){v.error(`Publish failed: ${e?.message??e}`)}finally{P(!1)}},Se=e=>{L(e),z(e.slug);let t=e.spec?.submitBehavior;V(t?.kind??`thank-you`),U(t?.title??``),G(t?.message??``),q(t?.url??``),F(!0)},Ce=async()=>{if(!I)return;let t=S(R);if(!t){v.error(`Invalid slug`);return}let n;switch(B){case`thank-you`:n={kind:`thank-you`},H&&(n.title=H),W&&(n.message=W);break;case`redirect`:if(!K){v.error(`Redirect URL is required`);return}n={kind:`redirect`,url:K};break;case`continue`:case`next-record`:n={kind:B};break}let r={...I.spec,sharing:{...I.spec.sharing??{},enabled:!0,allowAnonymous:!0,publicLink:`/forms/${t}`},submitBehavior:n};Y(!0);try{await e.meta.saveItem(`view`,I.name,r),v.success(`Saved ${I.name}`),F(!1),L(null),await X()}catch(e){v.error(`Save failed: ${e?.message??e}`)}finally{Y(!1)}},$=t.length>0;return(0,b.jsxs)(`div`,{className:`flex flex-1 flex-col gap-4 p-4 md:p-6 overflow-auto`,children:[(0,b.jsxs)(te,{children:[(0,b.jsxs)(ae,{className:`flex flex-row items-start justify-between gap-4 space-y-0`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsxs)(ie,{className:`flex items-center gap-2`,children:[(0,b.jsx)(me,{className:`h-4 w-4`}),`Public Forms`]}),(0,b.jsx)(ee,{children:`Forms anyone can fill out — no login required. Publish a form to get a shareable link; submissions land directly in the bound object.`})]}),(0,b.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,b.jsxs)(h,{variant:`default`,size:`sm`,onClick:()=>O(!0),disabled:C.length===0,title:C.length===0?`No non-public FormViews available`:`Publish a FormView`,children:[(0,b.jsx)(pe,{className:`h-3.5 w-3.5`}),(0,b.jsx)(`span`,{className:`ml-1.5`,children:`Publish form…`})]}),(0,b.jsxs)(h,{variant:`outline`,size:`sm`,onClick:X,disabled:w,children:[(0,b.jsx)(fe,{className:`h-3.5 w-3.5 ${w?`animate-spin`:``}`}),(0,b.jsx)(`span`,{className:`ml-1.5`,children:`Refresh`})]})]})]}),(0,b.jsxs)(se,{children:[E&&(0,b.jsx)(`div`,{className:`mb-3 rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive`,children:E}),!w&&!$&&(0,b.jsxs)(`div`,{className:`rounded-md border border-dashed p-6 text-center text-sm text-muted-foreground`,children:[(0,b.jsx)(`p`,{className:`font-medium text-foreground`,children:`No public forms yet`}),(0,b.jsxs)(`p`,{className:`mt-1`,children:[`Click `,(0,b.jsx)(`strong`,{children:`Publish form…`}),` above to share an existing form, or build a new one in Views & Apps and mark it public.`]})]}),$&&(0,b.jsxs)(ce,{children:[(0,b.jsx)(de,{children:(0,b.jsxs)(d,{children:[(0,b.jsx)(g,{children:`Name`}),(0,b.jsx)(g,{children:`Object`}),(0,b.jsx)(g,{children:`Slug`}),(0,b.jsx)(g,{children:`Public URL`}),(0,b.jsx)(g,{className:`text-right`,children:`Actions`})]})}),(0,b.jsx)(m,{children:t.map(e=>{let t=Z(e.slug);return(0,b.jsxs)(d,{children:[(0,b.jsx)(u,{children:(0,b.jsxs)(`div`,{className:`flex flex-col`,children:[(0,b.jsx)(`span`,{className:`font-medium`,children:e.label??e.name}),(0,b.jsx)(`code`,{className:`text-xs text-muted-foreground`,children:e.name})]})}),(0,b.jsx)(u,{children:e.object?(0,b.jsx)(re,{variant:`secondary`,children:e.object}):(0,b.jsx)(`span`,{className:`text-muted-foreground`,children:`—`})}),(0,b.jsx)(u,{children:(0,b.jsx)(`code`,{className:`text-xs`,children:e.slug})}),(0,b.jsx)(u,{children:(0,b.jsxs)(`a`,{href:t,target:`_blank`,rel:`noreferrer`,className:`inline-flex items-center gap-1 text-xs text-primary underline-offset-2 hover:underline`,children:[t,(0,b.jsx)(l,{className:`h-3 w-3`})]})}),(0,b.jsx)(u,{className:`text-right`,children:(0,b.jsxs)(`div`,{className:`inline-flex gap-1`,children:[(0,b.jsx)(h,{variant:`ghost`,size:`sm`,title:`Copy URL`,onClick:()=>Q(`URL`,t),children:(0,b.jsx)(le,{className:`h-3.5 w-3.5`})}),(0,b.jsx)(h,{variant:`ghost`,size:`sm`,title:`Copy <iframe> embed`,onClick:()=>Q(`iframe snippet`,ye(e.slug)),children:(0,b.jsx)(oe,{className:`h-3.5 w-3.5`})}),(0,b.jsx)(h,{variant:`ghost`,size:`sm`,title:`Copy React snippet`,onClick:()=>Q(`React snippet`,be(e.slug)),children:(0,b.jsx)(ne,{className:`h-3.5 w-3.5`})}),(0,b.jsx)(h,{variant:`ghost`,size:`sm`,title:`Edit sharing & post-submit behavior`,onClick:()=>Se(e),children:(0,b.jsx)(ue,{className:`h-3.5 w-3.5`})})]})})]},e.name)})})]})]})]}),(0,b.jsx)(a,{open:ge,onOpenChange:O,children:(0,b.jsxs)(o,{className:`sm:max-w-md`,children:[(0,b.jsxs)(_,{children:[(0,b.jsx)(i,{children:`Publish a FormView`}),(0,b.jsxs)(s,{children:[`Pick an existing FormView and turn it into a public form by enabling `,(0,b.jsx)(`code`,{className:`text-xs`,children:`sharing.allowAnonymous`}),` `,`and setting `,(0,b.jsx)(`code`,{className:`text-xs`,children:`publicLink`}),`.`]})]}),(0,b.jsxs)(`div`,{className:`space-y-3`,children:[(0,b.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,b.jsx)(p,{htmlFor:`publish-view`,children:`FormView`}),(0,b.jsxs)(`select`,{id:`publish-view`,className:`flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm`,value:k,onChange:e=>A(e.target.value),children:[(0,b.jsx)(`option`,{value:``,children:`— Select a FormView —`}),C.map(e=>(0,b.jsxs)(`option`,{value:e.name,children:[e.label??e.name,` (`,e.name,`) `,e.object?`· ${e.object}`:``]},e.name))]})]}),(0,b.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,b.jsx)(p,{htmlFor:`publish-slug`,children:`URL slug`}),(0,b.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,b.jsx)(`span`,{className:`text-xs text-muted-foreground whitespace-nowrap`,children:`/console/f/`}),(0,b.jsx)(f,{id:`publish-slug`,placeholder:`contact-us`,value:j,onChange:e=>M(e.target.value)})]}),(0,b.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Lowercase letters, digits, dashes and underscores only.`})]})]}),(0,b.jsxs)(c,{children:[(0,b.jsx)(h,{variant:`ghost`,onClick:()=>O(!1),disabled:N,children:`Cancel`}),(0,b.jsx)(h,{onClick:xe,disabled:N||!k||!j,children:N?`Publishing…`:`Publish`})]})]})}),(0,b.jsx)(a,{open:_e,onOpenChange:F,children:(0,b.jsxs)(o,{className:`sm:max-w-lg`,children:[(0,b.jsxs)(_,{children:[(0,b.jsx)(i,{children:I?`Edit ${I.label??I.name}`:`Edit form`}),(0,b.jsx)(s,{children:`Configure the public URL and what happens after submit.`})]}),(0,b.jsxs)(`div`,{className:`space-y-3`,children:[(0,b.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,b.jsx)(p,{htmlFor:`edit-slug`,children:`URL slug`}),(0,b.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,b.jsx)(`span`,{className:`text-xs text-muted-foreground whitespace-nowrap`,children:`/console/f/`}),(0,b.jsx)(f,{id:`edit-slug`,value:R,onChange:e=>z(e.target.value)})]})]}),(0,b.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,b.jsx)(p,{htmlFor:`edit-behavior`,children:`After submit`}),(0,b.jsxs)(`select`,{id:`edit-behavior`,className:`flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm`,value:B,onChange:e=>V(e.target.value),children:[(0,b.jsx)(`option`,{value:`thank-you`,children:`Show a thank-you panel`}),(0,b.jsx)(`option`,{value:`redirect`,children:`Redirect to a URL`}),(0,b.jsx)(`option`,{value:`continue`,children:`Reset for another response`}),(0,b.jsx)(`option`,{value:`next-record`,children:`Advance to next record (internal queues)`})]})]}),B===`thank-you`&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,b.jsx)(p,{htmlFor:`edit-tytitle`,children:`Title`}),(0,b.jsx)(f,{id:`edit-tytitle`,placeholder:`Thanks!`,value:H,onChange:e=>U(e.target.value)})]}),(0,b.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,b.jsx)(p,{htmlFor:`edit-tymsg`,children:`Message`}),(0,b.jsx)(f,{id:`edit-tymsg`,placeholder:`Your submission has been received.`,value:W,onChange:e=>G(e.target.value)})]})]}),B===`redirect`&&(0,b.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,b.jsx)(p,{htmlFor:`edit-url`,children:`Redirect URL`}),(0,b.jsx)(f,{id:`edit-url`,type:`url`,placeholder:`https://example.com/thanks`,value:K,onChange:e=>q(e.target.value)})]})]}),(0,b.jsxs)(c,{children:[(0,b.jsx)(h,{variant:`ghost`,onClick:()=>F(!1),disabled:J,children:`Cancel`}),(0,b.jsx)(h,{onClick:Ce,disabled:J||!R,children:J?`Saving…`:`Save`})]})]})})]})}export{C as PublicFormsPage};
@@ -1 +0,0 @@
1
- import{n as e}from"./vendor-objectstack-CwZ3saTl.js";import{lt as t}from"./framework-ClI3DbWX.js";var n=class{cache;inflight;maxSize;ttl;stats;constructor(e={}){this.cache=new Map,this.inflight=new Map,this.maxSize=e.maxSize||100,this.ttl=e.ttl||300*1e3,this.stats={hits:0,misses:0,evictions:0,coalesced:0}}async get(e,t){let n=Date.now(),r=this.cache.get(e);if(r){if(n-r.timestamp<this.ttl)return r.accessCount++,r.lastAccessed=n,this.stats.hits++,this.cache.delete(e),this.cache.set(e,r),r.data;this.cache.delete(e)}let i=this.inflight.get(e);if(i)return this.stats.coalesced++,i;this.stats.misses++;let a=(async()=>{try{let n=await t();return this.set(e,n),n}finally{this.inflight.delete(e)}})();return this.inflight.set(e,a),a}prime(e,t){this.set(e,t)}set(e,t){let n=Date.now();this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictLRU(),this.cache.set(e,{data:t,timestamp:n,accessCount:1,lastAccessed:n})}evictLRU(){let e=this.cache.keys().next().value;e!==void 0&&(this.cache.delete(e),this.stats.evictions++)}invalidate(e){e?this.cache.delete(e):this.cache.clear()}clear(){this.cache.clear(),this.inflight.clear(),this.stats={hits:0,misses:0,evictions:0,coalesced:0}}getStats(){let e=this.stats.hits+this.stats.misses,t=e>0?this.stats.hits/e:0;return{size:this.cache.size,maxSize:this.maxSize,hits:this.stats.hits,misses:this.stats.misses,evictions:this.stats.evictions,coalesced:this.stats.coalesced,hitRate:t}}getCachedSync(e){let t=this.cache.get(e);if(t){if(this.ttl>0&&Date.now()-t.timestamp>this.ttl){this.cache.delete(e);return}return this.cache.delete(e),this.cache.set(e,t),this.stats.hits++,t.data}}has(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>=this.ttl?(this.cache.delete(e),!1):!0:!1}},r=class extends Error{code;statusCode;details;constructor(e,t,n,r){super(e),this.code=t,this.statusCode=n,this.details=r,this.name=`ObjectStackError`,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,details:this.details,stack:this.stack}}},i=class extends r{constructor(e,t){super(`Metadata not found for object: ${e}`,`METADATA_NOT_FOUND`,404,{objectName:e,...t}),this.name=`MetadataNotFoundError`}},a=class extends r{successCount;failureCount;errors;constructor(e,t,n,r,i){super(`Bulk ${e} operation failed: ${t} succeeded, ${n} failed`,`BULK_OPERATION_ERROR`,500,{operation:e,successCount:t,failureCount:n,errors:r,...i}),this.successCount=t,this.failureCount=n,this.errors=r,this.name=`BulkOperationError`}getSummary(){let e=this.successCount+this.failureCount,t=e>0?this.failureCount/e:0;return{operation:this.details?.operation,total:e,successful:this.successCount,failed:this.failureCount,failureRate:t,errors:this.errors}}},o=class extends r{url;constructor(e,t,n,r){super(`Connection error: ${e}`,`CONNECTION_ERROR`,r||503,{url:t,...n}),this.url=t,this.name=`ConnectionError`}},s=class extends r{constructor(e=`Authentication failed`,t,n){super(e,`AUTHENTICATION_ERROR`,n||401,t),this.name=`AuthenticationError`}},c=class extends r{field;validationErrors;constructor(e,t,n,r){super(e,`VALIDATION_ERROR`,400,{field:t,validationErrors:n,...r}),this.field=t,this.validationErrors=n,this.name=`ValidationError`}getValidationErrors(){return this.validationErrors||[]}};function l(e,t){let n=e?.status||e?.statusCode||500,a=e?.message||e?.statusText||`Unknown error`,l={context:t,response:{status:n,data:e?.data,headers:e?.headers}};switch(n){case 401:return new s(a,l,401);case 403:return new s(a,l,403);case 404:return t?.includes(`metadata`)||t?.includes(`schema`)||t?.includes(`getObjectSchema`)?new i(u(t),l):new r(a,`NOT_FOUND`,404,l);case 400:return new c(a,void 0,e?.data?.errors,l);case 503:return new o(a,e?.config?.url,l,503);case 504:return new o(a,e?.config?.url,l,504);default:return new r(a,`UNKNOWN_ERROR`,n,l)}}function u(e){if(!e)return`unknown`;let t=e.match(/\(([^)]+)\)/);return t?t[1]:`unknown`}var d=`sys_user_preference`;function f(e){let{dataSource:t,userId:n,key:r,resource:i=d,onError:a=()=>{}}=e,o=null,s=async()=>{let e={$filter:{user_id:n,key:r},$top:1};return((await t.find(i,e))?.data??[]).find(e=>{if(!e)return!1;let t=e.user_id!==void 0&&e.user_id!==n,i=e.key!==void 0&&e.key!==r;return!t&&!i})??null},c=e=>{if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return[]};return{async load(){try{let e=await s();return e?(e.id!==void 0&&e.id!==null&&(o=e.id),c(e.value)):(o=null,[])}catch(e){return a(`load`,e),[]}},async save(e){try{let c=new Date().toISOString();if(o!==null)try{await t.update(i,o,{value:e,updated_at:c});return}catch(e){o=null,a(`save`,e)}let l=await s();if(l&&l.id!==void 0&&l.id!==null){o=l.id,await t.update(i,l.id,{value:e,updated_at:c});return}let u=(await t.create(i,{user_id:n,key:r,value:e,updated_at:c}))?.id;u!=null&&(o=u)}catch(e){a(`save`,e)}}}}var p=`/meta`,m=`/api/v1`;function h(e){let t=e.baseUrl.replace(/\/+$/,``),n=e.environmentId?`${m}/environments/${encodeURIComponent(e.environmentId)}${p}`:`${m}${p}`;return/\/api\/v\d+$/i.test(t)?`${t.replace(/\/api\/v\d+$/i,``)}${e.environmentId?`${m}/environments/${encodeURIComponent(e.environmentId)}${p}`:`${m}${p}`}`:`${t}${n}`}async function g(e){let t;try{t=await e.json()}catch{t=await e.text().catch(()=>void 0)}let n=(t&&typeof t==`object`&&`error`in t?String(t.error):void 0)??`Metadata request failed: ${e.status} ${e.statusText}`,r=Error(n);return r.status=e.status,r.body=t,t&&typeof t==`object`&&`code`in t&&(r.code=String(t.code)),r}var _=class e{base;fetchImpl;headers;constructor(e){this.base=h(e),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.headers={Accept:`application/json`,...e.headers??{}}}withEnvironment(t){return new e({baseUrl:this.base.replace(/\/api\/v\d+(?:\/environments\/[^/]+)?\/meta$/,``).replace(/\/+$/,``),environmentId:t,fetch:this.fetchImpl,headers:this.headers})}async listTypes(){let e=await this.fetchImpl(this.base,{method:`GET`,headers:this.headers,cache:`no-store`});if(!e.ok)throw await g(e);let t=await e.json();return Array.isArray(t)?t:t&&Array.isArray(t.entries)?t.entries:t&&Array.isArray(t.items)?t.items:t&&Array.isArray(t.types)?t.types.map(e=>({type:e})):[]}async list(e,t={}){let n=t.packageId?`?package=${encodeURIComponent(t.packageId)}`:``,r=`${this.base}/${encodeURIComponent(e)}${n}`,i=await this.fetchImpl(r,{method:`GET`,headers:this.headers,cache:`no-store`});if(!i.ok)throw await g(i);let a=await i.json();return Array.isArray(a)?a:a&&Array.isArray(a.items)?a.items:[]}async get(e,t){let n=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,r=await this.fetchImpl(n,{method:`GET`,headers:this.headers,cache:`no-store`});if(r.status===404)return null;if(!r.ok)throw await g(r);return await r.json()}async save(e,t,n,r={}){let i=r.force?`?force=true`:``,a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${i}`,o={...this.headers,"Content-Type":`application/json`};r.ifMatch&&(o[`If-Match`]=r.ifMatch),r.actor&&(o[`X-Actor`]=r.actor);let s=await this.fetchImpl(a,{method:`PUT`,headers:o,body:JSON.stringify(n)});if(!s.ok)throw await g(s);return await s.json()}async layered(e,t){let n=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}?layers=true`,r=await this.fetchImpl(n,{method:`GET`,headers:this.headers,cache:`no-store`});if(r.status===404)return{code:null,overlay:null,overlayScope:null,effective:null};if(!r.ok)throw await g(r);let i=await r.json();return i&&(`code`in i||`overlay`in i||`effective`in i)?{code:i.code??null,overlay:i.overlay??null,overlayScope:i.overlayScope??null,effective:i.effective??null}:{code:null,overlay:null,overlayScope:null,effective:i}}async references(e,t){let n=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/references`,r=await this.fetchImpl(n,{method:`GET`,headers:this.headers,cache:`no-store`});if(r.status===404)return[];if(!r.ok)throw await g(r);let i=await r.json();return Array.isArray(i)?i:i?.items??[]}async reset(e,t,n={}){let r=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,i={...this.headers};n.ifMatch&&(i[`If-Match`]=n.ifMatch),n.actor&&(i[`X-Actor`]=n.actor);let a=await this.fetchImpl(r,{method:`DELETE`,headers:i});if(!a.ok)throw await g(a);return await a.json()}async history(e,t,n={}){let r=new URLSearchParams;n.sinceSeq!==void 0&&r.set(`sinceSeq`,String(n.sinceSeq)),n.limit!==void 0&&r.set(`limit`,String(n.limit));let i=r.toString(),a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/history${i?`?${i}`:``}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(!o.ok)throw await g(o);return await o.json()}},v={equals:`=`,eq:`=`,"==":`=`,not_equals:`!=`,notequals:`!=`,ne:`!=`,greater_than:`>`,greaterthan:`>`,gt:`>`,greater_than_or_equal:`>=`,greater_than_or_equals:`>=`,greaterthanorequal:`>=`,gte:`>=`,less_than:`<`,lessthan:`<`,lt:`<`,less_than_or_equal:`<=`,less_than_or_equals:`<=`,lessthanorequal:`<=`,lte:`<=`,in:`in`,not_in:`nin`,notin:`nin`,nin:`nin`,contains:`contains`,not_contains:`notcontains`,notcontains:`notcontains`,starts_with:`startswith`,startswith:`startswith`,ends_with:`endswith`,endswith:`endswith`,between:`between`,is_null:`isnull`,isnull:`isnull`,is_not_null:`isnotnull`,isnotnull:`isnotnull`};function y(e){return typeof e==`string`?v[e.toLowerCase()]??v[e]??e:null}function b(e){if(!e||typeof e!=`object`)return null;let t=e.field??e.name,n=y(e.operator??e.op??`=`);return!t||!n?null:[String(t),n,e.value]}function x(e){if(e!=null){if(Array.isArray(e)){if(e.length===0)return;let t=e[0];if(e.length>0&&typeof t==`object`&&t&&!Array.isArray(t)&&t.field!==void 0){let t=e.map(e=>b(e)).filter(e=>e!==null);return t.length===0?void 0:t.length===1?t[0]:[`and`,...t]}return e}if(typeof e==`object`)return Object.keys(e).length===0?void 0:e}}var S=new Map;async function C(e,t){let n=e||`<default>`,r=S.get(n);if(r)return r;let i=t().catch(e=>{throw S.delete(n),e});return S.set(n,i),i}function w(e){if(!e||typeof e!=`object`)return!1;let t=e;if(t.httpStatus===404||t.status===404||t.statusCode===404)return!0;let n=typeof t.code==`string`?t.code:``;return n===`object_not_found`||n===`record_not_found`}var T=class extends Error{code=`CONCURRENT_UPDATE`;httpStatus=409;currentVersion;currentRecord;constructor(e){super(e.message??`Record was modified by another user`),this.name=`ConcurrentUpdateError`,this.currentVersion=e.currentVersion,this.currentRecord=e.currentRecord}};function E(e){if(!e||typeof e!=`object`)return e;let t=e;if(t.code!==`CONCURRENT_UPDATE`&&t.httpStatus!==409||t.code!==`CONCURRENT_UPDATE`)return e;let n=t.details??{};return new T({currentVersion:typeof n.currentVersion==`string`?n.currentVersion:null,currentRecord:n.currentRecord??null,message:typeof t.message==`string`?t.message:void 0})}function D(){let e=e=>{if(!e||typeof e!=`object`)return!1;if(e.status===404||e.statusCode===404)return!0;let t=e.error;if(t&&typeof t==`object`){let e=t.code;if(e===`object_not_found`||e===`record_not_found`)return!0}return!1},t={debug:(e,t)=>console.debug(e,t??``),info:(e,t)=>console.info(e,t??``),warn:(e,t)=>console.warn(e,t??``),error:(t,n,r)=>{if(e(r)){console.debug(`[ObjectStack] ${t} (suppressed expected 404)`,r);return}console.error(t,n??``,r??``)},fatal:(e,t,n)=>console.error(e,t??``,n??``),log:(e,...t)=>console.log(e,...t),child:()=>t,withTrace:()=>t};return t}function O(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(O).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${O(t[e])}`).join(`,`)}}`}var k=class{client;connected=!1;connectPromise=null;metadataCache;connectionState=`disconnected`;connectionStateListeners=[];batchProgressListeners=[];autoReconnect;maxReconnectAttempts;reconnectDelay;reconnectAttempts=0;baseUrl;token;fetchImpl;inflightFinds=new Map;missingResources=new Set;constructor(t){this.client=new e({...t,logger:D()}),this.metadataCache=new n(t.cache),this.autoReconnect=t.autoReconnect??!0,this.maxReconnectAttempts=t.maxReconnectAttempts??3,this.reconnectDelay=t.reconnectDelay??1e3,this.baseUrl=t.baseUrl,this.token=t.token,this.fetchImpl=t.fetch||globalThis.fetch.bind(globalThis)}async connect(){if(!this.connected)return this.connectPromise?this.connectPromise:(this.setConnectionState(`connecting`),this.connectPromise=(async()=>{try{let e=this.baseUrl||``,t=e?`${e.replace(/\/$/,``)}/api/v1/discovery`:`/api/v1/discovery`,n=await C(e,async()=>{let e=await this.fetchImpl(t,{method:`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`}:void 0});if(!e.ok)throw Error(`discovery ${e.status} ${e.statusText}`);let n=await e.json();return n&&typeof n.success==`boolean`&&`data`in n?n.data:n});this.client.discoveryInfo=n,this.connected=!0,this.reconnectAttempts=0,this.setConnectionState(`connected`)}catch(e){let t=new o(e instanceof Error?e.message:`Failed to connect to ObjectStack server`,void 0,{originalError:e});if(this.setConnectionState(`error`,t),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts)await this.attemptReconnect();else throw t}finally{this.connectPromise=null}})(),this.connectPromise)}async attemptReconnect(){this.reconnectAttempts++,this.setConnectionState(`reconnecting`);let e=this.reconnectDelay*2**(this.reconnectAttempts-1);await new Promise(t=>setTimeout(t,e)),this.connected=!1,await this.connect()}getConnectionState(){return this.connectionState}isConnected(){return this.connected&&this.connectionState===`connected`}onConnectionStateChange(e){return this.connectionStateListeners.push(e),()=>{let t=this.connectionStateListeners.indexOf(e);t>-1&&this.connectionStateListeners.splice(t,1)}}onBatchProgress(e){return this.batchProgressListeners.push(e),()=>{let t=this.batchProgressListeners.indexOf(e);t>-1&&this.batchProgressListeners.splice(t,1)}}setConnectionState(e,t){this.connectionState=e;let n={state:e,timestamp:Date.now(),error:t};this.connectionStateListeners.forEach(e=>{try{e(n)}catch(e){console.error(`Error in connection state listener:`,e)}})}emitBatchProgress(e){this.batchProgressListeners.forEach(t=>{try{t(e)}catch(e){console.error(`Error in batch progress listener:`,e)}})}async find(e,t){if(this.missingResources.has(e))return{data:[],total:0};let n=`${e}::${O(t)}`,r=this.inflightFinds.get(n);if(r)return r;let i=(async()=>{if(await this.connect(),t?.$expand&&t.$expand.length>0){let n=await this.rawFindWithPopulate(e,t);return this.normalizeQueryResult(n,t)}let n=this.convertQueryParams(t);try{let r=await this.client.data.find(e,n);return this.normalizeQueryResult(r,t)}catch(t){if(w(t))return this.missingResources.add(e),{data:[],total:0};throw t}})();this.inflightFinds.set(n,i);let a=()=>{this.inflightFinds.get(n)===i&&this.inflightFinds.delete(n)};return i.then(a,a),i}async findOne(e,t,n){if(await this.connect(),n?.$expand&&n.$expand.length>0)try{let r={...n,$filter:{id:String(t)},$top:1},i=await this.rawFindWithPopulate(e,r);if(Array.isArray(i))return i[0]||null;let a=i;return(a.records||a.value||[])[0]||null}catch(e){if(w(e))return null}try{return(await this.client.data.get(e,String(t))).record}catch(e){if(w(e))return null;throw e}}async create(e,t){return await this.connect(),(await this.client.data.create(e,t)).record}async update(e,t,n,r){await this.connect();try{return(await this.client.data.update(e,String(t),n,r?.ifMatch?{ifMatch:r.ifMatch}:void 0)).record}catch(e){throw E(e)}}async delete(e,t,n){await this.connect();try{return(await this.client.data.delete(e,String(t),n?.ifMatch?{ifMatch:n.ifMatch}:void 0)).deleted}catch(e){throw E(e)}}async bulkUpdate(e,t,n){if(await this.connect(),!t||t.length===0)return 0;let r=t.map(e=>({id:String(e),data:n})),i=this.client.data.updateMany;if(typeof i==`function`)try{let n=await i(e,r,{continueOnError:!0});return n&&typeof n==`object`&&typeof n.succeeded==`number`?n.succeeded:Array.isArray(n)?n.length:t.length}catch(e){throw E(e)}let a=0;for(let r of t)try{await this.client.data.update(e,String(r),n),a++}catch{}return a}async bulkDelete(e,t){if(await this.connect(),!t||t.length===0)return 0;let n=t.map(e=>String(e)),r=this.client.data.deleteMany;if(typeof r==`function`)try{let t=await r(e,n,{continueOnError:!0});return t&&typeof t==`object`&&typeof t.succeeded==`number`?t.succeeded:Array.isArray(t)?t.length:n.length}catch(e){throw E(e)}let i=0;for(let t of n)try{await this.client.data.delete(e,t),i++}catch{}return i}async bulk(e,t,n){if(await this.connect(),!n||n.length===0)return[];let i=n.length,o=0,s=0,c=()=>{this.emitBatchProgress({operation:t,total:i,completed:o,failed:s,percentage:i>0?(o+s)/i*100:0})};try{switch(t){case`create`:{c();let t=await this.client.data.createMany(e,n);return o=t.length,s=i-o,c(),t}case`delete`:{let t=n.map(e=>e.id).filter(Boolean);if(t.length===0){let e=n.map((e,t)=>({index:t,error:`Missing ID for item at index ${t}`}));throw s=n.length,c(),new a(`delete`,0,n.length,e)}return c(),await this.client.data.deleteMany(e,t),o=t.length,s=i-o,c(),[]}case`update`:{if(typeof this.client.data.updateMany==`function`)try{c();let t=this.client.data.updateMany,r=await t(e,n);return o=r.length,s=i-o,c(),r}catch{}let t=[],r=[];for(let i=0;i<n.length;i++){let a=n[i],l=a.id;if(!l){r.push({index:i,error:`Missing ID`}),s++,c();continue}try{let n=await this.client.data.update(e,String(l),a);t.push(n.record),o++,c()}catch(e){let t=e instanceof Error?e.message:String(e);r.push({index:i,error:t}),s++,c()}}if(r.length>0)throw new a(`update`,t.length,r.length,r,{resource:e,totalRecords:n.length});return t}default:throw new r(`Unsupported bulk operation: ${t}`,`UNSUPPORTED_OPERATION`,400)}}catch(i){if(c(),i instanceof a||i instanceof r)throw i;let o=i instanceof Error?i.message:String(i),s=n.map((e,t)=>({index:t,error:o}));throw new a(t,0,n.length,s,{resource:e,originalError:i})}}normalizeQueryResult(e,t){if(Array.isArray(e))return{data:e,total:e.length,page:1,pageSize:e.length,hasMore:!1};let n=e,r=n.records||n.value||[];return{data:r,total:n.total??n.count??r.length,page:t?.$skip&&t.$top?Math.floor(t.$skip/t.$top)+1:1,pageSize:t?.$top,hasMore:t?.$top?r.length===t.$top:!1}}async rawFindWithPopulate(e,t){let n=new URLSearchParams;if(t.$expand&&t.$expand.length>0&&n.set(`populate`,t.$expand.join(`,`)),t.$top!==void 0&&n.set(`top`,String(t.$top)),t.$skip!==void 0&&n.set(`skip`,String(t.$skip)),t.$select&&t.$select.length>0){let e=t.$select.includes(`id`)?t.$select:[`id`,...t.$select];n.set(`select`,e.join(`,`))}if(t.$orderby)if(Array.isArray(t.$orderby)){let e=t.$orderby.map(e=>{if(typeof e==`string`)return e;let t=e.field;return(e.order||`asc`)===`desc`?`-${t}`:t}).join(`,`);n.set(`sort`,e)}else{let e=Object.entries(t.$orderby).map(([e,t])=>t===`desc`?`-${e}`:e).join(`,`);n.set(`sort`,e)}if(t.$filter!==void 0&&t.$filter!==null){let e=x(t.$filter);e!==void 0&&n.set(`filter`,JSON.stringify(e))}let r=this.baseUrl.replace(/\/$/,``),i=n.toString(),a=`${r}${/\/api\/v\d+$/i.test(r)?`/data`:`/api/v1/data`}/${e}${i?`?${i}`:``}`,o={"Content-Type":`application/json`};this.token&&(o.Authorization=`Bearer ${this.token}`);let s=await this.fetchImpl(a,{method:`GET`,headers:o});if(!s.ok){let e=await s.json().catch(()=>({message:s.statusText})),t=Error(e?.error?.message||e?.message||s.statusText);throw t.status=s.status,t}let c=await s.json();return c&&typeof c.success==`boolean`&&`data`in c?c.data:c}convertQueryParams(e){if(!e)return{};let n={};if(e.$select&&(n.select=e.$select.includes(`id`)?e.$select:[`id`,...e.$select]),e.$filter!==void 0&&e.$filter!==null&&!(Array.isArray(e.$filter)?e.$filter.length===0:typeof e.$filter==`object`&&Object.keys(e.$filter).length===0))if(Array.isArray(e.$filter))if(e.$filter.length>0&&typeof e.$filter[0]==`object`&&!Array.isArray(e.$filter[0])&&e.$filter[0].field!==void 0){let t=e.$filter.map(e=>b(e)).filter(e=>e!==null);t.length===0||(t.length===1?n.filters=t[0]:n.filters=[`and`,...t])}else n.filters=e.$filter;else n.filters=t(e.$filter);return e.$orderby&&(Array.isArray(e.$orderby)?n.sort=e.$orderby.map(e=>{if(typeof e==`string`)return e;let t=e.field;return(e.order||`asc`)===`desc`?`-${t}`:t}):n.sort=Object.entries(e.$orderby).map(([e,t])=>t===`desc`?`-${e}`:e)),e.$skip!==void 0&&(n.skip=e.$skip),e.$top!==void 0&&(n.top=e.$top),n}async getObjectSchema(e){await this.connect();try{return await this.metadataCache.get(e,async()=>{let t=await this.client.meta.getItem(`object`,e);return t&&t.item?t.item:t})}catch(t){let n=t;throw w(n)?new i(e,{originalError:t}):t instanceof r?t:l(n,`getObjectSchema(${e})`)}}getClient(){return this.client}async getDiscovery(){try{return await this.connect(),this.client.discoveryInfo||null}catch{return null}}async listViewOverrides(e){await this.connect();try{let t=`view-overrides:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItems(e),n=Array.isArray(t?.items)?t.items:[],r={};for(let e of n){if(!e||typeof e!=`object`)continue;let t=e.name??e.id??e._name;typeof t==`string`&&t&&(r[t]=e)}return r})}catch{return{}}}async getView(e,t){await this.connect();try{let n=`view:${e}:${t}`;return await this.metadataCache.get(n,async()=>{let n=await this.client.meta.getItem(e,t);return n&&n.item?n.item:n??null})}catch{return null}}async updateViewConfig(e,t,n){await this.connect();try{let r={...n||{},object:n?.object||e,name:t},i=await this.client.meta.saveItem(`view`,t,r),a=`view:${e}:${t}`;return this.metadataCache.invalidate?.(a),this.metadataCache.invalidate?.(`view-overrides:${e}`),this.metadataCache.invalidate?.(`views:${e}`),i&&i.item?i.item:i??void 0}catch(e){throw e}}async listViews(e){await this.connect();try{let t=await this.client.meta.getItems(`view`);return(Array.isArray(t?.items)?t.items:Array.isArray(t)?t:[]).filter(t=>{if(!t)return!1;let n=t.list??t;return(n?.data?.object??n?.object??n?.objectName)===e}).map(e=>e.list??e)}catch(e){return console.warn(`[OBJECTSTACKDataSource] listViews failed:`,e),[]}}async createView(e,t){await this.connect();let n=String(t?.name||``).trim();if(!n){let r=String(t?.label||e||`view`).toLowerCase().replace(/[^a-z0-9_]+/g,`_`).replace(/^_+|_+$/g,``).slice(0,40);(!r||/^[0-9]/.test(r))&&(r=r?`view_${r}`:`view`);let i=Date.now().toString(36);n=`${r}_${i}`}let r={...t,name:n,object:t?.object||e,data:t?.data||{provider:`object`,object:e}};try{let t=await this.client.meta.saveItem(`view`,n,r);return this.metadataCache.invalidate?.(`views:${e}`),t&&t.item?t.item:r}catch(e){throw e}}async updateView(e,t,n){await this.connect();let r={};try{let e=await this.client.meta.getItem(`view`,t);r=e&&(e.item||e)||{},r?.list&&(r=r.list)}catch{}let i={...r,...n,name:t,object:r?.object||r?.data?.object||e};try{let n=await this.client.meta.saveItem(`view`,t,i);return this.metadataCache.invalidate?.(`views:${e}`),this.metadataCache.invalidate?.(`view:${e}:${t}`),n&&n.item?n.item:i}catch(e){throw e}}async deleteView(e,t){await this.connect();try{let n=await this.client.meta.deleteItem(`view`,t);return this.metadataCache.invalidate?.(`views:${e}`),this.metadataCache.invalidate?.(`view:${e}:${t}`),{deleted:!!(n?.deleted??n?.reset??!0)}}catch(e){throw e}}async getApp(e){await this.connect();try{let t=`app:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItem(`apps`,e);return t&&t.item?t.item:t??null})}catch{return null}}async getPage(e){await this.connect();try{let t=`page:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItem(`pages`,e);return t&&t.item?t.item:t??null})}catch{return null}}async updateDashboard(e,t){await this.connect();try{let n=await this.client.meta.saveItem(`dashboard`,e,t);return this.metadataCache.invalidate?.(`dashboards`),this.metadataCache.invalidate?.(`dashboard:${e}`),n&&n.item?n.item:n??void 0}catch(e){throw e}}async aggregate(e,t){if(await this.connect(),t!=null&&(Array.isArray(t.groupBy)||Array.isArray(t.aggregations)||t.where!==void 0)){let n={};Array.isArray(t.groupBy)&&(n.groupBy=t.groupBy),Array.isArray(t.aggregations)&&(n.aggregations=t.aggregations),t.where!==void 0&&(n.where=t.where),typeof t.limit==`number`&&(n.limit=t.limit);let r=await this.client.data.query(e,n);return Array.isArray(r)?r:Array.isArray(r?.records)?r.records:Array.isArray(r?.data)?r.data:[]}try{let n=t.function===`count`?`count`:`${t.field}_${t.function}`,r={cube:e,measures:[n],dimensions:t.groupBy&&t.groupBy!==`_all`?[t.groupBy]:[]};t.filter&&(r.where=t.filter);let i=await this.client.analytics.query(r),a=Array.isArray(i)?i:i?.rows&&Array.isArray(i.rows)?i.rows:i?.data&&Array.isArray(i.data)?i.data:i?.data?.rows&&Array.isArray(i.data.rows)?i.data.rows:i?.results&&Array.isArray(i.results)?i.results:[];if(a.length>0&&a.every(e=>e==null?!0:!(n in e&&e[n]!=null||t.field in e&&e[t.field]!=null))){let n=(await this.find(e,t.filter?{$filter:t.filter}:void 0)).data||[];return n.length===0?[]:this.aggregateClientSide(n,t)}return a.map(e=>{let r={...e};return n!==t.field&&n in r&&(r[t.field]=r[n],delete r[n]),r})}catch{let n=(await this.find(e,t.filter?{$filter:t.filter}:void 0)).data||[];return n.length===0?[]:this.aggregateClientSide(n,t)}}aggregateClientSide(e,t){let{field:n,function:r,groupBy:i}=t,a={};for(let t of e){let e=String(t[i]??`Unknown`);a[e]||(a[e]=[]),a[e].push(t)}return Object.entries(a).map(([e,t])=>{let a=t.map(e=>Number(e[n])||0),o;switch(r){case`count`:o=t.length;break;case`avg`:o=a.length>0?a.reduce((e,t)=>e+t,0)/a.length:0;break;case`min`:o=a.length>0?Math.min(...a):0;break;case`max`:o=a.length>0?Math.max(...a):0;break;default:o=a.reduce((e,t)=>e+t,0);break}return{[i]:e,[n]:o}})}async getItems(e,t){return await this.connect(),await Promise.all(t.map(async t=>{let n=`${e}:${t}`;return this.metadataCache.get(n,async()=>{let n=await this.client.meta.getItem(e,t);return n&&n.item?n.item:n})}))}getCached(e){return this.metadataCache.getCachedSync(e)}getCacheStats(){return this.metadataCache.getStats()}invalidateCache(e){this.metadataCache.invalidate(e)}clearCache(){this.metadataCache.clear()}async uploadFile(e,t,n){await this.connect();let i=new FormData;i.append(`file`,t),n?.recordId&&i.append(`recordId`,n.recordId),n?.fieldName&&i.append(`fieldName`,n.fieldName),n?.metadata&&i.append(`metadata`,JSON.stringify(n.metadata));let a=`${this.baseUrl}/api/data/${encodeURIComponent(e)}/upload`,o=await fetch(a,{method:`POST`,body:i,headers:{...this.getAuthHeaders()}});if(!o.ok)throw new r((await o.json().catch(()=>({message:o.statusText}))).message||`Upload failed with status ${o.status}`,`UPLOAD_ERROR`,o.status);return o.json()}async uploadFiles(e,t,n){await this.connect();let i=new FormData;t.forEach((e,t)=>{i.append(`files`,e,e.name||`file-${t}`)}),n?.recordId&&i.append(`recordId`,n.recordId),n?.fieldName&&i.append(`fieldName`,n.fieldName),n?.metadata&&i.append(`metadata`,JSON.stringify(n.metadata));let a=`${this.baseUrl}/api/data/${encodeURIComponent(e)}/upload`,o=await fetch(a,{method:`POST`,body:i,headers:{...this.getAuthHeaders()}});if(!o.ok)throw new r((await o.json().catch(()=>({message:o.statusText}))).message||`Upload failed with status ${o.status}`,`UPLOAD_ERROR`,o.status);return o.json()}async cancelPendingApproval(e,t){await this.connect();let n=`${this.baseUrl}/api/v1/approvals/requests?recordId=${encodeURIComponent(t)}&object=${encodeURIComponent(e)}`,i=await this.fetchImpl(n,{method:`GET`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()}});if(!i.ok)throw new r(`Failed to look up approval requests (status ${i.status})`,`APPROVAL_LOOKUP_FAILED`,i.status);let a=await i.json().catch(()=>({})),o=(Array.isArray(a)?a:a?.data??[]).find(e=>e?.status===`pending`||e?.status===`in_approval`);if(!o?.id)throw new r(`No pending approval request found for this record`,`NO_PENDING_REQUEST`,404);let s=`${this.baseUrl}/api/v1/approvals/requests/${encodeURIComponent(o.id)}/recall`,c=await this.fetchImpl(s,{method:`POST`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()},body:JSON.stringify({})});if(!c.ok){let e=await c.json().catch(()=>({}));throw new r(e?.error||e?.message||`Recall failed with status ${c.status}`,e?.code||`APPROVAL_RECALL_FAILED`,c.status)}let l=await c.json().catch(()=>({}));return{requestId:o.id,status:l?.data?.request?.status??`recalled`}}getAuthHeaders(){let e={};return this.token&&(e.Authorization=`Bearer ${this.token}`),e}};export{_ as n,f as r,k as t};