@standardbeagle/edit-db 0.4.494 → 0.4.583

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 (92) hide show
  1. package/dist/common/saved-objects.d.ts +40 -0
  2. package/dist/common/schema-queries.d.ts +1 -0
  3. package/dist/components/bulk-edit-dialog.d.ts +18 -0
  4. package/dist/components/content-viewer.d.ts +8 -1
  5. package/dist/components/data-table.d.ts +49 -2
  6. package/dist/components/detail-panel.d.ts +2 -2
  7. package/dist/components/export-button.d.ts +19 -0
  8. package/dist/components/export-button.test.d.ts +1 -0
  9. package/dist/components/filters/number-filter.d.ts +8 -1
  10. package/dist/components/fk-cell-popover.d.ts +5 -5
  11. package/dist/components/form-runner-host.d.ts +14 -0
  12. package/dist/components/form-runner.d.ts +43 -0
  13. package/dist/components/form-subform.d.ts +11 -0
  14. package/dist/components/form-subform.test.d.ts +0 -0
  15. package/dist/components/grouped-grid-summary.d.ts +17 -0
  16. package/dist/components/grouped-grid-summary.test.d.ts +0 -0
  17. package/dist/components/m2m-panel.d.ts +4 -5
  18. package/dist/components/ui/table.test.d.ts +1 -0
  19. package/dist/data-edit.d.ts +17 -4
  20. package/dist/data-panel.d.ts +0 -11
  21. package/dist/edit-db.css +1 -1
  22. package/dist/editor.d.ts +22 -1
  23. package/dist/editor.es.js +6822 -4695
  24. package/dist/editor.stories.d.ts +0 -1
  25. package/dist/editor.umd.cjs +41 -27
  26. package/dist/hooks/useColumnNav.d.ts +3 -3
  27. package/dist/hooks/useColumnSizingPersistence.d.ts +19 -0
  28. package/dist/hooks/useColumnVisibilityPersistence.d.ts +34 -0
  29. package/dist/hooks/useColumnVisibilityPersistence.test.d.ts +1 -0
  30. package/dist/hooks/useCompositeTableRef.d.ts +2 -2
  31. package/dist/hooks/useDataTable.d.ts +46 -5
  32. package/dist/hooks/useDebouncedCommit.test.d.ts +1 -0
  33. package/dist/hooks/useDeltaMutation.d.ts +20 -0
  34. package/dist/hooks/useDeltaMutation.test.d.ts +0 -0
  35. package/dist/hooks/useEditorConfig.d.ts +27 -0
  36. package/dist/hooks/useFitMode.d.ts +23 -0
  37. package/dist/hooks/useFitMode.test.d.ts +1 -0
  38. package/dist/hooks/usePanelSize.d.ts +28 -0
  39. package/dist/hooks/usePanelSize.test.d.ts +1 -0
  40. package/dist/hooks/usePath.d.ts +1 -0
  41. package/dist/hooks/useRowHoverActions.d.ts +26 -0
  42. package/dist/hooks/useSchema.d.ts +8 -2
  43. package/dist/hooks/useSchemaFilter.test.d.ts +1 -0
  44. package/dist/hooks/useTableExport.d.ts +13 -0
  45. package/dist/hooks/useTableMutation.d.ts +1 -4
  46. package/dist/hooks/useTableRef.d.ts +3 -3
  47. package/dist/hooks/useTableStats.d.ts +0 -24
  48. package/dist/index.d.ts +13 -1
  49. package/dist/lib/column-order.d.ts +17 -0
  50. package/dist/lib/column-order.test.d.ts +1 -0
  51. package/dist/lib/content-detect.d.ts +34 -0
  52. package/dist/lib/content-detect.sniff.test.d.ts +1 -0
  53. package/dist/lib/drill-stack.d.ts +19 -2
  54. package/dist/lib/export.d.ts +122 -0
  55. package/dist/lib/export.test.d.ts +1 -0
  56. package/dist/lib/field-validation.d.ts +16 -0
  57. package/dist/lib/fk.d.ts +13 -0
  58. package/dist/lib/form-definition.d.ts +57 -0
  59. package/dist/lib/form-definition.test.d.ts +1 -0
  60. package/dist/lib/form-runner-nav.d.ts +19 -0
  61. package/dist/lib/form-runner-nav.test.d.ts +1 -0
  62. package/dist/lib/form-subform.d.ts +12 -0
  63. package/dist/lib/form-subform.test.d.ts +1 -0
  64. package/dist/lib/form-widget.d.ts +36 -0
  65. package/dist/lib/form-widget.test.d.ts +1 -0
  66. package/dist/lib/format-value.d.ts +26 -0
  67. package/dist/lib/grid-grouping.d.ts +63 -0
  68. package/dist/lib/grid-grouping.test.d.ts +1 -0
  69. package/dist/lib/m2m.d.ts +26 -1
  70. package/dist/lib/mutation-payload.d.ts +37 -0
  71. package/dist/lib/mutation-payload.test.d.ts +1 -0
  72. package/dist/lib/query-builder.d.ts +116 -9
  73. package/dist/lib/row-id.d.ts +11 -0
  74. package/dist/lib/rows-by-pk-query.test.d.ts +1 -0
  75. package/dist/lib/scalar-types.d.ts +30 -0
  76. package/dist/lib/scalar-types.test.d.ts +1 -0
  77. package/dist/lib/table-action.d.ts +24 -0
  78. package/dist/{tableList.d.ts → table-list.d.ts} +1 -1
  79. package/dist/table-list.test.d.ts +0 -0
  80. package/dist/table-view.chart.test.d.ts +1 -0
  81. package/dist/table-view.d.ts +22 -0
  82. package/dist/table-view.test.d.ts +0 -0
  83. package/dist/types/schema.d.ts +45 -10
  84. package/package.json +2 -2
  85. package/dist/common/schema.d.ts +0 -2
  86. package/dist/data-data-table.d.ts +0 -17
  87. /package/dist/common/{schema.test.d.ts → saved-objects.test.d.ts} +0 -0
  88. /package/dist/{components/filters/use-debounced-commit.test.d.ts → common/schema-queries.test.d.ts} +0 -0
  89. /package/dist/{data-data-table.test.d.ts → components/bulk-edit-dialog.test.d.ts} +0 -0
  90. /package/dist/components/{table-dimensions.test.d.ts → content-viewer.test.d.ts} +0 -0
  91. /package/dist/{tableList.test.d.ts → components/form-runner.test.d.ts} +0 -0
  92. /package/dist/{components/filters/use-debounced-commit.d.ts → hooks/useDebouncedCommit.d.ts} +0 -0
@@ -1,17 +1,17 @@
1
- (function(be,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("react"),require("@tanstack/react-query"),require("lucide-react"),require("@radix-ui/react-slot"),require("radix-ui"),require("@tanstack/react-form"),require("@tanstack/react-table")):typeof define=="function"&&define.amd?define(["exports","react","@tanstack/react-query","lucide-react","@radix-ui/react-slot","radix-ui","@tanstack/react-form","@tanstack/react-table"],c):(be=typeof globalThis<"u"?globalThis:be||self,c(be.editor={},be.React,be.ReactQuery,be.LucideReact,be.RadixReactSlot,be.RadixUI,be.ReactForm,be.ReactTable))})(this,(function(be,c,me,N,Js,Q,Bt,Kt){"use strict";function Ws(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}return n.default=e,Object.freeze(n)}const ve=Ws(c);var Gt={exports:{}},Ct={};var Hn;function Hs(){if(Hn)return Ct;Hn=1;var e=c,n=Symbol.for("react.element"),r=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function a(l,u,d){var p,m={},h=null,x=null;d!==void 0&&(h=""+d),u.key!==void 0&&(h=""+u.key),u.ref!==void 0&&(x=u.ref);for(p in u)s.call(u,p)&&!i.hasOwnProperty(p)&&(m[p]=u[p]);if(l&&l.defaultProps)for(p in u=l.defaultProps,u)m[p]===void 0&&(m[p]=u[p]);return{$$typeof:n,type:l,key:h,ref:x,props:m,_owner:o.current}}return Ct.Fragment=r,Ct.jsx=a,Ct.jsxs=a,Ct}var kt={};var Qn;function Qs(){return Qn||(Qn=1,process.env.NODE_ENV!=="production"&&(function(){var e=c,n=Symbol.for("react.element"),r=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),a=Symbol.for("react.provider"),l=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),p=Symbol.for("react.suspense_list"),m=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),x=Symbol.for("react.offscreen"),g=Symbol.iterator,b="@@iterator";function k(f){if(f===null||typeof f!="object")return null;var F=g&&f[g]||f[b];return typeof F=="function"?F:null}var $=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function w(f){{for(var F=arguments.length,A=new Array(F>1?F-1:0),Y=1;Y<F;Y++)A[Y-1]=arguments[Y];P("error",f,A)}}function P(f,F,A){{var Y=$.ReactDebugCurrentFrame,ne=Y.getStackAddendum();ne!==""&&(F+="%s",A=A.concat([ne]));var oe=A.map(function(te){return String(te)});oe.unshift("Warning: "+F),Function.prototype.apply.call(console[f],console,oe)}}var C=!1,T=!1,j=!1,E=!1,y=!1,S;S=Symbol.for("react.module.reference");function L(f){return!!(typeof f=="string"||typeof f=="function"||f===s||f===i||y||f===o||f===d||f===p||E||f===x||C||T||j||typeof f=="object"&&f!==null&&(f.$$typeof===h||f.$$typeof===m||f.$$typeof===a||f.$$typeof===l||f.$$typeof===u||f.$$typeof===S||f.getModuleId!==void 0))}function v(f,F,A){var Y=f.displayName;if(Y)return Y;var ne=F.displayName||F.name||"";return ne!==""?A+"("+ne+")":A}function M(f){return f.displayName||"Context"}function O(f){if(f==null)return null;if(typeof f.tag=="number"&&w("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof f=="function")return f.displayName||f.name||null;if(typeof f=="string")return f;switch(f){case s:return"Fragment";case r:return"Portal";case i:return"Profiler";case o:return"StrictMode";case d:return"Suspense";case p:return"SuspenseList"}if(typeof f=="object")switch(f.$$typeof){case l:var F=f;return M(F)+".Consumer";case a:var A=f;return M(A._context)+".Provider";case u:return v(f,f.render,"ForwardRef");case m:var Y=f.displayName||null;return Y!==null?Y:O(f.type)||"Memo";case h:{var ne=f,oe=ne._payload,te=ne._init;try{return O(te(oe))}catch{return null}}}return null}var z=Object.assign,I=0,_,G,U,ie,B,Te,ye;function xe(){}xe.__reactDisabledLog=!0;function le(){{if(I===0){_=console.log,G=console.info,U=console.warn,ie=console.error,B=console.group,Te=console.groupCollapsed,ye=console.groupEnd;var f={configurable:!0,enumerable:!0,value:xe,writable:!0};Object.defineProperties(console,{info:f,log:f,warn:f,error:f,group:f,groupCollapsed:f,groupEnd:f})}I++}}function re(){{if(I--,I===0){var f={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:z({},f,{value:_}),info:z({},f,{value:G}),warn:z({},f,{value:U}),error:z({},f,{value:ie}),group:z({},f,{value:B}),groupCollapsed:z({},f,{value:Te}),groupEnd:z({},f,{value:ye})})}I<0&&w("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ae=$.ReactCurrentDispatcher,J;function ce(f,F,A){{if(J===void 0)try{throw Error()}catch(ne){var Y=ne.stack.trim().match(/\n( *(at )?)/);J=Y&&Y[1]||""}return`
2
- `+J+f}}var R=!1,Ne;{var Be=typeof WeakMap=="function"?WeakMap:Map;Ne=new Be}function ze(f,F){if(!f||R)return"";{var A=Ne.get(f);if(A!==void 0)return A}var Y;R=!0;var ne=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var oe;oe=ae.current,ae.current=null,le();try{if(F){var te=function(){throw Error()};if(Object.defineProperty(te.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(te,[])}catch(_e){Y=_e}Reflect.construct(f,[],te)}else{try{te.call()}catch(_e){Y=_e}f.call(te.prototype)}}else{try{throw Error()}catch(_e){Y=_e}f()}}catch(_e){if(_e&&Y&&typeof _e.stack=="string"){for(var ee=_e.stack.split(`
3
- `),we=Y.stack.split(`
4
- `),fe=ee.length-1,pe=we.length-1;fe>=1&&pe>=0&&ee[fe]!==we[pe];)pe--;for(;fe>=1&&pe>=0;fe--,pe--)if(ee[fe]!==we[pe]){if(fe!==1||pe!==1)do if(fe--,pe--,pe<0||ee[fe]!==we[pe]){var Me=`
5
- `+ee[fe].replace(" at new "," at ");return f.displayName&&Me.includes("<anonymous>")&&(Me=Me.replace("<anonymous>",f.displayName)),typeof f=="function"&&Ne.set(f,Me),Me}while(fe>=1&&pe>=0);break}}}finally{R=!1,ae.current=oe,re(),Error.prepareStackTrace=ne}var wt=f?f.displayName||f.name:"",ft=wt?ce(wt):"";return typeof f=="function"&&Ne.set(f,ft),ft}function Ke(f,F,A){return ze(f,!1)}function De(f){var F=f.prototype;return!!(F&&F.isReactComponent)}function Ge(f,F,A){if(f==null)return"";if(typeof f=="function")return ze(f,De(f));if(typeof f=="string")return ce(f);switch(f){case d:return ce("Suspense");case p:return ce("SuspenseList")}if(typeof f=="object")switch(f.$$typeof){case u:return Ke(f.render);case m:return Ge(f.type,F,A);case h:{var Y=f,ne=Y._payload,oe=Y._init;try{return Ge(oe(ne),F,A)}catch{}}}return""}var ue=Object.prototype.hasOwnProperty,X={},se=$.ReactDebugCurrentFrame;function Se(f){if(f){var F=f._owner,A=Ge(f.type,f._source,F?F.type:null);se.setExtraStackFrame(A)}else se.setExtraStackFrame(null)}function $e(f,F,A,Y,ne){{var oe=Function.call.bind(ue);for(var te in f)if(oe(f,te)){var ee=void 0;try{if(typeof f[te]!="function"){var we=Error((Y||"React class")+": "+A+" type `"+te+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof f[te]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw we.name="Invariant Violation",we}ee=f[te](F,te,Y,A,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(fe){ee=fe}ee&&!(ee instanceof Error)&&(Se(ne),w("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",Y||"React class",A,te,typeof ee),Se(null)),ee instanceof Error&&!(ee.message in X)&&(X[ee.message]=!0,Se(ne),w("Failed %s type: %s",A,ee.message),Se(null))}}}var rt=Array.isArray;function Je(f){return rt(f)}function ut(f){{var F=typeof Symbol=="function"&&Symbol.toStringTag,A=F&&f[Symbol.toStringTag]||f.constructor.name||"Object";return A}}function st(f){try{return D(f),!1}catch{return!0}}function D(f){return""+f}function K(f){if(st(f))return w("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ut(f)),D(f)}var de=$.ReactCurrentOwner,Ee={key:!0,ref:!0,__self:!0,__source:!0},mt,We;function dn(f){if(ue.call(f,"ref")){var F=Object.getOwnPropertyDescriptor(f,"ref").get;if(F&&F.isReactWarning)return!1}return f.ref!==void 0}function vc(f){if(ue.call(f,"key")){var F=Object.getOwnPropertyDescriptor(f,"key").get;if(F&&F.isReactWarning)return!1}return f.key!==void 0}function jc(f,F){typeof f.ref=="string"&&de.current}function Nc(f,F){{var A=function(){mt||(mt=!0,w("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",F))};A.isReactWarning=!0,Object.defineProperty(f,"key",{get:A,configurable:!0})}}function wc(f,F){{var A=function(){We||(We=!0,w("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",F))};A.isReactWarning=!0,Object.defineProperty(f,"ref",{get:A,configurable:!0})}}var Cc=function(f,F,A,Y,ne,oe,te){var ee={$$typeof:n,type:f,key:F,ref:A,props:te,_owner:oe};return ee._store={},Object.defineProperty(ee._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(ee,"_self",{configurable:!1,enumerable:!1,writable:!1,value:Y}),Object.defineProperty(ee,"_source",{configurable:!1,enumerable:!1,writable:!1,value:ne}),Object.freeze&&(Object.freeze(ee.props),Object.freeze(ee)),ee};function kc(f,F,A,Y,ne){{var oe,te={},ee=null,we=null;A!==void 0&&(K(A),ee=""+A),vc(F)&&(K(F.key),ee=""+F.key),dn(F)&&(we=F.ref,jc(F,ne));for(oe in F)ue.call(F,oe)&&!Ee.hasOwnProperty(oe)&&(te[oe]=F[oe]);if(f&&f.defaultProps){var fe=f.defaultProps;for(oe in fe)te[oe]===void 0&&(te[oe]=fe[oe])}if(ee||we){var pe=typeof f=="function"?f.displayName||f.name||"Unknown":f;ee&&Nc(te,pe),we&&wc(te,pe)}return Cc(f,ee,we,ne,Y,de.current,te)}}var Kn=$.ReactCurrentOwner,Os=$.ReactDebugCurrentFrame;function Nt(f){if(f){var F=f._owner,A=Ge(f.type,f._source,F?F.type:null);Os.setExtraStackFrame(A)}else Os.setExtraStackFrame(null)}var Gn;Gn=!1;function Jn(f){return typeof f=="object"&&f!==null&&f.$$typeof===n}function As(){{if(Kn.current){var f=O(Kn.current.type);if(f)return`
1
+ (function(ae,u){typeof exports=="object"&&typeof module<"u"?u(exports,require("react"),require("@tanstack/react-query"),require("lucide-react"),require("radix-ui"),require("@radix-ui/react-slot"),require("@tanstack/react-form"),require("@tanstack/react-table")):typeof define=="function"&&define.amd?define(["exports","react","@tanstack/react-query","lucide-react","radix-ui","@radix-ui/react-slot","@tanstack/react-form","@tanstack/react-table"],u):(ae=typeof globalThis<"u"?globalThis:ae||self,u(ae.editor={},ae.React,ae.ReactQuery,ae.LucideReact,ae.RadixUI,ae.RadixReactSlot,ae.ReactForm,ae.ReactTable))})(this,(function(ae,u,de,C,R,ka,Tn,$n){"use strict";function Sa(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const Ve=Sa(u);var En={exports:{}},sn={};var ls;function Ta(){if(ls)return sn;ls=1;var e=u,t=Symbol.for("react.element"),r=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function a(l,c,m){var d,f={},p=null,x=null;m!==void 0&&(p=""+m),c.key!==void 0&&(p=""+c.key),c.ref!==void 0&&(x=c.ref);for(d in c)s.call(c,d)&&!i.hasOwnProperty(d)&&(f[d]=c[d]);if(l&&l.defaultProps)for(d in c=l.defaultProps,c)f[d]===void 0&&(f[d]=c[d]);return{$$typeof:t,type:l,key:p,ref:x,props:f,_owner:o.current}}return sn.Fragment=r,sn.jsx=a,sn.jsxs=a,sn}var on={};var cs;function $a(){return cs||(cs=1,process.env.NODE_ENV!=="production"&&(function(){var e=u,t=Symbol.for("react.element"),r=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),a=Symbol.for("react.provider"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),x=Symbol.for("react.offscreen"),h=Symbol.iterator,y="@@iterator";function N(g){if(g===null||typeof g!="object")return null;var M=h&&g[h]||g[y];return typeof M=="function"?M:null}var T=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function k(g){{for(var M=arguments.length,G=new Array(M>1?M-1:0),te=1;te<M;te++)G[te-1]=arguments[te];$("error",g,G)}}function $(g,M,G){{var te=T.ReactDebugCurrentFrame,pe=te.getStackAddendum();pe!==""&&(M+="%s",G=G.concat([pe]));var ge=G.map(function(ue){return String(ue)});ge.unshift("Warning: "+M),Function.prototype.apply.call(console[g],console,ge)}}var b=!1,v=!1,w=!1,F=!1,j=!1,V;V=Symbol.for("react.module.reference");function S(g){return!!(typeof g=="string"||typeof g=="function"||g===s||g===i||j||g===o||g===m||g===d||F||g===x||b||v||w||typeof g=="object"&&g!==null&&(g.$$typeof===p||g.$$typeof===f||g.$$typeof===a||g.$$typeof===l||g.$$typeof===c||g.$$typeof===V||g.getModuleId!==void 0))}function L(g,M,G){var te=g.displayName;if(te)return te;var pe=M.displayName||M.name||"";return pe!==""?G+"("+pe+")":G}function A(g){return g.displayName||"Context"}function D(g){if(g==null)return null;if(typeof g.tag=="number"&&k("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof g=="function")return g.displayName||g.name||null;if(typeof g=="string")return g;switch(g){case s:return"Fragment";case r:return"Portal";case i:return"Profiler";case o:return"StrictMode";case m:return"Suspense";case d:return"SuspenseList"}if(typeof g=="object")switch(g.$$typeof){case l:var M=g;return A(M)+".Consumer";case a:var G=g;return A(G._context)+".Provider";case c:return L(g,g.render,"ForwardRef");case f:var te=g.displayName||null;return te!==null?te:D(g.type)||"Memo";case p:{var pe=g,ge=pe._payload,ue=pe._init;try{return D(ue(ge))}catch{return null}}}return null}var B=Object.assign,X=0,E,P,q,U,_,ce,he;function Ue(){}Ue.__reactDisabledLog=!0;function Pe(){{if(X===0){E=console.log,P=console.info,q=console.warn,U=console.error,_=console.group,ce=console.groupCollapsed,he=console.groupEnd;var g={configurable:!0,enumerable:!0,value:Ue,writable:!0};Object.defineProperties(console,{info:g,log:g,warn:g,error:g,group:g,groupCollapsed:g,groupEnd:g})}X++}}function ie(){{if(X--,X===0){var g={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:B({},g,{value:E}),info:B({},g,{value:P}),warn:B({},g,{value:q}),error:B({},g,{value:U}),group:B({},g,{value:_}),groupCollapsed:B({},g,{value:ce}),groupEnd:B({},g,{value:he})})}X<0&&k("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var se=T.ReactCurrentDispatcher,ke;function Ae(g,M,G){{if(ke===void 0)try{throw Error()}catch(pe){var te=pe.stack.trim().match(/\n( *(at )?)/);ke=te&&te[1]||""}return`
2
+ `+ke+g}}var re=!1,Ee;{var Ie=typeof WeakMap=="function"?WeakMap:Map;Ee=new Ie}function Le(g,M){if(!g||re)return"";{var G=Ee.get(g);if(G!==void 0)return G}var te;re=!0;var pe=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var ge;ge=se.current,se.current=null,Pe();try{if(M){var ue=function(){throw Error()};if(Object.defineProperty(ue.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ue,[])}catch(Re){te=Re}Reflect.construct(g,[],ue)}else{try{ue.call()}catch(Re){te=Re}g.call(ue.prototype)}}else{try{throw Error()}catch(Re){te=Re}g()}}catch(Re){if(Re&&te&&typeof Re.stack=="string"){for(var le=Re.stack.split(`
3
+ `),We=te.stack.split(`
4
+ `),Te=le.length-1,Fe=We.length-1;Te>=1&&Fe>=0&&le[Te]!==We[Fe];)Fe--;for(;Te>=1&&Fe>=0;Te--,Fe--)if(le[Te]!==We[Fe]){if(Te!==1||Fe!==1)do if(Te--,Fe--,Fe<0||le[Te]!==We[Fe]){var at=`
5
+ `+le[Te].replace(" at new "," at ");return g.displayName&&at.includes("<anonymous>")&&(at=at.replace("<anonymous>",g.displayName)),typeof g=="function"&&Ee.set(g,at),at}while(Te>=1&&Fe>=0);break}}}finally{re=!1,se.current=ge,ie(),Error.prepareStackTrace=pe}var rn=g?g.displayName||g.name:"",Yt=rn?Ae(rn):"";return typeof g=="function"&&Ee.set(g,Yt),Yt}function Ge(g,M,G){return Le(g,!1)}function Oe(g){var M=g.prototype;return!!(M&&M.isReactComponent)}function ye(g,M,G){if(g==null)return"";if(typeof g=="function")return Le(g,Oe(g));if(typeof g=="string")return Ae(g);switch(g){case m:return Ae("Suspense");case d:return Ae("SuspenseList")}if(typeof g=="object")switch(g.$$typeof){case c:return Ge(g.render);case f:return ye(g.type,M,G);case p:{var te=g,pe=te._payload,ge=te._init;try{return ye(ge(pe),M,G)}catch{}}}return""}var ze=Object.prototype.hasOwnProperty,O={},Z=T.ReactDebugCurrentFrame;function ee(g){if(g){var M=g._owner,G=ye(g.type,g._source,M?M.type:null);Z.setExtraStackFrame(G)}else Z.setExtraStackFrame(null)}function Ce(g,M,G,te,pe){{var ge=Function.call.bind(ze);for(var ue in g)if(ge(g,ue)){var le=void 0;try{if(typeof g[ue]!="function"){var We=Error((te||"React class")+": "+G+" type `"+ue+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof g[ue]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw We.name="Invariant Violation",We}le=g[ue](M,ue,te,G,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(Te){le=Te}le&&!(le instanceof Error)&&(ee(pe),k("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",te||"React class",G,ue,typeof le),ee(null)),le instanceof Error&&!(le.message in O)&&(O[le.message]=!0,ee(pe),k("Failed %s type: %s",G,le.message),ee(null))}}}var xe=Array.isArray;function qe(g){return xe(g)}function W(g){{var M=typeof Symbol=="function"&&Symbol.toStringTag,G=M&&g[Symbol.toStringTag]||g.constructor.name||"Object";return G}}function me(g){try{return Ne(g),!1}catch{return!0}}function Ne(g){return""+g}function ve(g){if(me(g))return k("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",W(g)),Ne(g)}var rt=T.ReactCurrentOwner,Mt={key:!0,ref:!0,__self:!0,__source:!0},be,ft;function Nt(g){if(ze.call(g,"ref")){var M=Object.getOwnPropertyDescriptor(g,"ref").get;if(M&&M.isReactWarning)return!1}return g.ref!==void 0}function Ye(g){if(ze.call(g,"key")){var M=Object.getOwnPropertyDescriptor(g,"key").get;if(M&&M.isReactWarning)return!1}return g.key!==void 0}function Xe(g,M){typeof g.ref=="string"&&rt.current}function Qt(g,M){{var G=function(){be||(be=!0,k("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",M))};G.isReactWarning=!0,Object.defineProperty(g,"key",{get:G,configurable:!0})}}function kn(g,M){{var G=function(){ft||(ft=!0,k("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",M))};G.isReactWarning=!0,Object.defineProperty(g,"ref",{get:G,configurable:!0})}}var Sn=function(g,M,G,te,pe,ge,ue){var le={$$typeof:t,type:g,key:M,ref:G,props:ue,_owner:ge};return le._store={},Object.defineProperty(le._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(le,"_self",{configurable:!1,enumerable:!1,writable:!1,value:te}),Object.defineProperty(le,"_source",{configurable:!1,enumerable:!1,writable:!1,value:pe}),Object.freeze&&(Object.freeze(le.props),Object.freeze(le)),le};function Ht(g,M,G,te,pe){{var ge,ue={},le=null,We=null;G!==void 0&&(ve(G),le=""+G),Ye(M)&&(ve(M.key),le=""+M.key),Nt(M)&&(We=M.ref,Xe(M,pe));for(ge in M)ze.call(M,ge)&&!Mt.hasOwnProperty(ge)&&(ue[ge]=M[ge]);if(g&&g.defaultProps){var Te=g.defaultProps;for(ge in Te)ue[ge]===void 0&&(ue[ge]=Te[ge])}if(le||We){var Fe=typeof g=="function"?g.displayName||g.name||"Unknown":g;le&&Qt(ue,Fe),We&&kn(ue,Fe)}return Sn(g,le,We,pe,te,rt.current,ue)}}var pt=T.ReactCurrentOwner,It=T.ReactDebugCurrentFrame;function st(g){if(g){var M=g._owner,G=ye(g.type,g._source,M?M.type:null);It.setExtraStackFrame(G)}else It.setExtraStackFrame(null)}var Ut;Ut=!1;function Lt(g){return typeof g=="object"&&g!==null&&g.$$typeof===t}function z(){{if(pt.current){var g=D(pt.current.type);if(g)return`
6
6
 
7
- Check the render method of \``+f+"`."}return""}}function Tc(f){return""}var qs={};function Sc(f){{var F=As();if(!F){var A=typeof f=="string"?f:f.displayName||f.name;A&&(F=`
7
+ Check the render method of \``+g+"`."}return""}}function H(g){return""}var I={};function ne(g){{var M=z();if(!M){var G=typeof g=="string"?g:g.displayName||g.name;G&&(M=`
8
8
 
9
- Check the top-level render call using <`+A+">.")}return F}}function Vs(f,F){{if(!f._store||f._store.validated||f.key!=null)return;f._store.validated=!0;var A=Sc(F);if(qs[A])return;qs[A]=!0;var Y="";f&&f._owner&&f._owner!==Kn.current&&(Y=" It was passed a child from "+O(f._owner.type)+"."),Nt(f),w('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',A,Y),Nt(null)}}function Bs(f,F){{if(typeof f!="object")return;if(Je(f))for(var A=0;A<f.length;A++){var Y=f[A];Jn(Y)&&Vs(Y,F)}else if(Jn(f))f._store&&(f._store.validated=!0);else if(f){var ne=k(f);if(typeof ne=="function"&&ne!==f.entries)for(var oe=ne.call(f),te;!(te=oe.next()).done;)Jn(te.value)&&Vs(te.value,F)}}}function $c(f){{var F=f.type;if(F==null||typeof F=="string")return;var A;if(typeof F=="function")A=F.propTypes;else if(typeof F=="object"&&(F.$$typeof===u||F.$$typeof===m))A=F.propTypes;else return;if(A){var Y=O(F);$e(A,f.props,"prop",Y,f)}else if(F.PropTypes!==void 0&&!Gn){Gn=!0;var ne=O(F);w("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",ne||"Unknown")}typeof F.getDefaultProps=="function"&&!F.getDefaultProps.isReactClassApproved&&w("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function _c(f){{for(var F=Object.keys(f.props),A=0;A<F.length;A++){var Y=F[A];if(Y!=="children"&&Y!=="key"){Nt(f),w("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",Y),Nt(null);break}}f.ref!==null&&(Nt(f),w("Invalid attribute `ref` supplied to `React.Fragment`."),Nt(null))}}var Ks={};function Gs(f,F,A,Y,ne,oe){{var te=L(f);if(!te){var ee="";(f===void 0||typeof f=="object"&&f!==null&&Object.keys(f).length===0)&&(ee+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var we=Tc();we?ee+=we:ee+=As();var fe;f===null?fe="null":Je(f)?fe="array":f!==void 0&&f.$$typeof===n?(fe="<"+(O(f.type)||"Unknown")+" />",ee=" Did you accidentally export a JSX literal instead of a component?"):fe=typeof f,w("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",fe,ee)}var pe=kc(f,F,A,ne,oe);if(pe==null)return pe;if(te){var Me=F.children;if(Me!==void 0)if(Y)if(Je(Me)){for(var wt=0;wt<Me.length;wt++)Bs(Me[wt],f);Object.freeze&&Object.freeze(Me)}else w("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Bs(Me,f)}if(ue.call(F,"key")){var ft=O(f),_e=Object.keys(F).filter(function(Mc){return Mc!=="key"}),Wn=_e.length>0?"{key: someKey, "+_e.join(": ..., ")+": ...}":"{key: someKey}";if(!Ks[ft+Wn]){var Dc=_e.length>0?"{"+_e.join(": ..., ")+": ...}":"{}";w(`A props object containing a "key" prop is being spread into JSX:
9
+ Check the top-level render call using <`+G+">.")}return M}}function Se(g,M){{if(!g._store||g._store.validated||g.key!=null)return;g._store.validated=!0;var G=ne(M);if(I[G])return;I[G]=!0;var te="";g&&g._owner&&g._owner!==pt.current&&(te=" It was passed a child from "+D(g._owner.type)+"."),st(g),k('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',G,te),st(null)}}function De(g,M){{if(typeof g!="object")return;if(qe(g))for(var G=0;G<g.length;G++){var te=g[G];Lt(te)&&Se(te,M)}else if(Lt(g))g._store&&(g._store.validated=!0);else if(g){var pe=N(g);if(typeof pe=="function"&&pe!==g.entries)for(var ge=pe.call(g),ue;!(ue=ge.next()).done;)Lt(ue.value)&&Se(ue.value,M)}}}function ot(g){{var M=g.type;if(M==null||typeof M=="string")return;var G;if(typeof M=="function")G=M.propTypes;else if(typeof M=="object"&&(M.$$typeof===c||M.$$typeof===f))G=M.propTypes;else return;if(G){var te=D(M);Ce(G,g.props,"prop",te,g)}else if(M.PropTypes!==void 0&&!Ut){Ut=!0;var pe=D(M);k("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",pe||"Unknown")}typeof M.getDefaultProps=="function"&&!M.getDefaultProps.isReactClassApproved&&k("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function ht(g){{for(var M=Object.keys(g.props),G=0;G<M.length;G++){var te=M[G];if(te!=="children"&&te!=="key"){st(g),k("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",te),st(null);break}}g.ref!==null&&(st(g),k("Invalid attribute `ref` supplied to `React.Fragment`."),st(null))}}var Ke={};function kt(g,M,G,te,pe,ge){{var ue=S(g);if(!ue){var le="";(g===void 0||typeof g=="object"&&g!==null&&Object.keys(g).length===0)&&(le+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var We=H();We?le+=We:le+=z();var Te;g===null?Te="null":qe(g)?Te="array":g!==void 0&&g.$$typeof===t?(Te="<"+(D(g.type)||"Unknown")+" />",le=" Did you accidentally export a JSX literal instead of a component?"):Te=typeof g,k("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",Te,le)}var Fe=Ht(g,M,G,pe,ge);if(Fe==null)return Fe;if(ue){var at=M.children;if(at!==void 0)if(te)if(qe(at)){for(var rn=0;rn<at.length;rn++)De(at[rn],g);Object.freeze&&Object.freeze(at)}else k("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else De(at,g)}if(ze.call(M,"key")){var Yt=D(g),Re=Object.keys(M).filter(function(wm){return wm!=="key"}),is=Re.length>0?"{key: someKey, "+Re.join(": ..., ")+": ...}":"{key: someKey}";if(!Ke[Yt+is]){var jm=Re.length>0?"{"+Re.join(": ..., ")+": ...}":"{}";k(`A props object containing a "key" prop is being spread into JSX:
10
10
  let props = %s;
11
11
  <%s {...props} />
12
12
  React keys must be passed directly to JSX without using spread:
13
13
  let props = %s;
14
- <%s key={someKey} {...props} />`,Wn,ft,Dc,ft),Ks[ft+Wn]=!0}}return f===s?_c(pe):$c(pe),pe}}function Fc(f,F,A){return Gs(f,F,A,!0)}function zc(f,F,A){return Gs(f,F,A,!1)}var Ec=zc,Pc=Fc;kt.Fragment=s,kt.jsx=Ec,kt.jsxs=Pc})()),kt}var Yn;function Ys(){return Yn||(Yn=1,process.env.NODE_ENV==="production"?Gt.exports=Hs():Gt.exports=Qs()),Gt.exports}var t=Ys();const Rn={path:"/",history:[],location:0},Xn={path:"*",data:{},hash:"",query:""},Jt=c.createContext(Rn),un=c.createContext(null),Tt=c.createContext(Xn),Un=e=>({type:"NAVIGATE",payload:e}),Rs=(e=1)=>({type:"BACK",payload:e}),Xs=(e=1)=>({type:"FORWARD",payload:e}),Us=100;function Zs(e,n){switch(n.type){case"NAVIGATE":{let{history:r,location:s}=e;return s>0&&(r=r.slice(s)),{path:ro(e.path,n.payload),history:[n.payload,...r].slice(0,Us),location:0}}case"BACK":{const r=e.location+n.payload,s=e.history.at(r);return s?{path:s,history:e.history,location:r}:e}case"FORWARD":{const r=e.location-n.payload,s=e.history.at(r);return s?{path:s,history:e.history,location:r}:e}default:return e}}function Zn(){return c.useContext(Jt).path}function Wt(){const e=c.useContext(un);return n=>e?.(Un(n))}function eo(){const e=c.useContext(un),n=c.useContext(Jt);return{navigate:r=>e?.(Un(r)),back:(r=1)=>e?.(Rs(r)),forward:(r=1)=>e?.(Xs(r)),hasBack:n.location<n.history.length-1,...n}}function mn(){return c.useContext(Tt).data}function er(){const{query:e,hash:n}=c.useContext(Tt);return{search:new URLSearchParams(e),hash:n}}function to({path:e,children:n}){const r=e?{path:e,history:[],location:0}:Rn,[s,o]=c.useReducer(Zs,r);return t.jsx(Jt.Provider,{value:s,children:t.jsx(un.Provider,{value:o,children:t.jsx(Tt.Provider,{value:Xn,children:n})})})}const St=c.forwardRef(({to:e,children:n,...r},s)=>{const o=Wt(),i=a=>{a.defaultPrevented||a.preventDefault(),o(e)};return t.jsx("a",{...r,href:e,ref:s,onClick:i,children:n})});function fn({children:e}){const n=c.useContext(Tt),r=c.useContext(Jt),s=nr(e,n.path),o=no(s.map(a=>a.route),r.path);if(!o)return t.jsx(t.Fragment,{});const i=s.find(a=>a.route===o.route).element;return t.jsx(Tt.Provider,{value:{...o.match},children:i})}function tr(e){let n=0;for(const r of e.split("/"))r===""||r==="*"||(n+=r.startsWith(":")?1:100);return n}function no(e,n){let r=null;for(const s of e){const o=ao(s,n);o.isMatch&&(r===null||tr(s)>tr(r.route))&&(r={route:s,match:o})}return r}function je({path:e,element:n}){return t.jsx(t.Fragment,{})}function nr(e,n){const r=[];return c.Children.map(e,s=>{if(!c.isValidElement(s))return;if(s.type===c.Fragment){r.push.apply(r,nr(s.props.children,n));return}const o=s.props;return r.push({route:oo(n,o.path),element:o.element}),s}),r}const ro=(e,n)=>{if(n.startsWith("/"))return n;if(n.startsWith("?")){const[o]=e?.split("?")??[""];return o+n}let r=0;const s=n.split("/").filter(o=>o!=="");for(;s.length>0&&(s[0]==="."||s[0]==="..");)s.shift()==".."&&++r;return so(e,s.join("/"),r)},so=(e,n,r)=>{const s=e.split("/").filter(i=>i!==""),o=n.split("/").filter(i=>i!=="");return r===0?`/${s.join("/")}/${o.join("/")}`:`/${s.slice(0,-r).join("/")}/${o.join("/")}`},oo=(e,n)=>{const r=e.split("/").filter(o=>o!==""),s=n.split("/").filter(o=>o!=="");return r.length>0&&r.at(-1)==="*"&&r.pop(),r.length===0?`/${s.join("/")}`:`/${r.join("/")}/${s.join("/")}`},ao=(e,n)=>{let r=e.split("/"),s=n.split("/");if(r.at(-1)===""&&(r=r.slice(0,-1)),s.at(-1)===""&&(s=s.slice(0,-1)),r.length>s.length)return{isMatch:!1,remainer:"",data:{},query:"",hash:"",path:""};if(r.length<s.length&&r.at(-1)!=="*")return{isMatch:!1,remainer:"",data:{},query:"",hash:"",path:""};let o={},i="",a="";for(let l=0;l<r.length;++l){const u=r[l],p=[...s[l].matchAll(/([?#]?)((?:(?![?#]).)*)/g)],m=p?.find(h=>h[1]==="")?.[2]??"";if(i=p?.find(h=>h[1]==="?")?.[2]??"",a=p?.find(h=>h[1]==="#")?.[2]??"",u.startsWith(":")&&m&&m!==""){o[u.substring(1)]=m;continue}if(u==="*"){const x=[...s.slice(l).join("/").matchAll(/([?#]?)((?:(?![?#]).)*)/g)];return{isMatch:!0,data:o,remainer:x.find(g=>g[1]==="")?.[2]??"",query:x.find(g=>g[1]==="?")?.[2]??"",hash:x.find(g=>g[1]==="#")?.[2]??"",path:s.slice(0,l).join("/")}}if(u!==m)return{isMatch:!1,data:{},remainer:"",query:"",hash:"",path:""}}return{isMatch:!0,remainer:"",data:o,query:i,hash:a,path:n?.split("?")?.[0]??""}},io=`
14
+ <%s key={someKey} {...props} />`,is,Yt,jm,Yt),Ke[Yt+is]=!0}}return g===s?ht(Fe):ot(Fe),Fe}}function gt(g,M,G){return kt(g,M,G,!0)}function nn(g,M,G){return kt(g,M,G,!1)}var Me=nn,as=gt;on.Fragment=s,on.jsx=Me,on.jsxs=as})()),on}var us;function Ea(){return us||(us=1,process.env.NODE_ENV==="production"?En.exports=Ta():En.exports=$a()),En.exports}var n=Ea();const ds={path:"/",history:[],location:0},ms={path:"*",data:{},hash:"",query:""},Fn=u.createContext(ds),ar=u.createContext(null),an=u.createContext(ms),fs=e=>({type:"NAVIGATE",payload:e}),Fa=(e=1)=>({type:"BACK",payload:e}),_a=(e=1)=>({type:"FORWARD",payload:e}),Pa=100;function za(e,t){switch(t.type){case"NAVIGATE":{let{history:r,location:s}=e;return s>0&&(r=r.slice(s)),{path:La(e.path,t.payload),history:[t.payload,...r].slice(0,Pa),location:0}}case"BACK":{const r=e.location+t.payload,s=e.history.at(r);return s?{path:s,history:e.history,location:r}:e}case"FORWARD":{const r=e.location-t.payload,s=e.history.at(r);return s?{path:s,history:e.history,location:r}:e}default:return e}}function ps(){return u.useContext(Fn).path}function _n(){const e=u.useContext(ar);return u.useCallback(t=>e?.(fs(t)),[e])}function Da(){const e=u.useContext(ar),t=u.useContext(Fn);return u.useMemo(()=>({navigate:r=>e?.(fs(r)),back:(r=1)=>e?.(Fa(r)),forward:(r=1)=>e?.(_a(r)),hasBack:t.location<t.history.length-1,...t}),[e,t])}function ir(){return u.useContext(an).data}function hs(){const{query:e,hash:t}=u.useContext(an);return u.useMemo(()=>({search:new URLSearchParams(e),hash:t}),[e,t])}function Ma({path:e,children:t}){const r=e?{path:e,history:[],location:0}:ds,[s,o]=u.useReducer(za,r);return n.jsx(Fn.Provider,{value:s,children:n.jsx(ar.Provider,{value:o,children:n.jsx(an.Provider,{value:ms,children:t})})})}const Pn=u.forwardRef(({to:e,children:t,...r},s)=>{const o=_n(),i=a=>{a.defaultPrevented||a.preventDefault(),o(e)};return n.jsx("a",{...r,href:e,ref:s,onClick:i,children:t})});function lr({children:e}){const t=u.useContext(an),r=u.useContext(Fn),s=xs(e,t.path),o=Ia(s.map(a=>a.route),r.path);if(!o)return n.jsx(n.Fragment,{});const i=s.find(a=>a.route===o.route).element;return n.jsx(an.Provider,{value:{...o.match},children:i})}function gs(e){let t=0;for(const r of e.split("/"))r===""||r==="*"||(t+=r.startsWith(":")?1:100);return t}function Ia(e,t){let r=null;for(const s of e){const o=qa(s,t);o.isMatch&&(r===null||gs(s)>gs(r.route))&&(r={route:s,match:o})}return r}function Be({path:e,element:t}){return n.jsx(n.Fragment,{})}function xs(e,t){const r=[];return u.Children.map(e,s=>{if(!u.isValidElement(s))return;if(s.type===u.Fragment){r.push.apply(r,xs(s.props.children,t));return}const o=s.props;return r.push({route:Aa(t,o.path),element:o.element}),s}),r}const La=(e,t)=>{if(t.startsWith("/"))return t;if(t.startsWith("?")){const[o]=e?.split("?")??[""];return o+t}let r=0;const s=t.split("/").filter(o=>o!=="");for(;s.length>0&&(s[0]==="."||s[0]==="..");)s.shift()==".."&&++r;return Oa(e,s.join("/"),r)},Oa=(e,t,r)=>{const s=e.split("/").filter(a=>a!==""),o=t.split("/").filter(a=>a!=="");return`/${[...s.slice(0,Math.max(0,s.length-r)),...o].join("/")}`},Aa=(e,t)=>{const r=e.split("/").filter(o=>o!==""),s=t.split("/").filter(o=>o!=="");return r.length>0&&r.at(-1)==="*"&&r.pop(),r.length===0?`/${s.join("/")}`:`/${r.join("/")}/${s.join("/")}`},qa=(e,t)=>{let r=e.split("/"),s=t.split("/");if(r.at(-1)===""&&(r=r.slice(0,-1)),s.at(-1)===""&&(s=s.slice(0,-1)),r.length>s.length)return{isMatch:!1,remainer:"",data:{},query:"",hash:"",path:""};if(r.length<s.length&&r.at(-1)!=="*")return{isMatch:!1,remainer:"",data:{},query:"",hash:"",path:""};let o={},i="",a="";for(let l=0;l<r.length;++l){const c=r[l],d=[...s[l].matchAll(/([?#]?)((?:(?![?#]).)*)/g)],f=d?.find(p=>p[1]==="")?.[2]??"";if(i=d?.find(p=>p[1]==="?")?.[2]??"",a=d?.find(p=>p[1]==="#")?.[2]??"",c.startsWith(":")&&f&&f!==""){o[c.substring(1)]=f;continue}if(c==="*"){const x=[...s.slice(l).join("/").matchAll(/([?#]?)((?:(?![?#]).)*)/g)];return{isMatch:!0,data:o,remainer:x.find(h=>h[1]==="")?.[2]??"",query:x.find(h=>h[1]==="?")?.[2]??"",hash:x.find(h=>h[1]==="#")?.[2]??"",path:s.slice(0,l).join("/")}}if(c!==f)return{isMatch:!1,data:{},remainer:"",query:"",hash:"",path:""}}return{isMatch:!0,remainer:"",data:o,query:i,hash:a,path:t?.split("?")?.[0]??""}},Va=`
15
15
  query dbSchema {
16
16
  _dbSchema {
17
17
  dbName
@@ -32,11 +32,14 @@ query dbSchema {
32
32
  isIdentity
33
33
  isNullable
34
34
  isReadOnly
35
+ isLargeValue
35
36
  maxLength
36
37
  minLength
37
38
  min
38
39
  max
39
40
  step
41
+ precision
42
+ scale
40
43
  pattern
41
44
  patternMessage
42
45
  inputType
@@ -73,36 +76,47 @@ query dbSchema {
73
76
  targetColumnNames
74
77
  hasPayload
75
78
  }
79
+ indexes {
80
+ name
81
+ isUnique
82
+ isClustered
83
+ isPrimaryKey
84
+ columns
85
+ }
76
86
  }
77
- }`;class lo extends Error{constructor(n,r){super(n.map(s=>s.message).join("; ")),this.errors=n,this.data=r,this.name="GraphQLRequestError"}errors;data}class rr{constructor(n){this.uri=n}uri;async query(n,r,s){const o=await fetch(this.uri,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:n,variables:r}),signal:s?.signal});if(!o.ok)throw new Error(`GraphQL request failed: ${o.status} ${o.statusText}`);const i=await o.json();if(i.errors?.length)throw new lo(i.errors,i.data);return i.data}}const sr=c.createContext(null),co=sr.Provider;function Ce(){const e=c.useContext(sr);if(!e)throw new Error("useFetcher must be used within a FetcherProvider");return e}function uo(e){const n=e.lastIndexOf(".");return n>=0?e.slice(n+1):e}function mo(e){return uo(e).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[_\-\s]+/).filter(Boolean)}function fo(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}function Ht(e){return e&&mo(e).map(fo).join(" ")}const or=c.createContext({loading:!0,error:null,data:[],findTable:()=>{}}),po=({children:e})=>{const n=ho();return t.jsx(or.Provider,{value:n,children:e})};function Pe(){return c.useContext(or)}function ho(){const e=Ce(),{isLoading:n,error:r,data:s}=me.useQuery({queryKey:["dbSchema"],queryFn:()=>e.query(io),staleTime:1/0});return c.useMemo(()=>{if(n)return{loading:!0,error:null,data:[],findTable:()=>{}};if(r)return{loading:!1,error:{message:r.message},data:[],findTable:()=>{}};if(!s)return{loading:!1,error:null,data:[],findTable:()=>{}};const o=s._dbSchema.map(a=>({...a,name:a.graphQlName,label:Ht(a.dbName),metadata:ar(a.metadata),columns:a.columns.map(l=>({...l,name:l.graphQlName,label:Ht(l.dbName),metadata:ar(l.metadata),inputType:yo(l.inputType)}))}));return{loading:!1,error:null,data:o,findTable:a=>o.find(l=>l.graphQlName===a)}},[n,r,s])}function ar(e){return e.reduce((n,r)=>({...n,[r.key]:xo(r)}),{})}function xo({key:e,value:n}){return e==="type"?go(n):n}function go(e){const n=e.match(/lookup\s*\(\s*(?<id>\w+)\s*,\s*(?<label>\w+)\s*\)/m);if(n?.groups?.id&&n?.groups?.label)return{type:"lookup",id:n.groups.id,label:n.groups.label}}const bo=["text","email","url","tel","date","datetime-local","number","password","search"];function yo(e){if(e&&bo.includes(e))return e}function ir(e){var n,r,s="";if(typeof e=="string"||typeof e=="number")s+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(n=0;n<o;n++)e[n]&&(r=ir(e[n]))&&(s&&(s+=" "),s+=r)}else for(r in e)e[r]&&(s&&(s+=" "),s+=r);return s}function lr(){for(var e,n,r=0,s="",o=arguments.length;r<o;r++)(e=arguments[r])&&(n=ir(e))&&(s&&(s+=" "),s+=n);return s}const cr=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,dr=lr,ur=(e,n)=>r=>{var s;if(n?.variants==null)return dr(e,r?.class,r?.className);const{variants:o,defaultVariants:i}=n,a=Object.keys(o).map(d=>{const p=r?.[d],m=i?.[d];if(p===null)return null;const h=cr(p)||cr(m);return o[d][h]}),l=r&&Object.entries(r).reduce((d,p)=>{let[m,h]=p;return h===void 0||(d[m]=h),d},{}),u=n==null||(s=n.compoundVariants)===null||s===void 0?void 0:s.reduce((d,p)=>{let{class:m,className:h,...x}=p;return Object.entries(x).every(g=>{let[b,k]=g;return Array.isArray(k)?k.includes({...i,...l}[b]):{...i,...l}[b]===k})?[...d,m,h]:d},[]);return dr(e,a,u,r?.class,r?.className)},vo=(e,n)=>{const r=new Array(e.length+n.length);for(let s=0;s<e.length;s++)r[s]=e[s];for(let s=0;s<n.length;s++)r[e.length+s]=n[s];return r},jo=(e,n)=>({classGroupId:e,validator:n}),mr=(e=new Map,n=null,r)=>({nextPart:e,validators:n,classGroupId:r}),Qt="-",fr=[],No="arbitrary..",wo=e=>{const n=ko(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:a=>{if(a.startsWith("[")&&a.endsWith("]"))return Co(a);const l=a.split(Qt),u=l[0]===""&&l.length>1?1:0;return pr(l,u,n)},getConflictingClassGroupIds:(a,l)=>{if(l){const u=s[a],d=r[a];return u?d?vo(d,u):u:d||fr}return r[a]||fr}}},pr=(e,n,r)=>{if(e.length-n===0)return r.classGroupId;const o=e[n],i=r.nextPart.get(o);if(i){const d=pr(e,n+1,i);if(d)return d}const a=r.validators;if(a===null)return;const l=n===0?e.join(Qt):e.slice(n).join(Qt),u=a.length;for(let d=0;d<u;d++){const p=a[d];if(p.validator(l))return p.classGroupId}},Co=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const n=e.slice(1,-1),r=n.indexOf(":"),s=n.slice(0,r);return s?No+s:void 0})(),ko=e=>{const{theme:n,classGroups:r}=e;return To(r,n)},To=(e,n)=>{const r=mr();for(const s in e){const o=e[s];pn(o,r,s,n)}return r},pn=(e,n,r,s)=>{const o=e.length;for(let i=0;i<o;i++){const a=e[i];So(a,n,r,s)}},So=(e,n,r,s)=>{if(typeof e=="string"){$o(e,n,r);return}if(typeof e=="function"){_o(e,n,r,s);return}Fo(e,n,r,s)},$o=(e,n,r)=>{const s=e===""?n:hr(n,e);s.classGroupId=r},_o=(e,n,r,s)=>{if(zo(e)){pn(e(s),n,r,s);return}n.validators===null&&(n.validators=[]),n.validators.push(jo(r,e))},Fo=(e,n,r,s)=>{const o=Object.entries(e),i=o.length;for(let a=0;a<i;a++){const[l,u]=o[a];pn(u,hr(n,l),r,s)}},hr=(e,n)=>{let r=e;const s=n.split(Qt),o=s.length;for(let i=0;i<o;i++){const a=s[i];let l=r.nextPart.get(a);l||(l=mr(),r.nextPart.set(a,l)),r=l}return r},zo=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,Eo=e=>{if(e<1)return{get:()=>{},set:()=>{}};let n=0,r=Object.create(null),s=Object.create(null);const o=(i,a)=>{r[i]=a,n++,n>e&&(n=0,s=r,r=Object.create(null))};return{get(i){let a=r[i];if(a!==void 0)return a;if((a=s[i])!==void 0)return o(i,a),a},set(i,a){i in r?r[i]=a:o(i,a)}}},hn="!",xr=":",Po=[],gr=(e,n,r,s,o)=>({modifiers:e,hasImportantModifier:n,baseClassName:r,maybePostfixModifierPosition:s,isExternal:o}),Do=e=>{const{prefix:n,experimentalParseClassName:r}=e;let s=o=>{const i=[];let a=0,l=0,u=0,d;const p=o.length;for(let b=0;b<p;b++){const k=o[b];if(a===0&&l===0){if(k===xr){i.push(o.slice(u,b)),u=b+1;continue}if(k==="/"){d=b;continue}}k==="["?a++:k==="]"?a--:k==="("?l++:k===")"&&l--}const m=i.length===0?o:o.slice(u);let h=m,x=!1;m.endsWith(hn)?(h=m.slice(0,-1),x=!0):m.startsWith(hn)&&(h=m.slice(1),x=!0);const g=d&&d>u?d-u:void 0;return gr(i,x,h,g)};if(n){const o=n+xr,i=s;s=a=>a.startsWith(o)?i(a.slice(o.length)):gr(Po,!1,a,void 0,!0)}if(r){const o=s;s=i=>r({className:i,parseClassName:o})}return s},Mo=e=>{const n=new Map;return e.orderSensitiveModifiers.forEach((r,s)=>{n.set(r,1e6+s)}),r=>{const s=[];let o=[];for(let i=0;i<r.length;i++){const a=r[i],l=a[0]==="[",u=n.has(a);l||u?(o.length>0&&(o.sort(),s.push(...o),o=[]),s.push(a)):o.push(a)}return o.length>0&&(o.sort(),s.push(...o)),s}},Io=e=>({cache:Eo(e.cacheSize),parseClassName:Do(e),sortModifiers:Mo(e),postfixLookupClassGroupIds:Lo(e),...wo(e)}),Lo=e=>{const n=Object.create(null),r=e.postfixLookupClassGroups;if(r)for(let s=0;s<r.length;s++)n[r[s]]=!0;return n},Oo=/\s+/,Ao=(e,n)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:o,sortModifiers:i,postfixLookupClassGroupIds:a}=n,l=[],u=e.trim().split(Oo);let d="";for(let p=u.length-1;p>=0;p-=1){const m=u[p],{isExternal:h,modifiers:x,hasImportantModifier:g,baseClassName:b,maybePostfixModifierPosition:k}=r(m);if(h){d=m+(d.length>0?" "+d:d);continue}let $=!!k,w;if($){const E=b.substring(0,k);w=s(E);const y=w&&a[w]?s(b):void 0;y&&y!==w&&(w=y,$=!1)}else w=s(b);if(!w){if(!$){d=m+(d.length>0?" "+d:d);continue}if(w=s(b),!w){d=m+(d.length>0?" "+d:d);continue}$=!1}const P=x.length===0?"":x.length===1?x[0]:i(x).join(":"),C=g?P+hn:P,T=C+w;if(l.indexOf(T)>-1)continue;l.push(T);const j=o(w,$);for(let E=0;E<j.length;++E){const y=j[E];l.push(C+y)}d=m+(d.length>0?" "+d:d)}return d},qo=(...e)=>{let n=0,r,s,o="";for(;n<e.length;)(r=e[n++])&&(s=br(r))&&(o&&(o+=" "),o+=s);return o},br=e=>{if(typeof e=="string")return e;let n,r="";for(let s=0;s<e.length;s++)e[s]&&(n=br(e[s]))&&(r&&(r+=" "),r+=n);return r},Vo=(e,...n)=>{let r,s,o,i;const a=u=>{const d=n.reduce((p,m)=>m(p),e());return r=Io(d),s=r.cache.get,o=r.cache.set,i=l,l(u)},l=u=>{const d=s(u);if(d)return d;const p=Ao(u,r);return o(u,p),p};return i=a,(...u)=>i(qo(...u))},Bo=[],he=e=>{const n=r=>r[e]||Bo;return n.isThemeGetter=!0,n},yr=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,vr=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Ko=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,Go=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Jo=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Wo=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Ho=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Qo=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ye=e=>Ko.test(e),Z=e=>!!e&&!Number.isNaN(Number(e)),Ve=e=>!!e&&Number.isInteger(Number(e)),xn=e=>e.endsWith("%")&&Z(e.slice(0,-1)),He=e=>Go.test(e),jr=()=>!0,Yo=e=>Jo.test(e)&&!Wo.test(e),gn=()=>!1,Ro=e=>Ho.test(e),Xo=e=>Qo.test(e),Uo=e=>!q(e)&&!V(e),Zo=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),ea=e=>Re(e,Sr,gn),q=e=>yr.test(e),ot=e=>Re(e,$r,Yo),Nr=e=>Re(e,la,Z),ta=e=>Re(e,Fr,jr),na=e=>Re(e,_r,gn),wr=e=>Re(e,kr,gn),ra=e=>Re(e,Tr,Xo),Yt=e=>Re(e,zr,Ro),V=e=>vr.test(e),$t=e=>at(e,$r),sa=e=>at(e,_r),Cr=e=>at(e,kr),oa=e=>at(e,Sr),aa=e=>at(e,Tr),Rt=e=>at(e,zr,!0),ia=e=>at(e,Fr,!0),Re=(e,n,r)=>{const s=yr.exec(e);return s?s[1]?n(s[1]):r(s[2]):!1},at=(e,n,r=!1)=>{const s=vr.exec(e);return s?s[1]?n(s[1]):r:!1},kr=e=>e==="position"||e==="percentage",Tr=e=>e==="image"||e==="url",Sr=e=>e==="length"||e==="size"||e==="bg-size",$r=e=>e==="length",la=e=>e==="number",_r=e=>e==="family-name",Fr=e=>e==="number"||e==="weight",zr=e=>e==="shadow",ca=Vo(()=>{const e=he("color"),n=he("font"),r=he("text"),s=he("font-weight"),o=he("tracking"),i=he("leading"),a=he("breakpoint"),l=he("container"),u=he("spacing"),d=he("radius"),p=he("shadow"),m=he("inset-shadow"),h=he("text-shadow"),x=he("drop-shadow"),g=he("blur"),b=he("perspective"),k=he("aspect"),$=he("ease"),w=he("animate"),P=()=>["auto","avoid","all","avoid-page","page","left","right","column"],C=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],T=()=>[...C(),V,q],j=()=>["auto","hidden","clip","visible","scroll"],E=()=>["auto","contain","none"],y=()=>[V,q,u],S=()=>[Ye,"full","auto",...y()],L=()=>[Ve,"none","subgrid",V,q],v=()=>["auto",{span:["full",Ve,V,q]},Ve,V,q],M=()=>[Ve,"auto",V,q],O=()=>["auto","min","max","fr",V,q],z=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],I=()=>["start","end","center","stretch","center-safe","end-safe"],_=()=>["auto",...y()],G=()=>[Ye,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...y()],U=()=>[Ye,"screen","full","dvw","lvw","svw","min","max","fit",...y()],ie=()=>[Ye,"screen","full","lh","dvh","lvh","svh","min","max","fit",...y()],B=()=>[e,V,q],Te=()=>[...C(),Cr,wr,{position:[V,q]}],ye=()=>["no-repeat",{repeat:["","x","y","space","round"]}],xe=()=>["auto","cover","contain",oa,ea,{size:[V,q]}],le=()=>[xn,$t,ot],re=()=>["","none","full",d,V,q],ae=()=>["",Z,$t,ot],J=()=>["solid","dashed","dotted","double"],ce=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],R=()=>[Z,xn,Cr,wr],Ne=()=>["","none",g,V,q],Be=()=>["none",Z,V,q],ze=()=>["none",Z,V,q],Ke=()=>[Z,V,q],De=()=>[Ye,"full",...y()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[He],breakpoint:[He],color:[jr],container:[He],"drop-shadow":[He],ease:["in","out","in-out"],font:[Uo],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[He],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[He],shadow:[He],spacing:["px",Z],text:[He],"text-shadow":[He],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ye,q,V,k]}],container:["container"],"container-type":[{"@container":["","normal","size",V,q]}],"container-named":[Zo],columns:[{columns:[Z,q,V,l]}],"break-after":[{"break-after":P()}],"break-before":[{"break-before":P()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:T()}],overflow:[{overflow:j()}],"overflow-x":[{"overflow-x":j()}],"overflow-y":[{"overflow-y":j()}],overscroll:[{overscroll:E()}],"overscroll-x":[{"overscroll-x":E()}],"overscroll-y":[{"overscroll-y":E()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:S()}],"inset-x":[{"inset-x":S()}],"inset-y":[{"inset-y":S()}],start:[{"inset-s":S(),start:S()}],end:[{"inset-e":S(),end:S()}],"inset-bs":[{"inset-bs":S()}],"inset-be":[{"inset-be":S()}],top:[{top:S()}],right:[{right:S()}],bottom:[{bottom:S()}],left:[{left:S()}],visibility:["visible","invisible","collapse"],z:[{z:[Ve,"auto",V,q]}],basis:[{basis:[Ye,"full","auto",l,...y()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Z,Ye,"auto","initial","none",q]}],grow:[{grow:["",Z,V,q]}],shrink:[{shrink:["",Z,V,q]}],order:[{order:[Ve,"first","last","none",V,q]}],"grid-cols":[{"grid-cols":L()}],"col-start-end":[{col:v()}],"col-start":[{"col-start":M()}],"col-end":[{"col-end":M()}],"grid-rows":[{"grid-rows":L()}],"row-start-end":[{row:v()}],"row-start":[{"row-start":M()}],"row-end":[{"row-end":M()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":O()}],"auto-rows":[{"auto-rows":O()}],gap:[{gap:y()}],"gap-x":[{"gap-x":y()}],"gap-y":[{"gap-y":y()}],"justify-content":[{justify:[...z(),"normal"]}],"justify-items":[{"justify-items":[...I(),"normal"]}],"justify-self":[{"justify-self":["auto",...I()]}],"align-content":[{content:["normal",...z()]}],"align-items":[{items:[...I(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...I(),{baseline:["","last"]}]}],"place-content":[{"place-content":z()}],"place-items":[{"place-items":[...I(),"baseline"]}],"place-self":[{"place-self":["auto",...I()]}],p:[{p:y()}],px:[{px:y()}],py:[{py:y()}],ps:[{ps:y()}],pe:[{pe:y()}],pbs:[{pbs:y()}],pbe:[{pbe:y()}],pt:[{pt:y()}],pr:[{pr:y()}],pb:[{pb:y()}],pl:[{pl:y()}],m:[{m:_()}],mx:[{mx:_()}],my:[{my:_()}],ms:[{ms:_()}],me:[{me:_()}],mbs:[{mbs:_()}],mbe:[{mbe:_()}],mt:[{mt:_()}],mr:[{mr:_()}],mb:[{mb:_()}],ml:[{ml:_()}],"space-x":[{"space-x":y()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":y()}],"space-y-reverse":["space-y-reverse"],size:[{size:G()}],"inline-size":[{inline:["auto",...U()]}],"min-inline-size":[{"min-inline":["auto",...U()]}],"max-inline-size":[{"max-inline":["none",...U()]}],"block-size":[{block:["auto",...ie()]}],"min-block-size":[{"min-block":["auto",...ie()]}],"max-block-size":[{"max-block":["none",...ie()]}],w:[{w:[l,"screen",...G()]}],"min-w":[{"min-w":[l,"screen","none",...G()]}],"max-w":[{"max-w":[l,"screen","none","prose",{screen:[a]},...G()]}],h:[{h:["screen","lh",...G()]}],"min-h":[{"min-h":["screen","lh","none",...G()]}],"max-h":[{"max-h":["screen","lh",...G()]}],"font-size":[{text:["base",r,$t,ot]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,ia,ta]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",xn,q]}],"font-family":[{font:[sa,na,n]}],"font-features":[{"font-features":[q]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,V,q]}],"line-clamp":[{"line-clamp":[Z,"none",V,Nr]}],leading:[{leading:[i,...y()]}],"list-image":[{"list-image":["none",V,q]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",V,q]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:B()}],"text-color":[{text:B()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...J(),"wavy"]}],"text-decoration-thickness":[{decoration:[Z,"from-font","auto",V,ot]}],"text-decoration-color":[{decoration:B()}],"underline-offset":[{"underline-offset":[Z,"auto",V,q]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:y()}],"tab-size":[{tab:[Ve,V,q]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",V,q]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",V,q]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:Te()}],"bg-repeat":[{bg:ye()}],"bg-size":[{bg:xe()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ve,V,q],radial:["",V,q],conic:[Ve,V,q]},aa,ra]}],"bg-color":[{bg:B()}],"gradient-from-pos":[{from:le()}],"gradient-via-pos":[{via:le()}],"gradient-to-pos":[{to:le()}],"gradient-from":[{from:B()}],"gradient-via":[{via:B()}],"gradient-to":[{to:B()}],rounded:[{rounded:re()}],"rounded-s":[{"rounded-s":re()}],"rounded-e":[{"rounded-e":re()}],"rounded-t":[{"rounded-t":re()}],"rounded-r":[{"rounded-r":re()}],"rounded-b":[{"rounded-b":re()}],"rounded-l":[{"rounded-l":re()}],"rounded-ss":[{"rounded-ss":re()}],"rounded-se":[{"rounded-se":re()}],"rounded-ee":[{"rounded-ee":re()}],"rounded-es":[{"rounded-es":re()}],"rounded-tl":[{"rounded-tl":re()}],"rounded-tr":[{"rounded-tr":re()}],"rounded-br":[{"rounded-br":re()}],"rounded-bl":[{"rounded-bl":re()}],"border-w":[{border:ae()}],"border-w-x":[{"border-x":ae()}],"border-w-y":[{"border-y":ae()}],"border-w-s":[{"border-s":ae()}],"border-w-e":[{"border-e":ae()}],"border-w-bs":[{"border-bs":ae()}],"border-w-be":[{"border-be":ae()}],"border-w-t":[{"border-t":ae()}],"border-w-r":[{"border-r":ae()}],"border-w-b":[{"border-b":ae()}],"border-w-l":[{"border-l":ae()}],"divide-x":[{"divide-x":ae()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":ae()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...J(),"hidden","none"]}],"divide-style":[{divide:[...J(),"hidden","none"]}],"border-color":[{border:B()}],"border-color-x":[{"border-x":B()}],"border-color-y":[{"border-y":B()}],"border-color-s":[{"border-s":B()}],"border-color-e":[{"border-e":B()}],"border-color-bs":[{"border-bs":B()}],"border-color-be":[{"border-be":B()}],"border-color-t":[{"border-t":B()}],"border-color-r":[{"border-r":B()}],"border-color-b":[{"border-b":B()}],"border-color-l":[{"border-l":B()}],"divide-color":[{divide:B()}],"outline-style":[{outline:[...J(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Z,V,q]}],"outline-w":[{outline:["",Z,$t,ot]}],"outline-color":[{outline:B()}],shadow:[{shadow:["","none",p,Rt,Yt]}],"shadow-color":[{shadow:B()}],"inset-shadow":[{"inset-shadow":["none",m,Rt,Yt]}],"inset-shadow-color":[{"inset-shadow":B()}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:B()}],"ring-offset-w":[{"ring-offset":[Z,ot]}],"ring-offset-color":[{"ring-offset":B()}],"inset-ring-w":[{"inset-ring":ae()}],"inset-ring-color":[{"inset-ring":B()}],"text-shadow":[{"text-shadow":["none",h,Rt,Yt]}],"text-shadow-color":[{"text-shadow":B()}],opacity:[{opacity:[Z,V,q]}],"mix-blend":[{"mix-blend":[...ce(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ce()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Z]}],"mask-image-linear-from-pos":[{"mask-linear-from":R()}],"mask-image-linear-to-pos":[{"mask-linear-to":R()}],"mask-image-linear-from-color":[{"mask-linear-from":B()}],"mask-image-linear-to-color":[{"mask-linear-to":B()}],"mask-image-t-from-pos":[{"mask-t-from":R()}],"mask-image-t-to-pos":[{"mask-t-to":R()}],"mask-image-t-from-color":[{"mask-t-from":B()}],"mask-image-t-to-color":[{"mask-t-to":B()}],"mask-image-r-from-pos":[{"mask-r-from":R()}],"mask-image-r-to-pos":[{"mask-r-to":R()}],"mask-image-r-from-color":[{"mask-r-from":B()}],"mask-image-r-to-color":[{"mask-r-to":B()}],"mask-image-b-from-pos":[{"mask-b-from":R()}],"mask-image-b-to-pos":[{"mask-b-to":R()}],"mask-image-b-from-color":[{"mask-b-from":B()}],"mask-image-b-to-color":[{"mask-b-to":B()}],"mask-image-l-from-pos":[{"mask-l-from":R()}],"mask-image-l-to-pos":[{"mask-l-to":R()}],"mask-image-l-from-color":[{"mask-l-from":B()}],"mask-image-l-to-color":[{"mask-l-to":B()}],"mask-image-x-from-pos":[{"mask-x-from":R()}],"mask-image-x-to-pos":[{"mask-x-to":R()}],"mask-image-x-from-color":[{"mask-x-from":B()}],"mask-image-x-to-color":[{"mask-x-to":B()}],"mask-image-y-from-pos":[{"mask-y-from":R()}],"mask-image-y-to-pos":[{"mask-y-to":R()}],"mask-image-y-from-color":[{"mask-y-from":B()}],"mask-image-y-to-color":[{"mask-y-to":B()}],"mask-image-radial":[{"mask-radial":[V,q]}],"mask-image-radial-from-pos":[{"mask-radial-from":R()}],"mask-image-radial-to-pos":[{"mask-radial-to":R()}],"mask-image-radial-from-color":[{"mask-radial-from":B()}],"mask-image-radial-to-color":[{"mask-radial-to":B()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":C()}],"mask-image-conic-pos":[{"mask-conic":[Z]}],"mask-image-conic-from-pos":[{"mask-conic-from":R()}],"mask-image-conic-to-pos":[{"mask-conic-to":R()}],"mask-image-conic-from-color":[{"mask-conic-from":B()}],"mask-image-conic-to-color":[{"mask-conic-to":B()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:Te()}],"mask-repeat":[{mask:ye()}],"mask-size":[{mask:xe()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",V,q]}],filter:[{filter:["","none",V,q]}],blur:[{blur:Ne()}],brightness:[{brightness:[Z,V,q]}],contrast:[{contrast:[Z,V,q]}],"drop-shadow":[{"drop-shadow":["","none",x,Rt,Yt]}],"drop-shadow-color":[{"drop-shadow":B()}],grayscale:[{grayscale:["",Z,V,q]}],"hue-rotate":[{"hue-rotate":[Z,V,q]}],invert:[{invert:["",Z,V,q]}],saturate:[{saturate:[Z,V,q]}],sepia:[{sepia:["",Z,V,q]}],"backdrop-filter":[{"backdrop-filter":["","none",V,q]}],"backdrop-blur":[{"backdrop-blur":Ne()}],"backdrop-brightness":[{"backdrop-brightness":[Z,V,q]}],"backdrop-contrast":[{"backdrop-contrast":[Z,V,q]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Z,V,q]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Z,V,q]}],"backdrop-invert":[{"backdrop-invert":["",Z,V,q]}],"backdrop-opacity":[{"backdrop-opacity":[Z,V,q]}],"backdrop-saturate":[{"backdrop-saturate":[Z,V,q]}],"backdrop-sepia":[{"backdrop-sepia":["",Z,V,q]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":y()}],"border-spacing-x":[{"border-spacing-x":y()}],"border-spacing-y":[{"border-spacing-y":y()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",V,q]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Z,"initial",V,q]}],ease:[{ease:["linear","initial",$,V,q]}],delay:[{delay:[Z,V,q]}],animate:[{animate:["none",w,V,q]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[b,V,q]}],"perspective-origin":[{"perspective-origin":T()}],rotate:[{rotate:Be()}],"rotate-x":[{"rotate-x":Be()}],"rotate-y":[{"rotate-y":Be()}],"rotate-z":[{"rotate-z":Be()}],scale:[{scale:ze()}],"scale-x":[{"scale-x":ze()}],"scale-y":[{"scale-y":ze()}],"scale-z":[{"scale-z":ze()}],"scale-3d":["scale-3d"],skew:[{skew:Ke()}],"skew-x":[{"skew-x":Ke()}],"skew-y":[{"skew-y":Ke()}],transform:[{transform:[V,q,"","none","gpu","cpu"]}],"transform-origin":[{origin:T()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:De()}],"translate-x":[{"translate-x":De()}],"translate-y":[{"translate-y":De()}],"translate-z":[{"translate-z":De()}],"translate-none":["translate-none"],zoom:[{zoom:[Ve,V,q]}],accent:[{accent:B()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:B()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",V,q]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":B()}],"scrollbar-track-color":[{"scrollbar-track":B()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":y()}],"scroll-mx":[{"scroll-mx":y()}],"scroll-my":[{"scroll-my":y()}],"scroll-ms":[{"scroll-ms":y()}],"scroll-me":[{"scroll-me":y()}],"scroll-mbs":[{"scroll-mbs":y()}],"scroll-mbe":[{"scroll-mbe":y()}],"scroll-mt":[{"scroll-mt":y()}],"scroll-mr":[{"scroll-mr":y()}],"scroll-mb":[{"scroll-mb":y()}],"scroll-ml":[{"scroll-ml":y()}],"scroll-p":[{"scroll-p":y()}],"scroll-px":[{"scroll-px":y()}],"scroll-py":[{"scroll-py":y()}],"scroll-ps":[{"scroll-ps":y()}],"scroll-pe":[{"scroll-pe":y()}],"scroll-pbs":[{"scroll-pbs":y()}],"scroll-pbe":[{"scroll-pbe":y()}],"scroll-pt":[{"scroll-pt":y()}],"scroll-pr":[{"scroll-pr":y()}],"scroll-pb":[{"scroll-pb":y()}],"scroll-pl":[{"scroll-pl":y()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",V,q]}],fill:[{fill:["none",...B()]}],"stroke-w":[{stroke:[Z,$t,ot,Nr]}],stroke:[{stroke:["none",...B()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});function H(...e){return ca(lr(e))}const da=ur("relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current"}},defaultVariants:{variant:"default"}});function pt({className:e,variant:n,...r}){return t.jsx("div",{"data-slot":"alert",role:"alert",className:H(da({variant:n}),e),...r})}function Er({className:e,...n}){return t.jsx("div",{"data-slot":"alert-title",className:H("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",e),...n})}function ht({className:e,...n}){return t.jsx("div",{"data-slot":"alert-description",className:H("col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed",e),...n})}const ke=ve.forwardRef(({className:e,type:n,...r},s)=>t.jsx("input",{type:n,ref:s,"data-slot":"input",className:H("h-9 w-full min-w-0 rounded-md border border-input bg-transparent text-foreground px-3 py-0 text-sm shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...r}));ke.displayName="Input";function Xe(e,n){if(e==null)return null;switch(n){case"Int":{const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.trunc(r):e}case"Float":{const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:e}case"Boolean":return typeof e=="boolean"?e:e==="true"||e===1?!0:e==="false"||e===0?!1:!!e;default:return String(e)}}function Xt(e){return e?.paramType?.replace("!","")??"String"}function it(e){return(e.sourceColumnNames?.length??0)>1}function ua(e,n,r,s="fk"){if(!e)return null;const o=n.sourceColumnNames??[],i=n.destinationColumnNames??[];if(o.length===0||o.length!==i.length)return null;const a=new Map((r?.columns??[]).map(m=>[m.name,m])),l=[],u={},d=[];for(let m=0;m<o.length;m++){const h=o[m],x=i[m];if(!(h in e))return null;const g=Xt(a.get(x)),b=`${s}_${x}`;u[b]=Xe(e[h],g),d.push(`$${b}: ${g}`),l.push(`{${x}: {_eq: $${b}}}`)}return{filterText:l.length===1?l[0]:`{and: [${l.join(", ")}]}`,variables:u,params:d}}const bn="::";function ma(e){return e==null?"":encodeURIComponent(String(e))}function Ut(e){if(e==="")return null;try{return decodeURIComponent(e)}catch{return e}}function xt(e){return e.map(ma).join(bn)}function Pr(e,n){const r=n<=1?[e]:e.split(bn);if(r.length!==n)throw new Error(`Route id '${e}' has ${r.length} part(s) but ${n} were expected.`);return r.map(s=>s===""?"":Ut(s)??"")}function _t(e,n,r){const s=n.primaryKeys??[];return s.length===0?`row-${r}`:xt(s.map(o=>e?.[o]))}function gt(e,n){const r=n.primaryKeys??[];if(r.length===0||e==null)return null;const s={};for(const o of r){if(!(o in e))return null;s[o]=e[o]}return s}function yn(e,n){const r=gt(e,n);if(!r)return null;const s=new Map((n.columns??[]).map(u=>[u.name,u])),o=[],i={},a=[];for(const u of n.primaryKeys??[]){const d=Xt(s.get(u)),p=`pk_${u}`;i[p]=Xe(r[u],d),a.push(`$${p}: ${d}`),o.push(`{${u}: {_eq: $${p}}}`)}return{filterText:o.length===1?o[0]:`{and: [${o.join(", ")}]}`,variables:i,params:a}}function vn(e,n){const r=n.primaryKeys??[];return r.length===0?"":xt(r.map(s=>e[s]))}function jn(e,n){const r=n.primaryKeys??[];if(r.length===0)return null;if(r.length===1)return{[r[0]]:Ut(e)};const s=e.split(bn);if(s.length!==r.length)return null;const o={};for(let i=0;i<r.length;i++)o[r[i]]=Ut(s[i]);return o}function fa(e,n,r){if(!e)return;const s=e.filter(o=>o.destinationTable===n);if(s.length!==0){if(s.length===1)return s[0];if(r)return s.find(o=>o.destinationColumnNames?.[0]===r)}}function pa(e){return e.fieldName??e.destinationTable}const ha=new Set(["binary","varbinary","image","blob","tinyblob","mediumblob","longblob","bytea"]),xa=new Set(["text","ntext","xml"]),ga=new Set(["json","jsonb"]);function bt(e){return ha.has(e.toLowerCase().replace(/\(.*\)/,""))}function Dr(e){return ga.has(e.toLowerCase().replace(/\(.*\)/,""))}function lt(e){return Dr(e.dbType)||e.paramType==="JSON"}function Ft(e){const n=e.toLowerCase(),r=n.replace(/\(.*\)/,"");return!!(xa.has(r)||n.includes("(max)"))}function Nn(e,n){if(!e)return"text";if(n&&bt(n))return"binary";if(n&&Dr(n))return"json";const r=e.trimStart();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{return JSON.parse(r),"json"}catch{}return r.startsWith("<?xml")||r.startsWith("<")&&r.includes("</")&&r.endsWith(">")?"xml":/^[aOsidb]:\d+[:{;]/.test(r)?"php-serialized":e.length>200||e.includes(`
78
- `)?"longtext":"text"}const Mr=80;function ba(e){return e.length<=Mr?e:e.slice(0,Mr)+"..."}function ya(e){const n=Math.ceil(e.length*3/4);return n<1024?`${n} bytes`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}const wn={String:["_eq","_neq","_contains","_starts_with","_ends_with","_null"],Int:["_eq","_neq","_gt","_gte","_lt","_lte","_between","_null"],Float:["_eq","_neq","_gt","_gte","_lt","_lte","_between","_null"],BigInt:["_eq","_neq","_gt","_gte","_lt","_lte","_between","_null"],Decimal:["_eq","_neq","_gt","_gte","_lt","_lte","_between","_null"],Boolean:["_eq","_null"],DateTime:["_eq","_neq","_gt","_gte","_lt","_lte","_between","_null"]},va=/^[_A-Za-z][_0-9A-Za-z]*$/,ja=/^[_A-Za-z][_0-9A-Za-z]*!?$/,Na=new Set(Object.values(wn).flat());function Ie(e){return typeof e=="string"&&va.test(e)}function Fe(e,n){if(!Ie(e))throw new Error(`Invalid GraphQL ${n}: ${String(e)}`)}function wa(e){return typeof e=="string"&&ja.test(e)}function Ir(e,n){return typeof e=="string"&&Lr(n).includes(e)}function Lr(e){const n=e.replace("!","");return wn[n]??wn.String}function Or(e){try{if(!e)return{variables:{},param:"",filterText:""};const[n,r,s,o]=JSON.parse(e);return!Ie(n)||!wa(o)||!Ir(r,o)?{variables:{},param:"",filterText:""}:{variables:{filter:s},param:`, $filter: ${o}`,filterText:`{${n}: {${r}: $filter} }`}}catch{return{variables:{},param:"",filterText:""}}}function Ar(e){if(!e)return"";const n=new Date(e);return n.toString()==="Invalid Date"||n.getTime()===0||n.getUTCFullYear()<=1?"":n.toLocaleString()}function Ca(e,n,r=0){return _t(e,n,r)}function qr(e){switch(e.replace("!","")){case"Int":return"Int";case"Float":return"Float";case"Boolean":return"Boolean";case"BigInt":return"BigInt";case"Decimal":return"Decimal";case"DateTime":return"String";default:return"String"}}function Vr(e,n){const r={},s=[],o=[];for(let i=0;i<e.length;i++){const a=e[i],l=a.value;if(l.value===void 0||l.value===null||l.value==="")continue;const u=n.columns.find(m=>m.name===a.id);if(!u||!Ie(a.id)||!Ir(l.operator,u.paramType))continue;const d=`cf_${a.id}_${i}`,p=qr(u.paramType);if(l.operator==="_null"){o.push(`{${a.id}: {_null: ${l.value?"true":"false"}}}`);continue}if(l.operator==="_between"){const m=l.value;if(!Array.isArray(m)||m.length!==2)continue;const h=`${d}_lo`,x=`${d}_hi`;r[h]=m[0],r[x]=m[1],s.push(`$${h}: ${p}`,`$${x}: ${p}`),o.push(`{${a.id}: {_between: [$${h}, $${x}]}}`);continue}r[d]=l.value,s.push(`$${d}: ${p}`),o.push(`{${a.id}: {${l.operator}: $${d}}}`)}return{variables:r,params:s,filterTexts:o}}function Br(e){return e.length===0?"":JSON.stringify(e.map(n=>[n.id,n.value.operator,n.value.value]))}function Kr(e){try{if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(ka).map(([r,s,o])=>({id:r,value:{operator:s,value:o}})):[]}catch{return[]}}function ka(e){if(!Array.isArray(e)||e.length!==3)return!1;const[n,r]=e;return Ie(n)&&typeof r=="string"&&Na.has(r)}function Gr(e){return Qe(e)[0]?.gqlType??"Int"}function Qe(e){const n=e.primaryKeys??[];if(n.length===0)return[];const r=new Map(e.columns.map(s=>[s.name,s]));return n.map(s=>({name:s,gqlType:r.get(s)?.paramType?.replace("!","")??"String"}))}function Cn(e,n){if(Qe(n).length<=1)return{id:Xe(Ut(e),Gr(n))};const s=jn(e,n);return s?yn(s,n)?.variables??{}:{}}function Ta(e,n,r){Fe(e.name,"single-row table name");for(const o of r)Fe(o,"single-row selection field");const s=n.params.length>0?`(${n.params.join(", ")})`:"";return`query GetSingleRow_${e.name}${s} { value: ${e.name}(filter: ${n.filterText}) { data { ${r.join(" ")} } } }`}const Sa=11;function Jr(e,n){return n.map(r=>{const s=e.findTable(r.destinationTable),o=s?.labelColumn??"id",a=[...s?.primaryKeys?.length?s.primaryKeys:["id"]];return o&&!a.includes(o)&&a.push(o),`${r.fieldName??r.destinationTable}(limit: ${Sa}) { total data { ${a.join(" ")} } }`}).join(" ")}function $a(e,n,r,s,o,i,a){if(!e||!n?.data)return null;const l=n.findTable(e.graphQlName);if(!l)return null;const u=Gr(l),d=Qe(l),p=d[0]?.name??"id";let{param:m,filterText:h}=Or(r);const{params:x,filterTexts:g}=Vr(s,e);x.length>0&&(m+=x.map(C=>`, ${C}`).join(""));const b=[];h&&b.push(h),b.push(...g),b.length>1?h=`{and: [${b.join(", ")}]}`:b.length===1?h=b[0]:h="";const k=new Set,$=e.columns.filter(C=>C?.joinTable===void 0).filter(C=>C.isPrimaryKey||!(bt(C.dbType)||Ft(C.dbType))).map(C=>{const T=l.singleJoins.find(y=>y.sourceColumnNames?.[0]===C.name);if(!T)return C;const E=n.findTable(T.destinationTable)?.labelColumn??"id";return{...C,joinTable:T,joinLabelColumn:E}}).map(C=>{if(C?.joinTable){k.add(C.name);const T=n.findTable(C.joinTable.destinationTable),j=T?.primaryKeys?.length?T.primaryKeys:C.joinTable.destinationColumnNames,E=C.joinLabelColumn??"id",y=E&&!j.includes(E)?` label: ${E}`:"";return j.length===1?`${C.name} ${C.joinTable.destinationTable} { id: ${j[0]}${y} }`:`${C.name} ${C.joinTable.destinationTable} { ${j.join(" ")}${y} }`}return C.name}).join(" "),w=Jr(n,l.multiJoins),P=w?`${$} ${w}`:$;if(o&&(a||i)){const C=kn(e,n,i,a);if(C&&Wr(C.childJoin)){const T=C.childJoin.destinationColumnNames[0];m=`, $id: ${Qe(C.parentTable)[0]?.gqlType??"Int"}`;const E=`filter: { ${T}: { _eq: $id } }`,y=Jr(n,l.multiJoins.filter(L=>!_a(L,C.childJoin))),S=y?`${$} ${y}`:$;return`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${m}) { ${e.name}(sort: $sort limit: $limit offset: $offset ${E}) { total offset limit data {${S}}}}`}if(C){const T=`${C.childField}(limit: $limit offset: $offset sort: $sort) { total offset limit data {${P}} }`,j=Qe(C.parentTable);if(j.length<=1){const L=j[0]?.name??"id";m=`, $id: ${j[0]?.gqlType??"Int"}`;const M=`{ ${L}: { _eq: $id}}`;return`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${m}) { ${C.parentTable.name}(filter: ${M}) { data { ${T} } } }`}m=`, ${j.map(L=>`$pk_${L.name}: ${L.gqlType}`).join(", ")}`;const S=`{and: [${j.map(L=>`{${L.name}: {_eq: $pk_${L.name}}}`).join(", ")}]}`;return`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${m}) { ${C.parentTable.name}(filter: ${S}) { data { ${T} } } }`}return null}return o&&!i&&!a&&(d.length<=1?(m=`, $id: ${u}`,h=`{ ${p}: { _eq: $id}}`):(m=`, ${d.map(T=>`$pk_${T.name}: ${T.gqlType}`).join(", ")}`,h=`{and: [${d.map(T=>`{${T.name}: {_eq: $pk_${T.name}}}`).join(", ")}]}`)),h&&(h=`filter: ${h}`),`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${m}) { ${e.name}(sort: $sort limit: $limit offset: $offset ${h}) { total offset limit data {${P}}}}`}function Wr(e){return!it(e)&&e.isPolymorphic!==!0&&(e.destinationColumnNames?.length??0)===1}function _a(e,n){return(e.fieldName??e.destinationTable)===(n.fieldName??n.destinationTable)&&e.destinationTable===n.destinationTable&&(e.destinationColumnNames??[]).join("\0")===(n.destinationColumnNames??[]).join("\0")&&(e.sourceColumnNames??[]).join("\0")===(n.sourceColumnNames??[]).join("\0")}const Fa={data:[],total:0,offset:0,limit:0};function za(e,n,r){const i=e?.[n]?.data?.[0]?.[r];return!i||!Array.isArray(i.data)?Fa:i}function kn(e,n,r,s){const o=r??n.findTable(e.graphQlName)?.singleJoins.find(l=>l.destinationTable===s)?.destinationTable;if(!o)return null;const i=n.findTable(o);if(!i)return null;const a=fa(i.multiJoins,e.graphQlName,s);return a?{parentTable:i,childField:pa(a),childJoin:a}:null}function Ea(e){const n=e.filter(Ie);return n.length===0?null:`query GetTableRowCounts { ${n.map(s=>`${s}: ${s}(limit: 1) { total }`).join(" ")} }`}function Pa(e=!0){const{data:n,loading:r,error:s}=Pe(),o=Ce(),i=c.useMemo(()=>n.map(m=>m.name),[n]),a=c.useMemo(()=>Ea(i),[i]),{data:l,isLoading:u,error:d}=me.useQuery({queryKey:["tableRowCounts",i],queryFn:()=>o.query(a),enabled:e&&!!a&&i.length>0,staleTime:300*1e3});return{stats:c.useMemo(()=>{const m={};for(const h of n){const g=l?.[h.name]?.total??null;m[h.name]={columnCount:h.columns.length,rowCount:g,fkCount:h.singleJoins.length,isLoading:u,error:d?d.message:null}}return m},[n,l,u,d]),isLoading:r||u,error:s}}function Da(e){if(e===null)return"—";if(e===0)return"0";if(e<1e3)return e.toString();if(e<1e6){const r=e/1e3;return r%1===0?`${r.toFixed(0)}k`:`${r.toFixed(1)}k`}const n=e/1e6;return n%1===0?`${n.toFixed(0)}M`:`${n.toFixed(1)}M`}const Ma={showStats:!1},Hr=c.createContext(Ma);function Ia({config:e,children:n}){return t.jsx(Hr.Provider,{value:e,children:n})}function La(){return c.useContext(Hr)}const Zt=50;function Oa(e,n){return e===null||n<=0?0:Math.max(2,Math.min(100,Math.round(e/n*100)))}function Aa({percent:e,label:n}){return t.jsx("span",{className:"flex-1 min-w-[1.5em] h-[0.5em] rounded-full bg-muted/70 overflow-hidden",role:"img","aria-label":n,title:n,children:t.jsx("span",{className:"block h-full rounded-full bg-emerald-500/70 dark:bg-emerald-400/70",style:{width:`${e}%`}})})}function Tn({count:e}){return e<=0?null:t.jsxs("span",{className:"shrink-0 rounded px-1 py-px text-[0.85em] tabular-nums bg-blue-100 text-blue-700 dark:bg-blue-900/60 dark:text-blue-300",children:[e," FK"]})}function qa(e){try{return decodeURIComponent(e)}catch{return e}}function Va({stats:e,maxRowCount:n}){const r=Oa(e.rowCount,n),s="flex items-center gap-1.5 text-xs leading-none min-w-0";return e.isLoading?t.jsxs("div",{className:`${s} text-muted-foreground`,children:[t.jsxs("span",{className:"tabular-nums shrink-0",children:[e.columnCount,"c"]}),t.jsx("span",{className:"flex-1 min-w-[1.5em] h-[0.5em] rounded-full bg-muted/70 overflow-hidden",children:t.jsx("span",{className:"block h-full w-1/3 rounded-full bg-muted-foreground/30 animate-pulse"})}),t.jsx(N.Loader2,{className:"size-[1em] shrink-0 animate-spin"}),t.jsx(Tn,{count:e.fkCount})]}):e.error?t.jsxs("div",{className:s,children:[t.jsxs("span",{className:"tabular-nums shrink-0 text-muted-foreground",children:[e.columnCount,"c"]}),t.jsx("span",{className:"flex-1 text-destructive truncate",title:e.error,children:"err"}),t.jsx(Tn,{count:e.fkCount})]}):t.jsxs("div",{className:s,children:[t.jsxs("span",{className:"tabular-nums shrink-0 text-muted-foreground/70",children:[e.columnCount,"c"]}),t.jsx(Aa,{percent:r,label:`${e.rowCount?.toLocaleString()??"unknown"} rows`}),t.jsx("span",{className:"tabular-nums shrink-0 text-right text-muted-foreground",children:Da(e.rowCount)}),t.jsx(Tn,{count:e.fkCount})]})}function Ba({table:e,stats:n,maxRowCount:r,showStats:s,active:o}){return t.jsx(St,{to:`/${e.name}`,"aria-current":o?"page":void 0,className:`plain-link block no-underline py-1.5 px-2 text-sm font-medium border-l-2 ${o?"bg-accent text-accent-foreground border-primary":"text-foreground border-transparent hover:bg-muted/50 hover:text-primary"}`,children:t.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[t.jsx("span",{className:"truncate",title:e.label,children:e.label}),s&&t.jsx(Va,{stats:n,maxRowCount:r})]})})}function Sn(e){const n=e.dbName.lastIndexOf(".");return n>0?e.dbName.slice(0,n):null}function Qr({schema:e,count:n,collapsed:r,context:s,onToggle:o}){const i=r?N.ChevronRight:N.ChevronDown,a=t.jsxs(t.Fragment,{children:[t.jsx(i,{className:"size-3.5 shrink-0 text-muted-foreground"}),t.jsx("span",{className:"truncate font-semibold",title:e,children:e}),t.jsx("span",{className:"ml-auto shrink-0 tabular-nums text-[0.85em] text-muted-foreground",children:n})]}),l="flex items-center gap-1.5 w-full px-2 py-1 text-xs uppercase tracking-wide text-muted-foreground bg-muted/40 border-y border-border sticky top-0 z-10";return s?t.jsx("div",{className:l,"aria-hidden":"true",children:a}):t.jsx("button",{type:"button",onClick:o,"aria-expanded":!r,className:`${l} hover:bg-muted/70 text-left`,children:a})}function Ka(){const{showStats:e}=La(),{loading:n,error:r,data:s}=Pe(),{stats:o,isLoading:i}=Pa(e),[a,l]=c.useState(""),[u,d]=c.useState(new Set),[p,m]=c.useState(0),h=Zn(),x=qa(h.split("/")[1]??""),g=c.useMemo(()=>{const v=Object.values(o).map(M=>M.rowCount).filter(M=>M!==null);return v.length>0?Math.max(...v):0},[o]),b=a.trim().length>0,k=c.useMemo(()=>{const v=a.trim().toLowerCase();return v?s.filter(M=>{const O=Sn(M);return M.label.toLowerCase().includes(v)||M.dbName.toLowerCase().includes(v)||(O?.toLowerCase().includes(v)??!1)}):s},[s,a]),{schemas:$,grouped:w,multiSchema:P}=c.useMemo(()=>{const v=new Map;for(const O of k){const z=Sn(O),I=v.get(z)??[];I.push(O),v.set(z,I)}const M=[...v.keys()].filter(O=>O!==null).sort((O,z)=>O.localeCompare(z));return{schemas:M,grouped:v,multiSchema:M.length>1}},[k]),C=c.useMemo(()=>{const v=[];if(P){const M=[...$,...w.has(null)?[null]:[]];for(const O of M){const z=w.get(O===void 0?null:O)??[],I=!b&&u.has(O);if(v.push({kind:"group",schema:O??"(no schema)",count:z.length,collapsed:I}),!I)for(const _ of z)v.push({kind:"table",schema:O,table:_})}}else for(const M of k)v.push({kind:"table",schema:Sn(M),table:M});return v},[P,$,w,k,u,b]);c.useEffect(()=>{m(0)},[a]);const T=Math.max(1,Math.ceil(C.length/Zt)),j=Math.min(p,T-1),E=j*Zt,y=C.slice(E,E+Zt),S=P&&y[0]?.kind==="table"&&y[0].schema?y[0].schema:null,L=v=>d(M=>{const O=new Set(M);return O.has(v)?O.delete(v):O.add(v),O});return n?t.jsxs("div",{className:"flex items-center justify-center gap-2 p-4",children:[t.jsx(N.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),t.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):r?t.jsx(pt,{variant:"destructive",className:"m-2",children:t.jsxs(ht,{children:["Error: ",r.message]})}):s.length===0?t.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[t.jsx("p",{className:"font-medium",children:"No tables found"}),t.jsx("p",{className:"mt-1",children:"The database may be empty or the connection may have failed."})]}):t.jsxs("div",{className:"@container min-w-0 flex flex-col h-full",children:[t.jsxs("div",{className:"sticky top-0 z-20 bg-background p-2 border-b border-border",children:[t.jsxs("div",{className:"relative",children:[t.jsx(N.Search,{className:"absolute left-2 top-1/2 -translate-y-1/2 size-4 text-muted-foreground pointer-events-none"}),t.jsx(ke,{type:"search",value:a,onChange:v=>l(v.target.value),placeholder:"Search tables...","aria-label":"Search tables",className:"pl-8 pr-8 h-8 text-sm"}),b&&t.jsx("button",{type:"button",onClick:()=>l(""),"aria-label":"Clear search",className:"absolute right-1.5 top-1/2 -translate-y-1/2 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted",children:t.jsx(N.X,{className:"size-4"})})]}),b&&t.jsxs("p",{className:"mt-1 px-0.5 text-xs text-muted-foreground",children:[k.length," match",k.length!==1?"es":""]})]}),t.jsx("div",{className:"flex-1 overflow-y-auto min-h-0",children:C.length===0?t.jsxs("p",{className:"p-4 text-center text-sm text-muted-foreground",children:["No tables match “",a,"”."]}):t.jsxs(t.Fragment,{children:[S&&t.jsx(Qr,{schema:S,count:w.get(S)?.length??0,collapsed:!1,context:!0}),y.map(v=>v.kind==="group"?t.jsx(Qr,{schema:v.schema,count:v.count,collapsed:v.collapsed,onToggle:()=>L(v.schema)},`g:${v.schema}`):t.jsx(Ba,{table:v.table,stats:o[v.table.name]??{columnCount:v.table.columns.length,rowCount:null,fkCount:v.table.singleJoins.length,isLoading:i,error:null},maxRowCount:g,showStats:e,active:v.table.name===x},`t:${v.table.name}`))]})}),T>1&&t.jsxs("div",{className:"sticky bottom-0 z-20 bg-background border-t border-border flex items-center justify-between gap-2 px-2 py-1.5",children:[t.jsx("button",{type:"button",onClick:()=>m(v=>Math.max(0,v-1)),disabled:j===0,"aria-label":"Previous page",className:"p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 disabled:pointer-events-none",children:t.jsx(N.ChevronLeft,{className:"size-4"})}),t.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:[E+1,"–",Math.min(E+Zt,C.length)," of ",C.length]}),t.jsx("button",{type:"button",onClick:()=>m(v=>Math.min(T-1,v+1)),disabled:j>=T-1,"aria-label":"Next page",className:"p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 disabled:pointer-events-none",children:t.jsx(N.ChevronRight,{className:"size-4"})})]})]})}const Ga=ur("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background text-foreground hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"text-foreground hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10","icon-sm":"h-8 w-8 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),W=ve.forwardRef(({className:e,variant:n,size:r,asChild:s=!1,...o},i)=>{const a=s?Js.Slot:"button";return t.jsx(a,{className:H(Ga({variant:n,size:r,className:e})),ref:i,...o})});W.displayName="Button";function Yr({...e}){return t.jsx(Q.DropdownMenu.Root,{"data-slot":"dropdown-menu",...e})}function Rr({...e}){return t.jsx(Q.DropdownMenu.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function Xr({className:e,sideOffset:n=4,...r}){return t.jsx(Q.DropdownMenu.Portal,{children:t.jsx(Q.DropdownMenu.Content,{"data-slot":"dropdown-menu-content",sideOffset:n,className:H("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...r})})}function zt({className:e,inset:n,variant:r="default",...s}){return t.jsx(Q.DropdownMenu.Item,{"data-slot":"dropdown-menu-item","data-inset":n,"data-variant":r,className:H("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...s})}function Ja({className:e,children:n,checked:r,...s}){return t.jsxs(Q.DropdownMenu.CheckboxItem,{"data-slot":"dropdown-menu-checkbox-item",className:H("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),checked:r,...s,children:[t.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:t.jsx(Q.DropdownMenu.ItemIndicator,{children:t.jsx(N.CheckIcon,{className:"size-4"})})}),n]})}function Wa({className:e,inset:n,...r}){return t.jsx(Q.DropdownMenu.Label,{"data-slot":"dropdown-menu-label","data-inset":n,className:H("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...r})}function Ue({className:e,...n}){return t.jsx(Q.DropdownMenu.Separator,{"data-slot":"dropdown-menu-separator",className:H("-mx-1 my-1 h-px bg-border",e),...n})}function Et({...e}){return t.jsx(Q.DropdownMenu.Sub,{"data-slot":"dropdown-menu-sub",...e})}function Pt({className:e,inset:n,children:r,...s}){return t.jsxs(Q.DropdownMenu.SubTrigger,{"data-slot":"dropdown-menu-sub-trigger","data-inset":n,className:H("flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...s,children:[r,t.jsx(N.ChevronRightIcon,{className:"ml-auto size-4"})]})}function Dt({className:e,...n}){return t.jsx(Q.DropdownMenu.SubContent,{"data-slot":"dropdown-menu-sub-content",className:H("z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})}const Mt=ve.forwardRef(({...e},n)=>t.jsx(Q.HoverCard.Root,{"data-slot":"hover-card",...e}));Mt.displayName="HoverCard";const It=ve.forwardRef(({...e},n)=>t.jsx(Q.HoverCard.Trigger,{"data-slot":"hover-card-trigger",...e}));It.displayName="HoverCardTrigger";const Lt=ve.forwardRef(({className:e,align:n="center",sideOffset:r=4,...s},o)=>t.jsx(Q.HoverCard.Portal,{children:t.jsx(Q.HoverCard.Content,{ref:o,"data-slot":"hover-card-content",align:n,sideOffset:r,className:H("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...s})}));Lt.displayName="HoverCardContent";function Le({...e}){return t.jsx(Q.Select.Root,{"data-slot":"select",...e})}function Oe({...e}){return t.jsx(Q.Select.Value,{"data-slot":"select-value",...e})}function Ae({className:e,size:n="default",children:r,...s}){return t.jsxs(Q.Select.Trigger,{"data-slot":"select-trigger","data-size":n,className:H("flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent text-foreground px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...s,children:[r,t.jsx(Q.Select.Icon,{asChild:!0,children:t.jsx(N.ChevronDownIcon,{className:"size-4 opacity-50"})})]})}function qe({className:e,children:n,position:r="item-aligned",align:s="center",...o}){return t.jsx(Q.Select.Portal,{children:t.jsxs(Q.Select.Content,{"data-slot":"select-content",className:H("relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,align:s,...o,children:[t.jsx(Ha,{}),t.jsx(Q.Select.Viewport,{className:H("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:n}),t.jsx(Qa,{})]})})}function ge({className:e,children:n,...r}){return t.jsxs(Q.Select.Item,{"data-slot":"select-item",className:H("relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...r,children:[t.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:t.jsx(Q.Select.ItemIndicator,{children:t.jsx(N.CheckIcon,{className:"size-4"})})}),t.jsx(Q.Select.ItemText,{children:n})]})}function Ha({className:e,...n}){return t.jsx(Q.Select.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:H("flex cursor-default items-center justify-center py-1",e),...n,children:t.jsx(N.ChevronUpIcon,{className:"size-4"})})}function Qa({className:e,...n}){return t.jsx(Q.Select.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:H("flex cursor-default items-center justify-center py-1",e),...n,children:t.jsx(N.ChevronDownIcon,{className:"size-4"})})}function Ur(e){const n=c.useRef(null),r=c.useRef(null),s=c.useRef(e);s.current=e;const o=c.useMemo(()=>{const i=()=>{n.current&&(clearTimeout(n.current),n.current=null)},a=()=>{i();const l=r.current;r.current=null,l?.()};return{schedule:l=>{i(),r.current=l,n.current=setTimeout(a,s.current)},cancel:()=>{i(),r.current=null},flush:a}},[]);return c.useEffect(()=>()=>o.flush(),[o]),o}const Zr={_contains:"Contains",_starts_with:"Starts with",_ends_with:"Ends with",_eq:"Equals",_neq:"Not equals",_null:"Is null"},Ya=300;function Ra({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(b=>b in Zr),s=e.getFilterValue(),[o,i]=c.useState(s?.operator??"_contains"),[a,l]=c.useState(s?.operator==="_null"?"":String(s?.value??"")),{schedule:u,cancel:d}=Ur(Ya),p=o==="_null",m=(b,k)=>{if(b==="_null"){d(),e.setFilterValue({operator:"_null",value:!0});return}if(!k){d(),e.setFilterValue(void 0);return}u(()=>e.setFilterValue({operator:b,value:k}))},h=b=>{i(b),b==="_null"?(l(""),m("_null","")):a?m(b,a):(d(),e.setFilterValue(void 0))},x=b=>{l(b),m(o,b)},g=()=>{d(),i("_contains"),l(""),e.setFilterValue(void 0)};return r.length===0?null:t.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[t.jsxs(Le,{value:o,onValueChange:h,children:[t.jsx(Ae,{size:"sm",className:"w-full text-xs",children:t.jsx(Oe,{})}),t.jsx(qe,{children:r.map(b=>t.jsx(ge,{value:b,children:Zr[b]},b))})]}),!p&&t.jsx(ke,{placeholder:"Filter value...",value:a,onChange:b=>x(b.target.value),className:"h-8 text-xs",autoFocus:!0}),s!==void 0&&t.jsxs(W,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:g,children:[t.jsx(N.X,{className:"size-3"}),"Clear filter"]})]})}const es={_eq:"Equals",_neq:"Not equals",_gt:"Greater than",_gte:"Greater or equal",_lt:"Less than",_lte:"Less or equal",_between:"Between",_null:"Is null"},Xa=300;function Ua(e){return(e.columnDef.meta?.paramType??"").replace("!","")==="Int"}function $n(e,n){const r=e.trim();if(r===""||r==="-"||r==="+"||!(n?/^[+-]?\d+$/.test(r):/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(r)))return null;const o=Number(r);return Number.isFinite(o)?o:null}function Za({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(S=>S in es),s=Ua(e),o=e.getFilterValue(),i=o?.operator??"_eq",[a,l]=c.useState(i),[u,d]=c.useState(()=>!o||o.operator==="_null"||o.operator==="_between"?"":String(o.value??"")),[p,m]=c.useState(()=>o?.operator==="_between"&&Array.isArray(o.value)?String(o.value[0]??""):""),[h,x]=c.useState(()=>o?.operator==="_between"&&Array.isArray(o.value)?String(o.value[1]??""):""),{schedule:g,cancel:b}=Ur(Xa),k=(S,L)=>{if(S==="_null"){b(),e.setFilterValue({operator:"_null",value:!0});return}const v=$n(L,s);if(v===null){b(),e.setFilterValue(void 0);return}g(()=>e.setFilterValue({operator:S,value:v}))},$=(S,L)=>{const v=$n(S,s),M=$n(L,s);if(v===null||M===null){b(),e.setFilterValue(void 0);return}g(()=>e.setFilterValue({operator:"_between",value:[v,M]}))},w=S=>{l(S),S==="_null"?(d(""),m(""),x(""),k("_null","")):S==="_between"?(d(""),p&&h?$(p,h):(b(),e.setFilterValue(void 0))):(m(""),x(""),u?k(S,u):(b(),e.setFilterValue(void 0)))},P=S=>{d(S),k(a,S)},C=S=>{m(S),$(S,h)},T=S=>{x(S),$(p,S)},j=()=>{b(),l("_eq"),d(""),m(""),x(""),e.setFilterValue(void 0)};if(r.length===0)return null;const E=a==="_between",y=a==="_null";return t.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[t.jsxs(Le,{value:a,onValueChange:w,children:[t.jsx(Ae,{size:"sm",className:"w-full text-xs",children:t.jsx(Oe,{})}),t.jsx(qe,{children:r.map(S=>t.jsx(ge,{value:S,children:es[S]},S))})]}),!y&&!E&&t.jsx(ke,{type:"number",placeholder:"Filter value...",value:u,onChange:S=>P(S.target.value),className:"h-8 text-xs",autoFocus:!0}),E&&t.jsxs("div",{className:"flex gap-2",children:[t.jsx(ke,{type:"number",placeholder:"Min",value:p,onChange:S=>C(S.target.value),className:"h-8 text-xs",autoFocus:!0}),t.jsx(ke,{type:"number",placeholder:"Max",value:h,onChange:S=>T(S.target.value),className:"h-8 text-xs"})]}),o!==void 0&&t.jsxs(W,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:j,children:[t.jsx(N.X,{className:"size-3"}),"Clear filter"]})]})}const ts={_eq:"On",_neq:"Not on",_gt:"After",_gte:"On or after",_lt:"Before",_lte:"On or before",_between:"Between",_null:"Is null"};function ei({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(j=>j in ts),s=e.getFilterValue(),o=s?.operator??"_eq",[i,a]=c.useState(o),[l,u]=c.useState(()=>!s||s.operator==="_null"||s.operator==="_between"?"":String(s.value??"")),[d,p]=c.useState(()=>s?.operator==="_between"&&Array.isArray(s.value)?String(s.value[0]??""):""),[m,h]=c.useState(()=>s?.operator==="_between"&&Array.isArray(s.value)?String(s.value[1]??""):""),x=(j,E)=>{if(j==="_null"){e.setFilterValue({operator:"_null",value:!0});return}if(!E){e.setFilterValue(void 0);return}e.setFilterValue({operator:j,value:E})},g=(j,E)=>{if(!j||!E){e.setFilterValue(void 0);return}e.setFilterValue({operator:"_between",value:[j,E]})},b=j=>{a(j),j==="_null"?(u(""),p(""),h(""),e.setFilterValue({operator:"_null",value:!0})):j==="_between"?(u(""),d&&m?g(d,m):e.setFilterValue(void 0)):(p(""),h(""),l?x(j,l):e.setFilterValue(void 0))},k=j=>{u(j),x(i,j)},$=j=>{p(j),g(j,m)},w=j=>{h(j),g(d,j)},P=()=>{a("_eq"),u(""),p(""),h(""),e.setFilterValue(void 0)};if(r.length===0)return null;const C=i==="_between",T=i==="_null";return t.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[t.jsxs(Le,{value:i,onValueChange:b,children:[t.jsx(Ae,{size:"sm",className:"w-full text-xs",children:t.jsx(Oe,{})}),t.jsx(qe,{children:r.map(j=>t.jsx(ge,{value:j,children:ts[j]},j))})]}),!T&&!C&&t.jsx(ke,{type:"date",value:l,onChange:j=>k(j.target.value),className:"h-8 text-xs"}),C&&t.jsxs("div",{className:"flex gap-2",children:[t.jsx(ke,{type:"date",value:d,onChange:j=>$(j.target.value),className:"h-8 text-xs"}),t.jsx(ke,{type:"date",value:m,onChange:j=>w(j.target.value),className:"h-8 text-xs"})]}),s!==void 0&&t.jsxs(W,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:P,children:[t.jsx(N.X,{className:"size-3"}),"Clear filter"]})]})}const ti={all:"All",true:"True",false:"False",_null:"Is null"};function ni(e){return e?e.operator==="_null"?"_null":e.operator==="_eq"&&e.value===!0?"true":e.operator==="_eq"&&e.value===!1?"false":"all":"all"}function ri({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).includes("_null"),s=e.getFilterValue(),o=ni(s),i=r?["all","true","false","_null"]:["all","true","false"],a=u=>{switch(u){case"true":e.setFilterValue({operator:"_eq",value:!0});break;case"false":e.setFilterValue({operator:"_eq",value:!1});break;case"_null":e.setFilterValue({operator:"_null",value:!0});break;default:e.setFilterValue(void 0)}},l=()=>{e.setFilterValue(void 0)};return t.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[t.jsxs(Le,{value:o,onValueChange:a,children:[t.jsx(Ae,{size:"sm",className:"w-full text-xs",children:t.jsx(Oe,{})}),t.jsx(qe,{children:i.map(u=>t.jsx(ge,{value:u,children:ti[u]},u))})]}),s!==void 0&&t.jsxs(W,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:l,children:[t.jsx(N.X,{className:"size-3"}),"Clear filter"]})]})}function si(e,n,r,s){return!Ie(e)||!Ie(n)||!Ie(r)||s&&(!s.some(o=>o.name===n)||!s.some(o=>o.name===r))?null:`query Lookup${e} { ${e}(sort: [${n}_asc], limit: 100) { data { id: ${r} label: ${n} } } }`}function oi({column:e,joinTable:n,joinLabelColumn:r,joinFkColumn:s}){const o=Ce(),a=Pe().findTable(n),l=si(n,r,s,a?.columns),u=Xt(a?.columns.find(b=>b.name===s)),{data:d}=me.useQuery({queryKey:["fkLookup",n,r,s],queryFn:()=>o.query(l),staleTime:300*1e3,enabled:!!a&&!!l}),p=d?.[n]?.data??[],m=e.getFilterValue(),h=m?.operator==="_eq"&&m.value!=null?String(m.value):"all",x=b=>{if(b==="all"){e.setFilterValue(void 0);return}e.setFilterValue({operator:"_eq",value:Xe(b,u)})},g=()=>{e.setFilterValue(void 0)};return t.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[t.jsxs(Le,{value:h,onValueChange:x,children:[t.jsx(Ae,{size:"sm",className:"w-full text-xs",children:t.jsx(Oe,{})}),t.jsxs(qe,{children:[t.jsx(ge,{value:"all",children:"All"}),p.map(b=>t.jsx(ge,{value:String(b.id),children:String(b.label)},String(b.id)))]})]}),m!==void 0&&t.jsxs(W,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:g,children:[t.jsx(N.X,{className:"size-3"}),"Clear filter"]})]})}function en(e){return(e.columnDef.meta?.paramType??"").replace("!","")}function ai(e){return en(e)==="String"}function ii(e){const n=en(e);return n==="Int"||n==="Float"}function li(e){return en(e)==="DateTime"}function ci(e){return en(e)==="Boolean"}function di(e){const n=e.columnDef.meta;return n?.joinTable?{joinTable:n.joinTable,joinLabelColumn:n.joinLabelColumn??"id",joinFkColumn:n.joinFkColumn??"id",isSelfReference:n.isSelfReference===!0}:null}function ui(e){return e.columnDef.meta?.column}function ns(e){const n=e.paramType.replace("!","");if(e.dbType){const r=e.dbType.toUpperCase();return e.maxLength&&(r.includes("VARCHAR")||r.includes("CHAR"))?`${r}(${e.maxLength})`:(r.includes("DECIMAL")||r.includes("NUMERIC"),r)}return n}function mi(e){const n=e.paramType.replace("!","");return e.isPrimaryKey?t.jsx(N.Key,{className:"size-3.5"}):n==="Int"||n==="Float"?t.jsx(N.Hash,{className:"size-3.5"}):n==="DateTime"?t.jsx(N.Calendar,{className:"size-3.5"}):n==="Boolean"?t.jsx(N.ToggleLeft,{className:"size-3.5"}):t.jsx(N.Type,{className:"size-3.5"})}function fi({column:e,fkMeta:n}){const r=ns(e),s=e.isNullable,o=e.isPrimaryKey,i=e.isIdentity,a=e.defaultValue;return t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2 border-b pb-2",children:[mi(e),t.jsx("span",{className:"font-semibold text-foreground",children:e.label})]}),t.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:[t.jsx("dt",{className:"text-muted-foreground",children:"Type"}),t.jsx("dd",{className:"text-foreground font-medium",children:r}),t.jsx("dt",{className:"text-muted-foreground",children:"Nullable"}),t.jsx("dd",{className:"text-foreground",children:s?"Yes":"No"}),o&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Primary Key"}),t.jsxs("dd",{className:"text-foreground text-primary flex items-center gap-1",children:[t.jsx(N.Key,{className:"size-3"}),"Yes"]})]}),i&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Auto Increment"}),t.jsx("dd",{className:"text-foreground",children:"Yes"})]}),n&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Foreign Key"}),t.jsxs("dd",{className:"text-foreground text-primary flex items-center gap-1",children:[t.jsx(N.Link2,{className:"size-3"}),n.joinTable,n.isSelfReference&&t.jsx("span",{className:"ml-1 px-1 rounded bg-primary/10 text-[10px] font-medium",children:"self-ref"})]})]}),a!=null&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Default"}),t.jsx("dd",{className:"text-foreground font-mono text-xs truncate max-w-[150px]",children:String(a)})]}),e.maxLength!==void 0&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Max Length"}),t.jsx("dd",{className:"text-foreground",children:e.maxLength})]}),e.min!==void 0&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Min"}),t.jsx("dd",{className:"text-foreground",children:e.min})]}),e.max!==void 0&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Max"}),t.jsx("dd",{className:"text-foreground",children:e.max})]})]})]})}function yt({column:e,table:n,title:r}){const s=n.options.meta?.onResetColumnWidths;if(!e.getCanSort())return t.jsx("span",{children:r});const o=e.getIsSorted(),i=e.getFilterValue()!==void 0,a=di(e),l=!a&&ai(e),u=!a&&ii(e),d=!a&&li(e),p=!a&&ci(e),m=ui(e),h=t.jsxs(W,{variant:"ghost",size:"sm",className:H("-ml-2 h-7 text-xs data-[state=open]:bg-accent",o&&"text-foreground"),children:[t.jsx("span",{children:r}),i&&t.jsx(N.Filter,{className:"size-3 text-primary"}),o==="desc"?t.jsx(N.ArrowDown,{className:"size-4"}):o==="asc"?t.jsx(N.ArrowUp,{className:"size-4"}):t.jsx(N.ArrowUpDown,{className:"size-4"})]});return t.jsxs(Mt,{openDelay:400,closeDelay:200,children:[t.jsxs(Yr,{children:[t.jsx(Rr,{asChild:!0,children:t.jsx(It,{asChild:!0,children:h})}),t.jsxs(Xr,{align:"start",children:[m&&t.jsxs(t.Fragment,{children:[t.jsxs(Wa,{className:"text-xs font-normal text-muted-foreground",children:[ns(m),m.isNullable?" · nullable":" · required",m.isPrimaryKey?" · PK":"",a?` · FK → ${a.joinTable}`:""]}),t.jsx(Ue,{})]}),t.jsxs(zt,{onClick:()=>e.toggleSorting(!1),children:[t.jsx(N.ArrowUp,{className:"size-3.5 text-muted-foreground"}),"Asc"]}),t.jsxs(zt,{onClick:()=>e.toggleSorting(!0),children:[t.jsx(N.ArrowDown,{className:"size-3.5 text-muted-foreground"}),"Desc"]}),o&&t.jsxs(zt,{onClick:()=>e.clearSorting(),children:[t.jsx(N.ArrowUpDown,{className:"size-3.5 text-muted-foreground"}),"Clear"]}),l&&t.jsxs(t.Fragment,{children:[t.jsx(Ue,{}),t.jsxs(Et,{children:[t.jsxs(Pt,{children:[t.jsx(N.Filter,{className:H("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),t.jsx(Dt,{children:t.jsx(Ra,{column:e})})]})]}),u&&t.jsxs(t.Fragment,{children:[t.jsx(Ue,{}),t.jsxs(Et,{children:[t.jsxs(Pt,{children:[t.jsx(N.Filter,{className:H("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),t.jsx(Dt,{children:t.jsx(Za,{column:e})})]})]}),d&&t.jsxs(t.Fragment,{children:[t.jsx(Ue,{}),t.jsxs(Et,{children:[t.jsxs(Pt,{children:[t.jsx(N.Filter,{className:H("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),t.jsx(Dt,{children:t.jsx(ei,{column:e})})]})]}),p&&t.jsxs(t.Fragment,{children:[t.jsx(Ue,{}),t.jsxs(Et,{children:[t.jsxs(Pt,{children:[t.jsx(N.Filter,{className:H("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),t.jsx(Dt,{children:t.jsx(ri,{column:e})})]})]}),a&&t.jsxs(t.Fragment,{children:[t.jsx(Ue,{}),t.jsxs(Et,{children:[t.jsxs(Pt,{children:[t.jsx(N.Filter,{className:H("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),t.jsx(Dt,{children:t.jsx(oi,{column:e,joinTable:a.joinTable,joinLabelColumn:a.joinLabelColumn,joinFkColumn:a.joinFkColumn})})]})]}),e.getCanHide()&&t.jsxs(t.Fragment,{children:[t.jsx(Ue,{}),t.jsxs(zt,{onClick:()=>e.toggleVisibility(!1),children:[t.jsx(N.EyeOff,{className:"size-3.5 text-muted-foreground"}),"Hide"]})]}),s&&t.jsxs(t.Fragment,{children:[t.jsx(Ue,{}),t.jsxs(zt,{onClick:s,children:[t.jsx(N.RotateCcw,{className:"size-3.5 text-muted-foreground"}),"Reset column widths"]})]})]})]}),m&&t.jsx(Lt,{align:"start",className:"w-64",children:t.jsx(fi,{column:m,fkMeta:a})})]})}function vt({kind:e}){return t.jsx("span",{className:"text-muted-foreground/60 italic select-none",children:e==="null"?"NULL":"empty"})}const pi="display-format",hi="display-format-preview",xi=new Set(["date","datetime","time","relative","number","percent","raw"]);function gi(e){return{param:(e.paramType??"").replace("!","").toLowerCase(),db:(e.dbType??"").toLowerCase()}}function bi({param:e,db:n}){return e==="date"||n==="date"}function yi({param:e,db:n}){return e==="datetime"||e==="datetimeoffset"||n.includes("datetime")||n==="timestamp"||n==="smalldatetime"}function rs(e,n){const s=(n?e.metadata?.[n]:void 0)??e.metadata?.[pi];if(typeof s=="string"&&xi.has(s.toLowerCase()))return s.toLowerCase();const o=gi(e);return yi(o)?"datetime":bi(o)?"date":null}function vi(e){if(e instanceof Date)return isNaN(e.getTime())?null:e;if(typeof e=="number"){const n=new Date(e);return isNaN(n.getTime())?null:n}if(typeof e=="string"){const n=new Date(e);return isNaN(n.getTime())?null:n}return null}const ji=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"}),Ni=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}),wi=new Intl.DateTimeFormat(void 0,{timeStyle:"short"}),Ci=new Intl.DateTimeFormat(void 0,{dateStyle:"full",timeStyle:"medium"}),ss=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),ki=[["year",31536e3],["month",2592e3],["week",604800],["day",86400],["hour",3600],["minute",60],["second",1]];function Ti(e,n=new Date){const r=Math.round((e.getTime()-n.getTime())/1e3),s=Math.abs(r);for(const[o,i]of ki)if(s>=i||o==="second")return ss.format(Math.round(r/i),o);return ss.format(0,"second")}function tn(e,n,r){if(e==null)return t.jsx(vt,{kind:"null"});if(e==="")return t.jsx(vt,{kind:"empty"});const s=rs(n,r?.formatKey);if(s===null||s==="raw")return String(e);if(s==="date"||s==="datetime"||s==="time"||s==="relative"){const o=vi(e);if(!o)return String(e);const i=Ci.format(o);if(s==="relative")return t.jsx("span",{title:i,className:"cursor-help underline decoration-dotted decoration-muted-foreground/40 underline-offset-2",children:Ti(o)});const a=(s==="date"?ji:s==="time"?wi:Ni).format(o);return t.jsx("span",{title:i,children:a})}if(s==="number"||s==="percent"){const o=typeof e=="number"?e:Number(e);if(isNaN(o))return String(e);const i=s==="percent"?new Intl.NumberFormat(void 0,{style:"percent",maximumFractionDigits:2}).format(o):new Intl.NumberFormat(void 0).format(o);return t.jsx("span",{title:String(e),children:i})}return String(e)}const Si=5,$i=400,_i=200;function Fi(e){return e.filter(n=>!n.isPrimaryKey).slice(0,Si)}function zi(e,n,r,s){const o=n.map(i=>i.name).join(" ");return`query FkPreview($id: ${s}) { ${e}(filter: { ${r}: { _eq: $id } } limit: 1) { data { ${o} } } }`}function Ei(e,n,r,s){const o=n.map(i=>i.name).join(" ");return`query FkPreview(${r}) { ${e}(filter: ${s} limit: 1) { data { ${o} } } }`}function Pi(e,n,r,s,o,i,a){if(r.length===0)return null;if(s&&it(s)&&o){const p=ua(o,s,n);if(!p)return null;const m=p.params.join(", ");return{query:Ei(e,r,m,p.filterText),variables:p.variables,cacheKey:p.variables}}const l=n.columns.find(p=>p.name===a)?.paramType??"Int",u=qr(l),d={id:Xe(i,u)};return{query:zi(e,r,a,u),variables:d,cacheKey:`${a}:${i}`}}function Di({tableName:e,recordId:n,filterColumn:r,join:s,sourceRow:o,children:i}){const[a,l]=c.useState(!1),u=Pe(),d=Ce(),p=u.findTable(e),m=p?Fi(p.columns):[],h=p?Pi(e,p,m,s,o,n,r):null,{data:x,isLoading:g}=me.useQuery({queryKey:["fkPreview",e,h?.cacheKey],queryFn:()=>d.query(h.query,h.variables),enabled:a&&!!h,staleTime:300*1e3}),b=x?.[e]?.data?.[0];return t.jsxs(Mt,{openDelay:$i,closeDelay:_i,open:a,onOpenChange:l,children:[t.jsx(It,{asChild:!0,children:i}),t.jsx(Lt,{align:"start",className:"w-72",children:t.jsxs("div",{className:"space-y-2",children:[t.jsx("p",{className:"text-sm font-semibold text-foreground",children:p?.label??e}),g&&t.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading..."}),b&&t.jsx("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:m.map(k=>t.jsxs("div",{className:"contents",children:[t.jsx("dt",{className:"text-muted-foreground truncate",children:k.label}),t.jsx("dd",{className:"text-foreground truncate",children:tn(b[k.name],k,{formatKey:hi})})]},k.name))}),!g&&!b&&a&&t.jsx("p",{className:"text-xs text-muted-foreground",children:"Record not found"})]})})]})}const Mi={json:N.Braces,xml:N.Code,"php-serialized":N.Database,binary:N.Binary,longtext:N.FileText,text:N.FileText},Ii={json:"JSON",xml:"XML","php-serialized":"PHP",binary:"Binary",longtext:"Text",text:"Text"};function Li(e,n){if(n==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return e}function Oi({value:e,dbType:n,onExpand:r}){if(e==null)return t.jsx(vt,{kind:"null"});const s=typeof e=="object"?JSON.stringify(e):String(e);if(s==="")return t.jsx(vt,{kind:"empty"});const o=Nn(s,n);if(o==="text")return t.jsx("span",{children:s});if(o==="binary")return t.jsxs("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[t.jsx(N.Binary,{className:"size-3.5"}),t.jsx("span",{className:"text-xs font-mono",children:ya(s)}),r&&t.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:u=>{u.stopPropagation(),r()},"aria-label":"Expand content",children:t.jsx(N.Expand,{className:"size-3"})})]});const i=Mi[o],a=ba(s);return s.length>80||o==="json"||o==="xml"||o==="php-serialized"?t.jsxs(Mt,{openDelay:300,closeDelay:200,children:[t.jsx(It,{asChild:!0,children:t.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 text-left hover:text-primary transition-colors max-w-full",children:[t.jsx(i,{className:"size-3 text-muted-foreground shrink-0"}),t.jsx("span",{className:"font-mono text-xs truncate",children:a}),r&&t.jsx("span",{role:"button",tabIndex:0,className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:u=>{u.stopPropagation(),u.preventDefault(),r()},onKeyDown:u=>{u.key==="Enter"&&(u.stopPropagation(),r())},"aria-label":"Expand content",children:t.jsx(N.Expand,{className:"size-3"})})]})}),t.jsxs(Lt,{side:"bottom",align:"start",className:"w-[420px] max-h-[320px] p-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 border-b border-border bg-muted/30",children:[t.jsx(i,{className:"size-3.5 text-muted-foreground"}),t.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:Ii[o]}),t.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:[s.length," chars"]})]}),t.jsx("pre",{className:"p-3 text-xs font-mono overflow-auto max-h-[280px] whitespace-pre-wrap break-all",children:Li(s,o)})]})]}):t.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[t.jsx(i,{className:"size-3 text-muted-foreground shrink-0"}),t.jsx("span",{className:"font-mono text-xs",children:s}),r&&t.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:u=>{u.stopPropagation(),r()},"aria-label":"Expand content",children:t.jsx(N.Expand,{className:"size-3"})})]})}function os(e,n){return e?!n||(n.primaryKeys?.length??0)<=1?xt([e?.id]):_t(e,n,0):""}function Ai(e,n){const r=Math.max(0,n-1);return e<0?0:e>r?r:e}function as(e,n){return Br(e)===n?e:Kr(n)}function qi(e,n){const r=n.fieldName??n.destinationTable;return e[r]?.data??[]}function Vi(e,n){const r=n.fieldName??n.destinationTable,s=e[r];return s?.total??s?.data?.length??0}const Bi=(e,n,r,s)=>{if(!e||!n)return[];const o=e.columns.map(a=>{const l=e.singleJoins.find(m=>m.sourceColumnNames?.[0]===a.name),u=l?void 0:e.singleJoins.find(m=>(m.sourceColumnNames??[]).includes(a.name)),d=Lr(a.paramType);if(l){const m=l.destinationTable,h=n.findTable(l.destinationTable),x=h?.labelColumn??"id",g=it(l),b=l.destinationTable===e.name,k=b?`Parent ${a.label}`:a.label;return{id:a.name,accessorKey:a.name,header:({column:$,table:w})=>t.jsx(yt,{column:$,table:w,title:k}),enableSorting:!0,meta:{sortField:a.name,paramType:a.paramType,filterOperators:d,joinTable:l.destinationTable,joinLabelColumn:x,joinFkColumn:l.destinationColumnNames[0],column:a,isSelfReference:b,isCompositeFk:g},cell:({row:$})=>{const w=$.original[m];if(!w)return t.jsx(vt,{kind:"null"});const P=os(w,h);return t.jsxs("span",{className:"group/fk inline-flex items-center gap-0.5",children:[t.jsx(Di,{tableName:l.destinationTable,recordId:P,filterColumn:l.destinationColumnNames[0],join:l,sourceRow:$.original,children:t.jsx(St,{to:"/"+h?.name+"/"+P,className:"text-primary hover:text-primary/80 hover:underline",children:w?.label})}),s&&t.jsx(W,{variant:"ghost",size:"icon-sm",className:"opacity-0 group-hover/fk:opacity-100 size-5 shrink-0",onClick:C=>{C.stopPropagation(),s({tableName:l.destinationTable,filterId:P})},"aria-label":"Open in side column",title:"Open in side column",children:t.jsx(N.PanelRight,{className:"size-3"})})]})}}}if(u){const h=n.findTable(u.destinationTable)?.labelColumn??"id",x=u.destinationTable===e.name;return{id:a.name,accessorFn:g=>a.name?String(g?.[a.name]??""):"",cell:({row:g})=>tn(g.original[a.name],a),header:({column:g,table:b})=>t.jsx(yt,{column:g,table:b,title:a.label}),enableSorting:!0,meta:{sortField:a.name,paramType:a.paramType,dbType:a.dbType,filterOperators:d,joinTable:u.destinationTable,joinLabelColumn:h,joinFkColumn:u.destinationColumnNames[(u.sourceColumnNames??[]).indexOf(a.name)]??u.destinationColumnNames[0],column:a,isSelfReference:x,isCompositeFk:!0,isCompositeFkMember:!0}}}return a?.joinTable?{id:a.name,accessorKey:a.name,header:({column:m,table:h})=>t.jsx(yt,{column:m,table:h,title:a.label}),enableSorting:!0,meta:{sortField:a.name,paramType:a.paramType,filterOperators:d,column:a},cell:({row:m})=>{const h=m.original[a.name];return h?t.jsx(St,{to:"/"+a.name+"/"+os(h,void 0),className:"text-primary hover:text-primary/80 hover:underline",children:a.name}):null}}:a?.paramType==="DateTime"?{id:a.name,accessorFn:m=>Ar(m?.[a.name]),cell:({row:m})=>{const h=m.original[a.name];return h==null||h===""?t.jsx(vt,{kind:h===""?"empty":"null"}):Ar(h)},header:({column:m,table:h})=>t.jsx(yt,{column:m,table:h,title:a.label}),enableSorting:!0,meta:{sortField:a.name,paramType:a.paramType,dbType:a.dbType,filterOperators:d,column:a}}:Ft(a.dbType)||bt(a.dbType)||lt(a)?{id:a.name,accessorFn:m=>a.name?String(m?.[a.name]??""):"",header:({column:m,table:h})=>t.jsx(yt,{column:m,table:h,title:a.label}),enableSorting:!0,meta:{sortField:a.name,paramType:a.paramType,dbType:a.dbType,filterOperators:d,column:a},cell:({row:m})=>t.jsx(Oi,{value:m.original[a.name],dbType:a.dbType,onExpand:r?()=>r(m.index,a.name):void 0})}:{id:a.name,accessorFn:m=>a.name?String(m?.[a.name]??""):"",cell:({row:m})=>tn(m.original[a.name],a),header:({column:m,table:h})=>t.jsx(yt,{column:m,table:h,title:a.label}),enableSorting:!0,meta:{sortField:a.name,paramType:a.paramType,dbType:a.dbType,filterOperators:d,column:a}}}),i=e.multiJoins.map(a=>{const l=n.findTable(a.destinationTable),u=l?.labelColumn??"id",p=a.destinationTable===e.name?`Child ${l?.label??a.destinationTable}`:l?.label??a.destinationTable;return{id:`join_${a.fieldName??a.destinationTable}`,header:p,enableSorting:!1,enableHiding:!0,cell:({row:m})=>{const h=Ca(m.original,e,m.index),x=qi(m.original,a),g=Vi(m.original,a);if(g===0)return t.jsx("span",{className:"text-muted-foreground",children:"—"});const b=x.slice(0,10).map($=>String($[u]??"")).filter(Boolean),k=l?.label??a.destinationTable;return t.jsxs("span",{className:"group/fk inline-flex items-center gap-1",children:[t.jsxs(Mt,{openDelay:300,closeDelay:100,children:[t.jsx(It,{asChild:!0,children:t.jsxs(St,{to:"/"+l?.name+"/from/"+e.name+"/"+h,className:"inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs font-medium text-primary hover:bg-muted hover:border-primary/40 transition-colors",children:[t.jsx(N.List,{className:"size-3"}),g]})}),t.jsxs(Lt,{align:"start",sideOffset:6,className:"w-auto max-w-xs p-3",children:[t.jsxs("div",{className:"flex items-center gap-2 border-b pb-2 mb-2",children:[t.jsx(N.List,{className:"size-3.5 text-primary"}),t.jsxs("span",{className:"text-xs font-semibold text-foreground",children:[g," ",k]})]}),t.jsxs("ul",{className:"space-y-0.5 text-xs text-foreground",children:[b.map(($,w)=>t.jsx("li",{className:"truncate",children:$},w)),g>10&&t.jsxs("li",{className:"text-muted-foreground italic",children:["… and ",g-10," more"]})]})]})]}),s&&t.jsx(W,{variant:"ghost",size:"icon-sm",className:"opacity-40 group-hover/fk:opacity-100 size-5 shrink-0 transition-opacity",onClick:$=>{$.stopPropagation(),s({tableName:a.destinationTable,filterTable:e.name,filterId:h,...it(a)?{}:{filterColumn:a.destinationColumnNames[0]}})},"aria-label":"Open in side column",title:"Open in side column",children:t.jsx(N.PanelRight,{className:"size-3"})})]})}}});return[...o,...i]};function Ki(e,n,r,s,o){if(!s&&!o)return Cn(e,n);const i=kn(n,r,s,o);return i?Cn(e,i.parentTable):Cn(e,n)}function Gi(e,n,r,s,o,i){const{search:a}=er(),l=Wt(),u=a.get("filter")??"",d=a.get("cf")??"",{variables:p}=Or(u),m=Pe(),h=Ce(),[x,g]=c.useState([]),[b,k]=c.useState(()=>Kr(d)),[$,w]=c.useState(0),[P,C]=c.useState(50),T=c.useRef(e);e&&e!==T.current&&(T.current=e,x.length>0&&g([]),$!==0&&w(0)),c.useEffect(()=>{k(J=>as(J,d))},[d]);const j=c.useMemo(()=>as(b,d),[b,d]),E=c.useMemo(()=>{if(!e)return"id";const J=Qe(e)[0]?.name;return J&&e.columns.some(R=>R.name===J)?J:e.columns.find(R=>!bt(R.dbType)&&!Ft(R.dbType)&&!lt(R))?.name??e.columns.at(0)?.name??"id"},[e]),y=c.useMemo(()=>{if(x.length>0&&e){const J=x[0];if(e.columns.some(R=>R.name===J.id))return[`${J.id}_${J.desc?"desc":"asc"}`]}return e?[`${E}_asc`]:[]},[x,e,E]),S=c.useMemo(()=>$a(e,m,u,j,n,r,s),[e,m,u,j,n,r,s]),L=c.useMemo(()=>e?Vr(j,e).variables:{},[j,e]),v=$*P,M=c.useMemo(()=>({sort:y,limit:P,offset:v,...n&&e?Ki(n,e,m,r,s):{},...p,...L}),[y,P,v,n,e,m,r,s,p,L]),{isLoading:O,error:z,data:I}=me.useQuery({queryKey:["tableData",e?.name,S,M],queryFn:({signal:J})=>h.query(S,M,{signal:J}),enabled:!!S&&!!e&&y.length>0,placeholderData:(J,ce)=>ce?.queryKey?.[1]===e?.name?J:void 0}),_=c.useMemo(()=>e?Bi(e,m,o,i):[],[e,m,o,i]),G=c.useMemo(()=>n&&(r||s)&&e?kn(e,m,r,s):null,[n,r,s,e,m]);let U,ie;if(G&&!Wr(G.childJoin)){const J=za(I,G.parentTable.name,G.childField);U=J.data,ie=J.total}else{const J=I?.[e?.name??""];U=J?.data??[],ie=J?.total??0}const B=Math.max(1,Math.ceil(ie/P));c.useEffect(()=>{const J=Ai($,B);J!==$&&w(J)},[$,B]);const Te=c.useCallback(J=>{const ce=new URLSearchParams(a),R=Br(J);R?ce.set("cf",R):ce.delete("cf");const Ne=ce.toString();l(Ne?`?${Ne}`:"?")},[a,l]),ye=c.useCallback(J=>{g(J),w(0)},[]),xe=c.useCallback(J=>{k(J),w(0),Te(J)},[Te]),le=c.useCallback(J=>{w(J)},[]),re=c.useCallback(J=>{C(J),w(0)},[]),ae=e?.primaryKeys??[];return{columns:_,sorting:x,columnFilters:b,primaryKeys:ae,pageIndex:$,pageSize:P,pageCount:B,rows:U,loading:O,error:z,onSortingChange:ye,onColumnFiltersChange:xe,onPageIndexChange:le,onPageSizeChange:re}}const Ji=new Set(["tableData","editRecord","tableRowCounts","m2mRows","fkPreview"]),Wi=new Set(["tableRef","tableRefValue","compositeTableRef","m2mTargets"]);function nn(e,n){return e.invalidateQueries({predicate:r=>{const[s,o]=r.queryKey;return typeof s!="string"?!1:Ji.has(s)?!0:Wi.has(s)?o===n:!1}})}const is=c.createContext({toast:()=>{}}),Hi=4e3;function Qi({children:e}){const[n,r]=c.useState([]),s=c.useRef(0),o=c.useRef(new Set),i=c.useCallback(u=>{r(d=>d.filter(p=>p.id!==u))},[]),a=c.useCallback((u,d="success")=>{const p=s.current++;r(h=>[...h,{id:p,message:u,variant:d}]);const m=setTimeout(()=>{i(p),o.current.delete(m)},Hi);o.current.add(m)},[i]);c.useEffect(()=>{const u=o.current;return()=>{u.forEach(clearTimeout)}},[]);const l=c.useMemo(()=>({toast:a}),[a]);return t.jsxs(is.Provider,{value:l,children:[e,t.jsx("div",{className:"fixed bottom-4 right-4 z-[100] flex flex-col gap-2 max-w-sm",role:"region","aria-label":"Notifications",children:n.map(u=>t.jsxs("div",{role:"status",className:H("flex items-start gap-2 rounded-md border px-3 py-2 text-sm shadow-md bg-popover",u.variant==="error"?"border-destructive/40 text-destructive":"border-border text-foreground"),children:[u.variant==="error"?t.jsx(N.AlertCircle,{className:"size-4 shrink-0 mt-0.5"}):t.jsx(N.CheckCircle2,{className:"size-4 shrink-0 mt-0.5 text-green-600"}),t.jsx("span",{className:"flex-1 break-words",children:u.message}),t.jsx("button",{type:"button",onClick:()=>i(u.id),"aria-label":"Dismiss notification",className:"shrink-0 opacity-60 hover:opacity-100",children:t.jsx(N.X,{className:"size-3.5"})})]},u.id))})]})}function rn(){return c.useContext(is)}function Yi(e){return typeof e=="object"&&e!==null}function ls(e,n){if(e==null)return null;if(!n)return e;const r=n.replace("!","");if(r==="Int"){const s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?Math.trunc(s):e}if(r==="Float"){const s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?s:e}return r==="Boolean"?typeof e=="boolean"?e:e==="true"||e===1:String(e)}function cs(e){Fe(e.name,"delete mutation table name");const n=Ce(),r=me.useQueryClient(),{toast:s}=rn(),o=c.useMemo(()=>{const g=new Map;for(const b of e.columns)g.set(b.name,b.paramType);return g},[e]),i=c.useMemo(()=>e.primaryKeys??[],[e]),a=g=>{if(i.length===0)throw new Error(`Cannot delete from '${e.name}': the table has no primary key.`);const b={};if(Yi(g)){for(const $ of i){const w=g[$];if(w==null)throw new Error(`Cannot delete row: missing value for primary-key column '${$}'.`);b[$]=ls(w,o.get($))}return b}if(i.length!==1)throw new Error(`Cannot delete from '${e.name}': composite primary key requires an object key, not a scalar.`);if(g==null)throw new Error(`Cannot delete row: missing value for primary-key column '${i[0]}'.`);const k=i[0];return b[k]=ls(g,o.get(k)),b},l=c.useMemo(()=>`mutation deleteSingle($detail: Delete_${e.name}){
87
+ }`;class bs extends Error{constructor(t,r){super(t.map(s=>s.message).join("; ")),this.errors=t,this.data=r,this.name="GraphQLRequestError"}errors;data}class ys{constructor(t){this.uri=t}uri;async query(t,r,s){const o=await fetch(this.uri,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:t,variables:r}),signal:s?.signal});if(!o.ok)throw new Error(`GraphQL request failed: ${o.status} ${o.statusText}`);const i=await o.json();if(i.errors?.length)throw new bs(i.errors,i.data);return i.data}}const vs=u.createContext(null),js=vs.Provider;function $e(){const e=u.useContext(vs);if(!e)throw new Error("useFetcher must be used within a FetcherProvider");return e}function Ba(e){const t=e.lastIndexOf(".");return t>=0?e.slice(t+1):e}function Ga(e){return Ba(e).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[_\-\s]+/).filter(Boolean)}function Ka(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}function zn(e){return e&&Ga(e).map(Ka).join(" ")}const Wa={showStats:!1},ws=u.createContext(Wa);function Ja({config:e,children:t}){return n.jsx(ws.Provider,{value:e,children:t})}function cr(){return u.useContext(ws)}const Cs=u.createContext({loading:!0,error:null,data:[],findTable:()=>{}}),Ns=({children:e})=>{const t=Ha();return n.jsx(Cs.Provider,{value:t,children:e})};function Je(){return u.useContext(Cs)}function Qa(e,t){if(!t||t.length===0)return e;const r=new Set(t.map(s=>s.toLowerCase()));return e.filter(s=>r.has(s.graphQlName.toLowerCase())||r.has(s.dbName.toLowerCase()))}function Ha(){const e=$e(),{tables:t}=cr(),{isLoading:r,error:s,data:o}=de.useQuery({queryKey:["dbSchema"],queryFn:()=>e.query(Va),staleTime:1/0});return u.useMemo(()=>{if(r)return{loading:!0,error:null,data:[],findTable:()=>{}};if(s)return{loading:!1,error:{message:s.message},data:[],findTable:()=>{}};if(!o)return{loading:!1,error:null,data:[],findTable:()=>{}};const i=o._dbSchema.map(c=>({...c,name:c.graphQlName,label:zn(c.dbName),metadata:ks(c.metadata),columns:c.columns.map(m=>({...m,name:m.graphQlName,label:zn(m.dbName),metadata:ks(m.metadata),inputType:Xa(m.inputType)}))})),a=Qa(i,t);return{loading:!1,error:null,data:a,findTable:c=>a.find(m=>m.graphQlName===c)}},[r,s,o,t])}function ks(e){return e.reduce((t,r)=>({...t,[r.key]:Ua(r)}),{})}function Ua({key:e,value:t}){return e==="type"?Ya(t):t}function Ya(e){const t=e.match(/lookup\s*\(\s*(?<id>\w+)\s*,\s*(?<label>\w+)\s*\)/m);if(t?.groups?.id&&t?.groups?.label)return{type:"lookup",id:t.groups.id,label:t.groups.label}}const Ra=["text","email","url","tel","date","datetime-local","number","password","search"];function Xa(e){if(e&&Ra.includes(e))return e}function Ss(e){var t,r,s="";if(typeof e=="string"||typeof e=="number")s+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(r=Ss(e[t]))&&(s&&(s+=" "),s+=r)}else for(r in e)e[r]&&(s&&(s+=" "),s+=r);return s}function Ts(){for(var e,t,r=0,s="",o=arguments.length;r<o;r++)(e=arguments[r])&&(t=Ss(e))&&(s&&(s+=" "),s+=t);return s}const $s=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Es=Ts,Fs=(e,t)=>r=>{var s;if(t?.variants==null)return Es(e,r?.class,r?.className);const{variants:o,defaultVariants:i}=t,a=Object.keys(o).map(m=>{const d=r?.[m],f=i?.[m];if(d===null)return null;const p=$s(d)||$s(f);return o[m][p]}),l=r&&Object.entries(r).reduce((m,d)=>{let[f,p]=d;return p===void 0||(m[f]=p),m},{}),c=t==null||(s=t.compoundVariants)===null||s===void 0?void 0:s.reduce((m,d)=>{let{class:f,className:p,...x}=d;return Object.entries(x).every(h=>{let[y,N]=h;return Array.isArray(N)?N.includes({...i,...l}[y]):{...i,...l}[y]===N})?[...m,f,p]:m},[]);return Es(e,a,c,r?.class,r?.className)},Za=(e,t)=>{const r=new Array(e.length+t.length);for(let s=0;s<e.length;s++)r[s]=e[s];for(let s=0;s<t.length;s++)r[e.length+s]=t[s];return r},ei=(e,t)=>({classGroupId:e,validator:t}),_s=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),Dn="-",Ps=[],ti="arbitrary..",ni=e=>{const t=si(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:a=>{if(a.startsWith("[")&&a.endsWith("]"))return ri(a);const l=a.split(Dn),c=l[0]===""&&l.length>1?1:0;return zs(l,c,t)},getConflictingClassGroupIds:(a,l)=>{if(l){const c=s[a],m=r[a];return c?m?Za(m,c):c:m||Ps}return r[a]||Ps}}},zs=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const o=e[t],i=r.nextPart.get(o);if(i){const m=zs(e,t+1,i);if(m)return m}const a=r.validators;if(a===null)return;const l=t===0?e.join(Dn):e.slice(t).join(Dn),c=a.length;for(let m=0;m<c;m++){const d=a[m];if(d.validator(l))return d.classGroupId}},ri=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),r=t.indexOf(":"),s=t.slice(0,r);return s?ti+s:void 0})(),si=e=>{const{theme:t,classGroups:r}=e;return oi(r,t)},oi=(e,t)=>{const r=_s();for(const s in e){const o=e[s];ur(o,r,s,t)}return r},ur=(e,t,r,s)=>{const o=e.length;for(let i=0;i<o;i++){const a=e[i];ai(a,t,r,s)}},ai=(e,t,r,s)=>{if(typeof e=="string"){ii(e,t,r);return}if(typeof e=="function"){li(e,t,r,s);return}ci(e,t,r,s)},ii=(e,t,r)=>{const s=e===""?t:Ds(t,e);s.classGroupId=r},li=(e,t,r,s)=>{if(ui(e)){ur(e(s),t,r,s);return}t.validators===null&&(t.validators=[]),t.validators.push(ei(r,e))},ci=(e,t,r,s)=>{const o=Object.entries(e),i=o.length;for(let a=0;a<i;a++){const[l,c]=o[a];ur(c,Ds(t,l),r,s)}},Ds=(e,t)=>{let r=e;const s=t.split(Dn),o=s.length;for(let i=0;i<o;i++){const a=s[i];let l=r.nextPart.get(a);l||(l=_s(),r.nextPart.set(a,l)),r=l}return r},ui=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,di=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=Object.create(null),s=Object.create(null);const o=(i,a)=>{r[i]=a,t++,t>e&&(t=0,s=r,r=Object.create(null))};return{get(i){let a=r[i];if(a!==void 0)return a;if((a=s[i])!==void 0)return o(i,a),a},set(i,a){i in r?r[i]=a:o(i,a)}}},dr="!",Ms=":",mi=[],Is=(e,t,r,s,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:s,isExternal:o}),fi=e=>{const{prefix:t,experimentalParseClassName:r}=e;let s=o=>{const i=[];let a=0,l=0,c=0,m;const d=o.length;for(let y=0;y<d;y++){const N=o[y];if(a===0&&l===0){if(N===Ms){i.push(o.slice(c,y)),c=y+1;continue}if(N==="/"){m=y;continue}}N==="["?a++:N==="]"?a--:N==="("?l++:N===")"&&l--}const f=i.length===0?o:o.slice(c);let p=f,x=!1;f.endsWith(dr)?(p=f.slice(0,-1),x=!0):f.startsWith(dr)&&(p=f.slice(1),x=!0);const h=m&&m>c?m-c:void 0;return Is(i,x,p,h)};if(t){const o=t+Ms,i=s;s=a=>a.startsWith(o)?i(a.slice(o.length)):Is(mi,!1,a,void 0,!0)}if(r){const o=s;s=i=>r({className:i,parseClassName:o})}return s},pi=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((r,s)=>{t.set(r,1e6+s)}),r=>{const s=[];let o=[];for(let i=0;i<r.length;i++){const a=r[i],l=a[0]==="[",c=t.has(a);l||c?(o.length>0&&(o.sort(),s.push(...o),o=[]),s.push(a)):o.push(a)}return o.length>0&&(o.sort(),s.push(...o)),s}},hi=e=>({cache:di(e.cacheSize),parseClassName:fi(e),sortModifiers:pi(e),postfixLookupClassGroupIds:gi(e),...ni(e)}),gi=e=>{const t=Object.create(null),r=e.postfixLookupClassGroups;if(r)for(let s=0;s<r.length;s++)t[r[s]]=!0;return t},xi=/\s+/,bi=(e,t)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:o,sortModifiers:i,postfixLookupClassGroupIds:a}=t,l=[],c=e.trim().split(xi);let m="";for(let d=c.length-1;d>=0;d-=1){const f=c[d],{isExternal:p,modifiers:x,hasImportantModifier:h,baseClassName:y,maybePostfixModifierPosition:N}=r(f);if(p){m=f+(m.length>0?" "+m:m);continue}let T=!!N,k;if(T){const F=y.substring(0,N);k=s(F);const j=k&&a[k]?s(y):void 0;j&&j!==k&&(k=j,T=!1)}else k=s(y);if(!k){if(!T){m=f+(m.length>0?" "+m:m);continue}if(k=s(y),!k){m=f+(m.length>0?" "+m:m);continue}T=!1}const $=x.length===0?"":x.length===1?x[0]:i(x).join(":"),b=h?$+dr:$,v=b+k;if(l.indexOf(v)>-1)continue;l.push(v);const w=o(k,T);for(let F=0;F<w.length;++F){const j=w[F];l.push(b+j)}m=f+(m.length>0?" "+m:m)}return m},yi=(...e)=>{let t=0,r,s,o="";for(;t<e.length;)(r=e[t++])&&(s=Ls(r))&&(o&&(o+=" "),o+=s);return o},Ls=e=>{if(typeof e=="string")return e;let t,r="";for(let s=0;s<e.length;s++)e[s]&&(t=Ls(e[s]))&&(r&&(r+=" "),r+=t);return r},vi=(e,...t)=>{let r,s,o,i;const a=c=>{const m=t.reduce((d,f)=>f(d),e());return r=hi(m),s=r.cache.get,o=r.cache.set,i=l,l(c)},l=c=>{const m=s(c);if(m)return m;const d=bi(c,r);return o(c,d),d};return i=a,(...c)=>i(yi(...c))},ji=[],_e=e=>{const t=r=>r[e]||ji;return t.isThemeGetter=!0,t},Os=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,As=/^\((?:(\w[\w-]*):)?(.+)\)$/i,wi=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,Ci=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Ni=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,ki=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Si=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Ti=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,St=e=>wi.test(e),oe=e=>!!e&&!Number.isNaN(Number(e)),ct=e=>!!e&&Number.isInteger(Number(e)),mr=e=>e.endsWith("%")&&oe(e.slice(0,-1)),xt=e=>Ci.test(e),qs=()=>!0,$i=e=>Ni.test(e)&&!ki.test(e),fr=()=>!1,Ei=e=>Si.test(e),Fi=e=>Ti.test(e),_i=e=>!K(e)&&!J(e),Pi=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),zi=e=>Tt(e,Js,fr),K=e=>Os.test(e),Ot=e=>Tt(e,Qs,$i),Vs=e=>Tt(e,Vi,oe),Di=e=>Tt(e,Us,qs),Mi=e=>Tt(e,Hs,fr),Bs=e=>Tt(e,Ks,fr),Ii=e=>Tt(e,Ws,Fi),Mn=e=>Tt(e,Ys,Ei),J=e=>As.test(e),ln=e=>At(e,Qs),Li=e=>At(e,Hs),Gs=e=>At(e,Ks),Oi=e=>At(e,Js),Ai=e=>At(e,Ws),In=e=>At(e,Ys,!0),qi=e=>At(e,Us,!0),Tt=(e,t,r)=>{const s=Os.exec(e);return s?s[1]?t(s[1]):r(s[2]):!1},At=(e,t,r=!1)=>{const s=As.exec(e);return s?s[1]?t(s[1]):r:!1},Ks=e=>e==="position"||e==="percentage",Ws=e=>e==="image"||e==="url",Js=e=>e==="length"||e==="size"||e==="bg-size",Qs=e=>e==="length",Vi=e=>e==="number",Hs=e=>e==="family-name",Us=e=>e==="number"||e==="weight",Ys=e=>e==="shadow",Bi=vi(()=>{const e=_e("color"),t=_e("font"),r=_e("text"),s=_e("font-weight"),o=_e("tracking"),i=_e("leading"),a=_e("breakpoint"),l=_e("container"),c=_e("spacing"),m=_e("radius"),d=_e("shadow"),f=_e("inset-shadow"),p=_e("text-shadow"),x=_e("drop-shadow"),h=_e("blur"),y=_e("perspective"),N=_e("aspect"),T=_e("ease"),k=_e("animate"),$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],b=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],v=()=>[...b(),J,K],w=()=>["auto","hidden","clip","visible","scroll"],F=()=>["auto","contain","none"],j=()=>[J,K,c],V=()=>[St,"full","auto",...j()],S=()=>[ct,"none","subgrid",J,K],L=()=>["auto",{span:["full",ct,J,K]},ct,J,K],A=()=>[ct,"auto",J,K],D=()=>["auto","min","max","fr",J,K],B=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],X=()=>["start","end","center","stretch","center-safe","end-safe"],E=()=>["auto",...j()],P=()=>[St,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...j()],q=()=>[St,"screen","full","dvw","lvw","svw","min","max","fit",...j()],U=()=>[St,"screen","full","lh","dvh","lvh","svh","min","max","fit",...j()],_=()=>[e,J,K],ce=()=>[...b(),Gs,Bs,{position:[J,K]}],he=()=>["no-repeat",{repeat:["","x","y","space","round"]}],Ue=()=>["auto","cover","contain",Oi,zi,{size:[J,K]}],Pe=()=>[mr,ln,Ot],ie=()=>["","none","full",m,J,K],se=()=>["",oe,ln,Ot],ke=()=>["solid","dashed","dotted","double"],Ae=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],re=()=>[oe,mr,Gs,Bs],Ee=()=>["","none",h,J,K],Ie=()=>["none",oe,J,K],Le=()=>["none",oe,J,K],Ge=()=>[oe,J,K],Oe=()=>[St,"full",...j()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[xt],breakpoint:[xt],color:[qs],container:[xt],"drop-shadow":[xt],ease:["in","out","in-out"],font:[_i],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[xt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[xt],shadow:[xt],spacing:["px",oe],text:[xt],"text-shadow":[xt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",St,K,J,N]}],container:["container"],"container-type":[{"@container":["","normal","size",J,K]}],"container-named":[Pi],columns:[{columns:[oe,K,J,l]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:v()}],overflow:[{overflow:w()}],"overflow-x":[{"overflow-x":w()}],"overflow-y":[{"overflow-y":w()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:V()}],"inset-x":[{"inset-x":V()}],"inset-y":[{"inset-y":V()}],start:[{"inset-s":V(),start:V()}],end:[{"inset-e":V(),end:V()}],"inset-bs":[{"inset-bs":V()}],"inset-be":[{"inset-be":V()}],top:[{top:V()}],right:[{right:V()}],bottom:[{bottom:V()}],left:[{left:V()}],visibility:["visible","invisible","collapse"],z:[{z:[ct,"auto",J,K]}],basis:[{basis:[St,"full","auto",l,...j()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[oe,St,"auto","initial","none",K]}],grow:[{grow:["",oe,J,K]}],shrink:[{shrink:["",oe,J,K]}],order:[{order:[ct,"first","last","none",J,K]}],"grid-cols":[{"grid-cols":S()}],"col-start-end":[{col:L()}],"col-start":[{"col-start":A()}],"col-end":[{"col-end":A()}],"grid-rows":[{"grid-rows":S()}],"row-start-end":[{row:L()}],"row-start":[{"row-start":A()}],"row-end":[{"row-end":A()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":D()}],"auto-rows":[{"auto-rows":D()}],gap:[{gap:j()}],"gap-x":[{"gap-x":j()}],"gap-y":[{"gap-y":j()}],"justify-content":[{justify:[...B(),"normal"]}],"justify-items":[{"justify-items":[...X(),"normal"]}],"justify-self":[{"justify-self":["auto",...X()]}],"align-content":[{content:["normal",...B()]}],"align-items":[{items:[...X(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...X(),{baseline:["","last"]}]}],"place-content":[{"place-content":B()}],"place-items":[{"place-items":[...X(),"baseline"]}],"place-self":[{"place-self":["auto",...X()]}],p:[{p:j()}],px:[{px:j()}],py:[{py:j()}],ps:[{ps:j()}],pe:[{pe:j()}],pbs:[{pbs:j()}],pbe:[{pbe:j()}],pt:[{pt:j()}],pr:[{pr:j()}],pb:[{pb:j()}],pl:[{pl:j()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mbs:[{mbs:E()}],mbe:[{mbe:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":j()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":j()}],"space-y-reverse":["space-y-reverse"],size:[{size:P()}],"inline-size":[{inline:["auto",...q()]}],"min-inline-size":[{"min-inline":["auto",...q()]}],"max-inline-size":[{"max-inline":["none",...q()]}],"block-size":[{block:["auto",...U()]}],"min-block-size":[{"min-block":["auto",...U()]}],"max-block-size":[{"max-block":["none",...U()]}],w:[{w:[l,"screen",...P()]}],"min-w":[{"min-w":[l,"screen","none",...P()]}],"max-w":[{"max-w":[l,"screen","none","prose",{screen:[a]},...P()]}],h:[{h:["screen","lh",...P()]}],"min-h":[{"min-h":["screen","lh","none",...P()]}],"max-h":[{"max-h":["screen","lh",...P()]}],"font-size":[{text:["base",r,ln,Ot]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,qi,Di]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",mr,K]}],"font-family":[{font:[Li,Mi,t]}],"font-features":[{"font-features":[K]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,J,K]}],"line-clamp":[{"line-clamp":[oe,"none",J,Vs]}],leading:[{leading:[i,...j()]}],"list-image":[{"list-image":["none",J,K]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",J,K]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:_()}],"text-color":[{text:_()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ke(),"wavy"]}],"text-decoration-thickness":[{decoration:[oe,"from-font","auto",J,Ot]}],"text-decoration-color":[{decoration:_()}],"underline-offset":[{"underline-offset":[oe,"auto",J,K]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:j()}],"tab-size":[{tab:[ct,J,K]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",J,K]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",J,K]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:ce()}],"bg-repeat":[{bg:he()}],"bg-size":[{bg:Ue()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ct,J,K],radial:["",J,K],conic:[ct,J,K]},Ai,Ii]}],"bg-color":[{bg:_()}],"gradient-from-pos":[{from:Pe()}],"gradient-via-pos":[{via:Pe()}],"gradient-to-pos":[{to:Pe()}],"gradient-from":[{from:_()}],"gradient-via":[{via:_()}],"gradient-to":[{to:_()}],rounded:[{rounded:ie()}],"rounded-s":[{"rounded-s":ie()}],"rounded-e":[{"rounded-e":ie()}],"rounded-t":[{"rounded-t":ie()}],"rounded-r":[{"rounded-r":ie()}],"rounded-b":[{"rounded-b":ie()}],"rounded-l":[{"rounded-l":ie()}],"rounded-ss":[{"rounded-ss":ie()}],"rounded-se":[{"rounded-se":ie()}],"rounded-ee":[{"rounded-ee":ie()}],"rounded-es":[{"rounded-es":ie()}],"rounded-tl":[{"rounded-tl":ie()}],"rounded-tr":[{"rounded-tr":ie()}],"rounded-br":[{"rounded-br":ie()}],"rounded-bl":[{"rounded-bl":ie()}],"border-w":[{border:se()}],"border-w-x":[{"border-x":se()}],"border-w-y":[{"border-y":se()}],"border-w-s":[{"border-s":se()}],"border-w-e":[{"border-e":se()}],"border-w-bs":[{"border-bs":se()}],"border-w-be":[{"border-be":se()}],"border-w-t":[{"border-t":se()}],"border-w-r":[{"border-r":se()}],"border-w-b":[{"border-b":se()}],"border-w-l":[{"border-l":se()}],"divide-x":[{"divide-x":se()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":se()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ke(),"hidden","none"]}],"divide-style":[{divide:[...ke(),"hidden","none"]}],"border-color":[{border:_()}],"border-color-x":[{"border-x":_()}],"border-color-y":[{"border-y":_()}],"border-color-s":[{"border-s":_()}],"border-color-e":[{"border-e":_()}],"border-color-bs":[{"border-bs":_()}],"border-color-be":[{"border-be":_()}],"border-color-t":[{"border-t":_()}],"border-color-r":[{"border-r":_()}],"border-color-b":[{"border-b":_()}],"border-color-l":[{"border-l":_()}],"divide-color":[{divide:_()}],"outline-style":[{outline:[...ke(),"none","hidden"]}],"outline-offset":[{"outline-offset":[oe,J,K]}],"outline-w":[{outline:["",oe,ln,Ot]}],"outline-color":[{outline:_()}],shadow:[{shadow:["","none",d,In,Mn]}],"shadow-color":[{shadow:_()}],"inset-shadow":[{"inset-shadow":["none",f,In,Mn]}],"inset-shadow-color":[{"inset-shadow":_()}],"ring-w":[{ring:se()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:_()}],"ring-offset-w":[{"ring-offset":[oe,Ot]}],"ring-offset-color":[{"ring-offset":_()}],"inset-ring-w":[{"inset-ring":se()}],"inset-ring-color":[{"inset-ring":_()}],"text-shadow":[{"text-shadow":["none",p,In,Mn]}],"text-shadow-color":[{"text-shadow":_()}],opacity:[{opacity:[oe,J,K]}],"mix-blend":[{"mix-blend":[...Ae(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Ae()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[oe]}],"mask-image-linear-from-pos":[{"mask-linear-from":re()}],"mask-image-linear-to-pos":[{"mask-linear-to":re()}],"mask-image-linear-from-color":[{"mask-linear-from":_()}],"mask-image-linear-to-color":[{"mask-linear-to":_()}],"mask-image-t-from-pos":[{"mask-t-from":re()}],"mask-image-t-to-pos":[{"mask-t-to":re()}],"mask-image-t-from-color":[{"mask-t-from":_()}],"mask-image-t-to-color":[{"mask-t-to":_()}],"mask-image-r-from-pos":[{"mask-r-from":re()}],"mask-image-r-to-pos":[{"mask-r-to":re()}],"mask-image-r-from-color":[{"mask-r-from":_()}],"mask-image-r-to-color":[{"mask-r-to":_()}],"mask-image-b-from-pos":[{"mask-b-from":re()}],"mask-image-b-to-pos":[{"mask-b-to":re()}],"mask-image-b-from-color":[{"mask-b-from":_()}],"mask-image-b-to-color":[{"mask-b-to":_()}],"mask-image-l-from-pos":[{"mask-l-from":re()}],"mask-image-l-to-pos":[{"mask-l-to":re()}],"mask-image-l-from-color":[{"mask-l-from":_()}],"mask-image-l-to-color":[{"mask-l-to":_()}],"mask-image-x-from-pos":[{"mask-x-from":re()}],"mask-image-x-to-pos":[{"mask-x-to":re()}],"mask-image-x-from-color":[{"mask-x-from":_()}],"mask-image-x-to-color":[{"mask-x-to":_()}],"mask-image-y-from-pos":[{"mask-y-from":re()}],"mask-image-y-to-pos":[{"mask-y-to":re()}],"mask-image-y-from-color":[{"mask-y-from":_()}],"mask-image-y-to-color":[{"mask-y-to":_()}],"mask-image-radial":[{"mask-radial":[J,K]}],"mask-image-radial-from-pos":[{"mask-radial-from":re()}],"mask-image-radial-to-pos":[{"mask-radial-to":re()}],"mask-image-radial-from-color":[{"mask-radial-from":_()}],"mask-image-radial-to-color":[{"mask-radial-to":_()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[oe]}],"mask-image-conic-from-pos":[{"mask-conic-from":re()}],"mask-image-conic-to-pos":[{"mask-conic-to":re()}],"mask-image-conic-from-color":[{"mask-conic-from":_()}],"mask-image-conic-to-color":[{"mask-conic-to":_()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:ce()}],"mask-repeat":[{mask:he()}],"mask-size":[{mask:Ue()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",J,K]}],filter:[{filter:["","none",J,K]}],blur:[{blur:Ee()}],brightness:[{brightness:[oe,J,K]}],contrast:[{contrast:[oe,J,K]}],"drop-shadow":[{"drop-shadow":["","none",x,In,Mn]}],"drop-shadow-color":[{"drop-shadow":_()}],grayscale:[{grayscale:["",oe,J,K]}],"hue-rotate":[{"hue-rotate":[oe,J,K]}],invert:[{invert:["",oe,J,K]}],saturate:[{saturate:[oe,J,K]}],sepia:[{sepia:["",oe,J,K]}],"backdrop-filter":[{"backdrop-filter":["","none",J,K]}],"backdrop-blur":[{"backdrop-blur":Ee()}],"backdrop-brightness":[{"backdrop-brightness":[oe,J,K]}],"backdrop-contrast":[{"backdrop-contrast":[oe,J,K]}],"backdrop-grayscale":[{"backdrop-grayscale":["",oe,J,K]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[oe,J,K]}],"backdrop-invert":[{"backdrop-invert":["",oe,J,K]}],"backdrop-opacity":[{"backdrop-opacity":[oe,J,K]}],"backdrop-saturate":[{"backdrop-saturate":[oe,J,K]}],"backdrop-sepia":[{"backdrop-sepia":["",oe,J,K]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":j()}],"border-spacing-x":[{"border-spacing-x":j()}],"border-spacing-y":[{"border-spacing-y":j()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",J,K]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[oe,"initial",J,K]}],ease:[{ease:["linear","initial",T,J,K]}],delay:[{delay:[oe,J,K]}],animate:[{animate:["none",k,J,K]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[y,J,K]}],"perspective-origin":[{"perspective-origin":v()}],rotate:[{rotate:Ie()}],"rotate-x":[{"rotate-x":Ie()}],"rotate-y":[{"rotate-y":Ie()}],"rotate-z":[{"rotate-z":Ie()}],scale:[{scale:Le()}],"scale-x":[{"scale-x":Le()}],"scale-y":[{"scale-y":Le()}],"scale-z":[{"scale-z":Le()}],"scale-3d":["scale-3d"],skew:[{skew:Ge()}],"skew-x":[{"skew-x":Ge()}],"skew-y":[{"skew-y":Ge()}],transform:[{transform:[J,K,"","none","gpu","cpu"]}],"transform-origin":[{origin:v()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Oe()}],"translate-x":[{"translate-x":Oe()}],"translate-y":[{"translate-y":Oe()}],"translate-z":[{"translate-z":Oe()}],"translate-none":["translate-none"],zoom:[{zoom:[ct,J,K]}],accent:[{accent:_()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:_()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",J,K]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":_()}],"scrollbar-track-color":[{"scrollbar-track":_()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":j()}],"scroll-mx":[{"scroll-mx":j()}],"scroll-my":[{"scroll-my":j()}],"scroll-ms":[{"scroll-ms":j()}],"scroll-me":[{"scroll-me":j()}],"scroll-mbs":[{"scroll-mbs":j()}],"scroll-mbe":[{"scroll-mbe":j()}],"scroll-mt":[{"scroll-mt":j()}],"scroll-mr":[{"scroll-mr":j()}],"scroll-mb":[{"scroll-mb":j()}],"scroll-ml":[{"scroll-ml":j()}],"scroll-p":[{"scroll-p":j()}],"scroll-px":[{"scroll-px":j()}],"scroll-py":[{"scroll-py":j()}],"scroll-ps":[{"scroll-ps":j()}],"scroll-pe":[{"scroll-pe":j()}],"scroll-pbs":[{"scroll-pbs":j()}],"scroll-pbe":[{"scroll-pbe":j()}],"scroll-pt":[{"scroll-pt":j()}],"scroll-pr":[{"scroll-pr":j()}],"scroll-pb":[{"scroll-pb":j()}],"scroll-pl":[{"scroll-pl":j()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",J,K]}],fill:[{fill:["none",..._()]}],"stroke-w":[{stroke:[oe,ln,Ot,Vs]}],stroke:[{stroke:["none",..._()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});function Y(...e){return Bi(Ts(e))}const Gi=Fs("relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current"}},defaultVariants:{variant:"default"}});function Rt({className:e,variant:t,...r}){return n.jsx("div",{"data-slot":"alert",role:"alert",className:Y(Gi({variant:t}),e),...r})}function Rs({className:e,...t}){return n.jsx("div",{"data-slot":"alert-title",className:Y("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",e),...t})}function Xt({className:e,...t}){return n.jsx("div",{"data-slot":"alert-description",className:Y("col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed",e),...t})}const Qe=Ve.forwardRef(({className:e,type:t,...r},s)=>n.jsx("input",{type:t,ref:s,"data-slot":"input",className:Y("h-9 w-full min-w-0 rounded-md border border-input bg-transparent text-foreground px-3 py-0 text-sm shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...r}));Qe.displayName="Input";function Ln({...e}){return n.jsx(R.DropdownMenu.Root,{"data-slot":"dropdown-menu",...e})}function On({...e}){return n.jsx(R.DropdownMenu.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function An({className:e,sideOffset:t=4,...r}){return n.jsx(R.DropdownMenu.Portal,{children:n.jsx(R.DropdownMenu.Content,{"data-slot":"dropdown-menu-content",sideOffset:t,className:Y("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...r})})}function bt({className:e,inset:t,variant:r="default",...s}){return n.jsx(R.DropdownMenu.Item,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":r,className:Y("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...s})}function Ki({className:e,children:t,checked:r,...s}){return n.jsxs(R.DropdownMenu.CheckboxItem,{"data-slot":"dropdown-menu-checkbox-item",className:Y("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),checked:r,...s,children:[n.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:n.jsx(R.DropdownMenu.ItemIndicator,{children:n.jsx(C.CheckIcon,{className:"size-4"})})}),t]})}function Wi({className:e,inset:t,...r}){return n.jsx(R.DropdownMenu.Label,{"data-slot":"dropdown-menu-label","data-inset":t,className:Y("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...r})}function yt({className:e,...t}){return n.jsx(R.DropdownMenu.Separator,{"data-slot":"dropdown-menu-separator",className:Y("-mx-1 my-1 h-px bg-border",e),...t})}function cn({...e}){return n.jsx(R.DropdownMenu.Sub,{"data-slot":"dropdown-menu-sub",...e})}function un({className:e,inset:t,children:r,...s}){return n.jsxs(R.DropdownMenu.SubTrigger,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:Y("flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...s,children:[r,n.jsx(C.ChevronRightIcon,{className:"ml-auto size-4"})]})}function dn({className:e,...t}){return n.jsx(R.DropdownMenu.SubContent,{"data-slot":"dropdown-menu-sub-content",className:Y("z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})}function ut(e){return(e??"").replace("!","")}const Xs=new Set(["Int","Short","Byte","BigInt"]),Ji=new Set(["Float","Decimal"]),Qi=new Set(["DateTime","DateTimeOffset"]),Hi=new Set(["BigInt","Decimal"]);function qt(e){return Xs.has(ut(e))}function Vt(e){const t=ut(e);return Xs.has(t)||Ji.has(t)}function Bt(e){return Hi.has(ut(e))}function Zs(e){return Qi.has(ut(e))}function Ui(e){return ut(e)==="String"}function eo(e,t){const r=e.trim();if(r===""||r==="-"||r==="+"||!(qt(t)?/^[+-]?\d+$/.test(r):/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(r)))return null;if(Bt(t))return r;const o=Number(r);return Number.isFinite(o)?o:null}function dt(e,t){if(e==null)return null;if(Bt(t))return String(e);if(qt(t)){const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.trunc(r):e}switch(ut(t)){case"Float":{const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:e}case"Boolean":return typeof e=="boolean"?e:e==="true"||e===1?!0:e==="false"||e===0?!1:!!e;default:return String(e)}}function mn(e){return e?.paramType?.replace("!","")??"String"}function Gt(e){return(e.sourceColumnNames?.length??0)>1}function Yi(e,t){const r=(e.sourceColumnNames??[]).indexOf(t);return r<0?null:(e.destinationColumnNames??[])[r]??null}function Ri(e,t,r,s="fk"){if(!e)return null;const o=t.sourceColumnNames??[],i=t.destinationColumnNames??[];if(o.length===0||o.length!==i.length)return null;const a=new Map((r?.columns??[]).map(f=>[f.name,f])),l=[],c={},m=[];for(let f=0;f<o.length;f++){const p=o[f],x=i[f];if(!(p in e))return null;const h=mn(a.get(x)),y=`${s}_${x}`;c[y]=dt(e[p],h),m.push(`$${y}: ${h}`),l.push(`{${x}: {_eq: $${y}}}`)}return{filterText:l.length===1?l[0]:`{and: [${l.join(", ")}]}`,variables:c,params:m}}const pr="::";function Xi(e){return e==null?"":encodeURIComponent(String(e))}function hr(e){if(e==="")return null;try{return decodeURIComponent(e)}catch{return e}}function $t(e){return e.map(Xi).join(pr)}function to(e,t){const r=t<=1?[e]:e.split(pr);if(r.length!==t)throw new Error(`Route id '${e}' has ${r.length} part(s) but ${t} were expected.`);return r.map(s=>s===""?"":hr(s)??"")}function He(e,t,r){const s=t.primaryKeys??[];return s.length===0?`row-${r}`:$t(s.map(o=>e?.[o]))}function mt(e,t){const r=t.primaryKeys??[];if(r.length===0||e==null)return null;const s={};for(const o of r){if(!(o in e))return null;s[o]=e[o]}return s}function qn(e,t){const r=mt(e,t);if(!r)return null;const s=new Map((t.columns??[]).map(c=>[c.name,c])),o=[],i={},a=[];for(const c of t.primaryKeys??[]){const m=mn(s.get(c)),d=`pk_${c}`;i[d]=dt(r[c],m),a.push(`$${d}: ${m}`),o.push(`{${c}: {_eq: $${d}}}`)}return{filterText:o.length===1?o[0]:`{and: [${o.join(", ")}]}`,variables:i,params:a}}function Vn(e,t){const r=t.primaryKeys??[];return r.length===0?"":$t(r.map(s=>e[s]))}function fn(e,t){const r=t.primaryKeys??[];if(r.length===0)return null;const s=r.length===1?[e]:e.split(pr);if(s.length!==r.length)return null;const o={};for(let i=0;i<r.length;i++){const a=hr(s[i]);if(a===null)return null;o[r[i]]=a}return o}function Zi(e,t,r){if(!e)return;const s=e.filter(o=>o.destinationTable===t);if(s.length!==0){if(s.length===1)return s[0];if(r)return s.find(o=>o.destinationColumnNames?.[0]===r)}}function el(e){return e.fieldName??e.destinationTable}const tl=new Set(["binary","varbinary","image","blob","tinyblob","mediumblob","longblob","bytea"]),nl=new Set(["text","ntext","xml"]),rl=new Set(["json","jsonb"]);function Et(e){return tl.has(e.toLowerCase().replace(/\(.*\)/,""))}function no(e){return rl.has(e.toLowerCase().replace(/\(.*\)/,""))}function Ft(e){return no(e.dbType)||e.paramType==="JSON"}function gr(e){const t=e.toLowerCase(),r=t.replace(/\(.*\)/,"");return!!(nl.has(r)||t.includes("(max)"))}function _t(e){return typeof e.isLargeValue=="boolean"?e.isLargeValue:Et(e.dbType)||gr(e.dbType)}function Bn(e,t){if(!e)return"text";if(t&&Et(t))return"binary";if(t&&no(t))return"json";const r=e.trimStart();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{return JSON.parse(r),"json"}catch{}return r.startsWith("<?xml")||r.startsWith("<")&&r.includes("</")&&r.endsWith(">")?"xml":/^[aOsidb]:\d+[:{;]/.test(r)?"php-serialized":e.length>200||e.includes(`
88
+ `)?"longtext":"text"}const ro=80;function sl(e){return e.length<=ro?e:e.slice(0,ro)+"..."}function xr(e){const t=Math.ceil(e.length*3/4);return t<1024?`${t} bytes`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function so(e){const t={kind:"unknown",mime:"application/octet-stream",extension:".bin"};let r;try{r=atob(e.slice(0,24))}catch{return t}const s=o=>r.charCodeAt(o);return r.length>=4&&s(0)===137&&r.slice(1,4)==="PNG"?{kind:"image",mime:"image/png",extension:".png"}:r.length>=3&&s(0)===255&&s(1)===216&&s(2)===255?{kind:"image",mime:"image/jpeg",extension:".jpg"}:r.slice(0,4)==="GIF8"?{kind:"image",mime:"image/gif",extension:".gif"}:r.slice(0,4)==="RIFF"&&r.slice(8,12)==="WEBP"?{kind:"image",mime:"image/webp",extension:".webp"}:r.slice(0,4)==="%PDF"?{kind:"pdf",mime:"application/pdf",extension:".pdf"}:t}function oo(e,t){return`data:${t};base64,${e}`}const Pt=["_eq","_neq","_gt","_gte","_lt","_lte","_between","_null"],br={String:["_eq","_neq","_contains","_starts_with","_ends_with","_null"],Int:Pt,Float:Pt,Short:Pt,Byte:Pt,BigInt:Pt,Decimal:Pt,Boolean:["_eq","_null"],DateTime:Pt,DateTimeOffset:Pt},ol=new Set(["DateTime","DateTimeOffset"]),al=/^[_A-Za-z][_0-9A-Za-z]*$/,il=/^[_A-Za-z][_0-9A-Za-z]*!?$/,ll=new Set(Object.values(br).flat());function it(e){return typeof e=="string"&&al.test(e)}function je(e,t){if(!it(e))throw new Error(`Invalid GraphQL ${t}: ${String(e)}`)}function cl(e){return typeof e=="string"&&il.test(e)}function ao(e,t){return typeof e=="string"&&pn(t).includes(e)}function pn(e){const t=e.replace("!","");return br[t]??br.String}function ul(){return{variables:{},param:"",filterText:"",error:null}}function hn(e){return{variables:{},param:"",filterText:"",error:e}}function yr(e){if(!e)return ul();let t;try{t=JSON.parse(e)}catch{return hn("The filter in the URL is not valid JSON.")}if(!Array.isArray(t)||t.length<4)return hn("The filter in the URL is malformed.");const[r,s,o,i]=t;return it(r)?cl(i)?ao(s,i)?{variables:{filter:o},param:`, $filter: ${i}`,filterText:`{${r}: {${s}: $filter} }`,error:null}:hn(`Filter operator '${String(s)}' is not supported for ${String(i)} column '${String(r)}'.`):hn(`Filter type '${String(i)}' is not a valid type name.`):hn(`Filter column '${String(r)}' is not a valid column name.`)}function dl(e,t,r=0){return He(e,t,r)}function io(e){const t=e.replace("!","");switch(t){case"Int":case"Float":case"Short":case"Byte":case"Boolean":case"BigInt":case"Decimal":case"DateTime":case"DateTimeOffset":return t;default:return"String"}}const ml=/^\d{4}-\d{2}-\d{2}$/;function fl(e){const t=e<=0?"+":"-",r=Math.abs(e),s=String(Math.floor(r/60)).padStart(2,"0"),o=String(r%60).padStart(2,"0");return`${t}${s}:${o}`}function lo(e,t,r,s){const i=`${e}T${t==="start"?"00:00:00.000":"23:59:59.999"}`;if(r!=="DateTimeOffset")return i;const a=new Date(`${e}T00:00:00`).getTimezoneOffset();return`${i}${fl(a)}`}function pl(e,t,r,s){if(!ol.has(r))return{operator:e,value:t};const o=l=>lo(String(l),"start",r),i=l=>lo(String(l),"end",r),a=l=>typeof l=="string"&&ml.test(l);if(e==="_between"){const l=Array.isArray(t)?t:null;return!l||l.length!==2?{operator:e,value:t}:{operator:e,value:[a(l[0])?o(l[0]):l[0],a(l[1])?i(l[1]):l[1]]}}if(!a(t))return{operator:e,value:t};switch(e){case"_eq":return{operator:"_between",value:[o(t),i(t)]};case"_neq":return{operator:"_nbetween",value:[o(t),i(t)]};case"_gt":case"_lte":return{operator:e,value:i(t)};default:return{operator:e,value:o(t)}}}function Gn(e,t){const r={},s=[],o=[],i=[];for(let a=0;a<e.length;a++){const l=e[a],c=l.value;if(c.value===void 0||c.value===null||c.value==="")continue;const m=t.columns.find(x=>x.name===l.id);if(!m){i.push(`Column '${String(l.id)}' is not on this table.`);continue}if(!it(l.id)){i.push(`Column '${String(l.id)}' is not a valid column name.`);continue}if(!ao(c.operator,m.paramType)){i.push(`Operator '${String(c.operator)}' is not supported for column '${l.id}'.`);continue}const d=`cf_${l.id}_${a}`,f=io(m.paramType);if(c.operator==="_null"){o.push(`{${l.id}: {_null: ${c.value?"true":"false"}}}`);continue}const p=pl(c.operator,c.value,f);if(p.operator==="_between"||p.operator==="_nbetween"){const x=p.value;if(!Array.isArray(x)||x.length!==2){i.push(`The range filter on column '${l.id}' needs exactly two bounds.`);continue}const h=`${d}_lo`,y=`${d}_hi`;r[h]=x[0],r[y]=x[1],s.push(`$${h}: ${f}`,`$${y}: ${f}`),o.push(`{${l.id}: {${p.operator}: [$${h}, $${y}]}}`);continue}r[d]=p.value,s.push(`$${d}: ${f}`),o.push(`{${l.id}: {${p.operator}: $${d}}}`)}return{variables:r,params:s,filterTexts:o,errors:i}}function co(e,t,r){const s=yr(t),o=Gn(r,e);return s.error?[s.error,...o.errors]:o.errors}function vr(e){return e.length===0?"":JSON.stringify(e.map(t=>[t.id,t.value.operator,t.value.value]))}function jr(e){try{if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(hl).map(([r,s,o])=>({id:r,value:{operator:s,value:o}})):[]}catch{return[]}}function hl(e){if(!Array.isArray(e)||e.length!==3)return!1;const[t,r]=e;return it(t)&&typeof r=="string"&&ll.has(r)}function uo(e){return zt(e)[0]?.gqlType??"Int"}function zt(e){const t=e.primaryKeys??[];if(t.length===0)return[];const r=new Map(e.columns.map(s=>[s.name,s]));return t.map(s=>({name:s,gqlType:r.get(s)?.paramType?.replace("!","")??"String"}))}function gl(e,t=()=>!0){const r=e.indexes??[];if(r.length===0)return null;const s=new Map(e.columns.map(i=>[i.name,i])),o=i=>{const a=i.columns[0],l=a?s.get(a):void 0;return l&&t(l)?l.name:null};for(const i of[a=>a.isClustered,a=>a.isUnique,()=>!0])for(const a of r){if(!i(a))continue;const l=o(a);if(l)return l}return null}function wr(e,t){if(zt(t).length<=1)return{id:dt(hr(e),uo(t))};const s=fn(e,t);return s?qn(s,t)?.variables??{}:{}}function Cr(e,t,r){je(e.name,"single-row table name");for(const o of r)je(o,"single-row selection field");const s=t.params.length>0?`(${t.params.join(", ")})`:"";return`query GetSingleRow_${e.name}${s} { value: ${e.name}(filter: ${t.filterText}) { data { ${r.join(" ")} } } }`}function mo(e,t,r){je(e.name,"rows-by-pk table name");for(const d of r)je(d,"rows-by-pk selection field");const s=e.primaryKeys??[];if(s.length===0||t.length===0||r.length===0)return null;for(const d of s)je(d,"rows-by-pk key column");const o=new Map((e.columns??[]).map(d=>[d.name,d])),i=[],a={},l=[];t.forEach((d,f)=>{const p=[];for(const x of s){const h=mn(o.get(x)),y=`pk${f}_${x}`;a[y]=dt(d[x],h),i.push(`$${y}: ${h}`),p.push(`{${x}: {_eq: $${y}}}`)}l.push(p.length===1?p[0]:`{and: [${p.join(", ")}]}`)});const c=l.length===1?l[0]:`{or: [${l.join(", ")}]}`;return{query:`query GetRowsByPk_${e.name}(${i.join(", ")}) { value: ${e.name}(filter: ${c} limit: ${t.length}) { data { ${r.join(" ")} } } }`,variables:a}}const xl=11;function fo(e,t){return t.map(r=>{const s=e.findTable(r.destinationTable),o=s?.labelColumn??"id",a=[...s?.primaryKeys?.length?s.primaryKeys:["id"]];return o&&!a.includes(o)&&a.push(o),`${r.fieldName??r.destinationTable}(limit: ${xl}) { total data { ${a.join(" ")} } }`}).join(" ")}function Nr(e,t,r,s){return`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${t}) { ${e.name}(sort: $sort limit: $limit offset: $offset ${r}) { total offset limit data {${s}}}}`}function bl(e,t,r){const s=new Set;return e.columns.filter(o=>o?.joinTable===void 0).filter(o=>o.isPrimaryKey||!_t(o)).map(o=>{const i=r.singleJoins.find(c=>c.sourceColumnNames?.[0]===o.name);if(!i)return o;const l=t.findTable(i.destinationTable)?.labelColumn??"id";return{...o,joinTable:i,joinLabelColumn:l}}).map(o=>{if(o?.joinTable){s.add(o.name);const i=t.findTable(o.joinTable.destinationTable),a=i?.primaryKeys?.length?i.primaryKeys:o.joinTable.destinationColumnNames,l=o.joinLabelColumn??"id",c=l&&!a.includes(l)?` label: ${l}`:"",m=o.joinTable.fieldName??o.joinTable.destinationTable;return a.length===1?`${o.name} ${m} { id: ${a[0]}${c} }`:`${o.name} ${m} { ${a.join(" ")}${c} }`}return o.name}).join(" ")}function yl(e,t,r,s,o,i,a,l=!1){const c=$r(e,t,i,a);if(c&&Tr(c.childJoin)){const m=c.childJoin.destinationColumnNames[0],f=`, $id: ${zt(c.parentTable)[0]?.gqlType??"Int"}`,p=`filter: { ${m}: { _eq: $id } }`,x=l?"":fo(t,r.multiJoins.filter(y=>!wl(y,c.childJoin))),h=x?`${s} ${x}`:s;return Nr(e,f,p,h)}if(c){const m=`${c.childField}(limit: $limit offset: $offset sort: $sort) { total offset limit data {${o}} }`,d=zt(c.parentTable);if(d.length===0)return null;let f,p;if(d.length===1){const x=d[0].name;f=`, $id: ${d[0].gqlType}`,p=`{ ${x}: { _eq: $id}}`}else f=`, ${d.map(y=>`$pk_${y.name}: ${y.gqlType}`).join(", ")}`,p=`{and: [${d.map(y=>`{${y.name}: {_eq: $pk_${y.name}}}`).join(", ")}]}`;return`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${f}) { ${c.parentTable.name}(filter: ${p}) { data { ${m} } } }`}return null}function vl(e,t,r){const s=zt(t);if(s.length===0)return null;let o,i;if(s.length===1){const a=uo(t),l=s[0].name;o=`, $id: ${a}`,i=`{ ${l}: { _eq: $id}}`}else o=`, ${s.map(l=>`$pk_${l.name}: ${l.gqlType}`).join(", ")}`,i=`{and: [${s.map(l=>`{${l.name}: {_eq: $pk_${l.name}}}`).join(", ")}]}`;return Nr(e,o,`filter: ${i}`,r)}function jl(e,t,r,s){let{param:o,filterText:i}=yr(t);const{params:a,filterTexts:l}=Gn(r,e);a.length>0&&(o+=a.map(m=>`, ${m}`).join(""));const c=[];return i&&c.push(i),c.push(...l),c.length>1?i=`{and: [${c.join(", ")}]}`:c.length===1?i=c[0]:i="",Nr(e,o,i?`filter: ${i}`:"",s)}function kr(e){return e.columns.filter(t=>t.isPrimaryKey||!Et(t.dbType))}function Sr(e,t,r,s,o,i,a,l){if(!e||!t?.data)return null;const c=t.findTable(e.graphQlName);if(!c)return null;const m=l?.fields==="export",d=m?kr(e).map(x=>x.name).join(" "):bl(e,t,c),f=m?"":fo(t,c.multiJoins),p=f?`${d} ${f}`:d;return o&&(a||i)?yl(e,t,c,d,p,i,a,m):o&&!i&&!a?vl(e,c,p):co(e,r,s).length>0?null:jl(e,r,s,p)}function Tr(e){return!Gt(e)&&e.isPolymorphic!==!0&&(e.destinationColumnNames?.length??0)===1}function wl(e,t){return(e.fieldName??e.destinationTable)===(t.fieldName??t.destinationTable)&&e.destinationTable===t.destinationTable&&(e.destinationColumnNames??[]).join("\0")===(t.destinationColumnNames??[]).join("\0")&&(e.sourceColumnNames??[]).join("\0")===(t.sourceColumnNames??[]).join("\0")}const Cl={data:[],total:0,offset:0,limit:0};function po(e,t,r){const i=e?.[t]?.data?.[0]?.[r];return!i||!Array.isArray(i.data)?Cl:i}function $r(e,t,r,s){const o=r??t.findTable(e.graphQlName)?.singleJoins.find(l=>l.destinationTable===s)?.destinationTable;if(!o)return null;const i=t.findTable(o);if(!i)return null;const a=Zi(i.multiJoins,e.graphQlName,s);return a?{parentTable:i,childField:el(a),childJoin:a}:null}function Nl(e){const t=e.filter(it);return t.length===0?null:`query GetTableRowCounts { ${t.map(s=>`${s}: ${s}(limit: 1) { total }`).join(" ")} }`}function kl(e=!0){const{data:t,loading:r,error:s}=Je(),o=$e(),i=u.useMemo(()=>t.map(f=>f.name),[t]),a=u.useMemo(()=>Nl(i),[i]),{data:l,isLoading:c,error:m}=de.useQuery({queryKey:["tableRowCounts",i],queryFn:()=>o.query(a),enabled:e&&!!a&&i.length>0,staleTime:300*1e3});return{stats:u.useMemo(()=>{const f={};for(const p of t){const h=l?.[p.name]?.total??null;f[p.name]={columnCount:p.columns.length,rowCount:h,fkCount:p.singleJoins.length,isLoading:c,error:m?m.message:null}}return f},[t,l,c,m]),isLoading:r||c,error:s}}function Zt({kind:e}){return n.jsx("span",{className:"text-muted-foreground/60 italic select-none",children:e==="null"?"NULL":"empty"})}const Sl="display-format",Tl="display-format-preview",$l=new Set(["date","datetime","time","relative","number","percent","raw"]);function El(e){return{param:(e.paramType??"").replace("!","").toLowerCase(),db:(e.dbType??"").toLowerCase()}}function Fl({param:e,db:t}){return e==="date"||t==="date"}function _l({param:e,db:t}){return e==="datetime"||e==="datetimeoffset"||t.includes("datetime")||t==="timestamp"||t==="smalldatetime"}function ho(e,t){const s=(t?e.metadata?.[t]:void 0)??e.metadata?.[Sl];if(typeof s=="string"&&$l.has(s.toLowerCase()))return s.toLowerCase();const o=El(e);return _l(o)?"datetime":Fl(o)?"date":null}function Pl(e){if(e instanceof Date)return isNaN(e.getTime())?null:e;if(typeof e=="number"){const t=new Date(e);return isNaN(t.getTime())?null:t}if(typeof e=="string"){const t=new Date(e);return isNaN(t.getTime())?null:t}return null}const zl=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"}),Dl=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}),Ml=new Intl.DateTimeFormat(void 0,{timeStyle:"short"}),Il=new Intl.DateTimeFormat(void 0,{dateStyle:"full",timeStyle:"medium"}),go=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Ll=[["year",31536e3],["month",2592e3],["week",604800],["day",86400],["hour",3600],["minute",60],["second",1]];function Ol(e,t=new Date){const r=Math.round((e.getTime()-t.getTime())/1e3),s=Math.abs(r);for(const[o,i]of Ll)if(s>=i||o==="second")return go.format(Math.round(r/i),o);return go.format(0,"second")}function Kn(e,t,r){if(e==null)return n.jsx(Zt,{kind:"null"});if(e==="")return n.jsx(Zt,{kind:"empty"});const s=ho(t,r?.formatKey);if(s===null||s==="raw")return String(e);if(s==="date"||s==="datetime"||s==="time"||s==="relative"){const o=Pl(e);if(!o)return String(e);const i=Il.format(o);if(s==="relative")return n.jsx("span",{title:i,className:"cursor-help underline decoration-dotted decoration-muted-foreground/40 underline-offset-2",children:Ol(o)});const a=(s==="date"?zl:s==="time"?Ml:Dl).format(o);return n.jsx("span",{title:i,children:a})}if(s==="number"||s==="percent"){const o=typeof e=="number"?e:Number(e);if(isNaN(o))return String(e);const i=s==="percent"?new Intl.NumberFormat(void 0,{style:"percent",maximumFractionDigits:2}).format(o):new Intl.NumberFormat(void 0).format(o);return n.jsx("span",{title:String(e),children:i})}return String(e)}function xo(e){if(!e)return"";const t=new Date(e);return t.toString()==="Invalid Date"||t.getTime()===0||t.getUTCFullYear()<=1?"":t.toLocaleString()}function Al(e){if(e===null)return"—";if(e===0)return"0";if(e<1e3)return e.toString();if(e<1e6){const r=e/1e3;return r%1===0?`${r.toFixed(0)}k`:`${r.toFixed(1)}k`}const t=e/1e6;return t%1===0?`${t.toFixed(0)}M`:`${t.toFixed(1)}M`}const bo="\uFEFF",ql=/["\n\r,]/;function Er(e){if(e==null)return"";const t=Vl(e);return t===""?'""':ql.test(t)?`"${t.replace(/"/g,'""')}"`:t}function Vl(e){switch(typeof e){case"string":return e;case"bigint":return e.toString();case"number":case"boolean":return String(e);case"object":return e instanceof Date?e.toISOString():JSON.stringify(e);default:return String(e)}}function yo(e,t,r={}){const s=e.map(Er).join(","),o=t.map(a=>a.map(Er).join(",")),i=[s,...o].join(`\r
89
+ `);return r.bom?bo+i:i}function vo(e,t){return typeof t=="bigint"?t.toString():t}function jo(e,t){const r={};for(let s=0;s<e.length;s++)r[e[s]]=t[s];return r}function wo(e,t,r={}){if(r.mode==="lines")return t.map(o=>JSON.stringify(jo(e,o),vo)).join(`
90
+ `);const s=t.map(o=>jo(e,o));return JSON.stringify(s,vo,2)}const Bl=500;function Fr(e){if(e?.aborted)throw new DOMException("Export cancelled","AbortError")}async function _r(e){const t=e.pageSize??Bl,{rowCap:r,signal:s}=e,o=[];let i=0,a=!1;Fr(s);let l=0,c=Number.POSITIVE_INFINITY;for(;l<c;){Fr(s);const d=await e.fetchPage(l,t);i=d.total,c=d.total;for(const f of d.rows){if(r!==void 0&&o.length>=r){a=!0;break}o.push(f)}if(e.onProgress?.(o.length,i),a||d.rows.length===0)break;l+=d.rows.length}return Fr(s),{content:e.format==="csv"?yo(e.headers,o,e.csv):wo(e.headers,o,e.json),rowCount:o.length,total:i,truncated:a}}const Pr=1e5;function zr(e){return e==="csv"?"text/csv;charset=utf-8;":"application/json;charset=utf-8;"}function Dr(e,t){return`${e}-export.${t}`}function Mr(e,t,r){if(typeof window>"u"||typeof document>"u")return;const s=new Blob([e],{type:r}),o=URL.createObjectURL(s),i=document.createElement("a");i.href=o,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o)}function Gl(e,t,r){if(typeof window>"u"||typeof document>"u")return;const s=Uint8Array.from(atob(e),l=>l.charCodeAt(0)),o=new Blob([s],{type:r}),i=URL.createObjectURL(o),a=document.createElement("a");a.href=i,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}function Kl(){const e=Je(),t=$e();return u.useCallback(async(r,s)=>{const o=Sr(r,e,"",[],void 0,void 0,void 0,{fields:"export"});if(!o)throw new Error(`Cannot export '${r.label??r.name}': no export query could be built.`);const i=kr(r),a=await _r({format:s,headers:i.map(l=>l.label??l.name),csv:{bom:!0},rowCap:Pr,fetchPage:async(l,c)=>{const d=(await t.query(o,{limit:c,offset:l}))?.[r.name],f=d?.data??[];return{rows:f.map(p=>i.map(x=>p[x.name])),total:d?.total??f.length}}});return Mr(a.content,Dr(r.name,s),zr(s)),a},[e,t])}const Co=u.createContext({toast:()=>{}}),Wl=4e3;function No({children:e}){const[t,r]=u.useState([]),s=u.useRef(0),o=u.useRef(new Set),i=u.useCallback(c=>{r(m=>m.filter(d=>d.id!==c))},[]),a=u.useCallback((c,m="success")=>{const d=s.current++;r(p=>[...p,{id:d,message:c,variant:m}]);const f=setTimeout(()=>{i(d),o.current.delete(f)},Wl);o.current.add(f)},[i]);u.useEffect(()=>{const c=o.current;return()=>{c.forEach(clearTimeout)}},[]);const l=u.useMemo(()=>({toast:a}),[a]);return n.jsxs(Co.Provider,{value:l,children:[e,n.jsx("div",{className:"fixed bottom-4 right-4 z-[100] flex flex-col gap-2 max-w-sm",role:"region","aria-label":"Notifications",children:t.map(c=>n.jsxs("div",{role:"status",className:Y("flex items-start gap-2 rounded-md border px-3 py-2 text-sm shadow-md bg-popover",c.variant==="error"?"border-destructive/40 text-destructive":"border-border text-foreground"),children:[c.variant==="error"?n.jsx(C.AlertCircle,{className:"size-4 shrink-0 mt-0.5"}):n.jsx(C.CheckCircle2,{className:"size-4 shrink-0 mt-0.5 text-green-600"}),n.jsx("span",{className:"flex-1 break-words",children:c.message}),n.jsx("button",{type:"button",onClick:()=>i(c.id),"aria-label":"Dismiss notification",className:"shrink-0 opacity-60 hover:opacity-100",children:n.jsx(C.X,{className:"size-3.5"})})]},c.id))})]})}function vt(){return u.useContext(Co)}const Wn=50;function Jl(e,t){return e===null||t<=0?0:Math.max(2,Math.min(100,Math.round(e/t*100)))}function Ql({percent:e,label:t}){return n.jsx("span",{className:"flex-1 min-w-[1.5em] h-[0.5em] rounded-full bg-muted/70 overflow-hidden",role:"img","aria-label":t,title:t,children:n.jsx("span",{className:"block h-full rounded-full bg-emerald-500/70 dark:bg-emerald-400/70",style:{width:`${e}%`}})})}function Ir({count:e}){return e<=0?null:n.jsxs("span",{className:"shrink-0 rounded px-1 py-px text-[0.85em] tabular-nums bg-blue-100 text-blue-700 dark:bg-blue-900/60 dark:text-blue-300",children:[e," FK"]})}function Hl(e){try{return decodeURIComponent(e)}catch{return e}}function Ul({stats:e,maxRowCount:t}){const r=Jl(e.rowCount,t),s="flex items-center gap-1.5 text-xs leading-none min-w-0";return e.isLoading?n.jsxs("div",{className:`${s} text-muted-foreground`,children:[n.jsxs("span",{className:"tabular-nums shrink-0",children:[e.columnCount,"c"]}),n.jsx("span",{className:"flex-1 min-w-[1.5em] h-[0.5em] rounded-full bg-muted/70 overflow-hidden",children:n.jsx("span",{className:"block h-full w-1/3 rounded-full bg-muted-foreground/30 animate-pulse"})}),n.jsx(C.Loader2,{className:"size-[1em] shrink-0 animate-spin"}),n.jsx(Ir,{count:e.fkCount})]}):e.error?n.jsxs("div",{className:s,children:[n.jsxs("span",{className:"tabular-nums shrink-0 text-muted-foreground",children:[e.columnCount,"c"]}),n.jsx("span",{className:"flex-1 text-destructive truncate",title:e.error,children:"err"}),n.jsx(Ir,{count:e.fkCount})]}):n.jsxs("div",{className:s,children:[n.jsxs("span",{className:"tabular-nums shrink-0 text-muted-foreground/70",children:[e.columnCount,"c"]}),n.jsx(Ql,{percent:r,label:`${e.rowCount?.toLocaleString()??"unknown"} rows`}),n.jsx("span",{className:"tabular-nums shrink-0 text-right text-muted-foreground",children:Al(e.rowCount)}),n.jsx(Ir,{count:e.fkCount})]})}function Yl({table:e,stats:t,maxRowCount:r,showStats:s,active:o,actions:i}){const a=(i??[]).filter(l=>l.enabled?.(e)??!0);return n.jsxs("div",{className:`group/tablerow flex items-stretch border-l-2 ${o?"bg-accent text-accent-foreground border-primary":"text-foreground border-transparent hover:bg-muted/50"}`,children:[n.jsx(Pn,{to:`/${e.name}`,"aria-current":o?"page":void 0,className:`plain-link flex-1 min-w-0 no-underline py-1.5 px-2 text-sm font-medium ${o?"":"hover:text-primary"}`,children:n.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[n.jsx("span",{className:"truncate",title:e.label,children:e.label}),s&&n.jsx(Ul,{stats:t,maxRowCount:r})]})}),a.length>0&&n.jsxs(Ln,{children:[n.jsx(On,{asChild:!0,children:n.jsx("button",{type:"button","aria-label":`Actions for ${e.label}`,className:"shrink-0 px-1 opacity-0 group-hover/tablerow:opacity-100 focus:opacity-100 data-[state=open]:opacity-100 text-muted-foreground hover:text-foreground",children:n.jsx(C.MoreVertical,{className:"size-3.5"})})}),n.jsx(An,{align:"start",children:a.map(l=>{const c=l.icon;return n.jsxs(bt,{onSelect:()=>{l.onSelect(e)},children:[c&&n.jsx(c,{className:"size-3.5"}),l.label]},l.id)})})]})]})}function Lr(e){const t=e.dbName.lastIndexOf(".");return t>0?e.dbName.slice(0,t):null}function ko({schema:e,count:t,collapsed:r,context:s,onToggle:o}){const i=r?C.ChevronRight:C.ChevronDown,a=n.jsxs(n.Fragment,{children:[n.jsx(i,{className:"size-3.5 shrink-0 text-muted-foreground"}),n.jsx("span",{className:"truncate font-semibold",title:e,children:e}),n.jsx("span",{className:"ml-auto shrink-0 tabular-nums text-[0.85em] text-muted-foreground",children:t})]}),l="flex items-center gap-1.5 w-full px-2 py-1 text-xs uppercase tracking-wide text-muted-foreground bg-muted/40 border-y border-border sticky top-0 z-10";return s?n.jsx("div",{className:l,"aria-hidden":"true",children:a}):n.jsx("button",{type:"button",onClick:o,"aria-expanded":!r,className:`${l} hover:bg-muted/70 text-left`,children:a})}function Rl(){const{showStats:e,tableActions:t}=cr(),{loading:r,error:s,data:o}=Je(),i=Kl(),{toast:a}=vt(),l=u.useCallback(async(E,P)=>{try{const q=await i(E,P);a(q.truncated?`${E.label} exported (truncated to ${q.rowCount.toLocaleString()} of ${q.total.toLocaleString()} rows)`:`${E.label} exported (${q.rowCount.toLocaleString()} rows)`)}catch(q){a(`Export failed: ${q.message}`,"error")}},[i,a]),c=u.useMemo(()=>[{id:"download-csv",label:"Download CSV",icon:C.Download,onSelect:E=>l(E,"csv")},{id:"download-json",label:"Download JSON",icon:C.Download,onSelect:E=>l(E,"json")},...t??[]],[l,t]),{stats:m,isLoading:d}=kl(e),[f,p]=u.useState(""),[x,h]=u.useState(new Set),[y,N]=u.useState(0),T=ps(),k=Hl(T.split("/")[1]??""),$=u.useMemo(()=>{const E=Object.values(m).map(P=>P.rowCount).filter(P=>P!==null);return E.length>0?Math.max(...E):0},[m]),b=f.trim().length>0,v=u.useMemo(()=>{const E=f.trim().toLowerCase();return E?o.filter(P=>{const q=Lr(P);return P.label.toLowerCase().includes(E)||P.dbName.toLowerCase().includes(E)||(q?.toLowerCase().includes(E)??!1)}):o},[o,f]),{schemas:w,grouped:F,multiSchema:j}=u.useMemo(()=>{const E=new Map;for(const q of v){const U=Lr(q),_=E.get(U)??[];_.push(q),E.set(U,_)}const P=[...E.keys()].filter(q=>q!==null).sort((q,U)=>q.localeCompare(U));return{schemas:P,grouped:E,multiSchema:P.length>1}},[v]),V=u.useMemo(()=>{const E=[];if(j){const P=[...w,...F.has(null)?[null]:[]];for(const q of P){const U=F.get(q===void 0?null:q)??[],_=!b&&x.has(q);if(E.push({kind:"group",schema:q??"(no schema)",count:U.length,collapsed:_}),!_)for(const ce of U)E.push({kind:"table",schema:q,table:ce})}}else for(const P of v)E.push({kind:"table",schema:Lr(P),table:P});return E},[j,w,F,v,x,b]);u.useEffect(()=>{N(0)},[f]);const S=Math.max(1,Math.ceil(V.length/Wn)),L=Math.min(y,S-1),A=L*Wn,D=V.slice(A,A+Wn),B=j&&D[0]?.kind==="table"&&D[0].schema?D[0].schema:null,X=E=>h(P=>{const q=new Set(P);return q.has(E)?q.delete(E):q.add(E),q});return r?n.jsxs("div",{className:"flex items-center justify-center gap-2 p-4",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):s?n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",s.message]})}):o.length===0?n.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[n.jsx("p",{className:"font-medium",children:"No tables found"}),n.jsx("p",{className:"mt-1",children:"The database may be empty or the connection may have failed."})]}):n.jsxs("div",{className:"@container min-w-0 flex flex-col h-full",children:[n.jsxs("div",{className:"sticky top-0 z-20 bg-background p-2 border-b border-border",children:[n.jsxs("div",{className:"relative",children:[n.jsx(C.Search,{className:"absolute left-2 top-1/2 -translate-y-1/2 size-4 text-muted-foreground pointer-events-none"}),n.jsx(Qe,{type:"search",value:f,onChange:E=>p(E.target.value),placeholder:"Search tables...","aria-label":"Search tables",className:"pl-8 pr-8 h-8 text-sm"}),b&&n.jsx("button",{type:"button",onClick:()=>p(""),"aria-label":"Clear search",className:"absolute right-1.5 top-1/2 -translate-y-1/2 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted",children:n.jsx(C.X,{className:"size-4"})})]}),b&&n.jsxs("p",{className:"mt-1 px-0.5 text-xs text-muted-foreground",children:[v.length," match",v.length!==1?"es":""]})]}),n.jsx("div",{className:"flex-1 overflow-y-auto min-h-0",children:V.length===0?n.jsxs("p",{className:"p-4 text-center text-sm text-muted-foreground",children:["No tables match “",f,"”."]}):n.jsxs(n.Fragment,{children:[B&&n.jsx(ko,{schema:B,count:F.get(B)?.length??0,collapsed:!1,context:!0}),D.map(E=>E.kind==="group"?n.jsx(ko,{schema:E.schema,count:E.count,collapsed:E.collapsed,onToggle:()=>X(E.schema)},`g:${E.schema}`):n.jsx(Yl,{table:E.table,stats:m[E.table.name]??{columnCount:E.table.columns.length,rowCount:null,fkCount:E.table.singleJoins.length,isLoading:d,error:null},maxRowCount:$,showStats:e,active:E.table.name===k,actions:c},`t:${E.table.name}`))]})}),S>1&&n.jsxs("div",{className:"sticky bottom-0 z-20 bg-background border-t border-border flex items-center justify-between gap-2 px-2 py-1.5",children:[n.jsx("button",{type:"button",onClick:()=>N(E=>Math.max(0,E-1)),disabled:L===0,"aria-label":"Previous page",className:"p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 disabled:pointer-events-none",children:n.jsx(C.ChevronLeft,{className:"size-4"})}),n.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:[A+1,"–",Math.min(A+Wn,V.length)," of ",V.length]}),n.jsx("button",{type:"button",onClick:()=>N(E=>Math.min(S-1,E+1)),disabled:L>=S-1,"aria-label":"Next page",className:"p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 disabled:pointer-events-none",children:n.jsx(C.ChevronRight,{className:"size-4"})})]})]})}const Xl=Fs("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background text-foreground hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"text-foreground hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10","icon-sm":"h-8 w-8 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),Q=Ve.forwardRef(({className:e,variant:t,size:r,asChild:s=!1,...o},i)=>{const a=s?ka.Slot:"button";return n.jsx(a,{className:Y(Xl({variant:t,size:r,className:e})),ref:i,...o})});Q.displayName="Button";const gn=Ve.forwardRef(({...e},t)=>n.jsx(R.HoverCard.Root,{"data-slot":"hover-card",...e}));gn.displayName="HoverCard";const xn=Ve.forwardRef(({...e},t)=>n.jsx(R.HoverCard.Trigger,{"data-slot":"hover-card-trigger",...e}));xn.displayName="HoverCardTrigger";const bn=Ve.forwardRef(({className:e,align:t="center",sideOffset:r=4,...s},o)=>n.jsx(R.HoverCard.Portal,{children:n.jsx(R.HoverCard.Content,{ref:o,"data-slot":"hover-card-content",align:t,sideOffset:r,className:Y("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...s})}));bn.displayName="HoverCardContent";function Ze({...e}){return n.jsx(R.Select.Root,{"data-slot":"select",...e})}function et({...e}){return n.jsx(R.Select.Value,{"data-slot":"select-value",...e})}function tt({className:e,size:t="default",children:r,...s}){return n.jsxs(R.Select.Trigger,{"data-slot":"select-trigger","data-size":t,className:Y("flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent text-foreground px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...s,children:[r,n.jsx(R.Select.Icon,{asChild:!0,children:n.jsx(C.ChevronDownIcon,{className:"size-4 opacity-50"})})]})}function nt({className:e,children:t,position:r="item-aligned",align:s="center",...o}){return n.jsx(R.Select.Portal,{children:n.jsxs(R.Select.Content,{"data-slot":"select-content",className:Y("relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,align:s,...o,children:[n.jsx(Zl,{}),n.jsx(R.Select.Viewport,{className:Y("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),n.jsx(ec,{})]})})}function we({className:e,children:t,...r}){return n.jsxs(R.Select.Item,{"data-slot":"select-item",className:Y("relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...r,children:[n.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:n.jsx(R.Select.ItemIndicator,{children:n.jsx(C.CheckIcon,{className:"size-4"})})}),n.jsx(R.Select.ItemText,{children:t})]})}function Zl({className:e,...t}){return n.jsx(R.Select.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:Y("flex cursor-default items-center justify-center py-1",e),...t,children:n.jsx(C.ChevronUpIcon,{className:"size-4"})})}function ec({className:e,...t}){return n.jsx(R.Select.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:Y("flex cursor-default items-center justify-center py-1",e),...t,children:n.jsx(C.ChevronDownIcon,{className:"size-4"})})}function So(e){const t=u.useRef(null),r=u.useRef(null),s=u.useRef(e);s.current=e;const o=u.useMemo(()=>{const i=()=>{t.current&&(clearTimeout(t.current),t.current=null)},a=()=>{i();const l=r.current;r.current=null,l?.()};return{schedule:l=>{i(),r.current=l,t.current=setTimeout(a,s.current)},cancel:()=>{i(),r.current=null},flush:a}},[]);return u.useEffect(()=>()=>o.flush(),[o]),o}const To={_contains:"Contains",_starts_with:"Starts with",_ends_with:"Ends with",_eq:"Equals",_neq:"Not equals",_null:"Is null"},tc=300;function nc({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(y=>y in To),s=e.getFilterValue(),[o,i]=u.useState(s?.operator??"_contains"),[a,l]=u.useState(s?.operator==="_null"?"":String(s?.value??"")),{schedule:c,cancel:m}=So(tc),d=o==="_null",f=(y,N)=>{if(y==="_null"){m(),e.setFilterValue({operator:"_null",value:!0});return}if(!N){m(),e.setFilterValue(void 0);return}c(()=>e.setFilterValue({operator:y,value:N}))},p=y=>{i(y),y==="_null"?(l(""),f("_null","")):a?f(y,a):(m(),e.setFilterValue(void 0))},x=y=>{l(y),f(o,y)},h=()=>{m(),i("_contains"),l(""),e.setFilterValue(void 0)};return r.length===0?null:n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:o,onValueChange:p,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:r.map(y=>n.jsx(we,{value:y,children:To[y]},y))})]}),!d&&n.jsx(Qe,{placeholder:"Filter value...",value:a,onChange:y=>x(y.target.value),className:"h-8 text-xs",autoFocus:!0}),s!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:h,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}const $o={_eq:"Equals",_neq:"Not equals",_gt:"Greater than",_gte:"Greater or equal",_lt:"Less than",_lte:"Less or equal",_between:"Between",_null:"Is null"},rc=300;function sc(e){return e.columnDef.meta?.paramType??""}function Or(e,t){return eo(e,t)}function oc({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(D=>D in $o),s=sc(e),o=qt(s),i=Bt(s),a=e.getFilterValue(),l=a?.operator??"_eq",[c,m]=u.useState(l),[d,f]=u.useState(()=>!a||a.operator==="_null"||a.operator==="_between"?"":String(a.value??"")),[p,x]=u.useState(()=>a?.operator==="_between"&&Array.isArray(a.value)?String(a.value[0]??""):""),[h,y]=u.useState(()=>a?.operator==="_between"&&Array.isArray(a.value)?String(a.value[1]??""):""),{schedule:N,cancel:T}=So(rc),k=(D,B)=>{if(D==="_null"){T(),e.setFilterValue({operator:"_null",value:!0});return}const X=Or(B,s);if(X===null){T(),e.setFilterValue(void 0);return}N(()=>e.setFilterValue({operator:D,value:X}))},$=(D,B)=>{const X=Or(D,s),E=Or(B,s);if(X===null||E===null){T(),e.setFilterValue(void 0);return}N(()=>e.setFilterValue({operator:"_between",value:[X,E]}))},b=D=>{m(D),D==="_null"?(f(""),x(""),y(""),k("_null","")):D==="_between"?(f(""),p&&h?$(p,h):(T(),e.setFilterValue(void 0))):(x(""),y(""),d?k(D,d):(T(),e.setFilterValue(void 0)))},v=D=>{f(D),k(c,D)},w=D=>{x(D),$(D,h)},F=D=>{y(D),$(p,D)},j=()=>{T(),m("_eq"),f(""),x(""),y(""),e.setFilterValue(void 0)};if(r.length===0)return null;const V=c==="_between",S=c==="_null",L=i?"text":"number",A=i?o?"numeric":"decimal":void 0;return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:c,onValueChange:b,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:r.map(D=>n.jsx(we,{value:D,children:$o[D]},D))})]}),!S&&!V&&n.jsx(Qe,{type:L,inputMode:A,placeholder:"Filter value...",value:d,onChange:D=>v(D.target.value),className:"h-8 text-xs",autoFocus:!0}),V&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Qe,{type:L,inputMode:A,placeholder:"Min",value:p,onChange:D=>w(D.target.value),className:"h-8 text-xs",autoFocus:!0}),n.jsx(Qe,{type:L,inputMode:A,placeholder:"Max",value:h,onChange:D=>F(D.target.value),className:"h-8 text-xs"})]}),a!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:j,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}const Eo={_eq:"On",_neq:"Not on",_gt:"After",_gte:"On or after",_lt:"Before",_lte:"On or before",_between:"Between",_null:"Is null"};function ac({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(w=>w in Eo),s=e.getFilterValue(),o=s?.operator??"_eq",[i,a]=u.useState(o),[l,c]=u.useState(()=>!s||s.operator==="_null"||s.operator==="_between"?"":String(s.value??"")),[m,d]=u.useState(()=>s?.operator==="_between"&&Array.isArray(s.value)?String(s.value[0]??""):""),[f,p]=u.useState(()=>s?.operator==="_between"&&Array.isArray(s.value)?String(s.value[1]??""):""),x=(w,F)=>{if(w==="_null"){e.setFilterValue({operator:"_null",value:!0});return}if(!F){e.setFilterValue(void 0);return}e.setFilterValue({operator:w,value:F})},h=(w,F)=>{if(!w||!F){e.setFilterValue(void 0);return}e.setFilterValue({operator:"_between",value:[w,F]})},y=w=>{a(w),w==="_null"?(c(""),d(""),p(""),e.setFilterValue({operator:"_null",value:!0})):w==="_between"?(c(""),m&&f?h(m,f):e.setFilterValue(void 0)):(d(""),p(""),l?x(w,l):e.setFilterValue(void 0))},N=w=>{c(w),x(i,w)},T=w=>{d(w),h(w,f)},k=w=>{p(w),h(m,w)},$=()=>{a("_eq"),c(""),d(""),p(""),e.setFilterValue(void 0)};if(r.length===0)return null;const b=i==="_between",v=i==="_null";return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:i,onValueChange:y,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:r.map(w=>n.jsx(we,{value:w,children:Eo[w]},w))})]}),!v&&!b&&n.jsx(Qe,{type:"date",value:l,onChange:w=>N(w.target.value),className:"h-8 text-xs"}),b&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Qe,{type:"date",value:m,onChange:w=>T(w.target.value),className:"h-8 text-xs"}),n.jsx(Qe,{type:"date",value:f,onChange:w=>k(w.target.value),className:"h-8 text-xs"})]}),s!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:$,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}const ic={all:"All",true:"True",false:"False",_null:"Is null"};function lc(e){return e?e.operator==="_null"?"_null":e.operator==="_eq"&&e.value===!0?"true":e.operator==="_eq"&&e.value===!1?"false":"all":"all"}function cc({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).includes("_null"),s=e.getFilterValue(),o=lc(s),i=r?["all","true","false","_null"]:["all","true","false"],a=c=>{switch(c){case"true":e.setFilterValue({operator:"_eq",value:!0});break;case"false":e.setFilterValue({operator:"_eq",value:!1});break;case"_null":e.setFilterValue({operator:"_null",value:!0});break;default:e.setFilterValue(void 0)}},l=()=>{e.setFilterValue(void 0)};return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:o,onValueChange:a,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:i.map(c=>n.jsx(we,{value:c,children:ic[c]},c))})]}),s!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:l,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}function uc(e,t,r,s){return!it(e)||!it(t)||!it(r)||s&&(!s.some(o=>o.name===t)||!s.some(o=>o.name===r))?null:`query Lookup${e} { ${e}(sort: [${t}_asc], limit: 100) { data { id: ${r} label: ${t} } } }`}function dc({column:e,joinTable:t,joinLabelColumn:r,joinFkColumn:s}){const o=$e(),a=Je().findTable(t),l=uc(t,r,s,a?.columns),c=mn(a?.columns.find(y=>y.name===s)),{data:m}=de.useQuery({queryKey:["fkLookup",t,r,s],queryFn:()=>o.query(l),staleTime:300*1e3,enabled:!!a&&!!l}),d=m?.[t]?.data??[],f=e.getFilterValue(),p=f?.operator==="_eq"&&f.value!=null?String(f.value):"all",x=y=>{if(y==="all"){e.setFilterValue(void 0);return}e.setFilterValue({operator:"_eq",value:dt(y,c)})},h=()=>{e.setFilterValue(void 0)};return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:p,onValueChange:x,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsxs(nt,{children:[n.jsx(we,{value:"all",children:"All"}),d.map(y=>n.jsx(we,{value:String(y.id),children:String(y.label)},String(y.id)))]})]}),f!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:h,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}function Jn(e){return(e.columnDef.meta?.paramType??"").replace("!","")}function mc(e){return Jn(e)==="String"}function fc(e){return Vt(Jn(e))}function pc(e){return Zs(Jn(e))}function hc(e){return Jn(e)==="Boolean"}function gc(e){const t=e.columnDef.meta;return t?.joinTable?{joinTable:t.joinTable,joinLabelColumn:t.joinLabelColumn??"id",joinFkColumn:t.joinFkColumn??null,isSelfReference:t.isSelfReference===!0}:null}function xc(e){return e.columnDef.meta?.column}function Fo(e){const t=e.paramType.replace("!","");if(e.dbType){const r=e.dbType.toUpperCase();return e.maxLength&&(r.includes("VARCHAR")||r.includes("CHAR"))?`${r}(${e.maxLength})`:(r.includes("DECIMAL")||r.includes("NUMERIC"),r)}return t}function bc(e){const t=e.paramType.replace("!","");return e.isPrimaryKey?n.jsx(C.Key,{className:"size-3.5"}):Vt(t)?n.jsx(C.Hash,{className:"size-3.5"}):Zs(t)?n.jsx(C.Calendar,{className:"size-3.5"}):t==="Boolean"?n.jsx(C.ToggleLeft,{className:"size-3.5"}):n.jsx(C.Type,{className:"size-3.5"})}function yc({column:e,fkMeta:t}){const r=Fo(e),s=e.isNullable,o=e.isPrimaryKey,i=e.isIdentity,a=e.defaultValue;return n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2 border-b pb-2",children:[bc(e),n.jsx("span",{className:"font-semibold text-foreground",children:e.label})]}),n.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:[n.jsx("dt",{className:"text-muted-foreground",children:"Type"}),n.jsx("dd",{className:"text-foreground font-medium",children:r}),n.jsx("dt",{className:"text-muted-foreground",children:"Nullable"}),n.jsx("dd",{className:"text-foreground",children:s?"Yes":"No"}),o&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Primary Key"}),n.jsxs("dd",{className:"text-foreground text-primary flex items-center gap-1",children:[n.jsx(C.Key,{className:"size-3"}),"Yes"]})]}),i&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Auto Increment"}),n.jsx("dd",{className:"text-foreground",children:"Yes"})]}),t&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Foreign Key"}),n.jsxs("dd",{className:"text-foreground text-primary flex items-center gap-1",children:[n.jsx(C.Link2,{className:"size-3"}),t.joinTable,t.isSelfReference&&n.jsx("span",{className:"ml-1 px-1 rounded bg-primary/10 text-[10px] font-medium",children:"self-ref"})]})]}),a!=null&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Default"}),n.jsx("dd",{className:"text-foreground font-mono text-xs truncate max-w-[150px]",children:String(a)})]}),e.maxLength!==void 0&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Max Length"}),n.jsx("dd",{className:"text-foreground",children:e.maxLength})]}),e.min!==void 0&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Min"}),n.jsx("dd",{className:"text-foreground",children:e.min})]}),e.max!==void 0&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Max"}),n.jsx("dd",{className:"text-foreground",children:e.max})]})]})]})}function yn({column:e,table:t,title:r}){const s=t.options.meta?.onResetColumnWidths;if(!e.getCanSort())return n.jsx("span",{children:r});const o=e.getIsSorted(),i=e.getFilterValue()!==void 0,a=gc(e),l=a?.joinFkColumn??null,c=!l&&mc(e),m=!l&&fc(e),d=!l&&pc(e),f=!l&&hc(e),p=xc(e),x=n.jsxs(Q,{variant:"ghost",size:"sm",className:Y("-ml-2 h-7 text-xs data-[state=open]:bg-accent",o&&"text-foreground"),children:[n.jsx("span",{children:r}),i&&n.jsx(C.Filter,{className:"size-3 text-primary"}),o==="desc"?n.jsx(C.ArrowDown,{className:"size-4"}):o==="asc"?n.jsx(C.ArrowUp,{className:"size-4"}):n.jsx(C.ArrowUpDown,{className:"size-4"})]});return n.jsxs(gn,{openDelay:400,closeDelay:200,children:[n.jsx(xn,{asChild:!0,children:n.jsx("span",{className:"inline-flex",children:n.jsxs(Ln,{children:[n.jsx(On,{asChild:!0,children:x}),n.jsxs(An,{align:"start",children:[p&&n.jsxs(n.Fragment,{children:[n.jsxs(Wi,{className:"text-xs font-normal text-muted-foreground",children:[Fo(p),p.isNullable?" · nullable":" · required",p.isPrimaryKey?" · PK":"",a?` · FK → ${a.joinTable}`:""]}),n.jsx(yt,{})]}),n.jsxs(bt,{onClick:()=>e.toggleSorting(!1),children:[n.jsx(C.ArrowUp,{className:"size-3.5 text-muted-foreground"}),"Asc"]}),n.jsxs(bt,{onClick:()=>e.toggleSorting(!0),children:[n.jsx(C.ArrowDown,{className:"size-3.5 text-muted-foreground"}),"Desc"]}),o&&n.jsxs(bt,{onClick:()=>e.clearSorting(),children:[n.jsx(C.ArrowUpDown,{className:"size-3.5 text-muted-foreground"}),"Clear"]}),c&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(nc,{column:e})})]})]}),m&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(oc,{column:e})})]})]}),d&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(ac,{column:e})})]})]}),f&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(cc,{column:e})})]})]}),a&&l&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(dc,{column:e,joinTable:a.joinTable,joinLabelColumn:a.joinLabelColumn,joinFkColumn:l})})]})]}),e.getCanHide()&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(bt,{onClick:()=>e.toggleVisibility(!1),children:[n.jsx(C.EyeOff,{className:"size-3.5 text-muted-foreground"}),"Hide"]})]}),s&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(bt,{onClick:s,children:[n.jsx(C.RotateCcw,{className:"size-3.5 text-muted-foreground"}),"Reset column widths"]})]})]})]})})}),p&&n.jsx(bn,{align:"start",className:"w-64",children:n.jsx(yc,{column:p,fkMeta:a})})]})}const vc=5,jc=400,wc=200;function Cc(e){return e.filter(t=>!t.isPrimaryKey&&!_t(t)).slice(0,vc)}function Nc(e,t,r,s){const o=t.map(i=>i.name).join(" ");return`query FkPreview($id: ${s}) { ${e}(filter: { ${r}: { _eq: $id } } limit: 1) { data { ${o} } } }`}function kc(e,t,r,s){const o=t.map(i=>i.name).join(" ");return`query FkPreview(${r}) { ${e}(filter: ${s} limit: 1) { data { ${o} } } }`}function Sc(e,t,r,s,o,i,a){if(r.length===0)return null;if(s&&Gt(s)&&o){const d=Ri(o,s,t);if(!d)return null;const f=d.params.join(", ");return{query:kc(e,r,f,d.filterText),variables:d.variables,cacheKey:d.variables}}const l=t.columns.find(d=>d.name===a)?.paramType??"Int",c=io(l),m={id:dt(i,c)};return{query:Nc(e,r,a,c),variables:m,cacheKey:`${a}:${i}`}}function Tc({tableName:e,fkValue:t,filterColumn:r,join:s,sourceRow:o,children:i}){const[a,l]=u.useState(!1),c=Je(),m=$e(),d=c.findTable(e),f=d?Cc(d.columns):[],p=d?Sc(e,d,f,s,o,t,r):null,{data:x,isLoading:h}=de.useQuery({queryKey:["fkPreview",e,p?.cacheKey],queryFn:()=>m.query(p.query,p.variables),enabled:a&&!!p,staleTime:300*1e3}),y=x?.[e]?.data?.[0];return n.jsxs(gn,{openDelay:jc,closeDelay:wc,open:a,onOpenChange:l,children:[n.jsx(xn,{asChild:!0,children:i}),n.jsx(bn,{align:"start",className:"w-72",children:n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground",children:d?.label??e}),h&&n.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading..."}),y&&n.jsx("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:f.map(N=>n.jsxs("div",{className:"contents",children:[n.jsx("dt",{className:"text-muted-foreground truncate",children:N.label}),n.jsx("dd",{className:"text-foreground truncate",children:Kn(y[N.name],N,{formatKey:Tl})})]},N.name))}),!h&&!y&&a&&n.jsx("p",{className:"text-xs text-muted-foreground",children:"Record not found"})]})})]})}const $c={json:C.Braces,xml:C.Code,"php-serialized":C.Database,binary:C.Binary,longtext:C.FileText,text:C.FileText},Ec={json:"JSON",xml:"XML","php-serialized":"PHP",binary:"Binary",longtext:"Text",text:"Text"};function Fc(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return e}function _o({value:e,dbType:t,onExpand:r,deferred:s}){if(e===void 0&&s)return n.jsxs("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[n.jsx(C.FileText,{className:"size-3.5"}),n.jsx("span",{className:"text-xs italic",children:"content"}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(C.Expand,{className:"size-3"})})]});if(e==null)return n.jsx(Zt,{kind:"null"});const o=typeof e=="object"?JSON.stringify(e):String(e);if(o==="")return n.jsx(Zt,{kind:"empty"});const i=Bn(o,t);if(i==="text")return n.jsx("span",{children:o});if(i==="binary")return n.jsxs("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[n.jsx(C.Binary,{className:"size-3.5"}),n.jsx("span",{className:"text-xs font-mono",children:xr(o)}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(C.Expand,{className:"size-3"})})]});const a=$c[i],l=sl(o);return o.length>80||i==="json"||i==="xml"||i==="php-serialized"?n.jsxs("span",{className:"inline-flex items-center gap-1.5 max-w-full",children:[n.jsxs(gn,{openDelay:300,closeDelay:200,children:[n.jsx(xn,{asChild:!0,children:n.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 text-left hover:text-primary transition-colors min-w-0",children:[n.jsx(a,{className:"size-3 text-muted-foreground shrink-0"}),n.jsx("span",{className:"font-mono text-xs truncate",children:l})]})}),n.jsxs(bn,{side:"bottom",align:"start",className:"w-[420px] max-h-[320px] p-0",children:[n.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 border-b border-border bg-muted/30",children:[n.jsx(a,{className:"size-3.5 text-muted-foreground"}),n.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:Ec[i]}),n.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:[o.length," chars"]})]}),n.jsx("pre",{className:"p-3 text-xs font-mono overflow-auto max-h-[280px] whitespace-pre-wrap break-all",children:Fc(o,i)})]})]}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(C.Expand,{className:"size-3"})})]}):n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(a,{className:"size-3 text-muted-foreground shrink-0"}),n.jsx("span",{className:"font-mono text-xs",children:o}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(C.Expand,{className:"size-3"})})]})}const Po="gb",Ar="gs",zo=/^[_A-Za-z][_0-9A-Za-z]*$/;function Do(e,t){return!e||!t?null:t.columns.find(r=>r.name===e||r.graphQlName===e)??null}const en={field:"key",desc:!1};function _c(e,t){if(!e||!t)return null;const r=Do(e,t);return r&&/^(byte|short|int|long|float|double|decimal|numeric|money|real)/i.test(r.paramType.replace(/[!\[\]]/g,""))?r:null}function Mo(e,t,r){const s=new URLSearchParams(e);return r?s.set(t,r):s.delete(t),s}function Pc(e){const t=new URLSearchParams(e);return t.delete(Po),t.delete(Ar),t}function Io(e,t,r){const s=[];try{const o=JSON.parse(r);if(Array.isArray(o)&&o.length===4){const[i,a,l,c]=o,m=typeof i=="string"?t.columns.find(d=>d.name===i):void 0;m&&c===m.paramType&&typeof a=="string"&&pn(m.paramType).includes(a)&&s.push({[m.graphQlName]:{[a]:a==="_null"?!!l:l}})}}catch{}for(const o of e){const i=o.value,a=t.columns.find(l=>l.name===o.id);!a||!pn(a.paramType).includes(i.operator)||i.operator!=="_null"&&(i.value===void 0||i.value===null||i.value==="")||s.push({[a.graphQlName]:{[i.operator]:i.operator==="_null"?!!i.value:i.value}})}return s.length===0?void 0:s.length===1?s[0]:{and:s}}function zc(e,t,r,s,o=null,i=en){for(const m of[e.name,e.graphQlName,t.graphQlName,...o?[o.graphQlName]:[]])if(!zo.test(m))throw new Error("Invalid schema-derived grouping name.");const a=Io(r,e,s),l=a?`($filter: ${e.graphQlName}Filter)`:"",c=[a?"filter: $filter":"",`groupBy: [${t.graphQlName}]`].filter(Boolean).join(", ");return{query:`query GridGrouping${l} { ${e.name}Aggregate(${c}) { ${t.graphQlName} _count${o?` _sum { ${o.graphQlName} }`:""} } }`,variables:a?{filter:a}:{},groupBy:t,sumBy:o,sort:i}}function Lo(e,t){return e.value===t.value?0:e.value===null||e.value===void 0?-1:t.value===null||t.value===void 0?1:typeof e.value=="number"&&typeof t.value=="number"?e.value-t.value:String(e.value).localeCompare(String(t.value))}function Dc(e,t,r=en){if(r.field==="count"){const o=e.count-t.count;return o!==0?r.desc?-o:o:Lo(e,t)}const s=Lo(e,t);return r.desc?-s:s}function Mc(e,t,r,s,o=en){const i=e?.[`${t.name}Aggregate`];return Array.isArray(i)?i.map(a=>{const l=a;return{value:l[r.graphQlName],count:Number(l._count??0),sum:s?l._sum?.[s.graphQlName]:void 0}}).sort((a,l)=>Dc(a,l,o)):[]}function Ic(e,t,r,s,o,i=[]){for(const d of[e.name,e.graphQlName,t.graphQlName,...e.columns.map(f=>f.graphQlName)])if(!zo.test(d))throw new Error("Invalid schema-derived grouping name.");const a=Io(s,e,o),l={[t.graphQlName]:r==null?{_null:!0}:{_eq:r}},c=a?{and:[a,l]}:l,m=e.columns.map(d=>d.graphQlName).join(" ");return{query:`query GridGroupMembers($filter: ${e.graphQlName}Filter, $sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int) { ${e.name}(filter: $filter sort: $sort limit: $limit offset: $offset) { total offset limit data { ${m} } } }`,variables:{filter:c,sort:[...i],limit:50,offset:0},responseKey:e.name}}function Lc(e,t){return!e||!t?"":(t.primaryKeys?.length??0)<=1?$t([e?.id]):He(e,t,0)}function Oc(e,t){const r=Math.max(0,t-1);return e<0?0:e>r?r:e}function Oo(e,t){return vr(e)===t?e:jr(t)}function Ac(e,t){const r=t.fieldName??t.destinationTable;return e[r]?.data??[]}function qc(e,t){const r=t.fieldName??t.destinationTable;return e[r]}function Vc(e,t){const r=t.fieldName??t.destinationTable,s=e[r];return s?.total??s?.data?.length??0}function vn(e,t,r={}){return{sortField:e.name,paramType:e.paramType,filterOperators:t,column:e,...r}}function Bc(e,t,r,s,o,i){const a=s.findTable(t.destinationTable),l=a?.labelColumn??"id",c=Gt(t),m=t.destinationTable===r.name,d=m?`Parent ${e.label}`:e.label;return{id:e.name,accessorKey:e.name,header:({column:f,table:p})=>n.jsx(yn,{column:f,table:p,title:d}),enableSorting:!0,meta:vn(e,o,{joinTable:t.destinationTable,joinLabelColumn:l,joinFkColumn:t.destinationColumnNames[0],isSelfReference:m,isCompositeFk:c}),cell:({row:f})=>{const p=qc(f.original,t);if(!p)return n.jsx(Zt,{kind:"null"});const x=Lc(p,a);return x?n.jsxs("span",{className:"group/fk inline-flex items-center gap-0.5",children:[n.jsx(Tc,{tableName:t.destinationTable,fkValue:x,filterColumn:t.destinationColumnNames[0],join:t,sourceRow:f.original,children:n.jsx(Pn,{to:"/"+a?.name+"/"+x,className:"text-primary hover:text-primary/80 hover:underline",children:p?.label})}),i&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"opacity-0 group-hover/fk:opacity-100 size-5 shrink-0",onClick:h=>{h.stopPropagation(),i({tableName:t.destinationTable,filterId:x})},"aria-label":"Open in side column",title:"Open in side column",children:n.jsx(C.PanelRight,{className:"size-3"})})]}):n.jsx(n.Fragment,{children:p?.label})}}}function Gc(e,t,r,s,o,i){if(t){const c=s.findTable(t.destinationTable)?.labelColumn??"id",m=t.destinationTable===r.name;return{id:e.name,accessorFn:d=>e.name?String(d?.[e.name]??""):"",cell:({row:d})=>Kn(d.original[e.name],e),header:({column:d,table:f})=>n.jsx(yn,{column:d,table:f,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType,joinTable:t.destinationTable,joinLabelColumn:c,joinFkColumn:Yi(t,e.name),isSelfReference:m,isCompositeFk:!0,isCompositeFkMember:!0})}}return e?.paramType==="DateTime"?{id:e.name,accessorFn:l=>xo(l?.[e.name]),cell:({row:l})=>{const c=l.original[e.name];return c==null||c===""?n.jsx(Zt,{kind:c===""?"empty":"null"}):xo(c)},header:({column:l,table:c})=>n.jsx(yn,{column:l,table:c,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType})}:_t(e)||Ft(e)?{id:e.name,accessorFn:l=>e.name?String(l?.[e.name]??""):"",header:({column:l,table:c})=>n.jsx(yn,{column:l,table:c,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType}),cell:({row:l})=>n.jsx(_o,{value:l.original[e.name],dbType:e.dbType,deferred:_t(e),onExpand:i?()=>i(l.index,e.name):void 0})}:{id:e.name,accessorFn:l=>e.name?String(l?.[e.name]??""):"",cell:({row:l})=>{const c=l.original[e.name];if(typeof c=="string"&&c.length>1){const m=Bn(c);if(m==="json"||m==="xml"||m==="php-serialized")return n.jsx(_o,{value:c,dbType:e.dbType,onExpand:i?()=>i(l.index,e.name):void 0})}return Kn(c,e)},header:({column:l,table:c})=>n.jsx(yn,{column:l,table:c,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType})}}const Kc=(e,t,r,s)=>{if(!e||!t)return[];const o=e.columns.map(a=>{const l=e.singleJoins.find(d=>d.sourceColumnNames?.[0]===a.name),c=l?void 0:e.singleJoins.find(d=>(d.sourceColumnNames??[]).includes(a.name)),m=pn(a.paramType);return l?Bc(a,l,e,t,m,s):Gc(a,c,e,t,m,r)}),i=e.multiJoins.map(a=>{const l=t.findTable(a.destinationTable),c=l?.labelColumn??"id",d=a.destinationTable===e.name?`Child ${l?.label??a.destinationTable}`:l?.label??a.destinationTable;return{id:`join_${a.fieldName??a.destinationTable}`,header:d,enableSorting:!1,enableHiding:!0,cell:({row:f})=>{const p=dl(f.original,e,f.index),x=Ac(f.original,a),h=Vc(f.original,a);if(h===0)return n.jsx("span",{className:"text-muted-foreground",children:"—"});const y=x.slice(0,10).map(T=>String(T[c]??"")).filter(Boolean),N=l?.label??a.destinationTable;return n.jsxs("span",{className:"group/fk inline-flex items-center gap-1",children:[n.jsxs(gn,{openDelay:300,closeDelay:100,children:[n.jsx(xn,{asChild:!0,children:n.jsxs(Pn,{to:"/"+l?.name+"/from/"+e.name+"/"+p,className:"inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs font-medium text-primary hover:bg-muted hover:border-primary/40 transition-colors",children:[n.jsx(C.List,{className:"size-3"}),h]})}),n.jsxs(bn,{align:"start",sideOffset:6,className:"w-auto max-w-xs p-3",children:[n.jsxs("div",{className:"flex items-center gap-2 border-b pb-2 mb-2",children:[n.jsx(C.List,{className:"size-3.5 text-primary"}),n.jsxs("span",{className:"text-xs font-semibold text-foreground",children:[h," ",N]})]}),n.jsxs("ul",{className:"space-y-0.5 text-xs text-foreground",children:[y.map((T,k)=>n.jsx("li",{className:"truncate",children:T},k)),h>10&&n.jsxs("li",{className:"text-muted-foreground italic",children:["… and ",h-10," more"]})]})]})]}),s&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"opacity-40 group-hover/fk:opacity-100 size-5 shrink-0 transition-opacity",onClick:T=>{T.stopPropagation(),s({tableName:a.destinationTable,filterTable:e.name,filterId:p,...Gt(a)?{}:{filterColumn:a.destinationColumnNames[0]}})},"aria-label":"Open in side column",title:"Open in side column",children:n.jsx(C.PanelRight,{className:"size-3"})})]})}}});return[...o,...i]};function Wc(e,t,r,s,o){if(!s&&!o)return wr(e,t);const i=$r(t,r,s,o);return i?wr(e,i.parentTable):wr(e,t)}function Jc(e,t,r,s,o,i){const{search:a}=hs(),l=_n(),c=a.get("filter")??"",m=a.get("cf")??"",d=a.get("gb"),f=a.get("gs"),p=u.useMemo(()=>yr(c).variables,[c]),x=Je(),h=$e(),[y,N]=u.useState([]),[T,k]=u.useState(en),[$,b]=u.useState(()=>jr(m)),[v,w]=u.useState(0),[F,j]=u.useState(50),V=u.useRef(e);e&&e!==V.current&&(V.current=e,y.length>0&&N([]),T!==en&&k(en),v!==0&&w(0)),u.useEffect(()=>{b(W=>Oo(W,m))},[m]);const S=u.useMemo(()=>Oo($,m),[$,m]),L=u.useRef(e?.name),A=L.current!==e?.name;A&&(L.current=e?.name);const D=u.useMemo(()=>A?null:Do(d,e),[A,d,e]),B=u.useMemo(()=>A?null:_c(f,e),[A,f,e]);u.useEffect(()=>{if(!A||!d)return;const me=Pc(a).toString();l(me?`?${me}`:"?")},[A,d,a,l]);const X=u.useMemo(()=>{if(!e)return"id";const W=zt(e)[0]?.name;if(W&&e.columns.some(ve=>ve.name===W))return W;const me=gl(e,ve=>!_t(ve)&&!Ft(ve));return me||(e.columns.find(ve=>!_t(ve)&&!Ft(ve))?.name??e.columns.at(0)?.name??"id")},[e]),E=u.useMemo(()=>{if(y.length>0&&e){const W=y[0];if(e.columns.some(Ne=>Ne.name===W.id))return[`${W.id}_${W.desc?"desc":"asc"}`]}return e?[`${X}_asc`]:[]},[y,e,X]),P=u.useMemo(()=>Sr(e,x,c,S,t,r,s),[e,x,c,S,t,r,s]),q=u.useMemo(()=>e?Gn(S,e).variables:{},[S,e]),U=u.useMemo(()=>{if(!e)return null;const W=co(e,c,S);return W.length===0?null:new Error(`These rows can't be shown because the filter can't be applied: ${W.join(" ")}`)},[e,c,S]),_=v*F,ce=u.useMemo(()=>({sort:E,limit:F,offset:_,...t&&e?Wc(t,e,x,r,s):{},...p,...q}),[E,F,_,t,e,x,r,s,p,q]),{isLoading:he,isFetching:Ue,error:Pe,data:ie}=de.useQuery({queryKey:["tableData",e?.name,P,ce],queryFn:({signal:W})=>h.query(P,ce,{signal:W}),enabled:!!P&&!!e&&E.length>0,placeholderData:(W,me)=>me?.queryKey?.[1]===e?.name?W:void 0}),se=u.useMemo(()=>e&&D?zc(e,D,S,c,B,T):null,[e,D,B,S,c,T]),ke=de.useQuery({queryKey:["tableGrouping",e?.name,se?.query,se?.variables],queryFn:({signal:W})=>h.query(se.query,se.variables,{signal:W}),enabled:se!==null,placeholderData:void 0}),Ae=u.useMemo(()=>e?Kc(e,x,o,i):[],[e,x,o,i]),re=u.useMemo(()=>t&&(r||s)&&e?$r(e,x,r,s):null,[t,r,s,e,x]);let Ee,Ie;if(re&&!Tr(re.childJoin)){const W=po(ie,re.parentTable.name,re.childField);Ee=W.data,Ie=W.total}else{const W=ie?.[e?.name??""];Ee=W?.data??[],Ie=W?.total??0}const Le=Math.max(1,Math.ceil(Ie/F));u.useEffect(()=>{const W=Oc(v,Le);W!==v&&w(W)},[v,Le]);const Ge=u.useCallback(W=>{const me=new URLSearchParams(a),Ne=vr(W);Ne?me.set("cf",Ne):me.delete("cf");const ve=me.toString();l(ve?`?${ve}`:"?")},[a,l]),Oe=u.useCallback(W=>{N(W),w(0)},[]),ye=u.useCallback(W=>{b(W),w(0),Ge(W)},[Ge]),ze=u.useCallback(W=>{w(W)},[]),O=u.useCallback(W=>{j(W),w(0)},[]),Z=u.useCallback(W=>{const me=Mo(a,Po,W);W||me.delete(Ar);const Ne=me.toString();l(Ne?`?${Ne}`:"?")},[a,l]),ee=u.useCallback(W=>{const Ne=Mo(a,Ar,W).toString();l(Ne?`?${Ne}`:"?")},[a,l]),Ce=e?.primaryKeys??[],xe=u.useMemo(()=>e?Sr(e,x,c,S,t,r,s,{fields:"export"}):null,[e,x,c,S,t,r,s]),qe=u.useCallback(async W=>{if(!xe||!e)return null;const me=kr(e),Ne=me.map(rt=>rt.label),ve=me.map(rt=>rt.name);return _r({headers:Ne,format:W.format,signal:W.signal,onProgress:W.onProgress,rowCap:W.rowCap,csv:{bom:!0},fetchPage:async(rt,Mt)=>{const be={...ce,limit:Mt,offset:rt},ft=await h.query(xe,be,{signal:W.signal});let Nt,Ye;if(re&&!Tr(re.childJoin)){const Xe=po(ft,re.parentTable.name,re.childField);Nt=Xe.data,Ye=Xe.total}else{const Xe=ft?.[e.name];Nt=Xe?.data??[],Ye=Xe?.total??0}return{rows:Nt.map(Xe=>ve.map(Qt=>Xe[Qt])),total:Ye}}})},[xe,e,ce,h,re]);return{columns:Ae,sorting:y,columnFilters:$,primaryKeys:Ce,pageIndex:v,pageSize:F,pageCount:Le,rows:Ee,totalRows:Ie,grouping:se?{column:se.groupBy,sumColumn:se.sumBy,rows:Mc(ke.data,e,se.groupBy,se.sumBy,se.sort),loading:ke.isLoading,error:ke.error,sort:se.sort,onSortChange:k,memberRequest:W=>Ic(e,se.groupBy,W,S,c,E)}:null,exportRows:qe,loading:he,fetching:Ue&&!he,error:U??Pe,onSortingChange:Oe,onColumnFiltersChange:ye,onPageIndexChange:ze,onPageSizeChange:O,onGroupingChange:Z,onGroupingSumChange:ee}}const Qc=new Set(["tableData","editRecord","tableRowCounts","m2mRows","fkPreview"]),Hc=new Set(["tableRef","tableRefValue","compositeTableRef","m2mTargets"]);function jn(e,t){return e.invalidateQueries({predicate:r=>{const[s,o]=r.queryKey;return typeof s!="string"?!1:Qc.has(s)?!0:Hc.has(s)?o===t:!1}})}function Uc(e){return typeof e=="object"&&e!==null}function Ao(e,t){if(e==null)return null;if(!t)return e;const r=ut(t);if(Bt(t))return String(e);if(qt(t)){const s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?Math.trunc(s):e}if(r==="Float"){const s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?s:e}return r==="Boolean"?typeof e=="boolean"?e:e==="true"||e===1:String(e)}function Qn(e){je(e.name,"delete mutation table name");const t=$e(),r=de.useQueryClient(),{toast:s}=vt(),o=u.useMemo(()=>{const h=new Map;for(const y of e.columns)h.set(y.name,y.paramType);return h},[e]),i=u.useMemo(()=>e.primaryKeys??[],[e]),a=h=>{if(i.length===0)throw new Error(`Cannot delete from '${e.name}': the table has no primary key.`);const y={};if(Uc(h)){for(const T of i){const k=h[T];if(k==null)throw new Error(`Cannot delete row: missing value for primary-key column '${T}'.`);y[T]=Ao(k,o.get(T))}return y}if(i.length!==1)throw new Error(`Cannot delete from '${e.name}': composite primary key requires an object key, not a scalar.`);if(h==null)throw new Error(`Cannot delete row: missing value for primary-key column '${i[0]}'.`);const N=i[0];return y[N]=Ao(h,o.get(N)),y},l=u.useMemo(()=>`mutation deleteSingle($detail: Delete_${e.name}){
79
91
  ${e.name}(delete: $detail)
80
- }`,[e]),u=c.useMemo(()=>`mutation batchDelete($actions: [batch_${e.name}!]!){
81
- ${e.name}_batch(actions: $actions)
82
- }`,[e]),d=me.useMutation({mutationFn:g=>n.query(l,{detail:g}),onSuccess:()=>{nn(r,e.name),s("Row deleted")}}),p=me.useMutation({mutationFn:g=>n.query(u,{actions:g}),onSuccess:(g,b)=>{nn(r,e.name);const k=b.length;s(`${k} ${k===1?"row":"rows"} deleted`)}}),m=g=>{let b;try{b=a(g)}catch(k){return Promise.reject(k)}return d.mutateAsync(b)},h=g=>{let b;try{b=g.map(k=>({delete:a(k)}))}catch(k){return Promise.reject(k)}return p.mutateAsync(b)},x=d.error??p.error;return{deleteRow:m,deleteRows:h,isPending:d.isPending||p.isPending,error:x}}const ds=["Int","Int!","Float","Float!"],Ri=["BigInt","BigInt!"],Xi=["Boolean","Boolean!"];function us(e,n,r){const s=n.replace("!","");if(typeof e=="number"){if(Number.isFinite(e)&&(s!=="Int"||Number.isInteger(e)))return e;throw new Error(`Invalid ${s} value for column '${r}'.`)}const o=String(e).trim();if(!(s==="Int"?/^[+-]?\d+$/.test(o):/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(o)))throw new Error(`Invalid ${s} value for column '${r}'.`);const a=Number(o);if(!Number.isFinite(a))throw new Error(`Invalid ${s} value for column '${r}'.`);return a}function ms(e,n,r,s,o){const i={...e};for(const{column:a}of n){if(i[a.name]===null){i[a.name]=o?void 0:null;continue}if(ds.some(l=>l===a.paramType)){const l=i[a.name];i[a.name]=l==null?void 0:l===""?o?void 0:null:us(l,a.paramType,a.name)}if(Ri.some(l=>l===a.paramType)){const l=i[a.name];i[a.name]=l==null?void 0:l===""?o?void 0:null:String(l)}if(Xi.some(l=>l===a.paramType)){const l=i[a.name];a.isNullable&&l==null?i[a.name]=o?void 0:null:i[a.name]=!!l}if(lt(a)){const l=i[a.name];if(typeof l=="string"&&l.trim()!=="")try{i[a.name]=JSON.parse(l)}catch{}}}if(!o&&s)for(const a of r){const l=s[a.name];ds.some(u=>u===a.paramType)?i[a.name]=l==null?null:us(l,a.paramType,a.name):i[a.name]=l}return i}function sn(e,n,r,s){Fe(e.name,"table mutation table name");const o=Ce(),i=me.useQueryClient(),{toast:a}=rn(),l=s===void 0||s==="",u=c.useMemo(()=>`mutation updateSingle($detail: Update_${e.name}){
92
+ }`,[e]),c=u.useMemo(()=>`mutation deleteMany($delta: ${e.name}_delta){
93
+ ${e.name}(delta: $delta)
94
+ }`,[e]),m=de.useMutation({mutationFn:h=>t.query(l,{detail:h}),onSuccess:()=>{jn(r,e.name),s("Row deleted")}}),d=de.useMutation({mutationFn:h=>t.query(c,{delta:{deleted:h}}),onSuccess:(h,y)=>{jn(r,e.name);const N=y.length;s(`${N} ${N===1?"row":"rows"} deleted`)}}),f=h=>{let y;try{y=a(h)}catch(N){return Promise.reject(N)}return m.mutateAsync(y)},p=h=>{let y;try{y=h.map(N=>a(N))}catch(N){return Promise.reject(N)}return d.mutateAsync(y)},x=m.error??d.error;return{deleteRow:f,deleteRows:p,isPending:m.isPending||d.isPending,error:x}}function Yc(e){return(e.inserted?.length??0)+(e.updated?.length??0)+(e.deleted?.length??0)}function qo(e){je(e.name,"delta mutation table name");const t=$e(),r=de.useQueryClient(),{toast:s}=vt(),o=u.useMemo(()=>`mutation saveDelta($delta: ${e.name}_delta){
95
+ ${e.name}(delta: $delta)
96
+ }`,[e]),i=de.useMutation({mutationFn:a=>t.query(o,{delta:a}),onSuccess:(a,l)=>{jn(r,e.name);const c=Yc(l);s(`${c} ${c===1?"change":"changes"} saved`)}});return{saveDelta:a=>i.mutateAsync(a),isPending:i.isPending,error:i.error}}function Rc(e){return Vt(e.paramType)}function Xc(e){return qt(e.paramType)}const Zc={Int:{min:-2147483648,max:2147483647},Short:{min:-32768,max:32767},Byte:{min:0,max:255}},eu=-(2n**63n),tu=2n**63n-1n;function nu(e){const t=(e.dbType??"").toLowerCase().trim(),r=t.includes("(")?t.slice(0,t.indexOf("(")).trimEnd():t;if(r==="datetimeoffset"||r==="datetime"||r==="datetime2"||r==="smalldatetime"||r.startsWith("timestamp"))return"datetime";if(r==="date")return"date";if(r.startsWith("time"))return"time"}function ru(e){const t=/^[+-]?(\d*)(?:\.\d*)?$/.exec(e.trim());return t?t[1].replace(/^0+/,"").length:void 0}function su(e){return e.startsWith("^")?e:`^(?:${e})$`}function ou(e){if(e!==e.trim()||/\s/.test(e))return!1;const t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return!1;const r=e.slice(t+1);return r.includes(".")&&!r.startsWith(".")&&!r.endsWith(".")}function au(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function qr(e,t,r){const s=e.label;if(r&&(t==null||t===""))return`${s} is required`;if(t==null||t==="")return;if(typeof t=="string"){if(e.pattern){let i;try{i=new RegExp(su(e.pattern))}catch{return`${s} has an invalid validation pattern`}if(!i.test(t))return e.patternMessage||`${s} format is invalid`}if(e.minLength&&t.length<e.minLength)return`${s} must be at least ${e.minLength} characters`;if(e.maxLength&&t.length>e.maxLength)return`${s} must be at most ${e.maxLength} characters`;if(e.inputType==="email"&&!ou(t))return"Invalid email address";if(e.inputType==="url"&&!au(t))return"Invalid URL"}const o=nu(e);if(o&&typeof t=="string"){if(!(o==="time"?/^\d{1,2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(t.trim()):!Number.isNaN(new Date(t).getTime())))return`${s} must be a valid ${o==="datetime"?"date/time":o}`;if(o!=="time"){const a=new Date(t).getTime(),l=typeof e.min=="string"?new Date(e.min).getTime():NaN,c=typeof e.max=="string"?new Date(e.max).getTime():NaN;if(!Number.isNaN(l)&&a<l)return`${s} must be on or after ${e.min}`;if(!Number.isNaN(c)&&a>c)return`${s} must be on or before ${e.max}`}return}if(ut(e.paramType)==="BigInt"&&typeof t=="string"&&t.trim()!==""){const i=t.trim();if(!/^[+-]?\d+$/.test(i))return`${s} must be a whole number`;const a=BigInt(i);return a<eu||a>tu?`${s} is out of range for a 64-bit integer`:void 0}if(e.precision!=null&&(typeof t=="string"||typeof t=="number")){const i=Math.max(e.precision-(e.scale??0),0),a=ru(String(t));if(a!==void 0&&a>i)return`${s} must have at most ${i} digits before the decimal point`}if(Rc(e)){const i=Number(t);if(!Number.isFinite(i))return`${s} must be a number`;if(Xc(e)&&!Number.isInteger(i))return`${s} must be a whole number`;const a=Zc[ut(e.paramType)];if(a&&(i<a.min||i>a.max))return`${s} must be between ${a.min} and ${a.max}`;const l=e.min==null?NaN:Number(e.min),c=e.max==null?NaN:Number(e.max);if(!Number.isNaN(l)&&i<l)return`${s} must be at least ${e.min}`;if(!Number.isNaN(c)&&i>c)return`${s} must be at most ${e.max}`}}function Hn(e,t){const r=[];for(const s of e){const o=t[s.name];if(o==null||o==="")continue;const i=qr(s,o,!1);i&&r.push(i)}return r}const Vo=e=>Vt(e)&&!Bt(e),iu=["Boolean","Boolean!"];function Bo(e,t,r){const s=ut(t),o=qt(t);if(typeof e=="number"){if(Number.isFinite(e)&&(!o||Number.isInteger(e)))return e;throw new Error(`Invalid ${s} value for column '${r}'.`)}const i=String(e).trim();if(!(o?/^[+-]?\d+$/.test(i):/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(i)))throw new Error(`Invalid ${s} value for column '${r}'.`);const l=Number(i);if(!Number.isFinite(l))throw new Error(`Invalid ${s} value for column '${r}'.`);return l}function Un(e,t,r,s,o){const i={...e};for(const{column:a}of t){if(i[a.name]===null){i[a.name]=o?void 0:null;continue}if(Vo(a.paramType)){const l=i[a.name];i[a.name]=l==null?void 0:l===""?o?void 0:null:Bo(l,a.paramType,a.name)}if(Bt(a.paramType)){const l=i[a.name];i[a.name]=l==null?void 0:l===""?o?void 0:null:String(l)}if(iu.some(l=>l===a.paramType)){const l=i[a.name];a.isNullable&&l==null?i[a.name]=o?void 0:null:i[a.name]=!!l}if(Ft(a)){const l=i[a.name];if(typeof l=="string"&&l.trim()!=="")try{i[a.name]=JSON.parse(l)}catch{}}}if(!o&&s)for(const a of r){const l=s[a.name];Vo(a.paramType)?i[a.name]=l==null?null:Bo(l,a.paramType,a.name):i[a.name]=l}return i}function lu(e,t,r,s,o){const i=t.map(a=>({column:a}));return s.map(a=>{const l=mt(a,e);if(!l)throw new Error("Cannot bulk edit: a selected row has no resolvable primary key.");const c={};for(const d of t)c[d.name]=a[d.name]??null;Object.assign(c,o);const m=Hn(t,c);if(m.length>0)throw new Error(m.join(" "));return Un(c,i,r,l,!1)})}function cu(e,t,r,s,o){return s.map(i=>{const a=o(i);if(!a||Object.keys(a).length===0)throw new Error("Cannot save: a fetched row carries no staged changes.");const l=mt(i,e);if(!l)throw new Error("Cannot save: an edited row has no resolvable primary key.");const c=t.filter(f=>!f.isNullable||f.name in a),m={};for(const f of c)m[f.name]=i[f.name]??null;Object.assign(m,a);const d=Hn(c,m);if(d.length>0)throw new Error(d.join(" "));return Un(m,c.map(f=>({column:f})),r,l,!1)})}function wn(e,t,r,s){je(e.name,"table mutation table name");const o=$e(),i=de.useQueryClient(),{toast:a}=vt(),l=s===void 0||s==="",c=u.useMemo(()=>`mutation updateSingle($detail: Update_${e.name}){
83
97
  ${e.name}(update: $detail)
84
- }`,[e]),d=c.useMemo(()=>`mutation insertSingle($detail: Insert_${e.name}){
98
+ }`,[e]),m=u.useMemo(()=>`mutation insertSingle($detail: Insert_${e.name}){
85
99
  ${e.name}(insert: $detail)
86
- }`,[e]),p=me.useMutation({mutationFn:k=>o.query(u,{detail:k}),onSuccess:()=>{nn(i,e.name),a(`${e.label??e.name} saved`)}}),m=me.useMutation({mutationFn:k=>o.query(d,{detail:k}),onSuccess:()=>{nn(i,e.name),a(`${e.label??e.name} created`)}}),h=c.useMemo(()=>l||!s?null:jn(s,e),[l,s,e]),x=k=>{if(!h||r.length===0)return Promise.reject(new Error(`Cannot update ${e.label??e.name}: the record has no resolvable primary key.`));let $;try{$=ms(k,n,r,h,!1)}catch(w){return Promise.reject(w)}return p.mutateAsync($)},g=k=>{let $;try{$=ms(k,n,r,null,!0)}catch(w){return Promise.reject(w)}return m.mutateAsync($)},b=p.error??m.error;return{update:x,insert:g,isPending:p.isPending||m.isPending,error:b}}const Ui=1e3,Zi=50;function fs(e){const n=e.labelColumn||Qe(e)[0]?.name||e.columns[0]?.name;if(!n)throw new Error(`Table '${e.name}' has no usable label column for a reference dropdown.`);return n}function el(e,n,r){Fe(e.name,"reference table name"),Fe(n,"reference key column");const s=fs(e);if(Fe(s,"reference label column"),!e.columns.some(p=>p.name===n))throw new Error(`Reference table '${e.name}' has no key column '${n}'.`);const i=e.columns.find(p=>p.name===s)?.paramType?.replace("!","")==="String",a=!!r&&r.trim()!==""&&i,l=a?"$limit: Int, $search: String":"$limit: Int",u=a?`filter: {${s}: {_contains: $search}} `:"";return{query:`query Get_${e.name}_Ref(${l}) {
87
- values: ${e.name}(${u}limit: $limit sort: [${s}_asc]) {
100
+ }`,[e]),d=de.useMutation({mutationFn:$=>o.query(c,{detail:$}),onSuccess:()=>{jn(i,e.name),a(`${e.label??e.name} saved`)}}),f=de.useMutation({mutationFn:$=>o.query(m,{detail:$}),onSuccess:()=>{jn(i,e.name),a(`${e.label??e.name} created`)}}),p=u.useMemo(()=>l||!s?null:fn(s,e),[l,s,e]),[x,h]=u.useState(null),y=$=>{const b=$ instanceof Error?$:new Error(String($));return h(b),Promise.reject(b)},N=$=>{if(h(null),!p||r.length===0)return y(new Error(`Cannot update ${e.label??e.name}: the record has no resolvable primary key.`));const b=Hn(t.map(w=>w.column),$);if(b.length>0)return y(new Error(b.join(" ")));let v;try{v=Un($,t,r,p,!1)}catch(w){return y(w)}return d.mutateAsync(v)},T=$=>{h(null);const b=Hn(t.map(w=>w.column),$);if(b.length>0)return y(new Error(b.join(" ")));let v;try{v=Un($,t,r,null,!0)}catch(w){return y(w)}return f.mutateAsync(v)},k=x??d.error??f.error;return{update:N,insert:T,isPending:d.isPending||f.isPending,error:k}}const uu=1e3,du=50;function Go(e){const t=e.labelColumn||zt(e)[0]?.name||e.columns[0]?.name;if(!t)throw new Error(`Table '${e.name}' has no usable label column for a reference dropdown.`);return t}function mu(e,t,r){je(e.name,"reference table name"),je(t,"reference key column");const s=Go(e);if(je(s,"reference label column"),!e.columns.some(d=>d.name===t))throw new Error(`Reference table '${e.name}' has no key column '${t}'.`);const i=e.columns.find(d=>d.name===s)?.paramType?.replace("!","")==="String",a=!!r&&r.trim()!==""&&i,l=a?"$limit: Int, $search: String":"$limit: Int",c=a?`filter: {${s}: {_contains: $search}} `:"";return{query:`query Get_${e.name}_Ref(${l}) {
101
+ values: ${e.name}(${c}limit: $limit sort: [${s}_asc]) {
88
102
  data {
89
- key: ${n}
103
+ key: ${t}
90
104
  label: ${s}
91
105
  }
92
106
  }
93
- }`,labelColumn:s,serverSearch:i}}function tl(e,n){Fe(e.name,"reference table name"),Fe(n,"reference key column");const r=fs(e);Fe(r,"reference label column");const s=e.columns.find(a=>a.name===n);if(!s)throw new Error(`Reference table '${e.name}' has no key column '${n}'.`);const o=s.paramType.replace("!","");return{query:`query Get_${e.name}_RefValue($key: ${o}) {
94
- values: ${e.name}(filter: {${n}: {_eq: $key}} limit: 1) {
107
+ }`,labelColumn:s,serverSearch:i}}function fu(e,t){je(e.name,"reference table name"),je(t,"reference key column");const r=Go(e);je(r,"reference label column");const s=e.columns.find(a=>a.name===t);if(!s)throw new Error(`Reference table '${e.name}' has no key column '${t}'.`);const o=s.paramType.replace("!","");return{query:`query Get_${e.name}_RefValue($key: ${o}) {
108
+ values: ${e.name}(filter: {${t}: {_eq: $key}} limit: 1) {
95
109
  data {
96
- key: ${n}
110
+ key: ${t}
97
111
  label: ${r}
98
112
  }
99
113
  }
100
- }`,keyType:o}}function nl(e,n){return Xe(n,e)}function ps(e,n){return e?.data?.find(r=>r.graphQlName===n)}function rl(e,n,r,s="",o=!0){const i=Ce(),a=c.useMemo(()=>ps(e,n),[e,n]),l=s.trim(),u=c.useMemo(()=>e.loading||e.error||!a?null:el(a,r,l),[r,a,e.loading,e.error,l]),d=u?.serverSearch?l:"",{isLoading:p,error:m,data:h}=me.useQuery({queryKey:["tableRef",n,r,d],queryFn:({signal:x})=>i.query(u.query,d?{limit:Zi,search:d}:{limit:Ui},{signal:x}),enabled:!!u&&o});return{loading:p||e.loading,error:m||e.error,data:h?.values?.data??[],serverSearch:u?.serverSearch??!1}}function sl(e,n,r,s){const o=Ce(),i=c.useMemo(()=>ps(e,n),[e,n]),a=!e.loading&&!e.error&&!!i&&s!=null&&s!=="",l=c.useMemo(()=>a?tl(i,r):null,[a,i,r]),{isLoading:u,error:d,data:p}=me.useQuery({queryKey:["tableRefValue",n,r,String(s??"")],queryFn:({signal:m})=>o.query(l.query,{key:nl(l.keyType,s)},{signal:m}),enabled:!!l});return{loading:u,error:d||e.error,value:p?.values?.data?.at(0)??null}}const ol=500,al=50;function il(e,n,r,s={}){const o=Ce(),{search:i="",enabled:a=!0,currentValues:l=null}=s,u=i.trim(),d=c.useMemo(()=>e?.data?.find(L=>L.graphQlName===n),[e,n]),p=c.useMemo(()=>d?.labelColumn||r[0],[d,r]),m=c.useMemo(()=>d?.columns.find(v=>v.name===p)?.paramType?.replace("!","")==="String",[d,p]),h=c.useMemo(()=>{if(!d||r.length===0||!Ie(n)||!Ie(p))return!1;const L=new Set(d.columns.map(v=>v.name));return L.has(p)?r.every(v=>Ie(v)&&L.has(v)):!1},[d,n,r,p]),x=c.useMemo(()=>{if(!d||!h)return"";const L=new Set(r);return L.add(p),Array.from(L).join(" ")},[d,h,r,p]),g=!!u&&m,b=c.useMemo(()=>{if(e.loading||e.error||!d||r.length===0||!h)return null;const L=g?"($limit: Int, $search: String)":"($limit: Int)",v=g?`filter: {${p}: {_contains: $search}} `:"";return`query Get_${n}_CompositeRef${L} { values: ${n}(${v}limit: $limit sort: [${p}_asc]) { data { ${x} } } }`},[d,n,x,p,g,e.loading,e.error,r.length,h]),k=m?u:"",{isLoading:$,error:w,data:P}=me.useQuery({queryKey:["compositeTableRef",n,r.join("|"),k],queryFn:()=>o.query(b,k?{limit:al,search:k}:{limit:ol}),enabled:!!b&&a}),C=c.useMemo(()=>{if(!d||!P)return[];const L={primaryKeys:r};return(P.values?.data??[]).map((v,M)=>{const O={};for(const I of r)O[I]=v[I];const z=_t(v,L,M);return{route:z,values:O,label:String(v[p]??z)}})},[d,r,p,P]),T=c.useMemo(()=>{if(!l)return"";const L=[];for(const v of r){const M=l[v];if(M==null||M==="")return"";L.push(M)}return xt(L)},[l,r]),j=T===""||C.some(L=>L.route===T),E=c.useMemo(()=>{if(!d||!h||j||T===""||!l)return null;const L=new Map(d.columns.map(_=>[_.name,_])),v=[],M=[],O={};for(let _=0;_<r.length;_++){const G=r[_],U=Xt(L.get(G)),ie=`k${_}`;M.push(`$${ie}: ${U}`),v.push(`{${G}: {_eq: $${ie}}}`),O[ie]=Xe(l[G],U)}const z=v.length===1?v[0]:`{and: [${v.join(", ")}]}`;return{query:`query Get_${n}_CompositeRefValue(${M.join(", ")}) { values: ${n}(filter: ${z} limit: 1) { data { ${x} } } }`,variables:O}},[d,n,x,r,j,T,l,h]),{data:y}=me.useQuery({queryKey:["compositeTableRefValue",n,T],queryFn:()=>o.query(E.query,E.variables),enabled:!!E}),S=c.useMemo(()=>{const L=y?.values?.data?.[0];if(!L)return C;const v={};for(const O of r)v[O]=L[O];const M=xt(r.map(O=>L[O]));return C.some(O=>O.route===M)?C:[{route:M,values:v,label:String(L[p]??M)},...C]},[C,y,r,p]);return{loading:$||e.loading,error:w||e.error,data:S,serverSearch:m}}const ll=new Set(["Int","Int!","Float","Float!","Decimal","Decimal!"]);function cl(e){return ll.has(e.paramType)}function dl(e){return e.startsWith("^")?e:`^(?:${e})$`}function ul(e){if(e!==e.trim()||/\s/.test(e))return!1;const n=e.lastIndexOf("@");if(n<=0||n===e.length-1)return!1;const r=e.slice(n+1);return r.includes(".")&&!r.startsWith(".")&&!r.endsWith(".")}function ml(e){try{const n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function fl(e,n,r){const s=e.label;if(r&&(n==null||n===""))return`${s} is required`;if(!(n==null||n==="")){if(typeof n=="string"){if(e.pattern){let o;try{o=new RegExp(dl(e.pattern))}catch{return`${s} has an invalid validation pattern`}if(!o.test(n))return e.patternMessage||`${s} format is invalid`}if(e.minLength&&n.length<e.minLength)return`${s} must be at least ${e.minLength} characters`;if(e.maxLength&&n.length>e.maxLength)return`${s} must be at most ${e.maxLength} characters`;if(e.inputType==="email"&&!ul(n))return"Invalid email address";if(e.inputType==="url"&&!ml(n))return"Invalid URL"}if(cl(e)){const o=Number(n);if(!Number.isNaN(o)){if(e.min!==void 0&&e.min!==null&&o<e.min)return`${s} must be at least ${e.min}`;if(e.max!==void 0&&e.max!==null&&o>e.max)return`${s} must be at most ${e.max}`}}}}const pl=new Set(["DateTime","DateTime!"]);function _n(e){return pl.has(e.paramType)}function Fn(e){return rs(e)==="datetime"}function hs(e,n){if(!e)return"";const r=e.match(/^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}(?::\d{2})?))?/);if(!r||r[1]==="0001-01-01")return"";if(!n||!r[2])return r[1];const s=r[2].length===5?`${r[2]}:00`:r[2];return`${r[1]}T${s}`}function hl(e,n,r){const s={...e};for(const o of r){if(!_n(o))continue;const i=n[o.name];typeof i!="string"||i===""||hs(i,Fn(o))===s[o.name]&&(s[o.name]=i)}return s}function xs(e,n,r){const s=e;return String(s.label??s[n]??"").toLowerCase().includes(r.toLowerCase())}const Ze=ve.forwardRef(({...e},n)=>t.jsx(Q.Dialog.Root,{"data-slot":"dialog",...e}));Ze.displayName="Dialog";const xl=ve.forwardRef(({...e},n)=>t.jsx(Q.Dialog.Trigger,{"data-slot":"dialog-trigger",...e}));xl.displayName="DialogTrigger";const gs=ve.forwardRef(({...e},n)=>t.jsx(Q.Dialog.Portal,{"data-slot":"dialog-portal",...e}));gs.displayName="DialogPortal";const gl=ve.forwardRef(({...e},n)=>t.jsx(Q.Dialog.Close,{"data-slot":"dialog-close",...e}));gl.displayName="DialogClose";const bs=ve.forwardRef(({className:e,...n},r)=>t.jsx(Q.Dialog.Overlay,{ref:r,"data-slot":"dialog-overlay",className:H("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...n}));bs.displayName="DialogOverlay";const et=ve.forwardRef(({className:e,children:n,showCloseButton:r=!0,...s},o)=>t.jsxs(gs,{"data-slot":"dialog-portal",children:[t.jsx(bs,{}),t.jsxs(Q.Dialog.Content,{ref:o,"data-slot":"dialog-content",className:H("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...s,children:[n,r&&t.jsxs(Q.Dialog.Close,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[t.jsx(N.XIcon,{}),t.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));et.displayName="DialogContent";const Ot=ve.forwardRef(({className:e,...n},r)=>t.jsx("div",{ref:r,"data-slot":"dialog-header",className:H("flex flex-col gap-2 text-center sm:text-left",e),...n}));Ot.displayName="DialogHeader";const ys=ve.forwardRef(({className:e,showCloseButton:n=!1,children:r,...s},o)=>t.jsxs("div",{ref:o,"data-slot":"dialog-footer",className:H("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...s,children:[r,n&&t.jsx(Q.Dialog.Close,{asChild:!0,children:t.jsx(W,{variant:"outline",children:"Close"})})]}));ys.displayName="DialogFooter";const tt=ve.forwardRef(({className:e,...n},r)=>t.jsx(Q.Dialog.Title,{ref:r,"data-slot":"dialog-title",className:H("text-lg leading-none font-semibold",e),...n}));tt.displayName="DialogTitle";const jt=ve.forwardRef(({className:e,...n},r)=>t.jsx(Q.Dialog.Description,{ref:r,"data-slot":"dialog-description",className:H("text-sm text-muted-foreground",e),...n}));jt.displayName="DialogDescription";function zn({className:e,...n}){return t.jsx(Q.Checkbox.Root,{"data-slot":"checkbox",className:H("peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary",e),...n,children:t.jsx(Q.Checkbox.Indicator,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:t.jsx(N.CheckIcon,{className:"size-3.5"})})})}function ct({className:e,...n}){return t.jsx(Q.Label.Root,{"data-slot":"label",className:H("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...n})}function En({open:e,onOpenChange:n,title:r,description:s,confirmLabel:o="Confirm",cancelLabel:i="Cancel",variant:a="default",isPending:l=!1,onConfirm:u}){return t.jsx(Ze,{open:e,onOpenChange:n,children:t.jsxs(et,{showCloseButton:!1,children:[t.jsxs(Ot,{children:[t.jsx(tt,{children:r}),t.jsx(jt,{asChild:!0,children:t.jsx("div",{children:s})})]}),t.jsxs(ys,{children:[t.jsx(W,{variant:"outline",onClick:()=>n(!1),disabled:l,children:i}),t.jsx(W,{variant:a==="destructive"?"destructive":"default",onClick:u,disabled:l,children:l?`${o}…`:o})]})]})})}function bl({name:e,label:n,value:r,dbType:s,onChange:o,onBlur:i,required:a,invalid:l}){const u=bt(s),d=Ft(s),p=Nn(r,s),[m,h]=c.useState(null),x=c.useRef(null),g=c.useCallback(()=>{const w=x.current;w&&(w.style.height="auto",w.style.height=Math.min(w.scrollHeight,400)+"px")},[]);if(c.useEffect(g,[r,g]),u)return t.jsx(yl,{name:e,label:n,value:r});if(!d&&p==="text")return null;const b=()=>{if(h(null),p==="json")try{o(JSON.stringify(JSON.parse(r),null,2))}catch{h("Invalid JSON")}else if(p==="xml")try{const w=r.replace(/>\s*</g,`>
114
+ }`,keyType:o}}function pu(e,t){return dt(t,e)}function Ko(e,t){return e?.data?.find(r=>r.graphQlName===t)}function hu(e,t,r,s="",o=!0){const i=$e(),a=u.useMemo(()=>Ko(e,t),[e,t]),l=s.trim(),c=u.useMemo(()=>e.loading||e.error||!a?null:mu(a,r,l),[r,a,e.loading,e.error,l]),m=c?.serverSearch?l:"",{isLoading:d,error:f,data:p}=de.useQuery({queryKey:["tableRef",t,r,m],queryFn:({signal:x})=>i.query(c.query,m?{limit:du,search:m}:{limit:uu},{signal:x}),enabled:!!c&&o});return{loading:d||e.loading,error:f||e.error,data:p?.values?.data??[],serverSearch:c?.serverSearch??!1}}function gu(e,t,r,s){const o=$e(),i=u.useMemo(()=>Ko(e,t),[e,t]),a=!e.loading&&!e.error&&!!i&&s!=null&&s!=="",l=u.useMemo(()=>a?fu(i,r):null,[a,i,r]),{isLoading:c,error:m,data:d}=de.useQuery({queryKey:["tableRefValue",t,r,String(s??"")],queryFn:({signal:f})=>o.query(l.query,{key:pu(l.keyType,s)},{signal:f}),enabled:!!l});return{loading:c,error:m||e.error,value:d?.values?.data?.at(0)??null}}const xu=500,bu=50;function yu(e,t,r,s={}){const o=$e(),{search:i="",enabled:a=!0,currentValues:l=null}=s,c=i.trim(),m=u.useMemo(()=>e?.data?.find(S=>S.graphQlName===t),[e,t]),d=u.useMemo(()=>m?.labelColumn||r[0],[m,r]),f=u.useMemo(()=>m?.columns.find(L=>L.name===d)?.paramType?.replace("!","")==="String",[m,d]),p=u.useMemo(()=>{if(!m||r.length===0||!it(t)||!it(d))return!1;const S=new Set(m.columns.map(L=>L.name));return S.has(d)?r.every(L=>it(L)&&S.has(L)):!1},[m,t,r,d]),x=u.useMemo(()=>{if(!m||!p)return"";const S=new Set(r);return S.add(d),Array.from(S).join(" ")},[m,p,r,d]),h=!!c&&f,y=u.useMemo(()=>{if(e.loading||e.error||!m||r.length===0||!p)return null;const S=h?"($limit: Int, $search: String)":"($limit: Int)",L=h?`filter: {${d}: {_contains: $search}} `:"";return`query Get_${t}_CompositeRef${S} { values: ${t}(${L}limit: $limit sort: [${d}_asc]) { data { ${x} } } }`},[m,t,x,d,h,e.loading,e.error,r.length,p]),N=f?c:"",{isLoading:T,error:k,data:$}=de.useQuery({queryKey:["compositeTableRef",t,r.join("|"),N],queryFn:()=>o.query(y,N?{limit:bu,search:N}:{limit:xu}),enabled:!!y&&a}),b=u.useMemo(()=>{if(!m||!$)return[];const S={primaryKeys:r};return($.values?.data??[]).map((L,A)=>{const D={};for(const X of r)D[X]=L[X];const B=He(L,S,A);return{route:B,values:D,label:String(L[d]??B)}})},[m,r,d,$]),v=u.useMemo(()=>{if(!l)return"";const S=[];for(const L of r){const A=l[L];if(A==null||A==="")return"";S.push(A)}return $t(S)},[l,r]),w=v===""||b.some(S=>S.route===v),F=u.useMemo(()=>{if(!m||!p||w||v===""||!l)return null;const S=new Map(m.columns.map(E=>[E.name,E])),L=[],A=[],D={};for(let E=0;E<r.length;E++){const P=r[E],q=mn(S.get(P)),U=`k${E}`;A.push(`$${U}: ${q}`),L.push(`{${P}: {_eq: $${U}}}`),D[U]=dt(l[P],q)}const B=L.length===1?L[0]:`{and: [${L.join(", ")}]}`;return{query:`query Get_${t}_CompositeRefValue(${A.join(", ")}) { values: ${t}(filter: ${B} limit: 1) { data { ${x} } } }`,variables:D}},[m,t,x,r,w,v,l,p]),{data:j}=de.useQuery({queryKey:["compositeTableRefValue",t,v],queryFn:()=>o.query(F.query,F.variables),enabled:!!F}),V=u.useMemo(()=>{const S=j?.values?.data?.[0];if(!S)return b;const L={};for(const D of r)L[D]=S[D];const A=$t(r.map(D=>S[D]));return b.some(D=>D.route===A)?b:[{route:A,values:L,label:String(S[d]??A)},...b]},[b,j,r,d]);return{loading:T||e.loading,error:k||e.error,data:V,serverSearch:f}}const vu=new Set(["DateTime","DateTime!"]);function Yn(e){return vu.has(e.paramType)}function Vr(e){return ho(e)==="datetime"}function Br(e,t){if(!e)return"";const r=e.match(/^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}(?::\d{2})?))?/);if(!r||r[1]==="0001-01-01")return"";if(!t||!r[2])return r[1];const s=r[2].length===5?`${r[2]}:00`:r[2];return`${r[1]}T${s}`}function ju(e,t,r){const s={...e};for(const o of r){if(!Yn(o))continue;const i=t[o.name];typeof i!="string"||i===""||Br(i,Vr(o))===s[o.name]&&(s[o.name]=i)}return s}function Wo(e,t,r){const s=e;return String(s.label??s[t]??"").toLowerCase().includes(r.toLowerCase())}const jt=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Root,{"data-slot":"dialog",...e}));jt.displayName="Dialog";const wu=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Trigger,{"data-slot":"dialog-trigger",...e}));wu.displayName="DialogTrigger";const Jo=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Portal,{"data-slot":"dialog-portal",...e}));Jo.displayName="DialogPortal";const Cu=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Close,{"data-slot":"dialog-close",...e}));Cu.displayName="DialogClose";const Qo=Ve.forwardRef(({className:e,...t},r)=>n.jsx(R.Dialog.Overlay,{ref:r,"data-slot":"dialog-overlay",className:Y("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t}));Qo.displayName="DialogOverlay";const wt=Ve.forwardRef(({className:e,children:t,showCloseButton:r=!0,...s},o)=>n.jsxs(Jo,{"data-slot":"dialog-portal",children:[n.jsx(Qo,{}),n.jsxs(R.Dialog.Content,{ref:o,"data-slot":"dialog-content",className:Y("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...s,children:[t,r&&n.jsxs(R.Dialog.Close,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[n.jsx(C.XIcon,{}),n.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));wt.displayName="DialogContent";const tn=Ve.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,"data-slot":"dialog-header",className:Y("flex flex-col gap-2 text-center sm:text-left",e),...t}));tn.displayName="DialogHeader";const Gr=Ve.forwardRef(({className:e,showCloseButton:t=!1,children:r,...s},o)=>n.jsxs("div",{ref:o,"data-slot":"dialog-footer",className:Y("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...s,children:[r,t&&n.jsx(R.Dialog.Close,{asChild:!0,children:n.jsx(Q,{variant:"outline",children:"Close"})})]}));Gr.displayName="DialogFooter";const Ct=Ve.forwardRef(({className:e,...t},r)=>n.jsx(R.Dialog.Title,{ref:r,"data-slot":"dialog-title",className:Y("text-lg leading-none font-semibold",e),...t}));Ct.displayName="DialogTitle";const Kt=Ve.forwardRef(({className:e,...t},r)=>n.jsx(R.Dialog.Description,{ref:r,"data-slot":"dialog-description",className:Y("text-sm text-muted-foreground",e),...t}));Kt.displayName="DialogDescription";function Cn({className:e,...t}){return n.jsx(R.Checkbox.Root,{"data-slot":"checkbox",className:Y("peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary",e),...t,children:n.jsx(R.Checkbox.Indicator,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:n.jsx(C.CheckIcon,{className:"size-3.5"})})})}function Wt({className:e,...t}){return n.jsx(R.Label.Root,{"data-slot":"label",className:Y("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function Kr({open:e,onOpenChange:t,title:r,description:s,confirmLabel:o="Confirm",cancelLabel:i="Cancel",variant:a="default",isPending:l=!1,onConfirm:c}){return n.jsx(jt,{open:e,onOpenChange:t,children:n.jsxs(wt,{showCloseButton:!1,children:[n.jsxs(tn,{children:[n.jsx(Ct,{children:r}),n.jsx(Kt,{asChild:!0,children:n.jsx("div",{children:s})})]}),n.jsxs(Gr,{children:[n.jsx(Q,{variant:"outline",onClick:()=>t(!1),disabled:l,children:i}),n.jsx(Q,{variant:a==="destructive"?"destructive":"default",onClick:c,disabled:l,children:l?`${o}…`:o})]})]})})}function Nu({name:e,label:t,value:r,dbType:s,onChange:o,onBlur:i,required:a,invalid:l}){const c=Et(s),m=gr(s),d=Bn(r,s),[f,p]=u.useState(null),x=u.useRef(null),h=u.useCallback(()=>{const k=x.current;k&&(k.style.height="auto",k.style.height=Math.min(k.scrollHeight,400)+"px")},[]);if(u.useEffect(h,[r,h]),c)return n.jsx(ku,{name:e,label:t,value:r});if(!m&&d==="text")return null;const y=()=>{if(p(null),d==="json")try{o(JSON.stringify(JSON.parse(r),null,2))}catch{p("Invalid JSON")}else if(d==="xml")try{const k=r.replace(/>\s*</g,`>
101
115
  <`).replace(/(<[^/][^>]*[^/]>)\n/g,`$1
102
- `).trim();o(w)}catch{h("Could not format XML")}},k=()=>{if(h(null),p==="json")try{o(JSON.stringify(JSON.parse(r)))}catch{h("Invalid JSON")}else p==="xml"&&o(r.replace(/\n\s*/g,"").trim())},$=p==="json"||p==="xml";return t.jsxs("div",{className:"grid gap-1",children:[$&&t.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[t.jsxs(W,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs px-2",onClick:b,children:[t.jsx(N.WrapText,{className:"size-3"}),"Format"]}),t.jsx(W,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs px-2",onClick:k,children:"Minify"})]}),t.jsx("textarea",{ref:x,id:e,value:r,onChange:w=>{o(w.target.value),h(null)},onBlur:i,required:a,"aria-invalid":l,className:H("flex w-full rounded-md border border-input bg-background px-3 py-2","text-xs font-mono leading-relaxed","ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","disabled:cursor-not-allowed disabled:opacity-50","resize-none min-h-[80px] max-h-[400px]",l&&"border-destructive")}),m&&t.jsx("p",{className:"text-xs text-destructive",children:m})]})}function yl({name:e,label:n,value:r}){const s=r?Math.ceil(r.length*3/4):0,o=s<1024?`${s} bytes`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`,i=r?r.slice(0,256)+(r.length>256?"...":""):"(empty)";return t.jsxs("div",{className:"grid gap-2",children:[t.jsxs(ct,{htmlFor:e,className:"flex items-center gap-1.5",children:[t.jsx(N.Binary,{className:"size-3.5 text-muted-foreground"}),n,t.jsxs("span",{className:"text-xs text-muted-foreground font-normal ml-1",children:["(binary, ",o,")"]})]}),t.jsx("div",{className:"rounded-md border border-input bg-muted/30 p-3 max-h-[160px] overflow-auto",children:t.jsx("pre",{className:"text-xs font-mono text-muted-foreground break-all whitespace-pre-wrap",children:i})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"Binary fields are read-only in this editor."})]})}const Pn=["Boolean","Boolean!"],vl=["Int","Int!","Float","Float!"],nt="__none__";function vs(e,n){return e==null||e===""?n?nt:"":String(e)}function At(e,n){const r=({value:s})=>fl(e,s,n);return{onSubmit:r,onBlur:r}}function qt(e,n){const r=e.state.meta.errors.length>0;return{hasError:r,ariaProps:{"aria-invalid":r,"aria-describedby":r?n:void 0}}}function js(e){return bt(e.dbType)||Ft(e.dbType)||lt(e)}const Ns={filterText:"",variables:{},params:[]};function jl(e,n){return c.useMemo(()=>{const r=e?.data?.find(l=>l.graphQlName===n),o=r.columns.filter(l=>!l.isReadOnly&&!l.isIdentity).map(l=>{const u=r.singleJoins.find(p=>p.sourceColumnNames[0]===l.graphQlName);if(u)return{column:l,join:u,fkRole:it(u)?"anchor-composite":"anchor-single"};const d=r.singleJoins.find(p=>(p.sourceColumnNames??[]).includes(l.graphQlName));return d?{column:l,join:d,fkRole:"member-composite"}:{column:l,fkRole:"none"}}),i=new Map(r.columns.map(l=>[l.name,l])),a=(r.primaryKeys??[]).map(l=>i.get(l)).filter(l=>!!l);return[r,o,a]},[e,n])}function Nl({table:e,schema:n,editid:r,onClose:s}){const o=Ce(),i=r===void 0||r==="",[a,l,u]=jl(n,e),d=a.labelColumn,p=a.label,m=sn(a,l,u,r),h=c.useMemo(()=>i?null:jn(r,a),[i,r,a]),x=c.useMemo(()=>i||!h?Ns:yn(h,a)??Ns,[i,h,a]),g=!i&&x.filterText==="",b=c.useMemo(()=>{const z=x.params.length>0?x.params.join(", "):"";return`query GetSingleEdit_${a.name}(${z}){
103
- value: ${a.name}(filter: ${x.filterText||"{}"}) {
104
- data { ${l.map(({column:I})=>I.name).join(" ")} }
116
+ `).trim();o(k)}catch{p("Could not format XML")}},N=()=>{if(p(null),d==="json")try{o(JSON.stringify(JSON.parse(r)))}catch{p("Invalid JSON")}else d==="xml"&&o(r.replace(/\n\s*/g,"").trim())},T=d==="json"||d==="xml";return n.jsxs("div",{className:"grid gap-1",children:[T&&n.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs px-2",onClick:y,children:[n.jsx(C.WrapText,{className:"size-3"}),"Format"]}),n.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs px-2",onClick:N,children:"Minify"})]}),n.jsx("textarea",{ref:x,id:e,value:r,onChange:k=>{o(k.target.value),p(null)},onBlur:i,required:a,"aria-invalid":l,className:Y("flex w-full rounded-md border border-input bg-background px-3 py-2","text-xs font-mono leading-relaxed","ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","disabled:cursor-not-allowed disabled:opacity-50","resize-none min-h-[80px] max-h-[400px]",l&&"border-destructive")}),f&&n.jsx("p",{className:"text-xs text-destructive",children:f})]})}function ku({name:e,label:t,value:r}){const s=r?Math.ceil(r.length*3/4):0,o=s<1024?`${s} bytes`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`,i=r?r.slice(0,256)+(r.length>256?"...":""):"(empty)",a=r?so(r):null;return n.jsxs("div",{className:"grid gap-2",children:[n.jsxs(Wt,{htmlFor:e,className:"flex items-center gap-1.5",children:[n.jsx(C.Binary,{className:"size-3.5 text-muted-foreground"}),t,n.jsxs("span",{className:"text-xs text-muted-foreground font-normal ml-1",children:["(binary, ",o,")"]})]}),a?.kind==="image"?n.jsx("img",{src:oo(r,a.mime),alt:t,className:"max-h-[160px] w-fit rounded-md border border-input"}):n.jsx("div",{className:"rounded-md border border-input bg-muted/30 p-3 max-h-[160px] overflow-auto",children:n.jsx("pre",{className:"text-xs font-mono text-muted-foreground break-all whitespace-pre-wrap",children:i})}),n.jsx("p",{className:"text-xs text-muted-foreground",children:"Binary fields are read-only in this editor."})]})}const Wr=["Boolean","Boolean!"],Dt="__none__";function Ho(e,t){return e==null||e===""?t?Dt:"":String(e)}function Jr(e){return t=>{t!==""&&e(t)}}function Nn(e,t){const r=({value:s})=>qr(e,s,t);return{onSubmit:r,onBlur:r}}function Rn(e,t){const r=e.state.meta.errors.length>0;return{hasError:r,ariaProps:{"aria-invalid":r,"aria-describedby":r?t:void 0}}}function Uo(e){return Et(e.dbType)||gr(e.dbType)||Ft(e)}const Yo={filterText:"",variables:{},params:[]};function Su(e,t){return t!=="none"||(e.enumValues?.length??0)>0}function Tu(e,t){return u.useMemo(()=>{const r=e?.data?.find(l=>l.graphQlName===t),o=r.columns.filter(l=>!l.isReadOnly&&!l.isIdentity).map(l=>{const c=r.singleJoins.find(d=>d.sourceColumnNames[0]===l.graphQlName);if(c)return{column:l,join:c,fkRole:Gt(c)?"anchor-composite":"anchor-single"};const m=r.singleJoins.find(d=>(d.sourceColumnNames??[]).includes(l.graphQlName));return m?{column:l,join:m,fkRole:"member-composite"}:{column:l,fkRole:"none"}}),i=new Map(r.columns.map(l=>[l.name,l])),a=(r.primaryKeys??[]).map(l=>i.get(l)).filter(l=>!!l);return[r,o,a]},[e,t])}function $u(e,t,r){const s=$e(),o=r===void 0||r==="",i=u.useMemo(()=>o?null:fn(r,e),[o,r,e]),a=u.useMemo(()=>o||!i?Yo:qn(i,e)??Yo,[o,i,e]),l=!o&&a.filterText==="",c=u.useMemo(()=>{const N=a.params.length>0?a.params.join(", "):"";return`query GetSingleEdit_${e.name}(${N}){
117
+ value: ${e.name}(filter: ${a.filterText||"{}"}) {
118
+ data { ${t.map(({column:T})=>T.name).join(" ")} }
105
119
  }
106
- }`},[a,l,x]),{isLoading:k,error:$,data:w}=me.useQuery({queryKey:["editRecord",a.name,r],queryFn:()=>o.query(b,x.variables),enabled:!!a&&!i&&x.filterText!==""}),P=c.useMemo(()=>w?.value?.data?.at(0)??{},[w]),C=c.useMemo(()=>{const z={};for(const{column:I,fkRole:_}of l){const G=_!=="none"||I.enumValues!==void 0&&I.enumValues.length>0;if(_n(I))z[I.name]=hs(P[I.name],Fn(I));else if(Pn.some(U=>U===I.paramType)){const U=P[I.name];z[I.name]=I.isNullable&&U==null?null:!!U}else if(lt(I)){const U=P[I.name];z[I.name]=U==null?"":JSON.stringify(U,null,2)}else if(G){const U=P[I.name];z[I.name]=U??null}else z[I.name]=P[I.name]??""}return z},[P,l]),T=Bt.useForm({defaultValues:C,onSubmit:async({value:z})=>{const I=hl(z,P,l.map(({column:G})=>G));await(i?m.insert:m.update)(I),s()}}),j=Bt.useStore(T.store,z=>z.isDirty),[E,y]=c.useState(!1),S=()=>{j?y(!0):s()};if(k&&!i)return t.jsx(Ze,{open:!0,onOpenChange:z=>{z||s()},children:t.jsxs(et,{showCloseButton:!1,className:"sm:max-w-2xl",children:[t.jsx(tt,{className:"sr-only",children:"Loading record"}),t.jsx(jt,{className:"sr-only",children:"Loading record for editing"}),t.jsxs("div",{className:"flex items-center justify-center gap-2 py-10 text-sm text-muted-foreground",children:[t.jsx(N.LoaderCircle,{className:"size-4 animate-spin"}),"Loading…"]})]})});if($)return t.jsxs("div",{children:["Error: ",$.message]});if(g)return t.jsx(Ze,{open:!0,onOpenChange:z=>{z||s()},children:t.jsxs(et,{showCloseButton:!1,className:"sm:max-w-md",children:[t.jsx(tt,{className:"text-sm font-semibold",children:"Cannot edit record"}),t.jsxs(jt,{className:"text-sm text-muted-foreground",children:["This record can't be opened for editing: its key (",r||"empty",") is missing or malformed for the ",p," table. Return to the grid and try again."]}),t.jsx("div",{className:"flex justify-end",children:t.jsx(W,{type:"button",size:"sm",onClick:s,children:"Close"})})]})});const L=P?.[d]??r,v=l.filter(({column:z})=>Pn.some(I=>I===z.paramType)),M=l.filter(({column:z})=>js(z)),O=l.filter(({column:z})=>!Pn.some(I=>I===z.paramType)&&!js(z));return t.jsxs(Ze,{open:!0,onOpenChange:z=>{z||S()},children:[t.jsxs(et,{showCloseButton:!1,className:"sm:max-w-2xl max-h-[90vh] flex flex-col gap-0 p-0 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-border bg-muted/30 shrink-0",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx(tt,{className:"text-sm font-semibold truncate",children:i?`New ${p}`:`${p} : ${L}`}),t.jsxs(jt,{className:"sr-only",children:[i?"Create":"Edit"," ",p," record"]})]}),t.jsx(W,{type:"button",variant:"ghost",size:"icon-sm",onClick:S,"aria-label":"Close",className:"shrink-0 -mr-1",children:t.jsx(N.X,{className:"size-4"})})]}),m.error&&t.jsxs("div",{className:"flex items-center gap-2 px-5 py-2 bg-destructive/10 border-b border-destructive/20 text-destructive text-sm shrink-0",children:[t.jsx(N.AlertCircle,{className:"size-3.5 shrink-0"}),t.jsx("span",{className:"truncate",children:m.error.message})]}),t.jsxs("form",{onSubmit:z=>{z.preventDefault(),z.stopPropagation(),T.handleSubmit()},className:"flex flex-col flex-1 min-h-0",children:[t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[O.length>0&&t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-3",children:O.map(({column:z,join:I,fkRole:_})=>t.jsx(kl,{column:z,join:I,fkRole:_,form:T,schema:n},z.name))}),v.length>0&&t.jsx("div",{className:O.length>0?"mt-4 pt-4 border-t border-border":"",children:t.jsx("div",{className:"flex flex-wrap gap-x-6 gap-y-2",children:v.map(({column:z})=>t.jsx(Sl,{column:z,form:T},z.name))})}),M.length>0&&t.jsx("div",{className:O.length>0||v.length>0?"mt-4 pt-4 border-t border-border":"",children:t.jsx("div",{className:"grid gap-3",children:M.map(({column:z})=>t.jsx($l,{column:z,form:T},z.name))})})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-border bg-muted/30 shrink-0",children:[t.jsx(W,{type:"button",variant:"outline",size:"sm",onClick:S,children:"Cancel"}),t.jsxs(W,{type:"submit",size:"sm",disabled:m.isPending,children:[m.isPending?t.jsx(N.LoaderCircle,{className:"size-3.5 animate-spin"}):t.jsx(N.Save,{className:"size-3.5"}),i?"Create":"Save"]})]})]})]}),t.jsx(En,{open:E,onOpenChange:y,title:"Discard unsaved changes?",description:t.jsx("p",{children:"You have unsaved changes. Closing now will discard them."}),confirmLabel:"Discard",cancelLabel:"Keep editing",variant:"destructive",onConfirm:()=>{y(!1),s()}})]})}function on(){const{table:e,editid:n}=mn(),r=Wt();return e?t.jsx(ws,{table:e,editid:n??"",onClose:()=>r("../..")}):t.jsx("div",{children:"Table missing"})}function ws({table:e,editid:n,onClose:r}){const s=Pe();return e?s.loading?t.jsx("div",{children:"Loading..."}):s.error?t.jsxs("div",{children:["Error: ",s.error.message]}):s.findTable(e)?t.jsx(Nl,{table:e,schema:s,editid:n,onClose:r}):t.jsxs("div",{className:"p-4 text-sm text-destructive",children:["Table not found: ",e]}):t.jsx("div",{children:"Table missing"})}function wl({current:e,max:n}){const r=n-e,s=r<=10&&r>0,o=r<=0;return t.jsx("div",{className:"text-xs text-right mt-0.5","aria-live":"polite",children:t.jsxs("span",{className:o?"text-destructive font-medium":s?"text-amber-500":"text-muted-foreground",children:[e,"/",n]})})}function Cl({min:e,max:n,step:r}){if(e===void 0&&n===void 0)return null;let s="";return e!=null&&n!==void 0&&n!==null?s=`Range: ${e} to ${n}`:e!=null?s=`Min: ${e}`:n!=null&&(s=`Max: ${n}`),r!=null&&r!==1&&(s+=` (step: ${r})`),t.jsx("div",{className:"text-xs text-muted-foreground mt-0.5","aria-live":"polite",children:s})}function kl({column:e,join:n,fkRole:r,form:s,schema:o}){const i=e.name,a=!e.isNullable;if(r==="member-composite")return null;const l=_n(e),u=vl.some(h=>h===e.paramType),d=e.maxLength&&e.maxLength>0&&!l&&!u;if(e.enumValues&&e.enumValues.length>0)return t.jsx(Tl,{column:e,form:s,isRequired:a});if(n&&o)return r==="anchor-composite"?t.jsx(Fl,{column:e,join:n,form:s,schema:o,isRequired:a}):t.jsx(_l,{column:e,join:n,form:s,schema:o,isRequired:a});const p=e.inputType||(l?Fn(e)?"datetime-local":"date":u?"number":"text"),m=`${i}-error`;return t.jsx(s.Field,{name:i,validators:At(e,a),children:h=>{const{ariaProps:x}=qt(h,m);return t.jsxs("div",{className:"grid gap-1",children:[t.jsxs(ct,{htmlFor:i,className:"text-xs text-muted-foreground",children:[e.label,a&&t.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),t.jsx(ke,{id:i,type:p,value:h.state.value??"",onChange:g=>h.handleChange(g.target.value),onBlur:h.handleBlur,required:a,maxLength:e.maxLength,minLength:e.minLength,min:e.min,max:e.max,step:e.step,pattern:e.pattern,title:e.patternMessage,...x,className:"h-8 text-sm"}),d&&t.jsx(wl,{current:String(h.state.value??"").length,max:e.maxLength}),u&&(e.min!==void 0||e.max!==void 0)&&t.jsx(Cl,{min:e.min,max:e.max,step:e.step}),t.jsx(Vt,{errors:h.state.meta.errors,id:m})]})}})}function Tl({column:e,form:n,isRequired:r}){const s=e.name,o=e.enumValues||[],i=e.enumLabels&&e.enumLabels.length===o.length?e.enumLabels:o,a=`${s}-error`;return t.jsx(n.Field,{name:s,validators:At(e,r),children:l=>{const{ariaProps:u}=qt(l,a);return t.jsxs("div",{className:"grid gap-1",children:[t.jsxs(ct,{htmlFor:s,className:"text-xs text-muted-foreground",children:[e.label,r&&t.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),t.jsxs(Le,{value:vs(l.state.value,!r),onValueChange:d=>l.handleChange(d===nt?null:d),children:[t.jsx(Ae,{id:s,className:"w-full h-8 text-sm",...u,children:t.jsx(Oe,{placeholder:`Select ${e.label}`})}),t.jsxs(qe,{children:[!r&&t.jsx(ge,{value:nt,className:"text-muted-foreground",children:"(none)"}),o.map((d,p)=>t.jsx(ge,{value:d,children:i[p]||d},d))]})]}),t.jsx(Vt,{errors:l.state.meta.errors,id:a})]})}})}const Dn="true",Cs="false";function Sl({column:e,form:n}){const r=e.name;return e.isNullable?t.jsx(n.Field,{name:r,children:s=>{const o=s.state.value,i=o==null?nt:o?Dn:Cs;return t.jsxs("div",{className:"grid gap-1 min-w-[10rem]",children:[t.jsx(ct,{htmlFor:r,className:"text-xs text-muted-foreground",children:e.label}),t.jsxs(Le,{value:i,onValueChange:a=>s.handleChange(a===nt?null:a===Dn),children:[t.jsx(Ae,{id:r,className:"w-full h-8 text-sm",children:t.jsx(Oe,{})}),t.jsxs(qe,{children:[t.jsx(ge,{value:nt,className:"text-muted-foreground",children:"(unset)"}),t.jsx(ge,{value:Dn,children:"Yes"}),t.jsx(ge,{value:Cs,children:"No"})]})]})]})}}):t.jsx(n.Field,{name:r,children:s=>t.jsxs("label",{htmlFor:r,className:"flex items-center gap-2 cursor-pointer select-none",children:[t.jsx(zn,{id:r,checked:!!s.state.value,onCheckedChange:o=>s.handleChange(!!o),onBlur:s.handleBlur}),t.jsx("span",{className:"text-sm",children:e.label})]})})}function $l({column:e,form:n}){const r=e.name,s=!e.isNullable,o=`${r}-error`;return t.jsx(n.Field,{name:r,validators:At(e,s),children:i=>{const{hasError:a}=qt(i,o);return t.jsxs("div",{className:"grid gap-1",children:[t.jsxs(ct,{htmlFor:r,className:"text-xs text-muted-foreground",children:[e.label,s&&t.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),t.jsx(bl,{name:r,label:e.label,value:String(i.state.value??""),dbType:e.dbType,onChange:l=>i.handleChange(l),onBlur:i.handleBlur,required:s,invalid:a}),t.jsx(Vt,{errors:i.state.meta.errors,id:o})]})}})}function _l({column:e,join:n,form:r,schema:s,isRequired:o}){const i=e.name,a=n.destinationColumnNames[0],[l,u]=c.useState(""),[d,p]=c.useState(""),[m,h]=c.useState(!1);c.useEffect(()=>{const T=setTimeout(()=>p(l),300);return()=>clearTimeout(T)},[l]);const x=rl(s,n.destinationTable,a,d,m),g=Bt.useStore(r.store,T=>T.values?.[i]),b=g==null||g===""||x.data.some(T=>String(T.key)===String(g)),k=sl(s,n.destinationTable,a,!x.loading&&!b?g:null),$=`${i}-error`,w=d.trim(),P=x.serverSearch||!w?x.data:x.data.filter(T=>xs(T,"key",w)),C=g==null||g===""?null:x.data.find(T=>String(T.key)===String(g))??k.value??{key:String(g),label:String(g)};return t.jsx(r.Field,{name:i,validators:At(e,o),children:T=>{const{ariaProps:j}=qt(T,$);return t.jsxs("div",{className:"grid gap-1",children:[t.jsxs(ct,{htmlFor:i,className:"text-xs text-muted-foreground",children:[e.label,o&&t.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),t.jsxs(Le,{value:vs(T.state.value,!o),onValueChange:E=>T.handleChange(E===nt?null:E),onOpenChange:E=>{h(E),E||(u(""),p(""))},children:[t.jsx(Ae,{id:i,className:"w-full h-8 text-sm",...j,children:t.jsx(Oe,{placeholder:`Select ${e.label}`})}),t.jsxs(qe,{children:[t.jsx("div",{className:"px-1 pb-1 sticky top-0 bg-popover z-10",children:t.jsx(ke,{value:l,onChange:E=>u(E.target.value),onKeyDown:E=>{(E.key.length===1||E.key==="Backspace"||E.key==="Delete")&&E.stopPropagation()},placeholder:"Search…",className:"h-7 text-xs"})}),!o&&t.jsx(ge,{value:nt,className:"text-muted-foreground",children:"(none)"}),C&&!P.some(E=>String(E.key)===String(C.key))&&t.jsx(ge,{value:String(C.key),children:C.label}),P.map(E=>t.jsx(ge,{value:String(E.key),children:E.label},E.key)),P.length===0&&t.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No matches."})]})]}),x.error!=null&&t.jsxs("p",{className:"text-xs text-destructive",role:"alert",children:["Failed to load ",e.label," options: ",String(x.error?.message??x.error)]}),t.jsx(Vt,{errors:T.state.meta.errors,id:$})]})}})}function Fl({column:e,join:n,form:r,schema:s,isRequired:o}){const i=n.sourceColumnNames??[],a=n.destinationColumnNames??[],[l,u]=c.useState(""),[d,p]=c.useState(""),[m,h]=c.useState(!1);c.useEffect(()=>{const C=setTimeout(()=>p(l),300);return()=>clearTimeout(C)},[l]);const x=Bt.useStore(r.store,C=>{const T={};for(let j=0;j<i.length;j++)T[a[j]]=C.values?.[i[j]];return T}),g=il(s,n.destinationTable,a,{search:d,enabled:m,currentValues:x}),b=c.useMemo(()=>{const C=[];for(let T=0;T<i.length;T++){const j=x[a[T]];if(j==null||j==="")return"";C.push(j)}return xt(C)},[x,i,a]),k=d.trim(),$=g.serverSearch||!k?g.data:g.data.filter(C=>C.label.toLowerCase().includes(k.toLowerCase())),w=C=>{const T=g.data.find(j=>j.route===C);if(T)for(let j=0;j<i.length;j++){const E=a[j],y=i[j];r.setFieldValue(y,T.values[E])}},P=`${e.name}-error`;return t.jsx(r.Field,{name:e.name,validators:At(e,o),children:C=>{const{ariaProps:T}=qt(C,P);return t.jsxs("div",{className:"grid gap-1 sm:col-span-2",children:[t.jsxs(ct,{htmlFor:e.name,className:"text-xs text-muted-foreground",children:[e.label,o&&t.jsx("span",{className:"text-destructive ml-0.5",children:"*"}),t.jsxs("span",{className:"ml-2 px-1 rounded bg-primary/10 text-[10px] font-medium text-primary",children:["composite FK (",i.length," cols)"]})]}),t.jsxs(Le,{value:b,onValueChange:w,onOpenChange:j=>{h(j),j||(u(""),p(""))},children:[t.jsx(Ae,{id:e.name,className:"w-full h-8 text-sm",...T,children:t.jsx(Oe,{placeholder:`Select ${e.label}`})}),t.jsxs(qe,{children:[t.jsx("div",{className:"px-1 pb-1 sticky top-0 bg-popover z-10",children:t.jsx(ke,{value:l,onChange:j=>u(j.target.value),onKeyDown:j=>{(j.key.length===1||j.key==="Backspace"||j.key==="Delete")&&j.stopPropagation()},placeholder:"Search…",className:"h-7 text-xs"})}),$.map(j=>t.jsx(ge,{value:j.route,children:j.label},j.route)),$.length===0&&t.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No matches."})]})]}),g.error!=null&&t.jsxs("p",{className:"text-xs text-destructive",role:"alert",children:["Failed to load ",e.label," options: ",String(g.error?.message??g.error)]}),t.jsx(Vt,{errors:C.state.meta.errors,id:P})]})}})}function Vt({errors:e,id:n}){return e.length===0?null:t.jsx("div",{id:n,role:"alert",children:e.map((r,s)=>t.jsx("p",{className:"text-xs text-destructive",children:String(r)},s))})}const ks=40,Ts=32;function zl({className:e,...n}){return t.jsx("div",{"data-slot":"table-container",className:"relative w-full h-full overflow-x-auto",children:t.jsx("table",{"data-slot":"table",className:H("min-w-full caption-bottom text-sm border-separate border-spacing-0",e),...n})})}function El({className:e,...n}){return t.jsx("thead",{"data-slot":"table-header",className:H("[&_tr]:border-b",e),...n})}function Pl({className:e,...n}){return t.jsx("tbody",{"data-slot":"table-body",className:H("[&_tr:last-child]:border-0 [&_tr:nth-child(even)]:bg-muted/25",e),...n})}function an({className:e,style:n,...r}){return t.jsx("tr",{"data-slot":"table-row",className:H("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),style:{height:ks,...n},...r})}function Dl({className:e,style:n,...r}){return t.jsx("th",{"data-slot":"table-head",className:H("px-2 text-left align-middle font-medium whitespace-nowrap text-muted-foreground text-xs border-r border-border last:border-r-0 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),style:{height:Ts,...n},...r})}function Mn({className:e,...n}){return t.jsx("td",{"data-slot":"table-cell",className:H("px-2 py-1 align-middle whitespace-nowrap text-[13px] overflow-hidden text-ellipsis border-r border-border last:border-r-0 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...n})}function Ml({anchorEl:e,onEdit:n,onDelete:r,onMouseEnter:s,onDismiss:o}){const i=c.useRef(null);return c.useEffect(()=>{const a=i.current;return a?((()=>{const u=e.getBoundingClientRect(),d=a.offsetHeight,p=a.offsetWidth;a.style.top=`${u.top+(u.height-d)/2}px`;const m=Math.min(u.right-p-8,window.innerWidth-p-8);a.style.left=`${Math.max(8,m)}px`})(),a.showPopover(),()=>{try{a.hidePopover()}catch{}}):void 0},[e]),c.useEffect(()=>{const a=l=>{const u=i.current;u&&!u.contains(l.target)&&o()};return document.addEventListener("pointerdown",a),()=>document.removeEventListener("pointerdown",a)},[o]),t.jsxs("div",{ref:i,popover:"manual",className:"flex items-center gap-0.5 rounded-md border border-border bg-popover px-1 py-0.5 shadow-md m-0",style:{position:"fixed"},onClick:a=>a.stopPropagation(),onMouseEnter:s,onMouseLeave:o,onFocusCapture:s,onBlur:a=>{a.currentTarget.contains(a.relatedTarget)||o()},children:[n&&t.jsx(W,{variant:"ghost",size:"icon-sm",onClick:n,"aria-label":"Edit row",title:"Edit",className:"size-6",children:t.jsx(N.Pencil,{className:"size-3.5"})}),r&&t.jsx(W,{variant:"ghost",size:"icon-sm",onClick:r,"aria-label":"Delete row",title:"Delete",className:"size-6 text-destructive hover:text-destructive",children:t.jsx(N.Trash2,{className:"size-3.5"})})]})}const In=60,Ss=450,Il=150,Ln="bifrost-col-sizes:";function $s(e){try{const n=localStorage.getItem(Ln+e);return n?Ll(JSON.parse(n)):{}}catch{return{}}}function Ll(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const n={};for(const[r,s]of Object.entries(e))typeof s!="number"||!Number.isFinite(s)||(n[r]=Math.min(Math.max(s,In),Ss));return n}function On(e,n){try{Object.keys(n).length===0?localStorage.removeItem(Ln+e):localStorage.setItem(Ln+e,JSON.stringify(n))}catch{}}const Ol=[10,20,30,50,100],An=-1;function Al({columns:e,data:n,tableName:r,pageCount:s,pageIndex:o,pageSize:i,sorting:a,columnFilters:l,loading:u,selectable:d=!1,primaryKeys:p=[],selectedRowId:m,onRowSelect:h,onSortingChange:x,onColumnFiltersChange:g,onPageIndexChange:b,onPageSizeChange:k,onEditRow:$,onDeleteRow:w,onDeleteSelected:P,stackingEnabled:C,onToggleStacking:T}){const[j,E]=c.useState(null),y=c.useRef(null),S=c.useCallback((D,K)=>{y.current&&(clearTimeout(y.current),y.current=null),E({rowId:D,el:K})},[]),L=c.useCallback(()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>E(null),150)},[]),v=c.useCallback(()=>{y.current&&(clearTimeout(y.current),y.current=null)},[]),M=c.useRef(null),O=c.useRef(!1),z=c.useRef(!1),I=500,_=c.useCallback(()=>{M.current&&(clearTimeout(M.current),M.current=null)},[]),G=c.useCallback((D,K,de)=>{de.pointerType==="touch"&&(O.current=!1,_(),M.current=setTimeout(()=>{O.current||(z.current=!0,S(D,K))},I))},[_,S]),U=c.useCallback(()=>{O.current=!0,_()},[_]),[ie,B]=c.useState({}),[Te,ye]=c.useState({}),[xe,le]=c.useState(()=>r?$s(r):{}),[re,ae]=c.useState(!0),J=c.useRef(null),ce=c.useRef(null),R=c.useRef(!0);c.useEffect(()=>{const D=ce.current;if(D&&D.tableName!==r&&(ce.current=null,On(D.tableName,D.sizing)),!r)return;if(R.current){R.current=!1;return}ce.current={tableName:r,sizing:xe};const K=setTimeout(()=>{ce.current=null,On(r,xe)},300);return()=>clearTimeout(K)},[r,xe]),c.useEffect(()=>()=>{const D=ce.current;D&&On(D.tableName,D.sizing)},[]);const Ne=c.useRef(r);if(r&&r!==Ne.current){Ne.current=r,R.current=!0;const D=$s(r);le(D)}const Be=c.useCallback(D=>{const K=J.current;if(!K)return;const de=K.querySelectorAll(`[data-col-id="${D}"]`);let Ee=In;de.forEach(We=>{const dn=We.scrollWidth+4;dn>Ee&&(Ee=dn)});const mt=Math.min(Ee,Ss);le(We=>({...We,[D]:mt}))},[]),ze=c.useCallback(()=>{le({})},[]),Ke=c.useRef(0),De=c.useCallback(()=>{const D=J.current;return D?Math.max(5,Math.floor((D.clientHeight-Ts)/ks)):10},[]);c.useEffect(()=>{if(!re)return;const D=J.current;if(!D)return;const K=()=>{const We=De();We!==Ke.current&&(Ke.current=We,k(We))},de=requestAnimationFrame(K);let Ee=null;const mt=new ResizeObserver(()=>{Ee&&clearTimeout(Ee),Ee=setTimeout(()=>requestAnimationFrame(K),200)});return mt.observe(D),()=>{cancelAnimationFrame(de),Ee&&clearTimeout(Ee),mt.disconnect()}},[re,De,k]),c.useEffect(()=>{ye({})},[n,o]);const Ge=c.useMemo(()=>{const D=[];return d&&D.push({id:"_select",header:({table:K})=>t.jsx(zn,{checked:K.getIsAllPageRowsSelected()||K.getIsSomePageRowsSelected()&&"indeterminate",onCheckedChange:de=>K.toggleAllPageRowsSelected(!!de),"aria-label":"Select all"}),cell:({row:K})=>t.jsx(zn,{checked:K.getIsSelected(),onCheckedChange:de=>K.toggleSelected(!!de),onClick:de=>de.stopPropagation(),"aria-label":"Select row"}),enableSorting:!1,enableHiding:!1,enableResizing:!1,size:32}),D.push(...e),D},[e,d]),ue=Kt.useReactTable({data:n,columns:Ge,pageCount:s,getRowId:(D,K)=>_t(D,{primaryKeys:p},K),state:{sorting:a,columnFilters:l,pagination:{pageIndex:o,pageSize:i},columnVisibility:ie,rowSelection:Te,columnSizing:xe},defaultColumn:{minSize:In,size:Il},columnResizeMode:"onChange",enableColumnResizing:!0,onColumnSizingChange:le,meta:{onResetColumnWidths:ze},onSortingChange:D=>{const K=typeof D=="function"?D(a):D;x(K)},onPaginationChange:D=>{const de=typeof D=="function"?D({pageIndex:o,pageSize:i}):D;de.pageSize!==i?(k(de.pageSize),b(0)):b(de.pageIndex)},onColumnFiltersChange:D=>{const K=typeof D=="function"?D(l):D;g(K)},onColumnVisibilityChange:B,onRowSelectionChange:ye,enableRowSelection:d,getCoreRowModel:Kt.getCoreRowModel(),manualSorting:!0,manualFiltering:!0,manualPagination:!0}),X=Object.keys(Te).length,se=ue.getVisibleLeafColumns().map(D=>D.id).join("|"),Se=c.useCallback(()=>{if(!P)return;const D=[];for(const K of ue.getSelectedRowModel().rows){const de=gt(K.original,{primaryKeys:p});de&&D.push(de)}D.length>0&&P(D)},[ue,P,p]),$e=c.useCallback(D=>{const K=ue.getRow(D);return K?gt(K.original,{primaryKeys:p}):null},[ue,p]),rt=c.useCallback(D=>{if(!$)return;const K=$e(D);K&&$(K)},[$,$e]),Je=c.useCallback(D=>{if(!w)return;const K=$e(D);K&&w(K)},[w,$e]),ut=c.useCallback(()=>{j&&rt(j.rowId)},[j,rt]),st=c.useCallback(()=>{j&&Je(j.rowId)},[j,Je]);return t.jsxs("div",{className:"flex flex-col w-full min-h-0 flex-1",children:[t.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[l.length>0&&t.jsxs(W,{variant:"outline",size:"sm",onClick:()=>ue.resetColumnFilters(),title:"Clear all column filters",children:[t.jsx(N.FilterX,{className:"size-3.5"}),"Clear filters"]}),X>0&&P&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"text-xs text-muted-foreground",children:[X," selected"]}),t.jsxs(W,{variant:"outline",size:"sm",onClick:Se,className:"text-destructive hover:text-destructive",children:[t.jsx(N.Trash2,{className:"size-3.5"}),"Delete"]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[T&&t.jsxs(W,{variant:C?"secondary":"outline",size:"sm",role:"switch","aria-checked":!!C,onClick:()=>T(!C),title:C?"Stacked drill-down active — click for flat grid":"Flat grid active — click for stacked drill-down",children:[C?t.jsx(N.PanelRight,{className:"size-3.5"}):t.jsx(N.Rows3,{className:"size-3.5"}),C?"Stacked":"Grid"]}),t.jsxs(Yr,{children:[t.jsx(Rr,{asChild:!0,children:t.jsxs(W,{variant:"outline",size:"sm",children:[t.jsx(N.Columns3,{className:"size-3.5"}),"Columns",t.jsx(N.ChevronDown,{className:"size-3.5"})]})}),t.jsx(Xr,{align:"end",children:ue.getAllColumns().filter(D=>D.getCanHide()).map(D=>{const de=D.columnDef.meta?.column?.label??(typeof D.columnDef.header=="string"?D.columnDef.header:D.id);return t.jsx(Ja,{checked:D.getIsVisible(),onCheckedChange:Ee=>D.toggleVisibility(!!Ee),children:de},D.id)})})]})]})]}),t.jsxs("div",{ref:J,className:"flex-1 overflow-auto min-h-0",children:[t.jsxs(zl,{style:{tableLayout:"fixed",width:ue.getTotalSize()},children:[t.jsx("colgroup",{children:ue.getVisibleLeafColumns().map(D=>t.jsx("col",{style:{width:D.getSize()}},D.id))}),t.jsx(El,{children:ue.getHeaderGroups().map(D=>t.jsx(an,{children:D.headers.map(K=>t.jsxs(Dl,{"data-col-id":K.column.id,className:"relative","aria-sort":K.column.getIsSorted()==="asc"?"ascending":K.column.getIsSorted()==="desc"?"descending":K.column.getCanSort()?"none":void 0,children:[K.isPlaceholder?null:Kt.flexRender(K.column.columnDef.header,K.getContext()),K.column.getCanResize()&&t.jsx("div",{onMouseDown:K.getResizeHandler(),onTouchStart:K.getResizeHandler(),onDoubleClick:()=>Be(K.column.id),className:`absolute top-0 right-0 w-1 h-full cursor-col-resize select-none touch-none opacity-0 hover:opacity-100 transition-opacity ${K.column.getIsResizing()?"bg-primary opacity-100":"bg-border hover:bg-muted-foreground"}`})]},K.id))},D.id))}),t.jsx(Pl,{children:u?t.jsx(an,{children:t.jsx(Mn,{colSpan:Ge.length,className:"h-24 text-center",children:"Loading..."})}):ue.getRowModel().rows.length===0?t.jsx(an,{children:t.jsx(Mn,{colSpan:Ge.length,className:"h-24 text-center",children:"No results."})}):ue.getRowModel().rows.map(D=>t.jsx(Vl,{row:D,isSelected:m!=null&&D.id===m,checked:D.getIsSelected(),visibleKey:se,onRowSelect:h,onEditRow:$?rt:void 0,onDeleteRow:w?Je:void 0,suppressClick:z,hoverRow:S,scheduleDismiss:L,startPress:G,onPressMove:U,cancelPress:_},D.id))})]}),j&&($||w)&&t.jsx(Ml,{anchorEl:j.el,onEdit:$?ut:void 0,onDelete:w?st:void 0,onMouseEnter:v,onDismiss:L})]}),t.jsxs("div",{className:"flex items-center justify-between px-2 py-1.5 border-t border-border mt-auto shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[t.jsx("span",{children:"Rows per page"}),t.jsxs(Le,{value:String(re?An:i),onValueChange:D=>{const K=Number(D);K===An?(ae(!0),k(De())):(ae(!1),k(K))},children:[t.jsx(Ae,{size:"sm",className:"w-auto h-7 text-xs","aria-label":"Rows per page",children:t.jsx(Oe,{children:re?"Fit":i})}),t.jsxs(qe,{children:[t.jsx(ge,{value:String(An),children:"Fit"}),Ol.map(D=>t.jsx(ge,{value:String(D),children:D},D))]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("span",{className:"text-xs text-muted-foreground mr-2",children:["Page ",o+1," of ",s||1]}),t.jsx(W,{variant:"outline",size:"icon-sm",onClick:()=>b(0),disabled:o===0,"aria-label":"First page",title:"First page",children:t.jsx(N.ChevronsLeft,{className:"size-4"})}),t.jsx(W,{variant:"outline",size:"icon-sm",onClick:()=>b(o-1),disabled:!ue.getCanPreviousPage(),"aria-label":"Previous page",title:"Previous page",children:t.jsx(N.ChevronLeft,{className:"size-4"})}),t.jsx(W,{variant:"outline",size:"icon-sm",onClick:()=>b(o+1),disabled:!ue.getCanNextPage(),"aria-label":"Next page",title:"Next page",children:t.jsx(N.ChevronRight,{className:"size-4"})}),t.jsx(W,{variant:"outline",size:"icon-sm",onClick:()=>b(s-1),disabled:o>=s-1,"aria-label":"Last page",title:"Last page",children:t.jsx(N.ChevronsRight,{className:"size-4"})})]})]})]})}function ql({row:e,isSelected:n,checked:r,onRowSelect:s,onEditRow:o,onDeleteRow:i,suppressClick:a,hoverRow:l,scheduleDismiss:u,startPress:d,onPressMove:p,cancelPress:m}){const h=!!(s||o||i);return t.jsx(an,{"data-state":n||r?"selected":void 0,className:s?"cursor-pointer group/row focus-visible:outline-2 focus-visible:outline-primary":"group/row focus-visible:outline-2 focus-visible:outline-primary",tabIndex:h?0:void 0,onClick:s?()=>{if(a.current){a.current=!1;return}window.getSelection()?.toString()||s(n?null:e.id)}:void 0,onKeyDown:h?x=>{x.target===x.currentTarget&&((x.key==="Enter"||x.key===" ")&&s?(x.preventDefault(),s(n?null:e.id)):(x.key==="e"||x.key==="E")&&o?(x.preventDefault(),o(e.id)):(x.key==="Delete"||x.key==="Backspace")&&i&&(x.preventDefault(),i(e.id)))}:void 0,onFocus:x=>{x.target===x.currentTarget&&l(e.id,x.currentTarget)},onBlur:x=>{x.currentTarget.contains(x.relatedTarget)||u()},onPointerEnter:x=>{x.pointerType==="mouse"&&l(e.id,x.currentTarget)},onPointerLeave:x=>{x.pointerType==="mouse"&&u()},onPointerDown:x=>d(e.id,x.currentTarget,x),onPointerMove:p,onPointerUp:m,onPointerCancel:m,children:e.getVisibleCells().map(x=>t.jsx(Mn,{"data-col-id":x.column.id,children:Kt.flexRender(x.column.columnDef.cell,x.getContext())},x.id))})}const Vl=c.memo(ql);function Bl({...e}){return t.jsx(Q.Dialog.Root,{"data-slot":"sheet",...e})}function Kl({...e}){return t.jsx(Q.Dialog.Portal,{"data-slot":"sheet-portal",...e})}function Gl({className:e,...n}){return t.jsx(Q.Dialog.Overlay,{"data-slot":"sheet-overlay",className:H("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...n})}function Jl({className:e,children:n,side:r="right",...s}){return t.jsxs(Kl,{children:[t.jsx(Gl,{}),t.jsxs(Q.Dialog.Content,{"data-slot":"sheet-content",className:H("fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out duration-200 outline-none","data-[state=closed]:animate-out data-[state=open]:animate-in data-[state=closed]:duration-200 data-[state=open]:duration-200",r==="right"&&"inset-y-0 right-0 h-full w-3/4 max-w-md border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",r==="left"&&"inset-y-0 left-0 h-full w-3/4 max-w-md border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left",r==="top"&&"inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",r==="bottom"&&"inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",e),...s,children:[n,t.jsxs(Q.Dialog.Close,{"data-slot":"sheet-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[t.jsx(N.XIcon,{}),t.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function Wl({className:e,...n}){return t.jsx("div",{"data-slot":"sheet-header",className:H("flex flex-col gap-2 p-4 pb-0",e),...n})}function Hl({className:e,...n}){return t.jsx(Q.Dialog.Title,{"data-slot":"sheet-title",className:H("text-lg leading-none font-semibold",e),...n})}function Ql({className:e,...n}){return t.jsx(Q.Dialog.Description,{"data-slot":"sheet-description",className:H("text-sm text-muted-foreground",e),...n})}const Yl={json:N.Braces,xml:N.Code,"php-serialized":N.Database,binary:N.Binary,longtext:N.FileText,text:N.FileText},Rl={json:"JSON",xml:"XML","php-serialized":"PHP Serialized",binary:"Binary",longtext:"Text",text:"Text"};function Xl(e,n){if(n==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return n==="xml"?e.replace(/>\s*</g,`>
107
- <`).trim():e}function Ul({target:e,onClose:n,onNavigate:r,onSave:s,canNavigatePrev:o,canNavigateNext:i}){const[a,l]=c.useState(!1),[u,d]=c.useState(!1),[p,m]=c.useState(""),[h,x]=c.useState(!1),[g,b]=c.useState(!1),k=c.useRef(null),$=e?.value??"",w=Nn($,e?.dbType),P=Yl[w],C=Xl($,w);c.useEffect(()=>{d(!1),m(""),x(!1),b(!1)},[e?.rowKey,e?.columnName]),c.useEffect(()=>{if(!e)return;const _=G=>{u||(G.key==="ArrowUp"&&o?(G.preventDefault(),r("prev")):G.key==="ArrowDown"&&i&&(G.preventDefault(),r("next")))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[e,u,o,i,r]);const T=c.useCallback(()=>{navigator.clipboard.writeText($),x(!0),setTimeout(()=>x(!1),1500)},[$]),j=c.useCallback(()=>{m(C),d(!0),requestAnimationFrame(()=>k.current?.focus())},[C]),E=c.useCallback(()=>{d(!1),m("")},[]),y=c.useCallback(async()=>{if(p===C){d(!1);return}if(!(!s||g)){b(!0);try{await s(p),d(!1)}catch{}finally{b(!1)}}},[s,p,C,g]),S=c.useCallback(()=>{if(w==="json")try{m(JSON.stringify(JSON.parse(p),null,2))}catch{}else w==="xml"&&m(p.replace(/>\s*</g,`>
108
- <`).trim())},[p,w]),L=w==="json"||w==="xml",v=!!s&&!e?.isReadOnly&&w!=="binary",M=t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx(P,{className:"size-4 text-muted-foreground shrink-0"}),t.jsx("span",{className:"truncate font-semibold text-sm",children:e?.columnLabel}),t.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:Rl[w]}),t.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[$.length," chars"]})]}),O=t.jsxs("div",{className:"flex items-center gap-1 px-4 pb-2",children:[t.jsxs(W,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:T,children:[h?t.jsx(N.Check,{className:"size-3"}):t.jsx(N.Copy,{className:"size-3"}),h?"Copied":"Copy"]}),v&&!u&&t.jsxs(W,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:j,children:[t.jsx(N.Pencil,{className:"size-3"}),"Edit"]}),u&&L&&t.jsxs(W,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:S,children:[t.jsx(N.WrapText,{className:"size-3"}),"Format"]}),t.jsxs("div",{className:"flex items-center gap-1 ml-auto",children:[t.jsx(W,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>r("prev"),disabled:!o,"aria-label":"Previous row",title:"Previous row",children:t.jsx(N.ChevronUp,{className:"size-4"})}),t.jsx(W,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>r("next"),disabled:!i,"aria-label":"Next row",title:"Next row",children:t.jsx(N.ChevronDown,{className:"size-4"})}),t.jsx(W,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>l(_=>!_),"aria-label":a?"Exit full screen":"Full screen",title:a?"Exit full screen":"Full screen",children:a?t.jsx(N.Minimize2,{className:"size-4"}):t.jsx(N.Maximize2,{className:"size-4"})})]})]}),z=t.jsx("div",{className:"flex-1 min-h-0 overflow-auto px-4 pb-4",children:u?t.jsxs("div",{className:"flex flex-col gap-2 h-full",children:[t.jsx("textarea",{ref:k,value:p,onChange:_=>m(_.target.value),className:H("flex-1 w-full rounded-md border border-input bg-background px-3 py-2","text-xs font-mono leading-relaxed","ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","resize-none min-h-[200px]")}),t.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[t.jsx(W,{type:"button",variant:"ghost",size:"sm",onClick:E,disabled:g,children:"Cancel"}),t.jsx(W,{type:"button",size:"sm",onClick:y,disabled:g,children:g?"Saving…":"Save"})]})]}):t.jsx("pre",{className:"text-xs font-mono leading-relaxed whitespace-pre-wrap break-all",children:C})}),I=!!e;return t.jsxs(t.Fragment,{children:[t.jsx(Bl,{open:I&&!a,onOpenChange:_=>{_||n()},children:t.jsxs(Jl,{side:"right",className:"w-[480px] max-w-[90vw]",children:[t.jsxs(Wl,{children:[t.jsx(Hl,{children:M}),t.jsx(Ql,{className:"sr-only",children:"Content viewer panel"})]}),O,z]})}),t.jsx(Ze,{open:I&&a,onOpenChange:_=>{_||l(!1)},children:t.jsxs(et,{className:"max-w-[90vw] max-h-[90vh] w-full h-full flex flex-col",children:[t.jsxs(Ot,{children:[t.jsx(tt,{children:M}),t.jsx(jt,{className:"sr-only",children:"Content viewer full screen"})]}),O,z]})})]})}function qn({table:e,id:n,tableFilter:r,filterColumn:s,selectedRowId:o,onRowSelect:i,onOpenColumn:a,stackingEnabled:l,onToggleStacking:u}){const d=cs(e),[p,m]=c.useState(null),[h,x]=c.useState(null),[g,b]=c.useState(null),k=c.useRef([]),$=c.useCallback(X=>{x(vn(X,e))},[e]),w=c.useCallback(X=>{m({type:"single",pk:X})},[]),P=c.useCallback(X=>{X.length!==0&&m({type:"batch",pks:X})},[]),C=c.useCallback((X,se)=>{const Se=k.current[X];b({columnName:se,pk:Se?gt(Se,e):null,rowIndex:X,tableName:e.name})},[e]),{columns:T,sorting:j,columnFilters:E,pageIndex:y,pageSize:S,pageCount:L,rows:v,loading:M,error:O,onSortingChange:z,onColumnFiltersChange:I,onPageIndexChange:_,onPageSizeChange:G}=Gi(e,n,r,s,C,a),U=c.useCallback(async()=>{if(p)try{p.type==="single"?await d.deleteRow(p.pk):await d.deleteRows(p.pks),m(null)}catch{}},[p,d]),ie=p?.type==="batch"?p.pks.length:1;k.current=v;const{toast:B}=rn(),Te=Ce(),ye=e.isEditable!==!1,xe=c.useMemo(()=>g?.pk?vn(g.pk,e):null,[g,e]),le=c.useMemo(()=>!g||g.tableName!==e.name?-1:xe===null?g.rowIndex<v.length?g.rowIndex:-1:v.findIndex(X=>{const se=gt(X,e);return se!==null&&vn(se,e)===xe}),[g,xe,v,e]),re=le>=0?v[le]:void 0;c.useEffect(()=>{g!==null&&g.tableName!==e.name&&b(null)},[g,e.name]),c.useEffect(()=>{g!==null&&g.tableName===e.name&&!M&&le===-1&&(b(null),B("Row is no longer in the current view; panel closed.","error"))},[g,e.name,M,le,B]);const ae=c.useMemo(()=>{if(!g||!re)return null;const X=e.columns.find(rt=>rt.name===g.columnName);if(!X)return null;const se=re[g.columnName],Se=lt(X);return{value:se==null?"":Se||typeof se=="object"?JSON.stringify(se,null,2):String(se),columnName:X.name,columnLabel:X.label,dbType:X.dbType,rowKey:xe??`row-${g.rowIndex}`,isReadOnly:X.isReadOnly||X.isPrimaryKey||X.isIdentity}},[g,re,xe,e]),J=c.useMemo(()=>g?.pk?yn(g.pk,e):null,[g,e]),ce=c.useMemo(()=>e.columns.filter(X=>!X.isReadOnly&&!X.isIdentity),[e]),R=c.useMemo(()=>ce.filter(X=>!X.isNullable||X.name===g?.columnName),[ce,g?.columnName]),Ne=c.useMemo(()=>R.map(X=>({column:X})),[R]),Be=c.useMemo(()=>{const X=new Map(e.columns.map(se=>[se.name,se]));return(e.primaryKeys??[]).map(se=>X.get(se)).filter(se=>!!se)},[e]),ze=sn(e,Ne,Be,xe??""),Ke=ye&&J!==null&&!ze.isPending,De=c.useCallback(async X=>{if(!g||!J)return;const se=e.columns.find($e=>$e.name===g.columnName);let Se=X;if(se&&lt(se))try{Se=JSON.parse(X)}catch{}try{const $e=Ta(e,J,R.map(st=>st.name)),Je=(await Te.query($e,J.variables))?.value?.data?.[0];if(!Je)throw new Error("Row no longer exists.");const ut={};for(const st of R)ut[st.name]=Je[st.name]??null;ut[g.columnName]=Se,await ze.update(ut)}catch($e){throw B(`Save failed: ${$e.message}`,"error"),$e}},[g,J,e,R,ze,Te,B]),Ge=c.useCallback(()=>{b(null)},[]),ue=c.useCallback(X=>{if(!g||le<0)return;const se=X==="prev"?Math.max(0,le-1):Math.min(v.length-1,le+1);C(se,g.columnName)},[g,le,v.length,C]);return O?t.jsx(pt,{variant:"destructive",className:"m-2",children:t.jsxs(ht,{children:["Error: ",O.message]})}):t.jsxs(t.Fragment,{children:[t.jsx(Al,{columns:T,data:v,tableName:e.name,pageCount:L,pageIndex:y,pageSize:S,sorting:j,columnFilters:E,loading:M,primaryKeys:e.primaryKeys??[],selectable:ye,selectedRowId:o,onRowSelect:i,onSortingChange:z,onColumnFiltersChange:I,onPageIndexChange:_,onPageSizeChange:G,onEditRow:ye?$:void 0,onDeleteRow:ye?w:void 0,onDeleteSelected:ye?P:void 0,stackingEnabled:l,onToggleStacking:u}),t.jsx(En,{open:p!==null,onOpenChange:X=>{X||m(null)},title:`Delete ${ie} ${ie===1?"row":"rows"}?`,description:t.jsxs(t.Fragment,{children:[t.jsx("p",{children:"This action cannot be undone."}),d.error&&t.jsx("p",{className:"mt-2 text-sm text-destructive",children:d.error.message})]}),confirmLabel:`Delete ${ie===1?"row":`${ie} rows`}`,variant:"destructive",isPending:d.isPending,onConfirm:U}),t.jsx(Ul,{target:ae,onClose:Ge,onNavigate:ue,onSave:Ke?De:void 0,canNavigatePrev:le>0,canNavigateNext:le>=0&&le<v.length-1}),h!==null&&t.jsx(ws,{table:e.graphQlName,editid:h,onClose:()=>x(null)})]})}function Zl(e){return new Set((e.manyToManyJoins??[]).map(n=>n.junctionTable))}function _s(e){const n=Zl(e),r=e.multiJoins.filter(o=>!n.has(o.destinationTable)).map(o=>({kind:"child",key:`child:${o.fieldName??o.destinationTable}`,join:o})),s=(e.manyToManyJoins??[]).map(o=>({kind:"m2m",key:`m2m:${o.junctionTable}:${o.targetTable}`,m2m:o}));return[...r,...s]}function Fs(e,n){const r=new Set([...n.junctionSourceColumnNames,...n.junctionTargetColumnNames]);return e.columns.filter(s=>!s.isPrimaryKey&&!r.has(s.name))}function ec(e,n,r,s){const o=r.junctionSourceColumnNames;if(o.length===0)throw new Error(`Many-to-many relationship '${r.name}' has no junction source columns.`);const i=Pr(s,o.length),a=new Map(e.columns.map(P=>[P.name,P])),l=[],u=[],d={};o.forEach((P,C)=>{const T=a.get(P);if(!T)throw new Error(`Junction table '${e.name}' has no column '${P}' (junction source column of many-to-many relationship '${r.name}').`);const j=T.paramType.replace("!",""),E=`src${C}`;l.push(`$${E}: ${j}`),u.push(`{ ${P}: { _eq: $${E} } }`),d[E]=Xe(i[C],j)});const p=u.length===1?u[0]:`{ and: [${u.join(", ")}] }`,m=e.primaryKeys??[],h=Fs(e,r).map(P=>P.name),x=n.primaryKeys?.length?n.primaryKeys:r.targetColumnNames,g=n.labelColumn,b=[...x];g&&!x.includes(g)&&b.push(`label: ${g}`);const k=`${r.junctionTargetField} { ${b.join(" ")} }`,$=[...m,...h,k].join(" ");return{query:`query GetLinks_${e.name}(${l.join(", ")}, $limit: Int, $offset: Int) { ${e.name}(filter: ${p} limit: $limit offset: $offset) { total offset limit data { ${$} } } }`,variables:d}}function tc(e,n,r){Fe(e.name,"many-to-many target table name");const s=Qe(e)[0]?.name??n.targetColumnNames[0],o=e.labelColumn||s;Fe(s,"many-to-many target id column"),Fe(o,"many-to-many target label column");const i=o!==s?`${s} label: ${o}`:s,a=e.columns.find(h=>h.name===o);if(!a)throw new Error(`Target table '${e.name}' has no column '${o}' (label column for the '${n.name}' many-to-many picker).`);const l=a.paramType.replace("!","")==="String",u=!!r&&r.trim()!==""&&l,d=u?"$limit: Int, $search: String":"$limit: Int",p=u?`filter: {${o}: {_contains: $search}} `:"";return{query:`query PickTarget(${d}) { ${e.name}(${p}limit: $limit sort: [${o}_asc]) { data { ${i} } } }`,idColumn:s,serverSearch:l}}function nc(e,n,r){const s=e[n.junctionTargetField];if(!s)return null;const o=_t(s,r,0),i=s.label!=null?String(s.label):o;return{id:o,label:i}}function rc(e,n,r){if(e.junctionSourceColumnNames.length!==1||e.junctionTargetColumnNames.length!==1)throw new Error("attachJunctionDetail supports single-column junction FKs only; this relationship uses a composite key which is not yet supported.");const[s]=Pr(n,1);return{[e.junctionSourceColumnNames[0]]:s,[e.junctionTargetColumnNames[0]]:r}}const Vn=200,sc=50,oc=500;function ac({parentTable:e,m2m:n,parentRowId:r,onOpenColumn:s}){const o=Pe(),i=Ce(),a=me.useQueryClient(),{toast:l}=rn(),[u,d]=c.useState(!1),[p,m]=c.useState(null),h=o.findTable(n.junctionTable),x=o.findTable(n.targetTable),g=cs(h??e);let b={query:null,variables:{}},k=null;if(h&&x)try{b=ec(h,x,n,r)}catch(z){k=z}const{query:$,variables:w}=b,P=c.useMemo(()=>["m2mRows",n.junctionTable,n.targetTable,r],[n.junctionTable,n.targetTable,r]),{data:C,isLoading:T,error:j}=me.useQuery({queryKey:P,queryFn:()=>i.query($,{...w,limit:Vn,offset:0}),enabled:!!$}),E=c.useCallback(()=>a.invalidateQueries({queryKey:P}),[a,P]),y=c.useCallback(async z=>{if(!h)return;const I=gt(z,h);I&&(await g.deleteRow(I),await E())},[h,g,E]);if(!h||!x)return t.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Relationship schema unavailable."});if(k)return t.jsxs("div",{className:"p-4 text-sm text-destructive",children:["Relationship misconfigured: ",k.message]});const S=C?.[h.name]?.data??[],L=Fs(h,n),v=h.isEditable!==!1,M=Qe(x)[0]?.name??n.targetColumnNames[0],O=new Set;for(const z of S){const _=z[n.junctionTargetField]?.[M];_!=null&&O.add(String(_))}return t.jsxs("div",{className:"flex flex-col min-h-0 flex-1 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 bg-muted/20 border-b border-border shrink-0",children:[t.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs text-muted-foreground",title:`Linked through ${h.label}`,children:[t.jsx(N.Link2,{className:"size-3"}),"via ",h.label]}),v&&t.jsxs(W,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs ml-auto",onClick:()=>d(!0),children:[t.jsx(N.Plus,{className:"size-3 mr-1"})," Add link"]})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-auto",children:[j&&t.jsxs("div",{className:"p-3 text-sm text-destructive",children:["Error: ",j.message]}),T&&t.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[t.jsx(N.Loader2,{className:"size-4 animate-spin"})," Loading…"]}),!T&&S.length===0&&t.jsxs("div",{className:"p-3 text-sm text-muted-foreground",children:["No linked ",x.label,"."]}),S.length>0&&t.jsxs("table",{className:"w-full text-sm",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"border-b border-border text-left text-xs text-muted-foreground",children:[t.jsx("th",{className:"px-2 py-1 font-medium",children:x.label}),L.map(z=>t.jsx("th",{className:"px-2 py-1 font-medium",children:z.label},z.name)),v&&t.jsx("th",{className:"px-2 py-1 w-8","aria-label":"actions"})]})}),t.jsx("tbody",{children:S.map((z,I)=>{const _=nc(z,n,x);return t.jsxs("tr",{className:"border-b border-border/50 hover:bg-muted/30",children:[t.jsx("td",{className:"px-2 py-1",children:_?t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(St,{to:`/${x.name}/${_.id}`,className:"text-primary hover:underline",children:_.label}),s&&t.jsx(W,{variant:"ghost",size:"icon-sm",className:"size-5",onClick:()=>s({tableName:x.name,filterId:_.id}),"aria-label":`Open ${_.label} in side column`,title:"Open in side column",children:t.jsx(N.Search,{className:"size-3"})})]}):t.jsx("span",{className:"text-muted-foreground",children:"—"})}),L.map(G=>t.jsx("td",{className:"px-2 py-1",children:tn(z[G.name],G)},G.name)),v&&t.jsx("td",{className:"px-2 py-1",children:t.jsx(W,{variant:"ghost",size:"icon-sm",className:"size-6 text-muted-foreground hover:text-destructive",onClick:()=>m(z),disabled:g.isPending,"aria-label":`Detach ${_?.label??"link"}`,title:"Detach",children:t.jsx(N.Unlink,{className:"size-3.5"})})})]},I)})})]}),S.length>=Vn&&t.jsxs("div",{className:"px-3 py-2 text-xs text-muted-foreground italic border-t border-border",children:["Showing the first ",Vn," links. Detach some or narrow the parent selection to see more."]})]}),u&&t.jsx(ic,{target:x,junction:h,m2m:n,parentRowId:r,linkedIds:O,onClose:()=>d(!1),onLinked:E}),t.jsx(En,{open:p!==null,onOpenChange:z=>{z||m(null)},title:"Detach this link?",description:t.jsxs("p",{children:["This removes the link row. The ",x.label," record itself is not deleted."]}),confirmLabel:"Detach",variant:"destructive",isPending:g.isPending,onConfirm:async()=>{try{p&&await y(p)}catch(z){l(`Detach failed: ${z.message}`,"error")}finally{m(null)}}})]})}function ic({target:e,junction:n,m2m:r,parentRowId:s,linkedIds:o,onClose:i,onLinked:a}){const l=Ce(),u=n.columns.filter(v=>r.junctionSourceColumnNames.includes(v.name)||r.junctionTargetColumnNames.includes(v.name)).map(v=>({column:v})),d=sn(n,u,[]),[p,m]=c.useState(""),[h,x]=c.useState("");c.useEffect(()=>{const v=setTimeout(()=>x(p),300);return()=>clearTimeout(v)},[p]);const g=h.trim();let b=null,k=null;try{b=tc(e,r,g)}catch(v){k=v}const{query:$,idColumn:w,serverSearch:P}=b??{query:"",idColumn:"",serverSearch:!1},C=P?sc:oc,{data:T,isLoading:j}=me.useQuery({queryKey:["m2mTargets",e.name,P?g:""],queryFn:({signal:v})=>l.query($,P&&g?{limit:C,search:g}:{limit:C},{signal:v}),enabled:b!==null}),E=T?.[e.name]?.data??[],y=P||!g?E:E.filter(v=>xs(v,w,g)),S=E.length>=C,L=c.useCallback(async v=>{if(!o.has(v)){try{await d.insert(rc(r,s,v))}catch{return}await a(),i()}},[d,r,s,o,a,i]);return k?t.jsx(Ze,{open:!0,onOpenChange:v=>{v||i()},children:t.jsxs(et,{className:"max-w-md",children:[t.jsx(Ot,{children:t.jsxs(tt,{children:["Add ",e.label," link"]})}),t.jsxs("p",{className:"text-sm text-destructive",children:["Relationship misconfigured: ",k.message]})]})}):t.jsx(Ze,{open:!0,onOpenChange:v=>{v||i()},children:t.jsxs(et,{className:"max-w-md",children:[t.jsx(Ot,{children:t.jsxs(tt,{children:["Add ",e.label," link"]})}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(N.Search,{className:"size-4 text-muted-foreground"}),t.jsx(ke,{autoFocus:!0,placeholder:`Search ${e.label}…`,value:p,onChange:v=>m(v.target.value)})]}),d.error&&t.jsx("p",{className:"text-sm text-destructive",children:d.error.message}),t.jsxs("div",{className:"max-h-72 overflow-auto border border-border rounded-md",children:[j&&t.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[t.jsx(N.Loader2,{className:"size-4 animate-spin"})," Loading…"]}),!j&&y.length===0&&t.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No matches."}),y.map((v,M)=>{const O=String(v[w]??""),z=v.label!=null?String(v.label):O,I=o.has(O);return t.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-2 text-left px-3 py-1.5 text-sm hover:bg-muted/50 disabled:opacity-50 disabled:hover:bg-transparent",disabled:d.isPending||I,onClick:()=>L(O),children:[t.jsx("span",{className:"truncate",children:z}),I&&t.jsx("span",{className:"shrink-0 text-xs text-muted-foreground italic",children:"Already linked"})]},M)}),!j&&S&&t.jsx("div",{className:"px-3 py-1.5 text-xs text-muted-foreground italic border-t border-border",children:P?`Showing the first ${C} matches — type to narrow.`:`Showing the first ${C} rows; some may not be listed.`})]})]})})}function zs(e){return e.kind==="child"?e.join.destinationTable:e.m2m.targetTable}function Es({parentTable:e,selectedRowId:n,onClose:r,onOpenColumn:s}){const o=Pe(),i=_s(e),[a,l]=c.useState(i[0]?.key??""),[u,d]=c.useState(!1),[p,m]=c.useState(null),h=i.find(b=>b.key===a)??i[0];if(c.useEffect(()=>{m(null)},[a,n]),i.length===0||!o.data)return null;const x=h.kind==="child"?o.findTable(h.join.destinationTable):void 0,g=(x?.multiJoins?.length??0)>0;return t.jsxs("div",{className:"border-t-2 border-primary/20 flex flex-col min-h-0 flex-1 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted/30 border-b border-border shrink-0",children:[t.jsx(W,{variant:"ghost",size:"icon-sm",onClick:()=>d(!u),"aria-label":u?"Expand detail panel":"Collapse detail panel",title:u?"Expand detail panel":"Collapse detail panel",children:u?t.jsx(N.ChevronUp,{className:"size-3.5"}):t.jsx(N.ChevronDown,{className:"size-3.5"})}),t.jsx("span",{className:"text-xs text-muted-foreground mr-1",children:"Detail:"}),t.jsx("div",{className:"flex items-center gap-0.5 overflow-x-auto",children:i.map(b=>{const $=o.findTable(zs(b))?.label??zs(b),w=b.key===h.key;return t.jsxs("span",{className:"group/tab inline-flex items-center",children:[t.jsx(W,{variant:w?"secondary":"ghost",size:"sm",className:H("text-xs h-7 px-2.5",w&&"font-semibold"),onClick:()=>l(b.key),children:$}),s&&b.kind==="child"&&t.jsx(W,{variant:"ghost",size:"icon-sm",className:"opacity-0 group-hover/tab:opacity-100 size-5 shrink-0",onClick:()=>s({tableName:b.join.destinationTable,filterTable:e.name,filterId:n,...it(b.join)?{}:{filterColumn:b.join.destinationColumnNames[0]}}),"aria-label":"Open in side column",title:"Open in side column",children:t.jsx(N.PanelRight,{className:"size-3"})})]},b.key)})}),r&&t.jsx(W,{variant:"ghost",size:"icon-sm",onClick:r,className:"ml-auto shrink-0","aria-label":"Close detail panel",title:"Close detail panel",children:t.jsx(N.X,{className:"size-3.5"})})]}),!u&&t.jsx("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:h.kind==="child"&&!x?t.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"This related table is not available."}):h.kind==="child"?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:g&&p?"flex-1 min-h-0 max-h-[50%] overflow-hidden flex flex-col":"flex-1 min-h-0 overflow-hidden flex flex-col",children:t.jsx(qn,{table:x,id:n,tableFilter:e.name,...it(h.join)?{}:{filterColumn:h.join.destinationColumnNames[0]},selectedRowId:g?p:void 0,onRowSelect:g?m:void 0,onOpenColumn:s},`${h.key}-${n}`)}),g&&p&&t.jsx("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:t.jsx(Es,{parentTable:x,selectedRowId:p,onClose:()=>m(null),onOpenColumn:s})})]}):t.jsx(ac,{parentTable:e,m2m:h.m2m,parentRowId:n,onOpenColumn:s},`${h.key}-${n}`)})]})}const lc={mainTable:null,columns:[],focusedIndex:0,focusColumn:()=>{},closeColumn:()=>{}},Ps=c.createContext(lc),Ds=c.createContext({register:()=>{},unregister:()=>{}});function cc({children:e}){const[n,r]=c.useState(null),[s,o]=c.useState(0),i=c.useCallback(h=>{r(h)},[]),a=c.useCallback(()=>{r(null),o(0)},[]),l=c.useCallback(h=>{if(o(h),!n)return;const x=n.columnRefs.get(h);x&&x.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[n]),u=c.useCallback(h=>{n&&h>0&&n.onClose(h-1)},[n]),d=c.useMemo(()=>n?n.columns.map((h,x)=>({panel:h,element:n.columnRefs.get(x+1)??null})):[],[n]),p=c.useMemo(()=>({mainTable:n?.mainTable??null,columns:d,focusedIndex:s,focusColumn:l,closeColumn:u}),[n,d,s,l,u]),m=c.useMemo(()=>({register:i,unregister:a}),[i,a]);return t.jsx(Ds.Provider,{value:m,children:t.jsx(Ps.Provider,{value:p,children:e})})}function dc(){return c.useContext(Ps)}function uc(){return c.useContext(Ds)}function Ms(e,n){return e.tableName===n.tableName&&e.filterTable===n.filterTable&&e.filterId===n.filterId&&e.filterColumn===n.filterColumn}function mc(e,n){const r=e[e.length-1];if(r&&Ms(r,n))return e;const s=e.findIndex(o=>Ms(o,n));return s>=0?e.slice(0,s+1):[...e,n]}function fc(e,n){return n<0?[]:n>=e.length?e:e.slice(0,n)}function pc(e,n,r){const s=i=>r(i)??i,o=[{index:-1,label:s(e)}];for(let i=0;i<n.length;i++){const a=n[i],l=a.filterTable?s(a.filterTable):s(i===0?e:n[i-1].tableName),u=a.filterId?`from ${l} #${a.filterId}`:void 0;o.push({index:i,label:s(a.tableName),detail:u,frame:a})}return o}function ln(e,n){return e.find(r=>r.name===n)}function dt(){const e=mn(),{table:n,id:r,filterTable:s}=e,{loading:o,error:i,data:a}=Pe(),[l,u]=c.useState(null),[d,p]=c.useState([]),[m,h]=c.useState(!0),[x,g]=c.useState(new Set),b=c.useRef(n);n!==b.current&&(b.current=n,d.length>0&&p([]),x.size>0&&g(new Set));const k=c.useCallback(_=>{g(G=>{const U=new Set(G);return U.has(_)?U.delete(_):U.add(_),U})},[]),{register:$,unregister:w}=uc(),P=c.useRef(null),C=c.useRef(new Map),T=c.useMemo(()=>a?ln(a,n):void 0,[a,n]),j=T?_s(T).length>0:!1,E=c.useCallback(_=>{p(G=>mc(G,_))},[]),y=c.useCallback(_=>{h(_),_||p([])},[]),S=m?E:void 0,L=c.useCallback(_=>{p(G=>G.filter((U,ie)=>ie!==_))},[]),v=c.useCallback(_=>{p(G=>fc(G,_+1))},[]),M=c.useMemo(()=>pc(n??"",d,_=>{if(a)return ln(a,_)?.label}),[n,d,a]);if(c.useEffect(()=>{const _=C.current;_.set(0,P.current);for(const G of _.keys())G>d.length&&_.delete(G);return $({mainTable:n,columns:d,columnRefs:_,onClose:L}),()=>w()},[n,d,$,w,L]),!n)return t.jsx("div",{className:"p-5 text-center text-muted-foreground",children:"Table missing"});if(o)return t.jsxs("div",{className:"flex items-center justify-center gap-2 p-5",children:[t.jsx(N.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),t.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]});if(i)return t.jsx(pt,{variant:"destructive",className:"m-2",children:t.jsxs(ht,{children:["Error: ",i.message]})});if(!T)return t.jsx("div",{className:"p-5 text-center text-muted-foreground",children:"Table not found"});const O=t.jsx(qn,{table:T,id:r,tableFilter:s,selectedRowId:j?l:void 0,onRowSelect:j?u:void 0,onOpenColumn:S,stackingEnabled:m,onToggleStacking:y});if(d.length===0)return t.jsx("div",{className:"flex flex-col flex-1 min-h-0",children:t.jsxs("div",{ref:P,className:"flex flex-col flex-1 min-h-0 min-w-0",children:[t.jsx("div",{className:j&&l?"flex-1 min-h-0 max-h-[50%] overflow-hidden flex flex-col":"flex-1 min-h-0 overflow-hidden flex flex-col",children:O}),j&&l&&t.jsx("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:t.jsx(Es,{parentTable:T,selectedRowId:l,onClose:()=>u(null),onOpenColumn:S})})]})});const z=d.length-1,I=(_,G)=>G||x.has(_);return t.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[t.jsx(hc,{crumbs:M,onCrumbClick:v,activeIndex:d.length-1}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto flex flex-col gap-0.5 p-0.5",children:[t.jsx(Is,{title:T.label,selectedRowId:d[0]?.filterId,expanded:I(-1,!1),active:!1,onToggle:()=>k(-1),onRef:_=>{P.current=_,C.current.set(0,_)},children:O}),d.map((_,G)=>{const U=G===z;return t.jsx(Is,{title:ln(a,_.tableName)?.label??_.tableName,selectedRowId:d[G+1]?.filterId,expanded:I(G,U),active:U,onToggle:()=>k(G),onClose:()=>L(G),onRef:ie=>{C.current.set(G+1,ie)},children:t.jsx(qn,{table:ln(a,_.tableName),id:_.filterId,tableFilter:_.filterTable,filterColumn:_.filterColumn,onOpenColumn:E})},`${_.tableName}|${_.filterTable??""}|${_.filterId??""}|${_.filterColumn??""}`)})]})]})}function hc({crumbs:e,onCrumbClick:n,activeIndex:r}){return t.jsx("nav",{"aria-label":"Drill-down breadcrumb",className:"flex items-center gap-1 px-2 py-1 bg-muted/20 border-b border-border shrink-0 overflow-x-auto",children:e.map((s,o)=>{const i=s.index===r,a=o===0;return t.jsxs("span",{className:"inline-flex items-center gap-1 shrink-0",children:[!a&&t.jsx(N.ChevronRight,{className:"size-3 text-muted-foreground shrink-0"}),t.jsxs(W,{variant:i?"secondary":"ghost",size:"sm",className:H("h-6 px-2 text-xs gap-1",i&&"font-semibold"),onClick:()=>n(s.index),"aria-current":i?"page":void 0,title:s.detail?`${s.label} (${s.detail})`:s.label,children:[a&&t.jsx(N.Home,{className:"size-3"}),t.jsx("span",{className:"truncate max-w-[12rem]",children:s.label}),s.detail&&t.jsx("span",{className:"text-muted-foreground font-normal truncate max-w-[10rem]",children:s.detail})]})]},`${s.index}-${s.label}`)})})}function Is({title:e,selectedRowId:n,expanded:r,active:s,onToggle:o,onClose:i,onRef:a,children:l}){return t.jsxs("div",{ref:a,className:"shrink-0 flex flex-col border border-border rounded-sm overflow-hidden",children:[t.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted/30 border-b border-border shrink-0",children:[t.jsx("button",{type:"button",onClick:o,className:"inline-flex items-center justify-center size-5 shrink-0 text-muted-foreground hover:text-foreground","aria-expanded":r,"aria-label":r?"Collapse table":"Expand table",title:r?"Collapse":"Expand",children:r?t.jsx(N.ChevronDown,{className:"size-3.5"}):t.jsx(N.ChevronRight,{className:"size-3.5"})}),t.jsx("span",{className:"text-xs font-medium truncate",children:e}),s&&t.jsx("span",{className:"text-[10px] uppercase tracking-wide text-primary/70 shrink-0",children:"active"}),!r&&n&&t.jsxs("span",{className:"text-xs text-muted-foreground truncate",children:["#",n]}),t.jsx("div",{className:"flex-1"}),i&&t.jsx(W,{variant:"ghost",size:"icon-sm",className:"shrink-0",onClick:i,"aria-label":"Close column",title:"Close column",children:t.jsx(N.X,{className:"size-3.5"})})]}),r&&t.jsx("div",{className:"flex flex-col min-h-[18rem] max-h-[34rem]",children:l})]})}function Bn(){const e=mn(),{loading:n,error:r,data:s}=Pe(),{mainTable:o,columns:i,focusedIndex:a,focusColumn:l,closeColumn:u}=dc(),[d,p]=c.useState(""),m=Wt(),{search:h}=er(),x=!!h.get("filter"),{back:g,hasBack:b}=eo(),k=e?.table,$=i.length>0,w=c.useMemo(()=>s?.find(y=>y.graphQlName===k),[s,k]),P=c.useMemo(()=>w?.columns?.filter(y=>{const S=y.paramType.replace("!","");return S==="String"||S==="Int"||S==="Float"}).map(y=>({key:y.name,value:`${y.name},${y.paramType}`,label:y.label})),[w]),[C,T]=c.useState(P?.at(0)?.value??"");c.useEffect(()=>{p(""),T(P?.at(0)?.value??"")},[P]);const j=()=>{if(!d)return;const[y,S]=C.split(",");if(!S)return;const L=S.replace("!","");if(L==="Int"||L==="Float"){const v=Number(d);if(!Number.isFinite(v))return;m(`?filter=["${y}", "_eq", ${v}, "${S}"]`)}else L==="String"&&m(`?filter=["${y}", "_contains", ${JSON.stringify(d)}, "${S}"]`)},E=()=>{p("");const y=new URLSearchParams(h.toString());y.delete("filter");const S=y.toString();m(S?`?${S}`:"?")};return n?t.jsxs("div",{className:"flex items-center gap-2 p-2.5",children:[t.jsx(N.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),t.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):r?t.jsx(pt,{variant:"destructive",className:"m-2",children:t.jsxs(ht,{children:["Error: ",r.message]})}):t.jsxs("header",{className:"flex flex-wrap items-center gap-x-3 gap-y-1.5 px-3 py-1.5 min-h-[2.5rem]",children:[t.jsxs("div",{className:"flex items-center gap-1.5 overflow-x-auto min-w-0 flex-1",children:[t.jsx(W,{variant:"ghost",size:"icon-sm",onClick:()=>b&&g(),disabled:!b,"aria-label":"Go back",title:"Go back",className:"shrink-0",children:t.jsx(N.ChevronLeft,{className:"size-4"})}),$?t.jsxs("div",{className:"flex items-center gap-1 overflow-x-auto",children:[t.jsx("button",{type:"button",onClick:()=>l(0),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium whitespace-nowrap transition-colors ${a===0?"bg-primary text-primary-foreground":"bg-muted/50 text-muted-foreground hover:bg-muted"}`,children:w?.label??Ht(e?.table??"")}),i.map((y,S)=>{const v=s?.find(M=>M.graphQlName===y.panel.tableName)?.label??Ht(y.panel.tableName);return t.jsxs("span",{className:`inline-flex items-center gap-1 pl-2 pr-1 py-0.5 rounded text-xs font-medium whitespace-nowrap transition-colors ${a===S+1?"bg-primary text-primary-foreground":"bg-muted/50 text-muted-foreground hover:bg-muted"}`,children:[t.jsx("button",{type:"button",onClick:()=>l(S+1),className:"whitespace-nowrap",children:v}),t.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),u(S+1)},className:"rounded-sm hover:bg-background/50 p-px","aria-label":`Close ${v}`,children:t.jsx(N.X,{className:"size-3"})})]},`${y.panel.tableName}-${y.panel.filterId??S}`)})]}):t.jsx("h2",{className:"text-sm font-semibold whitespace-nowrap",children:w?.label??e?.table??"(Select)"})]}),P&&P.length>0&&t.jsxs("div",{className:"flex items-center border border-border rounded-md overflow-hidden flex-[2_2_16rem] min-w-[12rem]",children:[t.jsxs(Le,{value:C,onValueChange:T,children:[t.jsx(Ae,{size:"sm",className:"w-auto min-w-[120px] shrink-0 border-0 rounded-none border-r border-border h-8 text-xs",children:t.jsx(Oe,{})}),t.jsx(qe,{children:P.map(y=>t.jsx(ge,{value:y.value,children:y.label},y.key))})]}),t.jsxs("div",{className:"relative flex-1 min-w-[180px]",children:[t.jsx(N.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground pointer-events-none"}),t.jsx(ke,{type:"search",value:d,onChange:y=>p(y.target.value),onKeyDown:y=>y.key==="Enter"&&j(),className:"h-8 border-0 rounded-none focus-visible:ring-0 focus-visible:ring-offset-0",style:{paddingLeft:"2.25rem"},placeholder:"Search..."})]}),t.jsxs(W,{variant:"ghost",size:"sm",onClick:j,className:"shrink-0 rounded-none border-l border-border h-8 px-3 text-xs",children:[t.jsx(N.Filter,{className:"size-3.5"}),"Filter"]}),x&&t.jsx(W,{variant:"ghost",size:"sm",onClick:E,title:"Clear filter","aria-label":"Clear filter",className:"shrink-0 rounded-none border-l border-border h-8 px-2 text-xs text-muted-foreground",children:t.jsx(N.X,{className:"size-3.5"})})]}),w&&t.jsxs("div",{className:"flex items-center gap-px border border-border rounded-md overflow-hidden shrink-0",children:[t.jsxs(W,{variant:"ghost",size:"sm",onClick:()=>m("/"),title:"Back to table list",className:"text-muted-foreground text-xs h-8 px-3 rounded-none",children:[t.jsx(N.Home,{className:"size-3.5"}),"Home"]}),w?.isEditable&&t.jsxs(W,{variant:"default",size:"sm",onClick:()=>m("edit/"),className:"h-8 text-xs px-4 rounded-none",children:[t.jsx(N.Plus,{className:"size-3.5"}),"Add"]})]})]})}class cn extends c.Component{constructor(n){super(n),this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,r){const{onError:s,section:o}=this.props;console.error(`Error in ${o??"component"}:`,n,r),s?.(n,r)}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){const{hasError:n,error:r}=this.state,{children:s,fallback:o,section:i}=this.props;return n?o||t.jsx("div",{className:"flex items-center justify-center p-5 min-h-[100px]",children:t.jsxs(pt,{variant:"destructive",className:"max-w-[400px]",children:[t.jsx(N.AlertCircle,{className:"size-4"}),t.jsxs(Er,{children:["Something went wrong",i?` in ${i}`:""]}),t.jsxs(ht,{className:"mt-2",children:[t.jsx("p",{children:r?.message??"An unexpected error occurred"}),t.jsx(W,{variant:"destructive",size:"sm",className:"mt-3",onClick:this.handleRetry,children:"Try Again"})]})]})}):s}}function xc(){const{loading:e,error:n,data:r}=Pe();return e?t.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[t.jsx(N.Database,{className:"size-10 animate-pulse"}),t.jsx("p",{className:"text-sm",children:"Loading schema..."})]}):n?t.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 max-w-md mx-auto text-center",children:[t.jsx(N.Database,{className:"size-12 text-destructive"}),t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Connection Error"}),t.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:n.message})]})]}):r.length===0?t.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 max-w-md mx-auto text-center",children:[t.jsx(N.Database,{className:"size-12 text-muted-foreground/50"}),t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"No Tables Found"}),t.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"This database doesn't contain any tables. It may be a new or empty database."}),t.jsx("p",{className:"mt-3 text-xs text-muted-foreground/70",children:"Create tables in your database and reconnect, or try a different connection."})]})]}):t.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-6 max-w-lg mx-auto text-center",children:[t.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground/50",children:[t.jsx(N.Table2,{className:"size-10"}),t.jsx(N.MousePointerClick,{className:"size-6"})]}),t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Select a Table"}),t.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Choose a table from the sidebar to browse and edit its data."})]}),t.jsxs("div",{className:"text-xs text-muted-foreground/60 border border-border rounded-md px-4 py-3 bg-muted/30",children:[t.jsxs("p",{className:"font-medium text-muted-foreground mb-1",children:[r.length," table",r.length!==1?"s":""," available"]}),t.jsxs("p",{className:"leading-relaxed",children:[r.slice(0,8).map(s=>s.label).join(", "),r.length>8?`, and ${r.length-8} more`:""]})]})]})}function gc({children:e}){const{loading:n,error:r}=Pe();return n?t.jsxs("div",{className:"flex items-center justify-center flex-1 gap-3 text-muted-foreground",children:[t.jsx(N.Loader2,{className:"size-6 animate-spin"}),t.jsx("span",{className:"text-sm",children:"Connecting to database..."})]}):r?t.jsx("div",{className:"flex items-center justify-center flex-1",children:t.jsxs(pt,{variant:"destructive",className:"max-w-lg",children:[t.jsx(N.AlertCircle,{className:"size-4"}),t.jsx(Er,{children:"Database Connection Error"}),t.jsxs(ht,{className:"mt-2",children:[t.jsx("p",{className:"text-sm",children:r.message}),t.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Check your connection string and ensure the database server is running."})]})]})}):t.jsx(t.Fragment,{children:e})}function bc(){const[e,n]=c.useState(!0);return t.jsx(gc,{children:t.jsx(cc,{children:t.jsxs("div",{className:`grid h-full flex-1 min-h-0 grid-rows-[auto_1fr] ${e?"grid-cols-[minmax(150px,min-content)_1fr]":"grid-cols-[0px_1fr]"} md:grid-cols-[minmax(150px,min-content)_1fr] transition-[grid-template-columns] duration-200`,children:[t.jsxs("div",{className:"col-span-full sticky top-0 z-50 bg-background border-b border-border flex items-center",children:[t.jsx(W,{variant:"ghost",size:"icon",className:"md:hidden ml-1 shrink-0",onClick:()=>n(!e),"aria-label":"Toggle sidebar",title:"Toggle sidebar",children:t.jsx(N.PanelLeft,{className:"size-5"})}),t.jsx("div",{className:"flex-1 min-w-0",children:t.jsx(cn,{section:"Header",children:t.jsxs(fn,{children:[t.jsx(je,{path:"/:table/*",element:t.jsx(Bn,{})}),t.jsx(je,{path:"/:table",element:t.jsx(Bn,{})}),t.jsx(je,{path:"/",element:t.jsx(Bn,{})})]})})})]}),t.jsx("nav",{"aria-label":"Tables",className:`border-r border-border overflow-hidden min-h-0 ${e?"":"hidden"} md:block`,children:t.jsx(cn,{section:"Table List",children:t.jsx(Ka,{})})}),t.jsxs("main",{className:"flex flex-col overflow-hidden min-h-0 px-1 py-0.5",children:[t.jsx(cn,{section:"Data Panel",children:t.jsxs(fn,{children:[t.jsx(je,{path:"/:table/from/:filterTable/:id/edit/:editid",element:t.jsx(dt,{})}),t.jsx(je,{path:"/:table/from/:filterTable/:id",element:t.jsx(dt,{})}),t.jsx(je,{path:"/:table/:id/edit/:editid",element:t.jsx(dt,{})}),t.jsx(je,{path:"/:table/:id",element:t.jsx(dt,{})}),t.jsx(je,{path:"/:table/edit/:editid",element:t.jsx(dt,{})}),t.jsx(je,{path:"/:table/edit",element:t.jsx(dt,{})}),t.jsx(je,{path:"/:table",element:t.jsx(dt,{})}),t.jsx(je,{path:"/",element:t.jsx(xc,{})})]})}),t.jsx(cn,{section:"Data Edit",children:t.jsxs(fn,{children:[t.jsx(je,{path:"/:table/from/:filterTable/:id/edit/:editid",element:t.jsx(on,{})}),t.jsx(je,{path:"/:table/:id/edit/:editid",element:t.jsx(on,{})}),t.jsx(je,{path:"/:table/edit/:editid",element:t.jsx(on,{})}),t.jsx(je,{path:"/:table/edit",element:t.jsx(on,{})})]})})]})]})})})}function yc({onLocate:e}){const n=Zn();return c.useEffect(()=>{e?.(n)},[n,e]),t.jsx(bc,{})}function Ls({uri:e,fetcher:n,uiPath:r,onLocate:s,showStats:o=!1}){const i=c.useMemo(()=>n||(e?new rr(e):null),[e,n]),a=c.useMemo(()=>new me.QueryClient({defaultOptions:{queries:{staleTime:300*1e3,retry:1}}}),[]);return i?t.jsx(me.QueryClientProvider,{client:a,children:t.jsx(co,{value:i,children:t.jsx(Ia,{config:{showStats:o},children:t.jsx(Qi,{children:t.jsx(to,{path:r||"/",children:t.jsx(po,{children:t.jsx(yc,{onLocate:s})})})})})})}):t.jsx("section",{children:"CONFIG MISSING..."})}be.Editor=Ls,be.HttpGraphQLFetcher=rr,be.default=Ls,be.useTableMutation=sn,Object.defineProperties(be,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
120
+ }`},[e,t,a]),{isLoading:m,error:d,data:f}=de.useQuery({queryKey:["editRecord",e.name,r],queryFn:()=>s.query(c,a.variables),enabled:!!e&&!o&&a.filterText!==""}),p=f?.value?.data?.at(0),x=!o&&f!==void 0&&p===void 0,h=u.useMemo(()=>p??{},[p]),y=u.useMemo(()=>{const N={};for(const{column:T,fkRole:k}of t){const $=Su(T,k);if(Yn(T))N[T.name]=Br(h[T.name],Vr(T));else if(Wr.some(b=>b===T.paramType)){const b=h[T.name];N[T.name]=T.isNullable&&b==null?null:!!b}else if(Ft(T)){const b=h[T.name];N[T.name]=b==null?"":JSON.stringify(b,null,2)}else if($){const b=h[T.name];N[T.name]=b??null}else N[T.name]=h[T.name]??""}return N},[h,t]);return{isLoading:m,error:d,value:h,defaultValues:y,pkResolveFailed:l,recordNotFound:x}}function Eu({table:e,schema:t,editId:r,onClose:s}){const o=r===void 0||r==="",[i,a,l]=Tu(t,e),c=i.labelColumn,m=i.label,d=wn(i,a,l,r),{isLoading:f,error:p,value:x,defaultValues:h,pkResolveFailed:y,recordNotFound:N}=$u(i,a,r),T=Tn.useForm({defaultValues:h,onSubmit:async({value:S})=>{const L=ju(S,x,a.map(({column:D})=>D));await(o?d.insert:d.update)(L),s()}}),k=Tn.useStore(T.store,S=>S.isDirty),[$,b]=u.useState(!1),v=()=>{k?b(!0):s()};if(f&&!o)return n.jsx(jt,{open:!0,onOpenChange:S=>{S||s()},children:n.jsxs(wt,{showCloseButton:!1,className:"sm:max-w-2xl",children:[n.jsx(Ct,{className:"sr-only",children:"Loading record"}),n.jsx(Kt,{className:"sr-only",children:"Loading record for editing"}),n.jsxs("div",{className:"flex items-center justify-center gap-2 py-10 text-sm text-muted-foreground",children:[n.jsx(C.LoaderCircle,{className:"size-4 animate-spin"}),"Loading…"]})]})});if(p)return n.jsxs("div",{children:["Error: ",p.message]});if(y||N)return n.jsx(jt,{open:!0,onOpenChange:S=>{S||s()},children:n.jsxs(wt,{showCloseButton:!1,className:"sm:max-w-md",children:[n.jsx(Ct,{className:"text-sm font-semibold",children:"Cannot edit record"}),n.jsxs(Kt,{className:"text-sm text-muted-foreground",children:[y?`This record can't be opened for editing: its key (${r||"empty"}) is missing or malformed for the ${m} table.`:`No ${m} record matches the key ${r}. It may have been deleted or is no longer visible to you.`," ","Return to the grid and try again."]}),n.jsx("div",{className:"flex justify-end",children:n.jsx(Q,{type:"button",size:"sm",onClick:s,children:"Close"})})]})});const w=x?.[c]??r,F=a.filter(({column:S})=>Wr.some(L=>L===S.paramType)),j=a.filter(({column:S})=>Uo(S)),V=a.filter(({column:S})=>!Wr.some(L=>L===S.paramType)&&!Uo(S));return n.jsxs(jt,{open:!0,onOpenChange:S=>{S||v()},children:[n.jsxs(wt,{showCloseButton:!1,className:"sm:max-w-2xl max-h-[90vh] flex flex-col gap-0 p-0 overflow-hidden",children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-border bg-muted/30 shrink-0",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx(Ct,{className:"text-sm font-semibold truncate",children:o?`New ${m}`:`${m} : ${w}`}),n.jsxs(Kt,{className:"sr-only",children:[o?"Create":"Edit"," ",m," record"]})]}),n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:v,"aria-label":"Close",className:"shrink-0 -mr-1",children:n.jsx(C.X,{className:"size-4"})})]}),d.error&&n.jsxs("div",{className:"flex items-center gap-2 px-5 py-2 bg-destructive/10 border-b border-destructive/20 text-destructive text-sm shrink-0",children:[n.jsx(C.AlertCircle,{className:"size-3.5 shrink-0"}),n.jsx("span",{className:"truncate",children:d.error.message})]}),n.jsxs("form",{onSubmit:S=>{S.preventDefault(),S.stopPropagation(),T.handleSubmit().catch(()=>{})},className:"flex flex-col flex-1 min-h-0",children:[n.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[V.length>0&&n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-3",children:V.map(({column:S,join:L,fkRole:A})=>n.jsx(Pu,{column:S,join:L,fkRole:A,form:T,schema:t},S.name))}),F.length>0&&n.jsx("div",{className:V.length>0?"mt-4 pt-4 border-t border-border":"",children:n.jsx("div",{className:"flex flex-wrap gap-x-6 gap-y-2",children:F.map(({column:S})=>n.jsx(Du,{column:S,form:T},S.name))})}),j.length>0&&n.jsx("div",{className:V.length>0||F.length>0?"mt-4 pt-4 border-t border-border":"",children:n.jsx("div",{className:"grid gap-3",children:j.map(({column:S})=>n.jsx(Mu,{column:S,form:T},S.name))})})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-border bg-muted/30 shrink-0",children:[n.jsx(Q,{type:"button",variant:"outline",size:"sm",onClick:v,children:"Cancel"}),n.jsxs(Q,{type:"submit",size:"sm",disabled:d.isPending,children:[d.isPending?n.jsx(C.LoaderCircle,{className:"size-3.5 animate-spin"}):n.jsx(C.Save,{className:"size-3.5"}),o?"Create":"Save"]})]})]})]}),n.jsx(Kr,{open:$,onOpenChange:b,title:"Discard unsaved changes?",description:n.jsx("p",{children:"You have unsaved changes. Closing now will discard them."}),confirmLabel:"Discard",cancelLabel:"Keep editing",variant:"destructive",onConfirm:()=>{b(!1),s()}})]})}function Xn(){const{table:e,editId:t}=ir(),r=_n();if(!e)return n.jsx("div",{children:"Table missing"});const s=t?"../..":"..";return n.jsx(Ro,{table:e,editId:t??"",onClose:()=>r(s)})}function Ro({table:e,editId:t,onClose:r}){const s=Je();return e?s.loading?n.jsx("div",{children:"Loading..."}):s.error?n.jsxs("div",{children:["Error: ",s.error.message]}):s.findTable(e)?n.jsx(Eu,{table:e,schema:s,editId:t,onClose:r}):n.jsxs("div",{className:"p-4 text-sm text-destructive",children:["Table not found: ",e]}):n.jsx("div",{children:"Table missing"})}function Fu({current:e,max:t}){const r=t-e,s=r<=10&&r>0,o=r<=0;return n.jsx("div",{className:"text-xs text-right mt-0.5","aria-live":"polite",children:n.jsxs("span",{className:o?"text-destructive font-medium":s?"text-amber-500":"text-muted-foreground",children:[e,"/",t]})})}function _u({min:e,max:t,step:r}){if(e===void 0&&t===void 0)return null;let s="";return e!=null&&t!==void 0&&t!==null?s=`Range: ${e} to ${t}`:e!=null?s=`Min: ${e}`:t!=null&&(s=`Max: ${t}`),r!=null&&r!==1&&(s+=` (step: ${r})`),n.jsx("div",{className:"text-xs text-muted-foreground mt-0.5","aria-live":"polite",children:s})}function Pu({column:e,join:t,fkRole:r,form:s,schema:o}){const i=e.name,a=!e.isNullable;if(r==="member-composite")return null;const l=Yn(e),c=Vt(e.paramType),m=e.maxLength&&e.maxLength>0&&!l&&!c;if(e.enumValues&&e.enumValues.length>0)return n.jsx(zu,{column:e,form:s,isRequired:a});if(t&&o)return r==="anchor-composite"?n.jsx(Lu,{column:e,join:t,form:s,schema:o,isRequired:a}):n.jsx(Iu,{column:e,join:t,form:s,schema:o,isRequired:a});const d=Bt(e.paramType),f=e.inputType||(l?Vr(e)?"datetime-local":"date":d?"text":c?"number":"text"),p=d?qt(e.paramType)?"numeric":"decimal":void 0,x=`${i}-error`;return n.jsx(s.Field,{name:i,validators:Nn(e,a),children:h=>{const{ariaProps:y}=Rn(h,x);return n.jsxs("div",{className:"grid gap-1",children:[n.jsxs(Wt,{htmlFor:i,className:"text-xs text-muted-foreground",children:[e.label,a&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),n.jsx(Qe,{id:i,type:f,inputMode:p,value:h.state.value??"",onChange:N=>h.handleChange(N.target.value),onBlur:h.handleBlur,required:a,maxLength:e.maxLength,minLength:e.minLength,min:e.min,max:e.max,step:e.step,pattern:e.pattern,title:e.patternMessage,...y,className:"h-8 text-sm"}),m&&n.jsx(Fu,{current:String(h.state.value??"").length,max:e.maxLength}),c&&(e.min!==void 0||e.max!==void 0)&&n.jsx(_u,{min:e.min,max:e.max,step:e.step}),n.jsx(Zn,{errors:h.state.meta.errors,id:x})]})}})}function zu({column:e,form:t,isRequired:r}){const s=e.name,o=e.enumValues||[],i=e.enumLabels&&e.enumLabels.length===o.length?e.enumLabels:o,a=`${s}-error`;return n.jsx(t.Field,{name:s,validators:Nn(e,r),children:l=>{const{ariaProps:c}=Rn(l,a);return n.jsxs("div",{className:"grid gap-1",children:[n.jsxs(Wt,{htmlFor:s,className:"text-xs text-muted-foreground",children:[e.label,r&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),n.jsxs(Ze,{value:Ho(l.state.value,!r),onValueChange:Jr(m=>l.handleChange(m===Dt?null:m)),children:[n.jsx(tt,{id:s,className:"w-full h-8 text-sm",...c,children:n.jsx(et,{placeholder:`Select ${e.label}`})}),n.jsxs(nt,{children:[!r&&n.jsx(we,{value:Dt,className:"text-muted-foreground",children:"(none)"}),o.map((m,d)=>n.jsx(we,{value:m,children:i[d]||m},m))]})]}),n.jsx(Zn,{errors:l.state.meta.errors,id:a})]})}})}const Qr="true",Xo="false";function Du({column:e,form:t}){const r=e.name;return e.isNullable?n.jsx(t.Field,{name:r,children:s=>{const o=s.state.value,i=o==null?Dt:o?Qr:Xo;return n.jsxs("div",{className:"grid gap-1 min-w-[10rem]",children:[n.jsx(Wt,{htmlFor:r,className:"text-xs text-muted-foreground",children:e.label}),n.jsxs(Ze,{value:i,onValueChange:Jr(a=>s.handleChange(a===Dt?null:a===Qr)),children:[n.jsx(tt,{id:r,className:"w-full h-8 text-sm",children:n.jsx(et,{})}),n.jsxs(nt,{children:[n.jsx(we,{value:Dt,className:"text-muted-foreground",children:"(unset)"}),n.jsx(we,{value:Qr,children:"Yes"}),n.jsx(we,{value:Xo,children:"No"})]})]})]})}}):n.jsx(t.Field,{name:r,children:s=>n.jsxs("label",{htmlFor:r,className:"flex items-center gap-2 cursor-pointer select-none",children:[n.jsx(Cn,{id:r,checked:!!s.state.value,onCheckedChange:o=>s.handleChange(!!o),onBlur:s.handleBlur}),n.jsx("span",{className:"text-sm",children:e.label})]})})}function Mu({column:e,form:t}){const r=e.name,s=!e.isNullable,o=`${r}-error`;return n.jsx(t.Field,{name:r,validators:Nn(e,s),children:i=>{const{hasError:a}=Rn(i,o);return n.jsxs("div",{className:"grid gap-1",children:[n.jsxs(Wt,{htmlFor:r,className:"text-xs text-muted-foreground",children:[e.label,s&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),n.jsx(Nu,{name:r,label:e.label,value:String(i.state.value??""),dbType:e.dbType,onChange:l=>i.handleChange(l),onBlur:i.handleBlur,required:s,invalid:a}),n.jsx(Zn,{errors:i.state.meta.errors,id:o})]})}})}function Zo(){const[e,t]=u.useState(""),[r,s]=u.useState(""),[o,i]=u.useState(!1);return u.useEffect(()=>{const l=setTimeout(()=>s(e),300);return()=>clearTimeout(l)},[e]),{search:e,setSearch:t,debounced:r,open:o,onOpenChange:l=>{i(l),l||(t(""),s(""))}}}function ea({field:e,column:t,isRequired:r,errorId:s,value:o,onValueChange:i,search:a,setSearch:l,onOpenChange:c,loadError:m,composite:d,children:f}){const{ariaProps:p}=Rn(e,s);return n.jsxs("div",{className:d?"grid gap-1 sm:col-span-2":"grid gap-1",children:[n.jsxs(Wt,{htmlFor:t.name,className:"text-xs text-muted-foreground",children:[t.label,r&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"}),d&&n.jsxs("span",{className:"ml-2 px-1 rounded bg-primary/10 text-[10px] font-medium text-primary",children:["composite FK (",d.cols," cols)"]})]}),n.jsxs(Ze,{value:o,onValueChange:Jr(i),onOpenChange:c,children:[n.jsx(tt,{id:t.name,className:"w-full h-8 text-sm",...p,children:n.jsx(et,{placeholder:`Select ${t.label}`})}),n.jsxs(nt,{children:[n.jsx("div",{className:"px-1 pb-1 sticky top-0 bg-popover z-10",children:n.jsx(Qe,{value:a,onChange:x=>l(x.target.value),onKeyDown:x=>{(x.key.length===1||x.key==="Backspace"||x.key==="Delete")&&x.stopPropagation()},placeholder:"Search…",className:"h-7 text-xs"})}),f]})]}),m!=null&&n.jsxs("p",{className:"text-xs text-destructive",role:"alert",children:["Failed to load ",t.label," options: ",String(m?.message??m)]}),n.jsx(Zn,{errors:e.state.meta.errors,id:s})]})}function Iu({column:e,join:t,form:r,schema:s,isRequired:o}){const i=e.name,a=t.destinationColumnNames[0],{search:l,setSearch:c,debounced:m,open:d,onOpenChange:f}=Zo(),p=hu(s,t.destinationTable,a,m,d),x=Tn.useStore(r.store,b=>b.values?.[i]),h=x==null||x===""||p.data.some(b=>String(b.key)===String(x)),y=gu(s,t.destinationTable,a,!p.loading&&!h?x:null),N=`${i}-error`,T=m.trim(),k=p.serverSearch||!T?p.data:p.data.filter(b=>Wo(b,"key",T)),$=x==null||x===""?null:p.data.find(b=>String(b.key)===String(x))??y.value??{key:String(x),label:String(x)};return n.jsx(r.Field,{name:i,validators:Nn(e,o),children:b=>n.jsxs(ea,{field:b,column:e,isRequired:o,errorId:N,value:Ho(b.state.value,!o),onValueChange:v=>b.handleChange(v===Dt?null:v),search:l,setSearch:c,onOpenChange:f,loadError:p.error,children:[!o&&n.jsx(we,{value:Dt,className:"text-muted-foreground",children:"(none)"}),$&&!k.some(v=>String(v.key)===String($.key))&&n.jsx(we,{value:String($.key),children:$.label}),k.map(v=>n.jsx(we,{value:String(v.key),children:v.label},v.key)),k.length===0&&n.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No matches."})]})})}function Lu({column:e,join:t,form:r,schema:s,isRequired:o}){const i=t.sourceColumnNames??[],a=t.destinationColumnNames??[],{search:l,setSearch:c,debounced:m,open:d,onOpenChange:f}=Zo(),p=Tn.useStore(r.store,$=>{const b={};for(let v=0;v<i.length;v++)b[a[v]]=$.values?.[i[v]];return b}),x=yu(s,t.destinationTable,a,{search:m,enabled:d,currentValues:p}),h=u.useMemo(()=>{const $=[];for(let b=0;b<i.length;b++){const v=p[a[b]];if(v==null||v==="")return"";$.push(v)}return $t($)},[p,i,a]),y=m.trim(),N=x.serverSearch||!y?x.data:x.data.filter($=>$.label.toLowerCase().includes(y.toLowerCase())),T=$=>{const b=x.data.find(v=>v.route===$);if(b)for(let v=0;v<i.length;v++){const w=a[v],F=i[v];r.setFieldValue(F,b.values[w])}},k=`${e.name}-error`;return n.jsx(r.Field,{name:e.name,validators:Nn(e,o),children:$=>n.jsxs(ea,{field:$,column:e,isRequired:o,errorId:k,value:h,onValueChange:T,search:l,setSearch:c,onOpenChange:f,loadError:x.error,composite:{cols:i.length},children:[N.map(b=>n.jsx(we,{value:b.route,children:b.label},b.route)),N.length===0&&n.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No matches."})]})})}function Zn({errors:e,id:t}){return e.length===0?null:n.jsx("div",{id:t,role:"alert",children:e.map((r,s)=>n.jsx("p",{className:"text-xs text-destructive",children:String(r)},s))})}const ta=40,na=32;function Ou({className:e,...t}){return n.jsx("div",{"data-slot":"table-container",className:"relative w-full h-full overflow-x-auto",children:n.jsx("table",{"data-slot":"table",className:Y("min-w-full caption-bottom text-sm border-separate border-spacing-0",e),...t})})}function Au({className:e,...t}){return n.jsx("thead",{"data-slot":"table-header",className:Y("[&_tr]:border-b",e),...t})}function qu({className:e,...t}){return n.jsx("tbody",{"data-slot":"table-body",className:Y("[&_tr:last-child]:border-0 [&_tr:nth-child(even)]:bg-muted/25",e),...t})}function er({className:e,style:t,...r}){return n.jsx("tr",{"data-slot":"table-row",className:Y("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),style:{height:ta,...t},...r})}function Vu({className:e,style:t,...r}){return n.jsx("th",{"data-slot":"table-head",className:Y("px-2 text-left align-middle font-medium whitespace-nowrap text-muted-foreground text-xs border-r border-border last:border-r-0 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),style:{height:na,...t},...r})}function Hr({className:e,...t}){return n.jsx("td",{"data-slot":"table-cell",className:Y("px-2 py-1 align-middle whitespace-nowrap text-[13px] overflow-hidden text-ellipsis border-r border-border last:border-r-0 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function Bu({anchorEl:e,onEdit:t,onDelete:r,onMouseEnter:s,onDismiss:o}){const i=u.useRef(null);return u.useEffect(()=>{const a=i.current;return a?((()=>{const c=e.getBoundingClientRect(),m=a.offsetHeight,d=a.offsetWidth;a.style.top=`${c.top+(c.height-m)/2}px`;const f=Math.min(c.right-d-8,window.innerWidth-d-8);a.style.left=`${Math.max(8,f)}px`})(),a.showPopover(),()=>{try{a.hidePopover()}catch{}}):void 0},[e]),u.useEffect(()=>{const a=l=>{const c=i.current;c&&!c.contains(l.target)&&o()};return document.addEventListener("pointerdown",a),()=>document.removeEventListener("pointerdown",a)},[o]),n.jsxs("div",{ref:i,popover:"manual",className:"flex items-center gap-0.5 rounded-md border border-border bg-popover px-1 py-0.5 shadow-md m-0",style:{position:"fixed"},onClick:a=>a.stopPropagation(),onMouseEnter:s,onMouseLeave:o,onFocusCapture:s,onBlur:a=>{a.currentTarget.contains(a.relatedTarget)||o()},children:[t&&n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:t,"aria-label":"Edit row",title:"Edit",className:"size-6",children:n.jsx(C.Pencil,{className:"size-3.5"})}),r&&n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:r,"aria-label":"Delete row",title:"Delete",className:"size-6 text-destructive hover:text-destructive",children:n.jsx(C.Trash2,{className:"size-3.5"})})]})}function Gu({exportRows:e,total:t,tableName:r,rowCap:s=Pr}){const{toast:o}=vt(),[i,a]=u.useState(!1),[l,c]=u.useState(0),m=u.useRef(null);u.useEffect(()=>()=>m.current?.abort(),[]);const d=u.useCallback(async p=>{if(i||t>s&&typeof window<"u"&&!window.confirm(`This export has ${t.toLocaleString()} rows, over the ${s.toLocaleString()} row limit. Only the first ${s.toLocaleString()} rows will be exported. Continue?`))return;const x=new AbortController;m.current=x,a(!0),c(0);try{const h=await e({format:p,signal:x.signal,rowCap:s,onProgress:y=>c(y)});if(!h)return;Mr(h.content,Dr(r,p),zr(p)),h.truncated&&o(`Export truncated at ${h.rowCount.toLocaleString()} rows.`,"error")}catch(h){if(x.signal.aborted)return;o(`Export failed: ${h instanceof Error?h.message:String(h)}`,"error")}finally{a(!1),m.current=null}},[i,t,s,e,r,o]),f=u.useCallback(()=>m.current?.abort(),[]);return i?n.jsxs(Q,{variant:"outline",size:"sm",onClick:f,title:"Cancel export",children:[n.jsx(C.X,{className:"size-3.5"}),"Cancel (",l.toLocaleString(),")"]}):n.jsxs(Ln,{children:[n.jsx(On,{asChild:!0,children:n.jsxs(Q,{variant:"outline",size:"sm",children:[n.jsx(C.Download,{className:"size-3.5"}),"Export",n.jsx(C.ChevronDown,{className:"size-3.5"})]})}),n.jsxs(An,{align:"end",children:[n.jsx(bt,{onClick:()=>{d("csv")},children:"CSV"}),n.jsx(bt,{onClick:()=>{d("json")},children:"JSON"})]})]})}const Ur=60,ra=450,Ku=150,Yr="bifrost-col-sizes:";function sa(e){try{const t=localStorage.getItem(Yr+e);return t?Wu(JSON.parse(t)):{}}catch{return{}}}function Wu(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={};for(const[r,s]of Object.entries(e))typeof s!="number"||!Number.isFinite(s)||(t[r]=Math.min(Math.max(s,Ur),ra));return t}function Rr(e,t){try{Object.keys(t).length===0?localStorage.removeItem(Yr+e):localStorage.setItem(Yr+e,JSON.stringify(t))}catch{}}function Ju(e){const[t,r]=u.useState(()=>e?sa(e):{}),s=u.useRef(null),o=u.useRef(!0);u.useEffect(()=>{const a=s.current;if(a&&a.tableName!==e&&(s.current=null,Rr(a.tableName,a.sizing)),!e)return;if(o.current){o.current=!1;return}s.current={tableName:e,sizing:t};const l=setTimeout(()=>{s.current=null,Rr(e,t)},300);return()=>clearTimeout(l)},[e,t]),u.useEffect(()=>()=>{const a=s.current;a&&Rr(a.tableName,a.sizing)},[]);const i=u.useRef(e);if(e&&e!==i.current){i.current=e,o.current=!0;const a=sa(e);r(a)}return{columnSizing:t,setColumnSizing:r}}const Qu="bifrost-col-visibility:";function Xr(e){return Qu+e}function Zr(e){try{const t=localStorage.getItem(Xr(e));return t?Hu(JSON.parse(t)):null}catch{return null}}function Hu(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;const t={};for(const[r,s]of Object.entries(e))typeof s=="boolean"&&(t[r]=s);return t}function Uu(e,t){try{localStorage.setItem(Xr(e),JSON.stringify(t))}catch{}}function Yu(e){try{localStorage.removeItem(Xr(e))}catch{}}function Ru(e,t){if(!t||t.length===0)return{};const r=new Set(t),s={};for(const o of e)s[o]=r.has(o);return s}function Xu(e,t){const[r,s]=u.useState(()=>(e?Zr(e):null)??t),o=u.useRef(r),i=u.useCallback(d=>{o.current=d,s(d)},[]),a=u.useCallback(d=>{const f=typeof d=="function"?d(o.current):d;i(f),e&&Uu(e,f)},[i,e]),l=u.useCallback(()=>{e&&Yu(e),i(t)},[i,t,e]),c=u.useRef(e);e&&e!==c.current&&(c.current=e,i(Zr(e)??t));const m=u.useRef(t);return e&&m.current!==t&&(m.current=t,Zr(e)===null&&i(t)),{columnVisibility:r,setColumnVisibility:a,resetColumnVisibility:l}}const Zu=500;function ed(){const[e,t]=u.useState(null),r=u.useRef(null),s=u.useCallback((p,x)=>{r.current&&(clearTimeout(r.current),r.current=null),t({rowId:p,el:x})},[]),o=u.useCallback(()=>{r.current&&clearTimeout(r.current),r.current=setTimeout(()=>t(null),150)},[]),i=u.useCallback(()=>{r.current&&(clearTimeout(r.current),r.current=null)},[]),a=u.useRef(null),l=u.useRef(!1),c=u.useRef(!1),m=u.useCallback(()=>{a.current&&(clearTimeout(a.current),a.current=null)},[]),d=u.useCallback((p,x,h)=>{h.pointerType==="touch"&&(l.current=!1,m(),a.current=setTimeout(()=>{l.current||(c.current=!0,s(p,x))},Zu))},[m,s]),f=u.useCallback(()=>{l.current=!0,m()},[m]);return{hoveredRow:e,hoverRow:s,scheduleDismiss:o,cancelDismiss:i,suppressClick:c,startPress:d,onPressMove:f,cancelPress:m}}const es=-1;function td(e){return Math.max(5,Math.floor((e-na)/ta))}function nd(e,t){const[r,s]=u.useState(!0),o=u.useRef(0),i=u.useCallback(()=>{const a=e.current;return a?td(a.clientHeight):10},[e]);return u.useEffect(()=>{if(!r)return;const a=e.current;if(!a)return;const l=()=>{const f=i();f!==o.current&&(o.current=f,t(f))},c=requestAnimationFrame(l);let m=null;const d=new ResizeObserver(()=>{m&&clearTimeout(m),m=setTimeout(()=>requestAnimationFrame(l),200)});return d.observe(a),()=>{cancelAnimationFrame(c),m&&clearTimeout(m),d.disconnect()}},[r,i,t,e]),{fitMode:r,setFitMode:s,computeFitSize:i}}function rd(e){return e.id??("accessorKey"in e?String(e.accessorKey):void 0)}function oa(e,t){return t.map(r=>e.find(s=>rd(s)===r)).filter(r=>r!==void 0)}function sd(e,{leading:t,trailing:r}){const s=t?oa(e,t):[],o=r?oa(e,r):[];if(s.length===0&&o.length===0)return e;const i=new Set([...s,...o]),a=e.filter(l=>!i.has(l));return[...s,...a,...o]}function od({label:e,rows:t,loading:r,error:s,sumLabel:o,pageSize:i,sort:a,onSortChange:l,memberRequest:c}){const m=$e(),[d,f]=u.useState(0),[p,x]=u.useState(null),h=p===null?null:c(p.value),y=de.useQuery({queryKey:["groupMembers",h?.query,h?.variables],queryFn:({signal:v})=>m.query(h.query,h.variables,{signal:v}),enabled:h!==null}),N=t.map(v=>`${String(v.value)}:${v.count}:${String(v.sum)}`).join("|");if(u.useEffect(()=>{f(0),x(null)},[e,N,i]),s)return n.jsxs("p",{role:"alert",className:"px-2 py-1 text-sm text-destructive",children:["Grouping failed: ",s.message]});if(r)return n.jsx("p",{className:"px-2 py-1 text-sm text-muted-foreground",children:"Loading grouped results…"});const T=Math.max(1,i),k=Math.max(1,Math.ceil(t.length/T)),$=t.slice(Math.min(d,k-1)*T,(Math.min(d,k-1)+1)*T),b=h?y.data?.[h.responseKey]:void 0;return n.jsxs("div",{className:"border-b px-2 py-2","aria-label":`Grouped by ${e}`,children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2 text-sm font-medium",children:[n.jsxs("span",{children:["Grouped by ",e]}),n.jsxs("label",{className:"text-xs font-normal text-muted-foreground",children:["Group order",n.jsxs("select",{"aria-label":"Group order",className:"ml-1 rounded border bg-background px-1 py-0.5 text-foreground",value:`${a.field}:${a.desc?"desc":"asc"}`,onChange:v=>{const[w,F]=v.target.value.split(":");l({field:w==="count"?"count":"key",desc:F==="desc"})},children:[n.jsxs("option",{value:"key:asc",children:[e," ascending"]}),n.jsxs("option",{value:"key:desc",children:[e," descending"]}),n.jsx("option",{value:"count:desc",children:"Count high to low"}),n.jsx("option",{value:"count:asc",children:"Count low to high"})]})]}),n.jsxs("span",{className:"text-muted-foreground",children:[t.length," groups"]})]}),n.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto_auto] gap-x-4 gap-y-1 text-sm",children:[$.map((v,w)=>n.jsxs("div",{className:"contents",children:[n.jsx("button",{type:"button",className:"text-left underline-offset-2 hover:underline","aria-expanded":p===v,onClick:()=>x(p===v?null:v),children:v.value===null||v.value===void 0?"(null)":String(v.value)}),n.jsx("span",{className:"tabular-nums text-muted-foreground",children:v.count}),n.jsx("span",{className:"tabular-nums text-muted-foreground",children:o?String(v.sum??"—"):""})]},`${String(v.value)}-${w}`)),t.length===0&&n.jsx("span",{className:"text-muted-foreground",children:"No grouped results."})]}),t.length>T&&n.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs",children:[n.jsx("button",{type:"button",disabled:d===0,onClick:()=>f(v=>v-1),children:"Previous groups"}),n.jsxs("span",{children:["Group page ",Math.min(d,k-1)+1," of ",k]}),n.jsx("button",{type:"button",disabled:d>=k-1,onClick:()=>f(v=>v+1),children:"Next groups"})]}),h&&n.jsx("div",{className:"mt-2 rounded bg-muted/40 p-2 text-xs","aria-live":"polite",children:y.isLoading?"Loading group members…":y.error?"Group member query failed.":n.jsxs(n.Fragment,{children:[n.jsxs("div",{children:[b?.total??0," matching members"]}),n.jsx("pre",{className:"max-h-32 overflow-auto",children:JSON.stringify(b?.data??[],null,2)})]})})]})}const ad=[10,20,30,50,100];function id({columns:e,data:t,tableName:r,pageCount:s,pageIndex:o,pageSize:i,sorting:a,columnFilters:l,loading:c,fetching:m=!1,selectable:d=!1,primaryKeys:f=[],selectedRowId:p,onRowSelect:x,onSortingChange:h,onColumnFiltersChange:y,onPageIndexChange:N,onPageSizeChange:T,onEditRow:k,onDeleteRow:$,onDeleteSelected:b,onBulkEditSelected:v,inlineEditableColumns:w,inlineBooleanColumns:F,pendingEdits:j,onCellCommit:V,onSaveAllEdits:S,onDiscardAllEdits:L,savingEdits:A=!1,stackingEnabled:D,onToggleStacking:B,exportRows:X,totalRows:E,onVisualize:P,groupableColumns:q,grouping:U,onGroupingChange:_,onGroupingSumChange:ce}){const{hoveredRow:he,hoverRow:Ue,scheduleDismiss:Pe,cancelDismiss:ie,suppressClick:se,startPress:ke,onPressMove:Ae,cancelPress:re}=ed(),{defaultColumns:Ee,trailingColumns:Ie}=cr(),[Le,Ge]=u.useState({}),[Oe,ye]=u.useState(null),{columnSizing:ze,setColumnSizing:O}=Ju(r),Z=u.useRef(null),{fitMode:ee,setFitMode:Ce,computeFitSize:xe}=nd(Z,T),qe=u.useCallback(z=>{const H=Z.current;if(!H)return;const I=H.querySelectorAll(`[data-col-id="${z}"]`);let ne=Ur;I.forEach(De=>{const ot=De.scrollWidth+4;ot>ne&&(ne=ot)});const Se=Math.min(ne,ra);O(De=>({...De,[z]:Se}))},[O]),W=u.useCallback(()=>{O({})},[O]);u.useEffect(()=>{Ge({})},[t,o]);const me=u.useMemo(()=>{const z=[];return d&&z.push({id:"_select",header:({table:H})=>n.jsx(Cn,{checked:H.getIsAllPageRowsSelected()||H.getIsSomePageRowsSelected()&&"indeterminate",onCheckedChange:I=>H.toggleAllPageRowsSelected(!!I),"aria-label":"Select all"}),cell:({row:H})=>n.jsx(Cn,{checked:H.getIsSelected(),onCheckedChange:I=>H.toggleSelected(!!I),onClick:I=>I.stopPropagation(),"aria-label":"Select row"}),enableSorting:!1,enableHiding:!1,enableResizing:!1,size:32}),z.push(...sd(e,{leading:r?Ee?.[r]:void 0,trailing:Ie})),z},[e,d,Ee,r,Ie]),Ne=u.useMemo(()=>Ru(me.filter(z=>z.enableHiding!==!1).map(z=>z.id).filter(z=>z!==void 0),r?Ee?.[r]:void 0),[me,Ee,r]),{columnVisibility:ve,setColumnVisibility:rt,resetColumnVisibility:Mt}=Xu(r,Ne),be=$n.useReactTable({data:t,columns:me,pageCount:s,getRowId:(z,H)=>He(z,{primaryKeys:f},H),state:{sorting:a,columnFilters:l,pagination:{pageIndex:o,pageSize:i},columnVisibility:ve,rowSelection:Le,columnSizing:ze},defaultColumn:{minSize:Ur,size:Ku},columnResizeMode:"onChange",enableColumnResizing:!0,onColumnSizingChange:O,meta:{onResetColumnWidths:W},onSortingChange:z=>{const H=typeof z=="function"?z(a):z;h(H)},onPaginationChange:z=>{const I=typeof z=="function"?z({pageIndex:o,pageSize:i}):z;I.pageSize!==i?(T(I.pageSize),N(0)):N(I.pageIndex)},onColumnFiltersChange:z=>{const H=typeof z=="function"?z(l):z;y(H)},onColumnVisibilityChange:rt,onRowSelectionChange:Ge,enableRowSelection:d,getCoreRowModel:$n.getCoreRowModel(),manualSorting:!0,manualFiltering:!0,manualPagination:!0}),ft=Object.keys(Le).length,Nt=be.getVisibleLeafColumns().map(z=>z.id).join("|"),Ye=u.useCallback(()=>{const z=[];for(const H of be.getSelectedRowModel().rows){const I=mt(H.original,{primaryKeys:f});I&&z.push(I)}return z},[be,f]),Xe=u.useCallback(()=>{if(!b)return;const z=Ye();z.length>0&&b(z)},[Ye,b]),Qt=u.useCallback(()=>{if(!v)return;const z=Ye();z.length>0&&v(z)},[Ye,v]),kn=u.useCallback((z,H)=>{ye({rowId:z,columnId:H})},[]),Sn=u.useCallback((z,H,I)=>{ye(null),V?.(z,H,I)},[V]),Ht=u.useCallback(()=>ye(null),[]),pt=u.useCallback(z=>{const H=be.getRow(z);return H?mt(H.original,{primaryKeys:f}):null},[be,f]),It=u.useCallback(z=>{if(!k)return;const H=pt(z);H&&k(H)},[k,pt]),st=u.useCallback(z=>{if(!$)return;const H=pt(z);H&&$(H)},[$,pt]),Ut=u.useCallback(()=>{he&&It(he.rowId)},[he,It]),Lt=u.useCallback(()=>{he&&st(he.rowId)},[he,st]);return n.jsxs("div",{className:"flex flex-col w-full min-h-0 flex-1",children:[n.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[l.length>0&&n.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>be.resetColumnFilters(),title:"Clear all column filters",children:[n.jsx(C.FilterX,{className:"size-3.5"}),"Clear filters"]}),ft>0&&(b||v)&&n.jsxs(n.Fragment,{children:[n.jsxs("span",{className:"text-xs text-muted-foreground",children:[ft," selected"]}),v&&n.jsxs(Q,{variant:"outline",size:"sm",onClick:Qt,title:"Apply one set of field changes to every selected row in one transaction",children:[n.jsx(C.Pencil,{className:"size-3.5"}),"Edit"]}),b&&n.jsxs(Q,{variant:"outline",size:"sm",onClick:Xe,className:"text-destructive hover:text-destructive",children:[n.jsx(C.Trash2,{className:"size-3.5"}),"Delete"]})]}),(j?.size??0)>0&&S&&n.jsxs(n.Fragment,{children:[n.jsxs("span",{className:"text-xs text-amber-600 dark:text-amber-400",children:[j.size," unsaved ",j.size===1?"row":"rows"]}),n.jsx(Q,{size:"sm",onClick:S,disabled:A,children:A?"Saving…":"Save all"}),L&&n.jsx(Q,{variant:"outline",size:"sm",onClick:L,disabled:A,children:"Discard"})]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[P&&n.jsx(Q,{variant:"outline",size:"sm",onClick:P,title:"Open a chart using this table and its active filters",children:"Visualize"}),X&&n.jsx(Gu,{exportRows:X,total:E??0,tableName:r??"export"}),B&&n.jsxs(Q,{variant:D?"secondary":"outline",size:"sm",role:"switch","aria-checked":!!D,onClick:()=>B(!D),title:D?"Stacked drill-down active — click for flat grid":"Flat grid active — click for stacked drill-down",children:[D?n.jsx(C.PanelRight,{className:"size-3.5"}):n.jsx(C.Rows3,{className:"size-3.5"}),D?"Stacked":"Grid"]}),_&&q&&n.jsxs(Ze,{value:U?.column.name??"__none",onValueChange:z=>_(z==="__none"?null:z),children:[n.jsx(tt,{size:"sm",className:"w-40","aria-label":"Group grid by column",children:n.jsx(et,{placeholder:"Group by"})}),n.jsxs(nt,{children:[n.jsx(we,{value:"__none",children:"No grouping"}),q.map(z=>n.jsx(we,{value:z.name,children:z.label},z.name))]})]}),U&&ce&&q&&n.jsxs(Ze,{value:U.sumColumn?.name??"__none",onValueChange:z=>ce(z==="__none"?null:z),children:[n.jsx(tt,{size:"sm",className:"w-40","aria-label":"Group sum column",children:n.jsx(et,{placeholder:"Sum column"})}),n.jsxs(nt,{children:[n.jsx(we,{value:"__none",children:"Count only"}),q.filter(z=>/^(byte|short|int|long|float|double|decimal|numeric|money|real)/i.test(z.paramType.replace(/[!\[\]]/g,""))).map(z=>n.jsxs(we,{value:z.name,children:["Sum ",z.label]},z.name))]})]}),n.jsxs(Ln,{children:[n.jsx(On,{asChild:!0,children:n.jsxs(Q,{variant:"outline",size:"sm",children:[n.jsx(C.Columns3,{className:"size-3.5"}),"Columns",n.jsx(C.ChevronDown,{className:"size-3.5"})]})}),n.jsxs(An,{align:"end",children:[be.getAllColumns().filter(z=>z.getCanHide()).map(z=>{const I=z.columnDef.meta?.column?.label??(typeof z.columnDef.header=="string"?z.columnDef.header:z.id);return n.jsx(Ki,{checked:z.getIsVisible(),onCheckedChange:ne=>z.toggleVisibility(!!ne),children:I},z.id)}),n.jsx(yt,{}),n.jsx(bt,{onClick:Mt,children:"Reset to default columns"})]})]})]})]}),U?n.jsxs(n.Fragment,{children:[n.jsx(od,{label:U.column.label,rows:U.rows,loading:U.loading,error:U.error,sumLabel:U.sumColumn?.label,pageSize:i,sort:U.sort,onSortChange:U.onSortChange,memberRequest:U.memberRequest}),n.jsx("p",{className:"border-b px-2 py-1 text-xs text-muted-foreground",role:"note",children:"Inline editing is disabled while grouping is active; expand a group to inspect its server-filtered members."})]}):n.jsxs(n.Fragment,{children:[m&&n.jsx("div",{className:"relative h-0 z-20",children:n.jsxs("div",{"data-testid":"fetch-indicator",role:"progressbar","aria-label":"Loading page",className:"absolute inset-x-0 top-0 h-0.5 overflow-hidden bg-primary/20",children:[n.jsx("div",{className:"h-full w-1/3 bg-primary",style:{animation:"edit-db-indeterminate 1.2s ease-in-out infinite"}}),n.jsx("style",{children:"@keyframes edit-db-indeterminate { 0% { transform: translateX(-100%); } 100% { transform: translateX(300%); } }"})]})}),n.jsxs("div",{ref:Z,className:"relative flex-1 overflow-auto min-h-0","aria-busy":m||c,children:[n.jsxs(Ou,{style:{tableLayout:"fixed",width:be.getTotalSize()},children:[n.jsx("colgroup",{children:be.getVisibleLeafColumns().map(z=>n.jsx("col",{style:{width:z.getSize()}},z.id))}),n.jsx(Au,{children:be.getHeaderGroups().map(z=>n.jsx(er,{children:z.headers.map(H=>n.jsxs(Vu,{"data-col-id":H.column.id,className:"relative","aria-sort":H.column.getIsSorted()==="asc"?"ascending":H.column.getIsSorted()==="desc"?"descending":H.column.getCanSort()?"none":void 0,children:[H.isPlaceholder?null:$n.flexRender(H.column.columnDef.header,H.getContext()),H.column.getCanResize()&&n.jsx("div",{onMouseDown:H.getResizeHandler(),onTouchStart:H.getResizeHandler(),onDoubleClick:()=>qe(H.column.id),className:`absolute top-0 right-0 w-1 h-full cursor-col-resize select-none touch-none opacity-0 hover:opacity-100 transition-opacity ${H.column.getIsResizing()?"bg-primary opacity-100":"bg-border hover:bg-muted-foreground"}`})]},H.id))},z.id))}),n.jsx(qu,{children:c?n.jsx(er,{children:n.jsx(Hr,{colSpan:me.length,className:"h-24 text-center",children:"Loading..."})}):be.getRowModel().rows.length===0?n.jsx(er,{children:n.jsx(Hr,{colSpan:me.length,className:"h-24 text-center",children:"No results."})}):be.getRowModel().rows.map(z=>n.jsx(cd,{row:z,isSelected:p!=null&&z.id===p,checked:z.getIsSelected(),visibleKey:Nt,pending:j?.get(z.id),editingColumnId:Oe?.rowId===z.id?Oe.columnId:null,inlineEditableColumns:V?w:void 0,inlineBooleanColumns:F,onStartEditCell:V?kn:void 0,onCommitCell:Sn,onCancelEditCell:Ht,onRowSelect:x,onEditRow:k?It:void 0,onDeleteRow:$?st:void 0,suppressClick:se,hoverRow:Ue,scheduleDismiss:Pe,startPress:ke,onPressMove:Ae,cancelPress:re},z.id))})]}),he&&(k||$)&&n.jsx(Bu,{anchorEl:he.el,onEdit:k?Ut:void 0,onDelete:$?Lt:void 0,onMouseEnter:ie,onDismiss:Pe})]}),n.jsxs("div",{className:"flex items-center justify-between px-2 py-1.5 border-t border-border mt-auto shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[n.jsx("span",{children:"Rows per page"}),n.jsxs(Ze,{value:String(ee?es:i),onValueChange:z=>{const H=Number(z);H===es?(Ce(!0),T(xe())):(Ce(!1),T(H))},children:[n.jsx(tt,{size:"sm",className:"w-auto h-7 text-xs","aria-label":"Rows per page",children:n.jsx(et,{children:ee?"Fit":i})}),n.jsxs(nt,{children:[n.jsx(we,{value:String(es),children:"Fit"}),ad.map(z=>n.jsx(we,{value:String(z),children:z},z))]})]})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsxs("span",{className:"text-xs text-muted-foreground mr-2",children:["Page ",o+1," of ",s||1]}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(0),disabled:o===0,"aria-label":"First page",title:"First page",children:n.jsx(C.ChevronsLeft,{className:"size-4"})}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(o-1),disabled:!be.getCanPreviousPage(),"aria-label":"Previous page",title:"Previous page",children:n.jsx(C.ChevronLeft,{className:"size-4"})}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(o+1),disabled:!be.getCanNextPage(),"aria-label":"Next page",title:"Next page",children:n.jsx(C.ChevronRight,{className:"size-4"})}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(s-1),disabled:o>=s-1,"aria-label":"Last page",title:"Last page",children:n.jsx(C.ChevronsRight,{className:"size-4"})})]})]})]})]})}function ld({row:e,isSelected:t,checked:r,pending:s,editingColumnId:o,inlineEditableColumns:i,inlineBooleanColumns:a,onStartEditCell:l,onCommitCell:c,onCancelEditCell:m,onRowSelect:d,onEditRow:f,onDeleteRow:p,suppressClick:x,hoverRow:h,scheduleDismiss:y,startPress:N,onPressMove:T,cancelPress:k}){const $=!!(d||f||p);return n.jsx(er,{"data-state":t||r?"selected":void 0,className:d?"cursor-pointer group/row focus-visible:outline-2 focus-visible:outline-primary":"group/row focus-visible:outline-2 focus-visible:outline-primary",tabIndex:$?0:void 0,onClick:d?()=>{if(x.current){x.current=!1;return}window.getSelection()?.toString()||d(t?null:e.id)}:void 0,onKeyDown:$?b=>{b.target===b.currentTarget&&((b.key==="Enter"||b.key===" ")&&d?(b.preventDefault(),d(t?null:e.id)):(b.key==="e"||b.key==="E")&&f?(b.preventDefault(),f(e.id)):(b.key==="Delete"||b.key==="Backspace")&&p&&(b.preventDefault(),p(e.id)))}:void 0,onFocus:b=>{b.target===b.currentTarget&&h(e.id,b.currentTarget)},onBlur:b=>{b.currentTarget.contains(b.relatedTarget)||y()},onPointerEnter:b=>{b.pointerType==="mouse"&&h(e.id,b.currentTarget)},onPointerLeave:b=>{b.pointerType==="mouse"&&y()},onPointerDown:b=>N(e.id,b.currentTarget,b),onPointerMove:T,onPointerUp:k,onPointerCancel:k,children:e.getVisibleCells().map(b=>{const v=b.column.id,w=!!l&&!!i?.has(v),F=o===v,j=!!s&&v in s;return n.jsx(Hr,{"data-col-id":v,"data-dirty":j?"true":void 0,className:j?"bg-amber-500/10 border-l-2 border-l-amber-500":void 0,title:w&&!F?"Double-click to edit":void 0,onDoubleClick:w&&!F?()=>l(e.id,v):void 0,children:F&&c&&m?n.jsx(ud,{initialValue:j?s[v]:e.original[v],boolean:!!a?.has(v),onCommit:V=>c(e.id,v,V),onCancel:m}):j?n.jsx("span",{title:"Unsaved change",children:s[v]==null?"":String(s[v])}):$n.flexRender(b.column.columnDef.cell,b.getContext())},b.id)})})}const cd=u.memo(ld);function ud({initialValue:e,boolean:t,onCommit:r,onCancel:s}){const[o,i]=u.useState(e==null?"":String(e));return t?n.jsx("input",{type:"checkbox",autoFocus:!0,defaultChecked:e===!0||e==="true",onChange:a=>r(a.target.checked),onKeyDown:a=>{a.key==="Escape"&&s()},onBlur:s,"aria-label":"Edit cell value"}):n.jsx("input",{autoFocus:!0,className:"w-full bg-background border border-primary rounded px-1 py-0.5 text-sm outline-none",value:o,onChange:a=>i(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),r(o)):a.key==="Escape"&&(a.preventDefault(),s()),a.stopPropagation()},onBlur:()=>r(o),onClick:a=>a.stopPropagation(),onDoubleClick:a=>a.stopPropagation(),"aria-label":"Edit cell value"})}function dd({table:e,pks:t,onClose:r}){const s=$e(),{toast:o}=vt(),i=qo(e),[a,l]=u.useState({}),[c,m]=u.useState(null),[d,f]=u.useState(!1),p=u.useMemo(()=>e.columns.filter(b=>!b.isReadOnly&&!b.isIdentity&&!b.isPrimaryKey&&!Et(b.dbType)),[e]),x=u.useMemo(()=>e.columns.some(b=>!b.isReadOnly&&!b.isIdentity&&!b.isPrimaryKey&&!b.isNullable&&Et(b.dbType)),[e]),h=u.useMemo(()=>{const b=new Map(e.columns.map(v=>[v.name,v]));return(e.primaryKeys??[]).map(v=>b.get(v)).filter(v=>!!v)},[e]),y=p.filter(b=>a[b.name]?.enabled),N=d||i.isPending,T=(b,v)=>l(w=>{const F=w[b]??{enabled:!1,value:"",setNull:!1};return{...w,[b]:{...F,...v}}}),k=b=>{const v=a[b.name];return v.setNull?null:b.paramType.startsWith("Boolean")?v.value==="true":v.value},$=async()=>{if(m(null),y.length===0){m("Choose at least one field to change.");return}f(!0);try{const b={};for(const L of y)b[L.name]=k(L);const v=p.filter(L=>!L.isNullable||b[L.name]!==void 0),w=[...new Set([...e.primaryKeys??[],...v.map(L=>L.name)])],F=mo(e,t,w);if(!F)throw new Error("The selected rows have no resolvable primary keys.");const V=(await s.query(F.query,F.variables))?.value?.data??[];if(V.length!==t.length)throw new Error(`Only ${V.length} of ${t.length} selected rows still exist. Refresh and retry.`);const S=lu(e,v,h,V,b);await i.saveDelta({updated:S}),r()}catch(b){const v=b.message??String(b);m(v),o(`Bulk edit failed: ${v}`,"error")}finally{f(!1)}};return n.jsx(jt,{open:!0,onOpenChange:b=>{!b&&!N&&r()},children:n.jsxs(wt,{showCloseButton:!1,className:"max-w-lg",children:[n.jsxs(tn,{children:[n.jsxs(Ct,{children:["Edit ",t.length," ",t.length===1?"row":"rows"]}),n.jsx(Kt,{children:"Chosen fields are applied to every selected row and saved in one transaction — if any row fails, nothing changes."})]}),x?n.jsx("p",{className:"text-sm text-destructive",children:"This table has a required binary column, which bulk edit cannot echo. Edit rows individually."}):n.jsx("div",{className:"flex flex-col gap-2 max-h-80 overflow-y-auto py-1",children:p.map(b=>{const v=a[b.name]??{enabled:!1,value:"",setNull:!1},w=b.paramType.startsWith("Boolean");return n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Cn,{id:`bulk-${b.name}`,checked:v.enabled,onCheckedChange:F=>T(b.name,{enabled:F===!0})}),n.jsx(Wt,{htmlFor:`bulk-${b.name}`,className:"w-40 truncate",title:b.label??b.name,children:b.label??b.name}),w?n.jsxs("select",{className:"h-8 rounded-md border bg-transparent px-2 text-sm flex-1",disabled:!v.enabled||v.setNull,value:v.value==="true"?"true":"false",onChange:F=>T(b.name,{value:F.target.value}),children:[n.jsx("option",{value:"true",children:"true"}),n.jsx("option",{value:"false",children:"false"})]}):n.jsx(Qe,{className:"h-8 flex-1",disabled:!v.enabled||v.setNull,value:v.value,onChange:F=>T(b.name,{value:F.target.value})}),b.isNullable&&n.jsxs("label",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[n.jsx(Cn,{checked:v.setNull,disabled:!v.enabled,onCheckedChange:F=>T(b.name,{setNull:F===!0})}),"null"]})]},b.name)})}),c&&n.jsx("p",{className:"text-sm text-destructive",children:c}),n.jsxs(Gr,{children:[n.jsx(Q,{variant:"outline",onClick:r,disabled:N,children:"Cancel"}),n.jsx(Q,{onClick:$,disabled:N||x,children:N?"Saving…":`Apply to ${t.length} ${t.length===1?"row":"rows"}`})]})]})})}function md({...e}){return n.jsx(R.Dialog.Root,{"data-slot":"sheet",...e})}function fd({...e}){return n.jsx(R.Dialog.Portal,{"data-slot":"sheet-portal",...e})}function pd({className:e,...t}){return n.jsx(R.Dialog.Overlay,{"data-slot":"sheet-overlay",className:Y("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function hd({className:e,children:t,side:r="right",...s}){return n.jsxs(fd,{children:[n.jsx(pd,{}),n.jsxs(R.Dialog.Content,{"data-slot":"sheet-content",className:Y("fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out duration-200 outline-none","data-[state=closed]:animate-out data-[state=open]:animate-in data-[state=closed]:duration-200 data-[state=open]:duration-200",r==="right"&&"inset-y-0 right-0 h-full w-3/4 max-w-md border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",r==="left"&&"inset-y-0 left-0 h-full w-3/4 max-w-md border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left",r==="top"&&"inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",r==="bottom"&&"inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",e),...s,children:[t,n.jsxs(R.Dialog.Close,{"data-slot":"sheet-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[n.jsx(C.XIcon,{}),n.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function gd({className:e,...t}){return n.jsx("div",{"data-slot":"sheet-header",className:Y("flex flex-col gap-2 p-4 pb-0",e),...t})}function xd({className:e,...t}){return n.jsx(R.Dialog.Title,{"data-slot":"sheet-title",className:Y("text-lg leading-none font-semibold",e),...t})}function bd({className:e,...t}){return n.jsx(R.Dialog.Description,{"data-slot":"sheet-description",className:Y("text-sm text-muted-foreground",e),...t})}const yd={json:C.Braces,xml:C.Code,"php-serialized":C.Database,binary:C.Binary,longtext:C.FileText,text:C.FileText},aa={json:"JSON",xml:"XML","php-serialized":"PHP Serialized",binary:"Binary",longtext:"Text",text:"Text"};function vd(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return t==="xml"?e.replace(/>\s*</g,`>
121
+ <`).trim():e}function jd({target:e,onClose:t,onNavigate:r,onSave:s,canNavigatePrev:o,canNavigateNext:i}){const{toast:a}=vt(),[l,c]=u.useState(!1),[m,d]=u.useState(!1),[f,p]=u.useState(""),[x,h]=u.useState(!1),[y,N]=u.useState(!1),T=u.useRef(null),k=e?.value??"",$=Bn(k,e?.dbType),b=yd[$],v=vd(k,$),w=$==="binary"&&k?so(k):null,F=u.useCallback(()=>{!e||!w||Gl(k,`${e.columnName}${w.extension}`,w.mime)},[e,w,k]);u.useEffect(()=>{d(!1),p(""),h(!1),N(!1)},[e?.rowKey,e?.columnName]),u.useEffect(()=>{if(!e)return;const _=ce=>{m||(ce.key==="ArrowUp"&&o?(ce.preventDefault(),r("prev")):ce.key==="ArrowDown"&&i&&(ce.preventDefault(),r("next")))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[e,m,o,i,r]);const j=u.useRef(null);u.useEffect(()=>()=>{j.current&&clearTimeout(j.current)},[]);const V=u.useCallback(async()=>{try{await navigator.clipboard.writeText(k)}catch(_){a(`Copy failed: ${_ instanceof Error?_.message:String(_)}`,"error");return}h(!0),j.current&&clearTimeout(j.current),j.current=setTimeout(()=>h(!1),1500)},[k,a]),S=u.useCallback(()=>{p(v),d(!0),requestAnimationFrame(()=>T.current?.focus())},[v]),L=u.useCallback(()=>{d(!1),p("")},[]),A=u.useCallback(async()=>{if(f===v){d(!1);return}if(!(!s||y)){N(!0);try{await s(f),d(!1)}catch{}finally{N(!1)}}},[s,f,v,y]),D=u.useCallback(()=>{if($==="json")try{p(JSON.stringify(JSON.parse(f),null,2))}catch{}else $==="xml"&&p(f.replace(/>\s*</g,`>
122
+ <`).trim())},[f,$]),B=$==="json"||$==="xml",X=!!s&&!e?.isReadOnly&&$!=="binary",E=n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx(b,{className:"size-4 text-muted-foreground shrink-0"}),n.jsx("span",{className:"truncate font-semibold text-sm",children:e?.columnLabel}),n.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:w?w.kind==="image"?w.mime.replace("image/","").toUpperCase()+" image":w.kind==="pdf"?"PDF document":aa[$]:aa[$]}),n.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:w?xr(k):`${k.length} chars`})]}),P=n.jsxs("div",{className:"flex items-center gap-1 px-4 pb-2",children:[n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:V,children:[x?n.jsx(C.Check,{className:"size-3"}):n.jsx(C.Copy,{className:"size-3"}),x?"Copied":"Copy"]}),w&&n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:F,children:[n.jsx(C.Download,{className:"size-3"}),"Download"]}),X&&!m&&n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:S,children:[n.jsx(C.Pencil,{className:"size-3"}),"Edit"]}),m&&B&&n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:D,children:[n.jsx(C.WrapText,{className:"size-3"}),"Format"]}),n.jsxs("div",{className:"flex items-center gap-1 ml-auto",children:[n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>r("prev"),disabled:!o,"aria-label":"Previous row",title:"Previous row",children:n.jsx(C.ChevronUp,{className:"size-4"})}),n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>r("next"),disabled:!i,"aria-label":"Next row",title:"Next row",children:n.jsx(C.ChevronDown,{className:"size-4"})}),n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>c(_=>!_),"aria-label":l?"Exit full screen":"Full screen",title:l?"Exit full screen":"Full screen",children:l?n.jsx(C.Minimize2,{className:"size-4"}):n.jsx(C.Maximize2,{className:"size-4"})})]})]}),q=n.jsx("div",{className:"flex-1 min-h-0 overflow-auto px-4 pb-4",children:m?n.jsxs("div",{className:"flex flex-col gap-2 h-full",children:[n.jsx("textarea",{ref:T,value:f,onChange:_=>p(_.target.value),className:Y("flex-1 w-full rounded-md border border-input bg-background px-3 py-2","text-xs font-mono leading-relaxed","ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","resize-none min-h-[200px]")}),n.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[n.jsx(Q,{type:"button",variant:"ghost",size:"sm",onClick:L,disabled:y,children:"Cancel"}),n.jsx(Q,{type:"button",size:"sm",onClick:A,disabled:y,children:y?"Saving…":"Save"})]})]}):w?.kind==="image"?n.jsx("img",{src:oo(k,w.mime),alt:e?.columnLabel??"Image content",className:"max-w-full rounded-md border border-input"}):w?n.jsxs("div",{className:"rounded-md border border-input bg-muted/30 p-4 text-sm text-muted-foreground",children:[n.jsxs("p",{children:[w.kind==="pdf"?"PDF document":"Binary content"," · ",xr(k)]}),n.jsx("p",{className:"mt-1 text-xs",children:"Use Download to save and open the file."})]}):n.jsx("pre",{className:"text-xs font-mono leading-relaxed whitespace-pre-wrap break-all",children:v})}),U=!!e;return n.jsxs(n.Fragment,{children:[n.jsx(md,{open:U&&!l,onOpenChange:_=>{_||t()},children:n.jsxs(hd,{side:"right",className:"w-[480px] max-w-[90vw]",children:[n.jsxs(gd,{children:[n.jsx(xd,{children:E}),n.jsx(bd,{className:"sr-only",children:"Content viewer panel"})]}),P,q]})}),n.jsx(jt,{open:U&&l,onOpenChange:_=>{_||c(!1)},children:n.jsxs(wt,{className:"max-w-[90vw] max-h-[90vh] w-full h-full flex flex-col",children:[n.jsxs(tn,{children:[n.jsx(Ct,{children:E}),n.jsx(Kt,{className:"sr-only",children:"Content viewer full screen"})]}),P,q]})})]})}function wd(e,t){if(Gn(e,t).filterTexts.length===0)return;const s=[];for(const o of e){const i=o.value,a=t.columns.find(l=>l.name===o.id);!a||!pn(a.paramType).includes(i.operator)||i.value===void 0||i.value===""&&i.operator!=="_null"||s.push({[a.graphQlName]:{[i.operator]:i.value}})}return s.length===1?s[0]:s.length>1?{and:s}:void 0}function ts({table:e,id:t,filterTable:r,filterColumn:s,selectedRowId:o,onRowSelect:i,onOpenColumn:a,stackingEnabled:l,onToggleStacking:c}){const m=Qn(e),[d,f]=u.useState(null),[p,x]=u.useState(null),[h,y]=u.useState(null),N=u.useRef([]),T=u.useCallback(I=>{x(Vn(I,e))},[e]),k=u.useCallback(I=>{f({type:"single",pk:I})},[]),$=u.useCallback(I=>{I.length!==0&&f({type:"batch",pks:I})},[]),[b,v]=u.useState(null),w=u.useCallback(I=>{I.length!==0&&v(I)},[]),[F,j]=u.useState(new Map),V=u.useRef(F);V.current=F;const[S,L]=u.useState(!1),A=qo(e),D=u.useCallback((I,ne)=>{const Se=N.current[I];y({columnName:ne,pk:Se?mt(Se,e):null,rowIndex:I,tableName:e.name})},[e]),{columns:B,sorting:X,columnFilters:E,pageIndex:P,pageSize:q,pageCount:U,rows:_,totalRows:ce,grouping:he,exportRows:Ue,loading:Pe,fetching:ie,error:se,onSortingChange:ke,onColumnFiltersChange:Ae,onPageIndexChange:re,onPageSizeChange:Ee,onGroupingChange:Ie,onGroupingSumChange:Le}=Jc(e,t,r,s,D,a),Ge=u.useCallback(async()=>{if(d)try{d.type==="single"?await m.deleteRow(d.pk):await m.deleteRows(d.pks),f(null)}catch{}},[d,m]),Oe=d?.type==="batch"?d.pks.length:1;N.current=_;const{toast:ye}=vt(),ze=$e(),O=e.isEditable!==!1,Z=u.useMemo(()=>h?.pk?Vn(h.pk,e):null,[h,e]),ee=u.useMemo(()=>!h||h.tableName!==e.name?-1:Z===null?h.rowIndex<_.length?h.rowIndex:-1:_.findIndex(I=>{const ne=mt(I,e);return ne!==null&&Vn(ne,e)===Z}),[h,Z,_,e]),Ce=ee>=0?_[ee]:void 0,xe=u.useMemo(()=>h?.pk?qn(h.pk,e):null,[h,e]),qe=h?e.columns.find(I=>I.name===h.columnName):void 0,W=!!h&&!!qe&&!!xe&&_t(qe)&&Ce!==void 0&&!(qe.name in Ce),{data:me,isLoading:Ne,error:ve}=de.useQuery({queryKey:["contentPanelValue",e.name,h?.columnName,Z],queryFn:async()=>{const I=Cr(e,xe,[qe.name]),Se=(await ze.query(I,xe.variables))?.value?.data?.at(0);if(!Se)throw new Error("Row no longer exists.");return Se[qe.name]??null},enabled:W});u.useEffect(()=>{h!==null&&W&&ve&&(y(null),ye(`Could not load content: ${ve.message}`,"error"))},[h,W,ve,ye]),u.useEffect(()=>{h!==null&&h.tableName!==e.name&&y(null)},[h,e.name]),u.useEffect(()=>{h!==null&&h.tableName===e.name&&!Pe&&ee===-1&&(y(null),ye("Row is no longer in the current view; panel closed.","error"))},[h,e.name,Pe,ee,ye]);const rt=u.useMemo(()=>{if(!h||!Ce)return null;const I=e.columns.find(ot=>ot.name===h.columnName);if(!I||W&&(Ne||ve))return null;const ne=W?me:Ce[h.columnName],Se=Ft(I);return{value:ne==null?"":Se||typeof ne=="object"?JSON.stringify(ne,null,2):String(ne),columnName:I.name,columnLabel:I.label,dbType:I.dbType,rowKey:Z??`row-${h.rowIndex}`,isReadOnly:I.isReadOnly||I.isPrimaryKey||I.isIdentity}},[h,Ce,Z,e,W,me,Ne,ve]),Mt=u.useMemo(()=>e.columns.filter(I=>!I.isReadOnly&&!I.isIdentity),[e]),be=u.useMemo(()=>Mt.filter(I=>!I.isNullable||I.name===h?.columnName),[Mt,h?.columnName]),ft=u.useMemo(()=>be.map(I=>({column:I})),[be]),Nt=u.useMemo(()=>{const I=new Map(e.columns.map(ne=>[ne.name,ne]));return(e.primaryKeys??[]).map(ne=>I.get(ne)).filter(ne=>!!ne)},[e]),Ye=wn(e,ft,Nt,Z??""),Xe=O&&xe!==null&&!Ye.isPending,Qt=u.useCallback(async I=>{if(!h||!xe)return;const ne=e.columns.find(De=>De.name===h.columnName);let Se=I;if(ne&&Ft(ne))try{Se=JSON.parse(I)}catch{}try{const De=Cr(e,xe,be.map(kt=>kt.name)),ht=(await ze.query(De,xe.variables))?.value?.data?.[0];if(!ht)throw new Error("Row no longer exists.");const Ke={};for(const kt of be)Ke[kt.name]=ht[kt.name]??null;Ke[h.columnName]=Se,await Ye.update(Ke)}catch(De){throw ye(`Save failed: ${De.message}`,"error"),De}},[h,xe,e,be,Ye,ze,ye]),kn=u.useCallback(()=>{y(null)},[]),Sn=u.useCallback(I=>{if(!h||ee<0)return;const ne=I==="prev"?Math.max(0,ee-1):Math.min(_.length-1,ee+1);D(ne,h.columnName)},[h,ee,_.length,D]),Ht=u.useMemo(()=>new Set(e.columns.filter(I=>!I.isReadOnly&&!I.isIdentity&&!I.isPrimaryKey&&!Et(I.dbType)&&!_t(I)).map(I=>I.name)),[e]),pt=u.useMemo(()=>new Set(e.columns.filter(I=>I.paramType.startsWith("Boolean")).map(I=>I.name)),[e]),It=u.useCallback((I,ne,Se)=>{const De=fn(I,e);if(!De)return;const ot=N.current.find(ht=>He(ht,e,-1)===I);j(ht=>{const Ke=new Map(ht),gt={...Ke.get(I)?.changes??{}},nn=ot?.[ne];return ot!==void 0&&nn==null==(Se==null)&&String(nn??"")===String(Se??"")?delete gt[ne]:gt[ne]=Se,Object.keys(gt).length===0?Ke.delete(I):Ke.set(I,{pk:De,changes:gt}),Ke})},[e]),st=u.useCallback(()=>j(new Map),[]),Ut=u.useCallback(async()=>{const I=[...V.current.entries()];if(I.length!==0){L(!0);try{const ne=e.columns.filter(Me=>Ht.has(Me.name)),Se=(e.primaryKeys??[]).map(Me=>e.columns.find(as=>as.name===Me)).filter(Me=>!!Me),De=new Set(I.flatMap(([,Me])=>Object.keys(Me.changes))),ot=ne.filter(Me=>!Me.isNullable||De.has(Me.name)),ht=[...new Set([...e.primaryKeys??[],...ot.map(Me=>Me.name)])],Ke=mo(e,I.map(([,Me])=>Me.pk),ht);if(!Ke)throw new Error("The edited rows have no resolvable primary keys.");const gt=(await ze.query(Ke.query,Ke.variables))?.value?.data??[];if(gt.length!==I.length)throw new Error(`Only ${gt.length} of ${I.length} edited rows still exist. Refresh and retry.`);const nn=cu(e,ne,Se,gt,Me=>V.current.get(He(Me,e,-1))?.changes);await A.saveDelta({updated:nn}),j(new Map)}catch(ne){ye(`Save failed: ${ne.message}`,"error")}finally{L(!1)}}},[e,Ht,A,ze,ye]),Lt=u.useRef(e.name);u.useEffect(()=>{Lt.current!==e.name&&(Lt.current=e.name,V.current.size>0&&(j(new Map),ye("Unsaved cell edits were discarded on table switch","error")))},[e.name,ye]);const z=u.useMemo(()=>new Map([...F].map(([I,ne])=>[I,ne.changes])),[F]),H=u.useCallback(()=>{const I=wd(E,e);window.dispatchEvent(new CustomEvent("bifrostql:visualize",{detail:{table:e.graphQlName,filter:I,filterType:`TableFilter${e.graphQlName}Input`}}))},[E,e]);return se?n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",se.message]})}):n.jsxs(n.Fragment,{children:[n.jsx(id,{columns:B,data:_,tableName:e.name,pageCount:U,pageIndex:P,pageSize:q,sorting:X,columnFilters:E,loading:Pe,fetching:ie,primaryKeys:e.primaryKeys??[],selectable:O&&!he,selectedRowId:o,onRowSelect:i,onSortingChange:ke,onColumnFiltersChange:Ae,onPageIndexChange:re,onPageSizeChange:Ee,onEditRow:O&&!he?T:void 0,onDeleteRow:O&&!he?k:void 0,onDeleteSelected:O&&!he?$:void 0,onBulkEditSelected:O&&!he?w:void 0,inlineEditableColumns:Ht,inlineBooleanColumns:pt,pendingEdits:z,onCellCommit:O&&!he?It:void 0,onSaveAllEdits:Ut,onDiscardAllEdits:st,savingEdits:S,stackingEnabled:l,onToggleStacking:c,exportRows:Ue,totalRows:ce,groupableColumns:e.columns,grouping:he,onGroupingChange:Ie,onGroupingSumChange:Le,onVisualize:H}),n.jsx(Kr,{open:d!==null,onOpenChange:I=>{I||f(null)},title:`Delete ${Oe} ${Oe===1?"row":"rows"}?`,description:n.jsxs(n.Fragment,{children:[n.jsx("p",{children:"This action cannot be undone."}),m.error&&n.jsx("p",{className:"mt-2 text-sm text-destructive",children:m.error.message})]}),confirmLabel:`Delete ${Oe===1?"row":`${Oe} rows`}`,variant:"destructive",isPending:m.isPending,onConfirm:Ge}),n.jsx(jd,{target:rt,onClose:kn,onNavigate:Sn,onSave:Xe?Qt:void 0,canNavigatePrev:ee>0,canNavigateNext:ee>=0&&ee<_.length-1}),b!==null&&n.jsx(dd,{table:e,pks:b,onClose:()=>v(null)}),p!==null&&n.jsx(Ro,{table:e.graphQlName,editId:p,onClose:()=>x(null)})]})}function Cd(e){return new Set((e.manyToManyJoins??[]).map(t=>t.junctionTable))}function ia(e){const t=Cd(e),r=e.multiJoins.filter(o=>!t.has(o.destinationTable)).map(o=>({kind:"child",key:`child:${o.fieldName??o.destinationTable}`,join:o})),s=(e.manyToManyJoins??[]).map(o=>({kind:"m2m",key:`m2m:${o.junctionTable}:${o.targetTable}`,m2m:o}));return[...r,...s]}function la(e,t){const r=new Set([...t.junctionSourceColumnNames,...t.junctionTargetColumnNames]);return e.columns.filter(s=>!s.isPrimaryKey&&!r.has(s.name))}function Nd(e,t,r,s){const o=r.junctionSourceColumnNames;if(o.length===0)throw new Error(`Many-to-many relationship '${r.name}' has no junction source columns.`);const i=to(s,o.length),a=new Map(e.columns.map($=>[$.name,$])),l=[],c=[],m={};o.forEach(($,b)=>{const v=a.get($);if(!v)throw new Error(`Junction table '${e.name}' has no column '${$}' (junction source column of many-to-many relationship '${r.name}').`);const w=v.paramType.replace("!",""),F=`src${b}`;l.push(`$${F}: ${w}`),c.push(`{ ${$}: { _eq: $${F} } }`),m[F]=dt(i[b],w)});const d=c.length===1?c[0]:`{ and: [${c.join(", ")}] }`,f=e.primaryKeys??[],p=la(e,r).map($=>$.name),x=t.primaryKeys?.length?t.primaryKeys:r.targetColumnNames,h=t.labelColumn,y=[...x];h&&!x.includes(h)&&y.push(`label: ${h}`);const N=`${r.junctionTargetField} { ${y.join(" ")} }`,T=[...f,...p,N].join(" ");return{query:`query GetLinks_${e.name}(${l.join(", ")}, $limit: Int, $offset: Int) { ${e.name}(filter: ${d} limit: $limit offset: $offset) { total offset limit data { ${T} } } }`,variables:m}}function ca(e,t){const r=zt(e).map(s=>s.name);return r.length>0?r:[...t.targetColumnNames]}function kd(e,t,r){je(e.name,"many-to-many target table name");const s=ca(e,t),o=t.targetColumnNames[0],i=e.labelColumn||s[0];for(const h of s)je(h,"many-to-many target identity column");je(o,"many-to-many junction target column"),je(i,"many-to-many target label column");const l=`${[...new Set([...s,o])].join(" ")} label: ${i}`,c=e.columns.find(h=>h.name===i);if(!c)throw new Error(`Target table '${e.name}' has no column '${i}' (label column for the '${t.name}' many-to-many picker).`);const m=c.paramType.replace("!","")==="String",d=!!r&&r.trim()!==""&&m,f=d?"$limit: Int, $search: String":"$limit: Int",p=d?`filter: {${i}: {_contains: $search}} `:"";return{query:`query PickTarget(${f}) { ${e.name}(${p}limit: $limit sort: [${i}_asc]) { data { ${l} } } }`,identityColumns:s,linkColumn:o,serverSearch:m}}function Sd(e,t,r){const s=e[t.junctionTargetField];if(!s)return null;const o=He(s,r,0),i=s.label!=null?String(s.label):o;return{id:o,label:i}}function Td(e,t,r){if(e.junctionSourceColumnNames.length!==1||e.junctionTargetColumnNames.length!==1)throw new Error("attachJunctionDetail supports single-column junction FKs only; this relationship uses a composite key which is not yet supported.");const[s]=to(t,1);return{[e.junctionSourceColumnNames[0]]:s,[e.junctionTargetColumnNames[0]]:r}}const ns=200,$d=50,Ed=500;function Fd({m2m:e,parentRowId:t,onOpenColumn:r}){const s=Je(),o=s.findTable(e.junctionTable),i=s.findTable(e.targetTable);return!o||!i?n.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Relationship schema unavailable."}):n.jsx(_d,{m2m:e,parentRowId:t,onOpenColumn:r,junction:o,target:i})}function _d({m2m:e,parentRowId:t,onOpenColumn:r,junction:s,target:o}){const i=$e(),a=de.useQueryClient(),{toast:l}=vt(),[c,m]=u.useState(!1),[d,f]=u.useState(null),p=Qn(s);let x={query:null,variables:{}},h=null;try{x=Nd(s,o,e,t)}catch(A){h=A}const{query:y,variables:N}=x,T=u.useMemo(()=>["m2mRows",e.junctionTable,e.targetTable,t],[e.junctionTable,e.targetTable,t]),{data:k,isLoading:$,error:b}=de.useQuery({queryKey:T,queryFn:()=>i.query(y,{...N,limit:ns,offset:0}),enabled:!!y}),v=u.useCallback(()=>a.invalidateQueries({queryKey:T}),[a,T]),w=u.useCallback(async A=>{const D=mt(A,s);if(!D)throw new Error(`This link cannot be removed: its ${s.label} row is missing one or more key columns (${(s.primaryKeys??[]).join(", ")||"none declared"}).`);await p.deleteRow(D),await v()},[s,p,v]);if(h)return n.jsxs("div",{className:"p-4 text-sm text-destructive",children:["Relationship misconfigured: ",h.message]});const F=k?.[s.name]?.data??[],j=la(s,e),V=s.isEditable!==!1,S=ca(o,e),L=new Set;for(const A of F){const D=A[e.junctionTargetField];D&&(S.some(B=>D[B]==null)||L.add($t(S.map(B=>D[B]))))}return n.jsxs("div",{className:"flex flex-col min-h-0 flex-1 overflow-hidden",children:[n.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 bg-muted/20 border-b border-border shrink-0",children:[n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs text-muted-foreground",title:`Linked through ${s.label}`,children:[n.jsx(C.Link2,{className:"size-3"}),"via ",s.label]}),V&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs ml-auto",onClick:()=>m(!0),children:[n.jsx(C.Plus,{className:"size-3 mr-1"})," Add link"]})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-auto",children:[b&&n.jsxs("div",{className:"p-3 text-sm text-destructive",children:["Error: ",b.message]}),$&&n.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin"})," Loading…"]}),!$&&F.length===0&&n.jsxs("div",{className:"p-3 text-sm text-muted-foreground",children:["No linked ",o.label,"."]}),F.length>0&&n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-border text-left text-xs text-muted-foreground",children:[n.jsx("th",{className:"px-2 py-1 font-medium",children:o.label}),j.map(A=>n.jsx("th",{className:"px-2 py-1 font-medium",children:A.label},A.name)),V&&n.jsx("th",{className:"px-2 py-1 w-8","aria-label":"actions"})]})}),n.jsx("tbody",{children:F.map((A,D)=>{const B=Sd(A,e,o);return n.jsxs("tr",{className:"border-b border-border/50 hover:bg-muted/30",children:[n.jsx("td",{className:"px-2 py-1",children:B?n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Pn,{to:`/${o.name}/${B.id}`,className:"text-primary hover:underline",children:B.label}),r&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"size-5",onClick:()=>r({tableName:o.name,filterId:B.id}),"aria-label":`Open ${B.label} in side column`,title:"Open in side column",children:n.jsx(C.Search,{className:"size-3"})})]}):n.jsx("span",{className:"text-muted-foreground",children:"—"})}),j.map(X=>n.jsx("td",{className:"px-2 py-1",children:Kn(A[X.name],X)},X.name)),V&&n.jsx("td",{className:"px-2 py-1",children:n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"size-6 text-muted-foreground hover:text-destructive",onClick:()=>f(A),disabled:p.isPending,"aria-label":`Detach ${B?.label??"link"}`,title:"Detach",children:n.jsx(C.Unlink,{className:"size-3.5"})})})]},D)})})]}),F.length>=ns&&n.jsxs("div",{className:"px-3 py-2 text-xs text-muted-foreground italic border-t border-border",children:["Showing the first ",ns," links. Detach some or narrow the parent selection to see more."]})]}),c&&n.jsx(Pd,{target:o,junction:s,m2m:e,parentRowId:t,linkedIds:L,onClose:()=>m(!1),onLinked:v}),n.jsx(Kr,{open:d!==null,onOpenChange:A=>{A||f(null)},title:"Detach this link?",description:n.jsxs("p",{children:["This removes the link row. The ",o.label," record itself is not deleted."]}),confirmLabel:"Detach",variant:"destructive",isPending:p.isPending,onConfirm:async()=>{try{d&&await w(d)}catch(A){l(`Detach failed: ${A.message}`,"error")}finally{f(null)}}})]})}function Pd({target:e,junction:t,m2m:r,parentRowId:s,linkedIds:o,onClose:i,onLinked:a}){const l=$e(),c=t.columns.filter(B=>r.junctionSourceColumnNames.includes(B.name)||r.junctionTargetColumnNames.includes(B.name)).map(B=>({column:B})),m=wn(t,c,[]),[d,f]=u.useState(""),[p,x]=u.useState("");u.useEffect(()=>{const B=setTimeout(()=>x(d),300);return()=>clearTimeout(B)},[d]);const h=p.trim();let y=null,N=null;try{y=kd(e,r,h)}catch(B){N=B}const{query:T,identityColumns:k,linkColumn:$,serverSearch:b}=y??{query:"",identityColumns:[],linkColumn:"",serverSearch:!1},v=b?$d:Ed,{data:w,isLoading:F}=de.useQuery({queryKey:["m2mTargets",e.name,b?h:""],queryFn:({signal:B})=>l.query(T,b&&h?{limit:v,search:h}:{limit:v},{signal:B}),enabled:y!==null}),j=w?.[e.name]?.data??[],V=b||!h?j:j.filter(B=>Wo(B,"label",h)),S=j.length>=v,[L,A]=u.useState(null),D=u.useCallback(async(B,X)=>{if(o.has(B))return;let E;try{E=Td(r,s,X)}catch(P){A(P);return}A(null);try{await m.insert(E)}catch{return}await a(),i()},[m,r,s,o,a,i]);return N?n.jsx(jt,{open:!0,onOpenChange:B=>{B||i()},children:n.jsxs(wt,{className:"max-w-md",children:[n.jsx(tn,{children:n.jsxs(Ct,{children:["Add ",e.label," link"]})}),n.jsxs("p",{className:"text-sm text-destructive",children:["Relationship misconfigured: ",N.message]})]})}):n.jsx(jt,{open:!0,onOpenChange:B=>{B||i()},children:n.jsxs(wt,{className:"max-w-md",children:[n.jsx(tn,{children:n.jsxs(Ct,{children:["Add ",e.label," link"]})}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(C.Search,{className:"size-4 text-muted-foreground"}),n.jsx(Qe,{autoFocus:!0,placeholder:`Search ${e.label}…`,value:d,onChange:B=>f(B.target.value)})]}),L&&n.jsx("p",{className:"text-sm text-destructive",children:L.message}),m.error&&n.jsx("p",{className:"text-sm text-destructive",children:m.error.message}),n.jsxs("div",{className:"max-h-72 overflow-auto border border-border rounded-md",children:[F&&n.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin"})," Loading…"]}),!F&&V.length===0&&n.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No matches."}),V.map((B,X)=>{const E=$t(k.map(_=>B[_])),P=String(B[$]??""),q=B.label!=null?String(B.label):E,U=o.has(E);return n.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-2 text-left px-3 py-1.5 text-sm hover:bg-muted/50 disabled:opacity-50 disabled:hover:bg-transparent",disabled:m.isPending||U,onClick:()=>D(E,P),children:[n.jsx("span",{className:"truncate",children:q}),U&&n.jsx("span",{className:"shrink-0 text-xs text-muted-foreground italic",children:"Already linked"})]},X)}),!F&&S&&n.jsx("div",{className:"px-3 py-1.5 text-xs text-muted-foreground italic border-t border-border",children:b?`Showing the first ${v} matches — type to narrow.`:`Showing the first ${v} rows; some may not be listed.`})]})]})})}function ua(e){return e.kind==="child"?e.join.destinationTable:e.m2m.targetTable}function da({parentTable:e,selectedRowId:t,onClose:r,onOpenColumn:s}){const o=Je(),i=ia(e),[a,l]=u.useState(i[0]?.key??""),[c,m]=u.useState(!1),[d,f]=u.useState(null),p=i.find(y=>y.key===a)??i[0];if(u.useEffect(()=>{f(null)},[a,t]),i.length===0||!o.data)return null;const x=p.kind==="child"?o.findTable(p.join.destinationTable):void 0,h=(x?.multiJoins?.length??0)>0;return n.jsxs("div",{className:"border-t-2 border-primary/20 flex flex-col flex-1 shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted/30 border-b border-border shrink-0",children:[n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:()=>m(!c),"aria-label":c?"Expand detail panel":"Collapse detail panel",title:c?"Expand detail panel":"Collapse detail panel",children:c?n.jsx(C.ChevronUp,{className:"size-3.5"}):n.jsx(C.ChevronDown,{className:"size-3.5"})}),n.jsx("span",{className:"text-xs text-muted-foreground mr-1",children:"Detail:"}),n.jsx("div",{className:"flex items-center gap-0.5 overflow-x-auto",children:i.map(y=>{const T=o.findTable(ua(y))?.label??ua(y),k=y.key===p.key;return n.jsxs("span",{className:"group/tab inline-flex items-center",children:[n.jsx(Q,{variant:k?"secondary":"ghost",size:"sm",className:Y("text-xs h-7 px-2.5",k&&"font-semibold"),onClick:()=>l(y.key),children:T}),s&&y.kind==="child"&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"opacity-0 group-hover/tab:opacity-100 size-5 shrink-0",onClick:()=>s({tableName:y.join.destinationTable,filterTable:e.name,filterId:t,...Gt(y.join)?{}:{filterColumn:y.join.destinationColumnNames[0]}}),"aria-label":"Open in side column",title:"Open in side column",children:n.jsx(C.PanelRight,{className:"size-3"})})]},y.key)})}),r&&n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:r,className:"ml-auto shrink-0","aria-label":"Close detail panel",title:"Close detail panel",children:n.jsx(C.X,{className:"size-3.5"})})]}),!c&&n.jsx("div",{className:"flex-1 flex flex-col",children:p.kind==="child"&&!x?n.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"This related table is not available."}):p.kind==="child"?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex-1 min-h-[11rem] overflow-hidden flex flex-col",children:n.jsx(ts,{table:x,id:t,filterTable:e.name,...Gt(p.join)?{}:{filterColumn:p.join.destinationColumnNames[0]},selectedRowId:h?d:void 0,onRowSelect:h?f:void 0,onOpenColumn:s},`${p.key}-${t}`)}),h&&d&&n.jsx("div",{className:"flex-1 flex flex-col",children:n.jsx(da,{parentTable:x,selectedRowId:d,onClose:()=>f(null),onOpenColumn:s})})]}):n.jsx(Fd,{m2m:p.m2m,parentRowId:t,onOpenColumn:s},`${p.key}-${t}`)})]})}const zd={mainTable:null,columns:[],focusedIndex:0,focusColumn:()=>{},closeColumn:()=>{}},ma=u.createContext(zd),fa=u.createContext({register:()=>{},unregister:()=>{}});function Dd({children:e}){const[t,r]=u.useState(null),[s,o]=u.useState(0),i=u.useCallback(p=>{r(p)},[]),a=u.useCallback(()=>{r(null),o(0)},[]),l=u.useCallback(p=>{if(o(p),!t)return;const x=t.columnRefs.get(p);x&&x.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[t]),c=u.useCallback(p=>{t&&p>0&&t.onClose(p-1)},[t]),m=u.useMemo(()=>t?t.columns.map((p,x)=>({panel:p,element:t.columnRefs.get(x+1)??null})):[],[t]),d=u.useMemo(()=>({mainTable:t?.mainTable??null,columns:m,focusedIndex:s,focusColumn:l,closeColumn:c}),[t,m,s,l,c]),f=u.useMemo(()=>({register:i,unregister:a}),[i,a]);return n.jsx(fa.Provider,{value:f,children:n.jsx(ma.Provider,{value:d,children:e})})}function Md(){return u.useContext(ma)}function Id(){return u.useContext(fa)}function pa(e,t){return e.tableName===t.tableName&&e.filterTable===t.filterTable&&e.filterId===t.filterId&&e.filterColumn===t.filterColumn}function Ld(e,t){const r=e[e.length-1];if(r&&pa(r,t))return e;const s=e.findIndex(o=>pa(o,t));return s>=0?e.slice(0,s+1):[...e,t]}function Od(e,t){return t<0?[]:t>=e.length?e:e.slice(0,t)}function Ad(e,t,r){const s=i=>r(i)??i,o=[{index:-1,label:s(e)}];for(let i=0;i<t.length;i++){const a=t[i],l=a.filterTable?s(a.filterTable):s(i===0?e:t[i-1].tableName),c=a.filterId?`from ${l} #${a.filterId}`:void 0;o.push({index:i,label:s(a.tableName),detail:c,frame:a})}return o}const ha="edit-db:panel:",qd=16;function ga(e,t,r){return Math.min(r,Math.max(t,e))}function Vd(e,t,r,s){try{const o=localStorage.getItem(ha+e),i=o===null?NaN:Number(o);return Number.isFinite(i)?ga(i,r,s):t}catch{return t}}function Bd(e,t){try{localStorage.setItem(ha+e,String(Math.round(t)))}catch{}}function xa({key:e,initial:t,min:r,max:s,axis:o,invert:i=!1}){const[a,l]=u.useState(()=>Vd(e,t,r,s)),c=u.useRef(null),m=u.useCallback(p=>{const x=ga(p,r,s);return l(x),Bd(e,x),x},[e,r,s]),d=u.useCallback(p=>{if(p.button!==0)return;p.preventDefault();const x=p.currentTarget;x.setPointerCapture(p.pointerId),c.current={start:o==="x"?p.clientX:p.clientY,startSize:a};const h=N=>{if(!c.current)return;const k=((o==="x"?N.clientX:N.clientY)-c.current.start)*(i?-1:1);m(c.current.startSize+k)},y=N=>{c.current=null;try{x.releasePointerCapture(N.pointerId)}catch{}x.removeEventListener("pointermove",h),x.removeEventListener("pointerup",y),x.removeEventListener("pointercancel",y)};x.addEventListener("pointermove",h),x.addEventListener("pointerup",y),x.addEventListener("pointercancel",y)},[m,o,i,a]),f=u.useCallback(p=>{const x=o==="x"?"ArrowRight":"ArrowDown",h=o==="x"?"ArrowLeft":"ArrowUp";if(p.key!==x&&p.key!==h)return;p.preventDefault();const y=(p.key===x?1:-1)*(i?-1:1);m(a+y*qd)},[m,o,i,a]);return{size:a,onPointerDown:d,onKeyDown:f}}function tr(e,t){return e.find(r=>r.name===t)}function Jt(){const e=ir(),{table:t,id:r,filterTable:s}=e,{loading:o,error:i,data:a}=Je(),[l,c]=u.useState(null),m=xa({key:"detail-height",initial:300,min:120,max:800,axis:"y",invert:!0}),[d,f]=u.useState([]),[p,x]=u.useState(!0),[h,y]=u.useState(new Set),N=u.useRef(t);t!==N.current&&(N.current=t,d.length>0&&f([]),h.size>0&&y(new Set));const T=u.useCallback(P=>{y(q=>{const U=new Set(q);return U.has(P)?U.delete(P):U.add(P),U})},[]),{register:k,unregister:$}=Id(),b=u.useRef(null),v=u.useRef(new Map),w=u.useMemo(()=>a?tr(a,t):void 0,[a,t]),F=w?ia(w).length>0:!1,j=u.useCallback(P=>{f(q=>Ld(q,P))},[]),V=u.useCallback(P=>{x(P),P||f([])},[]),S=p?j:void 0,L=u.useCallback(P=>{f(q=>q.filter((U,_)=>_!==P))},[]),A=u.useCallback(P=>{f(q=>Od(q,P+1))},[]),D=u.useMemo(()=>Ad(t??"",d,P=>{if(a)return tr(a,P)?.label}),[t,d,a]);if(u.useEffect(()=>{const P=v.current;P.set(0,b.current);for(const q of P.keys())q>d.length&&P.delete(q);return k({mainTable:t,columns:d,columnRefs:P,onClose:L}),()=>$()},[t,d,k,$,L]),!t)return n.jsx("div",{className:"p-5 text-center text-muted-foreground",children:"Table missing"});if(o)return n.jsxs("div",{className:"flex items-center justify-center gap-2 p-5",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]});if(i)return n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",i.message]})});if(!w)return n.jsx("div",{className:"p-5 text-center text-muted-foreground",children:"Table not found"});const B=n.jsx(ts,{table:w,id:r,filterTable:s,selectedRowId:F?l:void 0,onRowSelect:F?c:void 0,onOpenColumn:S,stackingEnabled:p,onToggleStacking:V});if(d.length===0){const P=F&&l;return n.jsx("div",{className:"flex flex-col flex-1 min-h-0",children:n.jsxs("div",{ref:b,className:"flex flex-col flex-1 min-h-0 min-w-0",children:[n.jsx("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:B}),P&&n.jsxs(n.Fragment,{children:[n.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":"Resize detail panel",tabIndex:0,"data-testid":"detail-resize-handle",className:"h-1.5 shrink-0 cursor-row-resize select-none touch-none hover:bg-primary/40 focus-visible:bg-primary/60 focus-visible:outline-none",onPointerDown:m.onPointerDown,onKeyDown:m.onKeyDown}),n.jsx("div",{className:"min-h-0 overflow-y-auto flex flex-col",style:{flex:`0 0 ${m.size}px`},children:n.jsx(da,{parentTable:w,selectedRowId:l,onClose:()=>c(null),onOpenColumn:S})})]})]})})}const X=d.length-1,E=(P,q)=>q||h.has(P);return n.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[n.jsx(Gd,{crumbs:D,onCrumbClick:A,activeIndex:d.length-1}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto flex flex-col gap-0.5 p-0.5",children:[n.jsx(ba,{title:w.label,selectedRowId:d[0]?.filterId,expanded:E(-1,!1),active:!1,onToggle:()=>T(-1),onRef:P=>{b.current=P,v.current.set(0,P)},children:B}),d.map((P,q)=>{const U=q===X;return n.jsx(ba,{title:tr(a,P.tableName)?.label??P.tableName,selectedRowId:d[q+1]?.filterId,expanded:E(q,U),active:U,onToggle:()=>T(q),onClose:()=>L(q),onRef:_=>{v.current.set(q+1,_)},children:n.jsx(ts,{table:tr(a,P.tableName),id:P.filterId,filterTable:P.filterTable,filterColumn:P.filterColumn,onOpenColumn:j})},`${P.tableName}|${P.filterTable??""}|${P.filterId??""}|${P.filterColumn??""}`)})]})]})}function Gd({crumbs:e,onCrumbClick:t,activeIndex:r}){return n.jsx("nav",{"aria-label":"Drill-down breadcrumb",className:"flex items-center gap-1 px-2 py-1 bg-muted/20 border-b border-border shrink-0 overflow-x-auto",children:e.map((s,o)=>{const i=s.index===r,a=o===0;return n.jsxs("span",{className:"inline-flex items-center gap-1 shrink-0",children:[!a&&n.jsx(C.ChevronRight,{className:"size-3 text-muted-foreground shrink-0"}),n.jsxs(Q,{variant:i?"secondary":"ghost",size:"sm",className:Y("h-6 px-2 text-xs gap-1",i&&"font-semibold"),onClick:()=>t(s.index),"aria-current":i?"page":void 0,title:s.detail?`${s.label} (${s.detail})`:s.label,children:[a&&n.jsx(C.Home,{className:"size-3"}),n.jsx("span",{className:"truncate max-w-[12rem]",children:s.label}),s.detail&&n.jsx("span",{className:"text-muted-foreground font-normal truncate max-w-[10rem]",children:s.detail})]})]},`${s.index}-${s.label}`)})})}function ba({title:e,selectedRowId:t,expanded:r,active:s,onToggle:o,onClose:i,onRef:a,children:l}){return n.jsxs("div",{ref:a,className:"shrink-0 flex flex-col border border-border rounded-sm overflow-hidden",children:[n.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted/30 border-b border-border shrink-0",children:[n.jsx("button",{type:"button",onClick:o,className:"inline-flex items-center justify-center size-5 shrink-0 text-muted-foreground hover:text-foreground","aria-expanded":r,"aria-label":r?"Collapse table":"Expand table",title:r?"Collapse":"Expand",children:r?n.jsx(C.ChevronDown,{className:"size-3.5"}):n.jsx(C.ChevronRight,{className:"size-3.5"})}),n.jsx("span",{className:"text-xs font-medium truncate",children:e}),s&&n.jsx("span",{className:"text-[10px] uppercase tracking-wide text-primary/70 shrink-0",children:"active"}),!r&&t&&n.jsxs("span",{className:"text-xs text-muted-foreground truncate",children:["#",t]}),n.jsx("div",{className:"flex-1"}),i&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"shrink-0",onClick:i,"aria-label":"Close column",title:"Close column",children:n.jsx(C.X,{className:"size-3.5"})})]}),r&&n.jsx("div",{className:"flex flex-col min-h-[18rem] max-h-[34rem]",children:l})]})}function rs(){const e=ir(),{loading:t,error:r,data:s}=Je(),{mainTable:o,columns:i,focusedIndex:a,focusColumn:l,closeColumn:c}=Md(),[m,d]=u.useState(""),f=_n(),{search:p}=hs(),x=!!p.get("filter"),{back:h,hasBack:y}=Da(),N=e?.table,T=i.length>0,k=u.useMemo(()=>s?.find(j=>j.graphQlName===N),[s,N]),$=u.useMemo(()=>k?.columns?.filter(j=>Ui(j.paramType)||Vt(j.paramType)).map(j=>({key:j.name,value:`${j.name},${j.paramType}`,label:j.label})),[k]),[b,v]=u.useState($?.at(0)?.value??"");u.useEffect(()=>{d(""),v($?.at(0)?.value??"")},[$]);const w=()=>{if(!m)return;const[j,V]=b.split(",");if(!V)return;const S=V.replace("!","");if(Vt(S)){const L=eo(m,S);if(L===null)return;f(`?filter=["${j}", "_eq", ${JSON.stringify(L)}, "${V}"]`)}else S==="String"&&f(`?filter=["${j}", "_contains", ${JSON.stringify(m)}, "${V}"]`)},F=()=>{d("");const j=new URLSearchParams(p.toString());j.delete("filter");const V=j.toString();f(V?`?${V}`:"?")};return t?n.jsxs("div",{className:"flex items-center gap-2 p-2.5",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):r?n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",r.message]})}):n.jsxs("header",{className:"flex flex-wrap items-center gap-x-3 gap-y-1.5 px-3 py-1.5 min-h-[2.5rem]",children:[n.jsxs("div",{className:"flex items-center gap-1.5 overflow-x-auto min-w-0 flex-1",children:[n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:()=>y&&h(),disabled:!y,"aria-label":"Go back",title:"Go back",className:"shrink-0",children:n.jsx(C.ChevronLeft,{className:"size-4"})}),T?n.jsxs("div",{className:"flex items-center gap-1 overflow-x-auto",children:[n.jsx("button",{type:"button",onClick:()=>l(0),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium whitespace-nowrap transition-colors ${a===0?"bg-primary text-primary-foreground":"bg-muted/50 text-muted-foreground hover:bg-muted"}`,children:k?.label??zn(e?.table??"")}),i.map((j,V)=>{const L=s?.find(A=>A.graphQlName===j.panel.tableName)?.label??zn(j.panel.tableName);return n.jsxs("span",{className:`inline-flex items-center gap-1 pl-2 pr-1 py-0.5 rounded text-xs font-medium whitespace-nowrap transition-colors ${a===V+1?"bg-primary text-primary-foreground":"bg-muted/50 text-muted-foreground hover:bg-muted"}`,children:[n.jsx("button",{type:"button",onClick:()=>l(V+1),className:"whitespace-nowrap",children:L}),n.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),c(V+1)},className:"rounded-sm hover:bg-background/50 p-px","aria-label":`Close ${L}`,children:n.jsx(C.X,{className:"size-3"})})]},`${j.panel.tableName}-${j.panel.filterId??V}`)})]}):n.jsx("h2",{className:"text-sm font-semibold whitespace-nowrap",children:k?.label??e?.table??"(Select)"})]}),$&&$.length>0&&n.jsxs("div",{className:"flex items-center border border-border rounded-md overflow-hidden flex-[2_2_16rem] min-w-[12rem]",children:[n.jsxs(Ze,{value:b,onValueChange:v,children:[n.jsx(tt,{size:"sm",className:"w-auto min-w-[120px] shrink-0 border-0 rounded-none border-r border-border h-8 text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:$.map(j=>n.jsx(we,{value:j.value,children:j.label},j.key))})]}),n.jsxs("div",{className:"relative flex-1 min-w-[180px]",children:[n.jsx(C.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground pointer-events-none"}),n.jsx(Qe,{type:"search",value:m,onChange:j=>d(j.target.value),onKeyDown:j=>j.key==="Enter"&&w(),className:"h-8 border-0 rounded-none focus-visible:ring-0 focus-visible:ring-offset-0",style:{paddingLeft:"2.25rem"},placeholder:"Search..."})]}),n.jsxs(Q,{variant:"ghost",size:"sm",onClick:w,className:"shrink-0 rounded-none border-l border-border h-8 px-3 text-xs",children:[n.jsx(C.Filter,{className:"size-3.5"}),"Filter"]}),x&&n.jsx(Q,{variant:"ghost",size:"sm",onClick:F,title:"Clear filter","aria-label":"Clear filter",className:"shrink-0 rounded-none border-l border-border h-8 px-2 text-xs text-muted-foreground",children:n.jsx(C.X,{className:"size-3.5"})})]}),k&&n.jsxs("div",{className:"flex items-center gap-px border border-border rounded-md overflow-hidden shrink-0",children:[n.jsxs(Q,{variant:"ghost",size:"sm",onClick:()=>f("/"),title:"Back to table list",className:"text-muted-foreground text-xs h-8 px-3 rounded-none",children:[n.jsx(C.Home,{className:"size-3.5"}),"Home"]}),k?.isEditable&&n.jsxs(Q,{variant:"default",size:"sm",onClick:()=>f("edit/"),className:"h-8 text-xs px-4 rounded-none",children:[n.jsx(C.Plus,{className:"size-3.5"}),"Add"]})]})]})}class nr extends u.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){const{onError:s,section:o}=this.props;console.error(`Error in ${o??"component"}:`,t,r),s?.(t,r)}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){const{hasError:t,error:r}=this.state,{children:s,fallback:o,section:i}=this.props;return t?o||n.jsx("div",{className:"flex items-center justify-center p-5 min-h-[100px]",children:n.jsxs(Rt,{variant:"destructive",className:"max-w-[400px]",children:[n.jsx(C.AlertCircle,{className:"size-4"}),n.jsxs(Rs,{children:["Something went wrong",i?` in ${i}`:""]}),n.jsxs(Xt,{className:"mt-2",children:[n.jsx("p",{children:r?.message??"An unexpected error occurred"}),n.jsx(Q,{variant:"destructive",size:"sm",className:"mt-3",onClick:this.handleRetry,children:"Try Again"})]})]})}):s}}function Kd(){const{loading:e,error:t,data:r}=Je();return e?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[n.jsx(C.Database,{className:"size-10 animate-pulse"}),n.jsx("p",{className:"text-sm",children:"Loading schema..."})]}):t?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 max-w-md mx-auto text-center",children:[n.jsx(C.Database,{className:"size-12 text-destructive"}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Connection Error"}),n.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:t.message})]})]}):r.length===0?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 max-w-md mx-auto text-center",children:[n.jsx(C.Database,{className:"size-12 text-muted-foreground/50"}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"No Tables Found"}),n.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"This database doesn't contain any tables. It may be a new or empty database."}),n.jsx("p",{className:"mt-3 text-xs text-muted-foreground/70",children:"Create tables in your database and reconnect, or try a different connection."})]})]}):n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-6 max-w-lg mx-auto text-center",children:[n.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground/50",children:[n.jsx(C.Table2,{className:"size-10"}),n.jsx(C.MousePointerClick,{className:"size-6"})]}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Select a Table"}),n.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Choose a table from the sidebar to browse and edit its data."})]}),n.jsxs("div",{className:"text-xs text-muted-foreground/60 border border-border rounded-md px-4 py-3 bg-muted/30",children:[n.jsxs("p",{className:"font-medium text-muted-foreground mb-1",children:[r.length," table",r.length!==1?"s":""," available"]}),n.jsxs("p",{className:"leading-relaxed",children:[r.slice(0,8).map(s=>s.label).join(", "),r.length>8?`, and ${r.length-8} more`:""]})]})]})}function Wd({children:e}){const{loading:t,error:r}=Je();return t?n.jsxs("div",{className:"flex items-center justify-center flex-1 gap-3 text-muted-foreground",children:[n.jsx(C.Loader2,{className:"size-6 animate-spin"}),n.jsx("span",{className:"text-sm",children:"Connecting to database..."})]}):r?n.jsx("div",{className:"flex items-center justify-center flex-1",children:n.jsxs(Rt,{variant:"destructive",className:"max-w-lg",children:[n.jsx(C.AlertCircle,{className:"size-4"}),n.jsx(Rs,{children:"Database Connection Error"}),n.jsxs(Xt,{className:"mt-2",children:[n.jsx("p",{className:"text-sm",children:r.message}),n.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Check your connection string and ensure the database server is running."})]})]})}):n.jsx(n.Fragment,{children:e})}function Jd(){const[e,t]=u.useState(!0),r=xa({key:"sidebar-width",initial:240,min:150,max:560,axis:"x"});return n.jsx(Wd,{children:n.jsx(Dd,{children:n.jsxs("div",{className:"grid h-full flex-1 min-h-0 grid-rows-[auto_1fr]",style:{gridTemplateColumns:e?`${r.size}px 1fr`:"0px 1fr"},children:[n.jsxs("div",{className:"col-span-full sticky top-0 z-50 bg-background border-b border-border flex items-center",children:[n.jsx(Q,{variant:"ghost",size:"icon",className:"md:hidden ml-1 shrink-0",onClick:()=>t(!e),"aria-label":"Toggle sidebar",title:"Toggle sidebar",children:n.jsx(C.PanelLeft,{className:"size-5"})}),n.jsx("div",{className:"flex-1 min-w-0",children:n.jsx(nr,{section:"Header",children:n.jsxs(lr,{children:[n.jsx(Be,{path:"/:table/*",element:n.jsx(rs,{})}),n.jsx(Be,{path:"/:table",element:n.jsx(rs,{})}),n.jsx(Be,{path:"/",element:n.jsx(rs,{})})]})})})]}),n.jsxs("nav",{"aria-label":"Tables",className:`relative border-r border-border overflow-hidden min-h-0 ${e?"":"hidden"} md:block`,children:[n.jsx(nr,{section:"Table List",children:n.jsx(Rl,{})}),n.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize table list",tabIndex:0,"data-testid":"sidebar-resize-handle",className:"absolute inset-y-0 right-0 w-1.5 cursor-col-resize select-none touch-none hover:bg-primary/40 focus-visible:bg-primary/60 focus-visible:outline-none",onPointerDown:r.onPointerDown,onKeyDown:r.onKeyDown})]}),n.jsxs("main",{className:"flex flex-col overflow-hidden min-h-0 px-1 py-0.5",children:[n.jsx(nr,{section:"Data Panel",children:n.jsxs(lr,{children:[n.jsx(Be,{path:"/:table/from/:filterTable/:id/edit/:editId",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/from/:filterTable/:id",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/:id/edit/:editId",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/:id",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/edit/:editId",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/edit",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/",element:n.jsx(Kd,{})})]})}),n.jsx(nr,{section:"Data Edit",children:n.jsxs(lr,{children:[n.jsx(Be,{path:"/:table/from/:filterTable/:id/edit/:editId",element:n.jsx(Xn,{})}),n.jsx(Be,{path:"/:table/:id/edit/:editId",element:n.jsx(Xn,{})}),n.jsx(Be,{path:"/:table/edit/:editId",element:n.jsx(Xn,{})}),n.jsx(Be,{path:"/:table/edit",element:n.jsx(Xn,{})})]})})]})]})})})}function Qd({onLocate:e}){const t=ps();return u.useEffect(()=>{e?.(t)},[t,e]),n.jsx(Jd,{})}function ya({uri:e,fetcher:t,uiPath:r,onLocate:s,showStats:o=!1,tables:i,defaultColumns:a,trailingColumns:l,tableActions:c}){const m=u.useMemo(()=>t||(e?new ys(e):null),[e,t]),d=u.useMemo(()=>({showStats:o,tables:i,defaultColumns:a,trailingColumns:l,tableActions:c}),[o,i,a,l,c]),f=u.useMemo(()=>new de.QueryClient({defaultOptions:{queries:{staleTime:300*1e3,retry:1}}}),[]);if(!m)throw new Error("Editor requires either a `fetcher` (GraphQLFetcher) or a `uri` prop to reach the GraphQL endpoint; neither was provided.");return n.jsx(de.QueryClientProvider,{client:f,children:n.jsx(js,{value:m,children:n.jsx(Ja,{config:d,children:n.jsx(No,{children:n.jsx(Ma,{path:r||"/",children:n.jsx(Ns,{children:n.jsx(Qd,{onLocate:s})})})})})})})}const Hd=["query","form","report","dashboard"];class va extends Error{constructor(t){super(t),this.name="SavedObjectConflictError"}}const ja="/_saved-objects";function Ud(e=""){const t=`${e}${ja}`,r=encodeURIComponent;async function s(o){try{return(await o.json())?.error??`${o.status} ${o.statusText}`}catch{return`${o.status} ${o.statusText}`}}return{async list(o,i,a){const l=o?`${t}/${r(o)}`:t,c=await fetch(l,{signal:i});if(!c.ok)throw new Error(`Failed to list saved objects: ${await s(c)}`);const m=await c.json();if(!Array.isArray(m))throw new Error("Failed to list saved objects: the server did not return a list.");const d=m.map(rr),f=d.filter(p=>p!==null);return f.length!==d.length&&a?.(d.length-f.length),f},async get(o,i,a){const l=await fetch(`${t}/${r(o)}/${r(i)}`,{signal:a});if(l.status===404)return null;if(!l.ok)throw new Error(`Failed to load saved object: ${await s(l)}`);return rr(await l.json())},async put(o,i){const a=await fetch(`${t}/${r(o.type)}/${r(o.id)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:i});if(a.status===409)throw new va(await s(a));if(!a.ok)throw new Error(`Failed to save object: ${await s(a)}`);const l=rr(await a.json());if(l===null)throw new Error("Server returned a malformed saved object.");return l},async remove(o,i,a){const l=await fetch(`${t}/${r(o)}/${r(i)}`,{method:"DELETE",signal:a});if(!l.ok&&l.status!==404)throw new Error(`Failed to delete saved object: ${await s(l)}`)}}}function rr(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.id!="string"||t.id.length===0||typeof t.type!="string"||!Hd.includes(t.type)||typeof t.name!="string"||typeof t.version!="number"||!("definition"in t)?null:{id:t.id,type:t.type,name:t.name,folder:typeof t.folder=="string"?t.folder:void 0,definition:t.definition,version:t.version}}const Yd=4,Rd=new Set(["text","textarea","number","checkbox","date","datetime","select"]);function Xd(e){return typeof e=="string"&&Rd.has(e)?e:"text"}function Zd(e){return typeof e!="number"||!Number.isFinite(e)?1:Math.min(Yd,Math.max(1,Math.trunc(e)))}function em(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.column!="string"||t.column===""?null:{column:t.column,label:typeof t.label=="string"?t.label:t.column,control:Xd(t.control),readOnly:t.readOnly===!0,required:t.required===!0,include:t.include!==!1}}function tm(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.relationship!="string"||typeof t.childTable!="string"||!Array.isArray(t.parentColumns)||!Array.isArray(t.childColumns)||!t.parentColumns.every(r=>typeof r=="string")||!t.childColumns.every(r=>typeof r=="string")||t.parentColumns.length===0||t.parentColumns.length!==t.childColumns.length?null:{relationship:t.relationship,childTable:t.childTable,parentColumns:t.parentColumns,childColumns:t.childColumns,label:typeof t.label=="string"?t.label:t.childTable,mode:t.mode==="stacked"?"stacked":"grid"}}function nm(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.table!="string"||t.table===""||!Array.isArray(t.fields))return null;const r=t.fields.map(em).filter(s=>s!==null);return r.length===0?null:{table:t.table,title:typeof t.title=="string"?t.title:t.table,columns:Zd(t.columns),fields:r,subforms:Array.isArray(t.subforms)?t.subforms.map(tm).filter(s=>s!==null):void 0}}function wa(e){return e.fields.filter(t=>t.include)}const rm=new Set(["text","textarea","number","checkbox","date","datetime","select"]);function sm(e){return e!==void 0&&rm.has(e)?e:void 0}function om(e,t){return{control:sm(t?.widget)??e.control,readOnly:e.readOnly||t?.readOnly===!0,visible:e.include&&t?.visible!==!1}}function am(e){switch(e){case"textarea":return{kind:"textarea"};case"checkbox":return{kind:"checkbox"};case"select":return{kind:"select"};case"number":return{kind:"input",type:"number"};case"date":return{kind:"input",type:"date"};case"datetime":return{kind:"input",type:"datetime-local"};default:return{kind:"input",type:"text"}}}function Ca(e,t,r){const s=Math.max(0,t-1);switch(r){case"first":return 0;case"last":return s;case"prev":return Math.max(0,Math.min(s,e-1));case"next":return Math.max(0,Math.min(s,e+1))}}function sr(e,t,r){return Ca(e,t,r)!==e}function im(e,t){return t<=0?"0 of 0":`${e+1} of ${t}`}function lm(e,t,r){return r.sourceColumnNames.length>0&&r.sourceColumnNames.length===r.destinationColumnNames.length&&r.sourceColumnNames.every(s=>e.columns.some(o=>o.name===s))&&r.destinationColumnNames.every(s=>t.columns.some(o=>o.name===s))}function cm(e,t,r,s){if(!s||!lm(e,t,r))return null;const o=[],i=[],a={};for(let l=0;l<r.sourceColumnNames.length;l++){const c=r.sourceColumnNames[l],m=r.destinationColumnNames[l],d=s[c];if(d==null)return null;const f=t.columns.find(x=>x.name===m)?.paramType.replace("!","")??"String",p=`parent_${c}`;o.push(`$${p}: ${f}`),i.push(`{${m}: {_eq: $${p}}}`),a[p]=dt(d,f)}return{params:o,filter:i.length===1?i[0]:`{and: [${i.join(", ")}]}`,variables:a}}function um(e,t){return!t||e.sourceColumnNames.length!==e.destinationColumnNames.length?{}:Object.fromEntries(e.destinationColumnNames.map((r,s)=>[r,t[e.sourceColumnNames[s]]]))}function dm(e){return{table:e.name,title:e.label,columns:1,fields:e.columns.map(t=>({column:t.name,label:t.label,control:t.paramType.startsWith("Boolean")?"checkbox":t.paramType.startsWith("Int")||t.paramType.startsWith("Float")||t.paramType.startsWith("Decimal")?"number":"text",readOnly:t.isReadOnly||t.isIdentity,required:!t.isNullable,include:!0}))}}function mm({parent:e,child:t,subform:r,row:s}){const o=$e(),i=de.useQueryClient(),a=Qn(t),[l,c]=u.useState(null),m=u.useMemo(()=>({name:r.relationship,fieldName:r.relationship,sourceColumnNames:r.parentColumns,destinationTable:t.name,destinationColumnNames:r.childColumns}),[r,t.name]),d=u.useMemo(()=>cm(e,t,m,s),[e,t,m,s]),f=u.useMemo(()=>t.columns.map(w=>(je(w.name,"form subform field"),w.name)),[t]),p=u.useMemo(()=>d?(je(t.name,"form subform table"),`query FormSubform_${t.name}(${d.params.join(", ")}) { ${t.name}(filter: ${d.filter}) { data { ${f.join(" ")} } } }`):null,[t.name,f,d]),x=["formSubform",e.name,t.name,He(s,e,0)],{data:h,isLoading:y,error:N}=de.useQuery({queryKey:x,queryFn:()=>o.query(p,d.variables),enabled:!!p}),T=u.useMemo(()=>dm(t),[t]),k=u.useMemo(()=>um(m,s),[m,s]);if(!d)return n.jsx("p",{style:lt.notice,children:"Related records unavailable: this relationship is incomplete."});if(y)return n.jsxs("p",{style:lt.notice,children:["Loading ",r.label,"…"]});if(N)return n.jsxs("p",{role:"alert",style:lt.error,children:["Failed to load ",r.label,": ",N.message]});const $=h?.[t.name]?.data??[],b=async w=>{const F=mt(w,t);F&&(await a.deleteRow(F),await i.invalidateQueries({queryKey:x}))},v=async()=>{c(null),await i.invalidateQueries({queryKey:x})};return n.jsxs("section",{style:lt.root,"aria-label":r.label,children:[n.jsx("h3",{style:lt.title,children:r.label}),n.jsxs("button",{type:"button",onClick:()=>c({kind:"create"}),children:["Add ",r.label]}),l?n.jsx("div",{style:lt.childForm,children:n.jsx(os,{table:t,definition:T,hiddenFields:r.childColumns,initialValues:l.kind==="create"?k:void 0,startInNewMode:l.kind==="create",initialPkRoute:l.kind==="edit"?He(l.row,t,l.index??0):void 0,onClose:()=>{v()}},l.kind==="create"?"create":He(l.row,t,l.index??0))}):$.length===0?n.jsx("p",{style:lt.notice,children:"No related records."}):r.mode==="grid"?n.jsxs("table",{style:lt.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[t.columns.map(w=>n.jsx("th",{style:lt.cell,children:w.label},w.name)),n.jsx("th",{})]})}),n.jsx("tbody",{children:$.map((w,F)=>n.jsxs("tr",{children:[t.columns.map(j=>n.jsx("td",{style:lt.cell,children:String(w[j.name]??"")},j.name)),n.jsxs("td",{children:[n.jsx("button",{type:"button",onClick:()=>c({kind:"edit",row:w,index:F}),children:"Edit"}),n.jsx("button",{type:"button",onClick:()=>b(w),disabled:a.isPending,children:"Delete"})]})]},He(w,t,F)))})]}):n.jsx("div",{children:$.map((w,F)=>n.jsxs("article",{style:lt.card,children:[t.columns.map(j=>n.jsxs("div",{children:[n.jsxs("strong",{children:[j.label,": "]}),String(w[j.name]??"")]},j.name)),n.jsx("button",{type:"button",onClick:()=>c({kind:"edit",row:w,index:F}),children:"Edit"}),n.jsx("button",{type:"button",onClick:()=>b(w),disabled:a.isPending,children:"Delete"})]},He(w,t,F)))})]})}const lt={root:{marginTop:20,borderTop:"1px solid #d1d5db",paddingTop:12},title:{margin:"0 0 8px",fontSize:15},notice:{color:"#6b7280",fontSize:13},error:{color:"#b91c1c",fontSize:13},table:{width:"100%",borderCollapse:"collapse",fontSize:13},cell:{textAlign:"left",padding:5,borderBottom:"1px solid #e5e7eb"},card:{border:"1px solid #e5e7eb",borderRadius:6,padding:8,marginBottom:8,fontSize:13},childForm:{minHeight:420,border:"1px solid #e5e7eb",borderRadius:6,marginTop:8}},fm={};function pm(e){const t=e.lastIndexOf(".");return t>=0?e.slice(t+1):e}function ss(e,t){const r=e.findTable(t);if(r)return r;const s=pm(t);return e.data.find(o=>o.graphQlName===t||o.dbName===t||o.graphQlName===s||o.dbName===s)}const hm="\0new";function gm(e,t){const r=new Set;for(const s of e)r.add(s.column.name);for(const s of t.primaryKeys??[])r.add(s);return[...r]}function xm(e,t){je(e.name,"form browse table name");for(const r of t)je(r,"form browse selection field");return`query FormBrowse_${e.name}($limit: Int, $offset: Int) { ${e.name}(limit: $limit offset: $offset) { total data { ${t.join(" ")} } } }`}function or(e,t,r){return e==="checkbox"?!!r:(e==="date"||e==="datetime")&&(r==null||typeof r=="string")?Br(r??void 0,e==="datetime"||Yn(t)&&!1):r==null?"":String(r)}function bm(e,t){const r={fields:{},form:null},s=e?.errors;if(Array.isArray(s)){const o=[];for(const i of s){const a=i.path?.[i.path.length-1];typeof a=="string"&&t.has(a)?r.fields[a]=i.message:o.push(i.message)}return r.form=o.length>0?o.join("; "):null,r}return r.form=e instanceof Error?e.message:String(e),r}function os({table:e,definition:t,fieldMetadata:r,onClose:s,schema:o,initialValues:i=fm,hiddenFields:a=[],startInNewMode:l=!1,initialPkRoute:c}){const m=$e(),d=de.useQueryClient(),f=u.useMemo(()=>new Map(e.columns.map(O=>[O.name,O])),[e]),[p,x]=u.useState(c?{kind:"pk",route:c}:{kind:"offset",index:0}),[h,y]=u.useState(l?"new":"browse"),[N,T]=u.useState(i),[k,$]=u.useState({}),[b,v]=u.useState(null),[w,F]=u.useState(""),[j,V]=u.useState(0),S=h==="new",L=u.useMemo(()=>wa(t).map(O=>{const Z=f.get(O.column);if(!Z)return null;const ee=om(O,r?.[O.column]);return ee.visible?{field:O,column:Z,control:ee.control,readOnly:ee.readOnly}:null}).filter(O=>O!==null),[t,f,r]),A=u.useCallback(O=>!(O.readOnly||O.column.isReadOnly||O.column.isIdentity||O.column.isPrimaryKey&&!S),[S]),D=u.useMemo(()=>L.filter(A).map(O=>({column:O.column})),[L,A]),B=u.useMemo(()=>(e.primaryKeys??[]).map(O=>f.get(O)).filter(O=>!!O),[e,f]),X=u.useMemo(()=>new Set(D.map(O=>O.column.name)),[D]),E=u.useMemo(()=>{const O=new Set(gm(L,e));for(const Z of t.subforms??[])for(const ee of Z.parentColumns)O.add(ee);return[...O]},[L,e,t.subforms]),P=u.useMemo(()=>{if(S||L.length===0)return null;if(p.kind==="offset")return{text:xm(e,E),variables:{limit:1,offset:p.index},kind:"offset"};const O=fn(p.route,e),Z=O?qn(O,e):null;return Z?{text:Cr(e,Z,E),variables:Z.variables,kind:"pk"}:null},[S,L.length,p,e,E]),{data:q,isLoading:U,error:_}=de.useQuery({queryKey:["formRunner",e.name,p,S],queryFn:()=>m.query(P.text,P.variables),enabled:!S&&P!==null}),ce=u.useMemo(()=>!q||!P?null:P.kind==="offset"?q[e.name]?.data?.[0]??null:q.value?.data?.[0]??null,[q,P,e.name]);u.useEffect(()=>{if(q&&P?.kind==="offset"){const O=q[e.name];O&&V(O.total)}},[q,P,e.name]);const he=S?hm:ce?He(ce,e,0):null,Ue=u.useRef(null),Pe=u.useRef(!1);u.useEffect(()=>{if(Ue.current===he&&Pe.current)return;if(Ue.current=he,Pe.current=!1,$({}),v(null),S){T(i);return}const O={};for(const Z of L)O[Z.column.name]=ce?.[Z.column.name]??null;T(O)},[he,ce,S,L,i]);const ie=p.kind==="offset"?p.index:-1,se=u.useMemo(()=>S||!ce?"":He(ce,e,ie<0?0:ie),[S,ce,e,ie]),ke=wn(e,D,B,se),Ae=Qn(e),re=u.useCallback(O=>{y("browse"),x(Z=>{const ee=Z.kind==="offset"?Z.index:0;return{kind:"offset",index:Ca(ee,j,O)}})},[j]),Ee=u.useCallback(()=>{y("new")},[]),Ie=u.useCallback(()=>{const O=w.trim();O!==""&&(y("browse"),x({kind:"pk",route:O}))},[w]),Le=u.useCallback((O,Z)=>{Pe.current=!0,T(ee=>({...ee,[O]:Z}))},[]),Ge=u.useCallback(async()=>{const O={};for(const ee of L){if(!A(ee))continue;const Ce=ee.field.required||!ee.column.isNullable,xe=qr(ee.column,N[ee.column.name],Ce);xe&&(O[ee.column.name]=xe)}if(Object.keys(O).length>0){$(O),v(null);return}$({}),v(null);const Z={};for(const ee of X)Z[ee]=N[ee];try{if(S){const Ce=(await ke.insert(Z))?.[e.name],xe={},qe=e.primaryKeys??[];for(const W of qe){const me=f.get(W);xe[W]=qe.length===1&&me?.isIdentity?Ce:N[W]}y("browse"),x({kind:"pk",route:Vn(xe,e)})}else await ke.update(Z),Pe.current=!1,await d.invalidateQueries({queryKey:["formRunner",e.name]})}catch(ee){const Ce=bm(ee,X);$(Ce.fields),v(Ce.form)}},[L,A,N,X,S,ke,e,f,d]),Oe=u.useCallback(async()=>{const O=mt(ce,e);if(O)try{await Ae.deleteRow(O),y("browse"),x({kind:"offset",index:Math.max(0,(ie<0?0:ie)-1)}),await d.invalidateQueries({queryKey:["formRunner",e.name]})}catch(Z){v(Z instanceof Error?Z.message:String(Z))}},[ce,e,Ae,ie,d]);if(L.length===0)return n.jsx("div",{style:fe.notice,children:"This form has no fields that match the current schema."});const ye=p.kind==="pk"?`key ${p.route}`:im(ie,j),ze=!S&&p.kind==="offset"&&j===0&&!U;return n.jsxs("div",{style:fe.root,children:[n.jsxs("div",{style:fe.toolbar,role:"toolbar","aria-label":"Record navigation",children:[n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("first"),disabled:S||!sr(ie,j,"first"),"aria-label":"First record",children:"⏮"}),n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("prev"),disabled:S||!sr(ie,j,"prev"),"aria-label":"Previous record",children:"◀"}),n.jsx("span",{style:fe.position,"aria-label":"Record position",children:S?"New record":ye}),n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("next"),disabled:S||!sr(ie,j,"next"),"aria-label":"Next record",children:"▶"}),n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("last"),disabled:S||!sr(ie,j,"last"),"aria-label":"Last record",children:"⏭"}),n.jsx("span",{style:fe.spacer}),n.jsx("input",{style:fe.jump,value:w,onChange:O=>F(O.target.value),placeholder:"Jump to key…","aria-label":"Jump to key"}),n.jsx("button",{type:"button",style:fe.btn,onClick:Ie,"aria-label":"Go to key",children:"Go"}),n.jsx("button",{type:"button",style:fe.btn,onClick:Ee,"aria-label":"New record",children:"New"}),s&&n.jsx("button",{type:"button",style:fe.btn,onClick:s,"aria-label":"Close form",children:"✕"})]}),n.jsxs("div",{style:fe.body,children:[n.jsx("h2",{style:fe.title,children:t.title}),b&&n.jsx("div",{role:"alert",style:fe.formError,children:b}),_&&n.jsxs("div",{role:"alert",style:fe.formError,children:["Failed to load record: ",_.message]}),ze?n.jsx("p",{style:fe.notice,children:"No records. Use “New” to create one."}):n.jsx("div",{style:{...fe.grid,gridTemplateColumns:`repeat(${t.columns}, minmax(0, 1fr))`},children:L.filter(O=>!a.includes(O.column.name)).map(O=>{const Z=A(O),ee=N[O.column.name],Ce=k[O.column.name],xe=O.field.required||!O.column.isNullable;return n.jsxs("label",{style:fe.field,children:[n.jsxs("span",{style:fe.label,children:[O.field.label,xe&&n.jsx("span",{style:fe.req,children:" *"})]}),ym(O,ee,Z,xe,Le),Ce&&n.jsx("span",{role:"alert",style:fe.fieldError,children:Ce})]},O.column.name)})}),!S&&ce&&o&&(t.subforms??[]).map(O=>{const Z=ss(o,O.childTable);return Z?n.jsx(mm,{parent:e,child:Z,subform:O,row:ce},O.relationship):n.jsxs("p",{style:fe.notice,children:[O.label," is not available in this schema."]},O.relationship)})]}),n.jsxs("div",{style:fe.footer,children:[n.jsx("button",{type:"button",style:fe.primaryBtn,onClick:Ge,disabled:ke.isPending||ze&&!S,children:S?"Create":"Save"}),!S&&!ze&&n.jsx("button",{type:"button",style:fe.btn,onClick:Oe,disabled:Ae.isPending,children:"Delete"})]})]})}function ym(e,t,r,s,o){const i=e.column.name,a=am(e.control),l={id:i,"aria-label":e.field.label,disabled:!r,style:fe.control};if(a.kind==="checkbox")return n.jsx("input",{...l,type:"checkbox",checked:!!or("checkbox",e.column,t),onChange:c=>o(i,c.target.checked)});if(a.kind==="textarea")return n.jsx("textarea",{...l,rows:3,required:s,value:String(or("text",e.column,t)),onChange:c=>o(i,c.target.value)});if(a.kind==="select"){const c=e.column.enumValues??[],m=e.column.enumLabels&&e.column.enumLabels.length===c.length?e.column.enumLabels:c;return n.jsxs("select",{...l,value:String(or("text",e.column,t)),onChange:d=>o(i,d.target.value===""?null:d.target.value),children:[!s&&n.jsx("option",{value:"",children:"(none)"}),c.map((d,f)=>n.jsx("option",{value:d,children:m[f]??d},d))]})}return n.jsx("input",{...l,type:a.type,required:s,value:String(or(e.control,e.column,t)),onChange:c=>o(i,c.target.value)})}function Na({definition:e,fieldMetadata:t,onClose:r}){const s=Je();if(s.loading)return n.jsx("div",{style:fe.notice,children:"Loading schema…"});if(s.error)return n.jsxs("div",{style:fe.notice,children:["Could not load schema: ",s.error.message]});const o=ss(s,e.table);return o?n.jsx(os,{table:o,definition:e,fieldMetadata:t,onClose:r,schema:s}):n.jsxs("div",{style:fe.notice,children:["Table “",e.table,"” is not in the current schema."]})}const fe={root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},toolbar:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",borderBottom:"1px solid var(--border, #d1d5db)",flexWrap:"wrap"},position:{fontSize:13,color:"#374151",minWidth:80,textAlign:"center"},spacer:{flex:1},jump:{padding:"4px 6px",border:"1px solid var(--border, #d1d5db)",borderRadius:6,font:"inherit",fontSize:13,width:120},body:{flex:1,minHeight:0,overflow:"auto",padding:16},title:{margin:"0 0 16px",fontSize:18},grid:{display:"grid",gap:14,maxWidth:720},field:{display:"flex",flexDirection:"column",gap:4,minWidth:0},label:{fontSize:12,fontWeight:600,color:"#374151"},control:{padding:"6px 8px",border:"1px solid var(--border, #d1d5db)",borderRadius:6,font:"inherit",fontSize:13},footer:{display:"flex",gap:8,padding:"8px 12px",borderTop:"1px solid var(--border, #d1d5db)"},btn:{border:"1px solid var(--border, #d1d5db)",background:"transparent",borderRadius:6,padding:"6px 12px",cursor:"pointer",font:"inherit"},primaryBtn:{border:"1px solid #2563eb",background:"#2563eb",color:"#fff",borderRadius:6,padding:"6px 16px",cursor:"pointer",font:"inherit"},req:{color:"#dc2626"},formError:{background:"#fef2f2",border:"1px solid #fecaca",color:"#b91c1c",borderRadius:6,padding:"8px 10px",marginBottom:12,fontSize:13},fieldError:{color:"#dc2626",fontSize:12},notice:{padding:24,color:"#6b7280"}};function vm({fetcher:e,definition:t,fieldMetadata:r,onClose:s}){const o=u.useMemo(()=>new de.QueryClient({defaultOptions:{queries:{staleTime:3e5,retry:1}}}),[]);return n.jsx(de.QueryClientProvider,{client:o,children:n.jsx(js,{value:e,children:n.jsx(No,{children:n.jsx(Ns,{children:n.jsx(Na,{definition:t,fieldMetadata:r,onClose:s})})})})})}ae.DEFAULT_ROW_CAP=Pr,ae.Editor=ya,ae.FormRunner=Na,ae.FormRunnerHost=vm,ae.FormRunnerView=os,ae.GraphQLRequestError=bs,ae.HttpGraphQLFetcher=ys,ae.SAVED_OBJECTS_PATH=ja,ae.SavedObjectConflictError=va,ae.UTF8_BOM=bo,ae.buildCsv=yo,ae.buildJson=wo,ae.createSavedObjectsClient=Ud,ae.default=ya,ae.deserializeColumnFilters=jr,ae.downloadTextFile=Mr,ae.exportAllRows=_r,ae.filenameFor=Dr,ae.formatCsvCell=Er,ae.mimeFor=zr,ae.parseFormDefinition=nm,ae.parseSavedObject=rr,ae.resolveDefinitionTable=ss,ae.serializeColumnFilters=vr,ae.useTableMutation=wn,ae.visibleFields=wa,Object.defineProperties(ae,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));