1import{j as e,r as x,M as qe,a5 as rt,aA as ga,R as Xt,L as St,a8 as ba,a9 as fa,ab as ya,ah as _t,ad as ja,ae as Na,aa as Ea,af as va,ap as Ra,a_ as wa,a$ as Pe}from"./vendor-CxNwWgkB.js";import{c as ue,p as es,G as Le,k as $,X as Me,aA as pe,aU as nt,cI as ka,ah as ts,cJ as Ft,j as ae,aW as ss,a7 as as,cK as rs,cL as Be,aM as K,aL as Ca,h as O,A as Je,b9 as ce,aB as Ta,aC as Ma,s as Da,aE as Sa,cM as ns,cN as ds,aJ as ls,t as _a,U as Fa,cO as Aa,cP as Ia,ac as os,ae as is,cQ as Oa,bC as qa,S as P,bH as Re,cR as se,aP as At,N as La,aT as Ba,q as cs,a8 as $a,aZ as us,a_ as Pa,cS as Ua,b2 as It,b1 as Ot,b3 as He,bp as Ka,bh as Va,bM as Ya,aY as ms,cT as k,b as ps,cU as za,V as Wa,bl as Qa,cp as Ga,W as qt}from"./index-BMuMptbK.js";import{C as Ja}from"./copy-ZY583Ae0.js";import{u as ze,c as De,a as he,b as xs,d as hs}from"./index.esm-DYVCYnMZ.js";import{E as be}from"./EmptyState-CLm3R8Yi.js";import{f as Se}from"./formatDate-Yn3jBN_p.js";import{u as gs,a as bs,b as Ha,c as Za,d as Xa,e as er,f as fs,g as tr,h as sr,i as ar,j as ys,k as rr,l as nr,m as dr,n as lr,o as or}from"./queries.generated-C1uyfpDO.js";import{C as ir}from"./calendar-days-CUfLxdbn.js";import{C as cr,L as js}from"./lock-BDR2y1R0.js";import{F as ur}from"./file-text-DTkZCW-a.js";import{S as dt}from"./Select-C6PxYOwE.js";import{c as Ns}from"./react-select.esm-CBaSxf6k.js";import{C as st}from"./circle-check-big-DR9qOfoR.js";import{D as xe}from"./database-CWvWvimP.js";import{A as Ke}from"./arrow-right-CZD27QwR.js";import{I as at}from"./IndeterminateCheckbox-BeJCXWk5.js";import{c as mr,u as pr,f as Lt,g as xr}from"./index-BQfc6pMk.js";import{T as hr}from"./Table-CJJwOoVi.js";import{g as Es}from"./generateEmailColor-CDwhOD_M.js";import{C as vs}from"./calendar-Uz46TCML.js";import{D as gr,S as br,v as fr,b as yr,d as jr,C as Nr}from"./sortable.esm-DRWtQQx-.js";import{P as Er}from"./index-CRjySEeO.js";import{D as vr}from"./Delete-4_FFZncm.js";import{A as Rr}from"./Add-BUWYccWP.js";import{C as wr}from"./CodeBlock-BbFYn3TU.js";import{D as kr}from"./download-CSaGsa3o.js";import{C as Cr}from"./chevron-left-7gZiefhT.js";import{F as Tr}from"./empty-comments-CEHorlka.js";import{C as Mr}from"./index-DgkPidO1.js";import"./SuspenseWrapper-DTGH05b4.js";import"./PlayCircleOutlined-I4a5VHwW.js";import"./objectWithoutPropertiesLoose-BT2thIKb.js";(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};t.SENTRY_RELEASE={id:"f0a3856bf84d79654b4faceedc4040f499eb23a4"};var a=new t.Error().stack;a&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[a]="22e18ddf-fd43-45ab-a6ab-f679d4713ded",t._sentryDebugIdIdentifier="sentry-dbid-22e18ddf-fd43-45ab-a6ab-f679d4713ded")}catch{}})();/** 2 * @license lucide-react v0.511.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const Dr=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8",key:"7n84p3"}]],Sr=ue("at-sign",Dr);/** 7 * @license lucide-react v0.511.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const _r=[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]],Fr=ue("braces",_r);/** 12 * @license lucide-react v0.511.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const Ar=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 15 21.84",key:"14ibmq"}],["path",{d:"M21 5V8",key:"1marbg"}],["path",{d:"M21 12L18 17H22L19 22",key:"zafso"}],["path",{d:"M3 12A9 3 0 0 0 14.59 14.87",key:"1y4wr8"}]],Ir=ue("database-zap",Ar);/** 17 * @license lucide-react v0.511.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const Or=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],qr=ue("ellipsis",Or);/** 22 * @license lucide-react v0.511.0 - ISC 23 * 24 * This source code is licensed under the ISC license. 25 * See the LICENSE file in the root directory of this source tree. 26 */const Lr=[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 15h6",key:"4e2qda"}],["path",{d:"M6 12v6",key:"1u72j0"}]],Br=ue("file-plus-2",Lr);/** 27 * @license lucide-react v0.511.0 - ISC 28 * 29 * This source code is licensed under the ISC license. 30 * See the LICENSE file in the root directory of this source tree. 31 */const $r=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}
31]],Bt=ue("hash",$r);/** 32 * @license lucide-react v0.511.0 - ISC 33 * 34 * This source code is licensed under the ISC license. 35 * See the LICENSE file in the root directory of this source tree. 36 */const Pr=[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]],Ur=ue("image-off",Pr);/** 37 * @license lucide-react v0.511.0 - ISC 38 * 39 * This source code is licensed under the ISC license. 40 * See the LICENSE file in the root directory of this source tree. 41 */const Kr=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],_e=ue("link-2",Kr);/** 42 * @license lucide-react v0.511.0 - ISC 43 * 44 * This source code is licensed under the ISC license. 45 * See the LICENSE file in the root directory of this source tree. 46 */const Vr=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],Yr=ue("link",Vr);/** 47 * @license lucide-react v0.511.0 - ISC 48 * 49 * This source code is licensed under the ISC license. 50 * See the LICENSE file in the root directory of this source tree. 51 */const zr=[["path",{d:"M5 12h14",key:"1ays0h"}]],Wr=ue("minus",zr);/** 52 * @license lucide-react v0.511.0 - ISC 53 * 54 * This source code is licensed under the ISC license. 55 * See the LICENSE file in the root directory of this source tree. 56 */const Qr=[["circle",{cx:"9",cy:"12",r:"3",key:"u3jwor"}],["rect",{width:"20",height:"14",x:"2",y:"5",rx:"7",key:"g7kal2"}]],Gr=ue("toggle-left",Qr);/** 57 * @license lucide-react v0.511.0 - ISC 58 * 59 * This source code is licensed under the ISC license. 60 * See the LICENSE file in the root directory of this source tree. 61 */const Jr=[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]],Ve=ue("type",Jr),Hr=es(e.jsx("path",{d:"M11 18c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2m-2-8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m6 4c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2m0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2"}),"DragIndicator"),Zr=es(e.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}),"Storage"),Xr=({onClose:t})=>{const{createToastAlert:a}=Le(),s=async()=>{var r;const d=`Data Tables Documentation - @memberstack/dom (DOM + Webflow) 62 63This document describes the Data Tables client methods exposed by @memberstack/dom, their exact parameters, and the raw REST requests they issue. It also calls out the current server response shapes and known mismatches so you can integrate with 100% accuracy. 64 65Rate limits (server): 66- Global (all client REST routes): 200 requests per 30 seconds per IP 67- Data Tables â Reads: 25 requests per second per IP (Applies to: GET /v1/data-tables, GET /v1/data-tables/:tableKey, POST /v1/data-records/query, GET /v1/data-records) 68- Data Tables â Creates: 10 requests per minute per IP (POST /v1/data-records) 69- Data Tables â Writes: 30 requests per minute per IP (PUT/DELETE /v1/data-records/:recordId) 70 71Quick start (DOM + Webflow): 72// Option A: Using @memberstack/dom directly 73import MemberstackDOM from '@memberstack/dom'; 74const memberstack = MemberstackDOM.init({ publicKey: 'pk_sb_123', appId: 'app_123' }); 75 76// Option B: Using the Memberstack script tag 77// The DOM methods are exposed globally via window.$memberstackDom 78const memberstackScript = window.$memberstackDom; // same methods as shown below 79 80Feature flag: 81If the environment variable DISABLE_DATA_TABLES is set to a truthy value on the server, all routes return 503 with message: "Data table feature is temporarilly offline." 82 83getDataTables 84Method: memberstack.getDataTables(options?) 85SDK type: (): Promise<Payloads.GetDataTablesPayload> 86REST call: GET /v1/data-tables 87 88Request: 89- Optional options.token overrides the Authorization header. 90 91Response (server): 92{ 93 "data": { 94 "tables": [ 95 { 96 "id": "tbl_...", 97 "key": "articles", 98 "name": "Articles", 99 "createRule": "...", 100 "readRule": "...", 101 "updateRule": "...", 102 "deleteRule": "...", 103 "createdAt": "2024-08-21T00:00:00.000Z", 104 "updatedAt": "2024-08-22T00:00:00.000Z", 105 "recordCount": 123, 106 "fields": [ 107 { 108 "id": "fld_...", 109 "key": "title", 110 "name": "Title", 111 "type": "TEXT", 112 "required": true, 113 "defaultValue": null, 114 "tableOrder": 1, 115 "referencedTableId": null, 116 "referencedTable": null 117 } 118 ] 119 } 120 ] 121 } 122} 123 124Notes: 125- Field objects do NOT contain unique in the current server response
125(the SDK's local type includes unique, but the server does not return it). 126- recordCount reflects only records accessible to the active context (access rules and auth are applied). 127 128Example (SDK / Webflow): 129const { data } = await memberstack.getDataTables(); 130data.tables.forEach((t) => { 131 console.log(\`\${t.key} â \${t.recordCount} records\`); 132}); 133 134getDataTable 135Method: memberstack.getDataTable(params, options?) 136Params: { table: string } 137SDK type: (params: Params.GetDataTableParams): Promise<Payloads.GetDataTablePayload> 138REST call: GET /v1/data-tables/:tableKey 139 140Response (server): 141{ "data": { /* DataTableResponse object (same shape as in getDataTables.tables[i]) */ } } 142 143Example (SDK / Webflow): 144const { data } = await memberstack.getDataTable({ table: 'cars' }); 145console.log(data.name, data.fields.length); 146 147Listing Records 148Prefer memberstack.queryDataRecords with findMany for listing, filtering, includes, and counts. See the "data-records/query â Includes, Counts, and Pagination" section below for full examples and pagination patterns. 149 150Example (SDK / Webflow): 151// First page 152let { data } = await memberstack.queryDataRecords({ 153 table: 'cars', 154 query: { 155 findMany: { 156 where: { make: { equals: 'Tesla' } }, 157 orderBy: { createdAt: 'desc' }, 158 take: 20 159 } 160 } 161}); 162 163console.log('Fetched', data.records.length, 'records'); 164 165// Next page using endCursor 166if (data.pagination?.hasMore && data.pagination.endCursor) { 167 const next = await memberstack.queryDataRecords({ 168 table: 'cars', 169 query: { 170 findMany: { 171 where: { make: { equals: 'Tesla' } }, 172 orderBy: { createdAt: 'desc' }, 173 take: 20, 174 after: String(data.pagination.endCursor) 175 } 176 } 177 }); 178 console.log('Fetched next page:', next.data.records.length); 179} 180 181createDataRecord 182Method: memberstack.createDataRecord(params, options?) 183SDK Params type: 184type CreateDataRecordParams = { 185 table: string; // UPDATED: SDK now requires 'table' 186 data: Record<string, any>; 187 memberId?: string; // optional, server ignores this field 188}; 189 190REST call: POST /v1/data-records with body { table, data, memberId? } 191 192Response (server on success): 193{ 194 "data": { 195 "id": "rec_...", 196 "tableKey": "articles", 197 "createdByMemberId": "mem_...", 198 "data": { /* typed field data */ }, 199 "createdAt": "...", 200 "updatedAt": "...", 201 "internalOrder": 123456, 202 "activeMemberOwnsIt": true 203 }, 204 "_internalUseOnly": { "message": "..." } 205} 206 207Notes: 208- SDK/server now aligned on body shape for create (table). 209- _internalUseOnly may be included in responses but is not part of the public SDK typings. 210 211Example (SDK / Webflow): 212const { data } = await memberstack.createDataRecord({ 213 table: 'cars', 214 data: { 215 make: 'Tesla', 216 model: 'Model 3', 217 year: 2022 218 } 219}); 220 221console.log('Created record:', data.id); 222 223getDataRecord 224Method: memberstack.getDataRecord(params, options?) 225Params type: 226type GetDataRecordParams = { table: string; recordId: string }; 227 228REST call (SDK issues): POST /v1/data-records/query with body: 229{ 230 "query": { 231 "findUnique": { 232 "where": { "id": "rec_..." } 233 } 234 } 235} 236 237Server expectation (IMPORTANT): 238Body must include the table key and the id must be wrapped in a where clause: 239{ 240 "table": "articles", 241 "query": { 242 "findUnique": { 243 "where": { "id": "rec_..." } 244 } 245 } 246} 247 248- The SDK includes table and wraps id under where, satisfying server requirements. 249 250SDK response normalization: 251The server returns { data: { record } }. The SDK unwraps this and returns { data: record } to match GetDataRecordPayload. 252 253Response (server on success): 254{ "data": { "record": { /* DataRecordResponse */ } } } 255 256Notes: 257SDK and server are aligned on request shape, and the SDK unwraps { data: { record } } to { data: record } for convenience. 258 259Example (SDK / Webflow): 260const { data } = await memberstack.getDataRecord({ 261 table: 'cars', 262 recordId: 'rec_abc123' 263}); 264 265console.log(data.data.make, data.data.model); 266 267updateDataRecord 268Method: memberstack.updateDataRecord(params, options?) 269Params type: 270type UpdateDataRecordParams = { 271 recordId: string; 272 data: Record<string, any>; 273}; 274 275REST call: PUT /v1/data-records/:recordId with body { data } 276 277Response (server): 278{ 279 "data": { /* DataRecordResponse */ }, 280 "_internalUseOnly": { "message": "..." } 281} 282 283Notes: 284Partial updates are supported;
284 member/reference operations for many-to-many fields use { connect: ..., disconnect: ... } objects. See access rules below. 285 286Examples (SDK): 287// Simple field edits 288await memberstack.updateDataRecord({ 289 recordId: 'rec_abc123', 290 data: { mileage: 12500 } 291}); 292 293// Record-to-record many relation (REFERENCE_MANY) â e.g., add/remove tags 294await memberstack.updateDataRecord({ 295 recordId: 'rec_abc123', 296 data: { 297 tags: { 298 connect: [{ id: 'rec_tag_electric' }], 299 disconnect: [{ id: 'rec_tag_gas' }] 300 } 301 } 302}); 303 304// Member many relation (MEMBER_REFERENCE_MANY) â e.g., the current member favorites this car 305await memberstack.updateDataRecord({ 306 recordId: 'rec_abc123', 307 data: { 308 favoritedBy: { connect: [{ self: true }] } 309 } 310}); 311 312deleteDataRecord 313Method: memberstack.deleteDataRecord(params, options?) 314Params type: 315type DeleteDataRecordParams = { recordId: string }; 316 317REST call: DELETE /v1/data-records/:recordId 318 319Response (server): 320{ 321 "data": { "id": "rec_..." }, 322 "_internalUseOnly": { "message": "..." } 323} 324 325Example (SDK / Webflow): 326await memberstack.deleteDataRecord({ recordId: 'rec_abc123' }); 327 328queryDataRecords 329Method: memberstack.queryDataRecords(params, options?) 330Params type: 331type QueryDataRecordsParams = { 332 table: string; // REQUIRED 333 query: { 334 where?: object; // Prisma-like, supports AND/OR/NOT and operators like { equals, in, gt, contains, ... } 335 include?: object; // Relationships: REFERENCE, MEMBER_REFERENCE; counts via _count.select 336 select?: object; // Field selection 337 orderBy?: object; // e.g., { createdAt: 'asc' } 338 take?: number; // 1..100 (server enforces +1 internally for hasMore detection) 339 skip?: number; // 0..10000 340 after?: string; // cursor (internalOrder as string) 341 _count?: boolean | { select: Record<string, boolean> }; 342 }; 343}; 344 345REST call: POST /v1/data-records/query 346 347Behavior and validation: 348- You must specify exactly one of query.findMany or query.findUnique at the top level (the SDK sends findMany for this method). 349- findMany: 350 - Include supports simple relations and _count.select (multiple counts allowed; server uses a hybrid approach under the hood). 351 - REFERENCE_MANY and MEMBER_REFERENCE_MANY cannot be included in findMany (validator rejects); use findUnique to include many-to-many relations. 352 - Pagination: take (1..100), skip (0..10000), and cursor via after (internalOrder). 353- findUnique: 354 - Must include where.id only (no top-level take, skip, after, or _count: true). 355 - Response wraps the record under data.record. 356 357Additional notes: 358BigInt values in responses are converted to Numbers by the server before JSON serialization. 359 360Responses (server): 361 362findMany: 363{ 364 "data": { 365 "records": [ 366 { 367 "id": "rec_...", 368 "internalOrder": 123456, 369 "createdAt": "2024-08-22T00:00:00.000Z", 370 "updatedAt": "2024-08-22T00:05:00.000Z", 371 "activeMemberOwnsIt": false, 372 "data": { /* field values plus any included relations */ }, 373 "_count": { /* present only when _count.select was used */ } 374 } 375 ], 376 "pagination": { 377 "hasMore": true, 378 "limit": 20, // present when 'take' is provided 379 "endCursor": 123456 // present when there are records 380 } 381 } 382} 383 384findUnique: 385{ 386 "data": { 387 "record": { 388 "id": "rec_...", 389 "internalOrder": 123456, 390 "createdAt": "...", 391 "updatedAt": "...", 392 "activeMemberOwnsIt": true, 393 "data": { /* field values plus included relations */ }, 394 "_count": { /* present only when _count.select was used */ } 395 } 396 } 397} 398 399Pure count (query.findMany with _count: true and no include/select): 400{ "data": { "_count": 42 } } 401 402Access Control & Auth 403- All endpoints enforce table-level access rules (createRule, readRule, updateRule, deleteRule). 404- For read operations, the server applies access filters automatically; you cannot manually override them via memberId. 405- Some operations (e.g., "self-only" member reference operations) permit updates when authenticated even if you don't own the record. 406 407Notes and Limitations
408- GET /v1/data-records supports only: tableKey, createdAfter, createdBefore, sortBy, sortDirection, limit, after. For field-level filtering or relationship includes, use queryDataRecords. 409- DataTableResponse.fields reflect server output; no unique property is returned. 410 411data-records/query â Includes, Counts, and Pagination 412 413This section shows practical patterns for POST /v1/data-records/query with findMany and findUnique using include, _count, and pagination. 414 415Request wrapper shape: 416{ 417 "table": "<tableKey>", 418 "query": { 419 "findMany": { /* ...see below... */ } 420 } 421} 422 423or 424 425{ 426 "table": "<tableKey>", 427 "query": { 428 "findUnique": { 429 "where": { "id": "rec_..." }, 430 /* ...see below... */ 431 } 432 } 433} 434 435General rules enforced by the server: 436- Include supports simple relations directly under include. 437- Deep nested includes/select/orderBy/where are not supported inside include values. 438- In findMany, includes for many-to-many relations (REFERENCE_MANY, MEMBER_REFERENCE_MANY) are not allowed; use findUnique for those. 439- Nested include pagination supports only take, skip, or after (cursor), and you may
439not combine skip and after together in a single include object. 440 441A) findMany with simple includes and counts 442 443Allowed includes in findMany: 444- REFERENCE (record relation, e.g., author) 445- MEMBER_REFERENCE (single member relation, e.g., postedBy) 446 447Not allowed in findMany includes (use findUnique): 448- REFERENCE_MANY, MEMBER_REFERENCE_MANY (junction-based many relations) 449 450Example request: 451{ 452 "table": "articles", 453 "query": { 454 "findMany": { 455 "where": { "published": { "equals": true } }, 456 "include": { 457 "author": true, 458 "_count": { "select": { "comments": true, "likes": true } } 459 }, 460 "orderBy": { "createdAt": "desc" }, 461 "take": 20, 462 "after": "123456" // internalOrder cursor from previous page 463 } 464 } 465} 466 467Example response (server): 468{ 469 "data": { 470 "records": [ 471 { 472 "id": "rec_...", 473 "internalOrder": 123500, 474 "createdAt": "2024-08-22T00:00:00.000Z", 475 "updatedAt": "2024-08-22T00:05:00.000Z", 476 "activeMemberOwnsIt": false, 477 "data": { 478 "title": "Hello", 479 "author": { 480 "id": "rec_author_...", 481 "internalOrder": 500, 482 "createdAt": "2024-08-01T00:00:00.000Z", 483 "updatedAt": "2024-08-10T00:00:00.000Z", 484 "activeMemberOwnsIt": false, 485 "data": { 486 /* author table fields */ 487 } 488 } 489 }, 490 "_count": { "comments": 12, "likes": 4 } 491 } 492 ], 493 "pagination": { 494 "hasMore": true, 495 "limit": 20, 496 "endCursor": 123480 497 } 498 } 499} 500 501Example (SDK / Webflow): 502const { data } = await memberstack.queryDataRecords({ 503 table: 'articles', 504 query: { 505 findMany: { 506 where: { published: { equals: true } }, 507 include: { 508 author: true, 509 _count: { select: { comments: true, likes: true } } 510 }, 511 orderBy: { createdAt: 'desc' }, 512 take: 20 513 } 514 } 515}); 516 517console.log('records:', data.records.length); 518console.log('first author id:', data.records[0].data.author?.id); 519console.log('first counts:', data.records[0]._count); 520 521Notes: 522- _count.select supports multiple relations; the server returns a combined _count object per record. 523- The top-level pagination.endCursor is always the record's internalOrder of the last item on the page. 524 525B) findUnique with many-to-many includes (with pagination) 526 527Use findUnique to include many relationships. Each many relation returns a structured object with records and pagination. 528 529Example request with a record that has both record and member many-to-many relations: 530{ 531 "table": "articles", 532 "query": { 533 "findUnique": { 534 "where": { "id": "rec_article_123" }, 535 "include": { 536 "tags": { "take": 10 }, // REFERENCE_MANY (records) 537 "likedBy": { "take": 25 } // MEMBER_REFERENCE_MANY (members) 538 } 539 } 540 } 541} 542 543Example response (server): 544{ 545 "data": { 546 "record": { 547 "id": "rec_article_123", 548 "internalOrder": 900, 549 "createdAt": "2024-08-20T00:00:00.000Z", 550 "updatedAt": "2024-08-22T00:00:00.000Z", 551 "activeMemberOwnsIt": false, 552 "data": { 553 /* article fields ... */ 554 "tags": { 555 "records": [ 556 { 557 "id": "rec_tag_1", 558 "internalOrder": 101, 559 "createdAt": "2024-08-01T00:00:00.000Z", 560 "updatedAt": "2024-08-10T00:00:00.000Z", 561 "activeMemberOwnsIt": false, 562 "data": { /* tag fields */ } 563 } 564 ], 565 "pagination": { 566 "limit": 10, 567 "hasMore": false, 568 "endCursor": 101 // numeric (internalOrder) 569 } 570 }, 571 "likedBy": { 572 "records": [ 573 { 574 "id": "mem_abc", 575 "email": "[email protected]", 576 "createdAt": "2024-07-01T00:00:00.000Z", 577 "updatedAt": "2024-08-02T00:00:00.000Z", 578 "verified": true, 579 "profileImage": null, 580 "customFields": {}, 581 "metaData": { /* present only when viewing self */ } 582 } 583 ], 584 "pagination": { 585 "limit": 25, 586 "hasMore": true, 587 "endCursor": "2024-08-02T00:00:00.000Z" // string (createdAt) 588 } 589 } 590 } 591 } 592 } 593} 594 595Pagination rules for includes: 596- REFERENCE_MANY and REVERSE_REFERENCE_MANY: 597 - orderBy: internalOrder ascending (server-managed) 598 - Cursor: after is the numeric internalOrder; response pagination.endCursor is numeric 599 - take defaults to 100 (server fetches 101 internally to compute hasMore) 600- MEMBER_REFERENCE_MANY: 601 - orderBy: createdAt ascending (server-managed) 602 - Cursor: after is an ISO date string (createdAt); response pagination.endCursor is a string 603 - take defaults to 100 (server fetches 101 internally to compute hasMore) 604 - Member objects include email via member.auth 605 606SDK note: 607The DOM SDK exposes getDataRecord for single-record fetches but does not currently accept include for findUnique. To retrieve related many-to-many collections, fetch the record via getDataRecord and then query related sets separately using queryD
607ataRecords (or rely on _count in a findMany list to avoid extra round trips). 608 609You may use skip as an alternative to after within an include, but not both together. 610 611C) Pure count queries 612 613To get only a total count for findMany without records: 614{ 615 "table": "articles", 616 "query": { 617 "findMany": { 618 "where": { "published": { "equals": true } }, 619 "_count": true 620 } 621 } 622} 623 624Response: 625{ "data": { "_count": 42 } } 626 627Example (SDK / Webflow): 628const { data } = await memberstack.queryDataRecords({ 629 table: 'articles', 630 query: { 631 findMany: { 632 where: { published: { equals: true } }, 633 _count: true 634 } 635 } 636}); 637 638console.log('count:', data._count); 639 640D) Top-level pagination (findMany) 641 642- take: 1â100; server fetches one extra to compute hasMore. 643- after: cursor string based on internalOrder of the last item returned. 644- skip: offset (0â10000). Prefer cursor-based pagination (after) for consistency across sorts. 645 646Example first page: 647{ 648 "table": "articles", 649 "query": { 650 "findMany": { 651 "orderBy": { "createdAt": "desc" }, 652 "take": 20 653 } 654 } 655} 656 657Next page: 658{ 659 "table": "articles", 660 "query": { 661 "findMany": { 662 "orderBy": { "createdAt": "desc" }, 663 "take": 20, 664 "after": "123480" 665 } 666 } 667} 668 669Example (SDK / Webflow): 670// First page 671let { data } = await memberstack.queryDataRecords({ 672 table: 'articles', 673 query: { findMany: { orderBy: { createdAt: 'desc' }, take: 20 } } 674}); 675 676// Next page 677if (data.pagination?.hasMore && data.pagination.endCursor) { 678 ({ data } = await memberstack.queryDataRecords({ 679 table: 'articles', 680 query: { findMany: { orderBy: { createdAt: 'desc' }, take: 20, after: String(data.pagination.endCursor) } } 681 })); 682}`;try{await((r=navigator==null?void 0:navigator.clipboard)==null?void 0:r.writeText(d)),a({alertType:"success",message:"Documentation copied for AI"})}catch(n){a({alertType:"error",message:`Failed to copy: ${n}`})}};return e.jsx("div",{className:"fixed inset-0 z-50 overflow-y-auto bg-background",children:e.jsxs("div",{className:"max-w-4xl mx-auto p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6 sticky top-0 bg-background py-4 border-b border-border",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Data Tables Documentation"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"skeleton",onClick:s,children:[e.jsx(Ja,{className:"w-4 h-4 mr-2"}),"Copy for AI"]}),e.jsx($,{variant:"ghost",onClick:t,children:e.jsx(Me,{className:"w-5 h-5"})})]})]}),e.jsxs("div",{className:"prose prose-app max-w-none",children:[e.jsx("h1",{className:"text-xl font-bold mb-4 text-foreground",children:"Data Tables â @memberstack/dom"}),e.jsxs("p",{className:"text-muted-foreground mb-6",children:["This document describes the Data Tables client methods exposed by"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-foreground",children:"@memberstack/dom"}),", their exact parameters, and the raw REST requests they issue. It also calls out the current server response shapes and known mismatches so you can integrate with 100% accuracy."]}),e.jsxs("div",{className:"bg-app-blue50 dark:bg-app-blue900/20 border border-app-blue200 dark:border-app-blue800 rounded-lg p-4 mb-6",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-2",children:"Rate limits (server):"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 text-muted-foreground",children:[e.jsx("li",{children:"Global (all client REST routes): 200 requests per 30 seconds per IP"}),e.jsxs("li",{children:["Data Tables â Reads: 25 requests per second per IP",e.jsx("ul",{className:"list-disc list-inside ml-6 mt-1 text-sm",children:e.jsxs("li",{children:["Applies to:"," ",e.jsx("code",{className:"bg-muted px-1 py-0.5 rounded text-xs text-foreground",children:"GET /v1/data-tables"}),","," ",e.jsx("code",{className:"bg-muted px-1 py-0.5 rounded text-xs text-foreground",children:"GET /v1/data-tables/:tableKey"}),","," ",e.jsx("code",{className:"bg-muted px-1 py-0.5 rounded text-xs text-foreground",children:"POST /v1/data-records/query"})," ","(and"," ",e.jsx("code",{className:"bg-muted px-1 py-0.5 rounded text-xs text-foreground",children:"GET /v1/data-records"}),")"]})})]}),e.jsxs("li",{children:["Data Tables â Creates: 10 requests per minute per IP (",e.jsx("code",{className:"bg-muted px-1 py-0.5 rounded text-xs text-foreground",children:"POST /v1/data-records"}),")"]}),e.jsxs("li",{children:["Data Tables â Writes: 30 requests per minute per IP (",e.jsx("code",{className:"bg-muted px-1 py-0.5 rounded text-xs text-foreground",children:"PUT/DELETE /v1/data-records/:recordId"}),")"]})]})]}),e.jsxs("div",{className:"bg-muted border border-border rounded-lg p-4 mb-6",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-2",children:"Qu
682ick start (DOM + Webflow):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-3 rounded-lg overflow-x-auto text-sm mt-2",children:`// Option A: Using @memberstack/dom directly 683import MemberstackDOM from '@memberstack/dom'; 684const memberstack = MemberstackDOM.init({ publicKey: 'pk_sb_123', appId: 'app_123' }); 685 686// Option B: Using the Memberstack script tag 687// The DOM methods are exposed globally via window.$memberstackDom 688const memberstackScript = window.$memberstackDom; // same methods as shown below`})]}),e.jsxs("div",{className:"bg-app-yellow50 dark:bg-app-yellow900/20 border border-app-yellow200 dark:border-app-yellow800 rounded-lg p-4 mb-6",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-2",children:"Feature flag:"}),e.jsxs("p",{className:"text-muted-foreground",children:["If the environment variable"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-foreground",children:"DISABLE_DATA_TABLES"})," ","is set to a truthy value on the server, all routes return"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-foreground",children:"503"})," ",'with message: "Data table feature is temporarilly offline."']})]}),e.jsxs("section",{className:"mb-8",children:[e.jsx("h2",{className:"text-lg font-bold mb-3 text-foreground",children:"getDataTables"}),e.jsxs("div",{className:"space-y-2 text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Method:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"memberstack.getDataTables(options?)"})]}),e.jsxs("p",{children:[e.jsx("strong",{children:"SDK type:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"(): Promise<Payloads.GetDataTablesPayload>"})]}),e.jsxs("p",{children:[e.jsx("strong",{children:"REST call:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"GET /v1/data-tables"})]})]}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Request:"}),e.jsx("ul",{className:"list-disc list-inside text-muted-foreground",children:e.jsxs("li",{children:["Optional"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"options.token"})," ","overrides the Authorization header."]})}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Response (server):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 689 "data": { 690 "tables": [ 691 { 692 "id": "tbl_...", 693 "key": "articles", 694 "name": "Articles", 695 "createRule": "...", 696 "readRule": "...", 697 "updateRule": "...", 698 "deleteRule": "...", 699 "createdAt": "2024-08-21T00:00:00.000Z", 700 "updatedAt": "2024-08-22T00:00:00.000Z", 701 "recordCount": 123, 702 "fields": [ 703 { 704 "id": "fld_...", 705 "key": "title", 706 "name": "Title", 707 "type": "TEXT", 708 "required": true, 709 "defaultValue": null, 710 "tableOrder": 1, 711 "referencedTableId": null, 712 "referencedTable": null 713 } 714 ] 715 } 716 ] 717 } 718}`}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Notes:"}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground space-y-1",children:[e.jsxs("li",{children:["Field objects do NOT contain"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"unique"})," in the current server response (the SDK's local type includes"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"unique"}),", but the server does not return it)."]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"recordCount"})," ","reflects only records accessible to the active context (access rules and auth are applied)."]})]}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Example (SDK / Webflow):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:"const { data } = await memberstack.getDataTables(); // or window.$memberstackDom.getDataTables()\ndata.tables.forEach((t) => {\n console.log(`${t.key} â ${t.recordCount} records`);\n});"})]}),e.jsxs("section",{className:"mb-8",children:[e.jsx("h2",{className:"text-lg font-bold mb-3 text-foreground",children:"getDataTable"}),e.jsxs("div",{className:"space-y-2 text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Method:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"memberstack.getDataTable(params, options?)"})]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Params:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"{ table: string }"})]}),e.jsxs("p",{children:[e.jsx("strong",{children:"SDK type:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"(params: Params.GetDataTableParams): Promise<Payloads.GetDataTablePayload>"})]}),e.jsxs("p",{children:[e.jsx("strong",{children:"REST call:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"GET /v1/data-tables/:tableKey"})]})]}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Response (server):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:'{ "data": { /* DataTableResponse object (same shape as in getDataTables.tables[i]) */ } }'}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Example (SDK / Webflow):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`const { data } = await memberstack.getDataTable({ table: 'cars' }); 719console.log(data.name, data.fields.length);`})]}),e.jsxs("section",{className:"mb-8",children:[e.jsx("h2",{className:"text-lg font-bold mb-3 text-foreground",children:"Listing Records"}),e.jsxs("p",{className:"text-muted-foreground mb-4",children:["Prefer"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"memberstack.queryDataRecords"})," ","with ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"findMany"})," ",'for listing, filtering, includes, and counts. See the "data-records/query â Includes, Counts, and Pagination" section below for full examples and pagination patterns.']}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Example (SDK / Webflow):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`// First page 720let { data } = await memberstack.queryDataRecords({ 721 table: 'cars', 722 query: { 723 findMany: { 724 where: { make: { equals: 'Tesla' } }, 725 orderBy: { createdAt: 'desc' }, 726 take: 20 727 } 728 } 729}); 730 731console.log('Fetched', data.records.length, 'records'); 732 733// Next page using endCursor 734if (data.pagination?.hasMore && data.pagination.endCursor) { 735 const next = await memberstack.queryDataRecords({ 736 table: 'cars', 737 query: { 738 findMany: { 739 where: { make: { equals: 'Tesla' } }, 740 orderBy: { createdAt: 'desc' }, 741 take: 20, 742 after: String(data.pagination.endCursor) 743 } 744 } 745 }); 746 console.log('Fetched next page:', next.data.records.length); 747}`})]}),e.jsxs("section",{className:"mb-8",children:[e.jsx("h2",{className:"text-lg font-bold mb-3 text-foreground",children:"createDataRecord"}),e.jsxs("div",{className:"space-y-2 text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Method:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"memberstack.createDataRecord(p
747arams, options?)"})]}),e.jsx("p",{children:e.jsx("strong",{children:"SDK Params type:"})})]}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm mt-2",children:`type CreateDataRecordParams = { 748 table: string; // UPDATED: SDK now requires 'table' 749 data: Record<string, any>; 750 memberId?: string; // optional, server ignores this field 751};`}),e.jsxs("p",{className:"text-muted-foreground mt-3",children:[e.jsx("strong",{children:"REST call:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"POST /v1/data-records"})," ","with body"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"{ table, data, memberId? }"})]}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Response (server on success):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 752 "data": { 753 "id": "rec_...", 754 "tableKey": "articles", 755 "createdByMemberId": "mem_...", 756 "data": { /* typed field data */ }, 757 "createdAt": "...", 758 "updatedAt": "...", 759 "internalOrder": 123456, 760 "activeMemberOwnsIt": true 761 }, 762 "_internalUseOnly": { "message": "..." } 763}`}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Notes:"}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground space-y-1",children:[e.jsxs("li",{children:["SDK/server now aligned on body shape for create (",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"table"}),")."]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"_internalUseOnly"})," ","may be included in responses but is not part of the public SDK typings."]})]}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Example (SDK / Webflow):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`const { data } = await memberstack.createDataRecord({ 764 table: 'cars', 765 data: { 766 make: 'Tesla', 767 model: 'Model 3', 768 year: 2022 769 } 770}); 771 772console.log('Created record:', data.id);`})]}),e.jsxs("section",{className:"mb-8",children:[e.jsx("h2",{className:"text-lg font-bold mb-3 text-foreground",children:"getDataRecord"}),e.jsxs("div",{className:"space-y-2 text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Method:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"memberstack.getDataRecord(params, options?)"})]}),e.jsx("p",{children:e.jsx("strong",{children:"Params type:"})})]}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm mt-2",children:"type GetDataRecordParams = { table: string; recordId: string };"}),e.jsxs("p",{className:"text-muted-foreground mt-3",children:[e.jsx("strong",{children:"REST call (SDK issues):"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"POST /v1/data-records/query"})," ","with body:"]}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm mt-2",children:`{ 773 "query": { 774 "findUnique": { 775 "where": { "id": "rec_..." } 776 } 777 } 778}`}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Server expectation (IMPORTANT):"}),e.jsxs("p",{className:"text-muted-foreground mb-2",children:["Body must include the table key and the"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"id"})," must be wrapped in a"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"where"})," clause:"]}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 779 "table": "articles", 780 "query": { 781 "findUnique": { 782 "where": { "id": "rec_..." } 783 } 784 } 785}`}),e.jsx("ul",{className:"list-disc list-inside text-muted-foreground space-y-1 mt-3",children:e.jsxs("li",{children:["The SDK includes"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"table"})," and wraps ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"id"})," ","under ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"where"}),", satisfying server requirements."]})}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"SDK response normalization:"}),e.jsxs("p",{className:"text-muted-foreground",children:["The server returns"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"{ data: { record } }"}),". The SDK unwraps this and returns"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"{ data: record }"})," ","to match"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"GetDataRecordPayload"}),"."]}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Response (server on success):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:'{ "data": { "record": { /* DataRecordResponse */ } } }'}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Notes:"}),e.jsxs("p",{className:"text-muted-foreground",children:["SDK and server are al
785igned on request shape, and the SDK unwraps"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"{ data: { record } }"})," ","to"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"{ data: record }"})," ","for convenience."]}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Example (SDK / Webflow):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`const { data } = await memberstack.getDataRecord({ 786 table: 'cars', 787 recordId: 'rec_abc123' 788}); 789 790console.log(data.data.make, data.data.model);`})]}),e.jsxs("section",{className:"mb-8",children:[e.jsx("h2",{className:"text-lg font-bold mb-3 text-foreground",children:"updateDataRecord"}),e.jsxs("div",{className:"space-y-2 text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Method:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"memberstack.updateDataRecord(params, options?)"})]}),e.jsx("p",{children:e.jsx("strong",{children:"Params type:"})})]}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm mt-2",children:`type UpdateDataRecordParams = { 791 recordId: string; 792 data: Record<string, any>; 793};`}),e.jsxs("p",{className:"text-muted-foreground mt-3",children:[e.jsx("strong",{children:"REST call:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"PUT /v1/data-records/:recordId"})," ","with body"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"{ data }"})]}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Response (server):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 794 "data": { /* DataRecordResponse */ }, 795 "_internalUseOnly": { "message": "..." } 796}`}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Notes:"}),e.jsxs("p",{className:"text-muted-foreground",children:["Partial updates are supported; member/reference operations for many-to-many fields use"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"{ connect: ..., disconnect: ... }"})," ","objects. See access rules below."]}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Examples (SDK):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`// Simple field edits 797await memberstack.updateDataRecord({ 798 recordId: 'rec_abc123', 799 data: { mileage: 12500 } 800}); 801 802// Record-to-record many relation (REFERENCE_MANY) â e.g., add/remove tags 803await memberstack.updateDataRecord({ 804 recordId: 'rec_abc123', 805 data: { 806 tags: { 807 connect: [{ id: 'rec_tag_electric' }], 808 disconnect: [{ id: 'rec_tag_gas' }] 809 } 810 } 811}); 812 813// Member many relation (MEMBER_REFERENCE_MANY) â e.g., the current member favorites this car 814await memberstack.updateDataRecord({ 815 recordId: 'rec_abc123', 816 data: { 817 favoritedBy: { connect: [{ self: true }] } 818 } 819});`})]}),e.jsxs("section",{className:"mb-8",children:[e.jsx("h2",{className:"text-lg font-bold mb-3 text-foreground",children:"deleteDataRecord"}),e.jsxs("div",{className:"space-y-2 text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Method:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"memberstack.deleteDataRecord(params, options?)"})]}),e.jsx("p",{children:e.jsx("strong",{children:"Params type:"})})]}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm mt-2",children:"type DeleteDataRecordParams = { recordId: string };"}),e.jsxs("p",{className:"text-muted-foreground mt-3",children:[e.jsx("strong",{children:"REST call:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"DELETE /v1/data-records/:recordId"})]}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Response (server):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 820 "data": { "id": "rec_..." }, 821 "_internalUseOnly": { "message": "..." } 822}`}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Example (SDK / Webflow):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:"await memberstack.deleteDataRecord({ recordId: 'rec_abc123' });"})]}),e.jsxs("section",{className:"mb-8",children:[e.jsx("h2",{className:"text-lg font-bold mb-3 text-foreground",children:"queryD
822ataRecords"}),e.jsxs("div",{className:"space-y-2 text-muted-foreground",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Method:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"memberstack.queryDataRecords(params, options?)"})]}),e.jsx("p",{children:e.jsx("strong",{children:"Params type:"})})]}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm mt-2",children:`type QueryDataRecordsParams = { 823 table: string; // REQUIRED 824 query: { 825 where?: object; // Prisma-like, supports AND/OR/NOT and operators like { equals, in, gt, contains, ... } 826 include?: object; // Relationships: REFERENCE, MEMBER_REFERENCE; counts via _count.select 827 select?: object; // Field selection 828 orderBy?: object; // e.g., { createdAt: 'asc' } 829 take?: number; // 1..100 (server enforces +1 internally for hasMore detection) 830 skip?: number; // 0..10000 831 after?: string; // cursor (internalOrder as string) 832 _count?: boolean | { select: Record<string, boolean> }; 833 }; 834};`}),e.jsxs("p",{className:"text-muted-foreground mt-3",children:[e.jsx("strong",{children:"REST call:"})," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"POST /v1/data-records/query"})]}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Behavior and validation:"}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground space-y-2",children:[e.jsxs("li",{children:["You must specify exactly one of"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"query.findMany"})," ","or"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"query.findUnique"})," ","at the top level (the SDK sends"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"findMany"})," for this method)."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"findMany:"}),e.jsxs("ul",{className:"list-disc list-inside ml-4 mt-1",children:[e.jsxs("li",{children:["Include supports simple relations and"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"_count.select"})," ","(multiple counts allowed; server uses a hybrid approach under the hood)."]}),e.jsxs("li",{children:["REFERENCE_MANY and MEMBER_REFERENCE_MANY cannot be included in"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"findMany"})," ","(validator rejects); use"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"findUnique"})," ","to include many-to-many relations."]}),e.jsxs("li",{children:["Pagination:"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"take"})," ","(1..100),"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"skip"})," ","(0..10000), and cursor via"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"after"})," ","(internalOrder)."]})]})]}),e.jsxs("li",{children:[e.jsx("strong",{children:"findUnique:"}),e.jsxs("ul",{className:"list-disc list-inside ml-4 mt-1",children:[e.jsxs("li",{children:["Must include"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"where.id"})," ","only (no top-level"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"take"}),","," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"skip"}),","," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"after"}),", or"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"_count: true"}),")."]}),e.jsxs("li",{children:["Response wraps the record under"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"data.record"}),"."]})]})]})]}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Additional notes:"}),e.jsx("p",{className:"text-muted-foreground",children:"BigInt values in responses are converted to Numbers by the server before JSON serialization."}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Responses (server):"}),e.jsx("p",{className:"text-muted-foreground mt-3",children:e.jsx("strong",{children:"findMany:"})}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm mt-2",children:`{ 835 "data": { 836 "records": [ 837 { 838 "id": "rec_...", 839 "internalOrder": 123456, 840 "createdAt": "2024-08-22T00:00:00.000Z", 841 "updatedAt": "2024-08-22T00:05:00.000Z", 842 "activeMemberOwnsIt": false, 843 "data": { /* field values plus any included relations */ }, 844 "_count": { /* present only when _count.select was used */ } 845 } 846 ], 847 "pagination": { 848 "hasMore": true, 849 "limit": 20, // present when 'take' is provided 850 "endCursor": 123456 // present when there are records 851 } 852 } 853}`}),e.jsx("p",{className:"text-muted-foreground mt-3",children:e.jsx("strong",{children:"findUnique:"})}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm mt-2",children:`{ 854 "data": { 855 "record": { 856 "id": "rec_...", 857 "internalOrder": 123456, 858 "createdAt": "...", 859 "updatedAt": "...", 860 "activeMemberOwnsIt": true, 861 "data": { /* field values plus included relations */ }, 862 "_count": { /* present only when _count.select was used */ } 863 } 864 } 865}`}),e.jsxs("p",{className:"text-muted-foreground mt-3",children:[e.jsx("strong",{children:"Pure count ("}),e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"query.findMany"})," ","with"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"_count: true"})," ","and no ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"include"}),"/",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"select"}),e.jsx("strong",{children:"):"})]}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm mt-2",children:'{ "data": { "_count": 42 } }'})]}),e.jsxs("section",{className:"mb-8",children:[e.jsx("h2",{className:"text-lg font-bold mb-3 text-foreground",children:"Access Control & Auth"}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground space-y-2",children:[e.jsxs("li",{children:["All endpoints enforce table-level access rules (",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"createRule"}),","," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"readRule"}),","," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"updateRule"}),","," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"deleteRule"}),")."]}),e.jsxs("li",{children:["For read operations, the server applies access filters automatically; you cannot manually override them via"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"memberId"}),"."]}),e.jsx("li",{children:`Some operations (e.g., "self-only" member reference operations) permit updates when authenticated even if you don't own the record.`})]})]}),e.jsxs("section",{className:"mb-8",children:[e.jsx("h2",{className:"text-lg font-bold mb-3 text-foreground",children:"Notes and Limitations"}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground space-y-2",children:[e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"GET /v1/data-records"})," ","supports only:"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"tableKey"}),","," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"createdAfter"}),","," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"createdBefore"}),", ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"sortBy"}),","," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"sortDirection"}),", ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"limit"}),","," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"after"}),". For field-level filtering or relationship includes, use"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"queryD
865ataRecords"}),"."]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"DataTableResponse.fields"})," ","reflect server output; no"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"unique"})," ","property is returned."]})]})]}),e.jsxs("section",{className:"mb-8",children:[e.jsx("h2",{className:"text-lg font-bold mb-3 text-foreground",children:"data-records/query â Includes, Counts, and Pagination"}),e.jsxs("p",{className:"text-muted-foreground mb-4",children:["This section shows practical patterns for"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"POST /v1/data-records/query"})," ","with ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"findMany"})," ","and ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"findUnique"})," ","using ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"include"}),","," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"_count"}),", and pagination."]}),e.jsx("p",{className:"text-muted-foreground mb-2",children:e.jsx("strong",{children:"Request wrapper shape:"})}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 866 "table": "<tableKey>", 867 "query": { 868 "findMany": { /* ...see below... */ } 869 } 870}`}),e.jsx("p",{className:"text-muted-foreground mt-3 mb-2",children:"or"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 871 "table": "<tableKey>", 872 "query": { 873 "findUnique": { 874 "where": { "id": "rec_..." }, 875 /* ...see below... */ 876 } 877 } 878}`}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"General rules enforced by the server:"}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground space-y-1",children:[e.jsxs("li",{children:["Include supports simple relations directly under"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"include"}),"."]}),e.jsxs("li",{children:["Deep nested includes/select/orderBy/where are not supported inside"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"include"})," ","values."]}),e.jsxs("li",{children:["In ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"findMany"}),", includes for many-to-many relations (REFERENCE_MANY, MEMBER_REFERENCE_MANY) are not allowed; use"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"findUnique"})," ","for those."]}),e.jsxs("li",{children:["Nested include pagination supports only"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"take"}),","," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"skip"}),", or"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"after"}
878)," ","(cursor), and you may not combine"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"skip"})," and"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"after"})," ","together in a single include object."]})]}),e.jsx("h3",{className:"font-semibold text-foreground mt-6 mb-3",children:"A) findMany with simple includes and counts"}),e.jsx("p",{className:"text-muted-foreground mb-2",children:e.jsx("strong",{children:"Allowed includes in findMany:"})}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground space-y-1 mb-3",children:[e.jsxs("li",{children:["REFERENCE (record relation, e.g.,"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"author"}),")"]}),e.jsxs("li",{children:["MEMBER_REFERENCE (single member relation, e.g.,"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"postedBy"}),")"]})]}),e.jsx("p",{className:"text-muted-foreground mb-2",children:e.jsx("strong",{children:"Not allowed in findMany includes (use findUnique):"})}),e.jsx("ul",{className:"list-disc list-inside text-muted-foreground space-y-1 mb-3",children:e.jsx("li",{children:"REFERENCE_MANY, MEMBER_REFERENCE_MANY (junction-based many relations)"})}),e.jsx("p",{className:"text-muted-foreground mb-2",children:e.jsx("strong",{children:"Example request:"})}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 879 "table": "articles", 880 "query": { 881 "findMany": { 882 "where": { "published": { "equals": true } }, 883 "include": { 884 "author": true, 885 "_count": { "select": { "comments": true, "likes": true } } 886 }, 887 "orderBy": { "createdAt": "desc" }, 888 "take": 20, 889 "after": "123456" // internalOrder cursor from previous page 890 } 891 } 892}`}),e.jsx("p",{className:"text-muted-foreground mt-3 mb-2",children:e.jsx("strong",{children:"Example response (server):"})}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 893 "data": { 894 "records": [ 895 { 896 "id": "rec_...", 897 "internalOrder": 123500, 898 "createdAt": "2024-08-22T00:00:00.000Z", 899 "updatedAt": "2024-08-22T00:05:00.000Z", 900 "activeMemberOwnsIt": false, 901 "data": { 902 "title": "Hello", 903 "author": { 904 "id": "rec_author_...", 905 "internalOrder": 500, 906 "createdAt": "2024-08-01T00:00:00.000Z", 907 "updatedAt": "2024-08-10T00:00:00.000Z", 908 "activeMemberOwnsIt": false, 909 "data": { 910 /* author table fields */ 911 } 912 } 913 }, 914 "_count": { "comments": 12, "likes": 4 } 915 } 916 ], 917 "pagination": { 918 "hasMore": true, 919 "limit": 20, 920 "endCursor": 123480 921 } 922 } 923}`}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Example (SDK / Webflow):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`const { data } = await memberstack.queryDataRecords({ 924 table: 'articles', 925 query: { 926 findMany: { 927 where: { published: { equals: true } }, 928 include: { 929 author: true, 930 _count: { select: { comments: true, likes: true } } 931 }, 932 orderBy: { createdAt: 'desc' }, 933 take: 20 934 } 935 } 936}); 937 938console.log('records:', data.records.length); 939console.log('first author id:', data.records[0].data.author?.id); 940console.log('first counts:', data.records[0]._count);`}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Notes:"}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground space-y-1",children:[e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"_count.select"})," ","supports multiple relations; the server returns a combined"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"_count"})," ","object per record."]}),e.jsxs("li",{children:["The top-level"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"pagination.endCursor"})," ","is always the record's"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"internalOrder"})," ","of the last item on the page."]})]}),e.jsx("h3",{className:"font-semibold text-foreground mt-6 mb-3",children:"B) findUnique with many-to-many includes (with pagination)"}),e.jsxs("p",{className:"text-muted-foreground mb-2",children:["Use ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"findUnique"})," ","to include many relationships. Each many relation returns a structured object with"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"records"})," and"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"pagination"}),"."]}),e.jsx("p",{className:"text-muted-foreground mb-2",children:e.jsx("strong",{children:"Example request with a record that has both record and member many-to-many relations:"})}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 941 "table": "articles", 942 "query": { 943 "findUnique": { 944 "where": { "id": "rec_article_123" }, 945 "include": { 946 "tags": { "take": 10 }, // REFERENCE_MANY (records) 947 "likedBy": { "take": 25 } // MEMBER_REFERENCE_MANY (members) 948 } 949 } 950 } 951}`}),e.jsx("p",{className:"text-muted-foreground mt-3 mb-2",children:e.jsx("strong",{children:"Example response
951(server):"})}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 952 "data": { 953 "record": { 954 "id": "rec_article_123", 955 "internalOrder": 900, 956 "createdAt": "2024-08-20T00:00:00.000Z", 957 "updatedAt": "2024-08-22T00:00:00.000Z", 958 "activeMemberOwnsIt": false, 959 "data": { 960 /* article fields ... */ 961 "tags": { 962 "records": [ 963 { 964 "id": "rec_tag_1", 965 "internalOrder": 101, 966 "createdAt": "2024-08-01T00:00:00.000Z", 967 "updatedAt": "2024-08-10T00:00:00.000Z", 968 "activeMemberOwnsIt": false, 969 "data": { /* tag fields */ } 970 } 971 ], 972 "pagination": { 973 "limit": 10, 974 "hasMore": false, 975 "endCursor": 101 // numeric (internalOrder) 976 } 977 }, 978 "likedBy": { 979 "records": [ 980 { 981 "id": "mem_abc", 982 "email": "[email protected]", 983 "createdAt": "2024-07-01T00:00:00.000Z", 984 "updatedAt": "2024-08-02T00:00:00.000Z", 985 "verified": true, 986 "profileImage": null, 987 "customFields": {}, 988 "metaData": { /* present only when viewing self */ } 989 } 990 ], 991 "pagination": { 992 "limit": 25, 993 "hasMore": true, 994 "endCursor": "2024-08-02T00:00:00.000Z" // string (createdAt) 995 } 996 } 997 } 998 } 999 } 1000}`}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Pagination rules for includes:"}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground space-y-2",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"REFERENCE_MANY and REVERSE_REFERENCE_MANY:"}),e.jsxs("ul",{className:"list-disc list-inside ml-4 mt-1",children:[e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"orderBy"}),": internalOrder ascending (server-managed)"]}),e.jsxs("li",{children:["Cursor:"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"after"})," is the numeric"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"internalOrder"}),"; response"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"pagination.endCursor"})," ","is numeric"]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"take"})," ","defaults to 100 (server fetches 101 internally to compute"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"hasMore"}),")"]})]})]}),e.jsxs("li",{children:[e.jsx("strong",{children:"MEMBER_REFERENCE_MANY:"}),e.jsxs("ul",{className:"list-disc list-inside ml-4 mt-1",children:[e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"orderBy"}),": createdAt ascending (server-managed)"]}),e.jsxs("li",{children:["Cursor:"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"after"})," is an ISO date string (createdAt); response"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"pagination.endCursor"})," ","is a string"]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"take"})," ","defaults to 100 (server fetches 101 internally to compute"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"hasMore"}),")"]}),e.jsxs("li",{children:["Member objects include"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"email"})," ","via"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"member.auth"})]})]})]})]}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"SDK note:"}),e.jsxs("p",{className:"text-muted-foreground mb-3",children:["The DOM SDK exposes"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"getDataRecord"})," ","for single-record fetches but does not currently accept"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"include"})," for"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"findUnique"}),". To retrieve related many-to-many collections, fetch the record via"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"getDataRecord"})," ","and then query related sets separately using"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"queryD
1000ataRecords"}),"(or rely on"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"_count"})," in a"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"findMany"})," list to avoid extra round trips)."]}),e.jsxs("p",{className:"text-muted-foreground mt-3",children:["You may use"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"skip"})," as an alternative to"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"after"})," within an include, but not both together."]}),e.jsx("h3",{className:"font-semibold text-foreground mt-6 mb-3",children:"C) Pure count queries"}),e.jsxs("p",{className:"text-muted-foreground mb-2",children:["To get only a total count for"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"findMany"})," ","without records:"]}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 1001 "table": "articles", 1002 "query": { 1003 "findMany": { 1004 "where": { "published": { "equals": true } }, 1005 "_count": true 1006 } 1007 } 1008}`}),e.jsx("p",{className:"text-muted-foreground mt-3 mb-2",children:e.jsx("strong",{children:"Response:"})}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:'{ "data": { "_count": 42 } }'}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Example (SDK / Webflow):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`const { data } = await memberstack.queryDataRecords({ 1009 table: 'articles', 1010 query: { 1011 findMany: { 1012 where: { published: { equals: true } }, 1013 _count: true 1014 } 1015 } 1016}); 1017 1018console.log('count:', data._count);`}),e.jsx("h3",{className:"font-semibold text-foreground mt-6 mb-3",children:"D) Top-level pagination (findMany)"}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground space-y-2 mb-3",children:[e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"take"}),": 1â100; server fetches one extra to compute"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"hasMore"}),"."]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"after"}),": cursor string based on"," ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"internalOrder"})," ","of the last item returned."]}),e.jsxs("li",{children:[e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"skip"}),": offset (0â10000). Prefer cursor-based pagination (",e.jsx("code",{className:"bg-muted px-2 py-1 rounded",children:"after"}),") for consistency across sorts."]})]}),e.jsx("p",{className:"text-muted-foreground mb-2",children:e.jsx("strong",{children:"Example first page:"})}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 1019 "table": "articles", 1020 "query": { 1021 "findMany": { 1022 "orderBy": { "createdAt": "desc" }, 1023 "take": 20 1024 } 1025 } 1026}`}),e.jsx("p",{className:"text-muted-foreground mt-3 mb-2",children:e.jsx("strong",{children:"Next page:"})}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`{ 1027 "table": "articles", 1028 "query": { 1029 "findMany": { 1030 "orderBy": { "createdAt": "desc" }, 1031 "take": 20, 1032 "after": "123480" 1033 } 1034 } 1035}`}),e.jsx("h4",{className:"font-semibold mt-4 mb-2",children:"Example (SDK / Webflow):"}),e.jsx("pre",{className:"bg-app-gray900 text-white p-4 rounded-lg overflow-x-auto text-sm",children:`// First page 1036let { data } = await memberstack.queryDataRecords({ 1037 table: 'articles', 1038 query: { findMany: { orderBy: { createdAt: 'desc' }, take: 20 } } 1039}); 1040 1041// Next page 1042if (data.pagination?.hasMore && data.pagination.endCursor) { 1043 ({ data } = await memberstack.queryDataRecords({ 1044 table: 'articles', 1045 query: { findMany: { orderBy: { createdAt: 'desc' }, take: 20, after: String(data.pagination.endCursor) } } 1046 })); 1047}`})]})]})]})})},en=({showModal:t,setShowModal:a,record:s,onConfirmDelete:d,isLoading:r=!1})=>s?e.jsx(pe,{showModal:t,setShowModal:a,title:"Delete Record",showDivider:!0,width:"500px",actionButtons:{confirm:{label:"Delete Record",onConfirm:d,isLoading:r,variant:"destructive"},cancel:{label:"Cancel"}},children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 bg-red-50 rounded-lg border border-red-200",children:[e.jsx(nt,{className:"w-5 h-5 text-red-600 shrink-0"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium text-red-900",children:"Warning: This action cannot be undone"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"This will permanently delete the record and all its data."})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-app-gray700",children:"Are you sure you want to delete this record?"}),e.jsx("div",{className:"bg-app-gray50 p-4 rounded-lg border",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-app-gray700",children:"Record ID:"}),e.jsx("code",{className:"text-xs bg-app-gray200 px-2 py-1 rounded font-mono",children:s.id})]}),e.jsxs("div",{className:"text-sm text-app-gray600",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Created:"}
1047)," ",new Date(s.createdAt).toLocaleString()]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Updated:"})," ",new Date(s.updatedAt).toLocaleString()]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx("span",{className:"text-sm font-medium text-app-gray700 block mb-2",children:"Data Preview:"}),e.jsx("pre",{className:"text-xs bg-app-gray100 p-3 rounded max-h-32 overflow-auto font-mono",children:JSON.stringify(s.data,null,2)})]})]})})]})]})}):null,We={TEXT:"Text",TEXT_FILTERABLE:"Text (Filterable)",TEXT_UNIQUE:"Text (Unique)",NUMBER:"Number",DECIMAL:"Decimal",BOOLEAN:"Boolean",DATE:"Date",REFERENCE:"Reference",REFERENCE_MANY:"Records (Many-to-Many)",MEMBER_REFERENCE:"Member Reference",MEMBER_REFERENCE_MANY:"Members (Many-to-Many)",EMAIL:"Email",URL:"URL",JSON:"JSON"},Ze={PUBLIC:"Public (No Auth)",AUTHENTICATED:"Any Member",AUTHENTICATED_OWN:"Member's Own Records",ADMIN_ONLY:"Admin Only"},tn={PUBLIC:"Public (No Auth)",AUTHENTICATED:"Any Member",ADMIN_ONLY:"Admin Only"},$t=t=>t?/^[a-zA-Z0-9_]{1,64}$/.test(t)?null:"Table key must be alphanumeric with underscores only (max 64 characters)":"Table key is required",sn=t=>t?/^[a-zA-Z0-9_]{1,64}$/.test(t)?null:"Field key must be alphanumeric with underscores only (max 64 characters)":"Field key is required",lt=t=>{if(t===0)return"No records";if(t===1)return"1 record";if(t<1e3)return`${t} records`;if(t<1e4)return`${t.toLocaleString()} records`;if(t<1e6){const s=t/1e3;return s%1===0?`${s}K records`:`${s.toFixed(1)}K records`}if(t<1e7)return`${t.toLocaleString()} records`;const a=t/1e6;return a%1===0?`${a}M records`:`${a.toFixed(2)}M records`},an=t=>t===0?"No fields":t===1?"1 field":`${t} fields`,rn=/^\d{4}-\d{2}-\d{2}$/,nn=/^(\d{4}-\d{2}-\d{2})T00:00:00(?:\.0+)?Z$/,dn=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,Rs=t=>{const a={day:"",moment:null};if(t==null||t==="")return a;let s;if(typeof t=="number"){const n=new Date(t);if(!Ft(n))return a;s=n.toISOString()}else s=String(t);const d=nn.exec(s);if(d)return{day:d[1],moment:null};if(rn.test(s))return{day:s,moment:null};const r=new Date(s);return Ft(r)?{day:ts(r,"yyyy-MM-dd"),moment:r}:a},ws=t=>{const{day:a,moment:s}=Rs(t);return s?ts(s,"yyyy-MM-dd'T'HH:mm"):a},ln=t=>({day:t.slice(0,10),time:t.length>10?t.slice(11,16):""}),Pt=(t,a)=>t?a?`${t}T${a}`:t:"",on=t=>{const{day:a,moment:s}=Rs(t);return s?Se(s,"dd LLL, yyyy, HH:mm"):a?Se(ka(a),"dd LLL, yyyy"):String(t)},ot=(t,a)=>a==null?"":t.type==="DATE"?ws(a):String(a),cn=(t,a,s)=>{if(!(a===void 0||a===""))switch(t.type){case"NUMBER":{const d=Number.parseInt(a,10);return Number.isNaN(d)?void 0:d}case"DECIMAL":{const d=Number.parseFloat(a);return Number.isNaN(d)?void 0:d}case"BOOLEAN":return a==="true";case"DATE":return s!=null&&ws(s)===a?s:dn.test(a)?new Date(a).toISOString():a;default:return a}},ks=(t,a)=>t.reduce((s,d)=>(s[d.key]=ot(d,a?a[d.key]:d.defaultValue),s),{}),un=t=>t!=null&&t!=="",Oe=(t,a,s,d={})=>{const r={};for(const n of t){const p=s==null?void 0:s[n.key],l=cn(n,a[n.key],p);l!==void 0?r[n.key]=l:d.clearEmptied&&un(p)&&(r[n.key]=null)}return r},Cs=t=>t.filter(a=>a.type!=="VIRTUAL_REFERENCE_LIST"),Ts=({id:t,icon:a,placeholder:s,chosen:d,clearLabel:r,onClear:n,query:p,onQueryChange:l,open:u,onOpenChange:o,containerRef:i,results:c,loading:b,failed:j,emptyText:C,onPick:R,onBlur:f})=>{if(d){const E=d.label!==d.id;return e.jsxs("div",{className:"flex h-8 items-center gap-2 rounded-md border border-input bg-background px-3 text-[14px] leading-6 text-foreground",children:[e.jsx(a,{"aria-hidden":!0,className:"size-4 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"min-w-0 truncate",children:d.label}),E&&e.jsx("code",{className:"hidden min-w-0 truncate font-mono text-utility-sm text-muted-foreground sm:inline",children:d.id}),e.jsx("button",{type:"button","aria-label":r,onClick:n,className:"ml-auto shrink-0 rounded text-muted-foreground hover:text-foreground",children:e.jsx(Me,{className:"size-4"})})]})}const g=`${t}-results`;return e.jsxs("div",{ref:i,className:"relative",children:[e.jsx(ae,{id:t,name:t,value:p,onChange:E=>{l(E.target.value),o(!0)},onFocus:()=>o(!0),onBlur:f,placeholder:s,autoComplete:"off",hideIndicators:!0,role:"combobox","aria-expanded":u,"aria-controls":g}),u&&e.jsx("div",{id:g,role:"listbox",className:"absolute z-50 mt-1 max-h-48 w-full overflow-y-auto rounded-md border border-border bg-popover p-1 shadow-md",children:j?e.jsx("p",{className:"px-3 py-2 text-body-sm text-destructive",children:"Could not load results"}):b?e.jsx("p",{className:"px-3 py-2 text-body-sm text-muted-foreground",children:"Searching"}):c.length===0?e.jsx("p",{className:"px-3 py-2 text-body-sm text-muted-foreground",children:C}):c.map(E=>e.jsx("button",{type:"button",role:"option","aria-selected":!1,onClick:()=>{R(E),o(!1)},className:"block w-full rounded-md px-3 py-2 text-left text-body-sm text-foreground hover:bg-muted",children:E.label},E.id))})]})},Ms=300,mn=({id:t,value:a,onChange:s,onBlur:d})=>{var g,E,h;const[r,n]=x.useState(""),[p,l]=x.useState(""),[u,o]=x.useState(null),i=ss(!1),c=i.isVisible;x.useEffect(()=>{const w=setTimeout(()=>l(r),Ms);return()=>clearTimeout(w)},[r]);const{data:b,loading:j,error:C}=as({variables:{first:10,search:p||void 0},skip:!c}),{data:R}=rs({variables:{id:a},skip:!a||(u==null?void 0:u.id)===a}),f=a?{id:a,label:(u==null?void 0:u.id)===a?u.label:((E=(g=R==null?void 0:R.currentMember)==null?void 0:g.auth)==null?void 0:E.email)??a}:null;return e.jsx(Ts,{id:t,icon:Be,placeholder:"Search members by email",chosen:f,clearLabel:"Clear member",onClear:()=>{s(""),n("")},query:r,onQueryChange:n,open:c,onOpenChange:i.setIsVisible,containerRef:i.ref,results:(((h=b==null?void 0:b.getMembers)==null?void 0:h.edges)??[]).map(({node:w})=>{var v;return{id:w.id,label:((v=w.auth)==null?void 0:v.email)??w.id}}),loading:j,failed:!!C,emptyText:"No members found",onPick:w=>
1047{o(w),s(w.id)},onBlur:d})},pn=["title","name","label","slug","email"],Ut=(t,a)=>{if(!t||typeof t!="object")return a;const s=Object.entries(t),d=n=>typeof n=="string"&&n.trim()!==""?n:null;for(const n of pn){const p=s.find(([l,u])=>l.toLowerCase()===n&&d(u));if(p)return String(p[1])}const r=s.find(([,n])=>d(n));return r?String(r[1]):a},xn=({id:t,tableId:a,value:s,onChange:d,onBlur:r})=>{var E;const[n,p]=x.useState(""),[l,u]=x.useState(""),[o,i]=x.useState(null),c=ss(!1),b=c.isVisible;x.useEffect(()=>{const h=setTimeout(()=>u(n),Ms);return()=>clearTimeout(h)},[n]);const{data:j,loading:C,error:R}=gs({variables:{tableId:a,filter:l?{search:l}:void 0,pagination:{first:10}},skip:!b}),{data:f}=bs({variables:{id:s},skip:!s||(o==null?void 0:o.id)===s}),g=s?{id:s,label:(o==null?void 0:o.id)===s?o.label:f!=null&&f.dataRecord?Ut(f.dataRecord.data,s):s}:null;return e.jsx(Ts,{id:t,icon:_e,placeholder:"Search records",chosen:g,clearLabel:"Clear record",onClear:()=>{d(""),p("")},query:n,onQueryChange:p,open:b,onOpenChange:c.setIsVisible,containerRef:c.ref,results:(((E=j==null?void 0:j.dataRecords)==null?void 0:E.edges)??[]).map(({node:h})=>({id:h.id,label:Ut(h.data,h.id)})),loading:C,failed:!!R,emptyText:"No records found",onPick:h=>{i(h),d(h.id)},onBlur:r})},hn=t=>We[t]??t,gn=t=>t==="NUMBER"||t==="DECIMAL"?"number":"text",Ds=({field:t,value:a,onChange:s,onBlur:d,error:r})=>{const n=`${t.name}${t.required?" *":""}`,p=`${hn(t.type)}${t.required?" · Required":""}`;if(t.type==="BOOLEAN"){const u=a===""?"Not set":a==="true"?"Yes":"No";return e.jsxs("div",{children:[e.jsx(K,{htmlFor:t.key,text:n}),e.jsxs("div",{className:"mt-1 flex items-center gap-3",children:[e.jsx(Ca,{id:t.key,name:t.key,isChecked:a==="true",onChange:o=>s(o?"true":"false")}),e.jsx("span",{className:"text-[14px] leading-6 text-foreground",children:u})]}),e.jsx("p",{className:"mt-1 text-utility-md text-muted-foreground",children:p})]})}if(t.type==="DATE"){const{day:u,time:o}=ln(a);return e.jsxs("div",{children:[e.jsx(K,{htmlFor:t.key,text:n}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ae,{id:t.key,name:t.key,type:"date",value:u,onChange:i=>s(Pt(i.target.value,o)),onBlur:d,errorMessage:r,containerClassName:"min-w-0 flex-1"}),e.jsx(ae,{id:`${t.key}-time`,name:`${t.key}-time`,type:"time",value:o,onChange:i=>s(Pt(u,i.target.value)),onBlur:d,"aria-label":`${t.name} time`,disabled:!u,hideIndicators:!0,containerClassName:"w-32 shrink-0"})]}),e.jsxs("p",{className:"mt-1 text-utility-md text-muted-foreground",children:[p,". Time is optional."]})]})}const l=t.type==="MEMBER_REFERENCE"?e.jsx(mn,{id:t.key,value:a,onChange:s,onBlur:d}):t.type==="REFERENCE"&&t.referencedTableId?e.jsx(xn,{id:t.key,tableId:t.referencedTableId,value:a,onChange:s,onBlur:d}):null;return l?e.jsxs("div",{children:[e.jsx(K,{htmlFor:t.key,text:n}),l,e.jsx("p",{className:O("mt-1 text-utility-md",r?"text-destructive":"text-muted-foreground"),children:r??p})]}):e.jsxs("div",{children:[e.jsx(K,{htmlFor:t.key,text:n}),e.jsx(ae,{id:t.key,name:t.key,type:gn(t.type),step:t.type==="DECIMAL"?"any":void 0,value:a,onChange:u=>s(u.target.value),onBlur:d,placeholder:`Enter ${t.name.toLowerCase()}`,errorMessage:r,description:p})]})},Kt=({active:t,onClick:a,icon:s,label:d})=>e.jsxs("button",{type:"button",onClick:a,className:O("flex flex-1 items-center justify-center gap-2 pb-2 border-b-2 border-transparent font-semibold text-muted-foreground hover:border-muted-foreground",t&&"text-primary border-primary hover:border-primary"),children:[e.jsx("span",{className:"[&_svg]:size-4 inline-flex",children:s}),d]}),bn=()=>{var J,H;const{recordId:t,tableKey:a,appId:s}=qe(),d=rt(),r=ga(),{tableFields:n,refetchRecords:p,refetchTable:l}=r??{tableFields:[],refetchRecords:()=>{},refetchTable:()=>{}},{createToastAlert:u}
1047=Le(),[o,i]=x.useState("form"),[c,b]=x.useState(!1),[j,C]=x.useState(!1),R=`/apps/${s}/data-tables/${a}`,{data:f,loading:g,error:E}=bs({variables:{id:t||""},skip:!t,fetchPolicy:"cache-and-network"}),[h,{loading:w}]=Ha(),[v,{loading:A}]=Za(),y=f==null?void 0:f.dataRecord,Y=Cs(n),q=ze({initialValues:y?{...ks(Y,y.data??{}),jsonData:JSON.stringify(y.data??{},null,2)}:{jsonData:"{}"},enableReinitialize:!0,validationSchema:o==="json"?De().shape({jsonData:he().required("JSON data is required").test("valid-json","Must be valid JSON",T=>{try{return JSON.parse(T||"{}"),!0}catch{return!1}})}):De().shape(Y.reduce((T,D)=>(T[D.key]=D.required?he().required(`${D.name} is required`):he(),T),{})),onSubmit:async T=>{if(!y)return;let D;if(o==="json")try{D=JSON.parse(T.jsonData)}catch(U){u({message:`Invalid JSON: ${U instanceof Error?U.message:"could not parse"}`,alertType:"error"});return}else D=Oe(Y,T,y.data??{},{clearEmptied:!0});try{await h({variables:{input:{id:y.id,data:D}}}),u({message:"Record updated successfully",alertType:"success"}),p()}catch(U){u({message:U.message||"Failed to update record",alertType:"error"})}}});x.useEffect(()=>{i("form"),b(!1)},[t]);const X=T=>{if(T!==o){if(T==="json")q.setFieldValue("jsonData",JSON.stringify(Oe(Y,q.values,(y==null?void 0:y.data)??{}),null,2));else try{const D=JSON.parse(q.values.jsonData);Y.forEach(U=>{q.setFieldValue(U.key,ot(U,D==null?void 0:D[U.key]))})}catch{}i(T)}},me=async()=>{if(y)try{await v({variables:{input:{id:y.id}}}),u({message:"Record deleted successfully",alertType:"success"}),b(!1),p(),l(),d(R)}catch(T){u({message:T.message||"Failed to delete record",alertType:"error"})}};return t?E&&!g?e.jsx("div",{className:"p-6",children:e.jsx(be,{icon:e.jsx(Ir,{className:"w-12 h-12 text-red-400"}),title:"Could not load record",description:E.message||"The record may have been deleted or doesn't exist in this environment.",action:e.jsx(Je,{to:R,children:"Back to table"})})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-5 pl-4 flex items-center justify-between border-b border-border",role:"region","aria-label":"record-pane",children:[e.jsxs("div",{className:"flex items-center h-10 min-w-0",children:[e.jsx(Je,{variant:"icon",to:R,"aria-label":"Close record panel",children:e.jsx(Me,{className:"w-5 h-5"})}),e.jsxs("div",{className:"ml-1 min-w-0",children:[e.jsx("h4",{className:"text-[14px] leading-5 font-semibold text-foreground",children:"Record"}),e.jsx(ce,{as:"code",className:"block text-[11px] leading-4 text-muted-foreground font-mono truncate max-w-[220px]",children:g&&!y?"Loading...":t})]})]}),e.jsx("div",{className:"flex items-center h-10",children:e.jsxs(Ta,{open:j,onOpenChange:C,children:[e.jsx(Ma,{className:Da({variant:"skeleton"}),"aria-label":"Record actions",children:e.jsx(qr,{className:"w-4 h-4"})}),e.jsx(Sa,{className:"flex flex-col",align:"end",children:e.jsx("div",{className:"p-1",children:e.jsxs("button",{type:"button",onClick:()=>{C(!1),b(!0)},className:"w-full text-left inline-flex items-center gap-2 py-2 px-3 rounded-md hover:bg-muted text-error-fill",children:[e.jsx(ns,{className:"w-4 h-4"}),"Delete record"]})})})]})})]}),y&&e.jsxs("div",{className:"px-5 py-4 border-b border-border space-y-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[e.jsx(ir,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Created"}),e.jsx("span",{className:"ml-auto",children:Se(y.createdAt,"dd LLL, yyyy")})]}),e.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[e.jsx(cr,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Updated"}),e.jsx("span",{className:"ml-auto",children:Se(y.updatedAt,"dd LLL, yyyy")})]}),e.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[e.jsx(Be,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Created by"}),e.jsx(ce,{as:"span",className:"ml-auto truncate max-w-[200px]",children:((H=(J=y.createdByMember)==null?void 0:J.auth)==null?void 0:H.email)||"System"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 border-b border-border px-4 pt-3",children:[e.jsx(Kt,{active:o==="form",onClick:()=>X("form"),icon:e.jsx(ur,{}),label:"Form Mode"}),e.jsx(Kt,{active:o==="json",onClick:()=>X("json"),icon:e.jsx(ds,{}),label:"JSON Mode"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-5 py-5",children:o==="form"?e.jsx("div",{className:"space-y-4",children:Y.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No fields defined for this table."}),e.jsx("p",{className:"text-sm mt-1",children:"Add fields to the table first or edit raw JSON."})]}):Y.map(T=>e.jsx(Ds,{field:T,value:q.values[T.key]??"",onChange:D=>q.setFieldValue(T.key,D),onBlur:()=>
1047q.setFieldTouched(T.key,!0),error:q.touched[T.key]&&q.errors[T.key]?q.errors[T.key]:void 0},T.id))}):e.jsxs("div",{children:[e.jsx(K,{htmlFor:"jsonData",text:"JSON Data *"}),e.jsx("textarea",{id:"jsonData",name:"jsonData",value:q.values.jsonData,onChange:q.handleChange,onBlur:q.handleBlur,placeholder:"Enter JSON data...",rows:16,className:"w-full px-3 py-2 border border-border bg-background text-foreground rounded-md font-mono text-sm resize-none focus:outline-none focus:ring-2 focus:ring-app-blue500 focus:border-transparent"}),q.touched.jsonData&&q.errors.jsonData&&e.jsx("p",{className:"mt-1 text-sm text-red-600",children:q.errors.jsonData}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Edit the record as raw JSON. Field types are inferred on save."})]})}),e.jsxs("div",{className:"px-5 py-3 border-t border-border flex items-center justify-end gap-2 bg-background",children:[e.jsx(Je,{variant:"skeleton",to:R,children:"Cancel"}),e.jsx($,{type:"button",onClick:()=>q.handleSubmit(),isLoading:w,disabled:!y||!q.isValid||!q.dirty,children:"Save changes"})]}),e.jsx(en,{showModal:c,setShowModal:b,record:y??null,onConfirmDelete:me,isLoading:A})]}):null},fn=({showModal:t,setShowModal:a,count:s,onConfirmDelete:d,isLoading:r=!1})=>e.jsx(pe,{showModal:t,setShowModal:a,title:`Delete ${s} record${s===1?"":"s"}`,showDivider:!0,width:"500px",actionButtons:{confirm:{label:`Delete ${s} record${s===1?"":"s"}`,onConfirm:d,isLoading:r,variant:"destructive"},cancel:{label:"Cancel"}},children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 bg-red-50 rounded-lg border border-red-200",children:[e.jsx(nt,{className:"w-5 h-5 text-red-600 shrink-0"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium text-red-900",children:"Warning: This action cannot be undone"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:s===1?"This will permanently delete the selected record.":`This will permanently delete all ${s} selected records.`})]})]}),e.jsx("p",{className:"text-app-gray700",children:"Are you sure you want to continue?"})]})}),yn=t=>{const{data:a,isSelected:s,isFocused:d}=t,{usage:r,baseLabel:n,isDisabled:p}=a,l=r.used+r.remaining,u=l>0?r.used/l*100:0,o=()=>p||u>=100?"text-red-700 bg-red-100":u>=80?"text-amber-700 bg-amber-100":u>=60?"text-orange-700 bg-orange-100":"text-emerald-700 bg-emerald-100",i=()=>p||u>=100?"bg-red-500":u>=80?"bg-amber-500":u>=60?"bg-orange-500":"bg-emerald-500";return e.jsx(Ns.Option,{...t,children:e.jsx("div",{className:O("px-3 py-1 rounded-md mx-1 my-0.5 transition-all duration-200",{"opacity-50 cursor-not-allowed":p,"bg-app-blue400 text-white shadow-sm":s&&!p,"hover:bg-gray-50 hover:shadow-sm":!s&&!p&&!d,"bg-gray-50":d&&!s&&!p}),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("span",{className:O("font-medium text-sm",p?"text-gray-400":s?"text-white":"text-gray-900"),children:n}),l>0&&e.jsx("div",{className:O("flex-1 h-1 rounded-full bg-gray-200 max-w-20",s&&"bg-blue-200"),children:e.jsx("div",{className:O("h-full rounded-full transition-all duration-300",p?"bg-gray-400":s?"bg-white":i()),style:{width:`${Math.min(u,100)}%`}})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{className:O("text-xs px-1.5 py-0.5 rounded-full font-medium",p?"text-gray-500 bg-gray-100":s?"text-blue-100 bg-blue-500/30":o()),children:[r.used,"/",l]}),e.jsx("span",{className:O("text-xs font-medium min-w-[35px] text-right",p?"text-gray-400":s?"text-blue-100":"text-gray-500"),children:r.remaining>0?`${r.remaining} left`:"Full"})]})]})})})},jn=t=>{const{data:a}=t,{usage:s,baseLabel:d}=a,r=s.used+s.remaining;return e.jsx(Ns.SingleValue,{...t,children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("span",{className:"font-medium text-gray-900",children:d}),r>0&&e.jsxs("span",{className:"text-sm text-gray-500",children:["(",s.used,"/",r,")"]})]})})},Nn=({options:t,value:a,onChange:s,name:d="fieldType"})=>e.jsx(dt,{name:d,options:t,value:a,onChange:s,isOptionDisabled:r=>r.isDisabled,components:{Option:yn,SingleValue:jn},classNames:{option:()=>"p-0!",menu:()=>"border! border-gray-200! shadow-lg! rounded-lg! mt-1!",menuList:()=>"p-2! max-h-64! overflow-auto!",control:r=>O("min-h-11! border-2! rounded-lg!",r.isFocused?"border-app-blue400! shadow-md! ring-2! ring-app-blue400/20!":"border-gray-200! hover:border-gray-300!"),valueContainer:()=>"px-3! py-2!",singleValue:()=>"text-gray-900!",placeholder:()=>"text-gray-400!",dropdownIndicator:()=>"text-gray-400! px-2!"},placeholder:"Select field type...",isSearchable:!1}),En=De().shape({name:he().required("Field name is required").min(1,"Field name must be at least 1 character").max(100,"Field name must be less than 100 characters"),key:he().required("Field key is required").test("valid-key","Invalid field key format",t=>sn(t||"")===null),type:he().required("Field type is required"),required:hs(),defaultValue:xs()}),vn=[],Rn=({showModal:t,setShowModal:a,onCreateField:s,onOpenRelationshipM
1047odal:d,existingFields:r=vn,fieldCounts:n,isLoading:p=!1})=>{const[l,u]=x.useState(!1),o=h=>{if(n!=null&&n[h])return n[h];const w=r.filter(A=>A.type===h).length;let v=15;switch(h){case"TEXT_FILTERABLE":case"TEXT_UNIQUE":v=5;break;case"DECIMAL":case"BOOLEAN":case"DATE":v=10;break;default:v=15}return{used:w,remaining:v-w}},i=ze({initialValues:{name:"",key:"",type:"TEXT",required:!1,defaultValue:""},validationSchema:En,onSubmit:h=>{const w={...h,defaultValue:h.defaultValue||void 0};s(w)}}),c=h=>h.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").substring(0,64),b=h=>{const w=h.target.value;if(i.setFieldValue("name",w),i.setFieldTouched("name",!0),!l){const v=c(w);i.setFieldValue("key",v),i.setFieldTouched("key",!0)}},j=h=>{const w=h.target.value;u(!0),i.setFieldValue("key",w),i.setFieldTouched("key",!0)},C=Object.entries(We).filter(([h])=>h!=="JSON"&&h!=="REFERENCE").map(([h,w])=>{const v=o(h),A=v.used+v.remaining,y=v.remaining<=0;let Y;return A>0?Y=`${w} (${v.used}/${A})`:Y=w,{value:h,label:Y,baseLabel:w,isDisabled:y,usage:v}}),R=()=>{i.resetForm(),u(!1),a(!1)},f=h=>{if(!h||h.isDisabled)return;const w=h.value||"TEXT";i.setFieldValue("type",w)},g=C.find(h=>h.value===i.values.type)||null,E=()=>{i.isValid&&i.values.name.trim()&&i.values.key.trim()&&i.handleSubmit()};return e.jsx(pe,{showModal:t,setShowModal:h=>a(typeof h=="function"?h(t):h),title:"Add Field",showDivider:!0,width:"500px",onModalClose:R,actionButtons:{confirm:{label:"Add Field",onConfirm:E,isDisabled:!i.isValid||!i.values.name.trim()||!i.values.key.trim(),isLoading:p},cancel:{label:"Cancel"}},children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx(K,{text:"Field Name *",htmlFor:"name"}),e.jsx(ae,{id:"name",name:"name",value:i.values.name,onChange:b,onBlur:i.handleBlur,placeholder:"Enter field name",errorMessage:i.touched.name&&i.errors.name?i.errors.name:void 0})]}),e.jsxs("div",{children:[e.jsx(K,{text:"Field Key *",htmlFor:"key"}),e.jsx(ae,{id:"key",name:"key",value:i.values.key,onChange:j,onBlur:i.handleBlur,placeholder:"field_key",errorMessage:i.touched.key&&i.errors.key?i.errors.key:void 0,hintText:"Alphanumeric characters and underscores only. Used in API calls."})]}),e.jsxs("div",{children:[e.jsx(K,{text:"Field Type *",htmlFor:"type"}),e.jsx(Nn,{name:"type",value:g,onChange:f,options:C}),(g==null?void 0:g.isDisabled)&&e.jsxs("p",{className:"mt-2 text-sm text-red-600 bg-red-50 border border-red-200 rounded-md p-2",children:["â ï¸ You've reached the limit for ",g.baseLabel," ","fields (",g.usage.used,"/",g.usage.used+g.usage.remaining,"). Consider using a different field type."]}),g&&!g.isDisabled&&g.usage.remaining<=2&&g.usage.remaining>0&&e.jsxs("p",{className:"mt-2 text-sm text-orange-600 bg-orange-50 border border-orange-200 rounded-md p-2",children:["ð¡ Only ",g.usage.remaining," ",g.baseLabel," field",g.usage.remaining===1?"":"s"," remaining."]})]}),e.jsxs("div",{children:[e.jsx(K,{text:"Default Value",htmlFor:"defaultValue"}),e.jsx(ae,{id:"defaultValue",name:"defaultValue",value:i.values.defaultValue,onChange:i.handleChange,onBlur:i.handleBlur,placeholder:"Optional default value"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(K,{text:"Field Options"}),e.jsx("div",{className:"space-y-3",children:e.jsx(ls,{id:"required",checked:i.values.required,onChange:h=>i.setFieldValue("required",h.target.checked),label:"Required field",description:"Users must provide a value for this field"})}),i.values.type==="TEXT_UNIQUE"&&e.jsx("div",{className:"p-3 bg-violet-50 border border-violet-200 rounded-lg",children:e.jsxs("div",{className:"text-sm text-violet-700",children:[e.jsx("strong",{children:"Unique Field:"})," Each record must have a unique value for this field."]})})]}),d&&e.jsx("div",{className:"pt-4 border-t border-app-gray200",children:e.jsx("div",{className:"p-3 bg-app-gray50 border border-app-gray200 rounded-lg",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-app-gray700 font-medium",children:"Need to connect tables?"}),e.jsx("p",{className:"text-xs text-app-gray600 mt-0.5",children:"Create relationships between your data"})]}),e.jsx("button",{type:"button",onClick:()=>{a(!1),d()},className:"inline-flex items-center h-8 box-border px-3 text-sm font-medium text-app-blue600 hover:text-app-blue700 bg-white border border-app-blue200 rounded-md hover:bg-app-blue50 transition-colors",children:"Create Reference â"})]})})})]})})},wn=t=>{try{return JSON.parse(t||"{}"),!0}catch{return!1}},kn=({showModal:t,setShowModal:a,onCreateRecord:s,isLoading:d=!1,tableFields:r})=>{const[n,p]=x.useState(!1),l=Cs(r),u=ks(l),o=ze({initialValues:{...u,jsonData:JSON.stringify(Oe(l,u),null,2)},validationSchema:n?De().shape({jsonData:he().required("JSON data is required").test("valid-json","Must be valid JSON",wn)}):De().shape(l.reduce((j,C)=>(j[C.key]=C.required?he().required(`${C.name} is required`):he(),j),{})),onSubmit:j=>
1047{if(n){try{s(JSON.parse(j.jsonData))}catch{}return}s(Oe(l,j))}}),i=()=>{o.resetForm(),a(!1)},c=()=>{o.isValid&&(o.dirty||n)&&o.handleSubmit()},b=()=>{if(!n)o.setFieldValue("jsonData",JSON.stringify(Oe(l,o.values),null,2));else try{const j=JSON.parse(o.values.jsonData);l.forEach(C=>{o.setFieldValue(C.key,ot(C,j==null?void 0:j[C.key]))})}catch{}p(!n)};return e.jsx(pe,{showModal:t,setShowModal:a,title:"Add Record",showDivider:!0,width:"600px",onModalClose:i,actionButtons:{confirm:{label:"Add Record",onConfirm:c,isDisabled:!o.isValid||!o.dirty&&!n,isLoading:d},cancel:{label:"Cancel"}},children:t&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx($,{type:"button",variant:n?"ghost":"primary",onClick:()=>!n||b(),children:"Form Mode"}),e.jsx($,{type:"button",variant:n?"primary":"ghost",onClick:()=>n||b(),children:"JSON Mode"})]}),n?e.jsxs("div",{children:[e.jsx(K,{htmlFor:"jsonData",text:"JSON Data *"}),e.jsx("textarea",{id:"jsonData",name:"jsonData",value:o.values.jsonData,onChange:o.handleChange,onBlur:o.handleBlur,placeholder:"Enter JSON data...",rows:12,className:"w-full px-3 py-2 border border-app-gray300 rounded-md font-mono text-sm resize-none focus:outline-none focus:ring-2 focus:ring-app-blue500 focus:border-transparent"}),o.touched.jsonData&&o.errors.jsonData&&e.jsx("p",{className:"mt-1 text-sm text-red-600",children:o.errors.jsonData}),e.jsx("p",{className:"mt-1 text-sm text-app-gray600",children:"Enter valid JSON data for the record"})]}):e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsxs("div",{className:"text-center py-8 text-app-gray500",children:[e.jsx("p",{children:"No fields defined for this table."}),e.jsx("p",{className:"text-sm",children:"Add fields to the table first or use JSON mode."})]}):l.map(j=>e.jsx(Ds,{field:j,value:o.values[j.key]??"",onChange:C=>o.setFieldValue(j.key,C),onBlur:()=>o.setFieldTouched(j.key,!0),error:o.touched[j.key]&&o.errors[j.key]?String(o.errors[j.key]):void 0},j.id))})]})})},V=t=>!t.endsWith("s")||["news","series","species","status","progress","address"].includes(t.toLowerCase())||t.endsWith("ss")?t:t.slice(0,-1),Cn=(t,a,s=[])=>{const d=[];return s.forEach(r=>{var n,p,l;if(r.type==="REFERENCE"){const u=((n=r.referencedTable)==null?void 0:n.id)||r.referencedTableId,o=a.find(i=>i.id===u);o&&d.push({id:r.id,type:"one",description:`Each ${V(t.name)} has one ${V(o.name)}`,fieldName:r.name,fieldKey:r.key,targetTableName:o.name,sourceType:"REFERENCE",icon:"ð"})}if(r.type==="REFERENCE_MANY"){const u=((p=r.referencedTable)==null?void 0:p.id)||r.referencedTableId,o=a.find(i=>i.id===u);o&&d.push({id:r.id,type:"many",description:`Each ${V(t.name)} has many ${o.name}`,fieldName:r.name,fieldKey:r.key,targetTableName:o.name,sourceType:"REFERENCE_MANY",icon:"ðð"})}if(r.type==="MEMBER_REFERENCE"&&d.push({id:r.id,type:"one",description:`Each ${V(t.name)} has one Member`,fieldName:r.name,fieldKey:r.key,targetTableName:"Members",sourceType:"MEMBER_REFERENCE",icon:"ð¤"}),r.type==="MEMBER_REFERENCE_MANY"&&d.push({id:r.id,type:"many",description:`Each ${V(t.name)} has many Members`,fieldName:r.name,fieldKey:r.key,targetTableName:"Members",sourceType:"MEMBER_REFERENCE_MANY",icon:"ð¥"}),r.type==="VIRTUAL_REFERENCE_LIST"){const u=((l=r.referencedTable)==null?void 0:l.id)||r.referencedTableId,o=a.find(i=>i.id===u);o&&d.push({id:r.id,type:"many",description:`Each ${V(t.name)} has many ${o.name}`,fieldName:r.name,fieldKey:r.key,targetTableName:o.name,sourceType:"VIRTUAL_REFERENCE_LIST",icon:"ð"})}}),d},Tn=(t,a,s=[])=>{const d=[],r=new Set,n=new Set;s.forEach(l=>{var u,o,i;if(l.type==="REFERENCE"){const c=((u=l.referencedTable)==null?void 0:u.id)||l.referencedTableId;c&&(r.add(`${t.id}-${c}`),r.add(`${c}-${t.id}`))}if(l.type==="REFERENCE_MANY"){const c=((o=l.referencedTable)==null?void 0:o.id)||l.referencedTableId;c&&(r.add(`${t.id}-${c}`),r.add(`${c}-${t.id}`))}if(l.type==="MEMBER_REFERENCE"&&n.add(`${t.id}-member-one`),l.type==="MEMBER_REFERENCE_MANY"&&n.add(`${t.id}-member-many`),l.type==="VIRTUAL_REFERENCE_LIST"){const c=((i=l.referencedTable)==null?void 0:i.id)||l.referencedTableId;c&&(r.add(`${c}-${t.id}`),r.add(`${t.id}-${c}`))}});const p=t.name.toLowerCase();if(p.includes("user")||p.includes("member")||p.includes("course")||p.includes("product")||p.includes("category")||p.includes("tag")||p.includes("group")){const l=`${t.id}-${t.id}`;if(!r.has(l)){let u="related",o="",i="";p.includes("user")||p.includes("member")?(u="connections",o=`Connect ${t.name} to other ${t.name}`,i="Friends, followers, team members"):p.includes("course")?(u="prerequisites",o=`${V(t.name)} has prerequisite ${t.name}`,i="Course dependencies and prerequisites"):p.includes("product")?(u="related_products",o=`Related ${t.name}
1047`,i="Cross-sell and upsell relationships"):(u=`related_${t.name.toLowerCase()}`,o=`Related ${t.name}`,i="Connect similar or related items"),d.push({id:`${t.id}-${t.id}-many`,sourceTable:t.name,targetTable:t.name,type:"many",description:o,example:i,fieldName:u,icon:"ð"})}}return a.forEach(l=>{if(l.id===t.id)return;const u=[{condition:(c,b)=>c.includes("user")&&b.includes("post")||c.includes("author")&&b.includes("book")||c.includes("customer")&&b.includes("order")||c.includes("company")&&b.includes("employee")||c.includes("category")&&b.includes("product"),type:"many",getFieldName:c=>c.toLowerCase().replace(/s$/,""),example:"Query all items belonging to this record"},{condition:(c,b)=>c.includes("user")&&b.includes("profile")||c.includes("customer")&&b.includes("address")||c.includes("order")&&b.includes("invoice"),type:"one",getFieldName:c=>c.toLowerCase().replace(/s$/,""),example:"Each record connects to one other record"}],o=t.name.toLowerCase(),i=l.name.toLowerCase();for(const c of u)if(c.condition(o,i)){const b=c.type==="many"?`${t.id}-${l.id}`:`${t.id}-${l.id}`;r.has(b)||d.push({id:`${t.id}-${l.id}-${c.type}`,sourceTable:t.name,targetTable:l.name,type:c.type,description:`Each ${V(t.name)} has ${c.type==="many"?"many":"one"} ${c.type==="many"?l.name:V(l.name)}`,example:c.example,fieldName:c.getFieldName(t.name),icon:c.type==="many"?"ð":"ð"});break}}),n.has(`${t.id}-member-many`)||d.push({id:`${t.id}-members-many`,sourceTable:t.name,targetTable:"Members",type:"many",description:`Each ${V(t.name)} has many Members`,example:"Connect each record to multiple members (e.g., collaborators, participants)",fieldName:"collaborators",icon:"ð¥"}),d},Mn=({currentStep:t})=>e.jsx("div",{className:"flex items-center justify-center mb-6",children:e.jsx("div",{className:"flex items-center space-x-2",children:["intent","tables","details","preview"].map((a,s)=>{const d=s+1,r=t===a,n=["intent","tables","details","preview"].indexOf(t)>s;return e.jsxs(Xt.Fragment,{children:[e.jsx("div",{className:O("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium",r?"bg-app-blue500 text-white":n?"bg-app-green500 text-white":"bg-muted text-muted-foreground"),children:n?e.jsx(st,{className:"w-4 h-4"}):d}),s<3&&e.jsx("div",{className:O("w-8 h-0.5",n?"bg-app-green500":"bg-muted")})]},a)})})}),Dn=({existingRelationships:t,suggestions:a,referenceUsage:s,onSuggestionSelect:d,onManualSetup:r})=>e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(xe,{className:"w-16 h-16 mx-auto text-app-blue500 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-2",children:"Manage Relationships"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"View existing connections and create new relationships between tables"})]}),t.length>0&&e.jsxs("div",{children:[e.jsx(K,{text:"Current Relationships"}),e.jsx("div",{className:"space-y-2 mt-2",children:t.map(n=>e.jsx("div",{className:"p-4 border border-app-green200 rounded-lg bg-app-green25",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:n.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-app-green900",children:n.description}),e.jsxs("div",{className:"text-sm text-app-green700 mt-1",children:["Field:"," ",e.jsx("span",{className:"font-mono bg-app-green100 px-1 rounded",children:n.fieldKey}),n.sourceType==="VIRTUAL_REFERENCE_LIST"&&e.jsx("span",{className:"ml-2 text-xs bg-app-blue100 text-app-blue700 px-2 py-0.5 rounded",children:"Auto-generated"})]})]}),e.jsx("div",{className:"flex items-center",children:e.jsx("div",{className:"text-xs text-app-green600 bg-app-green100 px-2 py-1 rounded font-medium",children:"Active"})})]})},n.id))})]}),a.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(K,{text:"Suggested Relationships"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.used,"/",s.used+s.remaining," references used"]})]}),e.jsx("div",{className:"space-y-2",children:a.map(n=>e.jsx("button",{type:"button",onClick:()=>d(n),className:O("w-full p-4 text-left border border-border rounded-lg transition-colors",s.remaining===0?"opacity-50 cursor-not-allowed":"hover:border-app-blue300 hover:bg-app-blue25"),disabled:s.remaining===0,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:n.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-foreground",children:n.description}),e.jsx("div",{className:"text-sm text-muted-foreground mt-1",children:n.example})]}),e.jsx(Ke,{className:"w-4 h-4 text-muted-foreground"})]})},n.id))})]}),e.jsxs("div",{className:"border-t pt-4",children:[a.length===0&&e.jsx("div",{className:"text-right mb-2",children:e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.used,"/",s.used+s.remaining," references used"]})}),e.jsx("button",{type:"button",onClick:r,className:"w-full p-4 text-left border border-border rounded-lg hover:border-app-blue300 hover:bg-app-blue25 transition-colors",disabled:s.remaining===0,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_e,{className:"w-6 h-6 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-foreground",children:"Custom Relationship"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:s.remaining===0?"Maximum reference fields reached":"Define your own relationship between tables"})]}),e.jsx(Ke,{className:"w-4 h-4 text-muted-foreground"})]})})]})]}),Sn=({currentTable:t,selectedFieldType:a,onFieldTypeSelect:s,referenceUsage:d,tables:r,otherTables:n,onTableSelect:p})=>e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-2",children:"Choose Relationship Type"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["How should ",t.name," connect to other tables and members?"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx("button",{type:"button",onClick:()=>s("MEMBER_REFERENCE_MANY"),className:O("p-4 rounded-lg border transition-colors text-left",a==="MEMBER_REFERENCE_MANY"?"border-app-blue500 bg-app-blue25":"border-border hover:border-app-blue300 hover:bg-app-blue25"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-2xl",children:"ð¥"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"font-medium text-foreground",children:["Members â ",t.name]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-1",children:["Many-to-many relationships between members and"," ",t.name.toLowerCase()]}),e.jsx("div",{className:"text-xs text-app-green600 mt-2",children:"No limit (junction table)"})]})]})}),e.jsx("button",{type:"button",onClick:()=>s("REFERENCE"),className:O("p-4 rounded-lg border transition-colors text-left",a==="REFERENCE"?"border-app-blue500 bg-app-blue25":d.remaining===0?"border-border bg-muted opacity-50 cursor-not-allowed":"border-border hover:border-app-blue300 hover:bg-app-blue25"),disabled:d.remaining===0,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-2xl",children:"ð"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"font-medium text-foreground",children:[V(t.name)," â Table"]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-1",children:["Each ",V(t.name).toLowerCase()," ","connects to one record from another table"]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-2",children:d.remaining===0?`Limit reached (${d.used}/4)`:`${d.used}/4 used`})]})]})}),e.jsx("button",{type:"button",onClick:()=>s("REFERENCE_MANY"),className:O("p-4 rounded-lg border transition-colors text-left",a==="REFERENCE_MANY"?"border-app-blue500 bg-app-blue25":"border-border hover:border-app-blue300 hover:bg-app-blue25"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-2xl",children:"ð"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"font-medium text-foreground",children:[t.name," â Table"]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-1",children:["Many-to-many relationships between"," ",t.name.toLowerCase()," and another table"]}),e.jsx("div",{className:"text-xs text-app-green600 mt-2",children:"No limit (junction table)"})]})]})})]}),a&&(a==="REFERENCE"||a==="REFERENCE_MANY")&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx(K,{text:"Select the table to connect to:"}),e.jsx("div",{className:"grid grid-cols-1 gap-2 mt-2",children:(a==="REFERENCE_MANY"?r:n).map(l
1047=>e.jsxs("button",{type:"button",onClick:()=>p(l),className:"p-3 text-left border border-border rounded-lg hover:border-app-blue300 hover:bg-app-blue25 transition-colors",children:[e.jsx("div",{className:"font-medium text-foreground",children:l.name}),e.jsx("div",{className:"text-sm text-muted-foreground font-mono",children:l.key}),l.id===t.id&&e.jsx("div",{className:"text-xs text-app-blue600 mt-1",children:"Self-referencing (many-to-many)"})]},l.id))})]})]}),_n=({selectedFieldType:t,selectedTable:a,currentTable:s,fieldName:d,onFieldNameChange:r,fieldKey:n,onFieldKeyChange:p,isRequired:l,onRequiredChange:u})=>{const i=(()=>{switch(t){case"MEMBER_REFERENCE":return{targetName:"Members",relationshipText:"has one",icon:"ð¤",placeholder:"owner"};case"MEMBER_REFERENCE_MANY":return{targetName:"Members",relationshipText:"has many",icon:"ð¥",placeholder:"collaborators"};case"REFERENCE":return{targetName:(a==null?void 0:a.name)||"Records",relationshipText:"has one",icon:"ð",placeholder:(a==null?void 0:a.name.replace(/s$/,""))||"record"};case"REFERENCE_MANY":return{targetName:(a==null?void 0:a.name)||"Records",relationshipText:"has many",icon:"ð",placeholder:(a==null?void 0:a.name)||"records"};default:return{targetName:"Records",relationshipText:"has one",icon:"ð",placeholder:"field"}}})();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-2",children:"Relationship Details"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure how this relationship will work"})]}),e.jsx("div",{className:"bg-muted rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center justify-between text-sm mb-3",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-medium text-foreground",children:s.name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["(",s.key,")"]})]}),e.jsx("div",{className:"flex-1 flex items-center justify-center px-4",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ke,{className:"w-4 h-4"}),e.jsx("span",{className:"text-xs",children:i.relationshipText}),e.jsx(Ke,{className:"w-4 h-4"})]})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx("span",{className:"text-xl",children:i.icon}),e.jsx("div",{className:"font-medium text-foreground",children:i.targetName})]}),a&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["(",a.key,")"]})]})]})}),e.jsxs("div",{children:[e.jsx(K,{text:"Field Name",htmlFor:"fieldName"}),e.jsx(ae,{id:"fieldName",value:d,onChange:r,placeholder:`e.g., ${i.placeholder}`}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Human-readable name for this relationship"})]}),e.jsxs("div",{children:[e.jsx(K,{text:"Field Key",htmlFor:"fieldKey"}),e.jsx(ae,{id:"fieldKey",value:n,onChange:p,placeholder:"field_key"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Used in API calls. Alphanumeric and underscores only."})]}),e.jsx("div",{children:e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:l,onChange:c=>u(c.target.checked),className:"rounded border-border"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Required field"})]})})]})},Fn=({selectedFieldType:t,memberReferenceUsage:a,referenceUsage:s,currentTable:d,selectedTable:r,fieldKey:n})=>{const l=(()=>{switch(t){case"MEMBER_REFERENCE":return{usage:a,usageType:"member reference",maxLimit:4,storageType:"typed column (memRef)",capabilities:[`Connect each ${V(d.name)} to one member`,`Query which member owns each ${V(d.name)}`,"Filter records by member"]};case"MEMBER_REFERENCE_MANY":return{usage:{used:0,remaining:999},usageType:"member reference (many)",maxLimit:null,storageType:"junction table",capabilities:[`Connect each ${V(d.name)} to multiple members`,`Query all members for a specific ${V(d.name)}`,`Get counts of ${d.name} per member`]};case"REFERENCE":return{usage:s,usageType:"record reference",maxLimit:4,storageType:"typed column (ref)",capabilities:[`Connect each ${V(d.name)} to one ${V((r==null?void 0:r.name)||"record")}`,`Query the ${V((r==null?void 0:r.name)||"record")} for any ${V(d.name)}`]};case"REFERENCE_MANY":return{usage:{used:0,remaining:999},usageType:"record reference (many)",maxLimit:null,storageType:"junction table",capabilities:[`Connect each ${V(d.name)} to multiple ${(r==null?void 0:r.name)||"records"}`,`Query all ${(r==null?void 0:r.name)||"records"} for a specific ${V(d.name)}`,`Get counts of ${(r==null?void 0:r.name)||"records"} per ${V(d.name)}`]};default:return{usage:s,usageType:"reference",maxLimit:4,storageType:"typed column",capabilities:["Connect records"]}}})();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(st,{className:"w-16 h-16 mx-auto text-app-green500 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-2",children:"Review Your Relationship"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This is what will be created when you confirm"})]}),l.maxLimit&&l.usage.remaining===0&&e.jsx("div",{className:"text-center p-3 bg-muted rounded-lg",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Maximum ",l.usageType," fields reached (",l.usage.used,"/",l.maxLimit,")"]})}),l.maxLimit&&l.usage.remaining===1&&e.jsx("div",{className:"text-center",children:e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Note: This will use your last ",l.usageType," field slot (",l.usage.used+1,"/",l.maxLimit,")"]})}),e.jsxs("div",{className:"bg-app-green25 dark:bg-app-green900/20 border border-app-green200 dark:border-app-green800 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(st,{className:"w-5 h-5 text-app-green600"}),e.jsx("span",{className:"font-medium text-app-green700 dark:text-app-green400",children:"What gets created:"})]}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 bg-app-green500 rounded-full"}),e.jsxs("span",{children:[e.jsx("code",{className:"bg-app-green100 px-2 py-1 rounded text-xs",children:n})," ","field on ",e.jsx("strong",{children:d.name})," table"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 bg-app-green500 rounded-full"}),e.jsxs("span",{children:["Stored using ",e.jsx("strong",{children:l.storageType}),e.jsxs("span",{className:"text-muted-foreground",children:[" ","(",t,")"]})]})]})]})]}),e.jsxs("div",{className:"bg-app-blue25 dark:bg-app-blue900/20 border border-app-blue200 dark:border-app-blue800 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(xe,{className:"w-5 h-5 text-app-blue600"}
1047),e.jsx("span",{className:"font-medium text-app-blue700 dark:text-app-blue400",children:"You'll be able to:"})]}),e.jsx("div",{className:"space-y-2 text-sm text-app-blue700 dark:text-app-blue300",children:l.capabilities.map(u=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1.5 h-1.5 bg-app-blue500 rounded-full shrink-0"}),e.jsx("span",{children:u})]},u))})]})]})},An=t=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Mn,{currentStep:t.currentStep}),t.currentStep==="intent"&&e.jsx(Dn,{existingRelationships:t.existingRelationships,suggestions:t.suggestions,referenceUsage:t.referenceUsage,onSuggestionSelect:t.onSuggestionSelect,onManualSetup:t.onManualSetup}),t.currentStep==="tables"&&e.jsx(Sn,{currentTable:t.currentTable,selectedFieldType:t.selectedFieldType,onFieldTypeSelect:t.onFieldTypeSelect,referenceUsage:t.referenceUsage,tables:t.tables,otherTables:t.otherTables,onTableSelect:t.onTableSelect}),t.currentStep==="details"&&e.jsx(_n,{selectedFieldType:t.selectedFieldType,selectedTable:t.selectedTable,currentTable:t.currentTable,fieldName:t.fieldName,onFieldNameChange:t.onFieldNameChange,fieldKey:t.fieldKey,onFieldKeyChange:t.onFieldKeyChange,isRequired:t.isRequired,onRequiredChange:t.onRequiredChange}),t.currentStep==="preview"&&e.jsx(Fn,{selectedFieldType:t.selectedFieldType,memberReferenceUsage:t.memberReferenceUsage,referenceUsage:t.referenceUsage,currentTable:t.currentTable,selectedTable:t.selectedTable,fieldKey:t.fieldKey})]}),In=[],On=({showModal:t,setShowModal:a,currentTable:s,tables:d,onCreateRelationship:r,existingFields:n=In,fieldCounts:p,isLoading:l=!1})=>{const[u,o]=x.useState("intent"),[i,c]=x.useState(null),[b,j]=x.useState(null),[C,R]=x.useState(""),[f,g]=x.useState(""),[E,h]=x.useState(!1),[w,v]=x.useState(!1),A=Cn(s,d,n),y=Tn(s,d,n),Y=d.filter(S=>S.id!==s.id),ne=S=>{if(p!=null&&p[S])return p[S];const te=n.filter(ge=>ge.type===S).length;let z=0;switch(S){case"REFERENCE":z=4;break;case"MEMBER_REFERENCE":z=4;break;case"REFERENCE_MANY":case"MEMBER_REFERENCE_MANY":z=0;break;default:z=4}return{used:te,remaining:z>0?z-te:999}},q=ne("REFERENCE"),X=ne("MEMBER_REFERENCE"),me=()=>{o("intent"),c(null),j(null),R(""),g(""),h(!1),v(!1),a(!1)},J=S=>{const te=d.find(z=>z.name===S.targetTable);j(te||null),R(S.fieldName),g(S.fieldName.toLowerCase().replace(/[^a-z0-9]/g,"_")),S.targetTable==="Members"?c(S.type==="one"?"MEMBER_REFERENCE":"MEMBER_REFERENCE_MANY"):c(S.type==="one"?"REFERENCE":"REFERENCE_MANY"),o("details")},H=()=>{o("tables")},T=S=>{c(S),(S==="MEMBER_REFERENCE"||S==="MEMBER_REFERENCE_MANY")&&(j(null),S==="MEMBER_REFERENCE"?(R("owner"),E||g("owner")):(R("collaborators"),E||g("collaborators")),o("details"))},D=S=>{if(j(S),i==="REFERENCE"){const te=S.name.replace(/s$/,"");R(te),E||g(te.toLowerCase().replace(/[^a-z0-9]/g,"_"))}else i==="REFERENCE_MANY"&&(R(S.name),E||g(S.name.toLowerCase().replace(/[^a-z0-9]/g,"_")));o("details")},U=S=>{const te=S.target.value;if(R(te),!E){const z=te.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").substring(0,64);g(z)}},Q=S=>{g(S.target.value),h(!0)},oe=()=>{o("preview")},ie=()=>{if(!i||!C||!f||(i==="REFERENCE"||i==="REFERENCE_MANY")&&!b)return;const S={tableId:s.id,key:f,name:C,type:i,required:w};(i==="REFERENCE"||i==="REFERENCE_MANY")&&(S.referencedTableId=b==null?void 0:b.id),r(S),me()},G=()=>{switch(u){case"intent":return"Manage Relationships";case"tables":return"Choose Connection Type";case"details":return"Configure Relationship";case"preview":return"Confirm Relationship";default:return"Manage Relationships"}},fe=()=>{switch(u){case"intent":return{cancel:{label:"Cancel"}};case"tables":return{cancel:{label:"Back",onClick:()=>o("intent")}};case"details":return{confirm:{label:"Next: Preview",onConfirm:oe,isDisabled:!C||!f},cancel:{label:"Back",onClick:()=>o("tables")}};case"preview":{let S=!1;return(i==="REFERENCE"&&q.remaining===0||i==="MEMBER_REFERENCE"&&X.remaining===0)&&(S=!0),{confirm:{label:"Create Relationship",onConfirm:ie,isLoading:l,isDisabled:S},cancel:{label:"Back",onClick:()=>o("details")}}}default:return{cancel:{label:"Cancel"}}}};return e.jsx(pe,{showModal:t,setShowModal:a,title:G(),showDivider:!0,width:"600px",onModalClose:me,actionButtons:fe(),children:e.jsx(An,{currentStep:u,currentTable:s,tables:d,otherTables:Y,selectedFieldType:i,selectedTable:b,existingRelationships:A,suggestions:y,referenceUsage:q,memberReferenceUsage:X,fieldName:C,fieldKey:f,isRequired:w,onSuggestionSelect:J,onManualSetup:H,onFieldTypeSelect:T,onTableSelect:D,onFieldNameChange:U,onFieldKeyChange:Q,onRequiredChange:v})})},qn=({showModal:t,setShowModal:a,field:s,onConfirmDelete:d,isLoading:r=!1})=>
1047s?e.jsx(pe,{showModal:t,setShowModal:a,title:"Delete Field",showDivider:!0,width:"400px",actionButtons:{confirm:{label:"Delete Field",onConfirm:d,isLoading:r,variant:"destructive"},cancel:{label:"Cancel"}},children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 bg-red-50 rounded-lg border border-red-200",children:[e.jsx(nt,{className:"w-5 h-5 text-red-600 shrink-0"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium text-red-900",children:"Warning: This action cannot be undone"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"Deleting this field will permanently remove it and all associated data from existing records."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-app-gray700",children:['Are you sure you want to delete the field "',s.name,'"?']}),e.jsx("div",{className:"bg-app-gray50 p-3 rounded border",children:e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Name:"})," ",s.name]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Key:"})," ",e.jsx("code",{className:"text-xs bg-app-gray200 px-1 py-0.5 rounded",children:s.key})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Type:"})," ",s.type]}),s.required&&e.jsx("div",{className:"text-red-600",children:"⢠Required field"}),s.unique&&e.jsx("div",{className:"text-blue-600",children:"⢠Unique values"})]})})]})]})}):null,Ln=De().shape({name:he().required("Field name is required").min(1,"Field name must be at least 1 character").max(100,"Field name must be less than 100 characters"),required:hs(),defaultValue:xs()}),Bn=({showModal:t,setShowModal:a,field:s,onUpdateField:d,isLoading:r=!1})=>{const n=ze({initialValues:{name:"",key:"",type:"TEXT",required:!1,defaultValue:""},validationSchema:Ln,onSubmit:c=>{if(!s)return;const b={name:c.name,required:c.required,defaultValue:c.defaultValue||void 0};d(s.id,b)}});x.useEffect(()=>{s&&t&&n.setValues({name:s.name,key:s.key,type:s.type,required:s.required,defaultValue:s.defaultValue||""})},[s,t]);const p=Object.entries(We).map(([c,b])=>({value:c,label:b})),l=()=>{n.resetForm(),a(!1)},u=()=>{n.isValid&&n.handleSubmit()},o=n.values.type!=="JSON"&&n.values.type!=="REFERENCE",i=n.values.type!=="REFERENCE";return s?e.jsx(pe,{showModal:t,setShowModal:a,title:"Edit Field",showDivider:!0,width:"500px",onModalClose:l,actionButtons:{confirm:{label:"Update Field",onConfirm:u,isDisabled:!n.isValid,isLoading:r},cancel:{label:"Cancel"}},children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx(K,{htmlFor:"name",text:"Field Name *"}),e.jsx(ae,{id:"name",name:"name",value:n.values.name,onChange:n.handleChange,onBlur:n.handleBlur,placeholder:"Enter field name",errorMessage:n.touched.name&&n.errors.name?n.errors.name:void 0})]}),e.jsxs("div",{children:[e.jsx(K,{htmlFor:"key",text:"Field Key"}),e.jsx(ae,{id:"key",name:"key",value:n.values.key,onChange:n.handleChange,onBlur:n.handleBlur,placeholder:"field_key",description:"Cannot be changed after field creation",disabled:!0})]}),e.jsxs("div",{children:[e.jsx(K,{htmlFor:"type",text:"Field Type"}),e.jsx(dt,{name:"type",value:p.find(c=>c.value===n.values.type),onChange:c=>n.setFieldValue("type",(c==null?void 0:c.value)||"TEXT"),options:p,isDisabled:!0,classNames:{control:()=>"px-2 border rounded-md text-black bg-app-gray100 border-app-gray200 opacity-60 cursor-not-allowed",singleValue:()=>"text-app-gray600",dropdownIndicator:()=>"pl-1 [&>svg]:fill-app-gray400 opacity-50 cursor-not-allowed"}}),e.jsx("p",{className:"mt-1 text-sm text-app-gray600",children:"Cannot be changed after field creation"})]}),n.values.type==="REFERENCE"&&(s==null?void 0:s.referencedTable)&&e.jsxs("div",{children:[e.jsx(K,{text:"Referenced Table"}),e.jsx("div",{className:"p-3 bg-app-gray50 rounded-lg border",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"text-sm font-medium text-app-gray900",children:s.referencedTable.name}),e.jsx("div",{className:"text-xs text-app-gray500 font-mono",children:s.referencedTable.key})]})}),e.jsx("p",{className:"mt-1 text-sm text-app-gray600",children:"This field stores IDs of records from the selected table"})]}),o&&e.jsxs("div",{children:[e.jsx(K,{htmlFor:"defaultValue",text:"Default Value"}),e.jsx(ae,{id:"defaultValue",name:"defaultValue",value:n.values.defaultValue,onChange:n.handleChange,onBlur:n.handleBlur,placeholder:"Optional default value"})]}),i&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(K,{text:"Field Options"}),e.jsx("div",{className:"space-y-3",children:e.jsx(ls,{id:"required",checked:n.values.required,onChange:c=>n.setFieldValue("required",c.target.checked),label:"Required field",description:"Users must provide a value for this field"})}),n.values.type==="TEXT_UNIQUE"&&e.jsx("div",{className:"p-3 bg-violet-50 border border-violet-200 rounded-lg",children:e.jsxs("div",{className:"text-sm text-violet-700",children:[e.jsx("strong",{children:"Unique Field:"})," Each record must have a unique value for this field."]})})]})]})}):null}
1047,Ss={TEXT:Ve,TEXT_FILTERABLE:Ve,TEXT_UNIQUE:Ia,NUMBER:Bt,DECIMAL:Bt,BOOLEAN:Gr,DATE:vs,EMAIL:Aa,URL:Yr,JSON:Fr,REFERENCE:_e,REFERENCE_MANY:_e,MEMBER_REFERENCE:Be,MEMBER_REFERENCE_MANY:Fa},$n=()=>e.jsx(Wr,{"aria-label":"Empty",className:"size-4 text-muted-foreground"}),Pn=({memberId:t})=>{var r,n;const{data:a}=rs({variables:{id:t},fetchPolicy:"cache-first"}),s=(n=(r=a==null?void 0:a.currentMember)==null?void 0:r.auth)==null?void 0:n.email;if(!s)return e.jsx(_s,{icon:Be,value:t});const d=Es(s);return e.jsxs("div",{className:"flex max-w-[200px] items-center gap-2",children:[e.jsx(os,{className:"size-6 shrink-0 border",style:{backgroundColor:d.bg,color:d.text,borderColor:d.text},children:e.jsx(is,{text:s})}),e.jsx(ce,{as:"span",className:"truncate",children:s})]})},_s=({icon:t,value:a})=>e.jsxs("span",{className:"flex max-w-[200px] items-center gap-1.5",children:[e.jsx(t,{"aria-hidden":!0,className:"size-4 shrink-0 text-muted-foreground"}),e.jsx(ce,{as:"code",className:"block truncate font-mono text-xs",children:a})]}),Un=t=>{if(!t||typeof t!="string")return!1;try{const a=new URL(t),s=a.pathname.toLowerCase();return!!([".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(n=>s.endsWith(n))||["images.unsplash.com","i.imgur.com","cloudinary.com","imagekit.io","res.cloudinary.com","ucarecdn.com","cdn.shopify.com","media.graphassets.com","cdn.sanity.io","images.ctfassets.net","imgix.net"].some(n=>a.hostname.includes(n)))}catch{return!1}},Kn=({value:t})=>{const[a,s]=x.useState(!1);return Un(t)&&!a?e.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",title:t,onClick:r=>r.stopPropagation(),children:e.jsx("img",{src:t,alt:"",className:"h-8 w-8 object-cover rounded border border-border hover:border-app-blue400 transition-colors",onError:()=>s(!0)})}):a?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ur,{"aria-hidden":!0,className:"size-5 text-muted-foreground"}),e.jsx(ce,{as:"a",href:t,target:"_blank",rel:"noopener noreferrer",className:"truncate max-w-40 text-app-blue500 hover:underline",onClick:r=>r.stopPropagation(),children:t})]}):e.jsx(ce,{as:"a",href:t,target:"_blank",rel:"noopener noreferrer",className:"truncate max-w-[200px] block text-app-blue500 hover:underline",onClick:r=>r.stopPropagation(),children:t})},Xe=({icon:t,label:a,filterable:s=!1})=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t,{"aria-hidden":!0,className:"size-4 shrink-0 text-muted-foreground"}),e.jsx(ce,{as:"span",className:"truncate",children:a}),s&&e.jsx(Oa,{"aria-label":"Filterable",className:"size-3.5 shrink-0 text-app-green700"})]}),et=mr(),Vn=({records:t,fields:a,hasMore:s=!1,totalCount:d,onRecordClick:r,onLoadMore:n=()=>{},rowSelection:p,onRowSelectionChange:l,empty:u})=>{const[o,i]=x.useState({}),c=p??o,b=g=>{const E=typeof g=="function"?g(c):g;l?l(E):i(E)},{recordId:j}=qe(),C=x.useMemo(()=>{const g=[{id:"selection",header:({table:v})=>e.jsx("div",{className:"flex items-center justify-center w-full h-full",children:e.jsx(at,{checked:v.getIsAllRowsSelected(),indeterminate:v.getIsSomeRowsSelected(),onChange:v.getToggleAllRowsSelectedHandler()})}),cell:({row:v})=>e.jsx("div",{className:"flex items-center justify-center w-full h-7 px-4 border-r",children:e.jsx(at,{checked:v.getIsSelected(),onChange:v.getToggleSelectedHandler(),onClick:A=>A.stopPropagation()})}),size:48}],h=a.filter(v=>v.type!=="VIRTUAL_REFERENCE_LIST").map(v=>et.accessor(A=>{var y;return(y=A.data)==null?void 0:y[v.key]},{id:v.key,header:()=>Xe({icon:Ss[v.type]??Ve,label:v.name,filterable:v.type==="TEXT_FILTERABLE"}),cell:A=>{const y=A.getValue();if(y==null||y==="")return e.jsx($n,{});switch(v.type){case"BOOLEAN":return e.jsx(_a,{text:y?"Yes":"No",variant:y?"success":"secondary"});case"DATE":return e.jsx("span",{className:"whitespace-nowrap",children:on(y)});case"JSON":return e.jsx(ce,{as:"code",className:"text-xs bg-muted px-2 py-1 rounded max-w-[200px] truncate block",children:typeof y=="string"?y:JSON.stringify(y)});case"NUMBER":case"DECIMAL":return e.jsx("span",{className:"font-mono tabular-nums",children:String(y)});case"URL":return e.jsx(Kn,{value:String(y)});case"MEMBER_REFERENCE":return e.jsx(Pn,{memberId:String(y)});case"REFERENCE":return e.jsx(_s,{icon:_e,value:String(y)});default:return e.jsx(ce,{as:"span",className:"truncate max-w-[200px] block",children:String(y)})}},size:180})),w=[et.accessor(v=>{var A,y;return((y=(A=v.createdByMember)==null?void 0:A.auth)==null?void 0:y.email)||"System"},{id:"createdBy",header:()=>Xe({icon:Sr,label:"Created By"}),cell:v=>{const A=v.getValue();if(A==="System")return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{"aria-hidden":!0,
1047className:"size-5 text-muted-foreground"}),e.jsx("span",{children:"System"})]});const y=Es(A);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(os,{className:"size-6 border",style:{backgroundColor:y.bg,color:y.text,borderColor:y.text},children:e.jsx(is,{text:A})}),e.jsx(ce,{as:"span",className:"truncate max-w-[200px]",children:A})]})},size:280}),et.accessor("createdAt",{id:"createdAt",header:()=>Xe({icon:vs,label:"Date Created"}),cell:v=>e.jsx("span",{children:Se(v.getValue(),"dd LLL, yyyy")}),size:150})];return[...g,...h,...w]},[a]),R=pr({data:t,columns:C,state:{rowSelection:c},enableRowSelection:!0,onRowSelectionChange:b,getRowId:g=>g.id,getCoreRowModel:xr()}),f=t.length===0&&!!u;return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col pt-5",children:[e.jsxs(hr,{className:O(f?"shrink-0 border-b border-border":"min-h-0 flex-1"),fetchMoreData:n,hasMoreData:s,numberOfData:d,headerCellPadding:0,isRowsInteractive:!0,tableProps:{style:{minWidth:R.getTotalSize()}},children:[e.jsx("thead",{className:"text-foreground",children:R.getHeaderGroups().map(g=>e.jsx("tr",{children:g.headers.map(E=>e.jsx("th",{className:O({"p-0!":E.column.id==="selection"}),style:{width:E.getSize()},children:E.isPlaceholder?null:Lt(E.column.columnDef.header,E.getContext())},E.id))},g.id))}),e.jsx("tbody",{className:"text-foreground",children:R.getRowModel().rows.map((g,E)=>{const h=j===g.original.id;return e.jsx("tr",{className:O((g.getIsSelected()||h)&&"selected",E===R.getRowModel().rows.length-1&&"border-b-0!"),onClick:()=>{r&&r(g.original)},children:g.getVisibleCells().map(w=>e.jsx("td",{className:O("align-middle",{"p-0!":w.column.id==="selection"}),style:{width:w.column.getSize()},children:Lt(w.column.columnDef.cell,w.getContext())},w.id))},g.id)})})]}),f&&e.jsx("div",{className:"pt-4",children:u})]})},Yn=t=>t.type!=="VIRTUAL_REFERENCE_LIST",zn=["REFERENCE","REFERENCE_MANY","MEMBER_REFERENCE","MEMBER_REFERENCE_MANY"],Vt=({id:t,checked:a,indeterminate:s,onChange:d,icon:r,label:n,ariaLabel:p,hint:l,className:u})=>e.jsxs("label",{htmlFor:t,className:O("flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-app-gray50",u),children:[e.jsx(at,{id:t,"aria-label":p,checked:a,indeterminate:s,onChange:d}),r,e.jsx("span",{className:"flex-1 truncate text-[14px] leading-6",children:n}),l&&e.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-[12px] leading-6 text-muted-foreground",children:l})]}),Wn=({showModal:t,setShowModal:a,fields:s,recordCount:d,selectedCount:r,isLoading:n=!1,onConfirm:p})=>{const l=x.useMemo(()=>s.filter(Yn),[s]),[u,o]=x.useState([]);x.useEffect(()=>{t&&o(l.map(f=>f.key))},[t,l]);const i=u.length===l.length,c=l.length>0,b=c&&u.length===0,j=f=>o(g=>g.includes(f)?g.filter(E=>E!==f):[...g,f]),C=()=>{const f=l.map(g=>g.key).filter(g=>u.includes(g));p(i?void 0:f)},R=r&&r>0?`${r} selected record${r===1?"":"s"}`:`${d.toLocaleString()} record${d===1?"":"s"}`;return e.jsx(pe,{showModal:t,setShowModal:a,title:"Export to CSV",showDivider:!0,width:"440px",actionButtons:{confirm:{label:"Export CSV",onConfirm:C,isLoading:n,isDisabled:b||d===0},cancel:{label:"Cancel"}},children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-app-gray700",children:d===0?"This table has no records to export yet.":`We'll email you a download link for ${R}.`}),d>0&&!c&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"This table has no stored columns, so the file will contain the record ID, who created each record, and its timestamps."}),d>0&&c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border border-border rounded-lg overflow-hidden",children:[e.jsx(Vt,{id:"export-column-all",checked:i,indeterminate:!i&&u.length>0,onChange:()=>o(i?[]:l.map(f=>f.key)),label:e.jsx("span",{className:"font-medium",children:"All columns"}),ariaLabel:"All columns",hint:`${u.length} of ${l.length}`,className:"bg-app-gray50 border-b border-border"}),e.jsx("div",{className:"max-h-64 overflow-y-auto",children:l.map(f=>{var E,h;const g=Ss[f.type]??Ve;return e.jsx(Vt,{id:`export-column-${f.key}`,checked:u.includes(f.key),onChange:()=>
1047j(f.key),icon:e.jsx(g,{"aria-hidden":!0,className:"size-4 shrink-0 text-muted-foreground"}),label:((E=f.name)==null?void 0:E.trim())||f.key,ariaLabel:((h=f.name)==null?void 0:h.trim())||f.key,hint:zn.includes(f.type)?"name + ID":void 0},f.key)})})]}),e.jsx("p",{className:O("text-[12px] leading-5",b?"text-destructive":"text-muted-foreground"),children:b?"Pick at least one column to export.":"The record ID, who created each record, and its timestamps are always included. Linked records export as both a name and an ID."})]})]})})},Qn=({field:t,onEdit:a,onDelete:s})=>{const{attributes:d,listeners:r,setNodeRef:n,transform:p,transition:l,isDragging:u}=jr({id:t.id}),o={transform:Nr.Transform.toString(p),transition:l};return e.jsxs("div",{ref:n,style:o,className:O("flex items-center gap-2 px-3 py-2 bg-card hover:bg-muted border-b border-border",u&&"opacity-50"),children:[e.jsx("div",{...d,...r,className:"cursor-grab active:cursor-grabbing text-muted-foreground shrink-0",children:e.jsx(Hr,{className:"size-4!"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ce,{as:"span",className:"font-medium text-foreground truncate",children:t.name}),e.jsx("span",{className:"text-xs bg-muted px-2 py-1 rounded uppercase font-mono shrink-0 text-foreground",children:t.type})]}),e.jsx(ce,{as:"div",className:"text-xs text-muted-foreground font-mono mb-1 truncate",children:t.key}),e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[t.required&&e.jsx("span",{className:"text-xs bg-red-100 text-red-700 px-2 py-0.5 rounded shrink-0",children:"Required"}),t.type==="TEXT_UNIQUE"&&e.jsx("span",{className:"text-xs bg-violet-100 text-violet-700 px-2 py-0.5 rounded shrink-0",children:"Unique"}),t.type==="TEXT_FILTERABLE"&&e.jsx("span",{className:"text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded shrink-0",children:"Filterable"})]})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2 shrink-0",children:[e.jsx($,{variant:"icon",onClick:i=>{i.stopPropagation(),a()},title:"Edit field",children:e.jsx(qa,{className:"size-4!"})}),e.jsx($,{variant:"icon",onClick:i=>{i.stopPropagation(),s()},title:"Delete field",children:e.jsx(vr,{className:"size-4!"})})]})]})},Gn=({fields:t,onCreateField:a,onEditField:s,onDeleteField:d,refetch:r})=>{const[n,p]=x.useState(()=>t.filter(c=>c.type!=="VIRTUAL_REFERENCE_LIST")),[l]=Xa(),{createToastAlert:u}=Le();Xt.useEffect(()=>{const c=t.filter(b=>b.type!=="VIRTUAL_REFERENCE_LIST");p([...c].sort((b,j)=>b.tableOrder-j.tableOrder))},[t]);const o=async c=>{const{active:b,over:j}=c;if(!j||b.id===j.id)return;const C=n.findIndex(f=>f.id===b.id),R=n.findIndex(f=>f.id===j.id);if(C!==-1&&R!==-1){const f=yr(n,C,R);p(f);const g=f.map((E,h)=>({fieldId:E.id,tableOrder:h}));u({message:"Updating field order...",alertType:"processing"});try{await l({variables:{input:{orders:g}}}),u({message:"Field order updated successfully!",alertType:"success"}),r&&await r()}catch(E){p(n),u({message:E.message||"Failed to update field order",alertType:"error"})}}},i=[{text:"Add a field",icon:e.jsx(Rr,{className:"size-4!"}),onClick:a,dataCy:"add-field-option"}];return e.jsx(Er,{buttonText:"Fields",variant:"skeleton",buttonLeftIcon:e.jsx(Zr,{className:"size-4!"}),dataCy:"fields-button",align:"end",children:e.jsxs("div",{className:"w-max max-w-[360px]",children:[n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"max-h-[calc(100vh-200px)] overflow-y-auto",children:e.jsx(gr,{onDragEnd:o,children:e.jsx(br,{items:n.map(c=>c.id),strategy:fr,children:n.map(c=>e.jsx(Qn,{field:c,onEdit:()=>s(c),onDelete:()=>d(c)},c.id))})})}),e.jsx("hr",{className:"my-1"})]}),e.jsx("div",{className:"p-1",children:i.map(({text:c,icon:b,onClick:j,dataCy:C})=>e.jsxs("button",{type:"button",className:"p-2 hover:bg-muted cursor-pointer text-right rounded flex items-center gap-2 focus:bg-muted text-foreground",onClick:j,"data-cy":C,children:[b,c]},c))})]})})},Fs=({rowCount:t=8,columnCount:a=5})=>e.jsxs("div",{className:"border border-border rounded-lg overflow-hidden",children:[e.jsx("div",{className:"flex items-center gap-4 bg-muted px-4 py-3 border-b border-border",children:Array.from({length:a}).map((s,d)=>e.jsx("div",{className:"flex-1",children:e.jsx(P,{height:16})},`records-skeleton-header-${d}`))}),Array.from({length:t}).map((s,d)=>e.jsx("div",{className:"flex items-center gap-4 px-4 py-3 border-b border-border last:border-b-0",children:Array.from({length:a}).map((r,n)=>e.jsx("div",{className:"flex-1",children:e.jsx(P,{height:18})},`records-skeleton-row-${d}-col-${n}`))},`records-skeleton-row-${d}`))]}),Jn=()=>e.jsx("div",{className:"flex h-full overflow-hidden",children:e.jsx(Re,{className:"w-full",children:e.jsxs("div",{className:"p-6 h-full w-full overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(P,{width:140,height:36,borderRadius:8}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(P,{width:40,height:40,borderRadius:8}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(P,{width:180,height:24}),e.jsx(P,{width:100,height:14})]}),e.jsx(P,{width:46,height:20,borderRadius:9999})]})]}),e.jsx(P,{width:120,height:32,borderRadius:9999})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-baseline gap-3",children:[e.jsx(P,{width:130,height:24}),e.jsx(P,{width:86,height:30,borderRadius:8})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(P,{width:172,height:36,borderRadius:8}),e.jsx(P,{width:86,height:36,borderRadius:8}),e.jsx(P,{width:110,height:36,borderRadius:8})]})]}),e.jsx(Fs,{})]})]})})}),it=[{id:"content_site",label:"Content site",description:"Anyone can read. Only you can add or edit.",rules:{createRule:se.AdminOnly,readRule:se.Public,updateRule:se.AdminOnly,deleteRule:se.AdminOnly}},{id:"members_own",label:"Members' own data",description:"Members add, see and edit only their own rows.",rules:{createRule:se.Authenticated,readRule:se.AuthenticatedOwn,updateRule:se.AuthenticatedOwn,deleteRule:se.AuthenticatedOwn}},{id:"shared_by_members",label:"Shared by members",description:"Members add rows and edit their own. Anyone logged in can read.",rules:{createRule:se.Authenticated,readRule:se.Authenticated,updateRule:se.AuthenticatedOwn,deleteRule:se.AdminOnly}}],tt="content_site",Te=t=>{const a=it.find(s=>
1047s.id===t);if(!a)throw new Error(`Unknown access preset: ${t}`);return a},Qe=t=>{var a;return((a=it.find(s=>s.rules.createRule===t.createRule&&s.rules.readRule===t.readRule&&s.rules.updateRule===t.updateRule&&s.rules.deleteRule===t.deleteRule))==null?void 0:a.id)??"custom"},Ue={[se.Public]:"anyone",[se.Authenticated]:"any member",[se.AuthenticatedOwn]:"the member who made it",[se.AdminOnly]:"only you"},Hn=t=>{const a=Qe(t);if(a!=="custom"){const s=Te(a);return`${s.label}: ${s.description}`}return`Custom: ${Ue[t.readRule]} can read, ${Ue[t.createRule]} can add, ${Ue[t.updateRule]} can edit, ${Ue[t.deleteRule]} can delete.`},Zn=t=>t===At.Vanilla||t===At.React?"npm":"script",Xn=new Set(["TEXT","TEXT_FILTERABLE","NUMBER","DECIMAL","DATE","EMAIL","URL"]),ed=t=>t.fields.filter(a=>Xn.has(a.type)).slice(0,3),td=(t,a,{publicKey:s}={})=>{const d=ed(t),r=`${t.key}-list`,n=[];return a==="npm"?(n.push('import memberstackDOM from "@memberstack/dom";',""),s?n.push(`const memberstack = memberstackDOM.init({ publicKey: ${JSON.stringify(s)} });`):n.push("// Replace the placeholder with your public key from Settings > Install.",'const memberstack = memberstackDOM.init({ publicKey: "YOUR_PUBLIC_KEY" });')):n.push("// Paste into your page's custom code, after the Memberstack script.","const memberstack = window.$memberstackDom;"),n.push("",`// Give the element that should show the list this id: ${r}`,`const list = document.getElementById("${r}");`,"","const { data } = await memberstack.queryDataRecords({",` table: "${t.key}",`,' query: { findMany: { orderBy: { createdAt: "desc" }, take: 20 } },',"});","","for (const record of data.records) {"," const item = document.createElement('div');"),d.length===0?n.push(" item.textContent = JSON.stringify(record.data);"):(n.push(" item.textContent = ["),d.forEach((p,l)=>{const u=l===d.length-1;n.push(` record.data.${p.key},${u?"":' " · ",'}`)}),n.push(' ].join("");')),n.push(" list.appendChild(item);","}"),n.join(` 1048`)},As=t=>`ms:data-tables:use-on-site:dismissed:${t}`,Yt=t=>{try{return localStorage.getItem(As(t))==="1"}catch{return!1}},sd=t=>{try{localStorage.setItem(As(t),"1")}catch{}},zt={script:"Webflow, WordPress or script tag",npm:"npm / yarn"},ad=({table:t,docsUrl:a})=>{var i;const{appData:s}=La(),[d,r]=x.useState(()=>Yt(t.id));x.useEffect(()=>{r(Yt(t.id))},[t.id]);const[n,p]=x.useState(!1),[l,u]=x.useState(()=>Zn(s==null?void 0:s.stack));if(d||t.fields.length===0)return null;const o=l==="script"?"npm":"script";return e.jsxs("section",{"aria-label":"Show these records on your site",className:"rounded-lg border border-app-blue200 bg-app-blue50/40",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5",children:[e.jsxs("button",{type:"button","aria-expanded":n,onClick:()=>p(c=>!c),className:"flex min-w-0 flex-1 items-center gap-2 text-left text-body-sm font-bold text-foreground",children:[e.jsx(ds,{"aria-hidden":!0,className:"size-4 shrink-0 text-app-blue400"}),e.jsx("span",{className:"truncate",children:"Show these records on your site"}),e.jsx(Ba,{"aria-hidden":!0,className:O("ml-auto size-4 shrink-0 text-muted-foreground transition-transform",n&&"rotate-180")})]}),e.jsx($,{variant:"icon","aria-label":"Dismiss",onClick:()=>{sd(t.id),r(!0)},children:e.jsx(Me,{className:"size-4"})})]}),n&&e.jsxs("div",{className:"space-y-3 border-t border-app-blue200 px-4 pb-4 pt-3",children:[e.jsxs("p",{className:"text-utility-md text-muted-foreground",children:["Copy this into your site to list the newest 20 records. It uses your real table and field names, so nothing needs renaming. Written for"," ",e.jsx("span",{className:"font-bold",children:zt[l]}),"."," ",e.jsxs("button",{type:"button",className:"text-app-blue400 underline-offset-2 hover:underline",onClick:()=>u(o),children:["Show the ",zt[o]," version"]})]}),e.jsx(wr,{value:td(t,l,{publicKey:(i=s==null?void 0:s.apiKeys)==null?void 0:i.publicKey}),enableCopy:!0,copyMessage:"Snippet copied.",showLineNumbers:!0,hasBorder:!0}),e.jsxs("p",{className:"text-utility-md text-muted-foreground",children:["Want filters, one record, or editing?"," ",e.jsx("a",{href:a,target:"_blank",rel:"noreferrer",className:"text-app-blue400 underline-offset-2 hover:underline",children:"Open the full guide"}),"."]})]})]})},rd=["TEXT","TEXT_FILTERABLE","TEXT_UNIQUE","EMAIL","URL","NUMBER","DECI
1048MAL","BOOLEAN","DATE"],Wt=[{value:"contains",label:"Contains"},{value:"equals",label:"Equals"},{value:"startsWith",label:"Starts with"},{value:"endsWith",label:"Ends with"}],nd=[{value:"equals",label:"Equals (=)"},{value:"gt",label:"Greater than (>)"},{value:"gte",label:"Greater or equal (>=)"},{value:"lt",label:"Less than (<)"},{value:"lte",label:"Less or equal (<=)"}],dd=[{value:"equals",label:"Equals"}],ld=[{value:"equals",label:"Equals"},{value:"gt",label:"After"},{value:"gte",label:"On or after"},{value:"lt",label:"Before"},{value:"lte",label:"On or before"}],od=t=>{switch(t){case"TEXT":case"TEXT_FILTERABLE":case"TEXT_UNIQUE":case"EMAIL":case"URL":return Wt;case"NUMBER":case"DECIMAL":return nd;case"BOOLEAN":return dd;case"DATE":return ld;default:return Wt}},id=()=>{var ht,gt,bt,ft,yt,jt,Nt,Et,vt,Rt,wt,kt,Ct,Tt,Mt,Dt;const{tableKey:t,recordId:a,appId:s}=qe(),d=rt(),[r,n]=x.useState(!1),[p,l]=x.useState(!1),[u,o]=x.useState(!1),[i,c]=x.useState(!1),[b,j]=x.useState(!1),[C,R]=x.useState(null),[f,g]=x.useState({}),[E,h]=x.useState(!1),[w,v]=x.useState(null),A=Object.keys(f).filter(m=>f[m]),y=A.length,[Y,ne]=x.useState(null),[q,X]=x.useState([]),me=20,[J,H]=x.useState([]),[T,D]=x.useState(null),[U,Q]=x.useState(""),[oe,ie]=x.useState(null),G=x.useRef(),[fe,S]=x.useState(""),[te,z]=x.useState(""),[ge,F]=x.useState(""),[de,ye]=x.useState("");x.useEffect(()=>{const m=setTimeout(()=>{z(fe)},300);return()=>clearTimeout(m)},[fe]);const Fe=m=>{ye(m),ne(null),X([]),g({})};x.useEffect(()=>()=>{G.current&&clearTimeout(G.current)},[]);const{createToastAlert:Z}=Le(),{env:Ee}=cs(),le=x.useRef(Ee),{data:N,loading:ct,error:ve,refetch:re}=er({variables:{key:t||""},skip:!t}),{data:we}=fs(),{data:ke,loading:Ls,error:Bs}=as({variables:{first:10,search:te||void 0},skip:(T==null?void 0:T.fieldType)!=="CREATED_BY"}),ut=x.useMemo(()=>{var m;return(m=N==null?void 0:N.dataTable)!=null&&m.fields?N.dataTable.fields.filter(M=>rd.includes(M.type)):[]},[(ht=N==null?void 0:N.dataTable)==null?void 0:ht.fields]),$s=x.useMemo(()=>{const m=de.trim();if(J.length===0&&!m)return;const M={};let I;for(const L of J){if(!L.value)continue;if(L.fieldType==="CREATED_BY"){I=L.value;continue}let ee=L.value;if(L.fieldType==="NUMBER"||L.fieldType==="DECIMAL"){const Ge=Number(L.value);if(Number.isNaN(Ge))continue;ee=Ge}else L.fieldType==="BOOLEAN"&&(ee=L.value==="true");M[L.fieldKey]={[L.operator]:ee}}const W=Object.keys(M).length>0;if(!(!W&&!I&&!m))return{...W&&{fieldFilters:M},...I&&{createdByMemberId:I},...m&&{search:m}}},[J,de]),{data:B,loading:Ae,error:Ie,refetch:je}=gs({variables:{tableId:((gt=N==null?void 0:N.dataTable)==null?void 0:gt.id)||"",filter:$s,pagination:{first:me,after:Y}},skip:!((bt=N==null?void 0:N.dataTable)!=null&&bt.id),fetchPolicy:"cache-and-network",notifyOnNetworkStatusChange:!0}),[Ps,{loading:Us}]=tr(),[Ks,{loading:Vs}]=sr(),[Ys,{loading:zs}]=ar(),[mt,{loading:pt}]=ys(),[Ws,{loading:Qs}]=rr(),[Gs,{loading:Js}]=nr();x.useEffect(()=>{var m;Ee!==le.current&&(re(),(m=N==null?void 0:N.dataTable)!=null&&m.id&&(ne(null),X([]),H([]),D(null),Q(""),S(""),z(""),ie(null),g({}),je()),le.current=Ee)},[Ee,re,je,(ft=N==null?void 0:N.dataTable)==null?void 0:ft.id]),x.useEffect(()=>{var m;(m=N==null?void 0:N.dataTable)!=null&&m.id&&je()},[Y,je,(yt=N==null?void 0:N.dataTable)==null?void 0:yt.id]);const $e=m=>{Q(m),G.current&&clearTimeout(G.current),G.current=setTimeout(()=>{if(T){const M={...T,value:m};H(I=>{const W=I.findIndex(L=>L.fieldKey===M.fieldKey);if(W>=0){const L=[...I];return L[W]=M,L}return[...I,M]}),D(null),Q(""),ie(null),Ce(),g({})}},300)},Hs=(m,M)=>{G.current&&clearTimeout(G.current),oe&&(H(I=>[...I,oe]),ie(null)),D({fieldKey:m.key,fieldName:m.name,fieldType:m.type,operator:M.value,operatorLabel:M.label,value:""}),Q("")},Zs=(m,M)=>{G.current&&clearTimeout(G.current);const I={fieldKey:"createdByMemberId",fieldName:"Created By",fieldType:"CREATED_BY",operator:"equals",operatorLabel:"is",value:m,displayValue:M};H(W=>{const L=W.findIndex(ee=>ee.fieldKey==="createdByMemberId");if(L>=0){const ee=[...W];return ee[L]=I,ee}return[...W,I]}),D(null),Q(""),S(""),z(""),ie(null),Ce(),g({})},Xs=m=>{H(M=>M.filter(I=>I.fieldKey!==m)),Ce(),g({})},ea=()=>{G.current&&clearTimeout(G.current),H([]),D(null),Q(""),S(""),z(""),ie(null),Ce(),g({})},ta=()=>{G.current&&clearTimeout(G.current),oe&&(H(m=>[...m,oe]),ie(null)),D(null),Q(""),S(""),z("")},sa=m=>{G.current&&clearTimeout(G.current),ie(m),D({fieldKey:m.fieldKey,fieldName:m.fieldName,fieldType:m.fieldType,operator:m.operator,operatorLabel:m.operatorLabel,value:m.value,displayValue:m.dis
1048playValue}),Q(m.value),m.fieldType==="CREATED_BY"&&S(m.displayValue||""),H(M=>M.filter(I=>I.fieldKey!==m.fieldKey))},aa=()=>{var m,M,I,W;if((M=(m=B==null?void 0:B.dataRecords)==null?void 0:m.pageInfo)!=null&&M.hasNextPage&&((W=(I=B==null?void 0:B.dataRecords)==null?void 0:I.pageInfo)!=null&&W.endCursor)){const L=B.dataRecords.pageInfo.endCursor;X(ee=>[...ee,Y||""]),ne(L)}},ra=()=>{if(q.length>0){const m=q[q.length-1];X(M=>M.slice(0,-1)),ne(m===""?null:m)}},Ce=()=>{ne(null),X([])},na=async m=>{var M;try{(await Ps({variables:{input:{tableId:((M=N==null?void 0:N.dataTable)==null?void 0:M.id)||"",data:m}}})).data&&(Z({message:"Record created successfully",alertType:"success"}),n(!1),Ce(),je(),re())}catch(I){Z({message:I.message||"Failed to create record",alertType:"error"})}},da=async()=>{var m,M,I;if(!(!((m=N==null?void 0:N.dataTable)!=null&&m.id)||A.length===0))try{const L=((I=(M=(await Ks({variables:{input:{tableId:N.dataTable.id,ids:A}}})).data)==null?void 0:M.bulkDeleteDataRecords)==null?void 0:I.deletedCount)??0;Z({message:`Deleted ${L} record${L===1?"":"s"}`,alertType:"success"}),h(!1),g({}),Ce(),je(),re()}catch(W){Z({message:W.message||"Failed to delete records",alertType:"error"})}},la=async m=>{var M,I,W;if((M=N==null?void 0:N.dataTable)!=null&&M.id)try{const ee=((W=(I=(await Ys({variables:{input:{tableId:N.dataTable.id,...m?{fieldKeys:m}:{},...w==="selected"?{recordIds:A}:{}}}})).data)==null?void 0:I.exportDataTable)==null?void 0:W.recordCount)??0;Z({message:ee===0?"Nothing to export â this table has no records.":`Exporting ${ee.toLocaleString()} record${ee===1?"":"s"}. We'll email you a download link.`,alertType:ee===0?"error":"success"}),v(null)}catch(L){Z({message:Ya(L)==="data-table-not-found"?"This table no longer exists. Refresh the page and try again.":Va(L)||"Failed to start export",alertType:"error"})}},oa=async m=>{var M;try{(await mt({variables:{input:{tableId:((M=N==null?void 0:N.dataTable)==null?void 0:M.id)||"",...m}}})).data&&(Z({message:"Field created successfully",alertType:"success"}),l(!1),re())}catch(I){Z({message:I.message||"Failed to create field",alertType:"error"})}},ia=async m=>{try{(await mt({variables:{input:m}})).data&&(Z({message:"Relationship created successfully",alertType:"success"}),o(!1),re())}catch(M){Z({message:M.message||"Failed to create relationship",alertType:"error"})}},ca=async(m,M)=>{try{const{name:I,required:W,defaultValue:L,tableOrder:ee}=M||{};(await Ws({variables:{input:{id:m,name:I,required:W,defaultValue:L,tableOrder:ee}}})).data&&(Z({message:"Field updated successfully",alertType:"success"}),c(!1),R(null),re())}catch(I){Z({message:I.message||"Failed to update field",alertType:"error"})}},ua=async()=>{if(C)try{(await Gs({variables:{input:{id:C.id}}})).data&&(Z({message:"Field deleted successfully",alertType:"success"}),j(!1),R(null),re())}catch(m){Z({message:m.message||"Failed to delete field",alertType:"error"})}},ma=m=>{R(m),c(!0)},pa=m=>{R(m),j(!0)};if(ct)return e.jsx(Jn,{});if(ve||!(N!=null&&N.dataTable))return e.jsx("div",{className:"flex h-full overflow-hidden",children:e.jsx(Re,{className:"w-full",children:e.jsx("div",{className:"p-6 h-full w-full overflow-y-auto",children:e.jsx(be,{icon:e.jsx(xe,{className:"w-12 h-12 text-red-400"}),title:"Failed to load data table",description:(ve==null?void 0:ve.message)||"The requested table could not be found.",action:e.jsxs("div",{className:"space-x-3",children:[e.jsx($,{onClick:()=>re(),children:"Try Again"}),e.jsx(St,{to:"..",children:e.jsx($,{variant:"ghost",children:"Back to Tables"})})]})})})})});const _=N.dataTable,Ne=(((jt=_.fields)==null?void 0:jt.length)??0)>0,xt=de!==""||J.length>0,xa=Ne&&((((Nt=N==null?void 0:N.dataTable)==null?void 0:Nt.recordCount)??0)>0||(((Et=B==null?void 0:B.dataRecords)==null?void 0:Et.totalCount)??0)>0||xt||ge!==""||T!==null),ha={appId:s||"",tableKey:t||"",tableFields:(_==null?void 0:_.fields)||[],refetchRecords:()=>{je()},refetchTable:()=>{re()}};return e.jsxs("div",{className:"flex h-full overflow-hidden",children:[e.jsx(Re,{className:O("w-full",a&&"md:mr-4"),children:e.jsxs("div",{className:"flex flex-col h-full w-full overflow-hidden",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 px-6 pt-6 pb-4 shrink-0",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(St,{to:"..",className:"text-h3 font-bold text-muted-foreground hover:text-foreground transition-colors whitespace-nowrap",children:"Data Tables"}),e.jsx("span",{className:"text-h3 font-bold text-muted-foreground",children:"/"}),e.jsx("h3",{className:"text-h3 font-bold text-foreground truncate min-w-0",children:_.name})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:[e.jsx("code",{className:"font-mono",children:_.key})," · ",lt(((vt=B==null?void 0:B.dataRecords)==null?void 0:vt.totalCount)||0)]}),e.jsxs("p",{className:"mt-1 flex items-start gap-1.5 text-utility-md text-muted-foreground",children:[e.jsx(js,{"aria-hidden":!0,
1048className:"mt-0.5 size-3.5 shrink-0"}),e.jsx("span",{children:Hn({createRule:_.createRule,readRule:_.readRule,updateRule:_.updateRule,deleteRule:_.deleteRule})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx($a,{responsive:!0}),e.jsxs($,{variant:"outline",onClick:()=>o(!0),"aria-label":"Manage Relationships",children:[e.jsx(_e,{className:O("w-4 h-4",!a&&"xl:mr-2")}),e.jsx("span",{className:O("hidden",!a&&"xl:inline"),children:"Manage Relationships"})]}),e.jsx(Gn,{fields:(_==null?void 0:_.fields)||[],onCreateField:()=>l(!0),onEditField:ma,onDeleteField:pa,refetch:re}),e.jsxs($,{variant:"outline",onClick:()=>v("all"),disabled:!Ne,title:Ne?void 0:"Add a field first","aria-label":"Export to CSV",children:[e.jsx(kr,{className:O("w-4 h-4",!a&&"xl:mr-2")}),e.jsx("span",{className:O("hidden",!a&&"xl:inline"),children:"Export CSV"})]}),e.jsx($,{onClick:()=>n(!0),disabled:!Ne,title:Ne?void 0:"Add a field first",children:a?"Add":"Add Record"})]})]}),Ne&&e.jsx("div",{className:"px-6 pb-4 shrink-0",children:e.jsx(ad,{table:{id:_.id,key:_.key,fields:(_.fields||[]).map(m=>({key:m.key,type:m.type}))},docsUrl:`/apps/${s}/data-tables/docs`})}),e.jsxs("div",{className:"px-6 space-y-4 shrink-0",children:[xa&&e.jsx(us,{value:ge,onChange:F,onDebouncedChange:Fe,placeholder:"Search records...",trailing:e.jsxs(ba,{modal:!1,children:[e.jsxs(fa,{className:"flex cursor-pointer items-center gap-2 px-4 text-[14px] leading-6 text-foreground outline-none hover:bg-muted focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring data-[state=open]:bg-muted",children:[e.jsx(Pa,{className:"size-4! text-foreground"})," Filters",J.length>0&&e.jsx(Ua,{count:J.length})]}),e.jsxs(ya,{className:Ot,align:"end",collisionPadding:It,children:[e.jsxs(_t,{className:O(He,"gap-2"),onClick:()=>{oe&&(H(m=>[...m,oe]),ie(null)),D({fieldKey:"createdByMemberId",fieldName:"Created By",fieldType:"CREATED_BY",operator:"equals",operatorLabel:"is",value:""}),Q(""),S(""),z("")},children:[e.jsx("span",{className:"flex-1",children:"Created By"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Member"})]}),ut.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"my-1 border-t border-border"}),ut.map(m=>e.jsxs(ja,{children:[e.jsxs(Na,{className:O(He,"gap-2 data-[state=open]:bg-muted"),children:[e.jsx("span",{className:"flex-1",children:m.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.type})]}),e.jsx(Ea,{children:e.jsx(va,{className:Ot,collisionPadding:It,children:od(m.type).map(M=>e.jsx(_t,{className:He,onClick:()=>Hs(m,M),children:M.label},M.value))})})]},m.id))]})]})]})}),T&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 bg-muted rounded-lg px-3 py-1.5 text-sm",children:[e.jsx("span",{className:"font-medium",children:T.fieldName}),e.jsx("span",{className:"text-muted-foreground",children:T.operatorLabel.toLowerCase()})]}),T.fieldType==="CREATED_BY"?e.jsxs("div",{className:"relative",children:[e.jsx("input",{autoFocus:!0,t
1048ype:"text",value:fe,onChange:m=>S(m.target.value),className:"max-w-xs px-3 py-1.5 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary",placeholder:"Search by email..."}),e.jsx("div",{className:"absolute top-full mt-1 w-full bg-popover border border-border rounded-lg z-50 shadow-md max-h-48 overflow-y-auto min-w-60",children:Bs?e.jsx("div",{className:"px-3 py-2 text-sm text-destructive",children:"Failed to load members"}):Ls?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):((wt=(Rt=ke==null?void 0:ke.getMembers)==null?void 0:Rt.edges)==null?void 0:wt.length)===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"No members found"}):(Ct=(kt=ke==null?void 0:ke.getMembers)==null?void 0:kt.edges)==null?void 0:Ct.map(m=>e.jsx("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-muted text-foreground",onClick:()=>Zs(m.node.id,m.node.auth.email),children:m.node.auth.email},m.node.id))})]}):T.fieldType==="BOOLEAN"?e.jsxs("select",{value:U,onChange:m=>$e(m.target.value),className:"max-w-xs px-3 py-1.5 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary",children:[e.jsx("option",{value:"",children:"Select value..."}),e.jsx("option",{value:"true",children:"True"}),e.jsx("option",{value:"false",children:"False"})]}):T.fieldType==="DATE"?e.jsx("input",{type:"date",value:U,onChange:m=>$e(m.target.value),className:"max-w-xs px-3 py-1.5 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary",placeholder:"Select date..."}):T.fieldType==="NUMBER"||T.fieldType==="DECIMAL"?e.jsx("input",{type:"number",value:U,onChange:m=>$e(m.target.value),className:"max-w-xs px-3 py-1.5 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary",placeholder:"Enter number...",step:T.fieldType==="DECIMAL"?"0.01":"1"}):e.jsx("input",{type:"text",value:U,onChange:m=>$e(m.target.value),className:"max-w-xs px-3 py-1.5 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary",placeholder:"Enter value..."}),e.jsx($,{variant:"ghost",onClick:ta,className:"text-muted-foreground hover:text-foreground p-1",children:e.jsx(Me,{className:"w-4 h-4"})})]}),J.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Filtering by:"}),J.map(m=>e.jsxs("div",{className:"inline-flex items-center gap-2 bg-card text-card-foreground rounded-lg px-3 py-1.5 text-sm font-medium border border-border",children:[e.jsxs("button",{type:"button",onClick:()=>sa(m),className:"inline-flex items-center gap-2 hover:bg-muted rounded px-1 -mx-1",title:"Click to edit filter value",children:[e.jsx("span",{children:m.fieldName}),e.jsx("span",{className:"text-app-gray500",children:m.operatorLabel.toLowerCase()}),e.jsxs("span",{children:['"',m.displayValue??m.value,'"']})]}),e.jsx("button",{type:"button","aria-label":"Remove filter",onClick:()=>Xs(m.fieldKey),className:"ml-1 hover:bg-muted rounded p-0.5",children:e.jsx(Me,{className:"w-3 h-3"})})]},m.fieldKey)),J.length>1&&e.jsx("button",{type:"button",onClick:ea,className:"text-sm text-muted-foreground hover:text-foreground font-medium",children:"Clear all"})]}),y>0&&e.jsxs("div",{className:"p-2 pl-4 bg-app-gray50 rounded-lg flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-black",children:y})," selected of ",((Tt=B==null?void 0:B.dataRecords)==null?void 0:Tt.totalCount)??0]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"ghost",onClick:()=>g({}),children:"Deselect all"}),e.jsxs($,{variant:"outline",onClick:()=>v("selected"),children:["Export ",y," record",y===1?"":"s"]}),e.jsxs($,{variant:"destructive",onClick:()=>h(!0),children:["Delete ",y," record",y===1?"":"s"]})]})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 px-6 pt-4 overflow-hidden flex flex-col",children:[Ae&&e.jsx(Fs,{}),!Ae&&Ie&&e.jsx(be,{icon:e.jsx(xe,{className:"w-12 h-12 text-red-400"}
1048),title:"Failed to load records",description:Ie.message||"There was an error loading the records.",action:e.jsx($,{onClick:()=>je(),children:"Try Again"})}),!Ae&&!Ie&&!Ne&&e.jsx(be,{icon:e.jsx(xe,{className:"w-12 h-12 text-app-gray300"}),title:"Add a field to get started",description:"Fields are the columns of your table, like title or price. Add one and you can start adding records.",action:e.jsx($,{onClick:()=>l(!0),children:"Add Field"})}),!Ae&&!Ie&&Ne&&((Mt=B==null?void 0:B.dataRecords)==null?void 0:Mt.edges)&&e.jsx(Vn,{records:B.dataRecords.edges.map(m=>m.node),fields:(_==null?void 0:_.fields)||[],hasMore:!1,totalCount:B.dataRecords.totalCount,onRecordClick:m=>d(m.id),onLoadMore:()=>{},rowSelection:f,onRowSelectionChange:g,empty:xt?e.jsx(be,{icon:e.jsx(xe,{className:"w-12 h-12 text-app-gray300"}),title:"No records match",description:"Try another search, or clear the filters."}):e.jsx(be,{icon:e.jsx(xe,{className:"w-12 h-12 text-app-gray300"}),title:"No records yet",description:"Your columns are ready. Add a record and it fills a row here.",action:e.jsx($,{onClick:()=>n(!0),children:"Add Record"})})})]}),!Ae&&!Ie&&((Dt=B==null?void 0:B.dataRecords)==null?void 0:Dt.edges)&&B.dataRecords.edges.length>0&&e.jsxs("div",{className:"flex items-center justify-between px-6 pt-3 pb-16 border-t border-border shrink-0",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Showing ",B.dataRecords.edges.length," of"," ",B.dataRecords.totalCount," records"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"ghost",onClick:ra,disabled:q.length===0,children:[e.jsx(Cr,{className:"w-4 h-4 mr-1"}),"Previous"]}),e.jsxs($,{variant:"ghost",onClick:aa,disabled:!B.dataRecords.pageInfo.hasNextPage,children:["Next",e.jsx(Ka,{className:"w-4 h-4 ml-1"})]})]})]}),e.jsx(kn,{showModal:r,setShowModal:n,onCreateRecord:na,isLoading:Us,tableFields:(_==null?void 0:_.fields)||[]}),e.jsx(Rn,{showModal:p,setShowModal:l,onCreateField:oa,onOpenRelationshipModal:()=>{l(!1),o(!0)},existingFields:(_==null?void 0:_.fields)||[],fieldCounts:_==null?void 0:_.fieldCounts,isLoading:pt}),e.jsx(On,{showModal:u,setShowModal:o,currentTable:N!=null&&N.dataTable?{id:N.dataTable.id,key:N.dataTable.key,name:N.dataTable.name}:{id:"",key:"",name:""},tables:(we==null?void 0:we.dataTables)||[],onCreateRelationship:ia,existingFields:(_==null?void 0:_.fields)||[],fieldCounts:_==null?void 0:_.fieldCounts,isLoading:pt}),e.jsx(Bn,{showModal:i,setShowModal:c,field:C,onUpdateField:ca,isLoading:Qs}),e.jsx(qn,{showModal:b,setShowModal:m=>{j(m),m||R(null)},field:C,onConfirmDelete:ua,isLoading:Js}),e.jsx(Wn,{showModal:w!==null,setShowModal:m=>{(typeof m=="function"?m(!0):m)||v(null)},fields:(_==null?void 0:_.fields)||[],recordCount:(_==null?void 0:_.recordCount)??0,selectedCount:w==="selected"?y:0,isLoading:zs,onConfirm:la}),e.jsx(fn,{showModal:E,setShowModal:h,count:y,onConfirmDelete:da,isLoading:Vs})]})}),e.jsx(Re,{className:O("flex-col h-full overflow-hidden transition-all",a?"flex w-full md:w-[440px] md:min-w-[440px]":"hidden md:flex md:w-0 md:min-w-0 md:border-none"),children:e.jsx(Ra,{context:ha})})]})},cd="flex h-full w-full items-start gap-2.5 rounded-lg border border-border bg-background px-3 py-2 text-left shadow-sm transition-colors cursor-pointer hover:border-app-blue300 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring",ud="border-app-blue400 bg-app-blue50 hover:border-app-blue400",Qt=({label:t,description:a,selected:s,onClick:d})=>e.jsxs("button",{type:"button",role:"radio","aria-checked":s,onClick:d,className:O(cd,s&&ud),children:[e.jsx("span",{"aria-hidden":!0,className:O("mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full border",s?"border-app-blue400 bg-app-blue400 text-white":"border-app-gray300 bg-background"),children:s&&e.jsx(ms,{className:"size-3"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-body-sm font-bold text-foreground",children:t}),e.jsx("span",{className:"block text-utility-md text-muted-foreground",children:a})]})]}),md=t=>Object.entries(t).map(([a,s])=>({value:a,label:s})),pd=[{key:"createRule",label:"Create",labels:tn},{key:"readRule",label:"Read",labels:Ze},{key:"updateRule",label:"Update",labels:Ze},{key:"deleteRule",label:"Delete",labels:Ze}],Is=({rules:t,onChange:a})=>
1048{const s=Qe(t),[d,r]=x.useState(s==="custom"),n=d||s==="custom",p=l=>{r(!1),a(l.rules)};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{role:"radiogroup","aria-label":"Who can do what",className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:[it.map(l=>e.jsx(Qt,{label:l.label,description:l.description,selected:!n&&s===l.id,onClick:()=>p(l)},l.id)),e.jsx(Qt,{label:"Custom",description:"Choose each rule yourself.",selected:n,onClick:()=>r(!0)})]}),n&&e.jsx("div",{className:"grid grid-cols-2 gap-3 rounded-lg border border-border bg-muted/40 p-3",children:pd.map(({key:l,label:u,labels:o})=>{const i=md(o);return e.jsxs("div",{children:[e.jsx(K,{htmlFor:l,text:u}),e.jsx(dt,{name:l,inputId:l,value:i.find(c=>c.value===t[l]),onChange:c=>c&&a({...t,[l]:c.value}),options:i})]},l)})}),t.readRule==="PUBLIC"&&e.jsx("p",{className:"text-utility-md text-muted-foreground",children:"Anyone on the internet can read this table, with or without an account. That is right for content you publish. Pick another option for anything private."}),(t.createRule==="PUBLIC"||t.updateRule==="PUBLIC"||t.deleteRule==="PUBLIC")&&e.jsx("p",{className:"text-utility-md text-app-red500",children:"Anyone can change this table without logging in. Only choose this if you are sure."})]})},xd=async(t,{createTable:a,createField:s,name:d=t.name,key:r=t.key,rules:n})=>{const p=await a({name:d,key:r,...n}),l=[];for(const[u,o]of t.fields.entries())try{await s({tableId:p.id,key:o.key,name:o.name,type:o.type,required:o.required??!1,defaultValue:o.defaultValue,tableOrder:u+1}),l.push(o.key)}catch(i){return{tableId:p.id,tableKey:r,createdFieldKeys:l,failedField:{key:o.key,name:o.name,error:i}}}return{tableId:p.id,tableKey:r,createdFieldKeys:l}},Gt=(t,a)=>{const s=new Set(a);if(!s.has(t))return t;for(let d=2;d<1e3;d+=1){const r=`_${d}`,n=`${t.slice(0,64-r.length)}${r}`;if(!s.has(n))return n}throw new Error(`Could not find a free key for ${t}`)},Os=[{id:"blog_posts",name:"Blog Posts",key:"blog_posts",description:"Articles with an author, a publish date and a draft switch.",presetId:"content_site",fields:[{key:"title",name:"Title",type:k.Text,required:!0},{key:"slug",name:"Slug",type:k.TextUnique,required:!0},{key:"content",name:"Content",type:k.Text,required:!0},{key:"excerpt",name:"Excerpt",type:k.Text},{key:"category",name:"Category",type:k.TextFilterable},{key:"cover_image_url",name:"Cover image URL",type:k.Url},{key:"published",name:"Published",type:k.Boolean,defaultValue:!1},{key:"published_at",name:"Published at",type:k.Date},{key:"author",name:"Author",type:k.MemberReference}]},{id:"product_catalog",name:"Product Catalog",key:"products",description:"Items with a price, a category and a stock switch.",presetId:"content_site",fields:[{key:"name",name:"Name",type:k.Text,required:!0},{key:"slug",name:"Slug",type:k.TextUnique,required:!0},{key:"description",name:"Description",type:k.Text},{key:"price",name:"Price",type:k.Decimal,required:!0},{key:"category",name:"Category",type:k.TextFilterable},{key:"image_url",name:"Image URL",type:k.Url},{key:"in_stock",name:"In stock",type:k.Boolean,defaultValue:!0}]},{id:"bookings",name:"Bookings",key:"bookings",description:"Time slots members book and only they can see.",presetId:"members_own",fields:[{key:"starts_at",name:"Starts at",type:k.Date,required:!0},{key:"ends_at",name:"Ends at",type:k.Date},{key:"service",name:"Service",type:k.TextFilterable},{key:"status",name:"Status",type:k.TextFilterable,defaultValue:"requested"},{key:"notes",name:"Notes",type:k.Text}]},{id:"member_profiles",name:"Member Directory",key:"profiles",description:"A public profile each member fills in and can edit.",presetId:"shared_by_members",fields:[{key:"display_name",name:"Display name",type:k.Text,required:!0},{key:"headline",name:"Headline",type:k.Text},{key:"bio",name:"Bio",type:k.Text},{key:"location",name:"Location",type:k.TextFilterable},{key:"website",name:"Website",type:k.Url},{key:"avatar_url",name:"Avatar URL",type:k.Url},{key:"is_public",name:"Show in directory",type:k.Boolean,defaultValue:!1}]},{id:"job_board",name:"Job Board",key:"jobs",description:"Job listings with a location, a salary range and an apply link.",presetId:"content_site",fields:[{key:"title",name:"Title",type:k.Text,required:!0},{key:"slug",name:"Slug",type:k.TextUnique,required:!0},{key:"company",name:"Company",type:k.Text,required:!0},{key:"location",name:"Location",type:k.TextFilterable},{key:"job_type",name:"Job type",type:k.TextFilterable},{key:"description",name:"Description",type:k.Text},{key:"salary_min",name:"Salary min",type:k.Number},{key:"salary_max",name:"Salary max",type:k.Number},{key:"apply_url",name:"Apply URL",type:k.Url},{key:"is_open",name:"Open",type:k.Boolean,defaultValue:!0}]},{id:"events",name:"Events",key:"events",description:"Upcoming events with a date, a place and a signup link.",presetId:"content_site",fields:[{key:"title",name:"Title",type:k.Text,required:!0},{key:"slug",name:"Slug",type:k.TextUnique,required:!0},{key:"description",name:"Description",type:k.Text},{key:"starts_at",name:"Starts at",type:k.Date,required:!0},{key:"ends_at",name:"Ends at",type:k.Date},{key:"location",name:"Location",type:k.TextFilterable},{key:"signup_url",name:"Signup URL",type:k.Url},{key:"is_published",name:"Published",type:k.Boolean,defaultValue:!1}]}],Jt=t=>Os.find(a=>a.id===t),Ye="blank",hd="group text-left rounded-lg border border-border bg-background p-3 shadow-sm transition-colors cursor-pointer hover:border-app-blue300 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring",gd="border-app-blue400 bg-app-blue50 hover:border-app-blue400",Ht=({id:t,name:a,description:s,meta:d,selected:r,onSelect:n,icon:p})=>e.jsxs("button",{type:"button",role:"radio","aria-checked":r,onClick:()=>n(t),className:O(hd,r&&gd),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-body-sm font-bold text-foreground",children:[p,a]}
1048),e.jsx(ms,{"aria-hidden":!0,className:O("size-4 shrink-0 text-app-blue400",r?"opacity-100":"opacity-0")})]}),e.jsx("p",{className:"mt-1 text-utility-md text-muted-foreground",children:s}),e.jsx("p",{className:"mt-2 text-utility-sm text-muted-foreground",children:d})]}),qs=({selected:t,onSelect:a,hideBlank:s=!1,className:d})=>e.jsxs("div",{role:"radiogroup","aria-label":"Starting point",className:O("grid grid-cols-1 gap-3 sm:grid-cols-2",d),children:[Os.map(r=>e.jsx(Ht,{id:r.id,name:r.name,description:r.description,meta:`${r.fields.length} fields, ready to use`,selected:t===r.id,onSelect:a},r.id)),!s&&e.jsx(Ht,{id:Ye,name:"Blank table",description:"Start from nothing and add your own fields.",meta:"No fields yet",selected:t===Ye,onSelect:a,icon:e.jsx(Br,{"aria-hidden":!0,className:"size-4 text-muted-foreground"})})]}),bd=[],fd=t=>t.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").substring(0,64),yd=({showModal:t,setShowModal:a,onCreateTable:s,isLoading:d=!1,existingKeys:r=bd,initialTemplateId:n=null})=>{const[p,l]=x.useState("pick"),[u,o]=x.useState(null),[i,c]=x.useState(""),[b,j]=x.useState(""),[C,R]=x.useState(!1),[f,g]=x.useState(!1),[E,h]=x.useState(Te(tt).rules),w=x.useMemo(()=>u&&u!==Ye?Jt(u):void 0,[u]),v=()=>{l("pick"),o(null),c(""),j(""),R(!1),g(!1),h(Te(tt).rules)},A=x.useCallback(D=>{o(D);const U=D===Ye?void 0:Jt(D);if(U){const Q=Gt(U.key,r),oe=Q.slice(U.key.length).replace("_"," ");c(`${U.name}${oe}`),j(Q),h(Te(U.presetId).rules)}else c(""),j(""),h(Te(tt).rules);R(!1),l("details")},[r]),y=x.useRef(!1);x.useEffect(()=>{if(!t){y.current=!1;return}n&&!y.current&&(y.current=!0,A(n))},[t,n,A]);const Y=D=>{const U=D.target.value;if(c(U),!C){const Q=fd(U);j(Q?Gt(Q,r):"")}},ne=D=>{R(!0),j(D.target.value)},q=(()=>{if(!b)return $t(b);const D=$t(b);return D||(!d&&r.includes(b)?"A table with this key already exists":null)})(),X=i.trim().length===0?"Table name is required":i.length>100?"Table name must be less than 100 characters":null,me=p==="details"&&!X&&!q,J=()=>{v(),a(!1)},H=()=>{me&&s({name:i.trim(),key:b,...E,template:w})},T=w?`Create table with ${w.fields.length} fields`:"Create table";return e.jsx(pe,{showModal:t,setShowModal:a,title:p==="pick"?"New table":w?w.name:"New table",description:p==="pick"?"Pick a starting point. You can change every field after.":void 0,showDivider:!0,width:"640px",onModalClose:J,actionButtons:p==="pick"?{cancel:{label:"Cancel"}}:{confirm:{label:T,onConfirm:H,isDisabled:!me,isLoading:d},cancel:{label:"Back",onClick:()=>l("pick")}},children:t?p==="pick"?e.jsx(qs,{selected:u,onSelect:A}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(K,{htmlFor:"name",text:"Table name"}),e.jsx(ae,{id:"name",name:"name",value:i,onChange:Y,placeholder:"e.g. Team notes",errorMessage:i&&X?X:void 0}),b&&e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-x-2 text-utility-md text-muted-foreground",children:[e.jsxs("span",{children:["Key: ",e.jsx("code",{className:"font-mono text-foreground",children:b})]}),e.jsx("button",{type:"button",className:"text-app-blue400 underline-offset-2 hover:underline",onClick:()=>g(D=>!D),children:f?"Hide":"Edit key"})]}),f&&e.jsxs("div",{className:"mt-2",children:[e.jsx(K,{htmlFor:"key",text:"Table key"}),e.jsx(ae,{id:"key",name:"key",value:b,onChange:ne,placeholder:"table_key",errorMessage:q??void 0,description:"Used in code to refer to this table. Letters, numbers and underscores only."})]}),!f&&q&&b&&e.jsx("p",{className:"mt-1 text-utility-md text-app-red500",children:q})]}),w&&e.jsxs("div",{children:[e.jsxs("p",{className:"mb-1.5 text-body-sm font-bold text-foreground",children:["Fields this will create"," ",e.jsx("span",{className:"font-normal text-muted-foreground",children:"(* required)"})]}),e.jsx("ul",{className:"grid grid-cols-1 gap-x-4 rounded-lg border border-border px-3 py-1 text-utility-md sm:grid-cols-2",children:w.fields.map(D=>e.jsxs("li",{className:"flex min-w-0 items-center gap-2 py-1",children:[e.jsxs("span",{className:"min-w-0 flex-1 truncate text-foreground",children:[D.name,D.required&&e.jsxs("span",{className:"text-muted-foreground",title:"Required",children:[" ","*"]})]}),e.jsx("span",{className:"shrink-0 text-utility-sm text-muted-foreground",children:We[D.t
1048ype]})]},D.key))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-body-sm font-bold text-foreground",children:"Who can do what"}),e.jsx(Is,{rules:E,onChange:h})]})]}):null})},jd=({showModal:t,setShowModal:a,onConfirmDelete:s,table:d,isLoading:r=!1})=>{const[n,p]=x.useState("");if(x.useEffect(()=>{t&&p("")},[t]),!d)return null;const l=d.key,u=d.fields.length,o=d.recordCount>0?`${lt(d.recordCount)} and ${u} field${u===1?"":"s"}`:u>0?`${u} field${u===1?"":"s"} and no records`:"no fields and no records";return e.jsx(pe,{showModal:t,setShowModal:a,title:`Delete ${d.name}`,description:"This cannot be undone.",showDivider:!0,width:"500px",actionButtons:{confirm:{label:"Delete table",onConfirm:s,isLoading:r,isDisabled:n!==l,variant:"danger"},cancel:{label:"Cancel"}},children:t&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-body-sm text-foreground",children:["This deletes the table, its ",o,". Any code on your site that reads ",e.jsx("code",{className:"font-mono",children:d.key})," will stop working."]}),e.jsxs("div",{children:[e.jsxs("p",{className:"mb-1 text-body-sm text-foreground",children:["Type ",e.jsx(Mr,{text:l})," to confirm."]}),e.jsx(ae,{id:"delete-table-confirm",name:"delete-table-confirm",value:n,onChange:i=>p(i.target.value),hideIndicators:!0,placeholder:l,"aria-label":"Type the table key to confirm"})]})]})})},Nd=t=>{const a=Qe({createRule:t.createRule,readRule:t.readRule,updateRule:t.updateRule,deleteRule:t.deleteRule});return a==="custom"?"Custom access":Te(a).label},Ed=({table:t,onViewTable:a,onUpdateTable:s,onDeleteTable:d})=>e.jsxs(ps,{className:"group relative p-5 transition-shadow duration-200 hover:shadow-lg",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-app-blue50 p-2.5",children:e.jsx(xe,{className:"size-5 text-app-blue600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"truncate text-lg font-semibold leading-tight text-foreground",children:e.jsx("button",{type:"button",onClick:()=>a(t),className:"text-left after:absolute after:inset-0 after:rounded-[inherit] focus-visible:outline-none focus-visible:after:outline-2 focus-visible:after:outline-ring",children:t.name})}),e.jsx("p",{className:"mt-0.5 truncate font-mono text-xs text-muted-foreground",children:t.key})]})]}),e.jsxs("div",{className:"relative z-10 flex shrink-0 items-center gap-1",children:[e.jsx($,{variant:"ghost",onClick:()=>s(t),"aria-label":`Edit ${t.name}`,className:"rounded-lg p-2 hover:bg-muted",children:e.jsx(za,{className:"size-4 text-muted-foreground"})}),e.jsx($,{variant:"ghost",onClick:()=>d(t),"aria-label":`Delete ${t.name}`,className:"rounded-lg p-2 text-muted-foreground hover:bg-app-red50 hover:text-app-red500",children:e.jsx(ns,{className:"size-4"})})]})]}),e.jsxs("dl",{className:"mt-4 space-y-1.5 text-body-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("dt",{className:"sr-only",children:"Size"}),e.jsxs("dd",{children:[e.jsx("span",{className:"font-semibold text-foreground",children:lt(t.recordCount)})," · ",an(t.fields.length)]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(js,{"aria-hidden":!0,className:"size-3.5 shrink-0"}),e.jsx("dt",{className:"sr-only",children:"Access"}),e.jsx("dd",{className:"truncate",children:Nd(t)})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("dt",{className:"sr-only",children:"Created"}),e.jsxs("dd",{className:"text-utility-sm",children:["Created ",Se(t.createdAt,"MMM dd, yyyy")]})]})]})]}),Zt=t=>({createRule:(t==null?void 0:t.createRule)??"AUTHENTICATED",readRule:(t==null?void 0:t.readRule)??"PUBLIC",updateRule:(t==null?void 0:t.updateRule)??"AUTHENTICATED_OWN",deleteRule:(t==null?void 0:t.deleteRule)??"ADMIN_ONLY"}),vd=({showModal:t,setShowModal:a,table:s,onUpdateTable:d,isLoading:r=!1})=>{const[n,p]=x.useState((s==null?void 0:s.name)??""),[l,u]=x.useState(()=>Zt(s));x.useEffect(()=>{p((s==null?void 0:s.name)??""),u(Zt(s))},[s]);const o=n.trim().length===0?"Table name is required":n.length>100?"Table name must be less than 100 characters":null,i=()=>{!s||o||d({id:s.id,name:n.trim(),...l})};return e.jsx(pe,{showModal:t,setShowModal:a,title:"Edit table",showDivider:!0,width:"640px",actionButtons:{confirm:{label:"Save changes",onConfirm:i,isDisabled:!!o,isLoading:r},cancel:{label:"Cancel"}},children:t&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(K,{htmlFor:"name",text:"Table name"}),e.jsx(ae,{id:"name",name:"name",value:n,onChange:c=>p(c.target.value),errorMessage:n&&o?o:void 0}),e.jsxs("p",{className:"mt-1.5 text-utility-md text-muted-foreground",children:["Key:"," ",e.jsx("code",{className:"font-mono text-foreground",children:s==null?void 0:s.key}),". The key cannot change, because code on your site refers to it."]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-body-sm font-bold text-foreground",children:"Who can do what"}),e.jsx(Is,{rules:l,onChange:u},s==null?void 0:s.id)]})]})})},Rd=6,wd=()=>e.jsxs(ps,{className:"p-5",children:[e.jsxs("div",{className:"mb-5 flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(P,{width:40,height:40,borderRadius:12}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(P,{width:140,height:20}),e.jsx(P,{width:90,height:14})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(P,{width:32,height:32,borderRadius:8}),e.jsx(P,{width:32,height:32,borderRadius:8})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-4",children:[e.jsx(P,{height:56,borderRadius:8}),e.jsx(P,{height:56,borderRadius:8})]}),e.jsx("div",{className:"mb-4",children:e.jsx(P,{width:110,height:16})}),e.jsxs("div",{className:"pt-3 border-t border-border space-y-2",children:[e.jsx(P,{width:160,height:14}),e.jsx(P,{height:32,borderRadius:8})]})]}),kd=()=>e.jsx("div",{className:"flex h-full overflow-hidden",children:e.jsx(Re,{className:"w-full",children:e.jsxs("div",{className:"p-6 h-full w-full overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx(P,{width:180,height:32}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(P,{width:150,height:36,borderRadius:8}),e.jsx(P,{width:140,height:36,borderRadius:8})]})]}),e.jsx("div",{className:"mb-6",children:e.jsx(P,{height:40,borderRadius:8})}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 items-start",children:Array.from({length:Rd}).map((t,a)=>e.jsx(wd,{},`table-card-skeleton-${a}`))})]})})}),Cd=({onTableSelect:t})=>
1048{const[a,s]=x.useState(""),[d,r]=x.useState(!1),[n,p]=x.useState(null),[l,u]=x.useState(!1),[o,i]=x.useState(!1),[c,b]=x.useState(null),{appId:j}=qe(),C=`/apps/${j}/data-tables/docs`,{createToastAlert:R}=Le(),{env:f}=cs(),g=x.useRef(f),E=Wa(),{data:h,loading:w,error:v,refetch:A}=fs({fetchPolicy:"cache-and-network",nextFetchPolicy:"cache-first",notifyOnNetworkStatusChange:!0}),[y,{loading:Y}]=dr({refetchQueries:["GET_DATA_TABLES"],awaitRefetchQueries:!0}),[ne,{loading:q}]=ys(),[X,{loading:me}]=lr({refetchQueries:["GET_DATA_TABLES"],awaitRefetchQueries:!0}),[J,{loading:H}]=or({refetchQueries:["GET_DATA_TABLES"],awaitRefetchQueries:!0});x.useEffect(()=>{f!==g.current&&(A(),g.current=f)},[f,A]),x.useEffect(()=>{A()},[]);const T=x.useMemo(()=>{const F=(h==null?void 0:h.dataTables)||[];if(!a.trim())return F;const de=a.toLowerCase();return F.filter(ye=>ye.name.toLowerCase().includes(de)||ye.key.toLowerCase().includes(de))},[h==null?void 0:h.dataTables,a]),D=async F=>{const{name:de,key:ye,template:Fe,...Z}=F,Ee=Qe(Z);try{if(!Fe){if(!(await y({variables:{input:{name:de,key:ye,...Z}}})).data)throw new Error("Failed to create table");E(qt.DataTableCreated,{template:"blank",field_count:0,preset:Ee,partial:!1}),R({message:"Table created. Add a field to start storing data.",alertType:"success"}),te(),t==null||t(ye);return}const le=await xd(Fe,{name:de,key:ye,rules:Z,createTable:async N=>{var re,we;const ve=(we=(re=(await y({variables:{input:N}})).data)==null?void 0:re.createDataTable)==null?void 0:we.id;if(!ve)throw new Error("Failed to create table");return{id:ve}},createField:async N=>{await ne({variables:{input:N}})}});if(E(qt.DataTableCreated,{template:Fe.id,field_count:le.createdFieldKeys.length,preset:Ee,partial:!!le.failedField}),le.failedField){const N=le.failedField.error instanceof Error?le.failedField.error.message:"unknown error";R({message:`Table created, but the "${le.failedField.name}" field could not be added (${N}). Add it from the Fields menu.`,alertType:"error"})}else R({message:`Table created with ${le.createdFieldKeys.length} fields. Add a record to see it in action.`,alertType:"success"});te(),t==null||t(le.tableKey)}catch(le){R({message:le.message||"Failed to create table",alertType:"error"})}},U=async F=>{try{(await X({variables:{input:{id:F.id,name:F.name,createRule:F.createRule,readRule:F.readRule,updateRule:F.updateRule,deleteRule:F.deleteRule}}})).data&&(R({message:"Table updated successfully",alertType:"success"}),u(!1),b(null),A())}catch(de){R({message:de.message||"Failed to update table",alertType:"error"})}},Q=async()=>{if(c)try{(await J({variables:{input:{id:c.id}}})).data&&(R({message:"Table deleted successfully",alertType:"success"}),i(!1),b(null),A())}catch(F){R({message:F.message||"Failed to delete table",alertType:"error"})}},oe=F=>{t&&t(F.key)},ie=F=>{b(F),u(!0)},G=F=>{b(F),i(!0)},fe=()=>{p(null),r(!0)},S=F=>{p(F),r(!0)},te=()=>{r(!1),p(null)},z=x.useMemo(()=>((h==null?void 0:h.dataTables)||[]).map(F=>F.key),[h==null?void 0:h.dataTables]),ge=z.length>0;return x.useEffect(()=>{ge||s("")},[ge]),w&&!h?e.jsx(kd,{}):v?e.jsx("div",{className:"flex h-full overflow-hidden",children:e.jsx(Re,{className:"w-full",children:e.jsxs("div",{className:"p-6 h-full overflow-y-auto",children:[e.jsx("div",{className:"flex items-center gap-3 mb-6",children:e.jsx("h3",{className:"text-h3 font-bold text-foreground",children:"Data Tables"})}),e.jsx(be,{icon:e.jsx(xe,{className:"w-12 h-12 text-red-400"}),title:"Failed to load data tables",description:v.message||"There was an error loading your data tables. Please try again.",action:e.jsx($,{onClick:()=>A(),children:"Try Again"})})]})})}):e.jsxs("div",{className:"flex h-full overflow-hidden",children:[e.jsxs(Re,{className:"w-full flex flex-col",children:[e.jsxs("div",{className:"px-6 pt-6 grow-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsx("h3",{className:"text-h3 font-bold text-foreground",children:"Data Tables"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"skeleton",onClick:()=>window.open(C,"_blank"),children:[e.jsx(Qa,{className:"size-4"}),"Documentation"]}),e.jsxs($,{onClick:fe,children:[e.jsx(Ga,{className:"size-4"}),"Create Table"]})]})]}),ge&&e.jsx("div",{className:"mb-6",children:e.jsx(us,{value:a,onChange:s,placeholder:"Search tables by name or key..."})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-6 pb-6",children:T.length===0?ge&&a?e.jsx(be,{icon:e.jsx(xe,{className:"w-12 h-12 text-app-gray400"}),title:"No tables found",description:"Try adjusting your search criteria"}):e.jsxs("div",{className:"flex flex-col gap-8",children:[e.jsx(be,{isFullScreen:!0,className:"flex-none",contentClassName:"max-w-[371px]",title:"Give your app a database",description:"A hosted database built right into Memberstack. Store the data your site runs on, like user generated blog posts, product catalogs, or bookings, with no backend to set up and no servers to manage.",bullets:["Store posts, products, bookings, or anything else","Link records to members so the data has an owner","Set rules for who can read and edit each table"],buttonText:"Create Table",onCreateClick:fe,docsLink:C,docsLinkText:"Learn More",svgImage:e.jsx(Tr,{})}),e.jsxs("div",{className:"px-12",children:[e.jsx("p",{className:"mb-3 text-base font-bold text-foreground",children:"Or start from a template"}),e.jsx(qs,{selected:null,onSelect:S,hideBlank:!0,className:"lg:grid-cols-3"})]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 items-start",children:T.map(F=>e.jsx(Ed,{table:F,onViewTable:oe,onUpdateTable:ie,onDeleteTable:G},F.id))})})]}),e.jsx(yd,{showModal:d,setShowModal:F=>{(typeof F=="function"?F(d):F)?r(!0):te()},onCreateTable:D,isLoading:Y||q,existingKeys:z,initialTemplateId:n}),e.jsx(vd,{showModal:l,setShowModal:F=>{u(F),F||b(null)},table:c,onUpdateTable:U,isLoading:me}),e.jsx(jd,{showModal:o,setShowModal:F=>{i(F),F||b(null)},onConfirmDelete:Q,table:c,isLoading:H})]})},dl=()=>{const t=rt(),{appId:a}=qe(),s=d=>{t(d)};return e.jsxs(wa,{children:[e.jsx(Pe,{index:!0,element:e.jsx(Cd,{onTableSelect:s})}),e.jsx(Pe,{path:"docs",element:e.jsx(Xr,{onClose:()=>t(`/apps/${a}/data-tables`)})}),e.jsx(Pe,{path:":tableKey",element:e.jsx(id,{}),children:e.jsx(Pe,{path:":recordId",element:e.jsx(bn,{})})})]})};export{dl as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.