@objectstack/console 7.7.0 → 7.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. package/dist/assets/{ApiConsolePage-C8YrK4Z2.js → ApiConsolePage-CWTG8Xo7.js} +1 -1
  2. package/dist/assets/{AppManagementPage-B_5Fa-DJ.js → AppManagementPage-GNlxvYjB.js} +1 -1
  3. package/dist/assets/{ComponentNavView-BzBKVw0V.js → ComponentNavView-BSO_oEuH.js} +1 -1
  4. package/dist/assets/{ConsoleFloatingChatbot-iFC0LZXD.js → ConsoleFloatingChatbot-CqIHTEt8.js} +1 -1
  5. package/dist/assets/{FlowRunsPage-vNJ-LHl4.js → FlowRunsPage--fqUTSur.js} +1 -1
  6. package/dist/assets/{PublicFormsPage-BV_uZLQO.js → PublicFormsPage-BYCoo2T3.js} +1 -1
  7. package/dist/assets/{SystemHubPage-DnzWHWwD.js → SystemHubPage-CrPlzy52.js} +1 -1
  8. package/dist/assets/data-adapter-ByiC1zK-.js +1 -0
  9. package/dist/assets/{index-DFCyFV4X.js → index-DKok_mql.js} +6 -6
  10. package/dist/assets/{plugin-calendar-BFas9fSm.js → plugin-calendar-C-9OPJzZ.js} +1 -1
  11. package/dist/assets/{plugin-gantt-B6c7-NaD.js → plugin-gantt-QTyZ46KN.js} +1 -1
  12. package/dist/assets/plugin-grid-CIlCwKyp.js +6 -0
  13. package/dist/assets/{plugin-kanban-CYoyum5o.js → plugin-kanban-B-o9RSK7.js} +1 -1
  14. package/dist/assets/{plugin-report-I3m5_ooy.js → plugin-report-AhX1YoV8.js} +1 -1
  15. package/dist/assets/{plugin-timeline-CQbcDFeM.js → plugin-timeline-Dju0mfv_.js} +1 -1
  16. package/dist/assets/{plugin-view-CpsHblZK.js → plugin-view-DF7-Dd3a.js} +1 -1
  17. package/dist/assets/{plugins-views-BUSRnnI0.js → plugins-views-rCdZtRbk.js} +1 -1
  18. package/dist/index.html +1 -1
  19. package/package.json +1 -1
  20. package/dist/assets/data-adapter-DnBY1kLN.js +0 -1
  21. package/dist/assets/plugin-grid-Dnbdtwqg.js +0 -6
@@ -1 +0,0 @@
1
- import{f as e}from"./vendor-objectstack-DCNcl1ou.js";import{ut as t}from"./framework-Bg_8y02a.js";var n=class{cache;inflight;maxSize;ttl;stats;constructor(e={}){this.cache=new Map,this.inflight=new Map,this.maxSize=e.maxSize||100,this.ttl=e.ttl||300*1e3,this.stats={hits:0,misses:0,evictions:0,coalesced:0}}async get(e,t){let n=Date.now(),r=this.cache.get(e);if(r){if(n-r.timestamp<this.ttl)return r.accessCount++,r.lastAccessed=n,this.stats.hits++,this.cache.delete(e),this.cache.set(e,r),r.data;this.cache.delete(e)}let i=this.inflight.get(e);if(i)return this.stats.coalesced++,i;this.stats.misses++;let a=(async()=>{try{let n=await t();return this.set(e,n),n}finally{this.inflight.delete(e)}})();return this.inflight.set(e,a),a}prime(e,t){this.set(e,t)}set(e,t){let n=Date.now();this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictLRU(),this.cache.set(e,{data:t,timestamp:n,accessCount:1,lastAccessed:n})}evictLRU(){let e=this.cache.keys().next().value;e!==void 0&&(this.cache.delete(e),this.stats.evictions++)}invalidate(e){e?this.cache.delete(e):this.cache.clear()}clear(){this.cache.clear(),this.inflight.clear(),this.stats={hits:0,misses:0,evictions:0,coalesced:0}}getStats(){let e=this.stats.hits+this.stats.misses,t=e>0?this.stats.hits/e:0;return{size:this.cache.size,maxSize:this.maxSize,hits:this.stats.hits,misses:this.stats.misses,evictions:this.stats.evictions,coalesced:this.stats.coalesced,hitRate:t}}getCachedSync(e){let t=this.cache.get(e);if(t){if(this.ttl>0&&Date.now()-t.timestamp>this.ttl){this.cache.delete(e);return}return this.cache.delete(e),this.cache.set(e,t),this.stats.hits++,t.data}}has(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>=this.ttl?(this.cache.delete(e),!1):!0:!1}},r=class extends Error{code;statusCode;details;constructor(e,t,n,r){super(e),this.code=t,this.statusCode=n,this.details=r,this.name=`ObjectStackError`,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,details:this.details,stack:this.stack}}},i=class extends r{constructor(e,t){super(`Metadata not found for object: ${e}`,`METADATA_NOT_FOUND`,404,{objectName:e,...t}),this.name=`MetadataNotFoundError`}},a=class extends r{successCount;failureCount;errors;constructor(e,t,n,r,i){super(`Bulk ${e} operation failed: ${t} succeeded, ${n} failed`,`BULK_OPERATION_ERROR`,500,{operation:e,successCount:t,failureCount:n,errors:r,...i}),this.successCount=t,this.failureCount=n,this.errors=r,this.name=`BulkOperationError`}getSummary(){let e=this.successCount+this.failureCount,t=e>0?this.failureCount/e:0;return{operation:this.details?.operation,total:e,successful:this.successCount,failed:this.failureCount,failureRate:t,errors:this.errors}}},o=class extends r{url;constructor(e,t,n,r){super(`Connection error: ${e}`,`CONNECTION_ERROR`,r||503,{url:t,...n}),this.url=t,this.name=`ConnectionError`}},s=class extends r{constructor(e=`Authentication failed`,t,n){super(e,`AUTHENTICATION_ERROR`,n||401,t),this.name=`AuthenticationError`}},c=class extends r{field;validationErrors;constructor(e,t,n,r){super(e,`VALIDATION_ERROR`,400,{field:t,validationErrors:n,...r}),this.field=t,this.validationErrors=n,this.name=`ValidationError`}getValidationErrors(){return this.validationErrors||[]}};function l(e,t){let n=e?.status||e?.statusCode||500,a=e?.message||e?.statusText||`Unknown error`,l={context:t,response:{status:n,data:e?.data,headers:e?.headers}};switch(n){case 401:return new s(a,l,401);case 403:return new s(a,l,403);case 404:return t?.includes(`metadata`)||t?.includes(`schema`)||t?.includes(`getObjectSchema`)?new i(u(t),l):new r(a,`NOT_FOUND`,404,l);case 400:return new c(a,void 0,e?.data?.errors,l);case 503:return new o(a,e?.config?.url,l,503);case 504:return new o(a,e?.config?.url,l,504);default:return new r(a,`UNKNOWN_ERROR`,n,l)}}function u(e){if(!e)return`unknown`;let t=e.match(/\(([^)]+)\)/);return t?t[1]:`unknown`}var d=`sys_user_preference`;function f(e){let{dataSource:t,userId:n,key:r,resource:i=d,onError:a=()=>{}}=e,o=null,s=async()=>{let e={$filter:{user_id:n,key:r},$top:1};return((await t.find(i,e))?.data??[]).find(e=>{if(!e)return!1;let t=e.user_id!==void 0&&e.user_id!==n,i=e.key!==void 0&&e.key!==r;return!t&&!i})??null},c=e=>{if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return[]};return{async load(){try{let e=await s();return e?(e.id!==void 0&&e.id!==null&&(o=e.id),c(e.value)):(o=null,[])}catch(e){return a(`load`,e),[]}},async save(e){try{let c=new Date().toISOString();if(o!==null)try{await t.update(i,o,{value:e,updated_at:c});return}catch(e){o=null,a(`save`,e)}let l=await s();if(l&&l.id!==void 0&&l.id!==null){o=l.id,await t.update(i,l.id,{value:e,updated_at:c});return}let u=(await t.create(i,{user_id:n,key:r,value:e,updated_at:c}))?.id;u!=null&&(o=u)}catch(e){a(`save`,e)}}}}var p=`/meta`,m=`/api/v1`;function h(e){let t=e.baseUrl.replace(/\/+$/,``),n=e.environmentId?`${m}/environments/${encodeURIComponent(e.environmentId)}${p}`:`${m}${p}`;return/\/api\/v\d+$/i.test(t)?`${t.replace(/\/api\/v\d+$/i,``)}${e.environmentId?`${m}/environments/${encodeURIComponent(e.environmentId)}${p}`:`${m}${p}`}`:`${t}${n}`}async function g(e){let t;try{t=await e.json()}catch{t=await e.text().catch(()=>void 0)}let n=(t&&typeof t==`object`&&`error`in t?String(t.error):void 0)??`Metadata request failed: ${e.status} ${e.statusText}`,r=Error(n);return r.status=e.status,r.body=t,t&&typeof t==`object`&&`code`in t&&(r.code=String(t.code)),r}var _=class e{base;fetchImpl;headers;constructor(e){this.base=h(e),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.headers={Accept:`application/json`,...e.headers??{}}}withEnvironment(t){return new e({baseUrl:this.base.replace(/\/api\/v\d+(?:\/environments\/[^/]+)?\/meta$/,``).replace(/\/+$/,``),environmentId:t,fetch:this.fetchImpl,headers:this.headers})}async listTypes(){let e=await this.fetchImpl(this.base,{method:`GET`,headers:this.headers,cache:`no-store`});if(!e.ok)throw await g(e);let t=await e.json();return Array.isArray(t)?t:t&&Array.isArray(t.entries)?t.entries:t&&Array.isArray(t.items)?t.items:t&&Array.isArray(t.types)?t.types.map(e=>({type:e})):[]}async list(e,t={}){let n=t.packageId?`?package=${encodeURIComponent(t.packageId)}`:``,r=`${this.base}/${encodeURIComponent(e)}${n}`,i=await this.fetchImpl(r,{method:`GET`,headers:this.headers,cache:`no-store`});if(!i.ok)throw await g(i);let a=await i.json();return Array.isArray(a)?a:a&&Array.isArray(a.items)?a.items:[]}async get(e,t,n={}){let r=n.state===`draft`?`?state=draft`:``,i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${r}`,a=await this.fetchImpl(i,{method:`GET`,headers:this.headers,cache:`no-store`});if(a.status===404)return null;if(!a.ok)throw await g(a);return await a.json()}async getDraft(e,t){return this.get(e,t,{state:`draft`})}async save(e,t,n,r={}){let i=[];r.force&&i.push(`force=true`),r.mode===`draft`&&i.push(`mode=draft`),r.packageId&&i.push(`package=${encodeURIComponent(r.packageId)}`);let a=i.length?`?${i.join(`&`)}`:``,o=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${a}`,s={...this.headers,"Content-Type":`application/json`};r.ifMatch&&(s[`If-Match`]=r.ifMatch),r.actor&&(s[`X-Actor`]=r.actor);let c=await this.fetchImpl(o,{method:`PUT`,headers:s,body:JSON.stringify(n)});if(!c.ok)throw await g(c);return await c.json()}async layered(e,t){let n=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}?layers=true`,r=await this.fetchImpl(n,{method:`GET`,headers:this.headers,cache:`no-store`});if(r.status===404)return{code:null,overlay:null,overlayScope:null,effective:null};if(!r.ok)throw await g(r);let i=await r.json();return i&&(`code`in i||`overlay`in i||`effective`in i)?{code:i.code??null,overlay:i.overlay??null,overlayScope:i.overlayScope??null,effective:i.effective??null,...i._diagnostics?{_diagnostics:i._diagnostics}:{},...i.lock===void 0?{}:{lock:i.lock},...i.lockReason===void 0?{}:{lockReason:i.lockReason},...i.lockSource===void 0?{}:{lockSource:i.lockSource},...i.lockDocsUrl===void 0?{}:{lockDocsUrl:i.lockDocsUrl},...i.provenance===void 0?{}:{provenance:i.provenance},...i.packageId===void 0?{}:{packageId:i.packageId},...i.packageVersion===void 0?{}:{packageVersion:i.packageVersion},...i.editable===void 0?{}:{editable:i.editable},...i.deletable===void 0?{}:{deletable:i.deletable},...i.resettable===void 0?{}:{resettable:i.resettable}}:{code:null,overlay:null,overlayScope:null,effective:i}}async diagnostics(e={}){let t=[];e.type&&t.push(`type=${encodeURIComponent(e.type)}`),e.severity&&t.push(`severity=${encodeURIComponent(e.severity)}`),e.packageId&&t.push(`package=${encodeURIComponent(e.packageId)}`);let n=t.length?`?${t.join(`&`)}`:``,r=`${this.base}/diagnostics${n}`,i=await this.fetchImpl(r,{method:`GET`,headers:this.headers,cache:`no-store`});if(i.status===404)return{entries:[],total:0,scannedTypes:0,scannedItems:0,stats:{}};if(!i.ok)throw await g(i);let a=await i.json();return{entries:Array.isArray(a.entries)?a.entries:[],total:typeof a.total==`number`?a.total:0,scannedTypes:typeof a.scannedTypes==`number`?a.scannedTypes:0,scannedItems:typeof a.scannedItems==`number`?a.scannedItems:0,stats:a.stats&&typeof a.stats==`object`?a.stats:{}}}async references(e,t){let n=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/references`,r=await this.fetchImpl(n,{method:`GET`,headers:this.headers,cache:`no-store`});if(r.status===404)return[];if(!r.ok)throw await g(r);let i=await r.json();return Array.isArray(i)?i:i?.items??[]}async reset(e,t,n={}){let r=n.state===`draft`?`?state=draft`:``,i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${r}`,a={...this.headers};n.ifMatch&&(a[`If-Match`]=n.ifMatch),n.actor&&(a[`X-Actor`]=n.actor);let o=await this.fetchImpl(i,{method:`DELETE`,headers:a});if(!o.ok)throw await g(o);return await o.json()}async publish(e,t,n={}){let r=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/publish`,i={...this.headers,"Content-Type":`application/json`};n.actor&&(i[`X-Actor`]=n.actor);let a=await this.fetchImpl(r,{method:`POST`,headers:i,body:JSON.stringify(n.message?{message:n.message}:{})});if(!a.ok)throw await g(a);return await a.json()}async rollback(e,t,n,r={}){let i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/rollback`,a={...this.headers,"Content-Type":`application/json`};r.actor&&(a[`X-Actor`]=r.actor);let o=await this.fetchImpl(i,{method:`POST`,headers:a,body:JSON.stringify({toVersion:n,...r.message?{message:r.message}:{}})});if(!o.ok)throw await g(o);return await o.json()}async diff(e,t,n,r){let i=new URLSearchParams;n!==void 0&&i.set(`from`,String(n)),r!==void 0&&i.set(`to`,String(r));let a=i.toString(),o=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/diff${a?`?${a}`:``}`,s=await this.fetchImpl(o,{method:`GET`,headers:this.headers,cache:`no-store`});if(!s.ok)throw await g(s);return await s.json()}async history(e,t,n={}){let r=new URLSearchParams;n.sinceSeq!==void 0&&r.set(`sinceSeq`,String(n.sinceSeq)),n.limit!==void 0&&r.set(`limit`,String(n.limit));let i=r.toString(),a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/history${i?`?${i}`:``}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(!o.ok)throw await g(o);return await o.json()}async audit(e,t,n={}){let r=new URLSearchParams;n.limit!==void 0&&r.set(`limit`,String(n.limit));let i=r.toString(),a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/audit${i?`?${i}`:``}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(!o.ok)throw await g(o);return await o.json()}},v={equals:`=`,eq:`=`,"==":`=`,not_equals:`!=`,notequals:`!=`,ne:`!=`,greater_than:`>`,greaterthan:`>`,gt:`>`,greater_than_or_equal:`>=`,greater_than_or_equals:`>=`,greaterthanorequal:`>=`,gte:`>=`,less_than:`<`,lessthan:`<`,lt:`<`,less_than_or_equal:`<=`,less_than_or_equals:`<=`,lessthanorequal:`<=`,lte:`<=`,in:`in`,not_in:`nin`,notin:`nin`,nin:`nin`,contains:`contains`,not_contains:`notcontains`,notcontains:`notcontains`,starts_with:`startswith`,startswith:`startswith`,ends_with:`endswith`,endswith:`endswith`,between:`between`,is_null:`isnull`,isnull:`isnull`,is_not_null:`isnotnull`,isnotnull:`isnotnull`};function y(e){return typeof e==`string`?v[e.toLowerCase()]??v[e]??e:null}function b(e){if(!e||typeof e!=`object`)return null;let t=e.field??e.name,n=y(e.operator??e.op??`=`);return!t||!n?null:[String(t),n,e.value]}function x(e){if(e!=null){if(Array.isArray(e)){if(e.length===0)return;let t=e[0];if(e.length>0&&typeof t==`object`&&t&&!Array.isArray(t)&&t.field!==void 0){let t=e.map(e=>b(e)).filter(e=>e!==null);return t.length===0?void 0:t.length===1?t[0]:[`and`,...t]}return e}if(typeof e==`object`)return Object.keys(e).length===0?void 0:e}}var S=new Map;async function C(e,t){let n=e||`<default>`,r=S.get(n);if(r)return r;let i=t().catch(e=>{throw S.delete(n),e});return S.set(n,i),i}function w(e){if(!e||typeof e!=`object`)return!1;let t=e;if(t.httpStatus===404||t.status===404||t.statusCode===404)return!0;let n=typeof t.code==`string`?t.code:``;return n===`object_not_found`||n===`record_not_found`}var T=class extends Error{code=`CONCURRENT_UPDATE`;httpStatus=409;currentVersion;currentRecord;constructor(e){super(e.message??`Record was modified by another user`),this.name=`ConcurrentUpdateError`,this.currentVersion=e.currentVersion,this.currentRecord=e.currentRecord}};function E(e){if(!e||typeof e!=`object`)return e;let t=e;if(t.code!==`CONCURRENT_UPDATE`&&t.httpStatus!==409||t.code!==`CONCURRENT_UPDATE`)return e;let n=t.details??{};return new T({currentVersion:typeof n.currentVersion==`string`?n.currentVersion:null,currentRecord:n.currentRecord??null,message:typeof t.message==`string`?t.message:void 0})}function D(){let e=e=>{if(!e||typeof e!=`object`)return!1;if(e.status===404||e.statusCode===404)return!0;let t=e.error;if(t&&typeof t==`object`){let e=t.code;if(e===`object_not_found`||e===`record_not_found`)return!0}return!1},t={debug:(e,t)=>console.debug(e,t??``),info:(e,t)=>console.info(e,t??``),warn:(e,t)=>console.warn(e,t??``),error:(t,n,r)=>{if(e(r)){console.debug(`[ObjectStack] ${t} (suppressed expected 404)`,r);return}console.error(t,n??``,r??``)},fatal:(e,t,n)=>console.error(e,t??``,n??``),log:(e,...t)=>console.log(e,...t),child:()=>t,withTrace:()=>t};return t}function O(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(O).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${O(t[e])}`).join(`,`)}}`}var k=class{client;connected=!1;connectPromise=null;metadataCache;connectionState=`disconnected`;connectionStateListeners=[];batchProgressListeners=[];autoReconnect;maxReconnectAttempts;reconnectDelay;reconnectAttempts=0;baseUrl;token;fetchImpl;inflightFinds=new Map;missingResources=new Set;constructor(t){this.client=new e({...t,logger:D()}),this.metadataCache=new n(t.cache),this.autoReconnect=t.autoReconnect??!0,this.maxReconnectAttempts=t.maxReconnectAttempts??3,this.reconnectDelay=t.reconnectDelay??1e3,this.baseUrl=t.baseUrl,this.token=t.token,this.fetchImpl=t.fetch||globalThis.fetch.bind(globalThis)}async connect(){if(!this.connected)return this.connectPromise?this.connectPromise:(this.setConnectionState(`connecting`),this.connectPromise=(async()=>{try{let e=this.baseUrl||``,t=e?`${e.replace(/\/$/,``)}/api/v1/discovery`:`/api/v1/discovery`,n=await C(e,async()=>{let e=await this.fetchImpl(t,{method:`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`}:void 0});if(!e.ok)throw Error(`discovery ${e.status} ${e.statusText}`);let n=await e.json();return n&&typeof n.success==`boolean`&&`data`in n?n.data:n});this.client.discoveryInfo=n,this.connected=!0,this.reconnectAttempts=0,this.setConnectionState(`connected`)}catch(e){let t=new o(e instanceof Error?e.message:`Failed to connect to ObjectStack server`,void 0,{originalError:e});if(this.setConnectionState(`error`,t),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts)await this.attemptReconnect();else throw t}finally{this.connectPromise=null}})(),this.connectPromise)}async attemptReconnect(){this.reconnectAttempts++,this.setConnectionState(`reconnecting`);let e=this.reconnectDelay*2**(this.reconnectAttempts-1);await new Promise(t=>setTimeout(t,e)),this.connected=!1,await this.connect()}getConnectionState(){return this.connectionState}isConnected(){return this.connected&&this.connectionState===`connected`}onConnectionStateChange(e){return this.connectionStateListeners.push(e),()=>{let t=this.connectionStateListeners.indexOf(e);t>-1&&this.connectionStateListeners.splice(t,1)}}onBatchProgress(e){return this.batchProgressListeners.push(e),()=>{let t=this.batchProgressListeners.indexOf(e);t>-1&&this.batchProgressListeners.splice(t,1)}}setConnectionState(e,t){this.connectionState=e;let n={state:e,timestamp:Date.now(),error:t};this.connectionStateListeners.forEach(e=>{try{e(n)}catch(e){console.error(`Error in connection state listener:`,e)}})}emitBatchProgress(e){this.batchProgressListeners.forEach(t=>{try{t(e)}catch(e){console.error(`Error in batch progress listener:`,e)}})}async find(e,t){if(this.missingResources.has(e))return{data:[],total:0};let n=`${e}::${O(t)}`,r=this.inflightFinds.get(n);if(r)return r;let i=(async()=>{if(await this.connect(),t?.$expand&&t.$expand.length>0){let n=await this.rawFindWithPopulate(e,t);return this.normalizeQueryResult(n,t)}let n=this.convertQueryParams(t);try{let r=await this.client.data.find(e,n);return this.normalizeQueryResult(r,t)}catch(t){if(w(t))return this.missingResources.add(e),{data:[],total:0};throw t}})();this.inflightFinds.set(n,i);let a=()=>{this.inflightFinds.get(n)===i&&this.inflightFinds.delete(n)};return i.then(a,a),i}async findOne(e,t,n){if(await this.connect(),n?.$expand&&n.$expand.length>0)try{let r={...n,$filter:{id:String(t)},$top:1},i=await this.rawFindWithPopulate(e,r);if(Array.isArray(i))return i[0]||null;let a=i;return(a.records||a.value||[])[0]||null}catch(e){if(w(e))return null}try{return(await this.client.data.get(e,String(t))).record}catch(e){if(w(e))return null;throw e}}async create(e,t){return await this.connect(),(await this.client.data.create(e,t)).record}async update(e,t,n,r){await this.connect();try{return(await this.client.data.update(e,String(t),n,r?.ifMatch?{ifMatch:r.ifMatch}:void 0)).record}catch(e){throw E(e)}}async delete(e,t,n){await this.connect();try{return(await this.client.data.delete(e,String(t),n?.ifMatch?{ifMatch:n.ifMatch}:void 0)).deleted}catch(e){throw E(e)}}async bulkUpdate(e,t,n){if(await this.connect(),!t||t.length===0)return 0;let r=t.map(e=>({id:String(e),data:n})),i=this.client.data.updateMany;if(typeof i==`function`)try{let n=await i(e,r,{continueOnError:!0});return n&&typeof n==`object`&&typeof n.succeeded==`number`?n.succeeded:Array.isArray(n)?n.length:t.length}catch(e){throw E(e)}let a=0;for(let r of t)try{await this.client.data.update(e,String(r),n),a++}catch{}return a}async bulkDelete(e,t){if(await this.connect(),!t||t.length===0)return 0;let n=t.map(e=>String(e)),r=this.client.data.deleteMany;if(typeof r==`function`)try{let t=await r(e,n,{continueOnError:!0});return t&&typeof t==`object`&&typeof t.succeeded==`number`?t.succeeded:Array.isArray(t)?t.length:n.length}catch(e){throw E(e)}let i=0;for(let t of n)try{await this.client.data.delete(e,t),i++}catch{}return i}async bulk(e,t,n){if(await this.connect(),!n||n.length===0)return[];let i=n.length,o=0,s=0,c=()=>{this.emitBatchProgress({operation:t,total:i,completed:o,failed:s,percentage:i>0?(o+s)/i*100:0})};try{switch(t){case`create`:{c();let t=await this.client.data.createMany(e,n);return o=t.length,s=i-o,c(),t}case`delete`:{let t=n.map(e=>e.id).filter(Boolean);if(t.length===0){let e=n.map((e,t)=>({index:t,error:`Missing ID for item at index ${t}`}));throw s=n.length,c(),new a(`delete`,0,n.length,e)}return c(),await this.client.data.deleteMany(e,t),o=t.length,s=i-o,c(),[]}case`update`:{if(typeof this.client.data.updateMany==`function`)try{c();let t=this.client.data.updateMany,r=await t(e,n);return o=r.length,s=i-o,c(),r}catch{}let t=[],r=[];for(let i=0;i<n.length;i++){let a=n[i],l=a.id;if(!l){r.push({index:i,error:`Missing ID`}),s++,c();continue}try{let n=await this.client.data.update(e,String(l),a);t.push(n.record),o++,c()}catch(e){let t=e instanceof Error?e.message:String(e);r.push({index:i,error:t}),s++,c()}}if(r.length>0)throw new a(`update`,t.length,r.length,r,{resource:e,totalRecords:n.length});return t}default:throw new r(`Unsupported bulk operation: ${t}`,`UNSUPPORTED_OPERATION`,400)}}catch(i){if(c(),i instanceof a||i instanceof r)throw i;let o=i instanceof Error?i.message:String(i),s=n.map((e,t)=>({index:t,error:o}));throw new a(t,0,n.length,s,{resource:e,originalError:i})}}normalizeQueryResult(e,t){if(Array.isArray(e))return{data:e,total:e.length,page:1,pageSize:e.length,hasMore:!1};let n=e,r=n.records||n.value||[];return{data:r,total:n.total??n.count??r.length,page:t?.$skip&&t.$top?Math.floor(t.$skip/t.$top)+1:1,pageSize:t?.$top,hasMore:t?.$top?r.length===t.$top:!1}}async rawFindWithPopulate(e,t){let n=new URLSearchParams;if(t.$expand&&t.$expand.length>0&&n.set(`populate`,t.$expand.join(`,`)),t.$top!==void 0&&n.set(`top`,String(t.$top)),t.$skip!==void 0&&n.set(`skip`,String(t.$skip)),t.$select&&t.$select.length>0){let e=t.$select.includes(`id`)?t.$select:[`id`,...t.$select];n.set(`select`,e.join(`,`))}if(t.$orderby)if(Array.isArray(t.$orderby)){let e=t.$orderby.map(e=>{if(typeof e==`string`)return e;let t=e.field;return(e.order||`asc`)===`desc`?`-${t}`:t}).join(`,`);n.set(`sort`,e)}else{let e=Object.entries(t.$orderby).map(([e,t])=>t===`desc`?`-${e}`:e).join(`,`);n.set(`sort`,e)}if(t.$filter!==void 0&&t.$filter!==null){let e=x(t.$filter);e!==void 0&&n.set(`filter`,JSON.stringify(e))}let r=this.baseUrl.replace(/\/$/,``),i=n.toString(),a=`${r}${/\/api\/v\d+$/i.test(r)?`/data`:`/api/v1/data`}/${e}${i?`?${i}`:``}`,o={"Content-Type":`application/json`};this.token&&(o.Authorization=`Bearer ${this.token}`);let s=await this.fetchImpl(a,{method:`GET`,headers:o});if(!s.ok){let e=await s.json().catch(()=>({message:s.statusText})),t=Error(e?.error?.message||e?.message||s.statusText);throw t.status=s.status,t}let c=await s.json();return c&&typeof c.success==`boolean`&&`data`in c?c.data:c}convertQueryParams(e){if(!e)return{};let n={};if(e.$select&&(n.select=e.$select.includes(`id`)?e.$select:[`id`,...e.$select]),e.$filter!==void 0&&e.$filter!==null&&!(Array.isArray(e.$filter)?e.$filter.length===0:typeof e.$filter==`object`&&Object.keys(e.$filter).length===0))if(Array.isArray(e.$filter))if(e.$filter.length>0&&typeof e.$filter[0]==`object`&&!Array.isArray(e.$filter[0])&&e.$filter[0].field!==void 0){let t=e.$filter.map(e=>b(e)).filter(e=>e!==null);t.length===0||(t.length===1?n.filters=t[0]:n.filters=[`and`,...t])}else n.filters=e.$filter;else n.filters=t(e.$filter);return e.$orderby&&(Array.isArray(e.$orderby)?n.sort=e.$orderby.map(e=>{if(typeof e==`string`)return e;let t=e.field;return(e.order||`asc`)===`desc`?`-${t}`:t}):n.sort=Object.entries(e.$orderby).map(([e,t])=>t===`desc`?`-${e}`:e)),e.$skip!==void 0&&(n.skip=e.$skip),e.$top!==void 0&&(n.top=e.$top),n}async getObjectSchema(e){await this.connect();try{return await this.metadataCache.get(e,async()=>{let t=await this.client.meta.getItem(`object`,e);return t&&t.item?t.item:t})}catch(t){let n=t;throw w(n)?new i(e,{originalError:t}):t instanceof r?t:l(n,`getObjectSchema(${e})`)}}getClient(){return this.client}async getDiscovery(){try{return await this.connect(),this.client.discoveryInfo||null}catch{return null}}async listViewOverrides(e){await this.connect();try{let t=`view-overrides:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItems(e),n=Array.isArray(t?.items)?t.items:[],r={};for(let e of n){if(!e||typeof e!=`object`)continue;let t=e.name??e.id??e._name;typeof t==`string`&&t&&(r[t]=e)}return r})}catch{return{}}}async getView(e,t){await this.connect();try{let n=`view:${e}:${t}`;return await this.metadataCache.get(n,async()=>{let n=await this.client.meta.getItem(e,t);return n&&n.item?n.item:n??null})}catch{return null}}async updateViewConfig(e,t,n){await this.connect();try{let r={...n||{},object:n?.object||e,name:t},i=await this.client.meta.saveItem(`view`,t,r),a=`view:${e}:${t}`;return this.metadataCache.invalidate?.(a),this.metadataCache.invalidate?.(`view-overrides:${e}`),this.metadataCache.invalidate?.(`views:${e}`),i&&i.item?i.item:i??void 0}catch(e){throw e}}async listViews(e){await this.connect();try{let t=await this.client.meta.getItems(`view`),n=Array.isArray(t?.items)?t.items:Array.isArray(t)?t:[],r=new Set([`form`,`detail`]);return n.filter(t=>{if(!t)return!1;let n=t.list??t;if((n?.data?.object??n?.object??n?.objectName)!==e)return!1;let i=t.viewKind??n?.viewKind;return!(i&&r.has(i))}).map(e=>{let t=e.list??e;return t&&t.config&&typeof t.config==`object`?{...t.config,name:t.name??t.config.name,label:t.label??t.config.label,isDefault:!!t.isDefault}:t})}catch(e){return console.warn(`[OBJECTSTACKDataSource] listViews failed:`,e),[]}}async createView(e,t){await this.connect();let n=String(t?.name||``).trim();if(!n){let r=String(t?.label||e||`view`).toLowerCase().replace(/[^a-z0-9_]+/g,`_`).replace(/^_+|_+$/g,``).slice(0,40);(!r||/^[0-9]/.test(r))&&(r=r?`view_${r}`:`view`);let i=Date.now().toString(36);n=`${r}_${i}`}let r={...t,name:n,object:t?.object||e,data:t?.data||{provider:`object`,object:e}};try{let t=await this.client.meta.saveItem(`view`,n,r);return this.metadataCache.invalidate?.(`views:${e}`),t&&t.item?t.item:r}catch(e){throw e}}async updateView(e,t,n){await this.connect();let r={};try{let e=await this.client.meta.getItem(`view`,t);r=e&&(e.item||e)||{},r?.list&&(r=r.list)}catch{}let i={...r,...n,name:t,object:r?.object||r?.data?.object||e};try{let n=await this.client.meta.saveItem(`view`,t,i);return this.metadataCache.invalidate?.(`views:${e}`),this.metadataCache.invalidate?.(`view:${e}:${t}`),n&&n.item?n.item:i}catch(e){throw e}}async deleteView(e,t){await this.connect();try{let n=await this.client.meta.deleteItem(`view`,t);return this.metadataCache.invalidate?.(`views:${e}`),this.metadataCache.invalidate?.(`view:${e}:${t}`),{deleted:!!(n?.deleted??n?.reset??!0)}}catch(e){throw e}}async getApp(e){await this.connect();try{let t=`app:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItem(`apps`,e);return t&&t.item?t.item:t??null})}catch{return null}}async getPage(e){await this.connect();try{let t=`page:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItem(`pages`,e);return t&&t.item?t.item:t??null})}catch{return null}}async updateDashboard(e,t){await this.connect();try{let n=await this.client.meta.saveItem(`dashboard`,e,t);return this.metadataCache.invalidate?.(`dashboards`),this.metadataCache.invalidate?.(`dashboard:${e}`),n&&n.item?n.item:n??void 0}catch(e){throw e}}async aggregate(e,t){if(await this.connect(),t!=null&&(Array.isArray(t.groupBy)||Array.isArray(t.aggregations)||t.where!==void 0)){let n={};Array.isArray(t.groupBy)&&(n.groupBy=t.groupBy),Array.isArray(t.aggregations)&&(n.aggregations=t.aggregations),t.where!==void 0&&(n.where=t.where),typeof t.limit==`number`&&(n.limit=t.limit);let r=await this.client.data.query(e,n);return Array.isArray(r)?r:Array.isArray(r?.records)?r.records:Array.isArray(r?.data)?r.data:[]}try{let n=t.function===`count`?`count`:`${t.field}_${t.function}`,r={cube:e,measures:[n],dimensions:t.groupBy&&t.groupBy!==`_all`?[t.groupBy]:[]};t.filter&&(r.where=t.filter);let i=await this.client.analytics.query(r),a=Array.isArray(i)?i:i?.rows&&Array.isArray(i.rows)?i.rows:i?.data&&Array.isArray(i.data)?i.data:i?.data?.rows&&Array.isArray(i.data.rows)?i.data.rows:i?.results&&Array.isArray(i.results)?i.results:[];if(a.length>0&&a.every(e=>e==null?!0:!(n in e&&e[n]!=null||t.field in e&&e[t.field]!=null))){let n=(await this.find(e,t.filter?{$filter:t.filter}:void 0)).data||[];return n.length===0?[]:this.aggregateClientSide(n,t)}return a.map(e=>{let r={...e};return n!==t.field&&n in r&&(r[t.field]=r[n],delete r[n]),r})}catch{let n=(await this.find(e,t.filter?{$filter:t.filter}:void 0)).data||[];return n.length===0?[]:this.aggregateClientSide(n,t)}}aggregateClientSide(e,t){let{field:n,function:r,groupBy:i}=t,a={};for(let t of e){let e=String(t[i]??`Unknown`);a[e]||(a[e]=[]),a[e].push(t)}return Object.entries(a).map(([e,t])=>{let a=t.map(e=>Number(e[n])||0),o;switch(r){case`count`:o=t.length;break;case`avg`:o=a.length>0?a.reduce((e,t)=>e+t,0)/a.length:0;break;case`min`:o=a.length>0?Math.min(...a):0;break;case`max`:o=a.length>0?Math.max(...a):0;break;default:o=a.reduce((e,t)=>e+t,0);break}return{[i]:e,[n]:o}})}async getItems(e,t){return await this.connect(),await Promise.all(t.map(async t=>{let n=`${e}:${t}`;return this.metadataCache.get(n,async()=>{let n=await this.client.meta.getItem(e,t);return n&&n.item?n.item:n})}))}getCached(e){return this.metadataCache.getCachedSync(e)}getCacheStats(){return this.metadataCache.getStats()}invalidateCache(e){this.metadataCache.invalidate(e)}clearCache(){this.metadataCache.clear()}async uploadFile(e,t,n){await this.connect();let i=new FormData;i.append(`file`,t),n?.recordId&&i.append(`recordId`,n.recordId),n?.fieldName&&i.append(`fieldName`,n.fieldName),n?.metadata&&i.append(`metadata`,JSON.stringify(n.metadata));let a=`${this.baseUrl}/api/data/${encodeURIComponent(e)}/upload`,o=await fetch(a,{method:`POST`,body:i,headers:{...this.getAuthHeaders()}});if(!o.ok)throw new r((await o.json().catch(()=>({message:o.statusText}))).message||`Upload failed with status ${o.status}`,`UPLOAD_ERROR`,o.status);return o.json()}async uploadFiles(e,t,n){await this.connect();let i=new FormData;t.forEach((e,t)=>{i.append(`files`,e,e.name||`file-${t}`)}),n?.recordId&&i.append(`recordId`,n.recordId),n?.fieldName&&i.append(`fieldName`,n.fieldName),n?.metadata&&i.append(`metadata`,JSON.stringify(n.metadata));let a=`${this.baseUrl}/api/data/${encodeURIComponent(e)}/upload`,o=await fetch(a,{method:`POST`,body:i,headers:{...this.getAuthHeaders()}});if(!o.ok)throw new r((await o.json().catch(()=>({message:o.statusText}))).message||`Upload failed with status ${o.status}`,`UPLOAD_ERROR`,o.status);return o.json()}async cancelPendingApproval(e,t){await this.connect();let n=`${this.baseUrl}/api/v1/approvals/requests?recordId=${encodeURIComponent(t)}&object=${encodeURIComponent(e)}`,i=await this.fetchImpl(n,{method:`GET`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()}});if(!i.ok)throw new r(`Failed to look up approval requests (status ${i.status})`,`APPROVAL_LOOKUP_FAILED`,i.status);let a=await i.json().catch(()=>({})),o=(Array.isArray(a)?a:a?.data??[]).find(e=>e?.status===`pending`||e?.status===`in_approval`);if(!o?.id)throw new r(`No pending approval request found for this record`,`NO_PENDING_REQUEST`,404);let s=`${this.baseUrl}/api/v1/approvals/requests/${encodeURIComponent(o.id)}/recall`,c=await this.fetchImpl(s,{method:`POST`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()},body:JSON.stringify({})});if(!c.ok){let e=await c.json().catch(()=>({}));throw new r(e?.error||e?.message||`Recall failed with status ${c.status}`,e?.code||`APPROVAL_RECALL_FAILED`,c.status)}let l=await c.json().catch(()=>({}));return{requestId:o.id,status:l?.data?.request?.status??`recalled`}}getAuthHeaders(){let e={};return this.token&&(e.Authorization=`Bearer ${this.token}`),e}};export{_ as n,f as r,k as t};
@@ -1,6 +0,0 @@
1
- import{o as e,r as t}from"./rolldown-runtime-CMxvf4Kt.js";import{r as n,v as r,y as i}from"./vendor-react-BMpe6Iqg.js";import{D as a,H as o,I as s,L as c,N as l,Q as u,R as d,U as f,at as p,dt as m,ot as h,r as g}from"./framework-Bg_8y02a.js";import{$t as _,A as v,Ao as y,B as ee,Bn as b,Bt as x,Ci as S,D as C,Da as te,E as w,Fn as ne,Fr as re,Go as ie,Ht as T,In as ae,Jr as E,Ln as D,Mo as O,Mr as k,N as A,Pr as oe,Q as se,Qn as ce,Qs as le,Qt as ue,Rn as de,Rr as j,Rt as M,S as fe,Si as pe,Ti as me,Us as he,Ut as N,Vs as ge,Vt as P,Wr as _e,Xa as ve,Xt as F,Y as I,Yo as ye,Ys as L,Zt as be,a as xe,ai as Se,an as Ce,at as R,bs as we,c as Te,cn as z,cs as Ee,ct as De,en as Oe,f as ke,i as Ae,in as je,is as Me,it as Ne,kr as Pe,l as B,lt as Fe,m as Ie,mn as Le,mr as V,ns as H,on as Re,ot as ze,q as Be,r as Ve,ri as He,rt as Ue,s as We,st as Ge,us as Ke,wi as qe,xr as Je,yo as Ye,zn as U,zt as W}from"./ui-components-C7AytqY9.js";var G=e(i(),1),K={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},q=[`xs`,`sm`,`md`,`lg`,`xl`,`2xl`];function J(e){for(let t=q.length-1;t>=0;t--){let n=q[t];if(e>=K[n])return n}return`xs`}function Xe(){let[e,t]=(0,G.useState)(()=>typeof window<`u`?window.innerWidth:1024);(0,G.useEffect)(()=>{if(typeof window>`u`)return;let e,n=()=>{clearTimeout(e),e=setTimeout(()=>{t(window.innerWidth)},100)};return window.addEventListener(`resize`,n),()=>{clearTimeout(e),window.removeEventListener(`resize`,n)}},[]);let n=J(e),r=q.indexOf(n);return{breakpoint:n,width:e,isMobile:r<q.indexOf(`md`),isTablet:r>=q.indexOf(`md`)&&r<q.indexOf(`lg`),isDesktop:r>=q.indexOf(`lg`),isAbove:t=>e>=K[t],isBelow:t=>e<K[t]}}function Ze(e){let{onRefresh:t,threshold:n=80,enabled:r=!0}=e,i=(0,G.useRef)(null),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(0),l=(0,G.useRef)(0),u=(0,G.useCallback)(e=>{if(!r||a)return;let t=i.current;t&&t.scrollTop===0&&(l.current=e.touches[0].clientY)},[r,a]),d=(0,G.useCallback)(e=>{if(!r||a||!l.current)return;let t=e.touches[0].clientY-l.current;t>0&&c(Math.min(t,n*1.5))},[r,a,n]),f=(0,G.useCallback)(async()=>{if(!r||a)return;let e=s;if(c(0),l.current=0,e>=n){o(!0);try{await t()}finally{o(!1)}}},[r,a,s,n,t]);return(0,G.useEffect)(()=>{let e=i.current;if(!(!e||!r))return e.addEventListener(`touchstart`,u,{passive:!0}),e.addEventListener(`touchmove`,d,{passive:!0}),e.addEventListener(`touchend`,f,{passive:!0}),()=>{e.removeEventListener(`touchstart`,u),e.removeEventListener(`touchmove`,d),e.removeEventListener(`touchend`,f)}},[u,d,f,r]),{ref:i,isRefreshing:a,pullDistance:s}}var Y=n(),X=(0,G.createContext)(null);X.displayName=`MobileContext`;function Qe({pwa:e,offline:t,children:n}){let r=Xe(),i=(0,G.useMemo)(()=>({...r,pwa:e,offline:t}),[r,e,t]);return(0,Y.jsx)(X.Provider,{value:i,children:n})}var $e={red:`bg-red-100`,green:`bg-green-100`,blue:`bg-blue-100`,yellow:`bg-yellow-100`,orange:`bg-orange-100`,purple:`bg-purple-100`,pink:`bg-pink-100`,gray:`bg-gray-100`,grey:`bg-gray-100`,indigo:`bg-indigo-100`,teal:`bg-teal-100`,cyan:`bg-cyan-100`,amber:`bg-amber-100`,lime:`bg-lime-100`,emerald:`bg-emerald-100`,rose:`bg-rose-100`,sky:`bg-sky-100`,violet:`bg-violet-100`,fuchsia:`bg-fuchsia-100`,slate:`bg-slate-100`,zinc:`bg-zinc-100`,stone:`bg-stone-100`,neutral:`bg-neutral-100`};function Z(e){return e.startsWith(`bg-`)?e:$e[e.toLowerCase().trim()]}function et(e){return(0,G.useCallback)(t=>{if(!e?.field||!e.colors)return;let n=String(t[e.field]??``),r=e.colors[n];if(r)return Z(r)},[e?.field,e?.colors])}function tt(e){if(e==null||e===``)return``;if(Array.isArray(e))return e.map(e=>tt(e)).join(`|`);if(typeof e==`object`){let t=e.id??e._id??e.pk??e.value;if(t!=null&&t!==``)return String(t);let n=e.name??e.label??e.title;if(n!=null&&n!==``)return String(n);try{return JSON.stringify(e)}catch{return``}}return String(e)}function nt(e,t){return tt(e[t])}function rt(e,t,n){if(e==null||e===``)return`(empty)`;if(n){let r=n(t,e);if(r!==void 0&&r!==``)return r}if(Array.isArray(e))return e.map(e=>{if(n){let r=n(t,e);if(r!==void 0&&r!==``)return r}return rt(e,t)}).join(`, `)||`(empty)`;if(typeof e==`object`){let t=e.name??e.label??e.title??e.display_name??e.displayName??e.fullName??e.full_name;if(t!=null&&t!==``)return String(t);let n=e.id??e._id??e.pk;return n!=null&&n!==``?String(n):`(empty)`}return String(e)}function it(e,t){return t.map(({field:t,type:n})=>{if(n===`count_distinct`){let r=new Set;for(let n of e){let e=n[t];e!=null&&e!==``&&r.add(e)}return{field:t,type:n,value:r.size}}if(n===`count`)return{field:t,type:n,value:e.length};let r=e.map(e=>Number(e[t])).filter(e=>Number.isFinite(e)),i;switch(n){case`sum`:i=r.reduce((e,t)=>e+t,0);break;case`avg`:i=r.length>0?r.reduce((e,t)=>e+t,0)/r.length:0;break;case`min`:i=r.length>0?Math.min(...r):0;break;case`max`:i=r.length>0?Math.max(...r):0;break;default:i=0}return{field:t,type:n,value:i}})}function at(e,t,n){let r=e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`});return n===`desc`?-r:r}function ot(e,t,n,r){let i=e?.fields,a=!!(i&&i.length>0),[o,s]=(0,G.useState)({});return{groups:(0,G.useMemo)(()=>{if(!a||!i)return[];let e=(t,a,s)=>{if(a>=i.length)return[];let c=i[a],l=new Map,u=[];for(let e of t){let t=nt(e,c.field);l.has(t)||(l.set(t,{label:rt(e[c.field],c.field,r),rows:[]}),u.push(t)),l.get(t).rows.push(e)}let d=c.order??`asc`;return u.sort((e,t)=>at(l.get(e)?.label??e,l.get(t)?.label??t,d)),u.map(t=>{let r=l.get(t),u=s?`${s}__${a}:${t}`:`${a}:${t}`,d=!!c.collapsed,f=u in o?o[u]:d,p=n&&n.length>0?it(r.rows,n):[],m=a+1<i.length?e(r.rows,a+1,u):[];return{key:u,label:r.label,field:c.field,depth:a,rows:r.rows,collapsed:f,aggregations:p,subgroups:m}})};return e(t,0,``)},[t,i,a,o,n,r]),isGrouped:a,toggleGroup:(0,G.useCallback)(e=>{s(t=>{let n=e.split(`__`).pop()||``,r=/^(\d+):/.exec(n),a=r?Number(r[1]):0,o=!!i?.[a]?.collapsed;return{...t,[e]:t[e]===void 0?!o:!t[e]}})},[i])}}var st=({groupKey:e,label:t,count:n,collapsed:r,aggregations:i,fieldLabel:a,labelColorClass:o,onToggle:s,children:c})=>{let l=o?L(`inline-flex items-center rounded-md border px-2 py-0.5 text-xs font-medium`,o):`inline-flex items-center rounded-md bg-muted px-2 py-0.5 text-xs font-medium text-foreground`;return(0,Y.jsxs)(`div`,{"data-testid":`group-row-${e}`,className:`group/grouprow`,children:[a&&(0,Y.jsx)(`div`,{className:`px-1 pb-1 text-[11px] font-medium text-muted-foreground tracking-wide group-label-caption`,children:a}),(0,Y.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 px-1 py-1 text-sm text-left rounded-md hover:bg-muted/40 transition-colors`,onClick:()=>s(e),"aria-expanded":!r,children:[r?(0,Y.jsx)(Ee,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,Y.jsx)(Ke,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:L(l,`group-label`),children:t}),(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground tabular-nums group-count`,children:n}),i&&i.length>0&&(0,Y.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground group-aggregations`,children:i.map(e=>(0,Y.jsxs)(`span`,{className:`mr-2`,children:[e.type,`: `,Number.isInteger(e.value)?e.value:e.value.toFixed(2)]},`${e.field}-${e.type}`))})]}),!r&&(0,Y.jsx)(`div`,{className:`mt-1 ml-1.5 pl-3 border-l border-border/60`,children:c})]})};function ct(e){return typeof e==`string`?{type:e}:e}function lt(e,t){if(t.length===0)return null;switch(e){case`count`:return t.length;case`sum`:return t.reduce((e,t)=>e+t,0);case`avg`:return t.reduce((e,t)=>e+t,0)/t.length;case`min`:return Math.min(...t);case`max`:return Math.max(...t);default:return null}}function ut(e,t,n){if(t===null)return``;let r={count:`Count`,sum:`Sum`,avg:`Avg`,min:`Min`,max:`Max`}[e]||e,i=n?.type,a;if(e!==`count`&&i===`currency`){let e=n?.currency||n?.defaultCurrency,r=n?.precision??n?.scale??0;try{a=e?new Intl.NumberFormat(void 0,{style:`currency`,currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(t):new Intl.NumberFormat(void 0,{minimumFractionDigits:r,maximumFractionDigits:r}).format(t)}catch{a=t.toLocaleString()}}else if(e!==`count`&&i===`percent`){let e=n?.precision??0;a=`${(t>-1&&t<1?t*100:t).toFixed(e)}%`}else a=e===`avg`?t.toLocaleString(void 0,{maximumFractionDigits:2}):t.toLocaleString();return`${r}: ${a}`}function dt(e,t,n){return(0,G.useMemo)(()=>{let r=new Map;if(!e||e.length===0||t.length===0)return{summaries:r,hasSummary:!1};for(let i of e){if(!i.summary)continue;let e=ct(i.summary),a=e.field||i.field,o=[];for(let e of t){let t=e[a];if(t!=null&&typeof t==`number`&&!isNaN(t))o.push(t);else if(t!=null&&typeof t==`string`){let e=parseFloat(t);isNaN(e)||o.push(e)}}let s;if(e.type===`count`){let e=t.filter(e=>e[a]!=null&&e[a]!==``).length;s=e>0?e:null}else s=lt(e.type,o);let c=n?.[a],l={type:i.type??c?.type,currency:i.currency??c?.currency,defaultCurrency:i.defaultCurrency??c?.defaultCurrency,precision:i.precision??c?.precision,scale:i.scale??c?.scale};r.set(i.field,{field:i.field,value:s,label:ut(e.type,s,l)})}return{summaries:r,hasSummary:r.size>0}},[e,t,n])}var ft={"grid.openMenu":`Open menu`,"grid.edit":`Edit`,"grid.delete":`Delete`};function pt(){try{let{t:e}=g();return t=>{let n=e(t);return n===t?ft[t]??t:n}}catch{return e=>ft[e]??e}}function mt(e){return e.replace(/_/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}var ht=({def:e,row:t,onActionDef:n})=>{let r=c(s(e.visible),t);return e.visible&&!r?null:(0,Y.jsx)(z,{onClick:()=>n?.(e,t),"data-testid":`row-action-${e.name}`,className:e.variant===`danger`?`text-destructive focus:text-destructive`:void 0,children:e.label??mt(e.name)})},gt=({row:e,rowActions:t,rowActionDefs:n,canEdit:r,canDelete:i,onEdit:a,onDelete:o,onAction:s,onActionDef:c})=>{let l=pt();return(0,Y.jsxs)(Ce,{children:[(0,Y.jsx)(Le,{asChild:!0,children:(0,Y.jsxs)(V,{variant:`ghost`,size:`icon`,className:`h-8 w-8 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0`,"data-testid":`row-action-trigger`,children:[(0,Y.jsx)(y,{className:`h-4 w-4`}),(0,Y.jsx)(`span`,{className:`sr-only`,children:l(`grid.openMenu`)})]})}),(0,Y.jsxs)(Re,{align:`end`,onClick:e=>e.stopPropagation(),children:[r&&a&&(0,Y.jsxs)(z,{onClick:()=>a(e),children:[(0,Y.jsx)(He,{className:`mr-2 h-4 w-4`}),l(`grid.edit`)]}),i&&o&&(0,Y.jsxs)(z,{onClick:()=>o(e),children:[(0,Y.jsx)(j,{className:`mr-2 h-4 w-4`}),l(`grid.delete`)]}),n?.map(t=>(0,Y.jsx)(ht,{def:t,row:e,onActionDef:c},t.name)),t?.map(t=>(0,Y.jsx)(z,{onClick:()=>s?.(t,e),"data-testid":`row-action-${t}`,children:mt(t)},t))]})]})},_t=({selectedRows:e,actions:t,actionDefs:n,onAction:r,onActionDef:i,onClearSelection:a,pageSize:o,totalMatching:s,allMatchingSelected:c,onSelectAllMatching:l})=>{let u=Array.isArray(n)&&n.length>0,d=Array.isArray(t)&&t.length>0;return!u&&!d||e.length===0?null:(0,Y.jsxs)(`div`,{className:`border-t border-primary/30 px-4 py-2 flex flex-col gap-1.5 text-xs bg-primary/10 text-foreground shrink-0 shadow-sm motion-safe:animate-in motion-safe:slide-in-from-bottom-2 motion-safe:fade-in-0 motion-safe:duration-200`,role:`region`,"aria-label":`Bulk actions`,"data-testid":`bulk-actions-bar`,children:[(!c&&typeof s==`number`&&typeof o==`number`&&o>0&&e.length>=o&&s>o||c)&&(0,Y.jsx)(`div`,{className:`flex items-center gap-2 text-[11px] text-muted-foreground`,"data-testid":`bulk-cross-page-banner`,children:c?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Se,{className:`h-3 w-3 text-primary shrink-0`}),(0,Y.jsxs)(`span`,{children:[`All `,s,` matching records are selected.`]})]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`span`,{children:[`All `,o,` on this page are selected.`]}),(0,Y.jsxs)(`button`,{type:`button`,className:`font-medium text-primary underline-offset-2 hover:underline`,onClick:l,"data-testid":`bulk-select-all-matching`,children:[`Select all `,s,` matching`]})]})}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Y.jsx)(Se,{className:`h-3.5 w-3.5 text-primary shrink-0`}),(0,Y.jsx)(`span`,{className:`font-medium tabular-nums`,children:(0,Y.jsx)(`span`,{className:`inline-block motion-safe:animate-in motion-safe:zoom-in-90 motion-safe:duration-150`,children:c?`${s} items selected (all matches)`:`${e.length} ${e.length===1?`item`:`items`} selected`},c?`all-${s}`:e.length)}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5 ml-3`,children:[u&&n.map(t=>{let n=t.variant===`danger`||t.operation===`delete`,r=t.icon?I(t.icon):null;return(0,Y.jsxs)(V,{variant:n?`destructive`:`outline`,size:`sm`,className:`h-7 px-2.5 text-xs gap-1.5`,onClick:()=>i?.(t,e),"data-testid":`bulk-action-${t.name}`,children:[r?(0,Y.jsx)(Be,{name:r,className:`h-3 w-3`}):n?(0,Y.jsx)(j,{className:`h-3 w-3`}):null,t.label??mt(t.name)]},t.name)}),!u&&d&&t.map(t=>{let n=String(t).toLowerCase(),i=n.includes(`delete`)||n.includes(`remove`)||n.includes(`destroy`),a=i?j:null;return(0,Y.jsxs)(V,{variant:i?`destructive`:`outline`,size:`sm`,className:`h-7 px-2.5 text-xs gap-1.5`,onClick:()=>r?.(t,e),"data-testid":`bulk-action-${t}`,children:[a&&(0,Y.jsx)(a,{className:`h-3 w-3`}),mt(t)]},t)})]}),(0,Y.jsxs)(V,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs ml-auto gap-1`,onClick:a,children:[(0,Y.jsx)(Je,{className:`h-3 w-3`}),`Clear`]})]})]})};function vt({resource:e,dataSource:t}){let[n,r]=(0,G.useState)({total:0,done:0,failed:0,inFlight:!1}),[i,a]=(0,G.useState)(null),o=(0,G.useRef)([]),s=(0,G.useRef)(null),c=(0,G.useCallback)(()=>{r({total:0,done:0,failed:0,inFlight:!1}),a(null),o.current=[],s.current=null},[]);return{run:(0,G.useCallback)(async(n,i,c)=>{let l=i.length,d=Math.max(1,n.batchSize??200),f=[],p=0,m=0;a(null),r({total:l,done:0,failed:0,inFlight:!0});let h=()=>({...n.patch??{},...c}),g=[];if(n.operation===`update`){let e=Object.keys(h());for(let t of i){let n=String(t.id??``);if(!n)continue;let r={};for(let n of e)r[n]=t[n];g.push({id:n,prev:r})}}for(let a=0;a<i.length;a+=d){let o=i.slice(a,a+d),s=[];for(let e=0;e<o.length;e+=1){let t=o[e].id==null?``:String(o[e].id);t?s.push(t):(m+=1,f.push({id:`index_${a+e}`,error:`Missing record id`}))}if(s.length===0){r({total:l,done:p,failed:m,inFlight:!0});continue}let c=s.length>=2,g,_=`bulk`;n.operation===`update`&&typeof t.bulkUpdate==`function`?(g=n=>t.bulkUpdate(e,n,h()),_=`bulk update`):n.operation===`delete`&&typeof t.bulkDelete==`function`&&(g=n=>t.bulkDelete(e,n),_=`bulk delete`);let v=await u({ids:s,originalSize:o.length,offset:a,allowBulk:c,label:_},{bulkCall:g,perRow:r=>{switch(n.operation){case`delete`:return t.delete(e,r);case`update`:return t.update(e,r,h());case`custom`:return Promise.resolve();default:return Promise.reject(Error(`Unknown operation: ${n.operation}`))}}});p+=v.succeeded,m+=v.failed,f.push(...v.errors),r({total:l,done:p,failed:m,inFlight:!0})}let _={total:l,succeeded:p,failed:m,errors:f},v=new Set(f.map(e=>e.id));return o.current=g.filter(e=>!v.has(e.id)),s.current={def:n,rows:i,params:c},r({total:l,done:p,failed:m,inFlight:!1}),a(_),p>0&&w.invalidate(e),_},[e,t]),undo:(0,G.useCallback)(async()=>{let n=o.current;if(!n.length)return null;let i=n.length,s=[],c=0,l=0;a(null),r({total:i,done:0,failed:0,inFlight:!0}),(await Promise.allSettled(n.map(n=>t.update(e,n.id,n.prev)))).forEach((e,t)=>{e.status===`fulfilled`?c+=1:(l+=1,s.push({id:n[t].id,error:e.reason instanceof Error?e.reason.message:String(e.reason)}))});let u={total:i,succeeded:c,failed:l,errors:s};return o.current=[],r({total:i,done:c,failed:l,inFlight:!1}),a(u),u},[e,t]),retry:(0,G.useCallback)(async n=>{let r=s.current;if(!r||!r.rows.find(e=>String(e.id??``)===n))return!1;let i={...r.def.patch??{},...r.params};try{switch(r.def.operation){case`delete`:await t.delete(e,n);break;case`update`:await t.update(e,n,i);break;case`custom`:return!0;default:return!1}return a(e=>{if(!e)return e;let t=e.errors.filter(e=>e.id!==n);return{...e,errors:t,succeeded:e.succeeded+1,failed:Math.max(0,e.failed-1)}}),!0}catch{return!1}},[e,t]),progress:n,result:i,reset:c}}var yt=({def:e,rows:t,resource:n,dataSource:r,open:i,onClose:a,labelKey:o=`name`})=>{let s=e?.params??[],c=(0,G.useMemo)(()=>{let e={};for(let t of s)t.default!==void 0&&(e[t.name]=t.default);return e},[e?.name]),[l,u]=(0,G.useState)(`params`),[d,f]=(0,G.useState)(c),[p,m]=(0,G.useState)({}),{run:h,undo:g,retry:_,progress:v,result:y,reset:ee}=vt({resource:n,dataSource:r}),[x,S]=(0,G.useState)(null),[C,w]=(0,G.useState)(!1),[ie,T]=(0,G.useState)(null);(0,G.useEffect)(()=>{i&&(ee(),f(c),T(null),w(!1),S(null),u(s.length===0?`confirm`:`params`))},[i,e?.name,c,s.length,ee]),(0,G.useEffect)(()=>{if(!i||typeof r.find!=`function`)return;let e=s.filter(e=>e.type===`lookup`&&e.object&&!p[e.name]);if(e.length===0)return;let t=!1;return(async()=>{let n={};for(let t of e)try{let e=await r.find(t.object,{$top:200}),i=Array.isArray(e)?e:e?.data??[];n[t.name]=i.map(e=>({value:String(e.id??e._id??``),label:String(e.name??e.full_name??e.email??e.id??`(unnamed)`)})).filter(e=>e.value)}catch{n[t.name]=[]}t||m(e=>({...e,...n}))})(),()=>{t=!0}},[i,e?.name]);let E=(0,G.useMemo)(()=>{for(let e of s)if(e.required){let t=d[e.name];if(t==null||t===``)return!1}return!0},[s,d]),O=e?.maxRecords??1/0,k=t.length>O,A=(0,G.useCallback)(async()=>{e&&(u(`running`),await h(e,t,d),u(`result`))},[e,t,d,h]),oe=(0,G.useCallback)(()=>{if(!y?.errors?.length)return;let t=[`record_id,error_message`,...y.errors.map(e=>`${e.id},"${e.error.replace(/"/g,`""`)}"`)].join(`
2
- `),n=new Blob([t],{type:`text/csv;charset=utf-8`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`bulk_errors_${e?.name??`action`}_${Date.now()}.csv`,i.click(),URL.revokeObjectURL(r)},[y,e?.name]),se=!!e&&e.operation===`update`&&!!y&&y.succeeded>0&&ie===null,ce=(0,G.useCallback)(async()=>{w(!0);try{await g()&&T(Date.now())}finally{w(!1)}},[g]),le=(0,G.useCallback)(async e=>{S(e);try{await _(e)}finally{S(null)}},[_]);if(!e)return null;let ue=e.label??e.name,j=t.slice(0,5),M=Math.max(0,t.length-j.length);return(0,Y.jsx)(ne,{open:i,onOpenChange:e=>{e||a(y)},children:(0,Y.jsxs)(ae,{className:`max-w-md`,children:[(0,Y.jsxs)(U,{children:[(0,Y.jsxs)(b,{className:`flex items-center gap-2`,children:[l===`running`&&(0,Y.jsx)(te,{className:`h-4 w-4 animate-spin`}),ue]}),l===`confirm`&&(0,Y.jsx)(D,{children:e.confirmText??`This will apply to ${t.length} record${t.length===1?``:`s`}.`})]}),l===`params`&&(0,Y.jsx)(`div`,{className:`space-y-3`,children:s.map(e=>(0,Y.jsx)(bt,{param:e,value:d[e.name],lookupOptions:p[e.name],onChange:t=>f(n=>({...n,[e.name]:t}))},e.name))}),l===`confirm`&&(0,Y.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[k&&(0,Y.jsxs)(`div`,{className:`rounded-md bg-destructive/10 text-destructive px-3 py-2 flex items-start gap-2`,children:[(0,Y.jsx)(re,{className:`h-4 w-4 mt-0.5 shrink-0`}),(0,Y.jsxs)(`div`,{children:[`Selection (`,t.length,`) exceeds the action limit (`,O,`). Reduce the selection to proceed.`]})]}),(0,Y.jsxs)(`div`,{className:`text-muted-foreground`,children:[`Affected records (`,t.length,`):`]}),(0,Y.jsx)(N,{className:`max-h-32 rounded border bg-muted/30 p-2`,children:(0,Y.jsxs)(`ul`,{className:`text-xs space-y-1`,children:[j.map((e,t)=>(0,Y.jsxs)(`li`,{className:`truncate`,children:[`• `,String(e[o]??e.id??`Row ${t+1}`)]},String(e.id??t))),M>0&&(0,Y.jsxs)(`li`,{className:`text-muted-foreground`,children:[`… and `,M,` more`]})]})}),Object.keys(d).length>0&&(0,Y.jsx)(`div`,{className:`rounded border bg-muted/30 p-2 text-xs space-y-0.5`,children:Object.entries(d).map(([e,t])=>(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`span`,{className:`text-muted-foreground`,children:[e,`:`]}),` `,Q(t)]},e))})]}),l===`running`&&(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(F,{value:v.total?(v.done+v.failed)/v.total*100:0}),(0,Y.jsxs)(`div`,{className:`text-xs text-muted-foreground text-center`,children:[v.done+v.failed,` / `,v.total,` processed`,v.failed>0&&` · ${v.failed} failed`]})]}),l===`result`&&y&&(0,Y.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-2`,children:[y.failed===0?(0,Y.jsx)(H,{className:`h-5 w-5 text-emerald-500`}):(0,Y.jsx)(re,{className:`h-5 w-5 text-amber-500`}),(0,Y.jsxs)(`span`,{children:[ie===null?``:`Undone — `,`Succeeded `,y.succeeded,` / `,y.total,y.failed>0&&` · Failed ${y.failed}`]})]}),y.errors.length>0&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(N,{className:`max-h-48 rounded border bg-destructive/5 p-2`,"data-testid":`bulk-error-inspector`,children:(0,Y.jsx)(`ul`,{className:`text-xs space-y-1.5`,children:y.errors.map(t=>(0,Y.jsxs)(`li`,{className:`flex items-start gap-2`,"data-testid":`bulk-error-row-${t.id}`,children:[(0,Y.jsx)(ye,{className:`h-3 w-3 mt-0.5 shrink-0 text-destructive`}),(0,Y.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Y.jsxs)(`div`,{className:`truncate`,children:[(0,Y.jsxs)(`span`,{className:`text-muted-foreground`,children:[t.id,`:`]}),` `,t.error]})}),e.operation!==`custom`&&(0,Y.jsx)(V,{variant:`ghost`,size:`sm`,className:`h-5 px-1.5 text-[10px]`,onClick:()=>le(t.id),disabled:x===t.id,"data-testid":`bulk-error-retry-${t.id}`,children:x===t.id?`…`:`Retry`})]},t.id))})}),(0,Y.jsx)(V,{variant:`outline`,size:`sm`,onClick:oe,children:`Download error CSV`})]})]}),(0,Y.jsxs)(de,{children:[l===`params`&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(V,{variant:`ghost`,onClick:()=>a(),children:`Cancel`}),(0,Y.jsx)(V,{onClick:()=>u(`confirm`),disabled:!E,children:`Next`})]}),l===`confirm`&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(V,{variant:`ghost`,onClick:()=>s.length?u(`params`):a(),children:s.length?`Back`:`Cancel`}),(0,Y.jsx)(V,{variant:e.variant===`danger`?`destructive`:`default`,onClick:A,disabled:k,children:e.confirmLabel??`Run`})]}),l===`running`&&(0,Y.jsx)(V,{variant:`ghost`,disabled:!0,children:`Running…`}),l===`result`&&(0,Y.jsxs)(Y.Fragment,{children:[se&&(0,Y.jsx)(V,{variant:`outline`,onClick:ce,disabled:C,"data-testid":`bulk-undo-button`,children:C?`Undoing…`:`Undo`}),(0,Y.jsx)(V,{onClick:()=>a(y),children:`Done`})]})]})]})})};function Q(e){return e==null||e===``?`—`:typeof e==`boolean`?e?`Yes`:`No`:String(e)}var bt=({param:e,value:t,onChange:n,lookupOptions:r})=>{let i=`bulk-param-${e.name}`,a=(0,Y.jsxs)(je,{htmlFor:i,className:`text-xs`,children:[e.label??e.name,e.required&&(0,Y.jsx)(`span`,{className:`text-destructive ml-0.5`,children:`*`})]}),o=null;switch(e.type){case`boolean`:o=(0,Y.jsx)(Fe,{id:i,checked:!!t,onCheckedChange:n});break;case`textarea`:o=(0,Y.jsx)(se,{id:i,value:t??``,onChange:e=>n(e.target.value),placeholder:e.placeholder});break;case`select`:{let r=e.options??[];o=(0,Y.jsxs)(M,{value:t==null?``:String(t),onValueChange:n,children:[(0,Y.jsx)(P,{id:i,children:(0,Y.jsx)(T,{placeholder:e.placeholder??`Select…`})}),(0,Y.jsx)(W,{children:r.map(e=>(0,Y.jsx)(x,{value:String(e.value),children:e.label},String(e.value)))})]});break}case`lookup`:{let a=r??[];o=(0,Y.jsxs)(M,{value:t??``,onValueChange:n,children:[(0,Y.jsx)(P,{id:i,children:(0,Y.jsx)(T,{placeholder:a.length===0?`Loading…`:e.placeholder??`Select…`})}),(0,Y.jsx)(W,{children:a.map(e=>(0,Y.jsx)(x,{value:e.value,children:e.label},e.value))})]});break}case`number`:o=(0,Y.jsx)(Oe,{id:i,type:`number`,value:t??``,onChange:e=>n(e.target.value===``?void 0:Number(e.target.value)),placeholder:e.placeholder});break;default:o=(0,Y.jsx)(Oe,{id:i,type:`text`,value:t??``,onChange:e=>n(e.target.value),placeholder:e.placeholder})}return(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(`div`,{className:`flex items-center justify-between`,children:a}),o,e.help&&(0,Y.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e.help})]})},xt=({testId:e,onActivate:t,children:n})=>(0,Y.jsx)(`span`,{role:`link`,tabIndex:0,"data-testid":e,className:`text-primary font-medium underline-offset-4 hover:underline cursor-pointer truncate block max-w-full`,onClick:e=>{e.stopPropagation(),t()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),e.stopPropagation(),t())},children:n}),St={"grid.actions":`Actions`,"grid.edit":`Edit`,"grid.delete":`Delete`,"grid.export":`Export`,"grid.exportAs":`Export as {{format}}`,"grid.loading":`Loading grid...`,"grid.errorLoading":`Error loading grid`,"grid.pullToRefresh":`Pull to refresh`,"grid.refreshing":`Refreshing…`,"grid.openRecord":`Open record`,"grid.empty":`Empty`,"grid.yes":`Yes`,"grid.no":`No`,"grid.systemFields":`System`};function Ct(){try{let e=g();return e.t(`grid.actions`)===`grid.actions`?{t:(e,t)=>{let n=St[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n}}:{t:e.t}}catch{return{t:(e,t)=>{let n=St[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n}}}}function wt(e){if(e!=null)return typeof e==`string`?e:void 0}function Tt(e){return e.data?Array.isArray(e.data)?{provider:`value`,items:e.data}:e.data:e.staticData?{provider:`value`,items:e.staticData}:e.objectName?{provider:`object`,object:e.objectName}:null}function Et(e){if(!(!e||e.length===0))return typeof e[0]==`object`&&e[0],e}var Dt=({schema:e,dataSource:t,onEdit:n,onDelete:r,onBulkDelete:i,onRowSelect:s,onRowClick:c,onCellChange:u,onRowSave:f,onBatchSave:m,onAddRecord:g,...y})=>{let[b,x]=(0,G.useState)([]),[te,w]=(0,G.useState)(!0),[ne,re]=(0,G.useState)(null),{t:T}=Ct(),{fieldLabel:ae,translateOptions:D}=le(),[k,se]=(0,G.useState)(null),[de,j]=(0,G.useState)(!1),[M,pe]=(0,G.useState)(0),[he,N]=(0,G.useState)(!1),[ge,P]=(0,G.useState)(!1),F=fe({dataSource:t}),[I,ye]=(0,G.useState)(e.rowHeight??`compact`),[L,Ce]=(0,G.useState)([]),[R,z]=(0,G.useState)(!1),[Ee,De]=(0,G.useState)(void 0),[Oe,je]=(0,G.useState)(null),[Me,Ne]=(0,G.useState)([]),Fe=G.useRef(null);G.useEffect(()=>{e.rowHeight&&e.rowHeight!==I&&ye(e.rowHeight)},[e.rowHeight]);let Le=G.useMemo(()=>e.id?`grid-columns-${e.objectName}-${e.id}`:`grid-columns-${e.objectName}`,[e.objectName,e.id]),[H,Re]=(0,G.useState)(()=>{let t=e.columnState;if(t&&typeof t==`object`)return t;try{let e=localStorage.getItem(Le);return e?JSON.parse(e):{}}catch{return{}}}),ze=G.useMemo(()=>JSON.stringify(e.columnState??null),[e.columnState]);G.useEffect(()=>{let t=e.columnState;t&&typeof t==`object`&&Re(t)},[ze]);let Be=(0,G.useCallback)(e=>{Re(e);try{localStorage.setItem(Le,JSON.stringify(e))}catch(e){console.warn(`Failed to persist column state:`,e)}let t=y.onColumnStateChange;if(typeof t==`function`)try{t(e)}catch(e){console.warn(`onColumnStateChange threw:`,e)}},[Le,y]),{ref:He,isRefreshing:Ue,pullDistance:Ge}=Ze({onRefresh:(0,G.useCallback)(async()=>{pe(e=>e+1)},[]),enabled:!!t&&!!e.objectName});(0,G.useEffect)(()=>{let e=()=>j(window.innerWidth<480);return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let Ke=y.data,Je=o(e.bind),Ye=Tt(e),U=G.useMemo(()=>Ke&&Array.isArray(Ke)?{provider:`value`,items:Ke}:Je&&Array.isArray(Je)?{provider:`value`,items:Je}:Ye,[JSON.stringify(Ye),Je,Ke]),W=U?.provider===`value`,K=U?.provider===`object`&&U&&`object`in U?U.object:e.objectName,q=e.fields,J=e.columns,Xe=e.filter,X=e.sort,Qe=e.pagination,$e=e.pageSize;(0,G.useEffect)(()=>{W&&U?.provider===`value`&&(x(e=>{let t=U.items;return JSON.stringify(e)===JSON.stringify(t)?e:t}),w(!1))},[W,U]),(0,G.useEffect)(()=>{if(!W||!K||!t)return;let e=!1;return(async()=>{try{if(typeof t.getObjectSchema!=`function`)return;let n=await t.getObjectSchema(K);e||se(n)}catch(e){console.warn(`[ObjectGrid] Failed to fetch objectSchema for inline data (objectName: ${K}):`,e)}})(),()=>{e=!0}},[W,K,t]),(0,G.useEffect)(()=>{if(W)return;let n=!1;return(async()=>{w(!0),re(null);try{let r=null,i=Et(J)||q;if(K&&t)if(typeof t.getObjectSchema==`function`){let e=await t.getObjectSchema(K);if(n)return;r=e}else r={name:K,fields:{}};else if(i&&K)r={name:K,fields:{}};else if(K)throw Error(`DataSource required`);else throw Error(`Object name required for data fetching`);if(n||se(r),t&&K){let i={$select:(()=>{let e=e=>e.map(e=>typeof e==`string`?e:e?.name||e?.field).includes(`id`)?e:[`id`,...e];if(q)return e(q);if(J&&Array.isArray(J))return e(J.map(e=>typeof e==`string`?e:e.field))})(),$top:Qe?.pageSize||$e||50};Xe&&Array.isArray(Xe)?i.$filter=Xe:e.defaultFilters&&(i.$filter=e.defaultFilters),X?typeof X==`string`?i.$orderby=X:Array.isArray(X)&&(i.$orderby=X.map(e=>`${e.field} ${e.order}`).join(`, `)):e.defaultSort&&(i.$orderby=`${e.defaultSort.field} ${e.defaultSort.order}`);let a=h(r?.fields,J??q);a.length>0&&(i.$expand=a);let o=await t.find(K,i);if(n)return;x(o.data||[]);let s=o.total;De(typeof s==`number`?s:void 0),Fe.current={...i},z(!1)}}catch(e){n||re(e)}finally{n||w(!1)}})(),()=>{n=!0}},[K,q,J,Xe,X,Qe,$e,t,W,U,M]);let Z=l({navigation:e.navigation,objectName:e.objectName,onNavigate:e.onNavigate,onRowClick:c}),{execute:tt}=a(),nt=et(e.rowColor),rt=(0,G.useCallback)(t=>{let n=e.conditionalFormatting;if(!(!n||n.length===0))for(let e of n){let n=!1,r=(`condition`in e?e.condition:void 0)||(`expression`in e?e.expression:void 0)||void 0;if(r)n=p(r,t);else if(`field`in e&&`operator`in e&&e.field&&e.operator){let r=e,i=t[r.field];switch(r.operator){case`equals`:n=i===r.value;break;case`not_equals`:n=i!==r.value;break;case`contains`:n=typeof i==`string`&&typeof r.value==`string`&&i.includes(r.value);break;case`greater_than`:n=typeof i==`number`&&typeof r.value==`number`&&i>r.value;break;case`less_than`:n=typeof i==`number`&&typeof r.value==`number`&&i<r.value;break;case`in`:n=Array.isArray(r.value)&&r.value.includes(i);break}}if(n){let t={};return`style`in e&&e.style&&Object.assign(t,e.style),`backgroundColor`in e&&e.backgroundColor&&(t.backgroundColor=e.backgroundColor),`textColor`in e&&e.textColor&&(t.color=e.textColor),`borderColor`in e&&e.borderColor&&(t.borderColor=e.borderColor),t}}},[e.conditionalFormatting]),it=G.useMemo(()=>{let t=e.grouping;if(!t?.fields?.length)return;let n=new Map;for(let r of t.fields){let t=r.field,i=k?.fields?.[t],a=Et(e.columns)?.find?.(e=>typeof e==`object`&&e?.field===t),o=a?.type||i?.type,s=a?.options||i?.options,c=new Map;if(Array.isArray(s)&&s.length>0){let n=e.objectName?D(e.objectName,t,s):s;for(let e of n)if(e&&e.value!==void 0&&e.value!==null){let t=e.label;c.set(String(e.value),String(t??e.value))}}n.set(t,{type:o||void 0,options:c.size>0?c:void 0})}return(e,t)=>{let r=n.get(e);if(r){if(r.options){let e=r.options.get(String(t));if(e!==void 0)return e}if(r.type===`boolean`||typeof t==`boolean`){if(t===!0||t===`true`)return T(`grid.booleanTrue`,`Yes`);if(t===!1||t===`false`)return T(`grid.booleanFalse`,`No`)}}}},[e.grouping,e.columns,e.objectName,k,D,T]),{groups:at,isGrouped:ct,toggleGroup:lt}=ot(e.grouping,b,e.aggregations,it),{summaries:ut,hasSummary:ft}=dt(G.useMemo(()=>{let t=Et(e.columns);if(t&&t.length>0&&typeof t[0]==`object`)return t},[e.columns]),b,k?.fields),pt=(0,G.useCallback)(()=>{let t=e=>e&&{text:(0,Y.jsx)(oe,{className:`h-3.5 w-3.5`}),number:(0,Y.jsx)(ve,{className:`h-3.5 w-3.5`}),currency:(0,Y.jsx)(ve,{className:`h-3.5 w-3.5`}),percent:(0,Y.jsx)(ve,{className:`h-3.5 w-3.5`}),date:(0,Y.jsx)(we,{className:`h-3.5 w-3.5`}),datetime:(0,Y.jsx)(ie,{className:`h-3.5 w-3.5`}),boolean:(0,Y.jsx)(Se,{className:`h-3.5 w-3.5`}),user:(0,Y.jsx)(Pe,{className:`h-3.5 w-3.5`}),select:(0,Y.jsx)(E,{className:`h-3.5 w-3.5`})}[e]||(0,Y.jsx)(oe,{className:`h-3.5 w-3.5`}),n=e=>{if(e.type)return e.type;let t=e.field.toLowerCase();if([`completed`,`is_completed`,`done`,`active`,`enabled`,`archived`].some(e=>t===e||t===`is_${e}`))return`boolean`;if([`created_time`,`modified_time`,`updated_time`,`created_at`,`updated_at`,`modified_at`,`last_login`,`logged_at`].some(e=>t===e||t.endsWith(`_${e}`)))return`datetime`;if([`date`,`due`,`created`,`updated`,`deadline`,`start`,`end`,`expires`].some(e=>t.includes(e))){if(b.length>0){let t=b.find(t=>t[e.field]!=null)?.[e.field];if(typeof t==`string`&&!isNaN(Date.parse(t)))return`date`}return`date`}if([`probability`,`percent`,`percentage`,`completion`,`progress`,`rate`].some(e=>t.includes(e))&&b.length>0&&typeof b.find(t=>t[e.field]!=null)?.[e.field]==`number`)return`percent`;if([`status`,`priority`,`category`,`stage`,`type`,`severity`,`level`].some(e=>t.includes(e))&&b.length>0){let t=new Set(b.map(t=>t[e.field]).filter(Boolean));if(t.size>0&&t.size<=10)return`select`}if([`assignee`,`owner`,`author`,`reporter`,`creator`,`user`].some(e=>t.includes(e)))return`user`;if([`amount`,`price`,`total`,`revenue`,`cost`,`budget`,`salary`].some(e=>t.includes(e))&&b.length>0&&typeof b.find(t=>t[e.field]!=null)?.[e.field]==`number`)return`currency`;if(b.length>0){let t=b.find(t=>t[e.field]!=null)?.[e.field];if(typeof t==`string`&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(t))return`datetime`}return null},r=Et(J);if(r){if(r.length>0&&typeof r[0]==`object`&&r[0]!==null){let i=r[0];if(`accessorKey`in i)return r.map(r=>{if(r.cell)return r;let i=n({field:r.accessorKey,label:r.header,type:r.type});if(!i)return r;let a=B(i),o={name:r.accessorKey,type:i};return i===`select`&&(o.options=Array.from(new Set(b.map(e=>e[r.accessorKey]).filter(Boolean))).map(e=>({value:e,label:ke(String(e))}))),r.appearance!=null&&(o.appearance=r.appearance),{...r,...e.showColumnTypeIcons&&{headerIcon:t(i)},cell:e=>(0,Y.jsx)(a,{value:e,field:o})}});if(`field`in i)return r.filter(e=>e?.field&&typeof e.field==`string`&&!e.hidden).map((r,i)=>{let a=wt(r.label)||r.field.charAt(0).toUpperCase()+r.field.slice(1).replace(/_/g,` `),o=e.objectName?ae(e.objectName,r.field,a):a,s,c=k?.fields?.[r.field],l=r.type||c?.type||n({field:r.field})||null,u=r.format??c?.format,d=l?Ie({type:l,format:u}):null,f=d?B(d):null,p={name:r.field,type:d||`text`};c&&(c.label&&(p.label=c.label),c.currency&&(p.currency=c.currency),c.precision!==void 0&&(p.precision=c.precision),c.format&&(p.format=c.format),c.options&&(p.options=D(e.objectName,r.field,c.options))),d===`select`&&!p.options&&(p.options=Array.from(new Set(b.map(e=>e[r.field]).filter(Boolean))).map(e=>({value:e,label:ke(String(e))}))),r.options&&(p.options=D(e.objectName,r.field,r.options));let m=r.appearance??c?.appearance;m!=null&&(p.appearance=m);let h=i===0&&!r.link&&!r.action,g=r.link||h;s=r.link&&r.action||h&&r.action||g?(e,t)=>(0,Y.jsx)(xt,{testId:h?`primary-field-link`:`link-cell`,onActivate:()=>Z.handleClick(t),children:f?(0,Y.jsx)(f,{value:e,field:p}):e!=null&&e!==``?String(e):(0,Y.jsx)(`span`,{className:`text-muted-foreground/50 text-xs italic`,children:`—`})}):r.action?(e,t)=>(0,Y.jsx)(V,{variant:`outline`,size:`sm`,className:`h-7 text-xs`,"data-testid":`action-cell`,onClick:n=>{n.stopPropagation(),tt({type:r.action,params:{record:t,field:r.field,value:e}})},children:mt(r.action)}):f?e=>(0,Y.jsx)(f,{value:e,field:p}):e=>e!=null&&e!==``?(0,Y.jsx)(`span`,{children:String(e)}):(0,Y.jsx)(ee,{});let _=r.prefix;if(_?.field){let e=s,t=_.type===`badge`?B(`select`):null;s=(n,r)=>{let i=r[_.field];return(0,Y.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[i!=null&&i!==``?t?(0,Y.jsx)(t,{value:i,field:{name:_.field,type:`select`}}):(0,Y.jsx)(`span`,{className:`text-muted-foreground text-xs mr-1.5`,children:String(i)}):null,e(n,r)]})}}let v=[`number`,`currency`,`percent`],y=d||r.type,x=r.align||(y&&v.includes(y)?`right`:void 0),S=i===0||r.essential===!0;return{header:o,accessorKey:r.field,...e.showColumnTypeIcons&&{headerIcon:t(d)},...!S&&{className:`hidden sm:table-cell`},...r.width&&{width:r.width},...x&&{align:x},sortable:r.sortable!==!1,...r.resizable!==void 0&&{resizable:r.resizable},...r.wrap!==void 0&&{wrap:r.wrap},...s&&{cell:s},...r.pinned&&{pinned:r.pinned}}})}return r.filter(e=>typeof e==`string`&&e.trim().length>0).map((r,i)=>{let a=k?.fields?.[r],o=a?.label||r.charAt(0).toUpperCase()+r.slice(1).replace(/_/g,` `),s=e.objectName?ae(e.objectName,r,o):o,c=a?.type||n({field:r})||null,l=c?B(c):null,u={name:r,type:c||`text`};a&&(a.label&&(u.label=a.label),a.currency&&(u.currency=a.currency),a.precision!==void 0&&(u.precision=a.precision),a.format&&(u.format=a.format),a.options&&(u.options=D(e.objectName,r,a.options))),c===`select`&&!u.options&&(u.options=Array.from(new Set(b.map(e=>e[r]).filter(Boolean))).map(e=>({value:e,label:ke(String(e))}))),(c===`select`||c===`status`)&&a?.appearance!=null&&(u.appearance=a.appearance);let d=c&&[`number`,`currency`,`percent`].includes(c)?`right`:void 0,f=i===0,p;return f&&l?p=(e,t)=>(0,Y.jsx)(xt,{testId:`primary-field-link`,onActivate:()=>Z.handleClick(t),children:(0,Y.jsx)(l,{value:e,field:u})}):f?p=(e,t)=>(0,Y.jsx)(xt,{testId:`primary-field-link`,onActivate:()=>Z.handleClick(t),children:e!=null&&e!==``?String(e):(0,Y.jsx)(`span`,{className:`text-muted-foreground/50 text-xs italic`,children:`—`})}):l&&(p=e=>(0,Y.jsx)(l,{value:e,field:u})),{header:s,accessorKey:r,...e.showColumnTypeIcons&&c&&{headerIcon:t(c)},...d&&{align:d},...p&&{cell:p},sortable:a?.sortable!==!1}})}if(W){let r=U?.provider===`value`?U.items:[];if(r.length>0)return(q||Object.keys(r[0])).map(r=>{let i=k?.fields?.[r],a=i?.type||n({field:r})||null,o=a?B(a):null,s=i?.label||r.charAt(0).toUpperCase()+r.slice(1).replace(/_/g,` `),c={name:r,type:a||`text`};i&&(i.label&&(c.label=i.label),i.currency&&(c.currency=i.currency),i.precision!==void 0&&(c.precision=i.precision),i.format&&(c.format=i.format),i.options&&(c.options=D(e.objectName,r,i.options))),a===`select`&&!c.options&&(c.options=Array.from(new Set(b.map(e=>e[r]).filter(Boolean))).map(e=>({value:e,label:ke(String(e))}))),(a===`select`||a===`status`)&&i?.appearance!=null&&(c.appearance=i.appearance);let l=a&&[`number`,`currency`,`percent`].includes(a)?`right`:void 0;return{header:s,accessorKey:r,...e.showColumnTypeIcons&&a&&{headerIcon:t(a)},...l&&{align:l},...o&&{cell:e=>(0,Y.jsx)(o,{value:e,field:c})},sortable:i?.sortable!==!1}})}if(!k)return[];let i=[],a=new Set([`id`,`created_at`,`createdAt`,`updated_at`,`updatedAt`,`deleted_at`,`deletedAt`,`created_by`,`createdBy`,`updated_by`,`updatedBy`,`_version`,`_rev`]),o=k?.compactLayout,s=Object.keys(k.fields||{}),c;if(q)c=q;else if(o?.length)c=o.filter(e=>k.fields?.[e]);else{let e=s.filter(e=>{let t=k.fields?.[e];return!(!t||t.hidden||t.readonly&&a.has(e))});c=[...e.filter(e=>!a.has(e)),...e.filter(e=>a.has(e))]}return c.forEach(t=>{let n=k.fields?.[t];if(!n||n.permissions&&n.permissions.read===!1)return;let r=B(n.type),a=[`number`,`currency`,`percent`],o=n.options?{...n,options:D(e.objectName,t,n.options)}:n;i.push({header:e.objectName?ae(e.objectName,t,n.label||t):n.label||t,accessorKey:t,...a.includes(n.type)&&{align:`right`},cell:e=>(0,Y.jsx)(r,{value:e,field:o}),sortable:n.sortable!==!1})}),i},[k,q,J,U,W,Z.handleClick,tt,b,ae,D,e.objectName]),ht=(0,G.useCallback)(t=>{let n=e.exportOptions,r=n?.maxRecords||0,i=n?.includeHeaders!==!1,a=n?.fileNamePrefix||e.objectName||`export`;if((t===`csv`||t===`xlsx`||t===`json`)&&F.isSupported&&e.objectName&&!W&&n?.streaming!==!1){let n=pt().filter(e=>e.accessorKey!==`_actions`).map(e=>e.accessorKey).filter(Boolean);N(!1),P(!0),F.start(e.objectName,{format:t===`json`?`json`:t,fields:n.length?n:void 0,includeHeaders:i,limit:r>0?r:void 0});return}let o=r>0?b.slice(0,r):b,s=(e,t)=>{let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),URL.revokeObjectURL(n)},c=e=>{let t=e==null?``:String(e);return t.includes(`,`)||t.includes(`"`)||t.includes(`
3
- `)||t.includes(`\r`)?`"${t.replace(/"/g,`""`)}"`:t};if(t===`csv`){let e=pt().filter(e=>e.accessorKey!==`_actions`),t=e.map(e=>e.accessorKey),n=e.map(e=>e.header),r=[];i&&r.push(n.join(`,`)),o.forEach(e=>{r.push(t.map(t=>c(e[t])).join(`,`))}),s(new Blob([r.join(`
4
- `)],{type:`text/csv;charset=utf-8;`}),`${a}.csv`)}else t===`json`&&s(new Blob([JSON.stringify(o,null,2)],{type:`application/json`}),`${a}.json`);N(!1)},[b,e.exportOptions,e.objectName,pt,F,W]);if(ne)return(0,Y.jsxs)(`div`,{className:`p-3 sm:p-4 border border-red-300 bg-red-50 rounded-md`,children:[(0,Y.jsx)(`h3`,{className:`text-red-800 font-semibold`,children:T(`grid.errorLoading`)}),(0,Y.jsx)(`p`,{className:`text-red-600 text-sm mt-1`,children:ne.message})]});if(te&&b.length===0)return de?(0,Y.jsx)(`div`,{className:`space-y-2 p-2`,children:[1,2,3].map(e=>(0,Y.jsxs)(`div`,{className:`border rounded-lg p-3 bg-card animate-pulse`,children:[(0,Y.jsx)(`div`,{className:`h-5 bg-muted rounded w-3/4 mb-3`}),(0,Y.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Y.jsx)(`div`,{className:`h-4 bg-muted rounded w-1/4`}),(0,Y.jsx)(`div`,{className:`h-5 bg-muted rounded-full w-20`})]}),(0,Y.jsx)(`div`,{className:`h-3 bg-muted rounded w-1/3`})]},e))}):(0,Y.jsxs)(`div`,{className:`p-4 sm:p-8 text-center`,children:[(0,Y.jsx)(`div`,{className:`inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-foreground`}),(0,Y.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:T(`grid.loading`)})]});let vt=[...pt()];if(H.widths&&(vt=vt.map(e=>{let t=H.widths?.[e.accessorKey];return t?{...e,size:t}:e})),H.order&&H.order.length>0){let e=new Map(H.order.map((e,t)=>[e,t]));vt.sort((t,n)=>(e.get(t.accessorKey)??1/0)-(e.get(n.accessorKey)??1/0))}let Q=(`operations`in e?e.operations:void 0)??{update:!!n,delete:!!r},bt=Array.isArray(e.rowActions)?e.rowActions:[],St=Array.isArray(e.rowActionDefs)?e.rowActionDefs:[],Dt=bt.includes(`edit`),Ot=bt.includes(`delete`),kt=bt.filter(e=>e!==`edit`&&e!==`delete`),At=!!((Q?.update||Dt)&&n),jt=!!((Q?.delete||Ot)&&r),Mt=!!(Q&&(Q.update||Q.delete)),Nt=kt.length>0||St.length>0||Dt||Ot,$=Mt||Nt?[...vt,{header:T(`grid.actions`),accessorKey:`_actions`,cell:(e,t)=>(0,Y.jsx)(gt,{row:t,rowActions:kt,rowActionDefs:St,canEdit:At,canDelete:jt,onEdit:n,onDelete:r,onAction:(e,t)=>tt({type:e,params:{record:t}}),onActionDef:(e,t)=>{let{params:n,...r}=e,i={...r};Array.isArray(n)&&n.length>0&&(i.actionParams=n),i.params={_rowRecord:t},tt(i)}}),sortable:!1}]:vt,Pt=$.filter(e=>e.pinned===`left`),Ft=$.filter(e=>e.pinned===`right`),It=$.filter(e=>!e.pinned),Lt=Pt.length>0||Ft.length>0,Rt=`sticky right-0 z-10 bg-background border-l border-border`,zt=I===`compact`?`px-3 py-1 h-9 text-[13px] leading-tight`:I===`short`?`px-3 py-1 h-9 text-[13px] leading-normal`:I===`tall`?`px-3 py-2.5 h-14 text-sm`:I===`extra_tall`?`px-3 py-3.5 h-16 text-sm leading-relaxed`:`px-3 py-1.5 h-11 text-[13px] leading-normal`,Bt=e=>({...e,cellClassName:[zt,e.cellClassName].filter(Boolean).join(` `)}),Vt=Lt?[...Pt.map(Bt),...It.map(Bt),...Ft.map(e=>({...Bt(e),className:[e.className,Rt].filter(Boolean).join(` `),cellClassName:[zt,e.cellClassName,Rt].filter(Boolean).join(` `)}))]:$.map(Bt),Ht=Lt?Pt.length:e.frozenColumns??1,Ut=e.batchActions??e.bulkActions,Wt=Array.isArray(e.bulkActionDefs)?e.bulkActionDefs:[],Gt=Ut&&Ut.length>0?Ut:jt&&i&&Wt.length===0?[`delete`]:[],Kt=Gt.length>0||Wt.length>0,qt=!1;e.selection?.type?qt=e.selection.type===`none`?!1:e.selection.type:e.selectable===void 0?Kt&&(qt=`multiple`):qt=e.selectable;let Jt=async n=>{if(!R)return n;let r=e.objectName;if(!t||!r)return n;let i={...Fe.current??{}};delete i.$top,delete i.$skip;let a=5e3,o=[],s=0;for(;o.length<a;){let e=(await t.find(r,{...i,$top:500,$skip:s})).data??[];if(e.length===0||(o.push(...e),e.length<500))break;s+=500}return o.slice(0,a)},Yt=(e,t)=>{(async()=>{let n=await Jt(t);if(e===`delete`&&i){i(n),Ce([]),z(!1);return}tt({type:e,params:{records:n}})})()},Xt=(e,t)=>{(async()=>{let n=await Jt(t);je(e),Ne(n)})()},Zt=e=>{je(null),Ne([]),e&&(Ce([]),z(!1),pe(e=>e+1))},Qt=e.pagination===void 0?e.showPagination===void 0?!0:e.showPagination:!0,$t=e.pagination?.pageSize||e.pageSize||10,en=e.searchableFields===void 0?e.showSearch===void 0?!0:e.showSearch:e.searchableFields.length>0,tn={type:`data-table`,caption:e.label||e.title,columns:Vt,data:b,pagination:Qt,pageSize:$t,searchable:en,selectable:qt,sortable:!0,exportable:Q?.export,borderless:!0,rowActions:!!(e.editable&&Mt),resizableColumns:e.resizable??e.resizableColumns??!0,reorderableColumns:e.reorderableColumns??!1,editable:e.editable??!1,singleClickEdit:e.singleClickEdit??!0,className:e.className,cellClassName:I===`compact`?`px-3 py-1 text-[13px] leading-tight`:I===`short`?`px-3 py-1 text-[13px] leading-normal`:I===`tall`?`px-3 py-2.5 text-sm`:I===`extra_tall`?`px-3 py-3.5 text-sm leading-relaxed`:`px-3 py-1.5 text-[13px] leading-normal`,showRowNumbers:!0,showAddRow:!!Q?.create,onAddRecord:g,rowClassName:e.rowColor?(e,t)=>nt(e):void 0,rowStyle:e.conditionalFormatting?.length?(e,t)=>rt(e):void 0,frozenColumns:Ht,onSelectionChange:e=>{Ce(e),s?.(e)},onRowClick:Z.handleClick,onCellChange:u,onRowSave:f,onBatchSave:m,onColumnResize:(e,t)=>{Be({...H,widths:{...H.widths,[e]:t}})},onColumnReorder:e=>{Be({...H,order:e})}},nn=e=>({...tn,caption:void 0,data:e,pagination:!1,searchable:!1,borderless:!0}),rn=e.label?`${e.label} Detail`:e.objectName?`${e.objectName.charAt(0).toUpperCase()+e.objectName.slice(1)} Detail`:`Record Detail`;if(de&&b.length>0&&!ct){let e=pt().filter(e=>e.accessorKey!==`_actions`),t=new Map;e.forEach(e=>t.set(e.accessorKey,e));let n=e[0],r=[`amount`,`price`,`total`,`revenue`,`cost`,`value`,`budget`,`salary`],i=[`stage`,`status`,`priority`,`category`,`severity`,`level`],a=[`date`,`due`,`created`,`updated`,`deadline`,`start`,`end`,`expires`],o=[`probability`,`percent`,`rate`,`ratio`,`confidence`,`score`],s=e=>{let t=(e||``).toLowerCase();return t.includes(`won`)||t.includes(`completed`)||t.includes(`done`)||t.includes(`active`)||t===`activated`||t===`success`||t===`approved`||t===`paid`?`bg-green-50 text-green-700 border-green-200 dark:bg-green-950/40 dark:text-green-300 dark:border-green-900/60`:t.includes(`lost`)||t.includes(`cancelled`)||t.includes(`rejected`)||t.includes(`closed lost`)||t===`expired`||t===`terminated`||t===`failed`||t===`overdue`?`bg-red-50 text-red-700 border-red-200 dark:bg-red-950/40 dark:text-red-300 dark:border-red-900/60`:t.includes(`negotiation`)||t.includes(`review`)||t.includes(`in progress`)||t.includes(`approval`)||t===`in_approval`||t===`pending_approval`?`bg-yellow-50 text-yellow-800 border-yellow-200 dark:bg-yellow-950/40 dark:text-yellow-300 dark:border-yellow-900/60`:t.includes(`proposal`)||t.includes(`pending`)?`bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-950/40 dark:text-blue-300 dark:border-blue-900/60`:t.includes(`qualification`)||t.includes(`qualified`)?`bg-indigo-50 text-indigo-700 border-indigo-200 dark:bg-indigo-950/40 dark:text-indigo-300 dark:border-indigo-900/60`:t.includes(`prospecting`)||t.includes(`new`)||t.includes(`open`)?`bg-purple-50 text-purple-700 border-purple-200 dark:bg-purple-950/40 dark:text-purple-300 dark:border-purple-900/60`:t===`draft`||t.includes(`draft`)?`bg-slate-50 text-slate-700 border-slate-200 dark:bg-slate-950/40 dark:text-slate-300 dark:border-slate-900/60`:`bg-muted text-muted-foreground border-border`},c=e=>{let t=(e||``).toLowerCase();return t.includes(`won`)||t.includes(`completed`)||t.includes(`done`)||t.includes(`active`)||t===`activated`?`border-l-green-500`:t.includes(`lost`)||t.includes(`cancelled`)||t.includes(`rejected`)||t===`expired`||t===`terminated`?`border-l-red-500`:t.includes(`negotiation`)||t.includes(`review`)||t.includes(`in progress`)||t.includes(`approval`)?`border-l-yellow-500`:t.includes(`proposal`)||t.includes(`pending`)?`border-l-blue-500`:t.includes(`qualification`)||t.includes(`qualified`)?`border-l-indigo-500`:t.includes(`prospecting`)||t.includes(`new`)||t.includes(`open`)?`border-l-purple-500`:t===`draft`||t.includes(`draft`)?`border-l-slate-400`:`border-l-gray-300`},l=e=>{let t=e.toLowerCase();return r.some(e=>t.includes(e))?`amount`:i.some(e=>t.includes(e))?`stage`:a.some(e=>t.includes(e))?`date`:o.some(e=>t.includes(e))?`percent`:`other`};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`space-y-2 p-2`,children:b.map((t,r)=>{let i=e.slice(1,5),a=i.find(e=>l(e.accessorKey)===`amount`),o=i.find(e=>l(e.accessorKey)===`stage`),u=i.filter(e=>l(e.accessorKey)===`date`),d=i.filter(e=>l(e.accessorKey)===`percent`),f=i.filter(e=>e!==a&&e!==o&&!u.includes(e)&&!d.includes(e)),p=o?String(t[o.accessorKey]??``):``,m=p?c(p):``;return(0,Y.jsxs)(`div`,{className:[`border rounded-lg p-2.5 bg-card hover:bg-accent/50 cursor-pointer transition-colors touch-manipulation`,m?`border-l-[3px] ${m}`:``].filter(Boolean).join(` `),onClick:()=>Z.handleClick(t),children:[n&&(0,Y.jsx)(`div`,{className:`font-semibold text-sm truncate mb-1`,children:t[n.accessorKey]!=null&&typeof t[n.accessorKey]==`object`?String(t[n.accessorKey]):t[n.accessorKey]??`—`}),(a||o)&&(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[a&&(0,Y.jsx)(`span`,{className:`text-sm tabular-nums font-medium`,children:typeof t[a.accessorKey]==`number`?Ve(t[a.accessorKey]):t[a.accessorKey]!=null&&typeof t[a.accessorKey]==`object`?String(t[a.accessorKey]):t[a.accessorKey]??`—`}),o&&t[o.accessorKey]&&(0,Y.jsx)(ce,{variant:`outline`,className:`text-xs shrink-0 max-w-[140px] truncate ${s(String(t[o.accessorKey]))}`,children:String(t[o.accessorKey])})]}),(u.length>0||d.length>0)&&(0,Y.jsxs)(`div`,{className:`flex items-center justify-between py-0.5 text-xs text-muted-foreground`,children:[u[0]&&(0,Y.jsx)(`span`,{className:`tabular-nums`,children:t[u[0].accessorKey]?xe(t[u[0].accessorKey],`short`):`—`}),d[0]&&t[d[0].accessorKey]!=null&&(0,Y.jsx)(`span`,{className:`tabular-nums`,children:We(Number(t[d[0].accessorKey]))})]}),u.slice(1).map(e=>(0,Y.jsxs)(`div`,{className:`flex justify-between items-center py-0.5`,children:[(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.header}),(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground tabular-nums`,children:t[e.accessorKey]?xe(t[e.accessorKey],`short`):`—`})]},e.accessorKey)),f.map(e=>{let n=t[e.accessorKey];return n==null||n===``?null:(0,Y.jsxs)(`div`,{className:`flex justify-between items-center py-0.5`,children:[(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.header}),(0,Y.jsx)(`span`,{className:`text-xs font-medium truncate ml-2 text-right`,children:e.cell?e.cell(n,t):String(n)})]},e.accessorKey)})]},t.id||t._id||r)})}),Z.isOverlay&&(0,Y.jsx)(A,{...Z,title:rn,children:e=>(0,Y.jsx)(`div`,{className:`space-y-3`,children:Object.entries(e).map(([e,t])=>(0,Y.jsxs)(`div`,{className:`flex flex-col`,children:[(0,Y.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:e.replace(/_/g,` `)}),(0,Y.jsx)(`span`,{className:`text-sm`,children:String(t??`—`)})]},e))})})]})}let an=()=>{ye(e=>e===`compact`?`short`:e===`short`?`medium`:e===`medium`?`tall`:e===`tall`?`extra_tall`:`compact`)},on={compact:S,short:qe,medium:me,tall:_e,extra_tall:_e}[I],sn=e.rowHeight!==void 0&&!e.hideRowHeightToggle,cn=e.exportOptions||sn?(0,Y.jsxs)(`div`,{className:`flex items-center justify-end gap-1 px-2 py-1`,children:[sn&&(0,Y.jsxs)(V,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-muted-foreground hover:text-primary text-xs`,onClick:an,title:`Row height: ${I}`,children:[(0,Y.jsx)(on,{className:`h-3.5 w-3.5 mr-1.5`}),(0,Y.jsx)(`span`,{className:`hidden sm:inline capitalize`,children:I})]}),e.exportOptions&&(0,Y.jsxs)(be,{open:he,onOpenChange:N,children:[(0,Y.jsx)(_,{asChild:!0,children:(0,Y.jsxs)(V,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-muted-foreground hover:text-primary text-xs`,children:[(0,Y.jsx)(O,{className:`h-3.5 w-3.5 mr-1.5`}),(0,Y.jsx)(`span`,{className:`hidden sm:inline`,children:T(`grid.export`)})]})}),(0,Y.jsx)(ue,{align:`end`,className:`w-48 p-2`,children:(0,Y.jsx)(`div`,{className:`space-y-1`,children:(e.exportOptions.formats||[`csv`,`json`]).map(e=>(0,Y.jsxs)(V,{variant:`ghost`,size:`sm`,className:`w-full justify-start h-8 text-xs`,onClick:()=>ht(e),children:[(0,Y.jsx)(O,{className:`h-3.5 w-3.5 mr-2`}),T(`grid.exportAs`,{format:e.toUpperCase()})]},e))})})]})]}):null,ln=e=>{let t=[`_id`,`id`,`created_at`,`updated_at`,`created_by`,`updated_by`],n=Object.entries(e),r=e=>k?.fields?.[e]?.hidden===!0,i=n.filter(([e])=>!t.includes(e)&&!r(e)),a=n.filter(([e])=>t.includes(e)&&e!==`_id`&&e!==`id`),o=e=>e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `),s=(e,t)=>{if(t==null||t===``)return(0,Y.jsx)(`span`,{className:`text-muted-foreground/50 text-sm italic`,children:T(`grid.empty`)});let n=k?.fields?.[e];if(n?.type){let e=B(n.type);if(e)return(0,Y.jsx)(e,{value:t,field:n})}return typeof t==`boolean`?(0,Y.jsx)(ce,{variant:t?`default`:`outline`,children:T(t?`grid.yes`:`grid.no`)}):typeof t==`string`&&!isNaN(Date.parse(t))&&(e.includes(`date`)||e.includes(`_at`)||e.includes(`time`))?(0,Y.jsx)(`span`,{className:`text-sm tabular-nums`,children:xe(t)}):typeof t==`number`&&[`amount`,`price`,`total`,`revenue`,`cost`,`value`,`budget`,`salary`].some(t=>e.toLowerCase().includes(t))?(0,Y.jsx)(`span`,{className:`text-sm tabular-nums font-medium`,children:Ae(t)}):(0,Y.jsx)(`span`,{className:`text-sm break-words`,children:String(t)})};return(0,Y.jsxs)(`div`,{className:`space-y-4`,"data-testid":`record-detail-panel`,children:[(0,Y.jsx)(`div`,{className:`rounded-lg border bg-card`,children:(0,Y.jsx)(`div`,{className:`divide-y`,children:i.map(([e,t])=>(0,Y.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-start gap-1 sm:gap-4 px-4 py-3`,children:[(0,Y.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground sm:w-1/3 sm:text-right sm:pt-0.5 uppercase tracking-wide shrink-0`,children:o(e)}),(0,Y.jsx)(`div`,{className:`flex-1 min-w-0`,children:s(e,t)})]},e))})}),a.length>0&&(0,Y.jsxs)(`div`,{className:`rounded-lg border bg-muted/30`,children:[(0,Y.jsx)(`div`,{className:`px-4 py-2 border-b`,children:(0,Y.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:T(`grid.systemFields`)})}),(0,Y.jsx)(`div`,{className:`divide-y divide-border/50`,children:a.map(([e,t])=>(0,Y.jsxs)(`div`,{className:`flex items-center gap-4 px-4 py-2`,children:[(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground w-1/3 text-right shrink-0`,children:o(e)}),(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground flex-1 min-w-0 break-words`,children:String(t??``)})]},e))})]})]})},un=ft?(0,Y.jsx)(`div`,{className:`border-t bg-muted/30 px-2 py-1.5`,"data-testid":`column-summary-footer`,children:(0,Y.jsx)(`div`,{className:`flex gap-4 text-xs text-muted-foreground font-medium`,children:Vt.filter(e=>ut.has(e.accessorKey)).map(e=>{let t=ut.get(e.accessorKey);return(0,Y.jsxs)(`span`,{"data-testid":`summary-${e.accessorKey}`,children:[e.header,`: `,t.label]},e.accessorKey)})})}):null,dn=(t,n)=>{let r=k?.fields?.[t],i=e.objectName?ae(e.objectName,t,r?.label||t):r?.label||t,a,o=r?.type;if(o===`select`||o===`status`){let i=r?.options?D(e.objectName,t,r.options):void 0,o=Array.isArray(i)?i.find(e=>String(e.label)===n||String(e.value)===n):void 0;a=Te(o?.color,o?.value??n)}return{fieldLabel:i,labelColorClass:a}},fn=e=>{let{fieldLabel:t,labelColorClass:n}=dn(e.field,e.label);return(0,Y.jsx)(`div`,{children:(0,Y.jsx)(st,{groupKey:e.key,label:e.label,count:e.rows.length,collapsed:e.collapsed,aggregations:e.aggregations,fieldLabel:e.depth===0?t:void 0,labelColorClass:n,onToggle:lt,children:e.subgroups.length>0?(0,Y.jsx)(`div`,{className:`space-y-4 mt-2`,children:e.subgroups.map(fn)}):(0,Y.jsx)(d,{schema:nn(e.rows)})})},e.key)},pn=ct?(0,Y.jsx)(`div`,{className:`space-y-4 px-3 sm:px-4 pt-2 pb-4`,children:at.map(fn)}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(d,{schema:tn}),un]}),mn=(0,Y.jsx)(C,{open:ge,onOpenChange:P,job:F,filename:`${e.exportOptions?.fileNamePrefix||e.objectName||`export`}.${F.progress?.format||`csv`}`,closeAfterDownloadMs:400}),hn=(0,Y.jsx)(yt,{def:Oe,rows:Me,open:!!Oe,onClose:Zt,dataSource:t,resource:e.objectName??``});return Z.isOverlay&&Z.mode===`split`?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(A,{...Z,title:rn,mainContent:(0,Y.jsxs)(Y.Fragment,{children:[cn,pn,(0,Y.jsx)(_t,{selectedRows:L,actions:Gt??[],actionDefs:Wt,onAction:Yt,onActionDef:Xt,onClearSelection:()=>{Ce([]),z(!1)},pageSize:b.length,totalMatching:Ee,allMatchingSelected:R,onSelectAllMatching:()=>z(!0)})]}),children:e=>ln(e)}),mn,hn]}):(0,Y.jsxs)(`div`,{ref:He,className:`relative h-full`,children:[(0,Y.jsx)(v,{active:te&&b.length>0}),Ge>0&&(0,Y.jsx)(`div`,{className:`flex items-center justify-center text-xs text-muted-foreground`,style:{height:Ge},children:T(Ue?`grid.refreshing`:`grid.pullToRefresh`)}),cn,pn,(0,Y.jsx)(_t,{selectedRows:L,actions:Gt??[],actionDefs:Wt,onAction:Yt,onActionDef:Xt,onClearSelection:()=>{Ce([]),z(!1)},pageSize:b.length,totalMatching:Ee,allMatchingSelected:R,onSelectAllMatching:()=>z(!0)}),Z.isOverlay&&(0,Y.jsx)(A,{...Z,title:rn,children:e=>ln(e)}),mn,hn]})},Ot=e(r(),1);function kt(e,t,n){let r=Array(e);return new Proxy(r,{get(r,i,a){if(typeof i==`string`){let a=i.charCodeAt(0);if(a>=48&&a<=57){let a=+i;if(Number.isInteger(a)&&a>=0&&a<e){let e=r[a];if(!e){let i=t[a*2];e=r[a]={index:a,key:n(a),start:i,size:t[a*2+1],end:i+t[a*2+1],lane:0}}return e}}if(i===`length`)return e}return Reflect.get(r,i,a)}})}function At(e,t,n){let r=n.initialDeps??[],i,a=!0;function o(){let o=e();return o.length!==r.length||o.some((e,t)=>r[t]!==e)?(r=o,i=t(...o),n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(i),a=!1,i):i}return o.updateDeps=e=>{r=e},o}function jt(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var Mt=(e,t)=>Math.abs(e-t)<1.01,Nt=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},$,Pt=()=>{if($!==void 0)return $;if(typeof navigator>`u`)return $=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return $=!0;let e=navigator.maxTouchPoints;return $=navigator.platform===`MacIntel`&&e!==void 0&&e>0},Ft=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},It=e=>e,Lt=e=>{let t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,r=Array(n);for(let e=0;e<n;e++)r[e]=t+e;return r},Rt=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=e=>{let{width:n,height:r}=e;t({width:Math.round(n),height:Math.round(r)})};if(i(Ft(n)),!r.ResizeObserver)return()=>{};let a=new r.ResizeObserver(t=>{let r=()=>{let e=t[0];if(e?.borderBoxSize){let t=e.borderBoxSize[0];if(t){i({width:t.inlineSize,height:t.blockSize});return}}i(Ft(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},zt={passive:!0},Bt=typeof window>`u`?!0:`onscrollend`in window,Vt=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&Bt,o=0,s=a?null:Nt(i,()=>t(o,!1),e.options.isScrollingResetDelay),c=e=>()=>{o=n(r),s?.(),t(o,e)},l=c(!0),u=c(!1);return r.addEventListener(`scroll`,l,zt),a&&r.addEventListener(`scrollend`,u,zt),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},Ht=(e,t)=>Vt(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),Ut=(e,t,n)=>{if(t?.borderBoxSize){let e=t.borderBoxSize[0];if(e)return Math.round(e[n.options.horizontal?`inlineSize`:`blockSize`])}return e[n.options.horizontal?`offsetWidth`:`offsetHeight`]},Wt=(e,{adjustments:t=0,behavior:n},r)=>{var i,a;(a=(i=r.scrollElement)?.scrollTo)==null||a.call(i,{[r.options.horizontal?`left`:`top`]:e+t,behavior:n})},Gt=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var e;return((e=this.targetWindow?.performance)?.now)?.call(e)??Date.now()},this.observer=(()=>{let e=null,t=()=>e||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:e=new this.targetWindow.ResizeObserver(e=>{e.forEach(e=>{let t=()=>{let t=e.target,n=this.indexFromElement(t);if(!t.isConnected){this.observer.unobserve(t);for(let[e,n]of this.elementsCache)if(n===t){this.elementsCache.delete(e);break}return}this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,e,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(t):t()})}));return{disconnect:()=>{var n;(n=t())==null||n.disconnect(),e=null},observe:e=>t()?.observe(e,{box:`border-box`}),unobserve:e=>t()?.unobserve(e)}})(),this.range=null,this.setOptions=e=>{let t={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:It,rangeExtractor:Lt,onChange:()=>{},measureElement:Ut,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:`data-index`,initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:`estimate`};for(let n in e){let r=e[n];r!==void 0&&(t[n]=r)}this.options=t},this.notify=e=>{var t,n;(n=(t=this.options).onChange)==null||n.call(t,this,e)},this.maybeNotify=At(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),e=>{this.notify(e)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(e=>e()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{let e=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==e){if(this.cleanup(),!e){this.maybeNotify();return}if(this.scrollElement=e,this.scrollElement&&`ownerDocument`in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=this.scrollElement?.window??null,this.elementsCache.forEach(e=>{this.observer.observe(e)}),this.unsubs.push(this.options.observeElementRect(this,e=>{this.scrollRect=e,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(e,t)=>{this._intendedScrollOffset!==null&&Math.abs(e-this._intendedScrollOffset)<1.5&&(e=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0,this.scrollDirection=t?this.getScrollOffset()<e?`forward`:`backward`:null,this.scrollOffset=e,this.isScrolling=t,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),`addEventListener`in this.scrollElement){let e=this.scrollElement,t=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},n=()=>{this._iosTouching=!1,!(!Pt()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,zt),e.addEventListener(`touchend`,n,zt),this.unsubs.push(()=>{e.removeEventListener(`touchstart`,t),e.removeEventListener(`touchend`,n),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;let e=this.getScrollOffset(),t=this.getMaxScrollOffset();if(e<0||e>t)return;let n=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(e,{adjustments:this.scrollAdjustments+=n,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?`width`:`height`]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset==`function`?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(e,t)=>{let n=new Map,r=new Map;for(let i=t-1;i>=0;i--){let t=e[i];if(n.has(t.lane))continue;let a=r.get(t.lane);if(a==null||t.end>a.end?r.set(t.lane,t):t.end<a.end&&n.set(t.lane,!0),n.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((e,t)=>e.end===t.end?e.index-t.index:e.end-t.end)[0]:void 0},this.getMeasurementOptions=At(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(e,t,n,r,i,a,o)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMin=null,{count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o}),{key:!1}),this.getMeasurements=At(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o},s)=>{let c=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>e)for(let t of this.laneAssignments.keys())t>=e&&this.laneAssignments.delete(t);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(e=>{this.itemSizeCache.set(e.key,e.size)}));let l=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1),a===1){let i=this.options.gap,a=e*2,o=this._flatMeasurements;if(!o||o.length<a){let e=new Float64Array(a);o&&l>0&&e.set(o.subarray(0,l*2)),o=e,this._flatMeasurements=o}let s;if(l===0)s=t+n;else{let e=l-1;s=o[e*2]+o[e*2+1]+i}for(let t=l;t<e;t++){let e=r(t),n=c.get(e),a=typeof n==`number`?n:this.options.estimateSize(t);o[t*2]=s,o[t*2+1]=a,s+=a+i}let u=kt(e,o,r);return this.measurementsCache=u,u}let u=this.measurementsCache.slice(0,l),d=Array(a).fill(void 0);for(let e=0;e<l;e++){let t=u[e];t&&(d[t.lane]=e)}for(let i=l;i<e;i++){let e=r(i),a=this.laneAssignments.get(i),s,l,f=o===`estimate`||c.has(e);if(a!==void 0&&this.options.lanes>1){s=a;let e=d[s],r=e===void 0?void 0:u[e];l=r?r.end+this.options.gap:t+n}else{let e=this.options.lanes===1?u[i-1]:this.getFurthestMeasurement(u,i);l=e?e.end+this.options.gap:t+n,s=e?e.lane:i%this.options.lanes,this.options.lanes>1&&f&&this.laneAssignments.set(i,s)}let p=c.get(e),m=typeof p==`number`?p:this.options.estimateSize(i),h=l+m;u[i]={index:i,start:l,size:m,end:h,key:e,lane:s},d[s]=i}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=At(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>this.range=e.length>0&&t>0?qt({measurements:e,outerSize:t,scrollOffset:n,lanes:r,flat:r===1&&this._flatMeasurements!=null?this._flatMeasurements:null}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=At(()=>{let e=null,t=null,n=this.calculateRange();return n&&(e=n.startIndex,t=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,e,t]),[this.options.rangeExtractor,this.options.overscan,this.options.count,e,t]},(e,t,n,r,i)=>r===null||i===null?[]:e({startIndex:r,endIndex:i,overscan:t,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=e=>{let t=this.options.indexAttribute,n=e.getAttribute(t);return n?parseInt(n,10):(console.warn(`Missing attribute name '${t}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=e=>{if(!this.scrollState||this.scrollState.behavior!==`smooth`)return!0;let t=this.scrollState.index??this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index;if(t!==void 0&&this.range){let n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),r=Math.max(0,t-n),i=Math.min(this.options.count-1,t+n);return e>=r&&e<=i}return!0},this.measureElement=e=>{if(!e){this.elementsCache.forEach((e,t)=>{e.isConnected||(this.observer.unobserve(e),this.elementsCache.delete(t))});return}let t=this.indexFromElement(e),n=this.options.getItemKey(t),r=this.elementsCache.get(n);r!==e&&(r&&this.observer.unobserve(r),this.observer.observe(e),this.elementsCache.set(n,e)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(t)&&this.resizeItem(t,this.options.measureElement(e,void 0,this))},this.resizeItem=(e,t)=>{if(e<0||e>=this.options.count)return;let n,r,i,a=this._flatMeasurements;if(this.options.lanes===1&&a!==null)i=this.options.getItemKey(e),r=a[e*2],n=a[e*2+1];else{let t=this.measurementsCache[e];if(!t)return;i=t.key,r=t.start,n=t.size}let o=t-(this.itemSizeCache.get(i)??n);o!==0&&(this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?r<this.getScrollOffset()+this.scrollAdjustments&&this.scrollDirection!==`backward`:this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[e]??{index:e,key:i,start:r,size:n,end:r+n,lane:0},o,this))&&(Pt()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=o:this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=o,behavior:void 0})),(this.pendingMin===null||e<this.pendingMin)&&(this.pendingMin=e),this.itemSizeCache.set(i,t),this.itemSizeCacheVersion++,this.notify(!1))},this.getVirtualItems=At(()=>[this.getVirtualIndexes(),this.getMeasurements()],(e,t)=>{let n=[];for(let r=0,i=e.length;r<i;r++){let i=t[e[r]];n.push(i)}return n},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=e=>{let t=this.getMeasurements();if(t.length===0)return;let n=this._flatMeasurements,r=this.options.lanes===1&&n!=null;return jt(t[Kt(0,t.length-1,r?e=>n[e*2]:e=>jt(t[e]).start,e)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if(`scrollHeight`in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{let e=this.scrollElement.document.documentElement;return this.options.horizontal?e.scrollWidth-this.scrollElement.innerWidth:e.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(e,t,n=0)=>{if(!this.scrollElement)return 0;let r=this.getSize(),i=this.getScrollOffset();t===`auto`&&(t=e>=i+r?`end`:`start`),t===`center`?e+=(n-r)/2:t===`end`&&(e-=r);let a=this.getMaxScrollOffset();return Math.max(Math.min(a,e),0)},this.getOffsetForIndex=(e,t=`auto`)=>{e=Math.max(0,Math.min(e,this.options.count-1));let n=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[e];if(!i)return;if(t===`auto`)if(i.end>=r+n-this.options.scrollPaddingEnd)t=`end`;else if(i.start<=r+this.options.scrollPaddingStart)t=`start`;else return[r,t];if(t===`end`&&e===this.options.count-1)return[this.getMaxScrollOffset(),t];let a=t===`end`?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,t,i.size),t]},this.scrollToOffset=(e,{align:t=`start`,behavior:n=`auto`}={})=>{let r=this.getOffsetForAlignment(e,t),i=this.now();this.scrollState={index:null,align:t,behavior:n,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(e,{align:t=`auto`,behavior:n=`auto`}={})=>{e=Math.max(0,Math.min(e,this.options.count-1));let r=this.getOffsetForIndex(e,t);if(!r)return;let[i,a]=r,o=this.now();this.scrollState={index:e,align:a,behavior:n,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(e,{behavior:t=`auto`}={})=>{let n=this.getScrollOffset()+e,r=this.now();this.scrollState={index:null,align:`start`,behavior:t,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:t}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{let e=this.getMeasurements(),t;if(e.length===0)t=this.options.paddingStart;else if(this.options.lanes===1){let n=e.length-1,r=this._flatMeasurements;t=r==null?e[n]?.end??0:r[n*2]+r[n*2+1]}else{let n=Array(this.options.lanes).fill(null),r=e.length-1;for(;r>=0&&n.some(e=>e===null);){let t=e[r];n[t.lane]===null&&(n[t.lane]=t.end),r--}t=Math.max(...n.filter(e=>e!==null))}return Math.max(t-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{let e=[];if(this.itemSizeCache.size===0)return e;let t=this.getMeasurements();for(let n of t)n&&this.itemSizeCache.has(n.key)&&e.push({index:n.index,key:n.key,start:n.start,size:n.size,end:n.end,lane:n.lane});return e},this._scrollToOffset=(e,{adjustments:t,behavior:n})=>{this._intendedScrollOffset=e+(t??0),this.options.scrollToFn(e,{behavior:n,adjustments:t},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()})}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}let e=this.scrollState.index==null?void 0:this.getOffsetForIndex(this.scrollState.index,this.scrollState.align),t=e?e[0]:this.scrollState.lastTargetOffset,n=t!==this.scrollState.lastTargetOffset;if(!n&&Mt(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=1){this.getScrollOffset()!==t&&this._scrollToOffset(t,{adjustments:void 0,behavior:`auto`}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,n){let e=this.getSize()||600,n=Math.abs(t-this.getScrollOffset()),r=this.scrollState.behavior===`smooth`&&n>e;this.scrollState.lastTargetOffset=t,r||(this.scrollState.behavior=`auto`),this._scrollToOffset(t,{adjustments:void 0,behavior:r?`smooth`:`auto`})}this.scheduleScrollReconcile()}},Kt=(e,t,n,r)=>{for(;e<=t;){let i=(e+t)/2|0,a=n(i);if(a<r)e=i+1;else if(a>r)t=i-1;else return i}return e>0?e-1:0};function qt({measurements:e,outerSize:t,scrollOffset:n,lanes:r,flat:i}){let a=e.length-1,o=i?e=>i[e*2]:t=>e[t].start,s=i?e=>i[e*2]+i[e*2+1]:t=>e[t].end;if(e.length<=r)return{startIndex:0,endIndex:a};let c=Kt(0,a,o,n),l=c;if(r===1)for(;l<a&&s(l)<n+t;)l++;else if(r>1){let i=Array(r).fill(0);for(;l<a&&i.some(e=>e<n+t);){let t=e[l];i[t.lane]=t.end,l++}let o=Array(r).fill(n+t);for(;c>=0&&o.some(e=>e>=n);){let t=e[c];o[t.lane]=t.start,c--}c=Math.max(0,c-c%r),l=Math.min(a,l+(r-1-l%r))}return{startIndex:c,endIndex:l}}var Jt=typeof document<`u`?G.useLayoutEffect:G.useEffect;function Yt({useFlushSync:e=!0,...t}){let n=G.useReducer(e=>e+1,0)[1],r={...t,onChange:(r,i)=>{var a;e&&i?(0,Ot.flushSync)(n):n(),(a=t.onChange)==null||a.call(t,r,i)}},[i]=G.useState(()=>new Gt(r));return i.setOptions(r),Jt(()=>i._didMount(),[]),Jt(()=>i._willUpdate()),i}function Xt(e){return Yt({observeElementRect:Rt,observeElementOffset:Ht,scrollToFn:Wt,...e})}var Zt={"grid.import.title":`Import {{object}}`,"grid.import.stepUpload":`Upload`,"grid.import.stepMapping":`Mapping`,"grid.import.stepPreview":`Preview`,"grid.import.uploadDescription":`Upload a CSV file to get started.`,"grid.import.mappingDescription":`Map CSV columns to object fields.`,"grid.import.previewDescription":`Review data before importing.`,"grid.import.dragDrop":`Drag & drop a CSV file here, or click to browse`,"grid.import.browseFiles":`Browse Files`,"grid.import.onlyCsv":`Only CSV files are supported.`,"grid.import.fileNeedsHeader":`File must contain a header row and at least one data row.`,"grid.import.mappingTemplate":`Mapping template:`,"grid.import.chooseTemplate":`Choose template…`,"grid.import.noSavedTemplates":`No saved templates`,"grid.import.noneOption":`— None —`,"grid.import.saveCurrent":`Save current`,"grid.import.templateName":`Template name`,"grid.import.save":`Save`,"grid.import.deleteTemplate":`Delete template`,"grid.import.csvColumn":`CSV Column`,"grid.import.mapsTo":`Maps To`,"grid.import.status":`Status`,"grid.import.skipColumn":`Skip column`,"grid.import.skip":`— Skip —`,"grid.import.mapped":`Mapped`,"grid.import.skipped":`Skipped`,"grid.import.rowsWithErrors":`{{count}} row(s) with errors`,"grid.import.rowsCorrected":`{{count}} row(s) corrected`,"grid.import.clickToFix":`— click a highlighted cell to fix it inline.`,"grid.import.showingRows":`Showing {{shown}} of {{total}} rows`,"grid.import.importing":`Importing… {{progress}}%`,"grid.import.importComplete":`Import Complete`,"grid.import.imported":`{{count}} imported`,"grid.import.skippedCount":`{{count}} skipped`,"grid.import.moreErrors":`…and {{count}} more errors`,"grid.import.cancel":`Cancel`,"grid.import.back":`Back`,"grid.import.next":`Next`,"grid.import.close":`Close`,"grid.import.importNRows":`Import {{count}} Rows`,"grid.import.importingProgress":`Importing…`,"grid.import.required":`Required`,"grid.import.invalidType":`Invalid {{type}}`};function Qt(e,t){if(!t)return e;let n=e;for(let[e,r]of Object.entries(t))n=n.replace(RegExp(`{{${e}}}`,`g`),String(r));return n}function $t(){let e=(e,t)=>Qt(Zt[e]??e,t);try{let t=g();return t.t(`grid.import.title`)===`grid.import.title`?{t:e}:{t:(n,r)=>{let i=t.t(n,r);return i===n?e(n,r):i}}}catch{return{t:e}}}var en=10;function tn(e){let t=[],n=[],r=``,i=!1;for(let a=0;a<e.length;a++){let o=e[a],s=e[a+1];i?o===`"`&&s===`"`?(r+=`"`,a++):o===`"`?i=!1:r+=o:o===`"`?i=!0:o===`,`?(n.push(r.trim()),r=``):o===`
5
- `||o===`\r`&&s===`
6
- `?(n.push(r.trim()),n.some(e=>e!==``)&&t.push(n),n=[],r=``,o===`\r`&&a++):r+=o}return n.push(r.trim()),n.some(e=>e!==``)&&t.push(n),t}function nn(e,t){if(!e)return!0;switch(t){case`number`:case`currency`:case`percent`:return!isNaN(Number(e));case`boolean`:return[`true`,`false`,`1`,`0`,`yes`,`no`].includes(e.toLowerCase());case`date`:case`datetime`:return!isNaN(Date.parse(e));default:return!0}}function rn(e,t){let n={};return e.forEach((e,r)=>{let i=e.toLowerCase().replace(/[_\s-]/g,``),a=t.find(e=>{let t=e.name.toLowerCase().replace(/[_\s-]/g,``),n=e.label.toLowerCase().replace(/[_\s-]/g,``);return t===i||n===i});a&&(n[r]=a.name)}),n}function an(){if(typeof window>`u`)return null;try{return window.localStorage}catch{return null}}function on(e,t){if(!e)return[];try{let n=e.getItem(t);if(!n)return[];let r=JSON.parse(n);return Array.isArray(r)?r.filter(e=>e&&e.id&&e.name&&e.mapping):[]}catch{return[]}}function sn(e,t,n){if(e)try{e.setItem(t,JSON.stringify(n))}catch{}}function cn(e,t){let n={};return Object.entries(t).forEach(([t,r])=>{let i=e[Number(t)];i&&(n[i.trim().toLowerCase()]=r)}),n}function ln(e,t,n){let r=new Set(n.map(e=>e.name)),i={};return t.forEach((t,n)=>{let a=e.mapping[t.trim().toLowerCase()];a&&r.has(a)&&(i[n]=a)}),i}function un(e,t,n){let r=[],i={};for(let a of t){let t=e[a.csvIdx]??``;if(a.field.required&&!t){r.push({row:n,field:a.field.name,message:`Required field is empty`});continue}if(t&&!nn(t,a.field.type)){r.push({row:n,field:a.field.name,message:`Invalid ${a.field.type} value: "${t}"`});continue}i[a.field.name]=t}return{record:i,errors:r}}var dn=({onFileLoaded:e})=>{let{t}=$t(),[n,r]=(0,G.useState)(!1),[i,a]=(0,G.useState)(null),o=(0,G.useCallback)(n=>{if(a(null),!n.name.endsWith(`.csv`)){a(t(`grid.import.onlyCsv`));return}let r=new FileReader;r.onload=n=>{let r=tn(n.target?.result);if(r.length<2){a(t(`grid.import.fileNeedsHeader`));return}e(r[0],r.slice(1))},r.readAsText(n)},[e,t]);return(0,Y.jsxs)(`div`,{className:`flex flex-col items-center gap-4 py-6`,children:[(0,Y.jsxs)(`div`,{className:L(`flex w-full flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed p-10 transition-colors`,n?`border-primary bg-primary/5`:`border-muted-foreground/25`),onDragOver:e=>{e.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:e=>{e.preventDefault(),r(!1);let t=e.dataTransfer.files[0];t&&o(t)},children:[(0,Y.jsx)(k,{className:`h-10 w-10 text-muted-foreground`}),(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t(`grid.import.dragDrop`)}),(0,Y.jsxs)(`label`,{children:[(0,Y.jsx)(`input`,{type:`file`,accept:`.csv`,className:`hidden`,onChange:e=>{let t=e.target.files?.[0];t&&o(t)}}),(0,Y.jsx)(V,{variant:`outline`,size:`sm`,asChild:!0,children:(0,Y.jsx)(`span`,{children:t(`grid.import.browseFiles`)})})]})]}),i&&(0,Y.jsxs)(`p`,{className:`flex items-center gap-1 text-sm text-destructive`,children:[(0,Y.jsx)(Me,{className:`h-4 w-4`}),` `,i]})]})},fn=({templates:e,selectedId:t,onSelect:n,onSaveAs:r,onDelete:i,disabled:a})=>{let{t:o}=$t(),[s,c]=(0,G.useState)(``),[l,u]=(0,G.useState)(!1);return(0,Y.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center gap-2 rounded-md border bg-muted/30 p-2`,"data-testid":`import-template-bar`,children:[(0,Y.jsx)(pe,{className:`h-4 w-4 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:o(`grid.import.mappingTemplate`)}),(0,Y.jsxs)(M,{value:t??`__none__`,onValueChange:e=>e!==`__none__`&&n(e),children:[(0,Y.jsx)(P,{className:`h-7 w-48 text-xs`,"data-testid":`import-template-select`,children:(0,Y.jsx)(T,{placeholder:e.length?o(`grid.import.chooseTemplate`):o(`grid.import.noSavedTemplates`)})}),(0,Y.jsxs)(W,{children:[(0,Y.jsx)(x,{value:`__none__`,disabled:e.length===0,children:e.length?o(`grid.import.noneOption`):o(`grid.import.noSavedTemplates`)}),e.map(e=>(0,Y.jsx)(x,{value:e.id,children:e.name},e.id))]})]}),l?(0,Y.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Y.jsx)(Oe,{value:s,onChange:e=>c(e.target.value),placeholder:o(`grid.import.templateName`),className:`h-7 w-40 text-xs`,"data-testid":`import-template-name-input`,autoFocus:!0}),(0,Y.jsx)(V,{type:`button`,size:`sm`,onClick:()=>{s.trim()&&(r(s.trim()),c(``),u(!1))},disabled:!s.trim()||a,"data-testid":`import-template-confirm-save`,children:o(`grid.import.save`)}),(0,Y.jsx)(V,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{u(!1),c(``)},children:o(`grid.import.cancel`)})]}):(0,Y.jsx)(V,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>u(!0),disabled:a,"data-testid":`import-template-save-btn`,children:o(`grid.import.saveCurrent`)}),t&&(0,Y.jsx)(V,{type:`button`,variant:`ghost`,size:`sm`,onClick:i,"aria-label":o(`grid.import.deleteTemplate`),"data-testid":`import-template-delete-btn`,children:(0,Y.jsx)(j,{className:`h-3.5 w-3.5`})})]})},pn=({headers:e,fields:t,mapping:n,onMappingChange:r,templates:i,selectedTemplateId:a,onSelectTemplate:o,onSaveTemplate:s,onDeleteTemplate:c})=>{let{t:l}=$t(),u=(0,G.useMemo)(()=>new Set(Object.values(n)),[n]),d=(0,G.useCallback)((e,t)=>{let i={...n};t===`__skip__`?delete i[e]:i[e]=t,r(i)},[n,r]);return(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(fn,{templates:i,selectedId:a,onSelect:o,onSaveAs:s,onDelete:c,disabled:Object.keys(n).length===0}),(0,Y.jsx)(`div`,{className:`max-h-[420px] overflow-auto`,children:(0,Y.jsxs)(Ue,{children:[(0,Y.jsx)(Ge,{children:(0,Y.jsxs)(De,{children:[(0,Y.jsx)(ze,{children:l(`grid.import.csvColumn`)}),(0,Y.jsx)(ze,{children:l(`grid.import.mapsTo`)}),(0,Y.jsx)(ze,{className:`w-24 text-center`,children:l(`grid.import.status`)})]})}),(0,Y.jsx)(Ne,{children:e.map((e,r)=>(0,Y.jsxs)(De,{children:[(0,Y.jsx)(R,{className:`font-medium`,children:e}),(0,Y.jsx)(R,{children:(0,Y.jsxs)(M,{value:n[r]??`__skip__`,onValueChange:e=>d(r,e),children:[(0,Y.jsx)(P,{className:`h-8 w-56`,children:(0,Y.jsx)(T,{placeholder:l(`grid.import.skipColumn`)})}),(0,Y.jsxs)(W,{children:[(0,Y.jsx)(x,{value:`__skip__`,children:l(`grid.import.skip`)}),t.map(e=>(0,Y.jsxs)(x,{value:e.name,disabled:u.has(e.name)&&n[r]!==e.name,children:[e.label,e.required?` *`:``]},e.name))]})]})}),(0,Y.jsx)(R,{className:`text-center`,children:n[r]?(0,Y.jsx)(ce,{variant:`default`,className:`text-xs`,children:l(`grid.import.mapped`)}):(0,Y.jsx)(ce,{variant:`secondary`,className:`text-xs`,children:l(`grid.import.skipped`)})})]},r))})]})})]})},mn=({headers:e,rows:t,mapping:n,fields:r,corrections:i,onCorrect:a})=>{let{t:o}=$t(),s=(0,G.useMemo)(()=>Object.entries(n).map(([t,n])=>({csvIdx:Number(t),header:e[Number(t)],field:r.find(e=>e.name===n)})),[n,e,r]),c=t.slice(0,en),l=(0,G.useCallback)((e,t)=>{let n=i[e]?.[t];return n===void 0?c[e]?.[t]??``:n},[i,c]),u=(0,G.useMemo)(()=>c.map((e,t)=>{let n={};for(let e of s){let r=l(t,e.csvIdx);e.field.required&&!r?n[e.csvIdx]=o(`grid.import.required`):r&&!nn(r,e.field.type)&&(n[e.csvIdx]=o(`grid.import.invalidType`,{type:e.field.type}))}return n}),[c,s,l,o]),d=u.filter(e=>Object.keys(e).length>0).length,f=Object.keys(i).length;return(0,Y.jsxs)(`div`,{className:`max-h-[440px] overflow-auto`,children:[(d>0||f>0)&&(0,Y.jsxs)(`p`,{className:`mb-2 flex items-center gap-2 text-xs`,"data-testid":`import-preview-status`,children:[d>0&&(0,Y.jsxs)(`span`,{className:`flex items-center gap-1 text-destructive`,children:[(0,Y.jsx)(Me,{className:`h-3.5 w-3.5`}),` `,o(`grid.import.rowsWithErrors`,{count:d})]}),f>0&&(0,Y.jsxs)(`span`,{className:`flex items-center gap-1 text-emerald-600`,children:[(0,Y.jsx)(H,{className:`h-3.5 w-3.5`}),` `,o(`grid.import.rowsCorrected`,{count:f})]}),(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:o(`grid.import.clickToFix`)})]}),(0,Y.jsxs)(Ue,{children:[(0,Y.jsx)(Ge,{children:(0,Y.jsxs)(De,{children:[(0,Y.jsx)(ze,{className:`w-12`,children:`#`}),s.map(e=>(0,Y.jsx)(ze,{children:e.field.label},e.csvIdx))]})}),(0,Y.jsx)(Ne,{children:c.map((e,t)=>{let n=u[t],r=Object.keys(n).length>0,o=i[t]!==void 0;return(0,Y.jsxs)(De,{className:L(r&&`bg-destructive/5`,!r&&o&&`bg-emerald-50 dark:bg-emerald-950/20`),"data-testid":`import-preview-row-${t}`,children:[(0,Y.jsx)(R,{className:`text-xs text-muted-foreground`,children:t+1}),s.map(e=>{let r=l(t,e.csvIdx),o=n[e.csvIdx],s=i[t]?.[e.csvIdx]!==void 0;return(0,Y.jsx)(R,{className:L(o&&`text-destructive`,s&&!o&&`text-emerald-600`),title:o,children:(0,Y.jsx)(Oe,{value:r,onChange:n=>a(t,e.csvIdx,n.target.value),className:L(`h-7 px-1 text-xs`,o&&`border-destructive`,s&&!o&&`border-emerald-500`),"data-testid":`import-preview-cell-${t}-${e.csvIdx}`,"aria-invalid":o?`true`:`false`,"aria-label":`${e.field.label} for row ${t+1}`})},e.csvIdx)})]},t)})})]}),(0,Y.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:o(`grid.import.showingRows`,{shown:c.length,total:t.length})})]})},hn=({objectName:e,objectLabel:t,fields:n,dataSource:r,onComplete:i,onCancel:a,open:o,onOpenChange:s,onErrorMode:c=`skip`,templateStorageKey:l,templateStorage:u})=>{let[d,f]=(0,G.useState)(`upload`),[p,m]=(0,G.useState)([]),[h,g]=(0,G.useState)([]),[_,v]=(0,G.useState)({}),[y,ee]=(0,G.useState)(!1),[x,S]=(0,G.useState)(0),[C,te]=(0,G.useState)(null),[w,re]=(0,G.useState)({}),ie=t??e,T=(0,G.useMemo)(()=>u===void 0?an():u,[u]),E=l??`objectui:import-templates:${e}`,[O,k]=(0,G.useState)(()=>on(T,E)),[A,oe]=(0,G.useState)(null);(0,G.useEffect)(()=>{k(on(T,E))},[T,E]);let se=(0,G.useCallback)(e=>{let t=O.find(t=>t.id===e);t&&(oe(e),v(ln(t,p,n)))},[O,p,n]),le=(0,G.useCallback)(e=>{let t={id:`tpl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,name:e,mapping:cn(p,_),updatedAt:Date.now()},n=[...O,t];k(n),oe(t.id),sn(T,E,n)},[O,p,_,T,E]),ue=(0,G.useCallback)(()=>{if(!A)return;let e=O.filter(e=>e.id!==A);k(e),oe(null),sn(T,E,e)},[O,A,T,E]),j=(0,G.useCallback)((e,t,n)=>{re(r=>{let i={...r},a={...i[e]??{}};return n===(h[e]?.[t]??``)?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,i})},[h]),M=(0,G.useMemo)(()=>{let e=new Set(Object.values(_));return n.filter(t=>t.required&&!e.has(t.name))},[n,_]),fe=(0,G.useCallback)((e,t)=>{m(e),g(t),v(rn(e,n)),re({}),f(`mapping`)},[n]),pe=(0,G.useCallback)(async()=>{ee(!0),S(0);let t=[],a=0,o=0,s=Object.entries(_).map(([e,t])=>({csvIdx:Number(e),field:n.find(e=>e.name===t)}));for(let n=0;n<h.length;n++){let i=h[n],l=w[n],{record:u,errors:d}=un(l?i.map((e,t)=>l[t]===void 0?e:l[t]):i,s,n+1);if(d.length>0){if(o++,t.push(...d),c===`stop`)break}else try{r?.create&&await r.create(e,u),a++}catch(e){o++;let r=e instanceof Error?e.message:`Failed to create record`;if(t.push({row:n+1,field:``,message:r}),c===`stop`)break}S(Math.round((n+1)/h.length*100))}let l={totalRows:h.length,importedRows:a,skippedRows:o,errors:t};te(l),ee(!1),i?.(l)},[h,_,n,r,e,i,c,w]),me=(0,G.useCallback)(()=>{f(`upload`),m([]),g([]),v({}),S(0),te(null),re({}),oe(null)},[]),N=(0,G.useCallback)(()=>{me(),s?.(!1),a?.()},[me,s,a]),{t:P}=$t();return(0,Y.jsx)(ne,{open:o,onOpenChange:e=>{e?s?.(e):N()},children:(0,Y.jsxs)(ae,{className:`flex max-h-[85vh] flex-col gap-4 overflow-hidden sm:max-w-4xl`,children:[(0,Y.jsxs)(U,{children:[(0,Y.jsxs)(b,{className:`flex items-center gap-2`,children:[(0,Y.jsx)(Ye,{className:`h-5 w-5`}),` `,P(`grid.import.title`,{object:ie})]}),(0,Y.jsxs)(D,{children:[d===`upload`&&P(`grid.import.uploadDescription`),d===`mapping`&&P(`grid.import.mappingDescription`),d===`preview`&&P(`grid.import.previewDescription`)]})]}),(0,Y.jsx)(`div`,{className:`flex items-center justify-center gap-2 text-xs text-muted-foreground`,children:[`upload`,`mapping`,`preview`].map((e,t)=>(0,Y.jsxs)(G.Fragment,{children:[t>0&&(0,Y.jsx)(ge,{className:`h-3 w-3`}),(0,Y.jsxs)(`span`,{className:L(`rounded-full px-3 py-1`,d===e?`bg-primary text-primary-foreground`:`bg-muted`),children:[t+1,`. `,P(e===`upload`?`grid.import.stepUpload`:e===`mapping`?`grid.import.stepMapping`:`grid.import.stepPreview`)]})]},e))}),(0,Y.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:C?(0,Y.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-4`,children:[(0,Y.jsx)(H,{className:`h-10 w-10 text-green-500`}),(0,Y.jsx)(`p`,{className:`text-lg font-semibold`,children:P(`grid.import.importComplete`)}),(0,Y.jsxs)(`div`,{className:`flex gap-3`,children:[(0,Y.jsx)(ce,{variant:`default`,children:P(`grid.import.imported`,{count:C.importedRows})}),C.skippedRows>0&&(0,Y.jsx)(ce,{variant:`destructive`,children:P(`grid.import.skippedCount`,{count:C.skippedRows})})]}),C.errors.length>0&&(0,Y.jsxs)(`div`,{className:`max-h-32 w-full overflow-auto rounded border p-2 text-xs`,children:[C.errors.slice(0,10).map((e,t)=>(0,Y.jsxs)(`p`,{className:`text-destructive`,children:[`Row `,e.row,e.field?` (${e.field})`:``,`: `,e.message]},t)),C.errors.length>10&&(0,Y.jsx)(`p`,{className:`text-muted-foreground`,children:P(`grid.import.moreErrors`,{count:C.errors.length-10})})]})]}):(0,Y.jsxs)(Y.Fragment,{children:[d===`upload`&&(0,Y.jsx)(dn,{onFileLoaded:fe}),d===`mapping`&&(0,Y.jsx)(pn,{headers:p,fields:n,mapping:_,onMappingChange:v,templates:O,selectedTemplateId:A,onSelectTemplate:se,onSaveTemplate:le,onDeleteTemplate:ue}),d===`preview`&&(0,Y.jsx)(mn,{headers:p,rows:h,mapping:_,fields:n,corrections:w,onCorrect:j}),y&&(0,Y.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,Y.jsx)(F,{value:x,className:`h-2`}),(0,Y.jsx)(`p`,{className:`text-center text-xs text-muted-foreground`,children:P(`grid.import.importing`,{progress:x})})]})]})}),(0,Y.jsx)(de,{className:`gap-2 sm:gap-0`,children:C?(0,Y.jsx)(V,{onClick:N,children:P(`grid.import.close`)}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(V,{variant:`ghost`,onClick:N,disabled:y,children:[(0,Y.jsx)(Je,{className:`mr-1 h-4 w-4`}),` `,P(`grid.import.cancel`)]}),(d===`mapping`||d===`preview`)&&(0,Y.jsxs)(V,{variant:`outline`,onClick:()=>f(d===`mapping`?`upload`:`mapping`),disabled:y,children:[(0,Y.jsx)(he,{className:`mr-1 h-4 w-4`}),` `,P(`grid.import.back`)]}),d===`mapping`&&(0,Y.jsxs)(V,{onClick:()=>f(`preview`),disabled:Object.keys(_).length===0||M.length>0,children:[P(`grid.import.next`),` `,(0,Y.jsx)(ge,{className:`ml-1 h-4 w-4`})]}),d===`preview`&&(0,Y.jsx)(V,{onClick:pe,disabled:y,children:y?P(`grid.import.importingProgress`):P(`grid.import.importNRows`,{count:h.length})})]})})]})})},gn=t({ImportWizard:()=>hn,ObjectGrid:()=>Dt,ObjectGridRenderer:()=>_n}),_n=({schema:e,...t})=>{let{dataSource:n}=f()||{};return(0,Y.jsx)(Dt,{schema:e,dataSource:n,...t})};m.register(`object-grid`,_n,{namespace:`plugin-grid`,label:`Object Grid`,category:`plugin`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`columns`,type:`array`,label:`Columns`},{name:`filters`,type:`array`,label:`Filters`}]}),m.register(`grid`,_n,{namespace:`view`,label:`Data Grid`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`columns`,type:`array`,label:`Columns`},{name:`filters`,type:`array`,label:`Filters`}]}),m.register(`import-wizard`,({schema:e,...t})=>{let{dataSource:n}=f()||{};return(0,Y.jsx)(hn,{objectName:e.objectName,objectLabel:e.objectLabel,fields:e.fields??[],dataSource:n,...t})},{namespace:`plugin-grid`,label:`Import Wizard`,category:`plugin`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`fields`,type:`array`,label:`Fields`,required:!0}]});export{Ze as a,Qe as i,Xt as n,Dt as r,gn as t};