@objectstack/console 12.5.0 → 13.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/.objectui-sha +1 -1
  2. package/dist/assets/{AdapterProvider-qwVfmAEk.js → AdapterProvider-G7o889LL.js} +1 -1
  3. package/dist/assets/{AiPendingActionsPage-BRZ9smBE.js → AiPendingActionsPage-B_bQ89Ap.js} +1 -1
  4. package/dist/assets/{ApiConsolePage-V6XcLsX4.js → ApiConsolePage-oJexbnMd.js} +1 -1
  5. package/dist/assets/{AppDocsIndex-C4IIeN6V.js → AppDocsIndex-B2EMS--S.js} +1 -1
  6. package/dist/assets/{AppManagementPage-WCLo2V17.js → AppManagementPage-BSLRnX7p.js} +1 -1
  7. package/dist/assets/{ApprovalsInboxPage-Cm6RlF50.js → ApprovalsInboxPage-DbdgZkz_.js} +1 -1
  8. package/dist/assets/{AuditLogPage-BUapxa-t.js → AuditLogPage-JHBVKm-o.js} +1 -1
  9. package/dist/assets/{ComponentNavView-CV-L0t8o.js → ComponentNavView-Be3JMpLK.js} +1 -1
  10. package/dist/assets/ConsoleFloatingChatbot-MtFbTLoq.js +1 -0
  11. package/dist/assets/{CreateViewDialog-CMNLzv6j.js → CreateViewDialog-CboUdp-q.js} +1 -1
  12. package/dist/assets/DashboardView-1nXwC0y_.js +1 -0
  13. package/dist/assets/{DeveloperHubPage-CigDAiDQ.js → DeveloperHubPage-B55QdK7b.js} +1 -1
  14. package/dist/assets/{ExpressionProvider-ODpzkcN3.js → ExpressionProvider-B3pkCzAo.js} +1 -1
  15. package/dist/assets/{FlowRunsPage-QMVLQvu7.js → FlowRunsPage-CKOKC3O1.js} +1 -1
  16. package/dist/assets/{IntegrationsPage-D8453O8m.js → IntegrationsPage-gLs4Ms2t.js} +1 -1
  17. package/dist/assets/{InterfaceListPage-Dbt7lZbl.js → InterfaceListPage-CwGb2Th3.js} +1 -1
  18. package/dist/assets/{ManagedByBadge-BGSB7vGi.js → ManagedByBadge-BtJfBjbT.js} +1 -1
  19. package/dist/assets/{MarketplaceAccessDenied-CAuxNcMw.js → MarketplaceAccessDenied-Bl4faFLm.js} +1 -1
  20. package/dist/assets/{MarketplaceInstalledPage-DIKAvmEt.js → MarketplaceInstalledPage-BQH-qEi5.js} +1 -1
  21. package/dist/assets/{MarketplacePackagePage-CiRyU-vK.js → MarketplacePackagePage-B2BXohna.js} +2 -2
  22. package/dist/assets/{MarketplacePage-SkUEdd3B.js → MarketplacePage-C_HnQQYH.js} +1 -1
  23. package/dist/assets/{MetadataInspector-RvnQ-QOT.js → MetadataInspector-DwPx9ueN.js} +1 -1
  24. package/dist/assets/{MetadataProvider-DKJsxrNu.js → MetadataProvider-seOmvY8N.js} +1 -1
  25. package/dist/assets/{ObjectDataPage-CAJf6Pu3.js → ObjectDataPage-D8W0OzJe.js} +1 -1
  26. package/dist/assets/PageView-cehnKJ9R.js +1 -0
  27. package/dist/assets/{ProfilePage-7etuxYZk.js → ProfilePage-CPk5ilAm.js} +1 -1
  28. package/dist/assets/{PublicFormsPage-DmpEEcq4.js → PublicFormsPage-5oWNwPiZ.js} +1 -1
  29. package/dist/assets/RecordDetailView-CUcCVoa1.js +9 -0
  30. package/dist/assets/{RecordFormPage-DadWkJyX.js → RecordFormPage-Dmw4MMhg.js} +1 -1
  31. package/dist/assets/ReportDefaultInspector-BBTLmEl-.js +11 -0
  32. package/dist/assets/ReportView-BPkQVP9-.js +2 -0
  33. package/dist/assets/SearchResultsPage-quEMr1ZW.js +1 -0
  34. package/dist/assets/{SettingsHub-ZMQjBQwP.js → SettingsHub-B5Y0DjDk.js} +1 -1
  35. package/dist/assets/{SettingsView-eCnpX1vu.js → SettingsView-Q3e7GG0S.js} +1 -1
  36. package/dist/assets/{SystemHubPage-2aGKeHcn.js → SystemHubPage-SIzLdDrE.js} +1 -1
  37. package/dist/assets/appRoute-1sYdkwBz.js +1 -0
  38. package/dist/assets/conversationLanguage-CgUPnufx.js +1 -0
  39. package/dist/assets/data-adapter-BP-pyfs8.js +7 -0
  40. package/dist/assets/{framework-B3O15Lsq.js → framework-CBCX6Urh.js} +8 -8
  41. package/dist/assets/{getIcon-B5xaQx5N.js → getIcon-Ci4w4xXM.js} +1 -1
  42. package/dist/assets/{highlighted-body-OFNGDK62-B_roNkgm.js → highlighted-body-OFNGDK62-B5Pqh6xJ.js} +1 -1
  43. package/dist/assets/index-Df624lGg.js +2 -0
  44. package/dist/assets/{index-BXgUF5nO.css → index-GDbpsyLD.css} +1 -1
  45. package/dist/assets/{infrastructure-Bcx6-8du.js → infrastructure-ASGyCRMg.js} +1 -1
  46. package/dist/assets/marketplaceApi-N63OOXW-.js +1 -0
  47. package/dist/assets/mermaid-GHXKKRXX-BlWXnAVk.js +1 -0
  48. package/dist/assets/metadata-admin-Jkl-QChK.js +23 -0
  49. package/dist/assets/{plugin-calendar-BKbWgkod.js → plugin-calendar-BHRBKeJq.js} +1 -1
  50. package/dist/assets/{plugin-charts-BZo5ApEF.js → plugin-charts-DyKYgW3L.js} +1 -1
  51. package/dist/assets/plugin-chatbot-CNLp4fGv.js +120 -0
  52. package/dist/assets/{plugin-dashboard-CRFZp7gC.js → plugin-dashboard-uOZwquef.js} +1 -1
  53. package/dist/assets/plugin-form-CX8z6nsj.js +1 -0
  54. package/dist/assets/{plugin-gantt-D9YRdBGD.js → plugin-gantt-CyktuI6d.js} +1 -1
  55. package/dist/assets/{plugin-grid-eiIl2HN_.js → plugin-grid-DNGRZzGM.js} +1 -1
  56. package/dist/assets/{plugin-kanban-3rFMGC21.js → plugin-kanban-B0Dwrpca.js} +1 -1
  57. package/dist/assets/{plugin-map-BHQrQ_Wu.js → plugin-map-Co_pYpOZ.js} +1 -1
  58. package/dist/assets/{plugin-markdown-DesFSRDB.js → plugin-markdown-CS5R-t3i.js} +1 -1
  59. package/dist/assets/{plugin-report-BKD6SOp5.js → plugin-report-_y8nt0FZ.js} +1 -1
  60. package/dist/assets/{plugin-timeline-BrkABjqu.js → plugin-timeline-Cy03-xov.js} +1 -1
  61. package/dist/assets/{plugin-tree-CKck3lEJ.js → plugin-tree-DCAEE54g.js} +1 -1
  62. package/dist/assets/plugin-view-OZpEPOgT.js +1 -0
  63. package/dist/assets/plugins-views-BVxwkRdi.js +4 -0
  64. package/dist/assets/{skeletons-CzC0fiXD.js → skeletons-BjaBYe9k.js} +1 -1
  65. package/dist/assets/{src-BeTFx9-N.js → src-D6ENIa3w.js} +1 -1
  66. package/dist/assets/src-rXeXV_HX.js +16 -0
  67. package/dist/assets/{types-UYoEctl-.js → types-DXCQOIiO.js} +1 -1
  68. package/dist/assets/{ui-components-rkvkkTxO.js → ui-components-BOOpjWsQ.js} +9 -9
  69. package/dist/assets/{ui-layout-CAjjF5_S.js → ui-layout-vWAZODrs.js} +1 -1
  70. package/dist/assets/{useMetadata-Ily0JuNR.js → useMetadata-D-bLZoNN.js} +1 -1
  71. package/dist/assets/useOpenRecordList-B3tjtz1e.js +1 -0
  72. package/dist/assets/{useRecordApprovals-obyIj2_8.js → useRecordApprovals-jo_LH43z.js} +1 -1
  73. package/dist/assets/vendor-objectstack-Jcqd9154.js +108 -0
  74. package/dist/index.html +4 -4
  75. package/package.json +1 -1
  76. package/dist/assets/ConsoleFloatingChatbot-mf-pVd3G.js +0 -1
  77. package/dist/assets/DashboardView-CPFt6TBZ.js +0 -1
  78. package/dist/assets/DashboardWidgetInspector-DknOds9r.js +0 -1
  79. package/dist/assets/PageView-GYrk78oW.js +0 -1
  80. package/dist/assets/RecordDetailView-CzR6BAUv.js +0 -9
  81. package/dist/assets/ReportDefaultInspector-CJGXWwWN.js +0 -11
  82. package/dist/assets/ReportView-CIZjxMSJ.js +0 -2
  83. package/dist/assets/SearchResultsPage-BPDjxMw8.js +0 -1
  84. package/dist/assets/appRoute-CbCiASix.js +0 -1
  85. package/dist/assets/data-adapter-Bm8GGtft.js +0 -7
  86. package/dist/assets/index-PrzZHiAk.js +0 -2
  87. package/dist/assets/marketplaceApi-zYQofLEk.js +0 -1
  88. package/dist/assets/mermaid-GHXKKRXX-B7uCX_yo.js +0 -1
  89. package/dist/assets/metadata-admin-CleGXds3.js +0 -22
  90. package/dist/assets/plugin-chatbot-D2Uv-hn9.js +0 -120
  91. package/dist/assets/plugin-form-FeZEoC2R.js +0 -1
  92. package/dist/assets/plugin-view-BJ9uLrnO.js +0 -1
  93. package/dist/assets/plugins-views-CibWNUsP.js +0 -4
  94. package/dist/assets/src-BBieSqPB.js +0 -16
  95. package/dist/assets/useOpenRecordList-tyj2_1bm.js +0 -1
  96. package/dist/assets/useReconcileOnError-_XnUvYJA.js +0 -1
  97. package/dist/assets/vendor-objectstack-Bw0HRuFa.js +0 -95
@@ -1,7 +0,0 @@
1
- import{t as e}from"./rolldown-runtime-DAXXjFlN.js";import{Gt as t,t as n}from"./framework-B3O15Lsq.js";import{n as r}from"./vendor-zod-DNgwlUUI.js";var i=e((e=>{var t=r();function n(e){if(typeof process<`u`&&{}.OS_EAGER_SCHEMAS===`1`)return e();let t,n=()=>(t===void 0&&(t=e()),t);return new Proxy(function(){},{get(e,t){let r=n(),i=r[t];return typeof i==`function`?i.bind(r):i},set(e,t,r){let i=n();return i[t]=r,!0},has(e,t){return t in n()},ownKeys(){return Reflect.ownKeys(n())},getOwnPropertyDescriptor(e,t){return Reflect.getOwnPropertyDescriptor(n(),t)},getPrototypeOf(){return Reflect.getPrototypeOf(n())}})}var i=n(()=>t.z.object({$field:t.z.string().describe(`Field Reference/Column Name`)})),a=n(()=>t.z.object({$eq:t.z.any().optional(),$ne:t.z.any().optional()})),o=n(()=>t.z.object({$gt:t.z.union([t.z.number(),t.z.date(),i]).optional(),$gte:t.z.union([t.z.number(),t.z.date(),i]).optional(),$lt:t.z.union([t.z.number(),t.z.date(),i]).optional(),$lte:t.z.union([t.z.number(),t.z.date(),i]).optional()})),s=n(()=>t.z.object({$in:t.z.array(t.z.any()).optional(),$nin:t.z.array(t.z.any()).optional()})),c=n(()=>t.z.object({$between:t.z.tuple([t.z.union([t.z.number(),t.z.date(),i]),t.z.union([t.z.number(),t.z.date(),i])]).optional()})),l=n(()=>t.z.object({$contains:t.z.string().optional(),$notContains:t.z.string().optional(),$startsWith:t.z.string().optional(),$endsWith:t.z.string().optional()})),u=n(()=>t.z.object({$null:t.z.boolean().optional(),$exists:t.z.boolean().optional()})),d=n(()=>t.z.object({$eq:t.z.any().optional(),$ne:t.z.any().optional(),$gt:t.z.union([t.z.number(),t.z.date(),i]).optional(),$gte:t.z.union([t.z.number(),t.z.date(),i]).optional(),$lt:t.z.union([t.z.number(),t.z.date(),i]).optional(),$lte:t.z.union([t.z.number(),t.z.date(),i]).optional(),$in:t.z.array(t.z.any()).optional(),$nin:t.z.array(t.z.any()).optional(),$between:t.z.tuple([t.z.union([t.z.number(),t.z.date(),i]),t.z.union([t.z.number(),t.z.date(),i])]).optional(),$contains:t.z.string().optional(),$notContains:t.z.string().optional(),$startsWith:t.z.string().optional(),$endsWith:t.z.string().optional(),$null:t.z.boolean().optional(),$exists:t.z.boolean().optional()})),f=t.z.lazy(()=>t.z.record(t.z.string(),t.z.unknown()).and(t.z.object({$and:t.z.array(f).optional(),$or:t.z.array(f).optional(),$not:f.optional()}))),ee=n(()=>t.z.object({where:f.optional()})),p=t.z.lazy(()=>t.z.object({$and:t.z.array(t.z.union([t.z.record(t.z.string(),d),p])).optional(),$or:t.z.array(t.z.union([t.z.record(t.z.string(),d),p])).optional(),$not:t.z.union([t.z.record(t.z.string(),d),p]).optional()})),m=new Set([`=`,`==`,`!=`,`<>`,`>`,`>=`,`<`,`<=`,`in`,`nin`,`not_in`,`contains`,`notcontains`,`not_contains`,`like`,`startswith`,`starts_with`,`endswith`,`ends_with`,`between`,`is_null`,`is_not_null`]);function h(e){if(!Array.isArray(e)||e.length===0)return!1;let t=e[0];if(typeof t==`string`){let n=t.toLowerCase();if(n===`and`||n===`or`)return e.length>=2&&e.slice(1).every(e=>h(e));if(e.length>=2&&typeof e[1]==`string`)return m.has(e[1].toLowerCase())}return e.every(e=>h(e))?e.length>0:!1}var g={"=":`$eq`,"==":`$eq`,"!=":`$ne`,"<>":`$ne`,">":`$gt`,">=":`$gte`,"<":`$lt`,"<=":`$lte`,in:`$in`,nin:`$nin`,not_in:`$nin`,contains:`$contains`,notcontains:`$notContains`,not_contains:`$notContains`,like:`$contains`,startswith:`$startsWith`,starts_with:`$startsWith`,endswith:`$endsWith`,ends_with:`$endsWith`,between:`$between`,is_null:`$null`,is_not_null:`$null`};function _(e){let[t,n,r]=e,i=n.toLowerCase();if(i===`=`||i===`==`)return{[t]:r};if(i===`is_null`)return{[t]:{$null:!0}};if(i===`is_not_null`)return{[t]:{$null:!1}};let a=g[i];return a?{[t]:{[a]:r}}:{[t]:{[`$${i}`]:r}}}function v(e){if(e==null)return;if(!Array.isArray(e))return e;if(e.length===0)return;let t=e[0];if(typeof t==`string`&&(t.toLowerCase()===`and`||t.toLowerCase()===`or`)){let n=`$${t.toLowerCase()}`,r=e.slice(1).map(e=>v(e)).filter(Boolean);return r.length===0?void 0:r.length===1?r[0]:{[n]:r}}if(e.length>=2&&typeof t==`string`)return _(e);if(e.every(e=>Array.isArray(e))){let t=e.map(e=>v(e)).filter(Boolean);return t.length===0?void 0:t.length===1?t[0]:{$and:t}}}var y=[`$eq`,`$ne`,`$gt`,`$gte`,`$lt`,`$lte`,`$in`,`$nin`,`$between`,`$contains`,`$notContains`,`$startsWith`,`$endsWith`,`$null`,`$exists`],te=[`$and`,`$or`,`$not`],ne=[...y,...te],b=n(()=>t.z.object({field:t.z.string(),order:t.z.enum([`asc`,`desc`]).default(`asc`)})),x=t.z.enum([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`array_agg`,`string_agg`]),S=t.z.enum([`day`,`week`,`month`,`quarter`,`year`]),C=n(()=>t.z.union([t.z.string(),t.z.object({field:t.z.string().describe(`Field to group by`),dateGranularity:S.optional().describe(`Bucket date values into uniform periods (day/week/month/quarter/year)`),alias:t.z.string().optional().describe(`Alias for the projected group value`)})])),w=n(()=>t.z.object({function:x.describe(`Aggregation function`),field:t.z.string().optional().describe(`Field to aggregate (optional for COUNT(*))`),alias:t.z.string().describe(`Result column alias`),distinct:t.z.boolean().optional().describe(`Apply DISTINCT before aggregation`),filter:f.optional().describe(`Filter/Condition to apply to the aggregation (FILTER WHERE clause)`)})),T=t.z.enum([`inner`,`left`,`right`,`full`]),re=t.z.enum([`auto`,`database`,`hash`,`loop`]),E=t.z.lazy(()=>t.z.object({type:T.describe(`Join type`),strategy:re.optional().describe(`Execution strategy hint`),object:t.z.string().describe(`Object/table to join`),alias:t.z.string().optional().describe(`Table alias`),on:f.describe(`Join condition`),subquery:t.z.lazy(()=>k).optional().describe(`Subquery instead of object`)})),ie=t.z.enum([`row_number`,`rank`,`dense_rank`,`percent_rank`,`lag`,`lead`,`first_value`,`last_value`,`sum`,`avg`,`count`,`min`,`max`]),D=n(()=>t.z.object({partitionBy:t.z.array(t.z.string()).optional().describe(`PARTITION BY fields`),orderBy:t.z.array(b).optional().describe(`ORDER BY specification`),frame:t.z.object({type:t.z.enum([`rows`,`range`]).optional(),start:t.z.string().optional().describe(`Frame start (e.g., "UNBOUNDED PRECEDING", "1 PRECEDING")`),end:t.z.string().optional().describe(`Frame end (e.g., "CURRENT ROW", "1 FOLLOWING")`)}).optional().describe(`Window frame specification`)})),ae=n(()=>t.z.object({function:ie.describe(`Window function name`),field:t.z.string().optional().describe(`Field to operate on (for aggregate window functions)`),alias:t.z.string().describe(`Result column alias`),over:D.describe(`Window specification (OVER clause)`)})),O=t.z.lazy(()=>t.z.union([t.z.string(),t.z.object({field:t.z.string(),fields:t.z.array(O).optional(),alias:t.z.string().optional()})])),oe=n(()=>t.z.object({query:t.z.string().describe(`Search query text`),fields:t.z.array(t.z.string()).optional().describe(`Fields to search in (if not specified, searches all text fields)`),fuzzy:t.z.boolean().optional().default(!1).describe(`Enable fuzzy matching (tolerates typos)`),operator:t.z.enum([`and`,`or`]).optional().default(`or`).describe(`Logical operator between terms`),boost:t.z.record(t.z.string(),t.z.number()).optional().describe(`Field-specific relevance boosting (field name -> boost factor)`),minScore:t.z.number().optional().describe(`Minimum relevance score threshold`),language:t.z.string().optional().describe(`Language for text analysis (e.g., "en", "zh", "es")`),highlight:t.z.boolean().optional().default(!1).describe(`Enable search result highlighting`)})),se=t.z.object({object:t.z.string().describe(`Object name (e.g. account)`),fields:t.z.array(O).optional().describe(`Fields to retrieve`),where:f.optional().describe(`Filtering criteria (WHERE)`),search:oe.optional().describe(`Full-text search configuration ($search parameter)`),orderBy:t.z.array(b).optional().describe(`Sorting instructions (ORDER BY)`),limit:t.z.number().optional().describe(`Max records to return (LIMIT)`),offset:t.z.number().optional().describe(`Records to skip (OFFSET)`),top:t.z.number().optional().describe(`Alias for limit (OData compatibility)`),cursor:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Cursor for keyset pagination`),joins:t.z.array(E).optional().describe(`Explicit Table Joins`),aggregations:t.z.array(w).optional().describe(`Aggregation functions`),groupBy:t.z.array(C).optional().describe("GROUP BY targets (strings or `{field, dateGranularity?}` objects for date bucketing)"),having:f.optional().describe(`HAVING clause for aggregation filtering`),windowFunctions:t.z.array(ae).optional().describe(`Window functions with OVER clause`),distinct:t.z.boolean().optional().describe(`SELECT DISTINCT flag`)}),k=n(()=>se.extend({expand:t.z.lazy(()=>t.z.record(t.z.string(),k)).optional().describe("Recursive relation loading map. Keys are lookup/master_detail field names; values are nested QueryAST objects that control select (`fields`) and filter (`where`, AND-merged with the batch $in), plus further expansion on the related object. The engine resolves expand via batch $in queries (driver-agnostic) with a default max depth of 3; per-parent `limit`/`offset`/`orderBy` are NOT applied on this path.")})),ce=[`today`,`yesterday`,`tomorrow`,`now`],le=[`current_week_start`,`current_week_end`,`current_month_start`,`current_month_end`,`current_quarter_start`,`current_quarter_end`,`current_year_start`,`current_year_end`,`last_week_start`,`last_week_end`,`last_month_start`,`last_month_end`,`last_quarter_start`,`last_quarter_end`,`last_year_start`,`last_year_end`,`next_week_start`,`next_week_end`,`next_month_start`,`next_month_end`,`next_quarter_start`,`next_quarter_end`,`next_year_start`,`next_year_end`],ue=[`week_start`,`week_end`,`month_start`,`month_end`,`quarter_start`,`quarter_end`,`year_start`,`year_end`],de=[...ce,...le,...ue],fe=/^(\d+)_(minutes?|hours?|days?|weeks?|months?|years?)_(ago|from_now)$/,pe=[`minute`,`hour`,`day`,`week`,`month`,`year`];function me(e){return de.includes(e)||fe.test(e)}function he(e){let t=e.match(fe);if(!t)return null;let n=t[2].replace(/s$/,``);return{n:parseInt(t[1],10),unit:n,direction:t[3]}}var ge=t.z.string().refine(me,{message:`Unknown date macro. Must be a fixed token (see DATE_MACRO_TOKENS) or match {N_<unit>_(ago|from_now)} where unit is one of: `+pe.join(`, `)}),_e=/^\$?\{([a-zA-Z0-9_]+)\}$/,ve=t.z.string().refine(e=>{let t=e.match(_e);return!!t&&me(t[1])},{message:`Not a recognised {date-macro} placeholder`}),ye={today:`Start of today (YYYY-MM-DD).`,yesterday:`Start of yesterday.`,tomorrow:`Start of tomorrow.`,now:`Current timestamp (full ISO).`,current_week_start:`Monday 00:00 of this week.`,current_week_end:`Sunday of this week.`,current_month_start:`1st of this month.`,current_month_end:`Last day of this month.`,current_quarter_start:`1st day of this quarter.`,current_quarter_end:`Last day of this quarter.`,current_year_start:`Jan 1 of this year.`,current_year_end:`Dec 31 of this year.`,last_week_start:`Monday of last week.`,last_week_end:`Sunday of last week.`,last_month_start:`1st of last month.`,last_month_end:`Last day of last month.`,last_quarter_start:`1st day of last quarter.`,last_quarter_end:`Last day of last quarter.`,last_year_start:`Jan 1 of last year.`,last_year_end:`Dec 31 of last year.`,next_week_start:`Monday of next week.`,next_week_end:`Sunday of next week.`,next_month_start:`1st of next month.`,next_month_end:`Last day of next month.`,next_quarter_start:`1st day of next quarter.`,next_quarter_end:`Last day of next quarter.`,next_year_start:`Jan 1 of next year.`,next_year_end:`Dec 31 of next year.`,week_start:`Alias for current_week_start.`,week_end:`Alias for current_week_end.`,month_start:`Alias for current_month_start.`,month_end:`Alias for current_month_end.`,quarter_start:`Alias for current_quarter_start.`,quarter_end:`Alias for current_quarter_end.`,year_start:`Alias for current_year_start.`,year_end:`Alias for current_year_end.`},be=n(()=>t.z.string().min(2,{message:`System identifier must be at least 2 characters`}).regex(/^[a-z][a-z0-9_.]*$/,{message:`System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")`}).describe(`System identifier (lowercase with underscores or dots)`)),A=n(()=>t.z.string().min(2,{message:`Identifier must be at least 2 characters`}).regex(/^[a-z][a-z0-9_]*$/,{message:`Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")`}).describe(`Snake case identifier (lowercase with underscores only)`));n(()=>t.z.string().min(3,{message:`Event name must be at least 3 characters`}).regex(/^[a-z][a-z0-9_.]*$/,{message:`Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")`}).describe(`Event name (lowercase with dot notation for namespacing)`));var xe=t.z.enum([`cel`,`js`,`cron`,`template`]),Se=t.z.object({rationale:t.z.string().optional(),generatedBy:t.z.string().optional()}),Ce=t.z.object({dialect:xe,source:t.z.string().min(1).optional(),ast:t.z.unknown().optional(),meta:Se.optional()}).refine(e=>e.source!==void 0||e.ast!==void 0,{message:"Expression requires at least one of `source` or `ast`"}),j=t.z.union([t.z.string().min(1).transform(e=>({dialect:`cel`,source:e})),Ce]);t.z.union([t.z.string().min(1).transform(e=>({dialect:`cron`,source:e})),Ce]);var we=t.z.union([t.z.string().min(1).transform(e=>({dialect:`template`,source:e})),Ce]),M=t.z.enum(`text.textarea.email.url.phone.password.secret.markdown.html.richtext.number.currency.percent.date.datetime.time.boolean.toggle.select.multiselect.radio.checkboxes.lookup.master_detail.tree.user.image.file.avatar.video.audio.formula.summary.autonumber.composite.repeater.record.location.address.code.json.color.rating.slider.signature.qrcode.progress.tags.vector`.split(`.`)),N=n(()=>t.z.object({label:t.z.string().describe(`Display label (human-readable, any case allowed)`),value:be.describe(`Stored value (lowercase machine identifier)`),color:t.z.string().optional().describe(`Color code for badges/charts`),default:t.z.boolean().optional().describe(`Is default option`),visibleWhen:j.optional().describe("Per-option visibility predicate (CEL) — option is offered only when TRUE (else omitted). Same env as field visibleWhen (record + current_user). e.g. P`record.country == 'cn'` or P`'admin' in current_user.roles`")})),Te=n(()=>t.z.object({latitude:t.z.number().min(-90).max(90).describe(`Latitude coordinate`),longitude:t.z.number().min(-180).max(180).describe(`Longitude coordinate`),altitude:t.z.number().optional().describe(`Altitude in meters`),accuracy:t.z.number().optional().describe(`Accuracy in meters`)})),Ee=n(()=>t.z.object({precision:t.z.number().int().min(0).max(10).default(2).describe(`Decimal precision (default: 2)`),currencyMode:t.z.enum([`dynamic`,`fixed`]).default(`dynamic`).describe(`Currency mode: dynamic (user selectable) or fixed (single currency)`),defaultCurrency:t.z.string().length(3).default(`CNY`).describe(`Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)`)})),De=n(()=>t.z.object({value:t.z.number().describe(`Monetary amount`),currency:t.z.string().length(3).describe(`Currency code (ISO 4217)`)})),Oe=n(()=>t.z.object({street:t.z.string().optional().describe(`Street address`),city:t.z.string().optional().describe(`City name`),state:t.z.string().optional().describe(`State/Province`),postalCode:t.z.string().optional().describe(`Postal/ZIP code`),country:t.z.string().optional().describe(`Country name or code`),countryCode:t.z.string().optional().describe(`ISO country code (e.g., US, GB)`),formatted:t.z.string().optional().describe(`Formatted address string`)})),ke=n(()=>t.z.object({dimensions:t.z.number().int().min(1).max(1e4).describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),distanceMetric:t.z.enum([`cosine`,`euclidean`,`dotProduct`,`manhattan`]).default(`cosine`).describe(`Distance/similarity metric for vector search`),normalized:t.z.boolean().default(!1).describe(`Whether vectors are normalized (unit length)`),indexed:t.z.boolean().default(!0).describe(`Whether to create a vector index for fast similarity search`),indexType:t.z.enum([`hnsw`,`ivfflat`,`flat`]).optional().describe(`Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)`)})),Ae=n(()=>t.z.object({minSize:t.z.number().min(0).optional().describe(`Minimum file size in bytes`),maxSize:t.z.number().min(1).optional().describe(`Maximum file size in bytes (e.g., 10485760 = 10MB)`),allowedTypes:t.z.array(t.z.string()).optional().describe(`Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])`),blockedTypes:t.z.array(t.z.string()).optional().describe(`Blocked file extensions (e.g., [".exe", ".bat", ".sh"])`),allowedMimeTypes:t.z.array(t.z.string()).optional().describe(`Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])`),blockedMimeTypes:t.z.array(t.z.string()).optional().describe(`Blocked MIME types`),virusScan:t.z.boolean().default(!1).describe(`Enable virus scanning for uploaded files`),virusScanProvider:t.z.enum([`clamav`,`virustotal`,`metadefender`,`custom`]).optional().describe(`Virus scanning service provider`),virusScanOnUpload:t.z.boolean().default(!0).describe(`Scan files immediately on upload`),quarantineOnThreat:t.z.boolean().default(!0).describe(`Quarantine files if threat detected`),storageProvider:t.z.string().optional().describe(`Object storage provider name (references ObjectStorageConfig)`),storageBucket:t.z.string().optional().describe(`Target bucket name`),storagePrefix:t.z.string().optional().describe(`Storage path prefix (e.g., "uploads/documents/")`),imageValidation:t.z.object({minWidth:t.z.number().min(1).optional().describe(`Minimum image width in pixels`),maxWidth:t.z.number().min(1).optional().describe(`Maximum image width in pixels`),minHeight:t.z.number().min(1).optional().describe(`Minimum image height in pixels`),maxHeight:t.z.number().min(1).optional().describe(`Maximum image height in pixels`),aspectRatio:t.z.string().optional().describe(`Required aspect ratio (e.g., "16:9", "1:1")`),generateThumbnails:t.z.boolean().default(!1).describe(`Auto-generate thumbnails`),thumbnailSizes:t.z.array(t.z.object({name:t.z.string().describe(`Thumbnail variant name (e.g., "small", "medium", "large")`),width:t.z.number().min(1).describe(`Thumbnail width in pixels`),height:t.z.number().min(1).describe(`Thumbnail height in pixels`),crop:t.z.boolean().default(!1).describe(`Crop to exact dimensions`)})).optional().describe(`Thumbnail size configurations`),preserveMetadata:t.z.boolean().default(!1).describe(`Preserve EXIF metadata`),autoRotate:t.z.boolean().default(!0).describe(`Auto-rotate based on EXIF orientation`)}).optional().describe(`Image-specific validation rules`),allowMultiple:t.z.boolean().default(!1).describe(`Allow multiple file uploads (overrides field.multiple)`),allowReplace:t.z.boolean().default(!0).describe(`Allow replacing existing files`),allowDelete:t.z.boolean().default(!0).describe(`Allow deleting uploaded files`),requireUpload:t.z.boolean().default(!1).describe(`Require at least one file when field is required`),extractMetadata:t.z.boolean().default(!0).describe(`Extract file metadata (name, size, type, etc.)`),extractText:t.z.boolean().default(!1).describe(`Extract text content from documents (OCR/parsing)`),versioningEnabled:t.z.boolean().default(!1).describe(`Keep previous versions of replaced files`),maxVersions:t.z.number().min(1).optional().describe(`Maximum number of versions to retain`),publicRead:t.z.boolean().default(!1).describe(`Allow public read access to uploaded files`),presignedUrlExpiry:t.z.number().min(60).max(604800).default(3600).describe(`Presigned URL expiration in seconds (default: 1 hour)`)}).refine(e=>!(e.minSize!==void 0&&e.maxSize!==void 0&&e.minSize>e.maxSize),{message:`minSize must be less than or equal to maxSize`}).refine(e=>!(e.virusScanProvider!==void 0&&e.virusScan!==!0),{message:`virusScanProvider requires virusScan to be enabled`})),je=n(()=>t.z.object({uniqueness:t.z.boolean().default(!1).describe(`Enforce unique values across all records`),completeness:t.z.number().min(0).max(1).default(0).describe(`Minimum ratio of non-null values (0-1, default: 0 = no requirement)`),accuracy:t.z.object({source:t.z.string().describe(`Reference data source for validation (e.g., "api.verify.com", "master_data")`),threshold:t.z.number().min(0).max(1).describe(`Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)`)}).optional().describe(`Accuracy validation configuration`)})),Me=n(()=>t.z.object({enabled:t.z.boolean().describe(`Enable caching for computed field results`),ttl:t.z.number().min(0).describe(`Cache TTL in seconds (0 = no expiration)`),invalidateOn:t.z.array(t.z.string()).describe(`Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])`)})),P=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine name (snake_case)`).optional(),label:t.z.string().optional().describe(`Human readable label`),type:M.describe(`Field Data Type`),description:t.z.string().optional().describe(`Tooltip/Help text`),format:t.z.string().optional().describe(`Format string (e.g. email, phone)`),columnName:t.z.string().optional().describe(`Physical column name in the target datasource. Defaults to the field key when not set.`),required:t.z.boolean().default(!1).describe(`Is required`),searchable:t.z.boolean().default(!1).describe(`Is searchable`),multiple:t.z.boolean().default(!1).describe(`Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.`),unique:t.z.boolean().default(!1).describe(`Is unique constraint`),defaultValue:t.z.unknown().optional().describe(`Default value`),maxLength:t.z.number().optional().describe(`Max character length`),minLength:t.z.number().optional().describe(`Min character length`),precision:t.z.number().optional().describe(`Total digits`),scale:t.z.number().optional().describe(`Decimal places`),min:t.z.number().optional().describe(`Minimum value`),max:t.z.number().optional().describe(`Maximum value`),options:t.z.array(N).optional().describe(`Static options for select/multiselect`),reference:t.z.string().optional().describe(`Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects.`),referenceFilters:t.z.array(t.z.string()).optional().describe(`Filters applied to lookup dialogs (e.g. "active = true")`),deleteBehavior:t.z.enum([`set_null`,`cascade`,`restrict`]).optional().default(`set_null`).describe(`What happens if referenced record is deleted`),inlineEdit:t.z.union([t.z.boolean(),t.z.enum([`grid`,`form`])]).optional().describe(`Edit these child records inline within the parent's form (atomic master-detail). true = auto-pick grid/form by child shape; 'grid' = editable line-item grid; 'form' = list + per-row full form.`),inlineTitle:t.z.string().optional().describe(`Title for the inline master-detail grid`),inlineColumns:t.z.array(t.z.any()).optional().describe(`Explicit columns for the inline grid (derived from the child object when omitted)`),inlineAmountField:t.z.string().optional().describe(`Numeric child field summed for the inline grid total`),relatedList:t.z.union([t.z.boolean(),t.z.literal(`primary`)]).optional().describe(`Show this child collection as a related list on the parent's detail page (read-side mirror of inlineEdit). false = suppress; true/absent = shown (stacked under the shared "Related" tab); 'primary' = core relationship, promoted to its own tab. Prominence intent, not a layout switch (ADR-0085).`),relatedListTitle:t.z.string().optional().describe(`Title for the detail-page related list`),relatedListColumns:t.z.array(t.z.any()).optional().describe(`Explicit columns for the detail-page related list (derived from the child object when omitted)`),displayField:t.z.string().optional().describe(`Field shown as each candidate's label in the picker/popover (defaults to the referenced object's name/title).`),descriptionField:t.z.string().optional().describe(`Secondary field shown under the label in the quick-select popover.`),lookupColumns:t.z.array(t.z.union([t.z.string(),t.z.object({field:t.z.string(),label:t.z.string().optional(),width:t.z.string().optional(),type:t.z.string().optional()})])).optional().describe(`Explicit columns for the record-picker table; auto-derived from the referenced object when omitted.`),lookupPageSize:t.z.number().int().positive().optional().describe(`Rows per page in the record-picker dialog (default 10).`),lookupFilters:t.z.array(t.z.object({field:t.z.string(),operator:t.z.enum([`eq`,`ne`,`gt`,`lt`,`gte`,`lte`,`contains`,`in`,`notIn`]),value:t.z.any()})).optional().describe(`Base filters restricting which records are selectable (e.g. only active). Structured, picker-honoured form of referenceFilters.`),dependsOn:t.z.array(t.z.union([t.z.string(),t.z.object({field:t.z.string(),param:t.z.string().optional()})])).optional().describe("Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; {field,param} when the remote filter key differs — the {field,param} form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent."),allowCreate:t.z.boolean().optional().describe(`Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field.`),expression:j.optional().describe("Formula expression (CEL). e.g. F`record.amount * 0.1`"),returnType:t.z.enum([`number`,`text`,`boolean`,`date`]).optional().describe(`Inferred value type of a formula field (number/text/boolean/date)`),summaryOperations:t.z.object({object:t.z.string().describe(`Source child object name for roll-up`),field:t.z.string().describe(`Field on child object to aggregate (ignored for count)`),function:t.z.enum([`count`,`sum`,`min`,`max`,`avg`]).describe(`Aggregation function to apply`),relationshipField:t.z.string().optional().describe(`FK field on the child pointing back to this parent. Auto-detected from the child's lookup/master_detail field referencing this object when omitted; set explicitly only when the child has more than one such reference.`)}).optional().describe(`Roll-up summary definition. The engine recomputes the value when child records are inserted/updated/deleted.`),language:t.z.string().optional().describe(`Programming language for syntax highlighting (e.g., javascript, python, sql)`),step:t.z.number().optional().describe(`Step increment for slider (default: 1)`),currencyConfig:Ee.optional().describe(`Configuration for currency field type`),dimensions:t.z.number().int().min(1).max(1e4).optional().describe(`Vector dimensionality (e.g., 1536 for OpenAI embeddings)`),vectorConfig:ke.optional().describe(`Configuration for vector field type (AI/ML embeddings)`),fileAttachmentConfig:Ae.optional().describe(`Configuration for file and attachment field types`),trackHistory:t.z.boolean().optional().describe(`Render this field's value changes as human-readable entries on the record activity timeline (ADR-0052 §5b). Opt-in per field.`),dependencies:t.z.array(t.z.string()).optional().describe(`Array of field names that this field depends on (for formulas, visibility rules, etc.)`),group:t.z.string().optional().describe(`Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")`),visibleWhen:j.optional().describe("Predicate (CEL) — field is shown only when TRUE (else hidden). e.g. P`record.type == 'invoice'`"),readonlyWhen:j.optional().describe("Predicate (CEL) — field is read-only when TRUE. e.g. P`record.status == 'paid'`"),requiredWhen:j.optional().describe("Predicate (CEL) — field is required when TRUE. Canonical name for `conditionalRequired`."),conditionalRequired:j.optional().describe("Predicate (CEL) — field is required when TRUE. Alias of `requiredWhen`."),hidden:t.z.boolean().default(!1).describe(`Hidden from default UI`),readonly:t.z.boolean().default(!1).describe(`Read-only in UI`),requiredPermissions:t.z.array(t.z.string()).optional().describe(`[ADR-0066 D3] Capabilities required to read/edit this field (mask on read, deny on write; AND-gate).`),system:t.z.boolean().optional().describe(`Auto-injected system/audit field (e.g. created_at, updated_by, organization_id). Tools that surface system fields separately from author-declared business fields should branch on this flag.`),sortable:t.z.boolean().optional().default(!0).describe(`Whether field is sortable in list views`),inlineHelpText:t.z.string().optional().describe(`Help text displayed below the field in forms`),autonumberFormat:t.z.string().optional().describe(`Auto-number format: literal text + {0000} counter, {YYYY}/{MM}/{DD}/{YYYYMMDD} date tokens (business tz), and {field_name} interpolation. Counter resets per rendered prefix (e.g. AD{YYYYMMDD}{0000} resets daily).`),index:t.z.boolean().default(!1).describe(`Create standard database index`),externalId:t.z.boolean().default(!1).describe(`Is external ID for upsert operations`)})),Ne={text:(e={})=>({type:`text`,...e}),textarea:(e={})=>({type:`textarea`,...e}),number:(e={})=>({type:`number`,...e}),boolean:(e={})=>({type:`boolean`,...e}),date:(e={})=>({type:`date`,...e}),datetime:(e={})=>({type:`datetime`,...e}),currency:(e={})=>({type:`currency`,...e}),percent:(e={})=>({type:`percent`,...e}),url:(e={})=>({type:`url`,...e}),email:(e={})=>({type:`email`,...e}),phone:(e={})=>({type:`phone`,...e}),image:(e={})=>({type:`image`,...e}),file:(e={})=>({type:`file`,...e}),avatar:(e={})=>({type:`avatar`,...e}),formula:(e={})=>({type:`formula`,...e}),summary:(e={})=>({type:`summary`,...e}),autonumber:(e={})=>({type:`autonumber`,...e}),markdown:(e={})=>({type:`markdown`,...e}),html:(e={})=>({type:`html`,...e}),password:(e={})=>({type:`password`,...e}),secret:(e={})=>({type:`secret`,...e}),select:(e,t)=>{let n=e=>e.toLowerCase().replace(/\s+/g,`_`).replace(/[^a-z0-9_]/g,``),r,i;if(Array.isArray(e))r=e.map(e=>typeof e==`string`?{label:e,value:n(e)}:{...e,value:e.value.toLowerCase()}),i=t||{};else{r=(e.options||[]).map(e=>typeof e==`string`?{label:e,value:n(e)}:{...e,value:e.value.toLowerCase()});let{options:t,...a}=e;i=a}return{type:`select`,options:r,...i}},lookup:(e,t={})=>({type:`lookup`,reference:e,...t}),masterDetail:(e,t={})=>({type:`master_detail`,reference:e,...t}),user:(e={})=>({type:`user`,reference:`sys_user`,...e}),location:(e={})=>({type:`location`,...e}),address:(e={})=>({type:`address`,...e}),richtext:(e={})=>({type:`richtext`,...e}),code:(e,t={})=>({type:`code`,language:e,...t}),color:(e={})=>({type:`color`,...e}),rating:(e=5,t={})=>({type:`rating`,max:e,...t}),signature:(e={})=>({type:`signature`,...e}),slider:(e={})=>({type:`slider`,...e}),qrcode:(e={})=>({type:`qrcode`,...e}),json:(e={})=>({type:`json`,...e}),vector:(e,t={})=>({type:`vector`,dimensions:e,...t})},F=t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique rule name (snake_case)`),label:t.z.string().optional().describe(`Human-readable label for the rule listing`),description:t.z.string().optional().describe(`Administrative notes explaining the business reason`),active:t.z.boolean().default(!0),events:t.z.array(t.z.enum([`insert`,`update`,`delete`])).default([`insert`,`update`]).describe(`Validation contexts`),priority:t.z.number().int().min(0).max(9999).default(100).describe(`Execution priority (lower runs first, default: 100)`),tags:t.z.array(t.z.string()).optional().describe(`Categorization tags (e.g., "compliance", "billing")`),severity:t.z.enum([`error`,`warning`,`info`]).default(`error`),message:t.z.string().describe(`Error message to display to the user`)}),Pe=n(()=>F.extend({type:t.z.literal(`script`),condition:j.describe("Predicate (CEL). If TRUE, validation fails. e.g. P`record.amount < 0`")})),Fe=n(()=>F.extend({type:t.z.literal(`state_machine`),field:t.z.string().describe(`State field (e.g. status)`),transitions:t.z.record(t.z.string(),t.z.array(t.z.string())).describe(`Map of { OldState: [AllowedNewStates] }`)})),Ie=n(()=>F.extend({type:t.z.literal(`format`),field:t.z.string(),regex:t.z.string().optional(),format:t.z.enum([`email`,`url`,`phone`,`json`]).optional()})),Le=n(()=>F.extend({type:t.z.literal(`cross_field`),condition:j.describe("Predicate (CEL) comparing fields. e.g. P`record.end_date > record.start_date`"),fields:t.z.array(t.z.string()).describe(`Fields involved in the validation`)})),Re=n(()=>F.extend({type:t.z.literal(`json_schema`),field:t.z.string().describe(`JSON field to validate`),schema:t.z.record(t.z.string(),t.z.unknown()).describe(`JSON Schema object definition`)})),I=t.z.lazy(()=>t.z.discriminatedUnion(`type`,[Pe,Fe,Ie,Le,Re,ze])),ze=n(()=>F.extend({type:t.z.literal(`conditional`),when:j.describe("Predicate (CEL). e.g. P`record.type == 'enterprise'`"),then:I.describe(`Validation rule to apply when condition is true`),otherwise:I.optional().describe(`Validation rule to apply when condition is false`)}));n(()=>t.z.object({key:t.z.string().describe(`Translation key (e.g., "views.task_list.label")`),defaultValue:t.z.string().optional().describe(`Fallback value when translation key is not found`),params:t.z.record(t.z.string(),t.z.union([t.z.string(),t.z.number(),t.z.boolean()])).optional().describe(`Interpolation parameters (e.g., { count: 5 })`)}));var L=n(()=>t.z.string().describe(`Display label (plain string; i18n keys are auto-generated by the framework)`)),Be=n(()=>t.z.object({ariaLabel:L.optional().describe(`Accessible label for screen readers (WAI-ARIA aria-label)`),ariaDescribedBy:t.z.string().optional().describe(`ID of element providing additional description (WAI-ARIA aria-describedby)`),role:t.z.string().optional().describe(`WAI-ARIA role attribute (e.g., "dialog", "navigation", "alert")`)}).describe(`ARIA accessibility attributes`));n(()=>t.z.object({key:t.z.string().describe(`Translation key`),zero:t.z.string().optional().describe(`Zero form (e.g., "No items")`),one:t.z.string().optional().describe(`Singular form (e.g., "{count} item")`),two:t.z.string().optional().describe(`Dual form (e.g., "{count} items" for exactly 2)`),few:t.z.string().optional().describe(`Few form (e.g., for 2-4 in some languages)`),many:t.z.string().optional().describe(`Many form (e.g., for 5+ in some languages)`),other:t.z.string().describe(`Default plural form (e.g., "{count} items")`)}).describe(`ICU plural rules for a translation key`));var Ve=n(()=>t.z.object({style:t.z.enum([`decimal`,`currency`,`percent`,`unit`]).default(`decimal`).describe(`Number formatting style`),currency:t.z.string().optional().describe(`ISO 4217 currency code (e.g., "USD", "EUR")`),unit:t.z.string().optional().describe(`Unit for unit formatting (e.g., "kilometer", "liter")`),minimumFractionDigits:t.z.number().optional().describe(`Minimum number of fraction digits`),maximumFractionDigits:t.z.number().optional().describe(`Maximum number of fraction digits`),useGrouping:t.z.boolean().optional().describe(`Whether to use grouping separators (e.g., 1,000)`)}).describe(`Number formatting rules`)),He=n(()=>t.z.object({dateStyle:t.z.enum([`full`,`long`,`medium`,`short`]).optional().describe(`Date display style`),timeStyle:t.z.enum([`full`,`long`,`medium`,`short`]).optional().describe(`Time display style`),timeZone:t.z.string().optional().describe(`IANA time zone (e.g., "America/New_York")`),hour12:t.z.boolean().optional().describe(`Use 12-hour format`)}).describe(`Date/time formatting rules`));n(()=>t.z.object({code:t.z.string().describe(`BCP 47 language code (e.g., "en-US", "zh-CN")`),fallbackChain:t.z.array(t.z.string()).optional().describe(`Fallback language codes in priority order (e.g., ["zh-TW", "en"])`),direction:t.z.enum([`ltr`,`rtl`]).default(`ltr`).describe(`Text direction: left-to-right or right-to-left`),numberFormat:Ve.optional().describe(`Default number formatting rules`),dateFormat:He.optional().describe(`Default date/time formatting rules`)}).describe(`Locale configuration`));var Ue=t.z.enum([`api.read`,`api.write`,`api.transaction`,`crypto.uuid`,`crypto.hash`,`log`]),We=t.z.object({language:t.z.literal(`expression`),source:t.z.string().min(1).describe(`Formula expression source`)}).describe(`L1 expression body — pure formula, no IO`),Ge=t.z.object({language:t.z.literal(`js`),source:t.z.string().min(1).describe(`Function body source`),capabilities:t.z.array(Ue).default([]).describe(`Granted capability tokens`),timeoutMs:t.z.number().int().positive().max(3e4).optional().describe(`Per-invocation timeout (ms)`),memoryMb:t.z.number().int().positive().max(256).optional().describe(`Per-invocation memory cap (MB)`)}).describe(`L2 sandboxed JS body — runs inside an isolated VM with declared capabilities`),R=t.z.discriminatedUnion(`language`,[We,Ge]).describe(`Hook/Action body — expression (L1) or sandboxed JS (L2)`),Ke=n(()=>t.z.object({name:t.z.string().optional(),field:A.optional(),objectOverride:A.optional(),label:L.optional(),type:M.optional(),required:t.z.boolean().optional().default(!1),options:t.z.array(t.z.object({label:L,value:t.z.string()})).optional(),placeholder:t.z.string().optional(),helpText:t.z.string().optional(),defaultValue:t.z.unknown().optional(),defaultFromRow:t.z.boolean().optional()}).refine(e=>!!e.name||!!e.field,{message:`ActionParam requires either "name" or "field"`})),qe=t.z.enum([`script`,`url`,`modal`,`flow`,`api`,`form`]),Je=new Set(qe.options.filter(e=>e!==`script`)),Ye=t.z.enum([`list_toolbar`,`list_item`,`record_header`,`record_more`,`record_related`,`record_section`,`global_nav`]),Xe=t.z.enum([`data`,`action`,`flow`,`integration`,`vector_search`,`analytics`,`utility`]),Ze=t.z.object({exposed:t.z.boolean().default(!1).describe("Expose this action to AI agents. Requires `description` when true."),description:t.z.string().min(40).optional().describe(`LLM-facing description (≥40 chars). Required when exposed.`),category:Xe.optional().describe(`Tool category override (defaults to "action").`),paramHints:t.z.record(t.z.string(),t.z.object({description:t.z.string().optional(),enum:t.z.array(t.z.union([t.z.string(),t.z.number()])).optional(),examples:t.z.array(t.z.unknown()).optional()})).optional().describe(`Per-parameter AI hints keyed by param name.`),outputSchema:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`JSON Schema for the action return value.`),requiresConfirmation:t.z.boolean().optional().describe(`Override HITL confirmation for AI invocations.`)}),Qe=n(()=>t.z.object({name:A.describe(`Machine name (lowercase snake_case)`),label:L.describe(`Display label`),objectName:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).optional().describe(`Target object this action belongs to. When set, the action is auto-merged into the object's actions array by defineStack().`),icon:t.z.string().optional().describe(`Icon name`),locations:t.z.array(Ye).optional().describe(`Locations where this action is visible`),component:t.z.enum([`action:button`,`action:icon`,`action:menu`,`action:group`]).optional().describe(`Visual component override`),type:qe.default(`script`).describe(`Action functionality type`),target:t.z.string().optional().describe("URL, Script Name, Flow ID, or API Endpoint. Supports ${param.X} and ${ctx.X} interpolation."),openIn:t.z.enum([`self`,`new-tab`]).optional().describe("For type:'url' — where to open `target`. 'new-tab' opens a new browser tab; 'self' navigates in place. When omitted, external/absolute URLs open in a new tab and relative URLs navigate in place. Static execution option — keep it OUT of `params` (which is user-input-collection only)."),body:R.optional().describe("Action body — expression (L1) or sandboxed JS (L2). Only used when type is `script`."),execute:t.z.string().optional().describe(`@deprecated — Use target instead. Auto-migrated to target during parsing.`),params:t.z.array(Ke).optional().describe(`Input parameters required from user`),variant:t.z.enum([`primary`,`secondary`,`danger`,`ghost`,`link`]).optional().describe(`Button visual variant for styling (primary = highlighted, danger = destructive, ghost = transparent)`),confirmText:L.optional().describe(`Confirmation message before execution`),successMessage:L.optional().describe(`Success message to show after execution`),errorMessage:L.optional().describe(`Error message to show when the action fails (overrides the raw error).`),refreshAfter:t.z.boolean().default(!1).describe(`Refresh view after execution`),undoable:t.z.boolean().optional().describe(`Offer an Undo affordance after this single-record update action succeeds.`),resultDialog:t.z.object({title:L.optional(),description:L.optional(),acknowledge:L.optional().describe(`Acknowledge button label, e.g. "I have saved this"`),format:t.z.enum([`qrcode`,`code-list`,`secret`,`text`,`json`]).optional().describe(`Default format for fields without their own format. Defaults to json when omitted.`),fields:t.z.array(t.z.object({path:t.z.string().describe(`Dot path into result.data (e.g. "totpURI", "client.client_secret").`),label:L.optional(),format:t.z.enum([`qrcode`,`code-list`,`secret`,`text`,`json`]).optional().describe(`Per-field format override.`)})).optional().describe(`Which fields from result.data to render. Omit to dump full JSON.`)}).optional().describe(`Render API response in a one-shot reveal dialog (suppresses successMessage when set).`),visible:j.optional().describe(`Visibility predicate (CEL).`),disabled:t.z.union([t.z.boolean(),j]).optional().describe(`Boolean or predicate (CEL) — action is disabled when TRUE.`),requiredPermissions:t.z.array(t.z.string()).optional().describe(`[ADR-0066 D4] Capabilities required to invoke this action (server-enforced 403 + UI hide/disable).`),shortcut:t.z.string().optional().describe(`Keyboard shortcut to trigger this action (e.g., "Ctrl+S")`),bulkEnabled:t.z.boolean().optional().describe(`Whether this action can be applied to multiple selected records`),ai:Ze.optional().describe(`AI exposure (opt-in). Set ai.exposed=true + ai.description to make this callable by agents.`),recordIdParam:t.z.string().optional().describe(`Body key to inject the row id into when running from a list_item context.`),recordIdField:t.z.string().optional().describe(`Row field whose value seeds recordIdParam. Defaults to "id".`),bodyShape:t.z.union([t.z.literal(`flat`),t.z.object({wrap:t.z.string()})]).optional().describe(`Body wrapping: flat (default) or { wrap: key } to nest user-collected params under a key.`),method:t.z.enum([`POST`,`PATCH`,`PUT`,`DELETE`]).optional().describe(`HTTP method for type:"api" actions. Defaults to POST.`),bodyExtra:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Constant body fields merged into the API request (applied last; overrides user params).`),mode:t.z.enum([`create`,`edit`,`delete`,`custom`]).optional().describe(`Semantic mode of the action.`),opensInNewTab:t.z.boolean().optional().describe(`Open the action result in a new tab. The renderer pre-opens the tab synchronously on click (popup-blocker-safe) and navigates it to the handler's redirectUrl.`),newTabUrl:t.z.string().optional().describe(`Direct new-tab URL template ({recordId} placeholder). When set with opensInNewTab, the renderer navigates the pre-opened tab here immediately — no action POST. The endpoint must enforce auth itself.`),timeout:t.z.number().optional().describe(`Maximum execution time in milliseconds for the action`),aria:Be.optional().describe(`ARIA accessibility attributes`)}).transform(e=>e.execute&&!e.target?{...e,target:e.execute}:e).refine(e=>!(Je.has(e.type)&&!e.target),{message:`Action 'target' is required when type is 'url', 'flow', 'modal', 'api', or 'form'.`,path:[`target`]}).refine(e=>!(e.type===`script`&&!e.body&&!e.target),{message:"A 'script' action requires either an inline `body` (sandboxed L1/L2 handler) or a `target` (a registered bundle function name).",path:[`body`]}).refine(e=>!(e.ai?.exposed===!0&&!e.ai.description),{message:`ai.description is required (≥40 chars) when ai.exposed is true.`,path:[`ai`,`description`]}).refine(e=>{let t=e.ai?.paramHints;if(!t)return!0;let n=new Set([`recordId`]);for(let t of e.params??[]){let e=t.name??t.field;e&&n.add(e)}return Object.keys(t).every(e=>n.has(e))},{message:`ai.paramHints keys must match a declared param name (or "recordId").`,path:[`ai`,`paramHints`]})),$e=t.z.enum([`none`,`no-overlay`,`no-delete`,`full`]),et=t.z.enum([`artifact`,`package`,`env-forced`]),tt=t.z.enum([`package`,`org`,`env-forced`]),z={_lock:$e.optional().describe(`Item-level lock — controls overlay & delete (ADR-0010).`),_lockReason:t.z.string().max(500).optional().describe(`Human-readable reason shown when a write is refused by _lock.`),_lockSource:et.optional().describe(`Layer that set _lock (artifact | package | env-forced).`),_provenance:tt.optional().describe(`Origin of the item (package | org | env-forced).`),_packageId:t.z.string().optional().describe(`Owning package machine id.`),_packageVersion:t.z.string().optional().describe(`Owning package version.`),_lockDocsUrl:t.z.string().optional().describe(`Optional documentation link surfaced next to _lockReason.`)},B=t.z.object({lock:$e.describe(`Lock policy — none | no-overlay | no-delete | full.`),reason:t.z.string().min(1).max(500).describe(`User-visible reason shown when the lock blocks an action.`),docsUrl:t.z.string().url().optional().describe(`Optional URL the Studio banner links to for more context.`)}).strict(),nt=n(()=>t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable public sharing`),publicLink:t.z.string().optional().describe(`Generated public share URL`),password:t.z.string().optional().describe(`Password required to access shared link`),allowedDomains:t.z.array(t.z.string()).optional().describe(`Restrict access to specific email domains (e.g. ["example.com"])`),expiresAt:t.z.string().optional().describe(`Expiration date/time in ISO 8601 format`),allowAnonymous:t.z.boolean().optional().default(!1).describe(`Allow access without authentication`)}));n(()=>t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable iframe embedding`),allowedOrigins:t.z.array(t.z.string()).optional().describe(`Allowed iframe parent origins (e.g. ["https://example.com"])`),width:t.z.string().optional().default(`100%`).describe(`Embed width (CSS value)`),height:t.z.string().optional().default(`600px`).describe(`Embed height (CSS value)`),showHeader:t.z.boolean().optional().default(!0).describe(`Show interface header in embed`),showNavigation:t.z.boolean().optional().default(!1).describe(`Show navigation in embed`),responsive:t.z.boolean().optional().default(!0).describe(`Enable responsive resizing`)}));var rt=t.z.enum([`xs`,`sm`,`md`,`lg`,`xl`,`2xl`]),it=n(()=>t.z.object({xs:t.z.number().min(1).max(12).optional(),sm:t.z.number().min(1).max(12).optional(),md:t.z.number().min(1).max(12).optional(),lg:t.z.number().min(1).max(12).optional(),xl:t.z.number().min(1).max(12).optional(),"2xl":t.z.number().min(1).max(12).optional()}).describe(`Grid columns per breakpoint (1-12)`)),at=n(()=>t.z.object({xs:t.z.number().optional(),sm:t.z.number().optional(),md:t.z.number().optional(),lg:t.z.number().optional(),xl:t.z.number().optional(),"2xl":t.z.number().optional()}).describe(`Display order per breakpoint`)),ot=n(()=>t.z.object({breakpoint:rt.optional().describe(`Minimum breakpoint for visibility`),hiddenOn:t.z.array(rt).optional().describe(`Hide on these breakpoints`),columns:it.optional().describe(`Grid columns per breakpoint`),order:at.optional().describe(`Display order per breakpoint`)}).describe(`Responsive layout configuration`)),V=n(()=>t.z.record(t.z.string(),t.z.union([t.z.string(),t.z.number()])).describe(`CSS property → value map (camelCase keys; design tokens encouraged)`));n(()=>t.z.object({large:V.optional().describe(`Unconditional base (desktop-first)`),medium:V.optional().describe(`Applied at ≤ medium breakpoint`),small:V.optional().describe(`Applied at ≤ small breakpoint`),xsmall:V.optional().describe(`Applied at ≤ xsmall breakpoint`)}).describe(`Per-breakpoint scoped style maps (ADR-0065)`));var st=n(()=>t.z.object({lazyLoad:t.z.boolean().optional().describe(`Enable lazy loading (defer rendering until visible)`),virtualScroll:t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable virtual scrolling`),itemHeight:t.z.number().optional().describe(`Fixed item height in pixels (for estimation)`),overscan:t.z.number().optional().describe(`Number of extra items to render outside viewport`)}).optional().describe(`Virtual scrolling configuration`),cacheStrategy:t.z.enum([`none`,`cache-first`,`network-first`,`stale-while-revalidate`]).optional().describe(`Client-side data caching strategy`),prefetch:t.z.boolean().optional().describe(`Prefetch data before component is visible`),pageSize:t.z.number().optional().describe(`Number of items per page for pagination`),debounceMs:t.z.number().optional().describe(`Debounce interval for user interactions in milliseconds`)}).describe(`Performance optimization configuration`)),ct=t.z.enum([`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]),lt=n(()=>t.z.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`])),ut=n(()=>t.z.object({url:t.z.string().describe(`API endpoint URL`),method:lt.optional().default(`GET`).describe(`HTTP method`),headers:t.z.record(t.z.string(),t.z.string()).optional().describe(`Custom HTTP headers`),params:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Query parameters`),body:t.z.unknown().optional().describe(`Request body for POST/PUT/PATCH`)}));n(()=>t.z.object({enabled:t.z.boolean().default(!0).describe(`Enable CORS`),origins:t.z.union([t.z.string(),t.z.array(t.z.string())]).default(`*`).describe(`Allowed origins (* for all)`),methods:t.z.array(ct).optional().describe(`Allowed HTTP methods`),credentials:t.z.boolean().default(!1).describe(`Allow credentials (cookies, authorization headers)`),maxAge:t.z.number().int().optional().describe(`Preflight cache duration in seconds`)})),n(()=>t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable rate limiting`),windowMs:t.z.number().int().default(6e4).describe(`Time window in milliseconds`),maxRequests:t.z.number().int().default(100).describe(`Max requests per window`)})),n(()=>t.z.object({path:t.z.string().describe(`URL path to serve from`),directory:t.z.string().describe(`Physical directory to serve`),cacheControl:t.z.string().optional().describe(`Cache-Control header value`)}));var dt=n(()=>t.z.discriminatedUnion(`provider`,[t.z.object({provider:t.z.literal(`object`),object:t.z.string().describe(`Target object name`)}),t.z.object({provider:t.z.literal(`api`),read:ut.optional().describe(`Configuration for fetching data`),write:ut.optional().describe(`Configuration for submitting data (for forms/editable tables)`)}),t.z.object({provider:t.z.literal(`value`),items:t.z.array(t.z.unknown()).describe(`Static data array`)}),t.z.object({provider:t.z.literal(`schema`),schemaId:t.z.string().describe(`Schema identifier — typically the metadata type name`),schema:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Inline JSON Schema (Draft 2020-12). Optional when schemaId is resolvable.`)})])),ft=n(()=>t.z.object({field:t.z.string().describe(`Field name to filter on`),operator:t.z.string().describe(`Filter operator (e.g. equals, not_equals, contains, this_quarter)`),value:t.z.union([t.z.string(),t.z.number(),t.z.boolean(),t.z.null(),t.z.array(t.z.union([t.z.string(),t.z.number()]))]).optional().describe(`Filter value`)}).describe(`View filter rule`)),pt=n(()=>t.z.enum([`none`,`count`,`count_empty`,`count_filled`,`count_unique`,`percent_empty`,`percent_filled`,`sum`,`avg`,`min`,`max`]).describe(`Aggregation function for column footer summary`)),mt=n(()=>t.z.object({field:t.z.string().describe(`Field name (snake_case)`),label:L.optional().describe(`Display label override`),width:t.z.number().positive().optional().describe(`Column width in pixels`),align:t.z.enum([`left`,`center`,`right`]).optional().describe(`Text alignment`),hidden:t.z.boolean().optional().describe(`Hide column by default`),sortable:t.z.boolean().optional().describe(`Allow sorting by this column`),resizable:t.z.boolean().optional().describe(`Allow resizing this column`),wrap:t.z.boolean().optional().describe(`Allow text wrapping`),type:t.z.string().optional().describe(`Renderer type override (e.g., "currency", "date")`),pinned:t.z.enum([`left`,`right`]).optional().describe(`Pin/freeze column to left or right side`),summary:pt.optional().describe(`Footer aggregation function for this column`),link:t.z.boolean().optional().describe(`Functions as the primary navigation link (triggers View navigation)`),action:t.z.string().optional().describe(`Registered Action ID to execute when clicked`)})),ht=n(()=>t.z.object({type:t.z.enum([`none`,`single`,`multiple`]).default(`none`).describe(`Selection mode`)})),gt=n(()=>t.z.object({pageSize:t.z.number().int().positive().default(25).describe(`Number of records per page`),pageSizeOptions:t.z.array(t.z.number().int().positive()).optional().describe(`Available page size options`)})),_t=n(()=>t.z.enum([`compact`,`short`,`medium`,`tall`,`extra_tall`]).describe(`Row height / density setting for list view`)),vt=n(()=>t.z.object({field:t.z.string().describe(`Field name to group by`),order:t.z.enum([`asc`,`desc`]).default(`asc`).describe(`Group sort order`),collapsed:t.z.boolean().default(!1).describe(`Collapse groups by default`)})),yt=n(()=>t.z.object({fields:t.z.array(vt).min(1).describe(`Fields to group by (supports up to 3 levels)`)}).describe(`Record grouping configuration`)),bt=n(()=>t.z.object({coverField:t.z.string().optional().describe(`Attachment/image field to display as card cover`),coverFit:t.z.enum([`cover`,`contain`]).default(`cover`).describe(`Image fit mode for card cover`),cardSize:t.z.enum([`small`,`medium`,`large`]).default(`medium`).describe(`Card size in gallery view`),titleField:t.z.string().optional().describe(`Field to display as card title`),visibleFields:t.z.array(t.z.string()).optional().describe(`Fields to display on card body`)}).describe(`Gallery/card view configuration`)),xt=n(()=>t.z.object({startDateField:t.z.string().describe(`Field for timeline item start date`),endDateField:t.z.string().optional().describe(`Field for timeline item end date`),titleField:t.z.string().describe(`Field to display as timeline item title`),groupByField:t.z.string().optional().describe(`Field to group timeline rows`),colorField:t.z.string().optional().describe(`Field to determine item color`),scale:t.z.enum([`hour`,`day`,`week`,`month`,`quarter`,`year`]).default(`week`).describe(`Default timeline scale`)}).describe(`Timeline view configuration`)),St=n(()=>t.z.object({type:t.z.enum([`personal`,`collaborative`]).default(`collaborative`).describe(`View ownership type`),lockedBy:t.z.string().optional().describe(`User who locked the view configuration`)}).describe(`View sharing and access configuration`)),Ct=n(()=>t.z.object({field:t.z.string().describe(`Field to derive color from (typically a select/status field)`),colors:t.z.record(t.z.string(),t.z.string()).optional().describe(`Map of field value to color (hex/token)`)}).describe(`Row color configuration based on field values`)),wt=n(()=>t.z.enum([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).describe(`Visualization type that users can switch to`)),Tt=n(()=>t.z.object({sort:t.z.boolean().default(!0).describe(`Allow users to sort records`),search:t.z.boolean().default(!0).describe(`Allow users to search records`),filter:t.z.boolean().default(!0).describe(`Allow users to filter records`),rowHeight:t.z.boolean().default(!0).describe(`Allow users to toggle row height/density`),addRecordForm:t.z.boolean().default(!1).describe(`Add records through a form instead of inline`),editInline:t.z.boolean().default(!1).describe(`Allow users to edit records inline — click a cell to edit it with the field's type-aware widget (the same control the form uses). Off by default: the list is read-only unless the author opts in.`),buttons:t.z.array(t.z.string()).optional().describe(`Custom action button IDs to show in the toolbar`)}).describe(`User action toggles for the view toolbar`)),Et=n(()=>t.z.object({showDescription:t.z.boolean().default(!0).describe(`Show the view description text`),allowedVisualizations:t.z.array(wt).optional().describe(`Whitelist of visualization types users can switch between (e.g. ["grid", "gallery", "kanban"])`)}).describe(`Appearance and visualization configuration`)),Dt=n(()=>t.z.object({name:A.describe(`Tab identifier (snake_case)`),label:L.optional().describe(`Display label`),icon:t.z.string().optional().describe(`Tab icon name`),view:t.z.string().optional().describe(`Referenced list view name from listViews`),filter:t.z.array(ft).optional().describe(`Tab-specific filter criteria`),order:t.z.number().int().min(0).optional().describe(`Tab display order`),pinned:t.z.boolean().default(!1).describe(`Pin tab (cannot be removed by users)`),isDefault:t.z.boolean().default(!1).describe(`Set as the default active tab`),visible:t.z.boolean().default(!0).describe(`Tab visibility`)}).describe(`Tab configuration for multi-tab view interface`)),Ot=n(()=>t.z.object({field:t.z.string().describe(`Field name on the source object (must exist — checked by reference diagnostics)`),label:L.optional().describe(`Display label override (defaults to the field label)`),type:t.z.enum([`select`,`multi-select`,`boolean`,`date-range`,`text`]).optional().describe(`Filter control type. Omit to infer from the field definition`),options:t.z.array(t.z.object({value:t.z.union([t.z.string(),t.z.number(),t.z.boolean()]).describe(`Option value`),label:L.describe(`Option label`),color:t.z.string().optional().describe(`Option color token/hex`)})).optional().describe(`Static options. Omit to derive from the field definition (select options / lookup records)`),showCount:t.z.boolean().optional().describe(`Show per-option record counts`),defaultValues:t.z.array(t.z.union([t.z.string(),t.z.number(),t.z.boolean()])).optional().describe(`Pre-selected values when the view loads`)}).describe(`Quick-filter field configuration`)),kt=n(()=>t.z.object({element:t.z.enum([`dropdown`,`tabs`,`toggle`]).default(`dropdown`).describe(`Filter control style: "dropdown" (per-field value selectors) or "tabs" (named presets). "toggle" is deprecated.`),fields:t.z.array(Ot).optional().describe(`Fields exposed as quick filters (dropdown/toggle elements)`),tabs:t.z.array(Dt).optional().describe(`Named filter presets rendered as tabs (tabs element). Reuses ViewTabSchema`),showAllRecords:t.z.boolean().optional().describe(`Show an "All records" tab before the presets (tabs element)`)}).describe(`End-user quick-filter configuration (Airtable "User filters" parity)`)),At=n(()=>t.z.object({enabled:t.z.boolean().default(!0).describe(`Show the add record entry point`),position:t.z.enum([`top`,`bottom`,`both`]).default(`bottom`).describe(`Position of the add record button`),mode:t.z.enum([`inline`,`form`,`modal`]).default(`inline`).describe(`How to add a new record`),formView:t.z.string().optional().describe(`Named form view to use when mode is "form" or "modal"`)}).describe(`Add record entry point configuration`)),jt=n(()=>t.z.object({groupByField:t.z.string().describe(`Field to group columns by (usually status/select)`),summarizeField:t.z.string().optional().describe(`Field to sum at top of column (e.g. amount)`),columns:t.z.array(t.z.string()).describe(`Fields to show on cards`)})),Mt=n(()=>t.z.object({chartType:t.z.enum([`bar`,`line`,`pie`,`area`,`scatter`]).default(`bar`).describe(`Chart visualisation type`),dataset:A.describe(`Dataset name to bind (ADR-0021)`),dimensions:t.z.array(t.z.string()).optional().describe(`Dimension names — X/group/split`),values:t.z.array(t.z.string()).min(1).describe(`Measure names — Y (at least one)`)}).describe(`List chart view configuration`)),Nt=n(()=>t.z.object({startDateField:t.z.string(),endDateField:t.z.string().optional(),titleField:t.z.string(),colorField:t.z.string().optional()})),Pt=n(()=>t.z.object({field:t.z.string().describe(`Record field / dot-path the dimension filters on`),label:t.z.string().optional().describe(`Trigger label (falls back to the field label)`),options:t.z.array(t.z.union([t.z.string(),t.z.object({value:t.z.union([t.z.string(),t.z.number()]),label:t.z.string().optional()})])).optional().describe(`Explicit option override for fixed enums`)})),Ft=n(()=>t.z.object({startDateField:t.z.string(),endDateField:t.z.string(),titleField:t.z.string(),progressField:t.z.string().optional(),dependenciesField:t.z.string().optional(),colorField:t.z.string().optional().describe(`Field that drives the bar color`),parentField:t.z.string().optional().describe(`Field holding the parent task id (builds the summary → step tree)`),typeField:t.z.string().optional().describe(`Field whose value maps to task/summary/milestone`),baselineStartField:t.z.string().optional().describe(`Baseline (planned) start field`),baselineEndField:t.z.string().optional().describe(`Baseline (planned) end field`),groupByField:t.z.string().optional().describe(`Field to group leaf tasks by (synthesized summary rows)`),resourceView:t.z.boolean().optional().describe(`Render a per-resource workload histogram instead of the timeline`),assigneeField:t.z.string().optional().describe(`Resource field to bucket load by (resource view)`),effortField:t.z.string().optional().describe(`Per-task load units (resource view; default 1)`),capacity:t.z.number().optional().describe(`Per-resource capacity ceiling; loads above this flag overload`),tooltipFields:t.z.array(t.z.union([t.z.string(),t.z.object({field:t.z.string(),label:t.z.string().optional()})])).optional().describe(`Fields to surface in the hover tooltip, in display order`),quickFilters:t.z.array(Pt).optional().describe(`Multi-select filter dropdowns rendered above the chart`),autoZoomToFilter:t.z.boolean().optional().describe(`When true (default), filtering zooms the range to the filtered tasks`)}).passthrough()),It=n(()=>t.z.object({parentField:t.z.string().optional().describe(`Single-parent pointer field (auto-detected from the object schema when omitted)`),labelField:t.z.string().optional().describe(`Field rendered indented in the first column (defaults to "name")`),fields:t.z.array(t.z.string()).optional().describe(`Additional fields rendered as flat columns alongside the label`),defaultExpandedDepth:t.z.number().int().min(0).optional().describe(`Initial expansion depth (0 = roots only; omit = expand all)`)}).passthrough()),Lt=n(()=>t.z.enum([`page`,`drawer`,`modal`,`split`,`popover`,`new_window`,`none`])),Rt=n(()=>t.z.object({mode:Lt.default(`page`),view:t.z.string().optional().describe(`Name of the form view to use for details (e.g. "summary_view", "edit_form")`),preventNavigation:t.z.boolean().default(!1).describe(`Disable standard navigation entirely`),openNewTab:t.z.boolean().default(!1).describe(`Force open in new tab (applies to page mode)`),size:t.z.enum([`auto`,`sm`,`md`,`lg`,`xl`,`full`]).default(`auto`).describe("[#2578] Overlay size bucket for drawer/modal detail: 'auto' (default — renderer derives from field count + viewport; AI writes nothing) or a coarse override sm/md/lg/xl/full. Prefer this over the pixel `width`; page mode ignores it."),width:t.z.union([t.z.string(),t.z.number()]).optional().describe('[DEPRECATED → size] Pixel/percent width of the drawer/modal (e.g. "600px"). A pixel width cannot be chosen at authoring time without knowing the client viewport — use the `size` bucket.')})),zt=n(()=>t.z.object({name:A.optional().describe(`Internal view name (lowercase snake_case)`),label:L.optional(),type:t.z.enum([`grid`,`kanban`,`gallery`,`calendar`,`timeline`,`gantt`,`map`,`chart`,`tree`]).default(`grid`),data:dt.optional().describe(`Data source configuration (defaults to "object" provider)`),columns:t.z.union([t.z.array(t.z.string()),t.z.array(mt)]).describe(`Fields to display as columns`),filter:t.z.array(ft).optional().describe(`Filter criteria (JSON Rules)`),sort:t.z.union([t.z.string(),t.z.array(t.z.object({field:t.z.string(),order:t.z.enum([`asc`,`desc`])}))]).optional(),searchableFields:t.z.array(t.z.string()).optional().describe(`Fields enabled for search`),filterableFields:t.z.array(t.z.string()).optional().describe(`Legacy shorthand for userFilters.fields — bare field names enabled for end-user filtering. Prefer userFilters`),userFilters:kt.optional().describe(`End-user quick-filter bar: dropdown/toggle fields or tab presets. Omit to let the renderer derive filters from select/boolean fields`),resizable:t.z.boolean().optional().describe(`Enable column resizing`),striped:t.z.boolean().optional().describe(`Striped row styling`),bordered:t.z.boolean().optional().describe(`Show borders`),compactToolbar:t.z.boolean().optional().describe(`Collapse Group/Color/Density/Hide-fields into a single View settings popover`),selection:ht.optional().describe(`Row selection configuration`),navigation:Rt.optional().describe(`Configuration for item click navigation (page, drawer, modal, etc.)`),pagination:gt.optional().describe(`Pagination configuration`),kanban:jt.optional(),calendar:Nt.optional(),gantt:Ft.optional(),gallery:bt.optional(),timeline:xt.optional(),chart:Mt.optional(),tree:It.optional(),description:L.optional().describe(`View description for documentation/tooltips`),sharing:St.optional().describe(`View sharing and access configuration`),rowHeight:_t.optional().describe(`Row height / density setting`),grouping:yt.optional().describe(`Group records by one or more fields`),rowColor:Ct.optional().describe(`Color rows based on field value`),hiddenFields:t.z.array(t.z.string()).optional().describe(`Fields to hide in this specific view`),fieldOrder:t.z.array(t.z.string()).optional().describe(`Explicit field display order for this view`),rowActions:t.z.array(t.z.string()).optional().describe(`Actions available for individual row items`),bulkActions:t.z.array(t.z.string()).optional().describe(`Actions available when multiple rows are selected`),bulkActionDefs:t.z.array(t.z.record(t.z.string(),t.z.any())).optional().describe(`Rich bulk action definitions (schema-driven, executed via BulkActionDialog)`),virtualScroll:t.z.boolean().optional().describe(`Enable virtual scrolling for large datasets`),conditionalFormatting:t.z.array(t.z.object({condition:j.describe(`Predicate (CEL) to evaluate.`),style:t.z.record(t.z.string(),t.z.string()).describe(`CSS styles to apply when condition is true`)})).optional().describe(`Conditional formatting rules for list rows`),inlineEdit:t.z.boolean().optional().describe(`Allow inline editing of records directly in the list view`),exportOptions:t.z.array(t.z.enum([`csv`,`xlsx`,`pdf`,`json`])).optional().describe(`Available export format options`),userActions:Tt.optional().describe(`User action toggles for the view toolbar`),appearance:Et.optional().describe(`Appearance and visualization configuration`),tabs:t.z.array(Dt).optional().describe(`Tab definitions for multi-tab view interface`),addRecord:At.optional().describe(`Add record entry point configuration`),showRecordCount:t.z.boolean().optional().describe(`Show record count at the bottom of the list`),allowPrinting:t.z.boolean().optional().describe(`Allow users to print the view`),emptyState:t.z.object({title:L.optional(),message:L.optional(),icon:t.z.string().optional()}).optional().describe(`Empty state configuration when no records found`),aria:Be.optional().describe(`ARIA accessibility attributes for the list view`),responsive:ot.optional().describe(`Responsive layout configuration`),performance:st.optional().describe(`Performance optimization settings`)})),Bt=n(()=>t.z.object({field:t.z.string().describe(`Field name (snake_case)`),type:M.optional().describe(`Field type (auto-infers widget if omitted)`),options:t.z.array(N).optional().describe(`Options for select/multiselect/radio/checkboxes fields`),reference:t.z.string().optional().describe(`Target object name for lookup/master_detail fields`),maxLength:t.z.number().optional().describe(`Maximum character length (for text/textarea/email/url/phone)`),minLength:t.z.number().optional().describe(`Minimum character length`),min:t.z.number().optional().describe(`Minimum value (for number/currency/percent/slider)`),max:t.z.number().optional().describe(`Maximum value`),precision:t.z.number().optional().describe(`Total digits (for number/currency)`),scale:t.z.number().optional().describe(`Decimal places`),multiple:t.z.boolean().optional().describe(`Allow multiple values (for select/lookup/file/image)`),label:L.optional().describe(`Display label override`),placeholder:L.optional().describe(`Placeholder text`),helpText:L.optional().describe(`Help/hint text`),readonly:t.z.boolean().optional().describe(`Read-only override`),immutable:t.z.boolean().optional().describe(`Editable on create, locked once the record exists (e.g. machine names).`),required:t.z.boolean().optional().describe(`Required override`),hidden:t.z.boolean().optional().describe(`Hidden override`),colSpan:t.z.number().int().min(1).max(4).optional().describe("[legacy — prefer `span`] Absolute column span (1-4). Fragile when the column count is derived per surface (mobile 1 / modal 2 / page 3-4): a fixed span only lines up at the width the author imagined. The renderer clamps it to the current column count. Prefer `span`."),span:t.z.enum([`auto`,`full`]).default(`auto`).describe("Relative field width. 'auto' (default — omit it): the renderer sizes the field from its widget type × the current column count (wide widgets like textarea/richtext/json/file/subform take the whole row). 'full': whole row at any column count. Prefer this over the absolute `colSpan`."),widget:t.z.string().optional().describe(`Custom widget/component name (overrides type-based inference)`),language:t.z.string().optional().describe(`Code editor language (for type=code)`),fields:t.z.array(t.z.lazy(()=>Bt)).optional().describe(`Sub-fields for composite/repeater/record types`),keyField:t.z.object({field:t.z.string().default(`name`).describe(`Property name that holds the key inside each item (defaults to "name")`),label:L.optional().describe(`Display label for the key column`),placeholder:L.optional().describe(`Placeholder when entering a new key`),helpText:L.optional().describe(`Help text under the key input`),regex:t.z.string().optional().describe(`JS regex source string the key must match (no flags)`),immutable:t.z.boolean().default(!0).describe(`If true, the key is read-only after creation`)}).optional().describe(`Key column config for record-typed fields`),dependsOn:t.z.string().optional().describe(`Parent field name for cascading`),visibleOn:j.optional().describe(`Visibility predicate (CEL).`),disclosure:t.z.enum([`inline`,`popover`]).optional().describe(`Composite rendering: inline bordered box (default) or a summary line + gear popover (progressive disclosure).`)})),Vt=n(()=>t.z.object({name:t.z.string().optional().describe(`Stable section identifier for i18n lookup (snake_case)`),label:L.optional(),description:t.z.string().optional().describe(`Optional description rendered under the section header.`),collapsible:t.z.boolean().default(!1),collapsed:t.z.boolean().default(!1),visibleOn:j.optional().describe(`Visibility predicate (CEL). Hides the whole section when false.`),columns:t.z.union([t.z.enum([`1`,`2`,`3`,`4`]),t.z.literal(1),t.z.literal(2),t.z.literal(3),t.z.literal(4)]).default(1).transform(e=>typeof e==`string`?parseInt(e):e),fields:t.z.array(t.z.union([t.z.string(),Bt]))})),H=n(()=>t.z.object({type:t.z.enum([`simple`,`tabbed`,`wizard`,`split`,`drawer`,`modal`]).default(`simple`),layout:t.z.enum([`vertical`,`horizontal`,`inline`,`grid`]).optional().describe(`Field layout direction`),columns:t.z.number().int().min(1).optional().describe(`Number of columns for the form body`),title:t.z.string().optional().describe(`Form title`),description:t.z.string().optional().describe(`Form description`),defaultTab:t.z.string().optional().describe(`Initially active tab (tabbed forms)`),tabPosition:t.z.enum([`top`,`bottom`,`left`,`right`]).optional().describe(`Tab strip position (tabbed forms)`),allowSkip:t.z.boolean().optional().describe(`Allow skipping steps (wizard forms)`),showStepIndicator:t.z.boolean().optional().describe(`Show the step indicator (wizard forms)`),splitDirection:t.z.enum([`horizontal`,`vertical`]).optional().describe(`Split orientation (split forms)`),splitSize:t.z.number().optional().describe(`Primary split panel size, % (split forms)`),splitResizable:t.z.boolean().optional().describe(`Whether the split is resizable (split forms)`),drawerSide:t.z.enum([`top`,`bottom`,`left`,`right`]).optional().describe(`Drawer side (drawer forms)`),drawerWidth:t.z.string().optional().describe(`[DEPRECATED → size buckets] Drawer width, e.g. "480px". A pixel width cannot be chosen without knowing the client viewport — the renderer derives it.`),modalSize:t.z.enum([`sm`,`default`,`lg`,`xl`,`full`]).optional().describe(`Modal size (modal forms)`),data:dt.optional().describe(`Data source configuration (defaults to "object" provider)`),sections:t.z.array(Vt).optional(),groups:t.z.array(Vt).optional(),subforms:t.z.array(t.z.object({childObject:t.z.string().describe(`Child object whose records are entered inline`),relationshipField:t.z.string().optional().describe(`FK on the child pointing back to the parent (auto-detected when omitted)`),columns:t.z.array(t.z.any()).optional().describe(`Editable grid columns (derived from the child object when omitted)`),amountField:t.z.string().optional().describe(`Numeric child column summed for the running total`),totalField:t.z.string().optional().describe(`Parent field to receive the rolled-up sum`),title:t.z.string().optional().describe(`Section title`),addLabel:t.z.string().optional().describe(`Add-row button label`),minRows:t.z.number().optional(),maxRows:t.z.number().optional()})).optional().describe(`Inline master-detail child collections`),defaultSort:t.z.array(t.z.object({field:t.z.string().describe(`Field name to sort by`),order:t.z.enum([`asc`,`desc`]).default(`desc`).describe(`Sort direction`)})).optional().describe(`Default sort order for related list views within this form`),sharing:nt.optional().describe(`Public sharing configuration for this form`),submitBehavior:t.z.union([t.z.object({kind:t.z.literal(`thank-you`),title:t.z.string().optional(),message:t.z.string().optional()}),t.z.object({kind:t.z.literal(`redirect`),url:t.z.string(),delayMs:t.z.number().int().min(0).optional()}),t.z.object({kind:t.z.literal(`continue`)}),t.z.object({kind:t.z.literal(`next-record`)})]).optional().describe(`Post-submit behavior`),aria:Be.optional().describe(`ARIA accessibility attributes for the form view`)})),U=n(()=>zt.omit({userFilters:!0}));n(()=>t.z.object({list:U.optional(),form:H.optional(),listViews:t.z.record(t.z.string(),U).optional().describe(`Additional named list views (views mode — no userFilters, ADR-0053)`),formViews:t.z.record(t.z.string(),H).optional().describe(`Additional named form views`),protection:B.optional().describe(`Package author protection block — lock policy for this view.`),...z}));var Ht=t.z.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/,`View item name must be a dotted snake_case qualified name, e.g. "crm_lead.pipeline".`).describe("Globally-unique view id, `<object>.<viewKey>`."),Ut=t.z.enum([`package`,`shared`,`personal`]).describe(`View identity layer: package | shared | personal.`);t.z.enum([`list`,`form`]).describe("Whether `config` is a ListView (list family) or a FormView.");function Wt(){return{name:Ht,object:t.z.string().describe(`Bound object name — the foreign key used to aggregate views.`),label:L.optional().describe(`Display label (supports i18n).`),isDefault:t.z.boolean().optional().describe(`Whether this is the object's default view in the switcher.`),order:t.z.number().int().optional().describe(`Sort order within the object's view switcher / left rail.`),scope:Ut.optional().describe("Identity layer (defaults to `package` for source-loaded views)."),owner:t.z.string().optional().describe("Owner user id — set when `scope` is `personal`."),hidden:t.z.boolean().optional().describe(`Hidden from the switcher (per-user / per-org declutter).`),protection:B.optional().describe(`Package author protection block — lock policy for this view.`),...z}}n(()=>t.z.discriminatedUnion(`viewKind`,[t.z.object({viewKind:t.z.literal(`list`),config:zt.describe(`List-family view configuration.`),...Wt()}),t.z.object({viewKind:t.z.literal(`form`),config:H.describe(`Form view configuration.`),...Wt()})]));function W(e){let{schemaId:t,...n}=e;return H.parse({...n,data:{provider:`schema`,schemaId:t}})}var Gt=t.z.enum([`get`,`list`,`create`,`update`,`delete`,`upsert`,`bulk`,`aggregate`,`history`,`search`,`restore`,`purge`,`import`,`export`]),Kt=t.z.object({trackHistory:t.z.boolean().default(!1).describe(`Enable field history tracking for audit compliance`),searchable:t.z.boolean().default(!0).describe(`Index records for global search`),apiEnabled:t.z.boolean().default(!0).describe(`Expose object via automatic APIs`),apiMethods:t.z.array(Gt).optional().describe(`Whitelist of allowed API operations`),files:t.z.boolean().default(!1).describe(`Enable file attachments and document management`),feeds:t.z.boolean().default(!1).describe(`Enable social feed, comments, and mentions (Chatter-like)`),activities:t.z.boolean().default(!1).describe(`Enable standard tasks and events tracking`),trash:t.z.boolean().default(!0).describe(`Enable soft-delete with restore capability`),mru:t.z.boolean().default(!0).describe(`Track Most Recently Used (MRU) list for users`),clone:t.z.boolean().default(!0).describe(`Allow record deep cloning`)}),qt=n(()=>t.z.object({name:t.z.string().optional().describe(`Index name (auto-generated if not provided)`),fields:t.z.array(t.z.string()).describe(`Fields included in the index`),type:t.z.enum([`btree`,`hash`,`gin`,`gist`,`fulltext`]).optional().default(`btree`).describe(`Index algorithm type`),unique:t.z.boolean().optional().default(!1).describe(`Whether the index enforces uniqueness`),partial:t.z.string().optional().describe(`Partial index condition (SQL WHERE clause for conditional indexes)`)})),Jt=n(()=>t.z.object({fields:t.z.array(t.z.string()).describe(`Fields to index for full-text search weighting`),displayFields:t.z.array(t.z.string()).optional().describe(`Fields to display in search result cards`),filters:t.z.array(t.z.string()).optional().describe(`Default filters for search results`)})),Yt=n(()=>t.z.object({enabled:t.z.boolean().describe(`Enable multi-tenancy for this object`),strategy:t.z.enum([`shared`,`isolated`,`hybrid`]).describe(`Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)`),tenantField:t.z.string().default(`tenant_id`).describe(`Field name for tenant identifier`),crossTenantAccess:t.z.boolean().default(!1).describe(`Allow cross-tenant data access (with explicit permission)`)})),Xt=n(()=>t.z.object({default:t.z.enum([`public`,`private`]).default(`public`).describe(`Default exposure posture: public (covered by wildcard grants) | private (needs explicit grant; exempt from wildcard RLS).`)})),Zt=n(()=>t.z.object({enabled:t.z.boolean().describe(`Enable soft delete (trash/recycle bin)`),field:t.z.string().default(`deleted_at`).describe(`Field name for soft delete timestamp`),cascadeDelete:t.z.boolean().default(!1).describe(`Cascade soft delete to related records`)})),Qt=n(()=>t.z.object({enabled:t.z.boolean().describe(`Enable record versioning`),strategy:t.z.enum([`snapshot`,`delta`,`event-sourcing`]).describe(`Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)`),retentionDays:t.z.number().min(1).optional().describe(`Number of days to retain old versions (undefined = infinite)`),versionField:t.z.string().default(`version`).describe(`Field name for version number/timestamp`)})),$t=n(()=>t.z.object({key:t.z.string().regex(/^[a-z_][a-z0-9_]*$/,{message:`Field group key must be lowercase snake_case (e.g., "contact_info", "billing", "system")`}).describe(`Group machine key (snake_case). Referenced by Field.group.`),label:t.z.string().describe(`Group display label`),icon:t.z.string().optional().describe(`Icon name (Lucide/Material) for the group header`),description:t.z.string().optional().describe(`Optional description shown under the group header`),collapse:t.z.enum([`none`,`expanded`,`collapsed`]).optional().default(`none`).describe(`[ADR-0085] Section collapse behaviour: 'none' (always open, no toggle), 'expanded' (collapsible, starts open), 'collapsed' (collapsible, starts closed).`),defaultExpanded:t.z.boolean().optional().describe(`[DEPRECATED → collapse] true → 'expanded', false → 'collapsed'.`),collapsible:t.z.boolean().optional().describe("[DEPRECATED → collapse] Boolean pair with `collapsed`; use the `collapse` enum."),collapsed:t.z.boolean().optional().describe("[DEPRECATED → collapse] Boolean pair with `collapsible`; use the `collapse` enum.")})),en=t.z.object({remoteName:t.z.string().optional().describe(`Remote table/view name. Defaults to object.name.`),remoteSchema:t.z.string().optional().describe(`Remote schema/database qualifier.`),writable:t.z.boolean().default(!1).describe(`Per-object write opt-in (also requires datasource.external.allowWrites).`),columnMap:t.z.record(t.z.string(),t.z.string()).optional().describe(`Remote column name → local field name.`),introspectedAt:t.z.string().datetime().optional().describe("Set by `os datasource introspect`; informational."),ignoreColumns:t.z.array(t.z.string()).optional().describe(`Remote columns to skip during validation (dev convenience).`)}).describe(`External datasource binding (ADR-0015)`),G=t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Machine unique key (snake_case). Immutable.`),label:t.z.string().optional().describe(`Human readable singular label (e.g. "Account")`),pluralLabel:t.z.string().optional().describe(`Human readable plural label (e.g. "Accounts")`),description:t.z.string().optional().describe(`Developer documentation / description`),icon:t.z.string().optional().describe(`Icon name (Lucide/Material) for UI representation`),tags:t.z.array(t.z.string()).optional().describe(`Categorization tags (e.g. "sales", "system", "reference")`),active:t.z.boolean().optional().default(!0).describe(`Is the object active and usable`),isSystem:t.z.boolean().optional().default(!1).describe(`Is system object (protected from deletion)`),abstract:t.z.boolean().optional().default(!1).describe(`Is abstract base object (cannot be instantiated)`),managedBy:t.z.enum([`platform`,`config`,`system`,`append-only`,`better-auth`]).optional().describe(`Lifecycle bucket — platform (user CRUD) | config (admin authored) | system (engine-managed) | append-only (audit) | better-auth (identity). UI clients honour the resolved affordance matrix.`),userActions:t.z.object({create:t.z.boolean().optional().describe(`Show generic "New" button.`),import:t.z.boolean().optional().describe(`Show CSV import wizard entry.`),edit:t.z.boolean().optional().describe(`Allow inline / form edit of existing rows.`),delete:t.z.boolean().optional().describe(`Show row-level delete + bulk delete.`),exportCsv:t.z.boolean().optional().describe(`Show CSV export entry.`)}).optional().describe(`Per-object override of the resolved CRUD affordance matrix.`),systemFields:t.z.union([t.z.literal(!1),t.z.object({tenant:t.z.boolean().optional().describe(`Inject organization_id (multi-tenant only). Default true.`),owner:t.z.boolean().optional().describe(`Reserved for future owner_id auto-injection.`),audit:t.z.boolean().optional().describe(`Reserved for future created_by/updated_by auto-injection.`)})]).optional().describe(`Opt out of, or selectively disable, registry-level system-field auto-injection.`),datasource:t.z.string().optional().default(`default`).describe(`Target Datasource ID. "default" is the primary DB.`),external:en.optional().describe(`Remote table binding for federated (external) objects.`),fields:t.z.record(t.z.string().regex(/^[a-z_][a-z0-9_]*$/,{message:`Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")`}),P).describe(`Field definitions map. Keys must be snake_case identifiers.`),indexes:t.z.array(qt).optional().describe(`Database performance indexes`),fieldGroups:t.z.array($t).refine(e=>new Set(e.map(e=>e.key)).size===e.length,{message:`fieldGroups[].key must be unique within an object`}).optional().describe(`Ordered list of field groups (array order = display order). See ObjectFieldGroupSchema.`),tenancy:Yt.optional().describe(`Multi-tenancy configuration for SaaS applications`),access:Xt.optional().describe(`[ADR-0066 D2] Object exposure posture (public-by-default vs private secure-by-default).`),requiredPermissions:t.z.array(t.z.string()).optional().describe(`[ADR-0066 D3] Capabilities required to access this object (AND-gate, checked alongside CRUD grants).`),softDelete:Zt.optional().describe(`Soft delete (trash/recycle bin) configuration`),versioning:Qt.optional().describe(`Record versioning and history tracking configuration`),validations:t.z.array(I).optional().describe(`Object-level validation rules`),activityMilestones:t.z.array(t.z.object({field:t.z.string().describe(`Field to watch (typically a status/stage select).`),value:t.z.string().describe(`The value the field must transition INTO to fire the milestone.`),summary:t.z.string().describe(`Activity summary template; {field} tokens interpolate the record value. e.g. "Deal won: {name}".`),type:t.z.string().optional().describe(`Activity type for the emitted row (default "completed").`)})).optional().describe(`Declarative semantic activity milestones — emit a templated timeline row when a field transitions into a value, no hook code (ADR-0052 §5b.2).`),nameField:t.z.string().optional().describe(`[ADR-0079] Canonical primary title field — the stored field used as the record display name (e.g. "name", "title"). Pairs with recordName.`),displayNameField:t.z.string().optional().describe(`[DEPRECATED → nameField] Field to use as the record display name (e.g., "name", "title"). Accepted as an alias for nameField.`),recordName:t.z.object({type:t.z.enum([`text`,`autonumber`]).describe(`Record name type: text (user-entered) or autonumber (system-generated)`),displayFormat:t.z.string().optional().describe(`Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")`),startNumber:t.z.number().int().min(0).optional().describe(`Starting number for autonumber (default: 1)`)}).optional().describe(`Record name generation configuration (Salesforce pattern)`),titleFormat:we.optional().describe(`[DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. Migrate a single-field title to nameField, a composite to a formula field designated as nameField.`),highlightFields:t.z.array(t.z.string()).optional().describe(`[ADR-0085] Ordered most-important fields; first entry wins where only one fits. Drives default columns, cards, previews, detail highlight strip. Renamed from compactLayout.`),stageField:t.z.union([t.z.string(),t.z.literal(!1)]).optional().describe(`[ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed.`),listViews:t.z.record(t.z.string(),U).optional().describe(`Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, no page-only userFilters (ADR-0053)`),searchableFields:t.z.array(t.z.string()).optional().describe("Fields the `$search` query matches against (ADR-0061). Canonical default for the record picker, list quick-search and global search; views may narrow it. When unset, search auto-defaults to the name/title field plus short-text fields."),search:Jt.optional().describe(`Search engine configuration`),enable:Kt.optional().describe(`Enabled system features modules`),sharingModel:t.z.enum([`private`,`public_read`,`public_read_write`,`controlled_by_parent`,`read`,`read_write`,`full`]).optional().describe(`Org-Wide Default record visibility (OWD). Canonical: private (owner-only) | public_read (everyone reads, owner writes) | public_read_write (everyone reads+writes) | controlled_by_parent (derived from the master record). Legacy aliases: read=public_read, read_write/full=public_read_write. ADR-0056 D1.`),publicSharing:t.z.object({enabled:t.z.boolean().default(!1).describe(`Allow records of this object to be published via share link`),allowedAudiences:t.z.array(t.z.enum([`public`,`link_only`,`signed_in`,`email`])).optional().describe(`Audiences callers may select when creating a link`),allowedPermissions:t.z.array(t.z.enum([`view`,`comment`,`edit`])).optional().describe(`Permission levels selectable on the share dialog`),maxExpiryDays:t.z.number().int().positive().optional().describe(`Reject links with expiry beyond this many days`),redactFields:t.z.array(t.z.string()).optional().describe(`Field names removed from records served via a share token`),eligibility:t.z.string().optional().describe(`CEL expression that must evaluate to true on the target record`)}).optional().describe(`Public share-link policy (Notion/Figma-style link sharing)`),keyPrefix:t.z.string().max(5).optional().describe(`Short prefix for record IDs (e.g., "001" for Account)`),actions:t.z.array(Qe).optional().describe(`Actions associated with this object (auto-populated from top-level actions via objectName)`),protection:B.optional().describe(`Package author protection block — lock policy for this object.`),...z});function tn(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}var nn={workflows:"`workflows` is not an ObjectSchema field. Object-level, record-triggered automation is authored as a lifecycle hook (`src/objects/<name>.hook.ts`, registered via `defineHook()`) or as a top-level `record_change` flow — not as `workflows[]` on the object schema.",workflow:"`workflow` is not an ObjectSchema field. Record-triggered automation is authored as a lifecycle hook (`src/objects/<name>.hook.ts`) or a top-level `record_change` flow.",hooks:"`hooks` is not an ObjectSchema field. Lifecycle hooks live in their own `src/objects/<name>.hook.ts` module, registered via `defineHook()`.",triggers:"`triggers` is not an ObjectSchema field. Use a lifecycle hook (`src/objects/<name>.hook.ts`) or a top-level `record_change` flow.",compactLayout:"`compactLayout` was renamed to `highlightFields` in @objectstack/spec 11.7.0 (ADR-0085 semantic roles) and the alias was retired in 11.9.1 (#2536). Rename the key — the value shape (ordered field-name list) is unchanged.",detail:"The `detail` UI-hints block was removed by ADR-0085 (spec 11.7.0). Its jobs moved to top-level semantic roles: `detail.stageField` → `stageField` (string | false), `detail.highlightFields` → `highlightFields`, section layout → `fieldGroups` + `Field.group`. Whole-page customization is done by assigning a custom Page schema instead of per-page hint keys.",views:"`views` is not an ObjectSchema field: the object-level `views.form/*` and `views.detail/*` UI-hint dialect was never part of the spec and its renderer support was removed (ADR-0085). Use the semantic roles (`highlightFields`, `stageField`, `fieldGroups`) for hints and `listViews` for named list views.",defaultDetailForm:"`defaultDetailForm` was never implemented and was removed from the spec (#2402). Curate the record page by assigning a custom Page schema; form layout derives from `fieldGroups` + `Field.group`."};function rn(e,t){let n=Array.from({length:e.length+1},()=>Array(t.length+1).fill(0));for(let t=0;t<=e.length;t++)n[t][0]=t;for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=e.length;r++)for(let i=1;i<=t.length;i++)n[r][i]=e[r-1]===t[i-1]?n[r-1][i-1]:1+Math.min(n[r-1][i],n[r][i-1],n[r-1][i-1]);return n[e.length][t.length]}function an(e,t){let n,r=1/0;for(let i of t){let t=rn(e.toLowerCase(),i.toLowerCase());t<r&&(r=t,n=i)}return n!==void 0&&r<=Math.max(2,Math.floor(e.length/3))?n:void 0}function on(e,t,n){let r=typeof e==`string`&&e.length>0?e:`<unnamed>`,i=t.map(e=>{let t=nn[e];if(t)return` \u2022 ${t}`;let r=an(e,n);return r?` \u2022 \`${e}\` is not an ObjectSchema field \u2014 did you mean \`${r}\`?`:` \u2022 \`${e}\` is not an ObjectSchema field.`});return Error(`ObjectSchema.create('${r}'): unknown key(s) \u2014 ${t.join(`, `)}.
2
- These keys would previously have been stripped silently at build, shipping dead metadata with no diagnostic (ADR-0032 "no silent failure", issue #1535).
3
-
4
- ${i.join(`
5
- `)}
6
-
7
- Remove the unknown key(s), fix the typo, or move the logic to a supported mechanism.`)}function sn(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e;return t.nameField==null&&typeof t.displayNameField==`string`?{...t,nameField:t.displayNameField}:e}function cn(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e,n=t;if(Array.isArray(t.fieldGroups)){let e=!1,r=t.fieldGroups.map(t=>{if(!t||typeof t!=`object`||Array.isArray(t))return t;let n=t;if(n.collapse!=null)return t;let r;return typeof n.collapsible==`boolean`||typeof n.collapsed==`boolean`?r=n.collapsed===!0?`collapsed`:n.collapsible===!0?`expanded`:`none`:typeof n.defaultExpanded==`boolean`&&(r=n.defaultExpanded?`expanded`:`collapsed`),r===void 0?t:(e=!0,{...n,collapse:r})});e&&(n={...n,fieldGroups:r})}return n}var ln=n(()=>{let e=G.parse.bind(G),t=G.safeParse.bind(G);return Object.assign(G,{parse(t,n){return e(cn(sn(t)),n)},safeParse(e,n){return t(cn(sn(e)),n)},create:e=>{let t=e,n=Object.keys(G.shape),r=Object.keys(t).filter(e=>!n.includes(e));if(r.length>0)throw on(t.name,r,n);let i={...t,label:t.label??tn(t.name)};return G.parse(i)}})}),un={platform:{create:!0,import:!0,edit:!0,delete:!0,exportCsv:!0},config:{create:!0,import:!1,edit:!0,delete:!0,exportCsv:!0},system:{create:!1,import:!1,edit:!1,delete:!1,exportCsv:!0},"append-only":{create:!1,import:!1,edit:!1,delete:!1,exportCsv:!0},"better-auth":{create:!1,import:!1,edit:!1,delete:!1,exportCsv:!0}};function dn(e){let t=un[e?.managedBy??`platform`]??un.platform,n=e?.userActions??{};return{create:n.create??t.create,import:n.import??t.import,edit:n.edit??t.edit,delete:n.delete??t.delete,exportCsv:n.exportCsv??t.exportCsv}}var fn=t.z.enum([`own`,`extend`]),pn=n(()=>t.z.object({extend:t.z.string().describe(`Target object name (FQN) to extend`),fields:t.z.record(t.z.string(),P).optional().describe(`Fields to add/override`),label:t.z.string().optional().describe(`Override label for the extended object`),pluralLabel:t.z.string().optional().describe(`Override plural label for the extended object`),description:t.z.string().optional().describe(`Override description for the extended object`),validations:t.z.array(I).optional().describe(`Additional validation rules to merge into the target object`),indexes:t.z.array(qt).optional().describe(`Additional indexes to merge into the target object`),priority:t.z.number().int().min(0).max(999).default(200).describe(`Merge priority (higher = applied later)`)}));function mn(e){return pn.parse(e)}var hn=new Set([`YYYY`,`YY`,`MM`,`DD`,`YYYYMMDD`]);function gn(e){let t=[];if(!e)return t;let n=/\{([^{}]*)\}/g,r=0,i,a=!1;for(;(i=n.exec(e))!==null;){i.index>r&&t.push({kind:`literal`,text:e.slice(r,i.index)});let o=i[1];/^0+$/.test(o)&&!a?(t.push({kind:`seq`,width:o.length}),a=!0):hn.has(o)?t.push({kind:`date`,pattern:o}):/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)?t.push({kind:`field`,field:o}):t.push({kind:`literal`,text:i[0]}),r=n.lastIndex}return r<e.length&&t.push({kind:`literal`,text:e.slice(r)}),t}function _n(e){return e.some(e=>e.kind===`date`||e.kind===`field`)}function vn(e,t=4){let n=e.find(e=>e.kind===`seq`);return n&&n.kind===`seq`?n.width:t}function yn(e){return e.filter(e=>e.kind===`field`).map(e=>e.field)}function bn(e,t){let n=[];for(let r of yn(e)){let e=t?t[r]:void 0;(e==null||e===``)&&!n.includes(r)&&n.push(r)}return n}function xn(e,t){let n,r,i;try{let a=new Intl.DateTimeFormat(`en-CA`,{timeZone:t||`UTC`,year:`numeric`,month:`2-digit`,day:`2-digit`}).formatToParts(e);n=a.find(e=>e.type===`year`)?.value??`0000`,r=a.find(e=>e.type===`month`)?.value??`01`,i=a.find(e=>e.type===`day`)?.value??`01`}catch{n=String(e.getUTCFullYear()).padStart(4,`0`),r=String(e.getUTCMonth()+1).padStart(2,`0`),i=String(e.getUTCDate()).padStart(2,`0`)}return{YYYY:n,YY:n.slice(-2),MM:r,DD:i}}function Sn(e,t){switch(e){case`YYYY`:return t.YYYY;case`YY`:return t.YY;case`MM`:return t.MM;case`DD`:return t.DD;case`YYYYMMDD`:return`${t.YYYY}${t.MM}${t.DD}`;default:return``}}function Cn(e){let{tokens:t,seq:n,record:r,now:i,timezone:a}=e,o=xn(i,a),s=``,c=``,l=null;for(let e of t){if(e.kind===`seq`){l=e.width;continue}let t=``;if(e.kind===`literal`)t=e.text;else if(e.kind===`date`)t=Sn(e.pattern,o);else if(e.kind===`field`){let n=r?r[e.field]:void 0;t=n==null?``:String(n)}l===null?s+=t:c+=t}let u=_n(t)?s:``,d=l===null?`${s}${n}`:`${s}${String(n).padStart(l,`0`)}${c}`;return{prefix:s,suffix:c,scope:u,value:d}}var wn=t.z.enum([`beforeFind`,`afterFind`,`beforeFindOne`,`afterFindOne`,`beforeCount`,`afterCount`,`beforeAggregate`,`afterAggregate`,`beforeInsert`,`afterInsert`,`beforeUpdate`,`afterUpdate`,`beforeDelete`,`afterDelete`,`beforeUpdateMany`,`afterUpdateMany`,`beforeDeleteMany`,`afterDeleteMany`]),Tn=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Hook unique name (snake_case)`),label:t.z.string().optional().describe(`Description of what this hook does`),object:t.z.union([t.z.string(),t.z.array(t.z.string())]).describe(`Target object(s)`),events:t.z.array(wn).describe(`Lifecycle events`),handler:t.z.union([t.z.string(),t.z.custom(e=>typeof e==`function`,{message:`Expected function`})]).optional().describe("Handler function name (string, post-build) or inline function (pre-build) — DEPRECATED, prefer `body`"),body:R.optional().describe(`Hook body — expression (L1) or sandboxed JS (L2)`),priority:t.z.number().default(100).describe(`Execution priority`),async:t.z.boolean().default(!1).describe(`Run specifically as fire-and-forget`),condition:j.optional().describe('Predicate (CEL); hook runs only when TRUE. e.g. P`record.status == "closed" && record.amount > 1000`'),description:t.z.string().optional().describe(`Human-readable description of what this hook does`),retryPolicy:t.z.object({maxRetries:t.z.number().default(3).describe(`Maximum retry attempts on failure`),backoffMs:t.z.number().default(1e3).describe(`Backoff delay between retries in milliseconds`)}).optional().describe(`Retry policy for failed hook executions`),timeout:t.z.number().optional().describe(`Maximum execution time in milliseconds before the hook is aborted`),onError:t.z.enum([`abort`,`log`]).default(`abort`).describe(`Error handling strategy`)})),En=n(()=>t.z.object({id:t.z.string().optional().describe(`Unique execution ID for tracing`),object:t.z.string(),event:wn,input:t.z.record(t.z.string(),t.z.unknown()).describe(`Mutable input parameters`),result:t.z.unknown().optional().describe(`Operation result (After hooks only)`),previous:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Record state before operation`),session:t.z.object({userId:t.z.string().optional(),tenantId:t.z.string().optional(),roles:t.z.array(t.z.string()).optional(),accessToken:t.z.string().optional(),isSystem:t.z.boolean().optional().describe(`True when the call was made with an elevated system context (engine self-writes)`),skipTriggers:t.z.boolean().optional().describe(`True when record-change automation (flow triggers) must be suppressed for this write — e.g. package seed replay. Lifecycle hooks still run.`)}).optional().describe(`Current session context`),transaction:t.z.unknown().optional().describe(`Database transaction handle`),ql:t.z.unknown().describe(`ObjectQL Engine Reference`),api:t.z.unknown().optional().describe(`Cross-object data access (ScopedContext)`),user:t.z.object({id:t.z.string().optional(),name:t.z.string().optional(),email:t.z.string().optional()}).optional().describe(`Current user info shortcut`)})),Dn=t.z.enum([`none`,`constant`,`lookup`,`split`,`join`,`javascript`,`map`]),On=n(()=>t.z.object({source:t.z.union([t.z.string(),t.z.array(t.z.string())]).describe(`Source column header(s)`),target:t.z.union([t.z.string(),t.z.array(t.z.string())]).describe(`Target object field(s)`),transform:Dn.default(`none`),params:t.z.object({value:t.z.unknown().optional(),object:t.z.string().optional(),fromField:t.z.string().optional(),toField:t.z.string().optional(),autoCreate:t.z.boolean().optional(),valueMap:t.z.record(t.z.string(),t.z.unknown()).optional(),separator:t.z.string().optional()}).optional()})),kn=n(()=>t.z.object({name:A.describe(`Mapping unique name (lowercase snake_case)`),label:t.z.string().optional(),sourceFormat:t.z.enum([`csv`,`json`,`xml`,`sql`]).default(`csv`),targetObject:t.z.string().describe(`Target Object Name`),fieldMapping:t.z.array(On),mode:t.z.enum([`insert`,`update`,`upsert`]).default(`insert`),upsertKey:t.z.array(t.z.string()).optional().describe(`Fields to match for upsert (e.g. email)`),extractQuery:k.optional().describe(`Query to run for export only`),errorPolicy:t.z.enum([`skip`,`abort`,`retry`]).default(`skip`),batchSize:t.z.number().default(1e3)}));function An(e){return kn.parse(e)}var jn=n(()=>t.z.object({userId:t.z.string().optional(),actor:t.z.string().optional(),email:t.z.string().optional(),tenantId:t.z.string().optional(),timezone:t.z.string().optional(),locale:t.z.string().optional(),currency:t.z.string().optional(),roles:t.z.array(t.z.string()).default([]),permissions:t.z.array(t.z.string()).default([]),systemPermissions:t.z.array(t.z.string()).optional(),tabPermissions:t.z.record(t.z.string(),t.z.enum([`visible`,`hidden`,`default_on`,`default_off`])).optional(),org_user_ids:t.z.array(t.z.string()).optional(),rlsMembership:t.z.record(t.z.string(),t.z.array(t.z.string())).optional(),isSystem:t.z.boolean().default(!1),skipTriggers:t.z.boolean().optional(),accessToken:t.z.string().optional(),transaction:t.z.unknown().optional(),traceId:t.z.string().optional()})),K=n(()=>t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).describe(`Data Engine query filter conditions`)),Mn=n(()=>t.z.union([t.z.record(t.z.string(),t.z.enum([`asc`,`desc`])),t.z.record(t.z.string(),t.z.union([t.z.literal(1),t.z.literal(-1)])),t.z.array(b)]).describe(`Sort order definition`)),q=n(()=>t.z.object({context:jn.optional()})),J=n(()=>q.extend({where:t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).optional(),fields:t.z.array(O).optional(),orderBy:t.z.array(b).optional(),limit:t.z.number().optional(),offset:t.z.number().optional(),top:t.z.number().optional(),cursor:t.z.record(t.z.string(),t.z.unknown()).optional(),search:oe.optional(),expand:t.z.lazy(()=>t.z.record(t.z.string(),k)).optional(),distinct:t.z.boolean().optional()}).describe(`QueryAST-aligned query options for IDataEngine.find() operations`)),Nn=n(()=>q.extend({filter:K.optional(),select:t.z.array(t.z.string()).optional(),sort:Mn.optional(),limit:t.z.number().int().min(1).optional(),skip:t.z.number().int().min(0).optional(),top:t.z.number().int().min(1).optional(),populate:t.z.array(t.z.string()).optional()}).describe(`Query options for IDataEngine.find() operations`)),Pn=n(()=>q.extend({returning:t.z.boolean().default(!0).optional()}).describe(`Options for DataEngine.insert operations`)),Fn=n(()=>q.extend({where:t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).optional(),upsert:t.z.boolean().default(!1).optional(),multi:t.z.boolean().default(!1).optional(),returning:t.z.boolean().default(!1).optional()}).describe(`QueryAST-aligned options for DataEngine.update operations`)),In=n(()=>q.extend({filter:K.optional(),upsert:t.z.boolean().default(!1).optional(),multi:t.z.boolean().default(!1).optional(),returning:t.z.boolean().default(!1).optional()}).describe(`Options for DataEngine.update operations`)),Ln=n(()=>q.extend({where:t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).optional(),multi:t.z.boolean().default(!1).optional()}).describe(`QueryAST-aligned options for DataEngine.delete operations`)),Rn=n(()=>q.extend({filter:K.optional(),multi:t.z.boolean().default(!1).optional()}).describe(`Options for DataEngine.delete operations`)),zn=n(()=>q.extend({where:t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).optional(),groupBy:t.z.array(t.z.string()).optional(),aggregations:t.z.array(w).optional(),timezone:t.z.string().optional()}).describe(`QueryAST-aligned options for DataEngine.aggregate operations`)),Bn=n(()=>q.extend({filter:K.optional(),groupBy:t.z.array(t.z.string()).optional(),aggregations:t.z.array(t.z.object({field:t.z.string(),method:t.z.enum([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`]),alias:t.z.string().optional()})).optional()}).describe(`Options for DataEngine.aggregate operations`)),Vn=n(()=>q.extend({where:t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).optional()}).describe(`QueryAST-aligned options for DataEngine.count operations`)),Hn=n(()=>q.extend({filter:K.optional()}).describe(`Options for DataEngine.count operations`)),Un=n(()=>t.z.object({find:t.z.function().input(t.z.tuple([t.z.string(),J.optional()])).output(t.z.promise(t.z.array(t.z.unknown()))),findOne:t.z.function().input(t.z.tuple([t.z.string(),J.optional()])).output(t.z.promise(t.z.unknown())),insert:t.z.function().input(t.z.tuple([t.z.string(),t.z.union([t.z.record(t.z.string(),t.z.unknown()),t.z.array(t.z.record(t.z.string(),t.z.unknown()))]),Pn.optional()])).output(t.z.promise(t.z.unknown())),update:t.z.function().input(t.z.tuple([t.z.string(),t.z.record(t.z.string(),t.z.unknown()),Fn.optional()])).output(t.z.promise(t.z.unknown())),delete:t.z.function().input(t.z.tuple([t.z.string(),Ln.optional()])).output(t.z.promise(t.z.unknown())),count:t.z.function().input(t.z.tuple([t.z.string(),Vn.optional()])).output(t.z.promise(t.z.number())),aggregate:t.z.function().input(t.z.tuple([t.z.string(),zn])).output(t.z.promise(t.z.array(t.z.unknown())))}).describe(`Standard Data Engine Contract`)),Y={filter:K.optional()},Wn=J.extend({...Y,select:t.z.array(t.z.string()).optional(),sort:Mn.optional(),skip:t.z.number().int().min(0).optional(),populate:t.z.array(t.z.string()).optional()}),Gn=n(()=>t.z.object({method:t.z.literal(`find`),object:t.z.string(),query:Wn.optional()})),Kn=n(()=>t.z.object({method:t.z.literal(`findOne`),object:t.z.string(),query:Wn.optional()})),qn=n(()=>t.z.object({method:t.z.literal(`insert`),object:t.z.string(),data:t.z.union([t.z.record(t.z.string(),t.z.unknown()),t.z.array(t.z.record(t.z.string(),t.z.unknown()))]),options:Pn.optional()})),Jn=n(()=>t.z.object({method:t.z.literal(`update`),object:t.z.string(),data:t.z.record(t.z.string(),t.z.unknown()),id:t.z.union([t.z.string(),t.z.number()]).optional().describe(`ID for single update, or use where in options`),options:Fn.extend(Y).optional()})),Yn=n(()=>t.z.object({method:t.z.literal(`delete`),object:t.z.string(),id:t.z.union([t.z.string(),t.z.number()]).optional().describe(`ID for single delete, or use where in options`),options:Ln.extend(Y).optional()})),Xn=n(()=>t.z.object({method:t.z.literal(`count`),object:t.z.string(),query:Vn.extend(Y).optional()})),Zn=n(()=>t.z.object({method:t.z.literal(`aggregate`),object:t.z.string(),query:zn.extend(Y)})),Qn=n(()=>t.z.object({method:t.z.literal(`execute`),command:t.z.unknown(),options:t.z.record(t.z.string(),t.z.unknown()).optional()})),$n=n(()=>t.z.object({method:t.z.literal(`vectorFind`),object:t.z.string(),vector:t.z.array(t.z.number()),where:t.z.union([t.z.record(t.z.string(),t.z.unknown()),f]).optional(),fields:t.z.array(t.z.string()).optional(),limit:t.z.number().int().default(5).optional(),threshold:t.z.number().optional()})),er=n(()=>t.z.object({method:t.z.literal(`batch`),requests:t.z.array(t.z.discriminatedUnion(`method`,[Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn,$n])),transaction:t.z.boolean().default(!0).optional()})),tr=n(()=>t.z.discriminatedUnion(`method`,[Gn,Kn,qn,Jn,Yn,Xn,Zn,er,Qn,$n]).describe(`Virtual ObjectQL Request Protocol`));t.z.enum([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`percentile`,`median`,`stddev`,`variance`]).describe(`Standard aggregation functions`);var nr=t.z.enum([`asc`,`desc`]).describe(`Sort order direction`);n(()=>t.z.object({field:t.z.string().describe(`Field name to sort by`),order:nr.describe(`Sort direction`)}).describe(`Sort field and direction pair`)),t.z.enum([`insert`,`update`,`delete`,`upsert`]).describe(`Data mutation event types`);var rr=t.z.enum([`read_uncommitted`,`read_committed`,`repeatable_read`,`serializable`,`snapshot`]).describe(`Transaction isolation levels (snake_case standard)`);t.z.enum([`lru`,`lfu`,`ttl`,`fifo`]).describe(`Cache eviction strategy`);var X=n(()=>t.z.object({transaction:t.z.unknown().optional().describe(`Transaction handle`),timeout:t.z.number().optional().describe(`Timeout in ms`),skipCache:t.z.boolean().optional().describe(`Bypass cache`),traceContext:t.z.record(t.z.string(),t.z.string()).optional().describe(`OpenTelemetry context or request ID`),tenantId:t.z.string().optional().describe(`Tenant Isolation identifier`),timezone:t.z.string().optional().describe(`Business reference timezone (IANA) for date-dependent generation, e.g. autonumber date tokens`)})),ir=n(()=>t.z.object({create:t.z.boolean().default(!0).describe(`Supports CREATE operations`),read:t.z.boolean().default(!0).describe(`Supports READ operations`),update:t.z.boolean().default(!0).describe(`Supports UPDATE operations`),delete:t.z.boolean().default(!0).describe(`Supports DELETE operations`),bulkCreate:t.z.boolean().default(!1).describe(`Supports bulk CREATE operations`),bulkUpdate:t.z.boolean().default(!1).describe(`Supports bulk UPDATE operations`),bulkDelete:t.z.boolean().default(!1).describe(`Supports bulk DELETE operations`),transactions:t.z.boolean().default(!1).describe(`Supports ACID transactions`),savepoints:t.z.boolean().default(!1).describe(`Supports transaction savepoints`),isolationLevels:t.z.array(rr).optional().describe(`Supported isolation levels`),queryFilters:t.z.boolean().default(!0).describe(`Supports WHERE clause filtering`),queryAggregations:t.z.boolean().default(!1).describe(`Supports GROUP BY and aggregation functions`),queryDateGranularity:t.z.record(S,t.z.boolean()).optional().describe(`Per-granularity native date bucketing (day/week/month/quarter/year). Missing keys fall back to in-memory bucketing.`),querySorting:t.z.boolean().default(!0).describe(`Supports ORDER BY sorting`),queryPagination:t.z.boolean().default(!0).describe(`Supports LIMIT/OFFSET pagination`),queryWindowFunctions:t.z.boolean().default(!1).describe(`Supports window functions with OVER clause`),querySubqueries:t.z.boolean().default(!1).describe(`Supports subqueries`),queryCTE:t.z.boolean().default(!1).describe(`Supports Common Table Expressions (WITH clause)`),joins:t.z.boolean().default(!1).describe(`Supports SQL joins`),fullTextSearch:t.z.boolean().default(!1).describe(`Supports full-text search`),jsonQuery:t.z.boolean().default(!1).describe(`Supports JSON field querying`),geospatialQuery:t.z.boolean().default(!1).describe(`Supports geospatial queries`),streaming:t.z.boolean().default(!1).describe(`Supports result streaming (cursors/iterators)`),jsonFields:t.z.boolean().default(!1).describe(`Supports JSON field types`),arrayFields:t.z.boolean().default(!1).describe(`Supports array field types`),vectorSearch:t.z.boolean().default(!1).describe(`Supports vector embeddings and similarity search`),autonumber:t.z.boolean().optional().describe(`Driver natively generates persistent autonumber/sequence values`),schemaSync:t.z.boolean().default(!1).describe(`Supports automatic schema synchronization`),batchSchemaSync:t.z.boolean().default(!1).describe(`Supports batched schema sync to reduce schema DDL round-trips`),migrations:t.z.boolean().default(!1).describe(`Supports database migrations`),indexes:t.z.boolean().default(!1).describe(`Supports index creation and management`),connectionPooling:t.z.boolean().default(!1).describe(`Supports connection pooling`),preparedStatements:t.z.boolean().default(!1).describe(`Supports prepared statements (SQL injection prevention)`),queryCache:t.z.boolean().default(!1).describe(`Supports query result caching`)})),ar=n(()=>t.z.object({name:t.z.string().describe(`Driver unique name`),version:t.z.string().describe(`Driver version`),supports:ir,connect:t.z.function().input(t.z.tuple([])).output(t.z.promise(t.z.void())).describe(`Establish connection`),disconnect:t.z.function().input(t.z.tuple([])).output(t.z.promise(t.z.void())).describe(`Close connection`),checkHealth:t.z.function().input(t.z.tuple([])).output(t.z.promise(t.z.boolean())).describe(`Health check`),getPoolStats:t.z.function().input(t.z.tuple([])).output(t.z.object({total:t.z.number(),idle:t.z.number(),active:t.z.number(),waiting:t.z.number()}).optional()).optional().describe(`Get connection pool statistics`),execute:t.z.function().input(t.z.tuple([t.z.unknown(),t.z.array(t.z.unknown()).optional(),X.optional()])).output(t.z.promise(t.z.unknown())).describe(`Execute raw command`),find:t.z.function().input(t.z.tuple([t.z.string(),k,X.optional()])).output(t.z.promise(t.z.array(t.z.record(t.z.string(),t.z.unknown())))).describe(`Find records`),findStream:t.z.function().input(t.z.tuple([t.z.string(),k,X.optional()])).output(t.z.unknown()).describe(`Stream records (AsyncIterable)`),findOne:t.z.function().input(t.z.tuple([t.z.string(),k,X.optional()])).output(t.z.promise(t.z.record(t.z.string(),t.z.unknown()).nullable())).describe(`Find one record`),create:t.z.function().input(t.z.tuple([t.z.string(),t.z.record(t.z.string(),t.z.unknown()),X.optional()])).output(t.z.promise(t.z.record(t.z.string(),t.z.unknown()))).describe(`Create record`),update:t.z.function().input(t.z.tuple([t.z.string(),t.z.string().or(t.z.number()),t.z.record(t.z.string(),t.z.unknown()),X.optional()])).output(t.z.promise(t.z.record(t.z.string(),t.z.unknown()))).describe(`Update record`),upsert:t.z.function().input(t.z.tuple([t.z.string(),t.z.record(t.z.string(),t.z.unknown()),t.z.array(t.z.string()).optional(),X.optional()])).output(t.z.promise(t.z.record(t.z.string(),t.z.unknown()))).describe(`Upsert record`),delete:t.z.function().input(t.z.tuple([t.z.string(),t.z.string().or(t.z.number()),X.optional()])).output(t.z.promise(t.z.boolean())).describe(`Delete record`),count:t.z.function().input(t.z.tuple([t.z.string(),k.optional(),X.optional()])).output(t.z.promise(t.z.number())).describe(`Count records`),bulkCreate:t.z.function().input(t.z.tuple([t.z.string(),t.z.array(t.z.record(t.z.string(),t.z.unknown())),X.optional()])).output(t.z.promise(t.z.array(t.z.record(t.z.string(),t.z.unknown())))),bulkUpdate:t.z.function().input(t.z.tuple([t.z.string(),t.z.array(t.z.object({id:t.z.string().or(t.z.number()),data:t.z.record(t.z.string(),t.z.unknown())})),X.optional()])).output(t.z.promise(t.z.array(t.z.record(t.z.string(),t.z.unknown())))),bulkDelete:t.z.function().input(t.z.tuple([t.z.string(),t.z.array(t.z.string().or(t.z.number())),X.optional()])).output(t.z.promise(t.z.void())),updateMany:t.z.function().input(t.z.tuple([t.z.string(),k,t.z.record(t.z.string(),t.z.unknown()),X.optional()])).output(t.z.promise(t.z.number())).optional(),deleteMany:t.z.function().input(t.z.tuple([t.z.string(),k,X.optional()])).output(t.z.promise(t.z.number())).optional(),beginTransaction:t.z.function().input(t.z.tuple([t.z.object({isolationLevel:rr.optional()}).optional()])).output(t.z.promise(t.z.unknown())).describe(`Start transaction`),commit:t.z.function().input(t.z.tuple([t.z.unknown()])).output(t.z.promise(t.z.void())).describe(`Commit transaction`),rollback:t.z.function().input(t.z.tuple([t.z.unknown()])).output(t.z.promise(t.z.void())).describe(`Rollback transaction`),syncSchema:t.z.function().input(t.z.tuple([t.z.string(),t.z.unknown(),X.optional()])).output(t.z.promise(t.z.void())).describe(`Sync object schema to DB`),syncSchemasBatch:t.z.function().input(t.z.tuple([t.z.array(t.z.object({object:t.z.string(),schema:t.z.unknown()})),X.optional()])).output(t.z.promise(t.z.void())).optional().describe(`Batch sync multiple schemas in one round-trip`),dropTable:t.z.function().input(t.z.tuple([t.z.string(),X.optional()])).output(t.z.promise(t.z.void())),explain:t.z.function().input(t.z.tuple([t.z.string(),k,X.optional()])).output(t.z.promise(t.z.unknown())).optional()})),or=n(()=>t.z.object({min:t.z.number().min(0).default(2).describe(`Minimum number of connections in pool`),max:t.z.number().min(1).default(10).describe(`Maximum number of connections in pool`),idleTimeoutMillis:t.z.number().min(0).default(3e4).describe(`Time in ms before idle connection is closed`),connectionTimeoutMillis:t.z.number().min(0).default(5e3).describe(`Time in ms to wait for available connection`)})),sr=n(()=>t.z.object({name:t.z.string().describe(`Driver instance name`),type:t.z.enum([`sql`,`nosql`,`cache`,`search`,`graph`,`timeseries`]).describe(`Driver type category`),capabilities:ir.describe(`Driver capability flags`),connectionString:t.z.string().optional().describe(`Database connection string (driver-specific format)`),poolConfig:or.optional().describe(`Connection pool configuration`)})),cr=n(()=>t.z.enum([`postgresql`,`mysql`,`sqlite`,`mssql`,`oracle`,`mariadb`])),lr=n(()=>t.z.object({text:t.z.string().describe(`SQL type for text fields (e.g., VARCHAR, TEXT)`),number:t.z.string().describe(`SQL type for number fields (e.g., NUMERIC, DECIMAL, INT)`),boolean:t.z.string().describe(`SQL type for boolean fields (e.g., BOOLEAN, BIT)`),date:t.z.string().describe(`SQL type for date fields (e.g., DATE)`),datetime:t.z.string().describe(`SQL type for datetime fields (e.g., TIMESTAMP, DATETIME)`),json:t.z.string().optional().describe(`SQL type for JSON fields (e.g., JSON, JSONB)`),uuid:t.z.string().optional().describe(`SQL type for UUID fields (e.g., UUID, CHAR(36))`),binary:t.z.string().optional().describe(`SQL type for binary fields (e.g., BLOB, BYTEA)`)})),ur=n(()=>t.z.object({rejectUnauthorized:t.z.boolean().default(!0).describe(`Reject connections with invalid certificates`),ca:t.z.string().optional().describe(`CA certificate file path or content`),cert:t.z.string().optional().describe(`Client certificate file path or content`),key:t.z.string().optional().describe(`Client private key file path or content`)}).refine(e=>e.cert!==void 0==(e.key!==void 0),{message:`Client certificate (cert) and private key (key) must be provided together`})),dr=n(()=>sr.extend({type:t.z.literal(`sql`).describe(`Driver type must be "sql"`),dialect:cr.describe(`SQL database dialect`),dataTypeMapping:lr.describe(`SQL data type mapping configuration`),ssl:t.z.boolean().default(!1).describe(`Enable SSL/TLS connection`),sslConfig:ur.optional().describe(`SSL/TLS configuration (required when ssl is true)`)}).refine(e=>!(e.ssl&&!e.sslConfig),{message:`sslConfig is required when ssl is true`})),fr={text:`TEXT`,number:`REAL`,boolean:`INTEGER`,date:`TEXT`,datetime:`TEXT`,json:`TEXT`,uuid:`TEXT`,binary:`BLOB`},pr={supportsAddColumn:!0,supportsRenameColumn:!0,supportsDropColumn:!0,supportsModifyColumn:!1,supportsAddConstraint:!1,rebuildStrategy:`create_copy_drop_rename`},mr=n(()=>t.z.enum([`mongodb`,`couchdb`,`dynamodb`,`cassandra`,`redis`,`elasticsearch`,`neo4j`,`orientdb`])),hr=n(()=>t.z.enum([`find`,`findOne`,`insert`,`update`,`delete`,`aggregate`,`mapReduce`,`count`,`distinct`,`createIndex`,`dropIndex`])),Z=n(()=>t.z.enum([`all`,`quorum`,`one`,`local_quorum`,`each_quorum`,`eventual`])),gr=n(()=>t.z.enum([`single`,`compound`,`unique`,`text`,`geospatial`,`hashed`,`ttl`,`sparse`])),_r=n(()=>t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable sharding`),shardKey:t.z.string().optional().describe(`Field to use as shard key`),shardingStrategy:t.z.enum([`hash`,`range`,`zone`]).optional().describe(`Sharding strategy`),numShards:t.z.number().int().positive().optional().describe(`Number of shards`)})),vr=n(()=>t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable replication`),replicaSetName:t.z.string().optional().describe(`Replica set name`),replicas:t.z.number().int().positive().optional().describe(`Number of replicas`),readPreference:t.z.enum([`primary`,`primaryPreferred`,`secondary`,`secondaryPreferred`,`nearest`]).optional().describe(`Read preference for replica set`),writeConcern:t.z.enum([`majority`,`acknowledged`,`unacknowledged`]).optional().describe(`Write concern level`)})),yr=n(()=>t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable schema validation`),validationLevel:t.z.enum([`strict`,`moderate`,`off`]).optional().describe(`Validation strictness`),validationAction:t.z.enum([`error`,`warn`]).optional().describe(`Action on validation failure`),jsonSchema:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`JSON Schema for validation`)})),br=n(()=>t.z.object({text:t.z.string().describe(`NoSQL type for text fields`),number:t.z.string().describe(`NoSQL type for number fields`),boolean:t.z.string().describe(`NoSQL type for boolean fields`),date:t.z.string().describe(`NoSQL type for date fields`),datetime:t.z.string().describe(`NoSQL type for datetime fields`),json:t.z.string().optional().describe(`NoSQL type for JSON/object fields`),uuid:t.z.string().optional().describe(`NoSQL type for UUID fields`),binary:t.z.string().optional().describe(`NoSQL type for binary fields`),array:t.z.string().optional().describe(`NoSQL type for array fields`),objectId:t.z.string().optional().describe(`NoSQL type for ObjectID fields (MongoDB)`),geopoint:t.z.string().optional().describe(`NoSQL type for geospatial point fields`)})),xr=n(()=>sr.extend({type:t.z.literal(`nosql`).describe(`Driver type must be "nosql"`),databaseType:mr.describe(`Specific NoSQL database type`),dataTypeMapping:br.describe(`NoSQL data type mapping configuration`),consistency:Z.optional().describe(`Consistency level for operations`),replication:vr.optional().describe(`Replication configuration`),sharding:_r.optional().describe(`Sharding configuration`),schemaValidation:yr.optional().describe(`Document schema validation`),region:t.z.string().optional().describe(`AWS region (for managed NoSQL services)`),accessKeyId:t.z.string().optional().describe(`AWS access key ID`),secretAccessKey:t.z.string().optional().describe(`AWS secret access key`),ttlField:t.z.string().optional().describe(`Field name for TTL (auto-deletion)`),maxDocumentSize:t.z.number().int().positive().optional().describe(`Maximum document size in bytes`),collectionPrefix:t.z.string().optional().describe(`Prefix for collection/table names`)})),Sr=n(()=>t.z.object({consistency:Z.optional().describe(`Consistency level override`),readFromSecondary:t.z.boolean().optional().describe(`Allow reading from secondary replicas`),projection:t.z.record(t.z.string(),t.z.union([t.z.literal(0),t.z.literal(1)])).optional().describe(`Field projection`),timeout:t.z.number().int().positive().optional().describe(`Query timeout (ms)`),useCursor:t.z.boolean().optional().describe(`Use cursor instead of loading all results`),batchSize:t.z.number().int().positive().optional().describe(`Cursor batch size`),profile:t.z.boolean().optional().describe(`Enable query profiling`),hint:t.z.string().optional().describe(`Index hint for query optimization`)})),Cr=n(()=>t.z.object({operator:t.z.string().describe(`Aggregation operator (e.g., $match, $group, $sort)`),options:t.z.record(t.z.string(),t.z.unknown()).describe(`Stage-specific options`)})),wr=n(()=>t.z.object({collection:t.z.string().describe(`Collection/table name`),stages:t.z.array(Cr).describe(`Aggregation pipeline stages`),options:Sr.optional().describe(`Query options`)})),Tr=n(()=>t.z.object({name:t.z.string().describe(`Index name`),type:gr.describe(`Index type`),fields:t.z.array(t.z.object({field:t.z.string().describe(`Field name`),order:t.z.enum([`asc`,`desc`,`text`,`2dsphere`]).optional().describe(`Index order or type`)})).describe(`Fields to index`),unique:t.z.boolean().default(!1).describe(`Enforce uniqueness`),sparse:t.z.boolean().default(!1).describe(`Sparse index`),expireAfterSeconds:t.z.number().int().positive().optional().describe(`TTL in seconds`),partialFilterExpression:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Partial index filter`),background:t.z.boolean().default(!1).describe(`Create index in background`)})),Er=n(()=>t.z.object({readConcern:t.z.enum([`local`,`majority`,`linearizable`,`snapshot`]).optional().describe(`Read concern level`),writeConcern:t.z.enum([`majority`,`acknowledged`,`unacknowledged`]).optional().describe(`Write concern level`),readPreference:t.z.enum([`primary`,`primaryPreferred`,`secondary`,`secondaryPreferred`,`nearest`]).optional().describe(`Read preference`),maxCommitTimeMS:t.z.number().int().positive().optional().describe(`Transaction commit timeout (ms)`)})),Q=t.z.enum([`insert`,`update`,`upsert`,`replace`,`ignore`]),Dr=n(()=>t.z.object({object:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Target Object Name`),externalId:t.z.string().default(`name`).describe(`Field match for uniqueness check`),mode:Q.default(`upsert`).describe(`Conflict resolution strategy`),env:t.z.array(t.z.enum([`prod`,`dev`,`test`])).default([`prod`,`dev`,`test`]).describe(`Applicable environments`),records:t.z.array(t.z.record(t.z.string(),t.z.unknown())).describe(`Data records`)}));function Or(e,t){return Dr.parse({...t,object:e.name})}var kr=W({schemaId:`object`,type:`simple`,sections:[{name:`basics`,label:`Basics`,description:`Identity, labels, and taxonomy.`,columns:2,fields:[{field:`name`,type:`text`,required:!0,immutable:!0,colSpan:1,helpText:`snake_case unique identifier (immutable after creation)`},{field:`label`,type:`text`,colSpan:1,helpText:`Singular display name (e.g. "Account")`},{field:`pluralLabel`,type:`text`,colSpan:1,helpText:`Plural display name (e.g. "Accounts")`},{field:`icon`,type:`text`,colSpan:1,helpText:`Lucide icon name (e.g. "building", "users")`},{field:`description`,type:`textarea`,colSpan:2,helpText:`Developer documentation`},{field:`tags`,type:`tags`,colSpan:2,helpText:`Categorization tags (e.g. "sales", "system")`},{field:`active`,type:`boolean`,colSpan:1,helpText:`Is the object active and usable`},{field:`isSystem`,type:`boolean`,colSpan:1,helpText:`System object (protected from deletion)`},{field:`abstract`,type:`boolean`,colSpan:1,helpText:`Abstract base (cannot be instantiated)`}]},{name:`fields`,label:`Fields`,description:`Define the data model — each entry becomes a column in the database table.`,fields:[{field:`fields`,type:`record`,required:!0,helpText:`Add the columns this object will store`,keyField:{field:`name`,label:`Name`,placeholder:`snake_case_identifier`,helpText:`snake_case machine name (used as column name and API key)`,regex:`^[a-z_][a-z0-9_]*$`,immutable:!0},fields:[{field:`label`,type:`text`,helpText:`Display label`},{field:`type`,type:`select`,required:!0,helpText:`Field type`,options:[{label:`Text`,value:`text`},{label:`Textarea`,value:`textarea`},{label:`Email`,value:`email`},{label:`URL`,value:`url`},{label:`Phone`,value:`phone`},{label:`Password`,value:`password`},{label:`Markdown`,value:`markdown`},{label:`HTML`,value:`html`},{label:`Rich Text`,value:`richtext`},{label:`Number`,value:`number`},{label:`Currency`,value:`currency`},{label:`Percent`,value:`percent`},{label:`Date`,value:`date`},{label:`Date & Time`,value:`datetime`},{label:`Time`,value:`time`},{label:`Boolean`,value:`boolean`},{label:`Toggle`,value:`toggle`},{label:`Select`,value:`select`},{label:`Multiselect`,value:`multiselect`},{label:`Radio`,value:`radio`},{label:`Checkboxes`,value:`checkboxes`},{label:`Lookup (reference)`,value:`lookup`},{label:`Master–Detail`,value:`master_detail`},{label:`Tree`,value:`tree`},{label:`Image`,value:`image`},{label:`File`,value:`file`},{label:`Avatar`,value:`avatar`},{label:`Video`,value:`video`},{label:`Audio`,value:`audio`},{label:`Formula (computed)`,value:`formula`},{label:`Summary (rollup)`,value:`summary`},{label:`Autonumber`,value:`autonumber`},{label:`Composite (embedded)`,value:`composite`},{label:`Repeater (embedded array)`,value:`repeater`},{label:`Record (keyed map)`,value:`record`},{label:`Location (GPS)`,value:`location`},{label:`Address`,value:`address`},{label:`Code`,value:`code`},{label:`JSON`,value:`json`},{label:`Color`,value:`color`},{label:`Rating`,value:`rating`},{label:`Slider`,value:`slider`},{label:`Signature`,value:`signature`},{label:`QR / Barcode`,value:`qrcode`},{label:`Progress`,value:`progress`},{label:`Tags`,value:`tags`},{label:`Vector embedding`,value:`vector`}]},{field:`description`,type:`textarea`,helpText:`Developer documentation for this column`},{field:`required`,type:`boolean`,helpText:`Must be set on every record`},{field:`unique`,type:`boolean`,helpText:`Disallow duplicate values`},{field:`indexed`,type:`boolean`,helpText:`Create a database index for faster querying`},{field:`readonly`,type:`boolean`,helpText:`Visible but never user-editable`},{field:`immutable`,type:`boolean`,helpText:`Editable on create, locked thereafter`},{field:`hidden`,type:`boolean`,helpText:`Hidden from default UI`},{field:`searchable`,type:`boolean`,helpText:`Include in full-text search`},{field:`sortable`,type:`boolean`,helpText:`Allow sorting on this column`},{field:`filterable`,type:`boolean`,helpText:`Allow filtering on this column`},{field:`defaultValue`,type:`text`,helpText:`Default value for new records (JSON literal)`},{field:`placeholder`,type:`text`,helpText:`Placeholder hint`},{field:`maxLength`,type:`number`,helpText:`Max characters`,visibleOn:`type in ['text','textarea','email','url','phone','password','markdown','html','richtext']`},{field:`minLength`,type:`number`,helpText:`Min characters`,visibleOn:`type in ['text','textarea','email','url','phone','password','markdown','html','richtext']`},{field:`min`,type:`number`,helpText:`Minimum value`,visibleOn:`type in ['number','currency','percent','rating','slider','progress']`},{field:`max`,type:`number`,helpText:`Maximum value`,visibleOn:`type in ['number','currency','percent','rating','slider','progress']`},{field:`precision`,type:`number`,helpText:`Total digits`,visibleOn:`type in ['number','currency','percent']`},{field:`scale`,type:`number`,helpText:`Decimal places`,visibleOn:`type in ['number','currency','percent']`},{field:`options`,type:`repeater`,helpText:`Available choices`,visibleOn:`type in ['select','multiselect','radio','checkboxes']`,fields:[{field:`label`,type:`text`,required:!0},{field:`value`,type:`text`,required:!0},{field:`color`,type:`color`},{field:`icon`,type:`text`,helpText:`Lucide icon name`},{field:`description`,type:`text`}]},{field:`reference`,type:`text`,helpText:`Target object name`,visibleOn:`type in ['lookup','master_detail','tree']`},{field:`referenceFilter`,type:`code`,language:`expression`,helpText:`CEL filter applied to the picker`,visibleOn:`type in ['lookup','master_detail']`},{field:`cascadeDelete`,type:`boolean`,helpText:`Delete children when parent is deleted`,visibleOn:`type == 'master_detail'`},{field:`multiple`,type:`boolean`,helpText:`Allow selecting multiple records`,visibleOn:`type in ['lookup']`},{field:`formula`,type:`code`,language:`expression`,helpText:`CEL formula expression`,visibleOn:`type == 'formula'`},{field:`returnType`,type:`select`,helpText:`Result type for formulas`,visibleOn:`type == 'formula'`,options:[{label:`Text`,value:`text`},{label:`Number`,value:`number`},{label:`Boolean`,value:`boolean`},{label:`Date`,value:`date`},{label:`Datetime`,value:`datetime`},{label:`Currency`,value:`currency`}]},{field:`summaryType`,type:`select`,helpText:`Aggregation`,visibleOn:`type == 'summary'`,options:[{label:`Count`,value:`count`},{label:`Sum`,value:`sum`},{label:`Avg`,value:`avg`},{label:`Min`,value:`min`},{label:`Max`,value:`max`}]},{field:`summaryField`,type:`text`,helpText:`Field on child object to aggregate`,visibleOn:`type == 'summary'`},{field:`displayFormat`,type:`text`,helpText:`e.g. "INV-{0000}"`,visibleOn:`type == 'autonumber'`},{field:`startingNumber`,type:`number`,helpText:`Starting sequence value`,visibleOn:`type == 'autonumber'`},{field:`language`,type:`text`,helpText:`Editor language (e.g. sql, javascript)`,visibleOn:`type == 'code'`},{field:`validation`,type:`code`,language:`expression`,helpText:`CEL predicate — must evaluate true`},{field:`errorMessage`,type:`text`,helpText:`Shown when validation fails`},{field:`audit`,type:`boolean`,helpText:`Audit changes to this field`},{field:`trackHistory`,type:`boolean`,helpText:`Keep change history`},{field:`pii`,type:`boolean`,helpText:`Personally identifiable information`},{field:`encrypted`,type:`boolean`,helpText:`Encrypt at rest`}]}]},{name:`capabilities`,label:`Capabilities`,description:`System features and API exposure.`,collapsible:!0,collapsed:!0,fields:[{field:`capabilities`,type:`composite`,helpText:`Enable/disable system features`,fields:[{field:`trackHistory`,type:`boolean`},{field:`searchable`,type:`boolean`},{field:`apiEnabled`,type:`boolean`},{field:`files`,type:`boolean`},{field:`feeds`,type:`boolean`},{field:`activities`,type:`boolean`},{field:`trash`,type:`boolean`},{field:`mru`,type:`boolean`},{field:`clone`,type:`boolean`}]}]},{name:`advanced`,label:`Advanced`,description:`State machines, actions, and storage.`,collapsible:!0,collapsed:!0,fields:[{field:`datasource`,type:`text`,helpText:`Target datasource ID (default: "default")`}]}]}),Ar=W({schemaId:`field`,type:`simple`,sections:[{name:`basics`,label:`Basics`,description:`Core field identity and constraints.`,columns:2,fields:[{field:`name`,required:!0,immutable:!0,colSpan:1,helpText:`Unique identifier (snake_case, immutable after creation)`},{field:`label`,required:!0,colSpan:1,helpText:`Display name for users`},{field:`type`,required:!0,colSpan:1,helpText:`Data type of this field`},{field:`group`,colSpan:1,helpText:`Group name for form layout`},{field:`description`,widget:`textarea`,colSpan:2,helpText:`Help text shown to users`},{field:`required`,colSpan:1,helpText:`User must provide a value`},{field:`unique`,colSpan:1,helpText:`No two records can have the same value`},{field:`multiple`,colSpan:1,helpText:`Allow multiple values (for select/lookup)`}]},{name:`configuration`,label:`Configuration`,description:`Field-type specific settings (visible blocks depend on the chosen type).`,fields:[{field:`defaultValue`,helpText:`Default value for new records`},{field:`minLength`,visibleOn:`data.type == 'text' || data.type == 'textarea' || data.type == 'email'`,helpText:`Minimum character length`},{field:`maxLength`,visibleOn:`data.type == 'text' || data.type == 'textarea' || data.type == 'email'`,helpText:`Maximum character length`},{field:`min`,visibleOn:`data.type == 'number' || data.type == 'currency'`,helpText:`Minimum value`},{field:`max`,visibleOn:`data.type == 'number' || data.type == 'currency'`,helpText:`Maximum value`},{field:`precision`,visibleOn:`data.type == 'currency' || data.type == 'number'`,helpText:`Decimal places (e.g., 2 for $10.50)`},{field:`scale`,visibleOn:`data.type == 'number'`,helpText:`Number of decimal digits`},{field:`options`,type:`repeater`,visibleOn:`data.type == 'select' || data.type == 'multiselect'`,helpText:`Available options (label/value pairs)`},{field:`reference`,widget:`ref:object`,visibleOn:`data.type == 'lookup' || data.type == 'master_detail'`,helpText:`Referenced object name`},{field:`referenceFilters`,widget:`string-tags`,visibleOn:`data.type == 'lookup' || data.type == 'master_detail'`,helpText:`Filter expressions (e.g., "active = true")`},{field:`deleteBehavior`,visibleOn:`data.type == 'lookup' || data.type == 'master_detail'`,helpText:`What happens when referenced record is deleted`}]},{name:`formula`,label:`Formula & Computed`,description:`Calculated values and roll-up summaries.`,collapsible:!0,collapsed:!0,fields:[{field:`expression`,widget:`textarea`,helpText:`CEL expression to calculate this field (makes it read-only)`},{field:`summaryOperations`,type:`composite`,helpText:`Roll-up summary configuration (for parent-child relationships)`}]},{name:`advanced`,label:`Advanced`,description:`Database, UI, audit, and security settings.`,collapsible:!0,collapsed:!0,columns:2,fields:[{field:`columnName`,colSpan:2,helpText:`Physical column name in database (defaults to field name)`},{field:`index`,colSpan:1,helpText:`Create database index for faster queries`},{field:`externalId`,colSpan:1,helpText:`Mark as external ID for upsert operations`},{field:`readonly`,colSpan:1,helpText:`Field is read-only in forms`},{field:`hidden`,colSpan:1,helpText:`Hide field from default UI views`},{field:`searchable`,colSpan:1,helpText:`Include in global search results`},{field:`sortable`,colSpan:1,helpText:`Allow sorting lists by this field`}]}]}),jr=W({schemaId:`hook`,type:`simple`,sections:[{label:`Identity`,description:`What this hook is and when it fires.`,columns:2,fields:[{field:`name`,type:`text`,required:!0,immutable:!0,colSpan:1,helpText:`snake_case identifier (immutable after creation)`},{field:`label`,type:`text`,colSpan:1},{field:`description`,type:`textarea`,colSpan:2},{field:`object`,type:`text`,required:!0,colSpan:1,helpText:`Target object name (or "*" for global)`},{field:`events`,type:`tags`,required:!0,colSpan:1,helpText:`Lifecycle events (e.g. beforeInsert, afterUpdate)`},{field:`priority`,type:`number`,colSpan:1,helpText:`Lower numbers run first`}]},{label:`Body`,description:`Inline expression or sandboxed JavaScript executed when the hook fires.`,fields:[{field:`body`,type:`composite`,helpText:`Either an L1 expression or an L2 sandboxed JS body`,fields:[{field:`language`,type:`select`,required:!0,helpText:`expression = pure formula; js = sandboxed JavaScript`,options:[{label:`Expression (L1)`,value:`expression`},{label:`JavaScript (L2 sandboxed)`,value:`js`}]},{field:`source`,type:`code`,language:`javascript`,required:!0,helpText:`Function body source — no top-level imports`},{field:`capabilities`,type:`tags`,helpText:`Allowed ctx APIs (api.read, api.write, crypto.uuid, log, …)`},{field:`timeoutMs`,type:`number`,helpText:`Per-invocation timeout (ms)`}]}]},{label:`Legacy handler`,description:`Function name reference — deprecated in favour of body.`,collapsible:!0,collapsed:!0,fields:[{field:`handler`,type:`text`,helpText:"Handler function name (deprecated — prefer `body`)"}]},{label:`Execution`,collapsible:!0,collapsed:!0,columns:2,fields:[{field:`async`,type:`boolean`,colSpan:1,helpText:`Run in background, do not block the transaction`},{field:`onError`,type:`select`,colSpan:1,options:[{label:`Abort`,value:`abort`},{label:`Log`,value:`log`}]},{field:`timeout`,type:`number`,colSpan:1,helpText:`Abort the hook after N milliseconds`},{field:`condition`,type:`code`,language:`javascript`,colSpan:2,helpText:`Optional formula — skip the hook when this evaluates to false`},{field:`retryPolicy`,type:`composite`,colSpan:2,helpText:`Retry on failure — most useful for async hooks`,fields:[{field:`maxRetries`,type:`number`,helpText:`Maximum retry attempts`},{field:`backoffMs`,type:`number`,helpText:`Delay between retries (ms)`}]}]}]}),Mr=n(()=>t.z.object({field:t.z.string().describe(`Source field name containing the reference value`),targetObject:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Target object name (snake_case)`),targetField:t.z.string().default(`name`).describe(`Field on target object used for matching`),fieldType:t.z.enum([`lookup`,`master_detail`,`user`]).describe(`Relationship field type`)}).describe(`Describes how a field reference is resolved during seed loading`)),Nr=n(()=>t.z.object({object:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Object name (snake_case)`),dependsOn:t.z.array(t.z.string()).describe(`Objects this object depends on`),references:t.z.array(Mr).describe(`Field-level reference details`)}).describe(`Object node in the seed data dependency graph`)),Pr=n(()=>t.z.object({nodes:t.z.array(Nr).describe(`All objects in the dependency graph`),insertOrder:t.z.array(t.z.string()).describe(`Topologically sorted insert order`),circularDependencies:t.z.array(t.z.array(t.z.string())).default([]).describe(`Circular dependency chains (e.g., [["a", "b", "a"]])`)}).describe(`Complete object dependency graph for seed data loading`)),Fr=n(()=>t.z.object({sourceObject:t.z.string().describe(`Object with the broken reference`),field:t.z.string().describe(`Field name with unresolved reference`),targetObject:t.z.string().describe(`Target object searched for the reference`),targetField:t.z.string().describe(`ExternalId field used for matching`),attemptedValue:t.z.unknown().describe(`Value that failed to resolve`),recordIndex:t.z.number().int().min(0).describe(`Index of the record in the dataset`),message:t.z.string().describe(`Human-readable error description`)}).describe(`Actionable error for a failed reference resolution`)),Ir=t.z.object({user:t.z.object({id:t.z.string().min(1),role:t.z.string().optional(),email:t.z.string().optional()}).optional().describe(`Subject bound to os.user in seed CEL expressions`),org:t.z.object({id:t.z.string().min(1),tier:t.z.string().optional()}).optional().describe(`Organization bound to os.org in seed CEL expressions`)}).describe(`Identity context for resolving os.user / os.org in seed CEL values`),Lr=n(()=>t.z.object({dryRun:t.z.boolean().default(!1).describe(`Validate references without writing data`),haltOnError:t.z.boolean().default(!1).describe(`Stop on first reference resolution error`),multiPass:t.z.boolean().default(!0).describe(`Enable multi-pass loading for circular dependencies`),defaultMode:Q.default(`upsert`).describe(`Default conflict resolution strategy`),batchSize:t.z.number().int().min(1).default(1e3).describe(`Maximum records per batch insert/upsert`),transaction:t.z.boolean().default(!1).describe(`Wrap entire load in a transaction (all-or-nothing)`),env:t.z.enum([`prod`,`dev`,`test`]).optional().describe(`Only load datasets matching this environment`),organizationId:t.z.string().min(1).optional().describe(`Target organization id for per-tenant seed replay`),identity:Ir.optional().describe(`Identity bound to os.user / os.org when resolving CEL seed values`)}).describe(`Seed data loader configuration`)),Rr=n(()=>t.z.object({object:t.z.string().describe(`Object that was loaded`),mode:Q.describe(`Import mode used`),inserted:t.z.number().int().min(0).describe(`Records inserted`),updated:t.z.number().int().min(0).describe(`Records updated`),skipped:t.z.number().int().min(0).describe(`Records skipped`),errored:t.z.number().int().min(0).describe(`Records with errors`),total:t.z.number().int().min(0).describe(`Total records in dataset`),referencesResolved:t.z.number().int().min(0).describe(`References resolved via externalId`),referencesDeferred:t.z.number().int().min(0).describe(`References deferred to second pass`),errors:t.z.array(Fr).default([]).describe(`Reference resolution errors`)}).describe(`Result of loading a single dataset`)),zr=n(()=>t.z.object({success:t.z.boolean().describe(`Overall success status`),dryRun:t.z.boolean().describe(`Whether this was a dry-run`),dependencyGraph:Pr.describe(`Object dependency graph`),results:t.z.array(Rr).describe(`Per-object load results`),errors:t.z.array(Fr).describe(`All reference resolution errors`),summary:t.z.object({objectsProcessed:t.z.number().int().min(0).describe(`Total objects processed`),totalRecords:t.z.number().int().min(0).describe(`Total records across all objects`),totalInserted:t.z.number().int().min(0).describe(`Total records inserted`),totalUpdated:t.z.number().int().min(0).describe(`Total records updated`),totalSkipped:t.z.number().int().min(0).describe(`Total records skipped`),totalErrored:t.z.number().int().min(0).describe(`Total records with errors`),totalReferencesResolved:t.z.number().int().min(0).describe(`Total references resolved`),totalReferencesDeferred:t.z.number().int().min(0).describe(`Total references deferred`),circularDependencyCount:t.z.number().int().min(0).describe(`Circular dependency chains detected`),durationMs:t.z.number().min(0).describe(`Load duration in milliseconds`)}).describe(`Summary statistics`)}).describe(`Complete seed loader result`)),Br=n(()=>t.z.object({seeds:t.z.array(Dr).min(1).describe(`Seeds to load`),config:Lr.default(()=>Lr.parse({})).describe(`Loader configuration`)}).describe(`Seed loader request with datasets and configuration`)),Vr=n(()=>t.z.object({versionNumber:t.z.number().describe(`Version number`),createdAt:t.z.number().describe(`Creation timestamp`),createdBy:t.z.string().describe(`Creator user ID`),size:t.z.number().describe(`File size in bytes`),checksum:t.z.string().describe(`File checksum`),downloadUrl:t.z.string().url().describe(`Download URL`),isLatest:t.z.boolean().optional().default(!1).describe(`Is latest version`)})),Hr=n(()=>t.z.object({id:t.z.string().describe(`Template ID`),name:t.z.string().describe(`Template name`),description:t.z.string().optional().describe(`Template description`),fileUrl:t.z.string().url().describe(`Template file URL`),fileType:t.z.string().describe(`File MIME type`),placeholders:t.z.array(t.z.object({key:t.z.string().describe(`Placeholder key`),label:t.z.string().describe(`Placeholder label`),type:t.z.enum([`text`,`number`,`date`,`image`]).describe(`Placeholder type`),required:t.z.boolean().optional().default(!1).describe(`Is required`)})).describe(`Template placeholders`)})),Ur=n(()=>t.z.object({provider:t.z.enum([`docusign`,`adobe-sign`,`hellosign`,`custom`]).describe(`E-signature provider`),enabled:t.z.boolean().optional().default(!1).describe(`E-signature enabled`),signers:t.z.array(t.z.object({email:t.z.string().email().describe(`Signer email`),name:t.z.string().describe(`Signer name`),role:t.z.string().describe(`Signer role`),order:t.z.number().describe(`Signing order`)})).describe(`Document signers`),expirationDays:t.z.number().optional().default(30).describe(`Expiration days`),reminderDays:t.z.number().optional().default(7).describe(`Reminder interval days`)})),Wr=n(()=>t.z.object({id:t.z.string().describe(`Document ID`),name:t.z.string().describe(`Document name`),description:t.z.string().optional().describe(`Document description`),fileType:t.z.string().describe(`File MIME type`),fileSize:t.z.number().describe(`File size in bytes`),category:t.z.string().optional().describe(`Document category`),tags:t.z.array(t.z.string()).optional().describe(`Document tags`),versioning:t.z.object({enabled:t.z.boolean().describe(`Versioning enabled`),versions:t.z.array(Vr).describe(`Version history`),majorVersion:t.z.number().describe(`Major version`),minorVersion:t.z.number().describe(`Minor version`)}).optional().describe(`Version control`),template:Hr.optional().describe(`Document template`),eSignature:Ur.optional().describe(`E-signature config`),access:t.z.object({isPublic:t.z.boolean().optional().default(!1).describe(`Public access`),sharedWith:t.z.array(t.z.string()).optional().describe(`Shared with`),expiresAt:t.z.number().optional().describe(`Access expiration`)}).optional().describe(`Access control`),metadata:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Custom metadata`)})),Gr=n(()=>t.z.discriminatedUnion(`type`,[t.z.object({type:t.z.literal(`constant`),value:t.z.unknown().describe(`Constant value to use`)}).describe(`Set a constant value`),t.z.object({type:t.z.literal(`cast`),targetType:t.z.enum([`string`,`number`,`boolean`,`date`]).describe(`Target data type`)}).describe(`Cast to a specific data type`),t.z.object({type:t.z.literal(`lookup`),table:t.z.string().describe(`Lookup table name`),keyField:t.z.string().describe(`Field to match on`),valueField:t.z.string().describe(`Field to retrieve`)}).describe(`Lookup value from another table`),t.z.object({type:t.z.literal(`javascript`),expression:j.describe(`JS expression (dialect="js" recommended). e.g. value.toUpperCase()`)}).describe(`Custom JavaScript transformation`),t.z.object({type:t.z.literal(`map`),mappings:t.z.record(t.z.string(),t.z.unknown()).describe(`Value mappings (e.g., {"Active": "active"})`)}).describe(`Map values using a dictionary`)])),Kr=n(()=>t.z.object({source:t.z.string().describe(`Source field name`),target:t.z.string().describe(`Target field name`),transform:Gr.optional().describe(`Transformation to apply`),defaultValue:t.z.unknown().optional().describe(`Default if source is null/undefined`)})),qr=n(()=>t.z.object({id:t.z.string().describe(`Data source ID`),name:t.z.string().describe(`Data source name`),type:t.z.enum([`odata`,`rest-api`,`graphql`,`custom`]).describe(`Protocol type`),endpoint:t.z.string().url().describe(`API endpoint URL`),authentication:t.z.object({type:t.z.enum([`oauth2`,`api-key`,`basic`,`none`]).describe(`Auth type`),config:t.z.record(t.z.string(),t.z.unknown()).describe(`Auth configuration`)}).describe(`Authentication`)})),Jr=n(()=>Kr.extend({type:t.z.string().optional().describe(`Field type`),readonly:t.z.boolean().optional().default(!0).describe(`Read-only field`)})),Yr=n(()=>t.z.object({fieldName:t.z.string().describe(`Field name`),dataSource:qr.describe(`External data source`),query:t.z.object({endpoint:t.z.string().describe(`Query endpoint path`),method:t.z.enum([`GET`,`POST`]).optional().default(`GET`).describe(`HTTP method`),parameters:t.z.record(t.z.string(),t.z.unknown()).optional().describe(`Query parameters`)}).describe(`Query configuration`),fieldMappings:t.z.array(Jr).describe(`Field mappings`),caching:t.z.object({enabled:t.z.boolean().optional().default(!0).describe(`Cache enabled`),ttl:t.z.number().optional().default(300).describe(`Cache TTL (seconds)`),strategy:t.z.enum([`lru`,`lfu`,`ttl`]).optional().default(`ttl`).describe(`Cache strategy`)}).optional().describe(`Caching configuration`),fallback:t.z.object({enabled:t.z.boolean().optional().default(!0).describe(`Fallback enabled`),defaultValue:t.z.unknown().optional().describe(`Default fallback value`),showError:t.z.boolean().optional().default(!0).describe(`Show error to user`)}).optional().describe(`Fallback configuration`),rateLimit:t.z.object({requestsPerSecond:t.z.number().describe(`Requests per second limit`),burstSize:t.z.number().optional().describe(`Burst size`)}).optional().describe(`Rate limiting`),retry:t.z.object({maxRetries:t.z.number().min(0).default(3).describe(`Maximum retry attempts`),initialDelayMs:t.z.number().default(1e3).describe(`Initial retry delay in milliseconds`),maxDelayMs:t.z.number().default(3e4).describe(`Maximum retry delay in milliseconds`),backoffMultiplier:t.z.number().default(2).describe(`Exponential backoff multiplier`),retryableStatusCodes:t.z.array(t.z.number()).default([429,500,502,503,504]).describe(`HTTP status codes that are retryable`)}).optional().describe(`Retry configuration with exponential backoff`),transform:t.z.object({request:t.z.object({headers:t.z.record(t.z.string(),t.z.string()).optional().describe(`Additional request headers`),queryParams:t.z.record(t.z.string(),t.z.string()).optional().describe(`Additional query parameters`)}).optional().describe(`Request transformation`),response:t.z.object({dataPath:t.z.string().optional().describe(`JSONPath to extract data (e.g., "$.data.results")`),totalPath:t.z.string().optional().describe(`JSONPath to extract total count (e.g., "$.meta.total")`)}).optional().describe(`Response transformation`)}).optional().describe(`Request/response transformation pipeline`),pagination:t.z.object({type:t.z.enum([`offset`,`cursor`,`page`]).default(`offset`).describe(`Pagination type`),pageSize:t.z.number().default(100).describe(`Items per page`),maxPages:t.z.number().optional().describe(`Maximum number of pages to fetch`)}).optional().describe(`Pagination configuration for external data`)})),Xr=t.z.string().describe(`Underlying driver identifier`),Zr=n(()=>t.z.object({id:t.z.string().describe(`Unique driver identifier (e.g. "postgres")`),label:t.z.string().describe(`Display label (e.g. "PostgreSQL")`),description:t.z.string().optional(),icon:t.z.string().optional(),configSchema:t.z.record(t.z.string(),t.z.unknown()).describe(`JSON Schema for connection configuration`),capabilities:t.z.lazy(()=>Qr).optional()})),Qr=t.z.object({transactions:t.z.boolean().default(!1),queryFilters:t.z.boolean().default(!1),queryAggregations:t.z.boolean().default(!1),querySorting:t.z.boolean().default(!1),queryPagination:t.z.boolean().default(!1),queryWindowFunctions:t.z.boolean().default(!1),querySubqueries:t.z.boolean().default(!1),joins:t.z.boolean().default(!1),fullTextSearch:t.z.boolean().default(!1),readOnly:t.z.boolean().default(!1),dynamicSchema:t.z.boolean().default(!1)}),$r=t.z.enum([`managed`,`external`,`validate-only`]).describe(`Schema ownership mode`),ei=t.z.object({label:t.z.string().optional().describe(`Display label, e.g. "Snowflake — ANALYTICS / PROD"`),allowedSchemas:t.z.array(t.z.string()).optional().describe(`Whitelist of remote schemas/databases that may be exposed.`),allowWrites:t.z.boolean().default(!1).describe(`Global write gate. Individual objects must also opt in via object.external.writable.`),validation:t.z.object({onMismatch:t.z.enum([`fail`,`warn`,`ignore`]).default(`fail`).describe(`What to do when a federated object diverges from the remote table.`),checkOnBoot:t.z.boolean().default(!0).describe(`Validate federated objects against the remote schema at boot.`),checkIntervalMs:t.z.number().optional().describe(`Optional background drift-check interval in milliseconds.`)}).default({onMismatch:`fail`,checkOnBoot:!0}).describe(`Boot/drift validation policy`),credentialsRef:t.z.string().optional().describe(`Reference into the secrets store; never inline credentials.`),queryTimeoutMs:t.z.number().default(3e4).describe(`Hard cap on per-query execution time.`),requirePermission:t.z.string().optional().describe(`Optional convenience: gate the entire datasource behind a single role.`)}).describe(`External datasource federation settings (schemaMode != "managed")`),ti=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique datasource identifier`),label:t.z.string().optional().describe(`Display label`),driver:Xr.describe(`Underlying driver type`),config:t.z.record(t.z.string(),t.z.unknown()).describe(`Driver specific configuration`),pool:t.z.object({min:t.z.number().default(0).describe(`Minimum connections`),max:t.z.number().default(10).describe(`Maximum connections`),idleTimeoutMillis:t.z.number().default(3e4).describe(`Idle timeout`),connectionTimeoutMillis:t.z.number().default(3e3).describe(`Connection establishment timeout`)}).optional().describe(`Connection pool settings`),readReplicas:t.z.array(t.z.record(t.z.string(),t.z.unknown())).optional().describe(`Read-only replica configurations`),capabilities:Qr.optional().describe(`Capability overrides`),healthCheck:t.z.object({enabled:t.z.boolean().default(!0).describe(`Enable health check endpoint`),intervalMs:t.z.number().default(3e4).describe(`Health check interval in milliseconds`),timeoutMs:t.z.number().default(5e3).describe(`Health check timeout in milliseconds`)}).optional().describe(`Datasource health check configuration`),ssl:t.z.object({enabled:t.z.boolean().default(!1).describe(`Enable SSL/TLS for database connection`),rejectUnauthorized:t.z.boolean().default(!0).describe(`Reject connections with invalid/self-signed certificates`),ca:t.z.string().optional().describe(`CA certificate (PEM format or path to file)`),cert:t.z.string().optional().describe(`Client certificate (PEM format or path to file)`),key:t.z.string().optional().describe(`Client private key (PEM format or path to file)`)}).optional().describe(`SSL/TLS configuration for secure database connections`),retryPolicy:t.z.object({maxRetries:t.z.number().default(3).describe(`Maximum number of retry attempts`),baseDelayMs:t.z.number().default(1e3).describe(`Base delay between retries in milliseconds`),maxDelayMs:t.z.number().default(3e4).describe(`Maximum delay between retries in milliseconds`),backoffMultiplier:t.z.number().default(2).describe(`Exponential backoff multiplier`)}).optional().describe(`Connection retry policy for transient failures`),description:t.z.string().optional().describe(`Internal description`),active:t.z.boolean().default(!0).describe(`Is datasource enabled`),autoConnect:t.z.boolean().default(!1).describe(`Force a live driver connection at boot even when managed + unrouted (ADR-0062 D2).`),schemaMode:$r.default(`managed`),external:ei.optional(),origin:t.z.enum([`code`,`runtime`]).default(`code`).describe(`Datasource provenance (server-managed, read-only)`)}).superRefine((e,t)=>{e.schemaMode!==`managed`&&!e.external&&t.addIssue({code:`custom`,path:[`external`],message:`schemaMode='${e.schemaMode}' requires 'external' settings.`}),e.schemaMode===`managed`&&e.external&&t.addIssue({code:`custom`,path:[`external`],message:`'external' settings only apply when schemaMode != 'managed'.`})}));function ni(e){return ti.parse(e)}var ri={postgres:{int2:`integer`,int4:`integer`,int8:`bigint`,serial:`integer`,bigserial:`bigint`,float4:`float`,float8:`float`,numeric:`decimal`,bool:`boolean`,timestamptz:`datetime`,timestamp:`datetime`,timetz:`time`,jsonb:`json`,json:`json`,uuid:`uuid`,bytea:`binary`,bpchar:`text`,citext:`text`,vector:`vector`},mysql:{tinyint:`integer`,smallint:`integer`,mediumint:`integer`,int:`integer`,bigint:`bigint`,double:`float`,real:`float`,decimal:`decimal`,datetime:`datetime`,timestamp:`datetime`,tinytext:`text`,mediumtext:`text`,longtext:`text`,json:`json`,blob:`binary`,longblob:`binary`,enum:`enum`},sqlite:{integer:`integer`,int:`integer`,real:`float`,numeric:`decimal`,text:`text`,blob:`binary`},snowflake:{number:`decimal`,int:`integer`,integer:`integer`,bigint:`bigint`,float:`float`,double:`float`,string:`text`,varchar:`text`,variant:`json`,object:`json`,array:`array`,boolean:`boolean`,timestamp_ntz:`datetime`,timestamp_tz:`datetime`,timestamp_ltz:`datetime`,binary:`binary`},bigquery:{int64:`bigint`,float64:`float`,numeric:`decimal`,bignumeric:`decimal`,string:`text`,bytes:`binary`,bool:`boolean`,boolean:`boolean`,timestamp:`datetime`,datetime:`datetime`,struct:`json`,json:`json`,array:`array`,record:`json`},mongo:{objectid:`text`,string:`text`,double:`float`,int:`integer`,long:`bigint`,decimal:`decimal`,bool:`boolean`,boolean:`boolean`,date:`datetime`,object:`json`,array:`array`,bindata:`binary`}},ii={text:`text`,varchar:`text`,char:`text`,character:`text`,string:`text`,"character varying":`text`,nvarchar:`text`,nchar:`text`,clob:`text`,integer:`integer`,int:`integer`,smallint:`integer`,tinyint:`integer`,bigint:`bigint`,decimal:`decimal`,numeric:`decimal`,number:`decimal`,money:`decimal`,float:`float`,double:`float`,"double precision":`float`,real:`float`,boolean:`boolean`,bool:`boolean`,bit:`boolean`,date:`date`,time:`time`,datetime:`datetime`,timestamp:`datetime`,json:`json`,jsonb:`json`,uuid:`uuid`,guid:`uuid`,binary:`binary`,varbinary:`binary`,blob:`binary`,bytes:`binary`,enum:`enum`,array:`array`,vector:`vector`},ai={text:{suggested:`text`,exact:[`text`,`textarea`,`email`,`url`,`phone`,`markdown`,`html`,`richtext`,`code`,`select`,`color`],lossy:[]},integer:{suggested:`number`,exact:[`number`,`autonumber`,`rating`,`percent`],lossy:[`currency`,`boolean`]},bigint:{suggested:`number`,exact:[`number`,`autonumber`],lossy:[`currency`]},decimal:{suggested:`number`,exact:[`number`,`currency`,`percent`],lossy:[`rating`]},float:{suggested:`number`,exact:[`number`,`currency`,`percent`,`slider`],lossy:[]},boolean:{suggested:`boolean`,exact:[`boolean`,`toggle`],lossy:[]},date:{suggested:`date`,exact:[`date`],lossy:[`datetime`]},time:{suggested:`time`,exact:[`time`],lossy:[]},datetime:{suggested:`datetime`,exact:[`datetime`],lossy:[`date`]},json:{suggested:`json`,exact:[`json`,`composite`,`repeater`,`record`,`location`,`address`,`tags`,`multiselect`],lossy:[`text`]},uuid:{suggested:`text`,exact:[`text`,`lookup`,`master_detail`,`user`],lossy:[]},binary:{suggested:`file`,exact:[`file`,`image`,`signature`],lossy:[`text`]},enum:{suggested:`select`,exact:[`select`,`radio`,`text`],lossy:[]},array:{suggested:`multiselect`,exact:[`multiselect`,`checkboxes`,`tags`,`json`],lossy:[`text`]},vector:{suggested:`vector`,exact:[`vector`],lossy:[`json`]},unknown:{suggested:`text`,exact:[],lossy:[`text`,`json`]}};function oi(e,t){if(!e)return`unknown`;let n=e.trim().toLowerCase();if(n.endsWith(`[]`)||n.startsWith(`_`))return`array`;let r=n.indexOf(`(`);r!==-1&&(n=n.slice(0,r).trim());for(let e of[` without time zone`,` with time zone`,` unsigned`,` signed`])if(n.endsWith(e)){n=n.slice(0,n.length-e.length).trim();break}let i=t?ri[t]:void 0;return i&&i[n]?i[n]:ii[n]?ii[n]:`unknown`}function si(e,t){let n=oi(e,t);if(n!==`unknown`)return ai[n].suggested}function ci(e,t,n){let r=ai[oi(e,n)];return r.exact.includes(t)?!0:r.lossy.includes(t)?`lossy`:!1}var li=t.z.object({name:t.z.string().describe(`Remote column name`),sqlType:t.z.string().describe(`Raw remote SQL type (e.g. "numeric(10,2)")`),nullable:t.z.boolean().describe(`Whether the remote column is nullable`),primaryKey:t.z.boolean().default(!1).describe(`Part of the remote primary key`),suggestedFieldType:t.z.string().optional().describe(`ObjectStack field type suggested by the type-compat matrix`)}),ui=t.z.object({remoteSchema:t.z.string().optional().describe(`Remote schema/database qualifier`),remoteName:t.z.string().describe(`Remote table/view name`),columns:t.z.array(li).describe(`Remote columns`),indexes:t.z.array(t.z.object({name:t.z.string(),columns:t.z.array(t.z.string()),unique:t.z.boolean()})).optional().describe(`Remote indexes, when introspectable`),rowCountEstimate:t.z.number().optional().describe(`Approximate row count`)}),di=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Catalog id, conventionally `<datasource>_catalog`."),datasource:t.z.string().describe(`Datasource.name this catalog snapshots.`),snapshotAt:t.z.string().datetime().describe(`When the snapshot was taken (ISO 8601).`),dialect:t.z.string().optional().describe(`Remote SQL dialect, when known.`),tables:t.z.array(ui).describe(`Snapshotted remote tables.`)})),fi=t.z.enum([`count`,`sum`,`avg`,`min`,`max`,`count_distinct`,`number`,`string`,`boolean`]),pi=t.z.enum([`string`,`number`,`boolean`,`time`,`geo`]),mi=t.z.enum([`second`,`minute`,`hour`,`day`,`week`,`month`,`quarter`,`year`]),hi=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique metric ID`),label:t.z.string().describe(`Human readable label`),description:t.z.string().optional(),type:fi,sql:t.z.string().describe(`SQL expression or field reference`),filters:t.z.array(t.z.object({sql:t.z.string()})).optional(),format:t.z.string().optional()})),gi=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Unique dimension ID`),label:t.z.string().describe(`Human readable label`),description:t.z.string().optional(),type:pi,sql:t.z.string().describe(`SQL expression or column reference`),granularities:t.z.array(mi).optional()})),_i=n(()=>t.z.object({name:t.z.string().describe(`Target cube name`),relationship:t.z.enum([`one_to_one`,`one_to_many`,`many_to_one`]).default(`many_to_one`),sql:t.z.string().describe(`Join condition (ON clause)`)})),vi=n(()=>t.z.object({name:t.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe(`Cube name (snake_case)`),title:t.z.string().optional(),description:t.z.string().optional(),sql:t.z.string().describe(`Base SQL statement or Table Name`),measures:t.z.record(t.z.string(),hi).describe(`Quantitative metrics`),dimensions:t.z.record(t.z.string(),gi).describe(`Qualitative attributes`),joins:t.z.record(t.z.string(),_i).optional(),refreshKey:t.z.object({every:t.z.string().optional(),sql:t.z.string().optional()}).optional(),public:t.z.boolean().default(!1)})),yi=n(()=>t.z.object({cube:t.z.string().optional().describe(`Target cube name (optional when provided externally, e.g. in API request wrapper)`),measures:t.z.array(t.z.string()).describe(`List of metrics to calculate`),dimensions:t.z.array(t.z.string()).optional().describe(`List of dimensions to group by`),where:f.optional().describe(`Filtering criteria (canonical Query DSL FilterCondition)`),timeDimensions:t.z.array(t.z.object({dimension:t.z.string(),granularity:mi.optional(),dateRange:t.z.union([t.z.string(),t.z.array(t.z.string())]).optional()})).optional(),order:t.z.record(t.z.string(),t.z.enum([`asc`,`desc`])).optional(),limit:t.z.number().optional(),offset:t.z.number().optional(),timezone:t.z.string().optional().default(`UTC`)}));function bi(e){return vi.parse(e)}var xi=new Set([`number`,`currency`,`percent`]);function Si(e){return e===`percent`?`avg`:`sum`}function Ci(e,t){return t===`percent`&&(e===`sum`||e===`count_distinct`)}var wi=new Set(`date.datetime.time.number.currency.percent.boolean.toggle.file.image.avatar.video.audio.attachment.signature.qrcode.json.code.composite.repeater.record.address.vector.geolocation.location.select.multiselect.multi_select.radio.checkboxes.checkbox.tags.color.rating.slider.progress.lookup.master_detail.tree.user.autonumber.password.secret.phone`.split(`.`)),Ti=new Set([`text`,`textarea`,`email`,`url`,`markdown`,`html`,`richtext`]),Ei=Ti;function $(e){if(!e)return!1;let t=e.type;return t?t===`formula`?(e.returnType??e.valueType)===`text`:wi.has(t)?!1:Ti.has(t):!1}var Di=new Set([`name`,`title`,`subject`,`label`,`full_name`,`display_name`]),Oi=[`_name`,`_title`],ki=[`name_`];function Ai(e){return Di.has(e.toLowerCase())}function ji(e){let t=e.toLowerCase();return Di.has(t)?!1:Oi.some(e=>t.endsWith(e))||ki.some(e=>t.startsWith(e))}function Mi(e){if(!e)return;let t=Object.keys(e);for(let n of[`name`,`title`,`subject`,`label`,`full_name`,`display_name`])for(let r of t)if(r.toLowerCase()===n&&$(e[r]))return r;for(let n of t)if(ji(n)&&$(e[n]))return n;for(let n of t)if(!Ai(n)&&$(e[n]))return n}function Ni(e){return e?(e.nameField??e.displayNameField)||Mi(e.fields):void 0}function Pi(e){return e==null||typeof e==`string`&&e.trim()===``}function Fi(e,t,n){let r=t??{},i=n?.viewTitleField??Ni(e),a=i?r[i]:void 0;return Pi(a)?`Record #${r.id??r._id??``}`.trimEnd():String(a)}function Ii(e,t){let n=Ni(e);if(n)return e.nameField===n?e:{...e,nameField:n};if(t?.synthesize===!1)return e;let r={...e.fields??{}};return r.name||={type:`text`,label:`Name`,required:!0},{...e,fields:r,nameField:`name`}}function Li(e){if(!e)return{status:`none`};let t=e.nameField??e.displayNameField;if(t)return{status:e.fields&&Object.prototype.hasOwnProperty.call(e.fields,t)?`explicit`:`synthesized`,field:t};let n=Mi(e.fields);return n?{status:`derived`,field:n}:{status:`none`}}var Ri=new Set([`created_at`,`created_by`,`updated_at`,`updated_by`,`organization_id`,`tenant_id`,`is_deleted`,`deleted_at`]);function zi(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e;if(typeof t.key!=`string`||t.key.length===0)return null;let n=`none`;return t.collapse===`expanded`||t.collapse===`collapsed`||t.collapse===`none`?n=t.collapse:typeof t.collapsible==`boolean`||typeof t.collapsed==`boolean`?n=t.collapsed===!0?`collapsed`:t.collapsible===!0?`expanded`:`none`:typeof t.defaultExpanded==`boolean`&&(n=t.defaultExpanded?`expanded`:`collapsed`),{key:t.key,label:typeof t.label==`string`?t.label:void 0,icon:typeof t.icon==`string`?t.icon:void 0,description:typeof t.description==`string`?t.description:void 0,collapse:n}}function Bi(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e,n=(Array.isArray(t.fieldGroups)?t.fieldGroups:[]).map(zi).filter(e=>e!==null);if(n.length===0)return null;let r=new Set(n.map(e=>e.key)),i=t.fields&&typeof t.fields==`object`&&!Array.isArray(t.fields)?t.fields:{},a=new Map;for(let e of n)a.set(e.key,[]);let o=[],s=!1;for(let[e,t]of Object.entries(i)){if(t?.hidden===!0)continue;let n=typeof t?.group==`string`&&r.has(t.group)?t.group:null;n?(a.get(n).push(e),s=!0):Ri.has(e)||o.push(e)}if(!s)return null;let c=[];for(let e of n){let t=a.get(e.key);t.length!==0&&c.push({key:e.key,label:e.label??e.key,...e.icon===void 0?{}:{icon:e.icon},...e.description===void 0?{}:{description:e.description},collapse:e.collapse,fields:t})}return o.length>0&&c.push({collapse:`none`,fields:o}),c.length>0?c:null}var Vi=12;function Hi(e){if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e.fields;if(!t||typeof t!=`object`||Array.isArray(t))return 0;let n=0;for(let[e,r]of Object.entries(t))r?.hidden!==!0&&(Ri.has(e)||n++);return n}function Ui(e,t={}){if(t.viewport===`mobile`)return`page`;let n=t.pageThreshold??Vi;return Hi(e)>=n?`page`:`drawer`}function Wi(e,t,n={}){let r=Ui(e,n);return t===`view`?{container:r===`page`?`route`:`overlay`,surface:r,size:`auto`}:r===`page`?{container:`overlay`,surface:`modal`,size:`full`}:{container:`overlay`,surface:r,size:`auto`}}var Gi=t.z.enum([`comment`,`field_change`,`task`,`event`,`email`,`call`,`note`,`file`,`record_create`,`record_delete`,`approval`,`sharing`,`system`]),Ki=n(()=>t.z.object({type:t.z.enum([`user`,`team`,`record`]).describe(`Mention target type`),id:t.z.string().describe(`Target ID`),name:t.z.string().describe(`Display name for rendering`),offset:t.z.number().int().min(0).describe(`Character offset in body text`),length:t.z.number().int().min(1).describe(`Length of mention token in body text`)})),qi=n(()=>t.z.object({field:t.z.string().describe(`Field machine name`),fieldLabel:t.z.string().optional().describe(`Field display label`),oldValue:t.z.unknown().optional().describe(`Previous value`),newValue:t.z.unknown().optional().describe(`New value`),oldDisplayValue:t.z.string().optional().describe(`Human-readable old value`),newDisplayValue:t.z.string().optional().describe(`Human-readable new value`)})),Ji=n(()=>t.z.object({emoji:t.z.string().describe(`Emoji character or shortcode (e.g., "👍", ":thumbsup:")`),userIds:t.z.array(t.z.string()).describe(`Users who reacted`),count:t.z.number().int().min(1).describe(`Total reaction count`)})),Yi=n(()=>t.z.object({type:t.z.enum([`user`,`system`,`service`,`automation`]).describe(`Actor type`),id:t.z.string().describe(`Actor ID`),name:t.z.string().optional().describe(`Actor display name`),avatarUrl:t.z.string().url().optional().describe(`Actor avatar URL`),source:t.z.string().optional().describe(`Source application (e.g., "Omni", "API", "Studio")`)})),Xi=t.z.enum([`public`,`internal`,`private`]),Zi=n(()=>t.z.object({id:t.z.string().describe(`Feed item ID`),type:Gi.describe(`Activity type`),object:t.z.string().describe(`Object name (e.g., "account")`),recordId:t.z.string().describe(`Record ID this feed item belongs to`),actor:Yi.describe(`Who performed this action`),body:t.z.string().optional().describe(`Rich text body (Markdown supported)`),mentions:t.z.array(Ki).optional().describe(`Mentioned users/teams/records`),changes:t.z.array(qi).optional().describe(`Field-level changes`),reactions:t.z.array(Ji).optional().describe(`Emoji reactions on this item`),parentId:t.z.string().optional().describe(`Parent feed item ID for threaded replies`),replyCount:t.z.number().int().min(0).default(0).describe(`Number of replies`),pinned:t.z.boolean().default(!1).describe(`Whether the feed item is pinned to the top of the timeline`),pinnedAt:t.z.string().datetime().optional().describe(`Timestamp when the item was pinned`),pinnedBy:t.z.string().optional().describe(`User ID who pinned the item`),starred:t.z.boolean().default(!1).describe(`Whether the feed item is starred/bookmarked by the current user`),starredAt:t.z.string().datetime().optional().describe(`Timestamp when the item was starred`),visibility:Xi.default(`public`).describe(`Visibility: public (all users), internal (team only), private (author + mentioned)`),createdAt:t.z.string().datetime().describe(`Creation timestamp`),updatedAt:t.z.string().datetime().optional().describe(`Last update timestamp`),editedAt:t.z.string().datetime().optional().describe(`When comment was last edited`),isEdited:t.z.boolean().default(!1).describe(`Whether comment has been edited`)})),Qi=t.z.enum([`all`,`comments_only`,`changes_only`,`tasks_only`]),$i=t.z.enum([`comment`,`mention`,`field_change`,`task`,`approval`,`all`]),ea=t.z.enum([`in_app`,`email`,`push`,`slack`]),ta=n(()=>t.z.object({object:t.z.string().describe(`Object name`),recordId:t.z.string().describe(`Record ID`),userId:t.z.string().describe(`Subscribing user ID`),events:t.z.array($i).default([`all`]).describe(`Event types to receive notifications for`),channels:t.z.array(ea).default([`in_app`]).describe(`Notification delivery channels`),active:t.z.boolean().default(!0).describe(`Whether the subscription is active`),createdAt:t.z.string().datetime().describe(`Subscription creation timestamp`)}));e.ALL_OPERATORS=ne,e.AddressSchema=Oe,e.AggregationFunction=x,e.AggregationMetricType=fi,e.AggregationNodeSchema=w,e.AggregationPipelineSchema=wr,e.AggregationStageSchema=Cr,e.AnalyticsQuerySchema=yi,e.ApiMethod=Gt,e.BaseEngineOptionsSchema=q,e.ComparisonOperatorSchema=o,e.ComputedFieldCacheSchema=Me,e.ConditionalValidationSchema=ze,e.ConsistencyLevelSchema=Z,e.CrossFieldValidationSchema=Le,e.CubeJoinSchema=_i,e.CubeSchema=vi,e.CurrencyConfigSchema=Ee,e.CurrencyValueSchema=De,e.DATE_MACRO_ALIAS_TOKENS=ue,e.DATE_MACRO_DESCRIPTIONS=ye,e.DATE_MACRO_INSTANT_TOKENS=ce,e.DATE_MACRO_PARAM_RE=fe,e.DATE_MACRO_PERIOD_TOKENS=le,e.DATE_MACRO_TOKENS=de,e.DATE_MACRO_UNITS=pe,e.DATE_MACRO_WRAPPED_RE=_e,e.DataEngineAggregateOptionsSchema=Bn,e.DataEngineAggregateRequestSchema=Zn,e.DataEngineBatchRequestSchema=er,e.DataEngineContractSchema=Un,e.DataEngineCountOptionsSchema=Hn,e.DataEngineCountRequestSchema=Xn,e.DataEngineDeleteOptionsSchema=Rn,e.DataEngineDeleteRequestSchema=Yn,e.DataEngineExecuteRequestSchema=Qn,e.DataEngineFilterSchema=K,e.DataEngineFindOneRequestSchema=Kn,e.DataEngineFindRequestSchema=Gn,e.DataEngineInsertOptionsSchema=Pn,e.DataEngineInsertRequestSchema=qn,e.DataEngineQueryOptionsSchema=Nn,e.DataEngineRequestSchema=tr,e.DataEngineSortSchema=Mn,e.DataEngineUpdateOptionsSchema=In,e.DataEngineUpdateRequestSchema=Jn,e.DataEngineVectorFindRequestSchema=$n,e.DataQualityRulesSchema=je,e.DataTypeMappingSchema=lr,e.DatasourceCapabilities=Qr,e.DatasourceSchema=ti,e.DateGranularity=S,e.DateMacroPlaceholderSchema=ve,e.DateMacroTokenSchema=ge,e.DimensionSchema=gi,e.DimensionType=pi,e.DocumentSchema=Wr,e.DocumentSchemaValidationSchema=yr,e.DocumentTemplateSchema=Hr,e.DocumentVersionSchema=Vr,e.DriverCapabilitiesSchema=ir,e.DriverConfigSchema=sr,e.DriverDefinitionSchema=Zr,e.DriverInterfaceSchema=ar,e.DriverOptionsSchema=X,e.DriverType=Xr,e.ESignatureConfigSchema=Ur,e.EngineAggregateOptionsSchema=zn,e.EngineCountOptionsSchema=Vn,e.EngineDeleteOptionsSchema=Ln,e.EngineQueryOptionsSchema=J,e.EngineUpdateOptionsSchema=Fn,e.EqualityOperatorSchema=a,e.ExpressionBodySchema=We,e.ExternalCatalogSchema=di,e.ExternalColumnSchema=li,e.ExternalDataSourceSchema=qr,e.ExternalDatasourceSettingsSchema=ei,e.ExternalFieldMappingSchema=Jr,e.ExternalLookupSchema=Yr,e.ExternalTableSchema=ui,e.FIELD_GROUP_SYSTEM_FIELDS=Ri,e.FILTER_OPERATORS=y,e.FeedActorSchema=Yi,e.FeedFilterMode=Qi,e.FeedItemSchema=Zi,e.FeedItemType=Gi,e.FeedVisibility=Xi,e.Field=Ne,e.FieldChangeEntrySchema=qi,e.FieldMappingSchema=On,e.FieldNodeSchema=O,e.FieldOperatorsSchema=d,e.FieldReferenceSchema=i,e.FieldSchema=P,e.FieldType=M,e.FileAttachmentConfigSchema=Ae,e.FilterConditionSchema=f,e.FormatValidationSchema=Ie,e.FullTextSearchSchema=oe,e.GroupByNodeSchema=C,e.HookBodyCapability=Ue,e.HookBodySchema=R,e.HookContextSchema=En,e.HookEvent=wn,e.HookSchema=Tn,e.IndexSchema=qt,e.JSONValidationSchema=Re,e.JoinNodeSchema=E,e.JoinStrategy=re,e.JoinType=T,e.LOGICAL_OPERATORS=te,e.LocationCoordinatesSchema=Te,e.MEASURE_FIELD_TYPES=xi,e.MappingSchema=kn,e.MentionSchema=Ki,e.MetricSchema=hi,e.NoSQLDataTypeMappingSchema=br,e.NoSQLDatabaseTypeSchema=mr,e.NoSQLDriverConfigSchema=xr,e.NoSQLIndexSchema=Tr,e.NoSQLIndexTypeSchema=gr,e.NoSQLOperationTypeSchema=hr,e.NoSQLQueryOptionsSchema=Sr,e.NoSQLTransactionOptionsSchema=Er,e.NormalizedFilterSchema=p,e.NotificationChannel=ea,e.ObjectAccessConfigSchema=Xt,e.ObjectCapabilities=Kt,e.ObjectDependencyGraphSchema=Pr,e.ObjectDependencyNodeSchema=Nr,e.ObjectExtensionSchema=pn,e.ObjectExternalBindingSchema=en,e.ObjectFieldGroupSchema=$t,e.ObjectOwnershipEnum=fn,e.ObjectSchema=ln,e.PoolConfigSchema=or,e.QueryFilterSchema=ee,e.QuerySchema=k,e.RECORD_SURFACE_PAGE_THRESHOLD=Vi,e.RangeOperatorSchema=c,e.ReactionSchema=Ji,e.RecordSubscriptionSchema=ta,e.ReferenceResolutionErrorSchema=Fr,e.ReferenceResolutionSchema=Mr,e.ReplicationConfigSchema=vr,e.SQLDialectSchema=cr,e.SQLDriverConfigSchema=dr,e.SQLiteAlterTableLimitations=pr,e.SQLiteDataTypeMappingDefaults=fr,e.SSLConfigSchema=ur,e.SchemaModeSchema=$r,e.ScriptBodySchema=Ge,e.ScriptValidationSchema=Pe,e.SearchConfigSchema=Jt,e.SeedIdentitySchema=Ir,e.SeedLoadResultSchema=Rr,e.SeedLoaderConfigSchema=Lr,e.SeedLoaderRequestSchema=Br,e.SeedLoaderResultSchema=zr,e.SeedMode=Q,e.SeedSchema=Dr,e.SelectOptionSchema=N,e.SetOperatorSchema=s,e.ShardingConfigSchema=_r,e.SoftDeleteConfigSchema=Zt,e.SortNodeSchema=b,e.SpecialOperatorSchema=u,e.StateMachineValidationSchema=Fe,e.StringOperatorSchema=l,e.SubscriptionEventType=$i,e.TITLE_ELIGIBLE=Ei,e.TITLE_ELIGIBLE_TYPES=Ti,e.TITLE_INELIGIBLE_TYPES=wi,e.TenancyConfigSchema=Yt,e.TimeUpdateInterval=mi,e.TransformType=Dn,e.VALID_AST_OPERATORS=m,e.ValidationRuleSchema=I,e.VectorConfigSchema=ke,e.VersioningConfigSchema=Qt,e.WindowFunction=ie,e.WindowFunctionNodeSchema=ae,e.WindowSpecSchema=D,e.canonicalizeSqlType=oi,e.countAuthorableFields=Hi,e.defaultAggregateFor=Si,e.defineCube=bi,e.defineDatasource=ni,e.defineMapping=An,e.defineObjectExtension=mn,e.defineSeed=Or,e.deriveFieldGroupLayout=Bi,e.deriveRecordFlowSurface=Wi,e.deriveRecordSurface=Ui,e.fieldForm=Ar,e.hasDynamicTokens=_n,e.hookForm=jr,e.isCompatible=ci,e.isDateMacroToken=me,e.isFilterAST=h,e.isIncoherentAggregate=Ci,e.isTitleEligible=$,e.missingFieldValues=bn,e.objectForm=kr,e.objectTitleCompleteness=Li,e.parseAutonumberFormat=gn,e.parseDateMacroParam=he,e.parseFilterAST=v,e.provisionPrimary=Ii,e.referencedFields=yn,e.renderAutonumber=Cn,e.resolveCrudAffordances=dn,e.resolveDisplayField=Ni,e.resolveRecordDisplayName=Fi,e.sequenceWidth=vn,e.suggestFieldType=si})),a=e(((e,t)=>{var r=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,i)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of o(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(i=a(t,c))||i.enumerable});return e},u=e=>l(r({},`__esModule`,{value:!0}),e),d={};c(d,{FilterBuilder:()=>m,ObjectStackClient:()=>v,QueryBuilder:()=>h,RealtimeAPI:()=>p,ScopedProjectClient:()=>y,createFilter:()=>_,createQuery:()=>g}),t.exports=u(d);var f=i(),ee=n(),p=class{constructor(e,t){this.subscriptions=new Map,this.eventBuffer=[],this._baseUrl=e,this._token=t}subscribeMetadata(e,t,n){let r=`metadata-${e}-${Date.now()}`;return this.subscriptions.set(r,{filter:{type:e,packageId:n?.packageId,eventTypes:[`metadata.${e}.created`,`metadata.${e}.updated`,`metadata.${e}.deleted`]},handler:e=>{e.type.startsWith(`metadata.`)&&t(e)}}),this.startPolling(),()=>{this.subscriptions.delete(r),this.subscriptions.size===0&&this.stopPolling()}}subscribeData(e,t,n){let r=`data-${e}-${Date.now()}`;return this.subscriptions.set(r,{filter:{type:e,recordId:n?.recordId,eventTypes:[`data.record.created`,`data.record.updated`,`data.record.deleted`]},handler:r=>{r.type.startsWith(`data.`)&&r.object===e&&(!n?.recordId||r.payload?.recordId===n.recordId)&&t(r)}}),this.startPolling(),()=>{this.subscriptions.delete(r),this.subscriptions.size===0&&this.stopPolling()}}emitEvent(e){for(let t of this.subscriptions.values()){let n=!t.filter.type||e.type.includes(t.filter.type)||e.object===t.filter.type,r=!t.filter.eventTypes?.length||t.filter.eventTypes.includes(e.type),i=!t.filter.packageId||e.payload?.packageId===t.filter.packageId;if(n&&r&&i)try{t.handler(e)}catch(e){console.error(`Error in realtime event handler:`,e)}}}startPolling(){this.pollInterval||=setInterval(()=>{for(;this.eventBuffer.length>0;){let e=this.eventBuffer.shift();e&&this.emitEvent(e)}},2e3)}stopPolling(){this.pollInterval&&=(clearInterval(this.pollInterval),void 0)}_bufferEvent(e){this.eventBuffer.push(e)}disconnect(){this.stopPolling(),this.subscriptions.clear(),this.eventBuffer=[]}},m=class{constructor(){this.conditions=[]}equals(e,t){return this.conditions.push([e,`=`,t]),this}notEquals(e,t){return this.conditions.push([e,`!=`,t]),this}greaterThan(e,t){return this.conditions.push([e,`>`,t]),this}greaterThanOrEqual(e,t){return this.conditions.push([e,`>=`,t]),this}lessThan(e,t){return this.conditions.push([e,`<`,t]),this}lessThanOrEqual(e,t){return this.conditions.push([e,`<=`,t]),this}in(e,t){return this.conditions.push([e,`in`,t]),this}notIn(e,t){return this.conditions.push([e,`not_in`,t]),this}like(e,t){return this.conditions.push([e,`like`,t]),this}isNull(e){return this.conditions.push([e,`is_null`,null]),this}isNotNull(e){return this.conditions.push([e,`is_not_null`,null]),this}between(e,t,n){return this.conditions.push([`and`,[e,`>=`,t],[e,`<=`,n]]),this}contains(e,t){return this.conditions.push([e,`like`,`%${t}%`]),this}startsWith(e,t){return this.conditions.push([e,`like`,`${t}%`]),this}endsWith(e,t){return this.conditions.push([e,`like`,`%${t}`]),this}exists(e){return this.conditions.push([e,`is_not_null`,null]),this}build(){if(this.conditions.length===0)throw Error(`Filter builder has no conditions`);return this.conditions.length===1?this.conditions[0]:[`and`,...this.conditions]}getConditions(){return this.conditions}},h=class{constructor(e){this.query={},this._object=e,this.query.object=e}select(...e){return this.query.fields=e,this}where(e){let t=new m;e(t);let n=t.getConditions();return n.length===1?this.query.where=n[0]:n.length>1&&(this.query.where=[`and`,...n]),this}filter(e){return this.query.where=e,this}orderBy(e,t=`asc`){return this.query.orderBy||(this.query.orderBy=[]),this.query.orderBy.push({field:e,order:t}),this}limit(e){return this.query.limit=e,this}skip(e){return this.query.offset=e,this}offset(e){return this.query.offset=e,this}paginate(e,t){return this.query.limit=t,this.query.offset=(e-1)*t,this}groupBy(...e){return this.query.groupBy=e,this}expand(e,t){return this.query.expand||(this.query.expand={}),this.query.expand[e]=t||{},this}search(e,t){return this.query.search={query:e,...t},this}cursor(e){return this.query.cursor=e,this}distinct(){return this.query.distinct=!0,this}build(){return{object:this._object,...this.query}}getQuery(){return{...this.query}}};function g(e){return new h(e)}function _(){return new m}var v=class{constructor(e){this.meta={getTypes:async()=>{let e=this.getRoute(`metadata`),t=await this.fetch(`${this.baseUrl}${e}`);return this.unwrapResponse(t)},getItems:async(e,t)=>{let n=this.getRoute(`metadata`),r=new URLSearchParams;t?.packageId&&r.set(`package`,t.packageId);let i=r.toString(),a=`${this.baseUrl}${n}/${e}${i?`?${i}`:``}`,o=await this.fetch(a);return this.unwrapResponse(o)},getItem:async(e,t,n)=>{let r=this.getRoute(`metadata`),i=new URLSearchParams;n?.packageId&&i.set(`package`,n.packageId);let a=i.toString(),o=`${this.baseUrl}${r}/${e}/${t}${a?`?${a}`:``}`,s=await this.fetch(o);return this.unwrapResponse(s)},saveItem:async(e,t,n)=>{let r=this.getRoute(`metadata`),i=await this.fetch(`${this.baseUrl}${r}/${e}/${t}`,{method:`PUT`,body:JSON.stringify(n)});return this.unwrapResponse(i)},deleteItem:async(e,t)=>{let n=this.getRoute(`metadata`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`DELETE`});return this.unwrapResponse(r)},getHistory:async(e,t,n)=>{let r=this.getRoute(`metadata`),i=new URLSearchParams;n?.sinceSeq!==void 0&&i.set(`sinceSeq`,String(n.sinceSeq)),n?.limit!==void 0&&i.set(`limit`,String(n.limit));let a=i.toString(),o=`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/history${a?`?${a}`:``}`,s=await this.fetch(o);return this.unwrapResponse(s)},getCached:async(e,t)=>{let n=this.getRoute(`metadata`),r={};t?.ifNoneMatch&&(r[`If-None-Match`]=t.ifNoneMatch),t?.ifModifiedSince&&(r[`If-Modified-Since`]=t.ifModifiedSince);let i=await this.fetch(`${this.baseUrl}${n}/object/${e}`,{headers:r});if(i.status===304)return{notModified:!0,etag:t?.ifNoneMatch?{value:t.ifNoneMatch.replace(/^W\/|"/g,``),weak:t.ifNoneMatch.startsWith(`W/`)}:void 0};let a=await i.json(),o=i.headers.get(`ETag`),s=i.headers.get(`Last-Modified`);return{data:a,etag:o?{value:o.replace(/^W\/|"/g,``),weak:o.startsWith(`W/`)}:void 0,lastModified:s||void 0,notModified:!1}},getView:async(e,t=`list`)=>{let n=this.getRoute(`ui`),r=await this.fetch(`${this.baseUrl}${n}/view/${e}?type=${t}`);return this.unwrapResponse(r)}},this.analytics={query:async e=>{let t=this.getRoute(`analytics`);return(await this.fetch(`${this.baseUrl}${t}/query`,{method:`POST`,body:JSON.stringify(e)})).json()},meta:async e=>{let t=this.getRoute(`analytics`);return(await this.fetch(`${this.baseUrl}${t}/meta/${e}`)).json()},explain:async e=>{let t=this.getRoute(`analytics`);return(await this.fetch(`${this.baseUrl}${t}/explain`,{method:`POST`,body:JSON.stringify(e)})).json()}},this.packages={list:async e=>{let t=this.getRoute(`packages`),n=new URLSearchParams;e?.status&&n.set(`status`,e.status),e?.type&&n.set(`type`,e.type),e?.enabled!==void 0&&n.set(`enabled`,String(e.enabled));let r=n.toString(),i=`${this.baseUrl}${t}${r?`?`+r:``}`,a=await this.fetch(i);return this.unwrapResponse(a)},get:async e=>{let t=this.getRoute(`packages`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}`);return this.unwrapResponse(n)},install:async(e,t)=>{let n=this.getRoute(`packages`),r=await this.fetch(`${this.baseUrl}${n}`,{method:`POST`,body:JSON.stringify({manifest:e,settings:t?.settings,enableOnInstall:t?.enableOnInstall})});return this.unwrapResponse(r)},uninstall:async e=>{let t=this.getRoute(`packages`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}`,{method:`DELETE`});return this.unwrapResponse(n)},enable:async e=>{let t=this.getRoute(`packages`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}/enable`,{method:`PATCH`});return this.unwrapResponse(n)},disable:async e=>{let t=this.getRoute(`packages`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}/disable`,{method:`PATCH`});return this.unwrapResponse(n)}},this.projects={list:async e=>{let t=new URLSearchParams;e?.organization_id&&t.set(`organizationId`,e.organization_id),e?.env_type&&t.set(`envType`,e.env_type),e?.status&&t.set(`status`,e.status);let n=t.toString(),r=`${this.baseUrl}/api/v1/cloud/environments${n?`?`+n:``}`,i=await this.fetch(r);return this.unwrapResponse(i)},get:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}`);return this.unwrapResponse(t)},create:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(t)},update:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)});return this.unwrapResponse(n)},delete:async(e,t)=>{let n=t?.force?`?force=1`:``,r=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}${n}`,{method:`DELETE`});return this.unwrapResponse(r)},activate:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/activate`,{method:`POST`});return this.unwrapResponse(t)},rotateCredential:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/credentials/rotate`,{method:`POST`,body:JSON.stringify({plaintext:t})});return this.unwrapResponse(n)},updateHostname:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/hostname`,{method:`POST`,body:JSON.stringify({hostname:t})});return this.unwrapResponse(n)},updateVisibility:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify({visibility:t})});return this.unwrapResponse(n)},listRevisions:async(e,t)=>{let n=new URLSearchParams;t?.limit&&n.set(`limit`,String(t.limit)),t?.cursor&&n.set(`cursor`,t.cursor),t?.branch&&n.set(`branch`,t.branch);let r=n.toString(),i=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/revisions${r?`?${r}`:``}`);return this.unwrapResponse(i)},listBranches:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/branches`);return this.unwrapResponse(t)},renameBranch:async(e,t,n)=>{let r=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/branches/${encodeURIComponent(t)}/rename`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({newName:n})});return this.unwrapResponse(r)},deleteBranch:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/branches/${encodeURIComponent(t)}`,{method:`DELETE`});return this.unwrapResponse(n)},retryProvisioning:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/retry`,{method:`POST`});return this.unwrapResponse(t)},listDrivers:async()=>{let e=await this.fetch(`${this.baseUrl}/api/v1/cloud/drivers`);return this.unwrapResponse(e)},listTemplates:async()=>{let e=await this.fetch(`${this.baseUrl}/api/v1/cloud/templates`);return this.unwrapResponse(e)},packages:{list:async e=>{let t=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages`);return this.unwrapResponse(t)},install:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(n)},get:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages/${encodeURIComponent(t)}`);return this.unwrapResponse(n)},enable:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages/${encodeURIComponent(t)}/enable`,{method:`PATCH`});return this.unwrapResponse(n)},disable:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages/${encodeURIComponent(t)}/disable`,{method:`PATCH`});return this.unwrapResponse(n)},uninstall:async(e,t)=>{let n=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages/${encodeURIComponent(t)}`,{method:`DELETE`});return this.unwrapResponse(n)},upgrade:async(e,t,n)=>{let r=await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(e)}/packages/${encodeURIComponent(t)}/upgrade`,{method:`POST`,body:JSON.stringify({targetVersion:n})});return this.unwrapResponse(r)}}},this.organizations={list:async()=>{let e=this.getRoute(`auth`),t=await(await this.fetch(`${this.baseUrl}${e}/organization/list`)).json();return{organizations:Array.isArray(t)?t:t?.data??[]}},create:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/create`,{method:`POST`,body:JSON.stringify(e)})).json()},update:async(e,t)=>{let n=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${n}/organization/update`,{method:`POST`,body:JSON.stringify({organizationId:e,data:t})})).json()},setActive:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/set-active`,{method:`POST`,body:JSON.stringify({organizationId:e})})).json()},get:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/get-full-organization?organizationId=${encodeURIComponent(e)}`)).json()},listMembers:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/list-members?organizationId=${encodeURIComponent(e)}`)).json()},invite:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/invite-member`,{method:`POST`,body:JSON.stringify(e)})).json()},leave:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/leave`,{method:`POST`,body:JSON.stringify({organizationId:e})})).json()},delete:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/delete`,{method:`POST`,body:JSON.stringify({organizationId:e})})).json()},removeMember:async(e,t)=>{let n=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${n}/organization/remove-member`,{method:`POST`,body:JSON.stringify({memberIdOrEmail:t.memberIdOrEmail,organizationId:e})})).json()},updateMemberRole:async(e,t)=>{let n=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${n}/organization/update-member-role`,{method:`POST`,body:JSON.stringify({memberId:t.memberId,role:t.role,organizationId:e})})).json()},getActiveMember:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/get-active-member?organizationId=${encodeURIComponent(e)}`)).json()},invitations:{list:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/organization/list-invitations?organizationId=${encodeURIComponent(e)}`)).json();return{invitations:Array.isArray(n)?n:n?.data??n?.invitations??[]}},listMine:async()=>{let e=this.getRoute(`auth`),t=await(await this.fetch(`${this.baseUrl}${e}/organization/list-user-invitations`)).json();return{invitations:Array.isArray(t)?t:t?.data??t?.invitations??[]}},cancel:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/cancel-invitation`,{method:`POST`,body:JSON.stringify({invitationId:e})})).json()},accept:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/accept-invitation`,{method:`POST`,body:JSON.stringify({invitationId:e})})).json()},reject:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/reject-invitation`,{method:`POST`,body:JSON.stringify({invitationId:e})})).json()},resend:async e=>{if(e.id)try{await this.organizations.invitations.cancel(e.id)}catch{}return this.organizations.invite({email:e.email,role:e.role??`member`,organizationId:e.organizationId})}},teams:{list:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/organization/list-teams?organizationId=${encodeURIComponent(e)}`)).json();return{teams:Array.isArray(n)?n:n?.data??n?.teams??[]}},create:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/create-team`,{method:`POST`,body:JSON.stringify(e)})).json()},update:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/update-team`,{method:`POST`,body:JSON.stringify(e)})).json()},delete:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/remove-team`,{method:`POST`,body:JSON.stringify(e)})).json()},listMembers:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/organization/list-team-members?teamId=${encodeURIComponent(e)}`)).json();return{members:Array.isArray(n)?n:n?.data??n?.members??[]}},addMember:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/add-team-member`,{method:`POST`,body:JSON.stringify(e)})).json()},removeMember:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/organization/remove-team-member`,{method:`POST`,body:JSON.stringify(e)})).json()}}},this.oauth={applications:{register:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/oauth2/create-client`,{method:`POST`,body:JSON.stringify(e)})).json()},get:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/oauth2/get-client?client_id=${encodeURIComponent(e)}`)).json()},getPublic:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/oauth2/public-client?client_id=${encodeURIComponent(e)}`)).json()},list:async()=>{let e=this.getRoute(`auth`),t=await(await this.fetch(`${this.baseUrl}${e}/oauth2/get-clients`)).json();return{applications:Array.isArray(t)?t:t?.clients??t?.data??[]}},delete:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/oauth2/delete-client`,{method:`POST`,body:JSON.stringify({client_id:e})})).json()}},consent:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/oauth2/consent`,{method:`POST`,body:JSON.stringify(e)})).json()}},this.auth={getConfig:async()=>{let e=this.getRoute(`auth`),t=await this.fetch(`${this.baseUrl}${e}/config`);return this.unwrapResponse(t)},login:async e=>{let t=this.getRoute(`auth`),n=await this.fetch(`${this.baseUrl}${t}/sign-in/email`,{method:`POST`,headers:{Origin:this.baseUrl},body:JSON.stringify(e)}),r=await n.json().catch(()=>({}));if(!n.ok){let e=r?.message||r?.error?.message||`Login failed (HTTP ${n.status})`,t=Error(e);throw r?.code&&(t.code=r.code),t.status=n.status,t}let i=r&&(r.data??(r.token||r.user?{token:r.token,user:r.user}:void 0)),a=i?{...r,data:i}:r;return a.data?.token&&(this.token=a.data.token),a},logout:async()=>{let e=this.getRoute(`auth`);await this.fetch(`${this.baseUrl}${e}/sign-out`,{method:`POST`,headers:{"Content-Type":`application/json`,Origin:this.baseUrl},body:`{}`}),this.token=void 0},me:async()=>{let e=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${e}/get-session`,{headers:{Origin:this.baseUrl}})).json()},register:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/sign-up/email`,{method:`POST`,headers:{Origin:this.baseUrl},body:JSON.stringify(e)})).json(),r=n&&(n.data??(n.token||n.user?{token:n.token,user:n.user}:void 0)),i=r?{...n,data:r}:n;return i.data?.token&&(this.token=i.data.token),i},signInWithProvider:async(e,t)=>{if(typeof window>`u`)throw Error(`signInWithProvider requires a browser environment`);let n=this.getRoute(`auth`),r=t?.callbackURL??window.location.origin+`/login`,i=t?.type===`oidc`,a=i?`/sign-in/oauth2`:`/sign-in/social`,o=i?{providerId:e,callbackURL:r}:{provider:e,callbackURL:r};t?.errorCallbackURL&&(o.errorCallbackURL=t.errorCallbackURL);let s=await(await this.fetch(`${this.baseUrl}${n}${a}`,{method:`POST`,body:JSON.stringify(o)})).json(),c=s?.url??s?.data?.url;if(c)window.location.assign(c);else throw Error(`signInWithProvider: no redirect URL returned for provider "${e}"`)},refreshToken:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/get-session`,{method:`GET`})).json();return n.data?.token&&(this.token=n.data.token),n},bootstrapStatus:async()=>{let e=this.getRoute(`auth`),t=await(await this.fetch(`${this.baseUrl}${e}/bootstrap-status`)).json();return{hasOwner:!!(t?.data??t)?.hasOwner}},updateUser:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/update-user`,{method:`POST`,body:JSON.stringify(e)})).json()},changePassword:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/change-password`,{method:`POST`,body:JSON.stringify(e)})).json()},changeEmail:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/change-email`,{method:`POST`,body:JSON.stringify(e)})).json()},sendVerificationEmail:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/send-verification-email`,{method:`POST`,body:JSON.stringify(e)})).json()},verifyEmail:async e=>{let t=this.getRoute(`auth`),n=new URL(`${this.baseUrl}${t}/verify-email`);return n.searchParams.set(`token`,e.token),e.callbackURL&&n.searchParams.set(`callbackURL`,e.callbackURL),(await this.fetch(n.toString())).json()},deleteUser:async e=>{let t=this.getRoute(`auth`),n=await this.fetch(`${this.baseUrl}${t}/delete-user`,{method:`POST`,body:JSON.stringify(e)});return this.token=void 0,n.json()},sessions:{list:async()=>{let e=this.getRoute(`auth`),t=await(await this.fetch(`${this.baseUrl}${e}/list-sessions`)).json();return{sessions:Array.isArray(t)?t:t?.data??t?.sessions??[]}},revoke:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/revoke-session`,{method:`POST`,body:JSON.stringify({token:e})})).json()},revokeOthers:async()=>{let e=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${e}/revoke-other-sessions`,{method:`POST`,body:`{}`})).json()},revokeAll:async()=>{let e=this.getRoute(`auth`),t=await this.fetch(`${this.baseUrl}${e}/revoke-sessions`,{method:`POST`,body:`{}`});return this.token=void 0,t.json()}},twoFactor:{enable:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/two-factor/enable`,{method:`POST`,body:JSON.stringify(e)})).json();return n?.data??n},verifyTotp:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/two-factor/verify-totp`,{method:`POST`,body:JSON.stringify(e)})).json()},disable:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/two-factor/disable`,{method:`POST`,body:JSON.stringify(e)})).json()},generateBackupCodes:async e=>{let t=this.getRoute(`auth`),n=await(await this.fetch(`${this.baseUrl}${t}/two-factor/generate-backup-codes`,{method:`POST`,body:JSON.stringify(e)})).json();return n?.data??n},verifyBackupCode:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/two-factor/verify-backup-code`,{method:`POST`,body:JSON.stringify(e)})).json()}},accounts:{list:async()=>{let e=this.getRoute(`auth`),t=await(await this.fetch(`${this.baseUrl}${e}/list-accounts`)).json();return{accounts:Array.isArray(t)?t:t?.data??t?.accounts??[]}},unlink:async e=>{let t=this.getRoute(`auth`);return(await this.fetch(`${this.baseUrl}${t}/unlink-account`,{method:`POST`,body:JSON.stringify(e)})).json()},linkSocial:async e=>{let t=this.getRoute(`auth`),n=e.callbackURL??(typeof window<`u`?window.location.href:void 0),r=await(await this.fetch(`${this.baseUrl}${t}/link-social`,{method:`POST`,body:JSON.stringify({provider:e.provider,callbackURL:n})})).json();return r?.data??r}}},this.storage={upload:async(e,t=`user`)=>{let n={filename:e.name,mimeType:e.type,size:e.size,scope:t},r=this.getRoute(`storage`),{data:i}=await(await this.fetch(`${this.baseUrl}${r}/upload/presigned`,{method:`POST`,body:JSON.stringify(n)})).json(),a=await this.fetchImpl(i.uploadUrl,{method:i.method,headers:i.headers,body:e});if(!a.ok)throw Error(`Storage Upload Failed: ${a.statusText}`);let o={fileId:i.fileId};return(await this.fetch(`${this.baseUrl}${r}/upload/complete`,{method:`POST`,body:JSON.stringify(o)})).json()},getDownloadUrl:async e=>{let t=this.getRoute(`storage`);return(await(await this.fetch(`${this.baseUrl}${t}/files/${e}/url`)).json()).url},getPresignedUrl:async e=>{let t=this.getRoute(`storage`);return(await this.fetch(`${this.baseUrl}${t}/upload/presigned`,{method:`POST`,body:JSON.stringify(e)})).json()},initChunkedUpload:async e=>{let t=this.getRoute(`storage`);return(await this.fetch(`${this.baseUrl}${t}/upload/chunked`,{method:`POST`,body:JSON.stringify(e)})).json()},uploadPart:async(e,t,n,r)=>{let i=this.getRoute(`storage`);return(await this.fetch(`${this.baseUrl}${i}/upload/chunked/${e}/chunk/${t}`,{method:`PUT`,headers:{"x-resume-token":n},body:r})).json()},completeChunkedUpload:async e=>{let t=this.getRoute(`storage`);return(await this.fetch(`${this.baseUrl}${t}/upload/chunked/${e.uploadId}/complete`,{method:`POST`,body:JSON.stringify(e)})).json()},resumeUpload:async(e,t,n,r)=>{let i=this.getRoute(`storage`),{totalChunks:a,uploadedChunks:o}=(await(await this.fetch(`${this.baseUrl}${i}/upload/chunked/${e}/progress`)).json()).data,s=[],c=t instanceof ArrayBuffer?t:await t.arrayBuffer();for(let t=o;t<a;t++){let i=t*n,a=Math.min(i+n,c.byteLength),o=new Blob([c.slice(i,a)]),l=await this.storage.uploadPart(e,t,r,o);s.push({chunkIndex:t,eTag:l.data.eTag})}return this.storage.completeChunkedUpload({uploadId:e,parts:s})}},this.automation={trigger:async(e,t)=>{let n=this.getRoute(`automation`);return(await this.fetch(`${this.baseUrl}${n}/trigger/${e}`,{method:`POST`,body:JSON.stringify(t)})).json()},list:async()=>{let e=this.getRoute(`automation`),t=await this.fetch(`${this.baseUrl}${e}`);return this.unwrapResponse(t)},get:async e=>{let t=this.getRoute(`automation`),n=await this.fetch(`${this.baseUrl}${t}/${e}`);return this.unwrapResponse(n)},create:async(e,t)=>{let n=this.getRoute(`automation`),r=await this.fetch(`${this.baseUrl}${n}`,{method:`POST`,body:JSON.stringify({name:e,...t})});return this.unwrapResponse(r)},update:async(e,t)=>{let n=this.getRoute(`automation`),r=await this.fetch(`${this.baseUrl}${n}/${e}`,{method:`PUT`,body:JSON.stringify({definition:t})});return this.unwrapResponse(r)},delete:async e=>{let t=this.getRoute(`automation`),n=await this.fetch(`${this.baseUrl}${t}/${e}`,{method:`DELETE`});return this.unwrapResponse(n)},toggle:async(e,t)=>{let n=this.getRoute(`automation`),r=await this.fetch(`${this.baseUrl}${n}/${e}/toggle`,{method:`POST`,body:JSON.stringify({enabled:t})});return this.unwrapResponse(r)},runs:{list:async(e,t)=>{let n=this.getRoute(`automation`),r=new URLSearchParams;t?.limit&&r.set(`limit`,String(t.limit)),t?.cursor&&r.set(`cursor`,t.cursor);let i=r.toString(),a=await this.fetch(`${this.baseUrl}${n}/${e}/runs${i?`?${i}`:``}`);return this.unwrapResponse(a)},get:async(e,t)=>{let n=this.getRoute(`automation`),r=await this.fetch(`${this.baseUrl}${n}/${e}/runs/${t}`);return this.unwrapResponse(r)}},getFlow:async e=>{let t=this.getRoute(`automation`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}`);return this.unwrapResponse(n)},execute:async(e,t)=>{let n=this.getRoute(`automation`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/trigger`,{method:`POST`,body:JSON.stringify(t??{})});return this.unwrapResponse(r)},listRuns:async(e,t)=>{let n=this.getRoute(`automation`),r=new URLSearchParams;t?.limit!=null&&r.set(`limit`,String(t.limit)),t?.cursor&&r.set(`cursor`,t.cursor);let i=r.toString(),a=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/runs${i?`?${i}`:``}`);return this.unwrapResponse(a)},getRun:async(e,t)=>{let n=this.getRoute(`automation`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/runs/${encodeURIComponent(t)}`);return this.unwrapResponse(r)}},this.permissions={check:async e=>{let t=this.getRoute(`permissions`),n=new URLSearchParams({object:e.object,action:e.action});e.recordId!==void 0&&n.set(`recordId`,e.recordId),e.field!==void 0&&n.set(`field`,e.field);let r=await this.fetch(`${this.baseUrl}${t}/check?${n.toString()}`);return this.unwrapResponse(r)},getObjectPermissions:async e=>{let t=this.getRoute(`permissions`),n=await this.fetch(`${this.baseUrl}${t}/objects/${encodeURIComponent(e)}`);return this.unwrapResponse(n)},getEffectivePermissions:async()=>{let e=this.getRoute(`permissions`),t=await this.fetch(`${this.baseUrl}${e}/effective`);return this.unwrapResponse(t)}},this.realtime={connect:async e=>{let t=this.getRoute(`realtime`),n=await this.fetch(`${this.baseUrl}${t}/connect`,{method:`POST`,body:JSON.stringify(e||{})});return this.unwrapResponse(n)},disconnect:async()=>{let e=this.getRoute(`realtime`);await this.fetch(`${this.baseUrl}${e}/disconnect`,{method:`POST`})},subscribe:async e=>{let t=this.getRoute(`realtime`),n=await this.fetch(`${this.baseUrl}${t}/subscribe`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(n)},unsubscribe:async e=>{let t=this.getRoute(`realtime`);await this.fetch(`${this.baseUrl}${t}/unsubscribe`,{method:`POST`,body:JSON.stringify({subscriptionId:e})})},setPresence:async(e,t)=>{let n=this.getRoute(`realtime`);await this.fetch(`${this.baseUrl}${n}/presence`,{method:`PUT`,body:JSON.stringify({channel:e,state:t})})},getPresence:async e=>{let t=this.getRoute(`realtime`),n=await this.fetch(`${this.baseUrl}${t}/presence/${encodeURIComponent(e)}`);return this.unwrapResponse(n)}},this.workflow={getConfig:async e=>{let t=this.getRoute(`workflow`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e)}/config`);return this.unwrapResponse(n)},getState:async(e,t)=>{let n=this.getRoute(`workflow`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/state`);return this.unwrapResponse(r)},transition:async e=>{let t=this.getRoute(`workflow`),n=await this.fetch(`${this.baseUrl}${t}/${encodeURIComponent(e.object)}/${encodeURIComponent(e.recordId)}/transition`,{method:`POST`,body:JSON.stringify({transition:e.transition,comment:e.comment,data:e.data})});return this.unwrapResponse(n)}},this.approvals={listRequests:async e=>{let t=this.getRoute(`approvals`),n=new URLSearchParams;e?.object&&n.set(`object`,e.object),e?.recordId&&n.set(`recordId`,e.recordId),e?.status&&n.set(`status`,Array.isArray(e.status)?e.status.join(`,`):e.status),e?.approverId&&n.set(`approverId`,Array.isArray(e.approverId)?e.approverId.join(`,`):e.approverId),e?.submitterId&&n.set(`submitterId`,e.submitterId);let r=n.toString(),i=await this.fetch(`${this.baseUrl}${t}/requests${r?`?${r}`:``}`),a=await this.unwrapResponse(i);return Array.isArray(a)?a:a?.data??[]},getRequest:async e=>{let t=this.getRoute(`approvals`),n=await this.fetch(`${this.baseUrl}${t}/requests/${encodeURIComponent(e)}`);return this.unwrapResponse(n)},approve:async(e,t)=>{let n=this.getRoute(`approvals`),r=await this.fetch(`${this.baseUrl}${n}/requests/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({actorId:t?.actorId,comment:t?.comment})});return this.unwrapResponse(r)},reject:async(e,t)=>{let n=this.getRoute(`approvals`),r=await this.fetch(`${this.baseUrl}${n}/requests/${encodeURIComponent(e)}/reject`,{method:`POST`,body:JSON.stringify({actorId:t?.actorId,comment:t?.comment})});return this.unwrapResponse(r)},listActions:async e=>{let t=this.getRoute(`approvals`),n=await this.fetch(`${this.baseUrl}${t}/requests/${encodeURIComponent(e)}/actions`),r=await this.unwrapResponse(n);return Array.isArray(r)?r:r?.data??[]}},this.views={list:async(e,t)=>{let n=this.getRoute(`views`),r=new URLSearchParams;t&&r.set(`type`,t);let i=r.toString(),a=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}${i?`?${i}`:``}`);return this.unwrapResponse(a)},get:async(e,t)=>{let n=this.getRoute(`views`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`);return this.unwrapResponse(r)},create:async(e,t)=>{let n=this.getRoute(`views`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}`,{method:`POST`,body:JSON.stringify({object:e,data:t})});return this.unwrapResponse(r)},update:async(e,t,n)=>{let r=this.getRoute(`views`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PUT`,body:JSON.stringify({object:e,viewId:t,data:n})});return this.unwrapResponse(i)},delete:async(e,t)=>{let n=this.getRoute(`views`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`DELETE`});return this.unwrapResponse(r)}},this.notifications={registerDevice:async e=>{let t=this.getRoute(`notifications`),n=await this.fetch(`${this.baseUrl}${t}/devices`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(n)},unregisterDevice:async e=>{let t=this.getRoute(`notifications`),n=await this.fetch(`${this.baseUrl}${t}/devices/${encodeURIComponent(e)}`,{method:`DELETE`});return this.unwrapResponse(n)},getPreferences:async()=>{let e=this.getRoute(`notifications`),t=await this.fetch(`${this.baseUrl}${e}/preferences`);return this.unwrapResponse(t)},updatePreferences:async e=>{let t=this.getRoute(`notifications`),n=await this.fetch(`${this.baseUrl}${t}/preferences`,{method:`PUT`,body:JSON.stringify({preferences:e})});return this.unwrapResponse(n)},list:async e=>{let t=this.getRoute(`notifications`),n=new URLSearchParams;e?.read!==void 0&&n.set(`read`,String(e.read)),e?.type&&n.set(`type`,e.type),e?.limit&&n.set(`limit`,String(e.limit)),e?.cursor&&n.set(`cursor`,e.cursor);let r=n.toString(),i=await this.fetch(`${this.baseUrl}${t}${r?`?${r}`:``}`);return this.unwrapResponse(i)},markRead:async e=>{let t=this.getRoute(`notifications`),n=await this.fetch(`${this.baseUrl}${t}/read`,{method:`POST`,body:JSON.stringify({ids:e})});return this.unwrapResponse(n)},markAllRead:async()=>{let e=this.getRoute(`notifications`),t=await this.fetch(`${this.baseUrl}${e}/read/all`,{method:`POST`});return this.unwrapResponse(t)}},this.ai={nlq:async e=>{let t=this.getRoute(`ai`),n=await this.fetch(`${this.baseUrl}${t}/nlq`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(n)},suggest:async e=>{let t=this.getRoute(`ai`),n=await this.fetch(`${this.baseUrl}${t}/suggest`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(n)},insights:async e=>{let t=this.getRoute(`ai`),n=await this.fetch(`${this.baseUrl}${t}/insights`,{method:`POST`,body:JSON.stringify(e)});return this.unwrapResponse(n)}},this.i18n={getLocales:async()=>{let e=this.getRoute(`i18n`),t=await this.fetch(`${this.baseUrl}${e}/locales`);return this.unwrapResponse(t)},getTranslations:async(e,t)=>{let n=this.getRoute(`i18n`),r=new URLSearchParams;r.set(`locale`,e),t?.namespace&&r.set(`namespace`,t.namespace),t?.keys&&r.set(`keys`,t.keys.join(`,`));let i=await this.fetch(`${this.baseUrl}${n}/translations?${r.toString()}`);return this.unwrapResponse(i)},getFieldLabels:async(e,t)=>{let n=this.getRoute(`i18n`),r=await this.fetch(`${this.baseUrl}${n}/labels/${encodeURIComponent(e)}?locale=${encodeURIComponent(t)}`);return this.unwrapResponse(r)}},this.feed={list:async(e,t,n)=>{let r=this.getRoute(`data`),i=new URLSearchParams;n?.type&&i.set(`type`,n.type),n?.limit&&i.set(`limit`,String(n.limit)),n?.cursor&&i.set(`cursor`,n.cursor);let a=i.toString(),o=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed${a?`?${a}`:``}`);return this.unwrapResponse(o)},create:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed`,{method:`POST`,body:JSON.stringify(n)});return this.unwrapResponse(i)},update:async(e,t,n,r)=>{let i=this.getRoute(`data`),a=await this.fetch(`${this.baseUrl}${i}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}`,{method:`PUT`,body:JSON.stringify(r)});return this.unwrapResponse(a)},delete:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}`,{method:`DELETE`});return this.unwrapResponse(i)},addReaction:async(e,t,n,r)=>{let i=this.getRoute(`data`),a=await this.fetch(`${this.baseUrl}${i}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}/reactions`,{method:`POST`,body:JSON.stringify({emoji:r})});return this.unwrapResponse(a)},removeReaction:async(e,t,n,r)=>{let i=this.getRoute(`data`),a=await this.fetch(`${this.baseUrl}${i}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}/reactions/${encodeURIComponent(r)}`,{method:`DELETE`});return this.unwrapResponse(a)},pin:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}/pin`,{method:`POST`});return this.unwrapResponse(i)},unpin:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}/pin`,{method:`DELETE`});return this.unwrapResponse(i)},star:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}/star`,{method:`POST`});return this.unwrapResponse(i)},unstar:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/${encodeURIComponent(n)}/star`,{method:`DELETE`});return this.unwrapResponse(i)},search:async(e,t,n,r)=>{let i=this.getRoute(`data`),a=new URLSearchParams;a.set(`query`,n),r?.type&&a.set(`type`,r.type),r?.actorId&&a.set(`actorId`,r.actorId),r?.dateFrom&&a.set(`dateFrom`,r.dateFrom),r?.dateTo&&a.set(`dateTo`,r.dateTo),r?.limit&&a.set(`limit`,String(r.limit)),r?.cursor&&a.set(`cursor`,r.cursor);let o=await this.fetch(`${this.baseUrl}${i}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/feed/search?${a.toString()}`);return this.unwrapResponse(o)},getChangelog:async(e,t,n)=>{let r=this.getRoute(`data`),i=new URLSearchParams;n?.field&&i.set(`field`,n.field),n?.actorId&&i.set(`actorId`,n.actorId),n?.dateFrom&&i.set(`dateFrom`,n.dateFrom),n?.dateTo&&i.set(`dateTo`,n.dateTo),n?.limit&&i.set(`limit`,String(n.limit)),n?.cursor&&i.set(`cursor`,n.cursor);let a=i.toString(),o=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/changelog${a?`?${a}`:``}`);return this.unwrapResponse(o)},subscribe:async(e,t,n)=>{let r=this.getRoute(`data`),i=await this.fetch(`${this.baseUrl}${r}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/subscribe`,{method:`POST`,body:JSON.stringify(n||{})});return this.unwrapResponse(i)},unsubscribe:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/subscribe`,{method:`DELETE`});return this.unwrapResponse(r)}},this.data={query:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}/query`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(r)},find:async(e,t={})=>{let n=this.getRoute(`data`),r=new URLSearchParams,i=t,a={};if(`where`in t||`fields`in t||`orderBy`in t||`offset`in t?(i.where&&(a.filter=i.where),i.fields&&(a.select=i.fields),i.orderBy&&(a.sort=i.orderBy),i.limit!=null&&(a.top=i.limit),i.offset!=null&&(a.skip=i.offset),i.aggregations&&(a.aggregations=i.aggregations),i.groupBy&&(a.groupBy=i.groupBy)):Object.assign(a,t),a.top&&r.set(`top`,a.top.toString()),a.skip&&r.set(`skip`,a.skip.toString()),a.sort)if(Array.isArray(a.sort)&&typeof a.sort[0]==`object`)r.set(`sort`,JSON.stringify(a.sort));else{let e=Array.isArray(a.sort)?a.sort.join(`,`):a.sort;r.set(`sort`,e)}a.select&&r.set(`select`,a.select.join(`,`));let o=a.filter??a.filters;o&&(this.isFilterAST(o)||Array.isArray(o)?r.set(`filter`,JSON.stringify(o)):typeof o==`object`&&o&&Object.entries(o).forEach(([e,t])=>{t!=null&&r.append(e,String(t))})),a.aggregations&&r.set(`aggregations`,JSON.stringify(a.aggregations)),a.groupBy&&r.set(`groupBy`,a.groupBy.join(`,`));let s=await this.fetch(`${this.baseUrl}${n}/${e}?${r.toString()}`);return this.unwrapResponse(s)},get:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}/${t}`);return this.unwrapResponse(r)},create:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(r)},createMany:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}/createMany`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(r)},import:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}/import`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(r)},createImportJob:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}/import/jobs`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(r)},getImportJobProgress:async e=>{let t=this.getRoute(`data`),n=await this.fetch(`${this.baseUrl}${t}/import/jobs/${encodeURIComponent(e)}`);return this.unwrapResponse(n)},getImportJobResults:async e=>{let t=this.getRoute(`data`),n=await this.fetch(`${this.baseUrl}${t}/import/jobs/${encodeURIComponent(e)}/results`);return this.unwrapResponse(n)},listImportJobs:async(e={})=>{let t=this.getRoute(`data`),n=new URLSearchParams;e.object&&n.set(`object`,e.object),e.status&&n.set(`status`,e.status),e.limit!=null&&n.set(`limit`,String(e.limit)),e.offset!=null&&n.set(`offset`,String(e.offset));let r=n.toString()?`?${n.toString()}`:``,i=await this.fetch(`${this.baseUrl}${t}/import/jobs${r}`);return(await this.unwrapResponse(i)).jobs},cancelImportJob:async e=>{let t=this.getRoute(`data`),n=await this.fetch(`${this.baseUrl}${t}/import/jobs/${encodeURIComponent(e)}/cancel`,{method:`POST`});return this.unwrapResponse(n)},undoImportJob:async e=>{let t=this.getRoute(`data`),n=await this.fetch(`${this.baseUrl}${t}/import/jobs/${encodeURIComponent(e)}/undo`,{method:`POST`});return this.unwrapResponse(n)},update:async(e,t,n,r)=>{let i=this.getRoute(`data`),a={};r?.ifMatch&&(a[`If-Match`]=String(r.ifMatch));let o=await this.fetch(`${this.baseUrl}${i}/${e}/${t}`,{method:`PATCH`,body:JSON.stringify(n),...Object.keys(a).length?{headers:a}:{}});return this.unwrapResponse(o)},batch:async(e,t)=>{let n=this.getRoute(`data`),r=await this.fetch(`${this.baseUrl}${n}/${e}/batch`,{method:`POST`,body:JSON.stringify(t)});return this.unwrapResponse(r)},updateMany:async(e,t,n)=>{let r=this.getRoute(`data`),i={records:t,options:n},a=await this.fetch(`${this.baseUrl}${r}/${e}/updateMany`,{method:`POST`,body:JSON.stringify(i)});return this.unwrapResponse(a)},delete:async(e,t,n)=>{let r=this.getRoute(`data`),i={};n?.ifMatch&&(i[`If-Match`]=String(n.ifMatch));let a=await this.fetch(`${this.baseUrl}${r}/${e}/${t}`,{method:`DELETE`,...Object.keys(i).length?{headers:i}:{}});return this.unwrapResponse(a)},deleteMany:async(e,t,n)=>{let r=this.getRoute(`data`),i={ids:t,options:n},a=await this.fetch(`${this.baseUrl}${r}/${e}/deleteMany`,{method:`POST`,body:JSON.stringify(i)});return this.unwrapResponse(a)}},this.baseUrl=e.baseUrl.replace(/\/$/,``),this.token=e.token,this.environmentId=e.environmentId,this.locale=e.locale,this.fetchImpl=e.fetch||globalThis.fetch.bind(globalThis),this.logger=e.logger||(0,ee.createLogger)({level:e.debug?`debug`:`info`,format:`pretty`}),this.realtimeAPI=new p(this.baseUrl,this.token),this.logger.debug(`ObjectStack client created`,{baseUrl:this.baseUrl})}async connect(){this.logger.debug(`Connecting to ObjectStack server`,{baseUrl:this.baseUrl});try{let e;try{let t=`${this.baseUrl}/api/v1/discovery`;this.logger.debug(`Probing protocol-standard discovery endpoint`,{url:t});let n=await this.fetchImpl(t);if(n.ok){let t=await n.json();e=t.data||t,this.logger.debug(`Discovered via /api/v1/discovery`)}}catch(e){this.logger.debug(`Protocol-standard discovery probe failed`,{error:e.message})}if(!e){let t;try{t=`${new URL(this.baseUrl).origin}/.well-known/objectstack`}catch{t=`/.well-known/objectstack`}this.logger.debug(`Falling back to .well-known discovery`,{url:t});let n=await this.fetchImpl(t);if(!n.ok)throw Error(`Failed to connect to ${t}: ${n.statusText}`);let r=await n.json();e=r.data||r}if(!e)throw Error(`Connection failed: No discovery data returned`);return this.discoveryInfo=e,this.logger.info(`Connected to ObjectStack server`,{version:e.version,apiName:e.apiName,services:e.services}),e}catch(e){throw this.logger.error(`Failed to connect to ObjectStack server`,e,{baseUrl:this.baseUrl}),e}}get capabilities(){let e=this.discoveryInfo?.capabilities;if(!e)return;let t={};for(let[n,r]of Object.entries(e))t[n]=typeof r==`object`&&r?!!r.enabled:!!r;return t}project(e){if(!e)throw Error(`[ObjectStack] project(id): environmentId is required`);return new y(this,e)}_baseUrl(){return this.baseUrl}_fetch(e,t){return this.fetch(e,t)}_unwrap(e){return this.unwrapResponse(e)}_isFilterAST(e){return this.isFilterAST(e)}setProjectId(e){this.environmentId=e,this.logger.debug(`Active project changed`,{environmentId:e})}getProjectId(){return this.environmentId}setLocale(e){this.locale=e,this.logger.debug(`Active locale changed`,{locale:e})}getLocale(){return this.locale}get events(){return this.realtimeAPI}isFilterAST(e){return(0,f.isFilterAST)(e)}async unwrapResponse(e){let t=await e.json();return t&&typeof t.success==`boolean`&&`data`in t?t.data:t}async fetch(e,t={}){this.logger.debug(`HTTP request`,{method:t.method||`GET`,url:e,hasBody:!!t.body});let n={"Content-Type":`application/json`,...t.headers||{}};this.token&&(n.Authorization=`Bearer ${this.token}`),this.environmentId&&(n[`X-Environment-Id`]=this.environmentId),this.locale&&!Object.keys(n).some(e=>e.toLowerCase()===`accept-language`)&&(n[`Accept-Language`]=this.locale);let r=await this.fetchImpl(e,{...t,headers:n});if(this.logger.debug(`HTTP response`,{method:t.method||`GET`,url:e,status:r.status,ok:r.ok}),!r.ok){let n;try{n=await r.json()}catch{n={message:r.statusText}}this.logger.error(`HTTP request failed`,void 0,{method:t.method||`GET`,url:e,status:r.status,error:n});let i=n?.message??n?.error?.message??(typeof n?.error==`string`?n.error:void 0)??r.statusText,a=n?.code||n?.error?.code,o=Error(`[ObjectStack] ${a?`${a}: `:``}${i}`);throw o.code=a,o.category=n?.category,o.httpStatus=r.status,o.retryable=n?.retryable,o.details=n?.details||n,o}return r}getRoute(e){let t=this.discoveryInfo?.routes;if(t){let n=t[e];if(n)return n}return{data:`/api/v1/data`,metadata:`/api/v1/meta`,discovery:`/api/v1/discovery`,ui:`/api/v1/ui`,auth:`/api/v1/auth`,analytics:`/api/v1/analytics`,storage:`/api/v1/storage`,automation:`/api/v1/automation`,packages:`/api/v1/packages`,permissions:`/api/v1/permissions`,realtime:`/api/v1/realtime`,workflow:`/api/v1/workflow`,approvals:`/api/v1/approvals`,views:`/api/v1/ui/views`,notifications:`/api/v1/notifications`,ai:`/api/v1/ai`,i18n:`/api/v1/i18n`,feed:`/api/v1/feed`,graphql:`/graphql`}[e]||`/api/v1/${e}`}},y=class{constructor(e,t){this.meta={getTypes:async()=>{let e=await this.parent._fetch(this.url(`/meta`));return this.parent._unwrap(e)},getItems:async(e,t)=>{let n=new URLSearchParams;t?.packageId&&n.set(`package`,t.packageId);let r=n.toString(),i=await this.parent._fetch(this.url(`/meta/${e}${r?`?${r}`:``}`));return this.parent._unwrap(i)},getItem:async(e,t,n)=>{let r=new URLSearchParams;n?.packageId&&r.set(`package`,n.packageId);let i=r.toString(),a=await this.parent._fetch(this.url(`/meta/${e}/${t}${i?`?${i}`:``}`));return this.parent._unwrap(a)},saveItem:async(e,t,n)=>{let r=await this.parent._fetch(this.url(`/meta/${e}/${t}`),{method:`PUT`,body:JSON.stringify(n)});return this.parent._unwrap(r)},deleteItem:async(e,t)=>{let n=await this.parent._fetch(this.url(`/meta/${encodeURIComponent(e)}/${encodeURIComponent(t)}`),{method:`DELETE`});return this.parent._unwrap(n)},getHistory:async(e,t,n)=>{let r=new URLSearchParams;n?.sinceSeq!==void 0&&r.set(`sinceSeq`,String(n.sinceSeq)),n?.limit!==void 0&&r.set(`limit`,String(n.limit));let i=r.toString(),a=await this.parent._fetch(this.url(`/meta/${encodeURIComponent(e)}/${encodeURIComponent(t)}/history${i?`?${i}`:``}`));return this.parent._unwrap(a)}},this.data={query:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/query`),{method:`POST`,body:JSON.stringify(t)});return this.parent._unwrap(n)},find:async(e,t={})=>{let n=new URLSearchParams,r=t,i={};if(`where`in t||`fields`in t||`orderBy`in t||`offset`in t?(r.where&&(i.filter=r.where),r.fields&&(i.select=r.fields),r.orderBy&&(i.sort=r.orderBy),r.limit!=null&&(i.top=r.limit),r.offset!=null&&(i.skip=r.offset),r.aggregations&&(i.aggregations=r.aggregations),r.groupBy&&(i.groupBy=r.groupBy)):Object.assign(i,t),i.top&&n.set(`top`,i.top.toString()),i.skip&&n.set(`skip`,i.skip.toString()),i.sort)if(Array.isArray(i.sort)&&typeof i.sort[0]==`object`)n.set(`sort`,JSON.stringify(i.sort));else{let e=Array.isArray(i.sort)?i.sort.join(`,`):i.sort;n.set(`sort`,e)}i.select&&n.set(`select`,i.select.join(`,`));let a=i.filter??i.filters;a&&(this.parent._isFilterAST(a)||Array.isArray(a)?n.set(`filter`,JSON.stringify(a)):typeof a==`object`&&a&&Object.entries(a).forEach(([e,t])=>{t!=null&&n.append(e,String(t))})),i.aggregations&&n.set(`aggregations`,JSON.stringify(i.aggregations)),i.groupBy&&n.set(`groupBy`,i.groupBy.join(`,`));let o=n.toString(),s=await this.parent._fetch(this.url(`/data/${e}${o?`?${o}`:``}`));return this.parent._unwrap(s)},get:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/${t}`));return this.parent._unwrap(n)},create:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}`),{method:`POST`,body:JSON.stringify(t)});return this.parent._unwrap(n)},createMany:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/createMany`),{method:`POST`,body:JSON.stringify(t)});return this.parent._unwrap(n)},import:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/import`),{method:`POST`,body:JSON.stringify(t)});return this.parent._unwrap(n)},createImportJob:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/import/jobs`),{method:`POST`,body:JSON.stringify(t)});return this.parent._unwrap(n)},getImportJobProgress:async e=>{let t=await this.parent._fetch(this.url(`/data/import/jobs/${encodeURIComponent(e)}`));return this.parent._unwrap(t)},getImportJobResults:async e=>{let t=await this.parent._fetch(this.url(`/data/import/jobs/${encodeURIComponent(e)}/results`));return this.parent._unwrap(t)},listImportJobs:async(e={})=>{let t=new URLSearchParams;e.object&&t.set(`object`,e.object),e.status&&t.set(`status`,e.status),e.limit!=null&&t.set(`limit`,String(e.limit)),e.offset!=null&&t.set(`offset`,String(e.offset));let n=t.toString()?`?${t.toString()}`:``,r=await this.parent._fetch(this.url(`/data/import/jobs${n}`));return(await this.parent._unwrap(r)).jobs},cancelImportJob:async e=>{let t=await this.parent._fetch(this.url(`/data/import/jobs/${encodeURIComponent(e)}/cancel`),{method:`POST`});return this.parent._unwrap(t)},undoImportJob:async e=>{let t=await this.parent._fetch(this.url(`/data/import/jobs/${encodeURIComponent(e)}/undo`),{method:`POST`});return this.parent._unwrap(t)},update:async(e,t,n)=>{let r=await this.parent._fetch(this.url(`/data/${e}/${t}`),{method:`PATCH`,body:JSON.stringify(n)});return this.parent._unwrap(r)},batch:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/batch`),{method:`POST`,body:JSON.stringify(t)});return this.parent._unwrap(n)},updateMany:async(e,t,n)=>{let r={records:t,options:n},i=await this.parent._fetch(this.url(`/data/${e}/updateMany`),{method:`POST`,body:JSON.stringify(r)});return this.parent._unwrap(i)},delete:async(e,t)=>{let n=await this.parent._fetch(this.url(`/data/${e}/${t}`),{method:`DELETE`});return this.parent._unwrap(n)},deleteMany:async(e,t,n)=>{let r={ids:t,options:n},i=await this.parent._fetch(this.url(`/data/${e}/deleteMany`),{method:`POST`,body:JSON.stringify(r)});return this.parent._unwrap(i)}},this.packages={list:async()=>{let e=await this.parent._fetch(this.url(`/packages`));return this.parent._unwrap(e)},get:async(e,t)=>{let n=t?`?version=${encodeURIComponent(t)}`:``,r=await this.parent._fetch(this.url(`/packages/${encodeURIComponent(e)}${n}`));return this.parent._unwrap(r)}},this.automation={getFlow:async e=>{let t=await this.parent._fetch(this.url(`/automation/${encodeURIComponent(e)}`));return this.parent._unwrap(t)},execute:async(e,t)=>{let n=await this.parent._fetch(this.url(`/automation/${encodeURIComponent(e)}/trigger`),{method:`POST`,body:JSON.stringify(t??{})});return this.parent._unwrap(n)},listRuns:async(e,t)=>{let n=new URLSearchParams;t?.limit!=null&&n.set(`limit`,String(t.limit)),t?.cursor&&n.set(`cursor`,t.cursor);let r=n.toString(),i=await this.parent._fetch(this.url(`/automation/${encodeURIComponent(e)}/runs${r?`?${r}`:``}`));return this.parent._unwrap(i)},getRun:async(e,t)=>{let n=await this.parent._fetch(this.url(`/automation/${encodeURIComponent(e)}/runs/${encodeURIComponent(t)}`));return this.parent._unwrap(n)}},this.parent=e,this.environmentId=t}getProjectId(){return this.environmentId}scope(){return`/api/v1/environments/${encodeURIComponent(this.environmentId)}`}url(e){return`${this.parent._baseUrl()}${this.scope()}${e}`}};0&&(t.exports={FilterBuilder:m,ObjectStackClient:v,QueryBuilder:h,RealtimeAPI:p,ScopedProjectClient:y,createFilter:_,createQuery:g})}))(),o=class{cache;inflight;maxSize;ttl;stats;constructor(e={}){this.cache=new Map,this.inflight=new Map,this.maxSize=e.maxSize||100,this.ttl=e.ttl||300*1e3,this.stats={hits:0,misses:0,evictions:0,coalesced:0}}async get(e,t){let n=Date.now(),r=this.cache.get(e);if(r){if(n-r.timestamp<this.ttl)return r.accessCount++,r.lastAccessed=n,this.stats.hits++,this.cache.delete(e),this.cache.set(e,r),r.data;this.cache.delete(e)}let i=this.inflight.get(e);if(i)return this.stats.coalesced++,i;this.stats.misses++;let a=(async()=>{try{let n=await t();return this.set(e,n),n}finally{this.inflight.delete(e)}})();return this.inflight.set(e,a),a}prime(e,t){this.set(e,t)}set(e,t){let n=Date.now();this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictLRU(),this.cache.set(e,{data:t,timestamp:n,accessCount:1,lastAccessed:n})}evictLRU(){let e=this.cache.keys().next().value;e!==void 0&&(this.cache.delete(e),this.stats.evictions++)}invalidate(e){e?this.cache.delete(e):this.cache.clear()}clear(){this.cache.clear(),this.inflight.clear(),this.stats={hits:0,misses:0,evictions:0,coalesced:0}}getStats(){let e=this.stats.hits+this.stats.misses,t=e>0?this.stats.hits/e:0;return{size:this.cache.size,maxSize:this.maxSize,hits:this.stats.hits,misses:this.stats.misses,evictions:this.stats.evictions,coalesced:this.stats.coalesced,hitRate:t}}getCachedSync(e){let t=this.cache.get(e);if(t){if(this.ttl>0&&Date.now()-t.timestamp>this.ttl){this.cache.delete(e);return}return this.cache.delete(e),this.cache.set(e,t),this.stats.hits++,t.data}}has(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>=this.ttl?(this.cache.delete(e),!1):!0:!1}},s=class extends Error{code;statusCode;details;constructor(e,t,n,r){super(e),this.code=t,this.statusCode=n,this.details=r,this.name=`ObjectStackError`,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,details:this.details,stack:this.stack}}},c=class extends s{constructor(e,t){super(`Metadata not found for object: ${e}`,`METADATA_NOT_FOUND`,404,{objectName:e,...t}),this.name=`MetadataNotFoundError`}},l=class extends s{successCount;failureCount;errors;constructor(e,t,n,r,i){super(`Bulk ${e} operation failed: ${t} succeeded, ${n} failed`,`BULK_OPERATION_ERROR`,500,{operation:e,successCount:t,failureCount:n,errors:r,...i}),this.successCount=t,this.failureCount=n,this.errors=r,this.name=`BulkOperationError`}getSummary(){let e=this.successCount+this.failureCount,t=e>0?this.failureCount/e:0;return{operation:this.details?.operation,total:e,successful:this.successCount,failed:this.failureCount,failureRate:t,errors:this.errors}}},u=class extends s{url;constructor(e,t,n,r){super(`Connection error: ${e}`,`CONNECTION_ERROR`,r||503,{url:t,...n}),this.url=t,this.name=`ConnectionError`}},d=class extends s{constructor(e=`Authentication failed`,t,n){super(e,`AUTHENTICATION_ERROR`,n||401,t),this.name=`AuthenticationError`}},f=class extends s{field;validationErrors;constructor(e,t,n,r){super(e,`VALIDATION_ERROR`,400,{field:t,validationErrors:n,...r}),this.field=t,this.validationErrors=n,this.name=`ValidationError`}getValidationErrors(){return this.validationErrors||[]}};function ee(e,t){let n=e?.status||e?.statusCode||500,r=e?.message||e?.statusText||`Unknown error`,i={context:t,response:{status:n,data:e?.data,headers:e?.headers}};switch(n){case 401:return new d(r,i,401);case 403:return new d(r,i,403);case 404:return t?.includes(`metadata`)||t?.includes(`schema`)||t?.includes(`getObjectSchema`)?new c(p(t),i):new s(r,`NOT_FOUND`,404,i);case 400:return new f(r,void 0,e?.data?.errors,i);case 503:return new u(r,e?.config?.url,i,503);case 504:return new u(r,e?.config?.url,i,504);default:return new s(r,`UNKNOWN_ERROR`,n,i)}}function p(e){if(!e)return`unknown`;let t=e.match(/\(([^)]+)\)/);return t?t[1]:`unknown`}var m=`sys_user_preference`;function h(e){let{dataSource:t,userId:n,key:r,resource:i=m,onError:a=()=>{}}=e,o=null,s=Promise.resolve(),c=async()=>{let e={$filter:{user_id:n,key:r},$top:1};return((await t.find(i,e))?.data??[]).find(e=>{if(!e)return!1;let t=e.user_id!==void 0&&e.user_id!==n,i=e.key!==void 0&&e.key!==r;return!t&&!i})??null},l=e=>{if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return[]},u=async e=>{let s=new Date().toISOString();if(o!==null)try{await t.update(i,o,{value:e,updated_at:s});return}catch(e){o=null,a(`save`,e)}let l=await c();if(l&&l.id!==void 0&&l.id!==null){o=l.id,await t.update(i,l.id,{value:e,updated_at:s});return}try{let a=(await t.create(i,{user_id:n,key:r,value:e,updated_at:s}))?.id;a!=null&&(o=a)}catch(n){let r=await c();if(r&&r.id!==void 0&&r.id!==null){o=r.id,await t.update(i,r.id,{value:e,updated_at:s});return}throw n}};return{async load(){try{let e=await c();return e?(e.id!==void 0&&e.id!==null&&(o=e.id),l(e.value)):(o=null,[])}catch(e){return a(`load`,e),[]}},async save(e){let t=s.then(()=>u(e)).catch(e=>{a(`save`,e)});return s=t,t}}}var g=`/meta`,_=`/api/v1`;function v(e){let t=e.baseUrl.replace(/\/+$/,``),n=e.environmentId?`${_}/environments/${encodeURIComponent(e.environmentId)}${g}`:`${_}${g}`;return/\/api\/v\d+$/i.test(t)?`${t.replace(/\/api\/v\d+$/i,``)}${e.environmentId?`${_}/environments/${encodeURIComponent(e.environmentId)}${g}`:`${_}${g}`}`:`${t}${n}`}async function y(e){let t;try{t=await e.json()}catch{t=await e.text().catch(()=>void 0)}let n=t&&typeof t==`object`?t:void 0,r=n?.error,i=(r&&typeof r==`object`?r.message:r)??n?.message??`Metadata request failed: ${e.status} ${e.statusText}`,a=Error(String(i));a.status=e.status,a.body=t;let o=r&&typeof r==`object`?r.details:void 0,s=o?.issues??(r&&typeof r==`object`?r.issues:void 0)??n?.issues;Array.isArray(s)&&(a.issues=s);let c=o?.code??(r&&typeof r==`object`?r.code:void 0)??n?.code;return c!=null&&(a.code=String(c)),a}var te=class e{base;fetchImpl;headers;previewDrafts;constructor(e){this.base=v(e),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.headers={Accept:`application/json`,...e.headers??{}},this.previewDrafts=e.previewDrafts===!0}withEnvironment(t){return new e({baseUrl:this.base.replace(/\/api\/v\d+(?:\/environments\/[^/]+)?\/meta$/,``).replace(/\/+$/,``),environmentId:t,fetch:this.fetchImpl,headers:this.headers,previewDrafts:this.previewDrafts})}withPreviewDrafts(t){if(t===this.previewDrafts)return this;let n=this.base.match(/\/api\/v\d+\/environments\/([^/]+)\/meta$/);return new e({baseUrl:this.base.replace(/\/api\/v\d+(?:\/environments\/[^/]+)?\/meta$/,``).replace(/\/+$/,``),...n?{environmentId:decodeURIComponent(n[1])}:{},fetch:this.fetchImpl,headers:this.headers,previewDrafts:t})}async listTypes(){let e=await this.fetchImpl(this.base,{method:`GET`,headers:this.headers,cache:`no-store`});if(!e.ok)throw await y(e);let t=await e.json();return Array.isArray(t)?t:t&&Array.isArray(t.entries)?t.entries:t&&Array.isArray(t.items)?t.items:t&&Array.isArray(t.types)?t.types.map(e=>({type:e})):[]}async list(e,t={}){let n=[];t.packageId&&n.push(`package=${encodeURIComponent(t.packageId)}`),this.previewDrafts&&n.push(`preview=draft`);let r=n.length?`?${n.join(`&`)}`:``,i=`${this.base}/${encodeURIComponent(e)}${r}`,a=await this.fetchImpl(i,{method:`GET`,headers:this.headers,cache:`no-store`});if(!a.ok)throw await y(a);let o=await a.json();return Array.isArray(o)?o:o&&Array.isArray(o.items)?o.items:[]}async listDrafts(e={}){let t=[];e.packageId&&t.push(`packageId=${encodeURIComponent(e.packageId)}`),e.type&&t.push(`type=${encodeURIComponent(e.type)}`);let n=t.length?`?${t.join(`&`)}`:``,r=`${this.base}/_drafts${n}`,i=await this.fetchImpl(r,{method:`GET`,headers:this.headers,cache:`no-store`});if(!i.ok)throw await y(i);let a=await i.json();return Array.isArray(a)?a:a?.drafts??a?.data?.drafts??[]}async get(e,t,n={}){let r=[];n.state===`draft`?r.push(`state=draft`):this.previewDrafts&&r.push(`preview=draft`),n.packageId&&r.push(`package=${encodeURIComponent(n.packageId)}`);let i=r.length?`?${r.join(`&`)}`:``,a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${i}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(o.status===404)return null;if(!o.ok)throw await y(o);return await o.json()}async getDraft(e,t,n={}){return this.get(e,t,{state:`draft`,...n.packageId?{packageId:n.packageId}:{}})}async save(e,t,n,r={}){let i=[];r.force&&i.push(`force=true`),r.mode===`draft`&&i.push(`mode=draft`),r.packageId&&i.push(`package=${encodeURIComponent(r.packageId)}`);let a=i.length?`?${i.join(`&`)}`:``,o=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${a}`,s={...this.headers,"Content-Type":`application/json`};r.ifMatch&&(s[`If-Match`]=r.ifMatch),r.actor&&(s[`X-Actor`]=r.actor);let c=await this.fetchImpl(o,{method:`PUT`,headers:s,body:JSON.stringify(n)});if(!c.ok)throw await y(c);return await c.json()}async publishDraft(e,t){let n=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/publish`,r=await this.fetchImpl(n,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`});if(!r.ok)throw await y(r);let i=await r.json().catch(()=>({}));return i?.data&&typeof i.data==`object`?i.data:i}async layered(e,t,n={}){let r=n.packageId?`&package=${encodeURIComponent(n.packageId)}`:``,i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}?layers=true${r}`,a=await this.fetchImpl(i,{method:`GET`,headers:this.headers,cache:`no-store`});if(a.status===404)return{code:null,overlay:null,overlayScope:null,effective:null};if(!a.ok)throw await y(a);let o=await a.json();return o&&(`code`in o||`overlay`in o||`effective`in o)?{code:o.code??null,overlay:o.overlay??null,overlayScope:o.overlayScope??null,effective:o.effective??null,...o._diagnostics?{_diagnostics:o._diagnostics}:{},...o.lock===void 0?{}:{lock:o.lock},...o.lockReason===void 0?{}:{lockReason:o.lockReason},...o.lockSource===void 0?{}:{lockSource:o.lockSource},...o.lockDocsUrl===void 0?{}:{lockDocsUrl:o.lockDocsUrl},...o.provenance===void 0?{}:{provenance:o.provenance},...o.packageId===void 0?{}:{packageId:o.packageId},...o.packageVersion===void 0?{}:{packageVersion:o.packageVersion},...o.editable===void 0?{}:{editable:o.editable},...o.deletable===void 0?{}:{deletable:o.deletable},...o.resettable===void 0?{}:{resettable:o.resettable}}:{code:null,overlay:null,overlayScope:null,effective:o}}async diagnostics(e={}){let t=[];e.type&&t.push(`type=${encodeURIComponent(e.type)}`),e.severity&&t.push(`severity=${encodeURIComponent(e.severity)}`),e.packageId&&t.push(`package=${encodeURIComponent(e.packageId)}`);let n=t.length?`?${t.join(`&`)}`:``,r=`${this.base}/diagnostics${n}`,i=await this.fetchImpl(r,{method:`GET`,headers:this.headers,cache:`no-store`});if(i.status===404)return{entries:[],total:0,scannedTypes:0,scannedItems:0,stats:{}};if(!i.ok)throw await y(i);let a=await i.json();return{entries:Array.isArray(a.entries)?a.entries:[],total:typeof a.total==`number`?a.total:0,scannedTypes:typeof a.scannedTypes==`number`?a.scannedTypes:0,scannedItems:typeof a.scannedItems==`number`?a.scannedItems:0,stats:a.stats&&typeof a.stats==`object`?a.stats:{}}}async references(e,t){let n=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/references`,r=await this.fetchImpl(n,{method:`GET`,headers:this.headers,cache:`no-store`});if(r.status===404)return[];if(!r.ok)throw await y(r);let i=await r.json();return Array.isArray(i)?i:i?.items??[]}async reset(e,t,n={}){let r=n.state===`draft`?`?state=draft`:``,i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${r}`,a={...this.headers};n.ifMatch&&(a[`If-Match`]=n.ifMatch),n.actor&&(a[`X-Actor`]=n.actor);let o=await this.fetchImpl(i,{method:`DELETE`,headers:a});if(!o.ok)throw await y(o);return await o.json()}async publish(e,t,n={}){let r=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/publish`,i={...this.headers,"Content-Type":`application/json`};n.actor&&(i[`X-Actor`]=n.actor);let a=await this.fetchImpl(r,{method:`POST`,headers:i,body:JSON.stringify(n.message?{message:n.message}:{})});if(!a.ok)throw await y(a);return await a.json()}async rollback(e,t,n,r={}){let i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/rollback`,a={...this.headers,"Content-Type":`application/json`};r.actor&&(a[`X-Actor`]=r.actor);let o=await this.fetchImpl(i,{method:`POST`,headers:a,body:JSON.stringify({toVersion:n,...r.message?{message:r.message}:{}})});if(!o.ok)throw await y(o);return await o.json()}async diff(e,t,n,r){let i=new URLSearchParams;n!==void 0&&i.set(`from`,String(n)),r!==void 0&&i.set(`to`,String(r));let a=i.toString(),o=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/diff${a?`?${a}`:``}`,s=await this.fetchImpl(o,{method:`GET`,headers:this.headers,cache:`no-store`});if(!s.ok)throw await y(s);return await s.json()}async history(e,t,n={}){let r=new URLSearchParams;n.sinceSeq!==void 0&&r.set(`sinceSeq`,String(n.sinceSeq)),n.limit!==void 0&&r.set(`limit`,String(n.limit));let i=r.toString(),a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/history${i?`?${i}`:``}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(!o.ok)throw await y(o);return await o.json()}async audit(e,t,n={}){let r=new URLSearchParams;n.limit!==void 0&&r.set(`limit`,String(n.limit));let i=r.toString(),a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/audit${i?`?${i}`:``}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(!o.ok)throw await y(o);return await o.json()}},ne={equals:`=`,eq:`=`,"==":`=`,not_equals:`!=`,notequals:`!=`,ne:`!=`,greater_than:`>`,greaterthan:`>`,gt:`>`,greater_than_or_equal:`>=`,greater_than_or_equals:`>=`,greaterthanorequal:`>=`,gte:`>=`,less_than:`<`,lessthan:`<`,lt:`<`,less_than_or_equal:`<=`,less_than_or_equals:`<=`,lessthanorequal:`<=`,lte:`<=`,in:`in`,not_in:`nin`,notin:`nin`,nin:`nin`,contains:`contains`,not_contains:`notcontains`,notcontains:`notcontains`,starts_with:`startswith`,startswith:`startswith`,ends_with:`endswith`,endswith:`endswith`,between:`between`,is_null:`isnull`,isnull:`isnull`,is_not_null:`isnotnull`,isnotnull:`isnotnull`};function b(e){return typeof e==`string`?ne[e.toLowerCase()]??ne[e]??e:null}function x(e){if(!e||typeof e!=`object`)return null;let t=e.field??e.name,n=b(e.operator??e.op??`=`);return!t||!n?null:[String(t),n,e.value]}function S(e){if(e!=null){if(Array.isArray(e)){if(e.length===0)return;let t=e[0];if(e.length>0&&typeof t==`object`&&t&&!Array.isArray(t)&&t.field!==void 0){let t=e.map(e=>x(e)).filter(e=>e!==null);return t.length===0?void 0:t.length===1?t[0]:[`and`,...t]}return e}if(typeof e==`object`)return Object.keys(e).length===0?void 0:e}}var C=new Map;async function w(e,t){let n=e||`<default>`,r=C.get(n);if(r)return r;let i=t().catch(e=>{throw C.delete(n),e});return C.set(n,i),i}function T(e){if(!e||typeof e!=`object`)return!1;let t=e;if(t.httpStatus===404||t.status===404||t.statusCode===404)return!0;let n=typeof t.code==`string`?t.code:``;return n===`object_not_found`||n===`record_not_found`}var re=class extends Error{code=`CONCURRENT_UPDATE`;httpStatus=409;currentVersion;currentRecord;constructor(e){super(e.message??`Record was modified by another user`),this.name=`ConcurrentUpdateError`,this.currentVersion=e.currentVersion,this.currentRecord=e.currentRecord}};function E(e){if(!e||typeof e!=`object`)return e;let t=e;if(t.code!==`CONCURRENT_UPDATE`&&t.httpStatus!==409||t.code!==`CONCURRENT_UPDATE`)return e;let n=t.details??{};return new re({currentVersion:typeof n.currentVersion==`string`?n.currentVersion:null,currentRecord:n.currentRecord??null,message:typeof t.message==`string`?t.message:void 0})}function ie(){let e=e=>{if(!e||typeof e!=`object`)return!1;if(e.status===404||e.statusCode===404)return!0;let t=e.error;if(t&&typeof t==`object`){let e=t.code;if(e===`object_not_found`||e===`record_not_found`)return!0}return!1},t={debug:(e,t)=>console.debug(e,t??``),info:(e,t)=>console.info(e,t??``),warn:(e,t)=>console.warn(e,t??``),error:(t,n,r)=>{if(e(r)){console.debug(`[ObjectStack] ${t} (suppressed expected 404)`,r);return}console.error(t,n??``,r??``)},fatal:(e,t,n)=>console.error(e,t??``,n??``),log:(e,...t)=>console.log(e,...t),child:()=>t,withTrace:()=>t};return t}function D(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(D).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${D(t[e])}`).join(`,`)}}`}var ae=class{client;connected=!1;connectPromise=null;metadataCache;connectionState=`disconnected`;connectionStateListeners=[];batchProgressListeners=[];autoReconnect;maxReconnectAttempts;reconnectDelay;reconnectAttempts=0;baseUrl;token;fetchImpl;inflightFinds=new Map;missingResources=new Set;mutationListeners=new Set;constructor(e){this.client=new a.ObjectStackClient({...e,logger:ie()}),this.metadataCache=new o(e.cache),this.autoReconnect=e.autoReconnect??!0,this.maxReconnectAttempts=e.maxReconnectAttempts??3,this.reconnectDelay=e.reconnectDelay??1e3,this.baseUrl=e.baseUrl,this.token=e.token,this.fetchImpl=e.fetch||globalThis.fetch.bind(globalThis)}async connect(){if(!this.connected)return this.connectPromise?this.connectPromise:(this.setConnectionState(`connecting`),this.connectPromise=(async()=>{try{let e=this.baseUrl||``,t=e?`${e.replace(/\/$/,``)}/api/v1/discovery`:`/api/v1/discovery`,n=await w(e,async()=>{let e=await this.fetchImpl(t,{method:`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`}:void 0});if(!e.ok)throw Error(`discovery ${e.status} ${e.statusText}`);let n=await e.json();return n&&typeof n.success==`boolean`&&`data`in n?n.data:n});this.client.discoveryInfo=n,this.connected=!0,this.reconnectAttempts=0,this.setConnectionState(`connected`)}catch(e){let t=new u(e instanceof Error?e.message:`Failed to connect to ObjectStack server`,void 0,{originalError:e});if(this.setConnectionState(`error`,t),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts)await this.attemptReconnect();else throw t}finally{this.connectPromise=null}})(),this.connectPromise)}async attemptReconnect(){this.reconnectAttempts++,this.setConnectionState(`reconnecting`);let e=this.reconnectDelay*2**(this.reconnectAttempts-1);await new Promise(t=>setTimeout(t,e)),this.connected=!1,await this.connect()}getConnectionState(){return this.connectionState}isConnected(){return this.connected&&this.connectionState===`connected`}onConnectionStateChange(e){return this.connectionStateListeners.push(e),()=>{let t=this.connectionStateListeners.indexOf(e);t>-1&&this.connectionStateListeners.splice(t,1)}}onBatchProgress(e){return this.batchProgressListeners.push(e),()=>{let t=this.batchProgressListeners.indexOf(e);t>-1&&this.batchProgressListeners.splice(t,1)}}setConnectionState(e,t){this.connectionState=e;let n={state:e,timestamp:Date.now(),error:t};this.connectionStateListeners.forEach(e=>{try{e(n)}catch(e){console.error(`Error in connection state listener:`,e)}})}emitBatchProgress(e){this.batchProgressListeners.forEach(t=>{try{t(e)}catch(e){console.error(`Error in batch progress listener:`,e)}})}async find(e,t){if(this.missingResources.has(e))return{data:[],total:0};let n=`${e}::${D(t)}`,r=this.inflightFinds.get(n);if(r)return r;let i=(async()=>{if(await this.connect(),t?.$expand&&t.$expand.length>0||t?.$search!=null&&String(t.$search).trim()!==``){let n=await this.rawFindWithPopulate(e,t);return this.normalizeQueryResult(n,t)}let n=this.convertQueryParams(t);try{let r=await this.client.data.find(e,n);return this.normalizeQueryResult(r,t)}catch(t){if(T(t))return this.missingResources.add(e),{data:[],total:0};throw t}})();this.inflightFinds.set(n,i);let a=()=>{this.inflightFinds.get(n)===i&&this.inflightFinds.delete(n)};return i.then(a,a),i}async findOne(e,t,n){if(await this.connect(),n?.$expand&&n.$expand.length>0)try{let r={...n,$filter:{id:String(t)},$top:1},i=await this.rawFindWithPopulate(e,r);if(Array.isArray(i))return i[0]||null;let a=i;return(a.records||a.value||[])[0]||null}catch(e){if(T(e))return null}try{return(await this.client.data.get(e,String(t))).record}catch(e){if(T(e))return null;throw e}}emitMutation(e){for(let t of this.mutationListeners)try{t(e)}catch(e){console.warn(`ObjectStackAdapter: mutation listener error`,e)}}onMutation(e){return this.mutationListeners.add(e),()=>{this.mutationListeners.delete(e)}}async create(e,t){await this.connect();let n=await this.client.data.create(e,t);return this.emitMutation({type:`create`,resource:e,record:{...n.record}}),n.record}async update(e,t,n,r){await this.connect();try{let i=await this.client.data.update(e,String(t),n,r?.ifMatch?{ifMatch:r.ifMatch}:void 0);return this.emitMutation({type:`update`,resource:e,id:t,record:{...i.record}}),i.record}catch(e){throw E(e)}}async delete(e,t,n){await this.connect();try{let r=await this.client.data.delete(e,String(t),n?.ifMatch?{ifMatch:n.ifMatch}:void 0);return r.deleted&&this.emitMutation({type:`delete`,resource:e,id:t}),r.deleted}catch(e){throw E(e)}}async bulkUpdate(e,t,n){if(await this.connect(),!t||t.length===0)return 0;let r=t.map(e=>({id:String(e),data:n})),i=t=>(t>0&&this.emitMutation({type:`update`,resource:e}),t),a=this.client.data.updateMany;if(typeof a==`function`)try{let n=await a(e,r,{continueOnError:!0});return n&&typeof n==`object`&&typeof n.succeeded==`number`?i(n.succeeded):i(Array.isArray(n)?n.length:t.length)}catch(e){throw E(e)}let o=0;for(let r of t)try{await this.client.data.update(e,String(r),n),o++}catch{}return i(o)}async bulkDelete(e,t){if(await this.connect(),!t||t.length===0)return 0;let n=t.map(e=>String(e)),r=t=>(t>0&&this.emitMutation({type:`delete`,resource:e}),t),i=this.client.data.deleteMany;if(typeof i==`function`)try{let t=await i(e,n,{continueOnError:!0});return t&&typeof t==`object`&&typeof t.succeeded==`number`?r(t.succeeded):r(Array.isArray(t)?t.length:n.length)}catch(e){throw E(e)}let a=0;for(let t of n)try{await this.client.data.delete(e,t),a++}catch{}return r(a)}async batchTransaction(e){let t=`${this.baseUrl}/api/v1/batch`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()},credentials:`include`,body:JSON.stringify({operations:e})});if(!n.ok){let e=await n.json().catch(()=>({message:n.statusText}));throw new s(e.error||e.message||`Batch failed with status ${n.status}`,`BATCH_ERROR`,n.status)}return n.json()}async bulk(e,t,n){if(await this.connect(),!n||n.length===0)return[];let r=n.length,i=0,a=0,o=()=>{this.emitBatchProgress({operation:t,total:r,completed:i,failed:a,percentage:r>0?(i+a)/r*100:0})};try{switch(t){case`create`:{o();let t=await this.client.data.createMany(e,n);return i=t.length,a=r-i,o(),t}case`delete`:{let t=n.map(e=>e.id).filter(Boolean);if(t.length===0){let e=n.map((e,t)=>({index:t,error:`Missing ID for item at index ${t}`}));throw a=n.length,o(),new l(`delete`,0,n.length,e)}return o(),await this.client.data.deleteMany(e,t),i=t.length,a=r-i,o(),[]}case`update`:{if(typeof this.client.data.updateMany==`function`)try{o();let t=this.client.data.updateMany,s=await t(e,n);return i=s.length,a=r-i,o(),s}catch{}let t=[],s=[];for(let r=0;r<n.length;r++){let c=n[r],l=c.id;if(!l){s.push({index:r,error:`Missing ID`}),a++,o();continue}try{let n=await this.client.data.update(e,String(l),c);t.push(n.record),i++,o()}catch(e){let t=e instanceof Error?e.message:String(e);s.push({index:r,error:t}),a++,o()}}if(s.length>0)throw new l(`update`,t.length,s.length,s,{resource:e,totalRecords:n.length});return t}default:throw new s(`Unsupported bulk operation: ${t}`,`UNSUPPORTED_OPERATION`,400)}}catch(r){if(o(),r instanceof l||r instanceof s)throw r;let i=r instanceof Error?r.message:String(r),a=n.map((e,t)=>({index:t,error:i}));throw new l(t,0,n.length,a,{resource:e,originalError:r})}}async importRecords(e,t){await this.connect();let n=this.client.data.import;if(typeof n!=`function`)throw new s(`The connected @objectstack/client does not support data.import(). Upgrade the client, or import via a per-row create fallback.`,`UNSUPPORTED_OPERATION`,400);try{return await n.call(this.client.data,e,t)}catch(e){throw E(e)}}importJobApi(){let e=this.client.data;if(typeof e.createImportJob==`function`)return e}async createImportJob(e,t){await this.connect();let n=this.importJobApi();if(!n)throw new s(`The connected @objectstack/client does not support async import jobs (data.createImportJob). Upgrade the client, or use the synchronous importRecords() path.`,`UNSUPPORTED_OPERATION`,400);try{return await n.createImportJob.call(this.client.data,e,t)}catch(e){throw E(e)}}async getImportJobProgress(e){await this.connect();let t=this.importJobApi();if(!t)throw new s(`The connected @objectstack/client does not support async import jobs.`,`UNSUPPORTED_OPERATION`,400);try{return await t.getImportJobProgress.call(this.client.data,e)}catch(e){throw E(e)}}async getImportJobResults(e){await this.connect();let t=this.importJobApi();if(!t)throw new s(`The connected @objectstack/client does not support async import jobs.`,`UNSUPPORTED_OPERATION`,400);try{return await t.getImportJobResults.call(this.client.data,e)}catch(e){throw E(e)}}async listImportJobs(e={}){await this.connect();let t=this.importJobApi();if(!t)throw new s(`The connected @objectstack/client does not support async import jobs.`,`UNSUPPORTED_OPERATION`,400);try{return await t.listImportJobs.call(this.client.data,e)}catch(e){throw E(e)}}async cancelImportJob(e){await this.connect();let t=this.importJobApi();if(!t)throw new s(`The connected @objectstack/client does not support async import jobs.`,`UNSUPPORTED_OPERATION`,400);try{await t.cancelImportJob.call(this.client.data,e)}catch(e){throw E(e)}}async undoImportJob(e){await this.connect();let t=this.importJobApi();if(!t||typeof t.undoImportJob!=`function`)throw new s(`The connected @objectstack/client does not support undoing import jobs (data.undoImportJob).`,`UNSUPPORTED_OPERATION`,400);try{return await t.undoImportJob.call(this.client.data,e)}catch(e){throw E(e)}}normalizeQueryResult(e,t){if(Array.isArray(e))return{data:e,total:e.length,page:1,pageSize:e.length,hasMore:!1};let n=e,r=n.records||n.value||[],i=n.total??n.count??r.length,a=typeof n.hasMore==`boolean`?n.hasMore:t?.$top?r.length===t.$top:!1;return{data:r,total:i,page:t?.$skip&&t.$top?Math.floor(t.$skip/t.$top)+1:1,pageSize:t?.$top,hasMore:a}}async rawFindWithPopulate(e,t){let n=new URLSearchParams;if(t.$expand&&t.$expand.length>0&&n.set(`populate`,t.$expand.join(`,`)),t.$top!==void 0&&n.set(`top`,String(t.$top)),t.$skip!==void 0&&n.set(`skip`,String(t.$skip)),t.$search!=null&&String(t.$search).trim()!==``&&n.set(`search`,String(t.$search).trim()),t.$searchFields&&t.$searchFields.length>0&&n.set(`searchFields`,t.$searchFields.join(`,`)),t.$select&&t.$select.length>0){let e=t.$select.includes(`id`)?t.$select:[`id`,...t.$select];n.set(`select`,e.join(`,`))}if(t.$orderby)if(Array.isArray(t.$orderby)){let e=t.$orderby.map(e=>{if(typeof e==`string`)return e;let t=e.field;return(e.order||`asc`)===`desc`?`-${t}`:t}).join(`,`);n.set(`sort`,e)}else{let e=Object.entries(t.$orderby).map(([e,t])=>t===`desc`?`-${e}`:e).join(`,`);n.set(`sort`,e)}if(t.$filter!==void 0&&t.$filter!==null){let e=S(t.$filter);e!==void 0&&n.set(`filter`,JSON.stringify(e))}let r=this.baseUrl.replace(/\/$/,``),i=n.toString(),a=`${r}${/\/api\/v\d+$/i.test(r)?`/data`:`/api/v1/data`}/${e}${i?`?${i}`:``}`,o={"Content-Type":`application/json`};this.token&&(o.Authorization=`Bearer ${this.token}`);let s=await this.fetchImpl(a,{method:`GET`,headers:o});if(!s.ok){let e=await s.json().catch(()=>({message:s.statusText})),t=Error(e?.error?.message||e?.message||s.statusText);throw t.status=s.status,t}let c=await s.json();return c&&typeof c.success==`boolean`&&`data`in c?c.data:c}async exportDownload(e,t={}){let n=new URLSearchParams,r=t.format===`xlsx`?`xlsx`:t.format===`json`?`json`:`csv`;if(n.set(`format`,r),t.fields&&t.fields.length>0&&n.set(`fields`,t.fields.join(`,`)),t.limit&&t.limit>0&&n.set(`limit`,String(t.limit)),t.includeHeaders===!1&&n.set(`header`,`false`),t.sort&&t.sort.length>0){let e=t.sort.filter(e=>e&&e.field).map(e=>`${e.field}:${e.direction===`desc`?`desc`:`asc`}`).join(`,`);e&&n.set(`orderby`,e)}if(t.filter!==void 0&&t.filter!==null){let e=S(t.filter);e!==void 0&&n.set(`filter`,JSON.stringify(e))}let i=this.baseUrl.replace(/\/$/,``),a=`${i}${/\/api\/v\d+$/i.test(i)?`/data`:`/api/v1/data`}/${encodeURIComponent(e)}/export?${n.toString()}`,o={...this.getAuthHeaders()},s=await this.fetchImpl(a,{method:`GET`,headers:o,credentials:`include`});if(!s.ok){let e=await s.json().catch(()=>({message:s.statusText})),t=Error(e?.error?.message||e?.message||s.statusText);throw t.status=s.status,t}return await s.blob()}convertQueryParams(e){if(!e)return{};let n={};if(e.$select&&(n.select=e.$select.includes(`id`)?e.$select:[`id`,...e.$select]),e.$filter!==void 0&&e.$filter!==null&&!(Array.isArray(e.$filter)?e.$filter.length===0:typeof e.$filter==`object`&&Object.keys(e.$filter).length===0))if(Array.isArray(e.$filter))if(e.$filter.length>0&&typeof e.$filter[0]==`object`&&!Array.isArray(e.$filter[0])&&e.$filter[0].field!==void 0){let t=e.$filter.map(e=>x(e)).filter(e=>e!==null);t.length===0||(t.length===1?n.filters=t[0]:n.filters=[`and`,...t])}else n.filters=e.$filter;else n.filters=t(e.$filter);return e.$orderby&&(Array.isArray(e.$orderby)?n.sort=e.$orderby.map(e=>{if(typeof e==`string`)return e;let t=e.field;return(e.order||`asc`)===`desc`?`-${t}`:t}):n.sort=Object.entries(e.$orderby).map(([e,t])=>t===`desc`?`-${e}`:e)),e.$skip!==void 0&&(n.skip=e.$skip),e.$top!==void 0&&(n.top=e.$top),e.$search!=null&&String(e.$search).trim()!==``&&(n.search=String(e.$search).trim()),e.$searchFields&&e.$searchFields.length>0&&(n.searchFields=e.$searchFields),n}async getObjectSchema(e){await this.connect();try{return await this.metadataCache.get(e,()=>this.fetchObjectSchemaFresh(e))}catch(t){let n=t;throw T(n)?new c(e,{originalError:t}):t instanceof s?t:ee(n,`getObjectSchema(${e})`)}}async fetchObjectSchemaFresh(e){let t=(this.baseUrl||``).replace(/\/$/,``),n=`${t}${/\/api\/v\d+$/i.test(t)?`/meta`:`/api/v1/meta`}/object/${encodeURIComponent(e)}`,r={"Content-Type":`application/json`};this.token&&(r.Authorization=`Bearer ${this.token}`);let i=await this.fetchImpl(n,{method:`GET`,headers:r,cache:`no-cache`});if(!i.ok){let e=await i.json().catch(()=>({message:i.statusText})),t=Error(e?.error?.message||e?.message||i.statusText);throw t.status=i.status,t}let a=await i.json(),o=a&&typeof a==`object`&&`success`in a&&`data`in a?a.data:a;return o&&typeof o==`object`&&`item`in o?o.item:o}getClient(){return this.client}async getDiscovery(){try{return await this.connect(),this.client.discoveryInfo||null}catch{return null}}async listViewOverrides(e){await this.connect();try{let t=`view-overrides:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItems(e),n=Array.isArray(t?.items)?t.items:[],r={};for(let e of n){if(!e||typeof e!=`object`)continue;let t=e.name??e.id??e._name;typeof t==`string`&&t&&(r[t]=e)}return r})}catch{return{}}}async getView(e,t){await this.connect();try{let n=`view:${e}:${t}`;return await this.metadataCache.get(n,async()=>{let e=await this.client.meta.getItem(`view`,t);return e&&e.item?e.item:e??null})}catch{return null}}async updateViewConfig(e,t,n){await this.connect();try{let r={...n||{},object:n?.object||e,name:t},i=await this.client.meta.saveItem(`view`,t,r),a=`view:${e}:${t}`;return this.metadataCache.invalidate?.(a),this.metadataCache.invalidate?.(`view-overrides:${e}`),this.metadataCache.invalidate?.(`views:${e}`),i&&i.item?i.item:i??void 0}catch(e){throw e}}async listViews(e){await this.connect();try{let t=await this.client.meta.getItems(`view`),n=Array.isArray(t?.items)?t.items:Array.isArray(t)?t:[],r=new Set([`form`,`detail`]);return n.filter(t=>{if(!t)return!1;let n=t.list??t;if((n?.data?.object??n?.object??n?.objectName)!==e)return!1;let i=t.viewKind??n?.viewKind;return!(i&&r.has(i))}).map(e=>{let t=e.list??e;return t&&t.config&&typeof t.config==`object`?{...t.config,name:t.name??t.config.name,label:t.label??t.config.label,isDefault:!!t.isDefault}:t})}catch(e){return console.warn(`[OBJECTSTACKDataSource] listViews failed:`,e),[]}}async listImportMappings(e){await this.connect();try{let t=await this.client.meta.getItems(`mapping`);return(Array.isArray(t?.items)?t.items:Array.isArray(t)?t:[]).filter(t=>t&&t.targetObject===e)}catch(e){return console.warn(`[OBJECTSTACKDataSource] listImportMappings failed:`,e),[]}}async createView(e,t){await this.connect();let n=String(t?.name||``).trim();if(!n){let r=String(t?.label||e||`view`).toLowerCase().replace(/[^a-z0-9_]+/g,`_`).replace(/^_+|_+$/g,``).slice(0,40);(!r||/^[0-9]/.test(r))&&(r=r?`view_${r}`:`view`);let i=Date.now().toString(36);n=`${r}_${i}`}let r={...t,name:n,object:t?.object||e,data:t?.data||{provider:`object`,object:e}};try{let t=await this.client.meta.saveItem(`view`,n,r);return this.metadataCache.invalidate?.(`views:${e}`),t&&t.item?t.item:r}catch(e){throw e}}async updateView(e,t,n){await this.connect();let r={};try{let e=await this.client.meta.getItem(`view`,t);r=e&&(e.item||e)||{},r?.list&&(r=r.list)}catch{}let i={...r,...n,name:t,object:r?.object||r?.data?.object||e};try{let n=await this.client.meta.saveItem(`view`,t,i);return this.metadataCache.invalidate?.(`views:${e}`),this.metadataCache.invalidate?.(`view:${e}:${t}`),n&&n.item?n.item:i}catch(e){throw e}}async deleteView(e,t){await this.connect();try{let n=await this.client.meta.deleteItem(`view`,t);return this.metadataCache.invalidate?.(`views:${e}`),this.metadataCache.invalidate?.(`view:${e}:${t}`),{deleted:!!(n?.deleted??n?.reset??!0)}}catch(e){throw e}}async getApp(e){await this.connect();try{let t=`app:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItem(`apps`,e);return t&&t.item?t.item:t??null})}catch{return null}}async getPage(e){await this.connect();try{let t=`page:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItem(`pages`,e);return t&&t.item?t.item:t??null})}catch{return null}}async updateDashboard(e,t){await this.connect();try{let n=await this.client.meta.saveItem(`dashboard`,e,t);return this.metadataCache.invalidate?.(`dashboards`),this.metadataCache.invalidate?.(`dashboard:${e}`),n&&n.item?n.item:n??void 0}catch(e){throw e}}async aggregate(e,t){if(await this.connect(),t!=null&&(Array.isArray(t.groupBy)||Array.isArray(t.aggregations)||t.where!==void 0)){let n={};Array.isArray(t.groupBy)&&(n.groupBy=t.groupBy),Array.isArray(t.aggregations)&&(n.aggregations=t.aggregations),t.where!==void 0&&(n.where=t.where),typeof t.limit==`number`&&(n.limit=t.limit);let r=await this.client.data.query(e,n);return Array.isArray(r)?r:Array.isArray(r?.records)?r.records:Array.isArray(r?.data)?r.data:[]}try{let n=t.function===`count`?`count`:`${t.field}_${t.function}`,r={cube:e,measures:[n],dimensions:t.groupBy&&t.groupBy!==`_all`?[t.groupBy]:[]};t.filter&&(r.where=t.filter);let i=await this.client.analytics.query(r),a=Array.isArray(i)?i:i?.rows&&Array.isArray(i.rows)?i.rows:i?.data&&Array.isArray(i.data)?i.data:i?.data?.rows&&Array.isArray(i.data.rows)?i.data.rows:i?.results&&Array.isArray(i.results)?i.results:[];if(a.length>0&&a.every(e=>e==null?!0:!(n in e&&e[n]!=null||t.field in e&&e[t.field]!=null))){let n=(await this.find(e,t.filter?{$filter:t.filter}:void 0)).data||[];return n.length===0?[]:this.aggregateClientSide(n,t)}return a.map(e=>{let r={...e};return n!==t.field&&n in r&&(r[t.field]=r[n],delete r[n]),r})}catch{let n=(await this.find(e,t.filter?{$filter:t.filter}:void 0)).data||[];return n.length===0?[]:this.aggregateClientSide(n,t)}}async queryDataset(e,t){await this.connect();let n=`${(this.baseUrl||``).replace(/\/$/,``)}/api/v1/analytics/dataset/query`,r=typeof window<`u`&&new URLSearchParams(window.location.search).get(`preview`)===`draft`,i=typeof e==`string`?{datasetName:e,selection:t,...r?{previewDrafts:!0}:{}}:{dataset:e,selection:t,...r?{previewDrafts:!0}:{}},a=await this.fetchImpl(n,{method:`POST`,headers:{"Content-Type":`application/json`,...this.token?{Authorization:`Bearer ${this.token}`}:{}},body:JSON.stringify(i)});if(!a.ok){let e=``;try{let t=await a.json();e=t?.message||t?.error||JSON.stringify(t)}catch{}throw Error(`Dataset query failed: ${a.status} ${a.statusText}${e?` — ${e}`:``}`)}let o=await a.json(),s=o&&typeof o==`object`&&`success`in o&&`data`in o?o.data:o;return{rows:Array.isArray(s?.rows)?s.rows:Array.isArray(s)?s:[],fields:Array.isArray(s?.fields)?s.fields:[],object:typeof s?.object==`string`?s.object:void 0,dimensionFields:s?.dimensionFields&&typeof s.dimensionFields==`object`?s.dimensionFields:void 0,drillRawRows:Array.isArray(s?.drillRawRows)?s.drillRawRows:void 0,totals:Array.isArray(s?.totals)?s.totals:void 0}}aggregateClientSide(e,t){let{field:n,function:r,groupBy:i}=t,a={};for(let t of e){let e=String(t[i]??`Unknown`);a[e]||(a[e]=[]),a[e].push(t)}return Object.entries(a).map(([e,t])=>{let a=t.map(e=>Number(e[n])||0),o;switch(r){case`count`:o=t.length;break;case`avg`:o=a.length>0?a.reduce((e,t)=>e+t,0)/a.length:0;break;case`min`:o=a.length>0?Math.min(...a):0;break;case`max`:o=a.length>0?Math.max(...a):0;break;default:o=a.reduce((e,t)=>e+t,0);break}return{[i]:e,[n]:o}})}async getItems(e,t){return await this.connect(),await Promise.all(t.map(async t=>{let n=`${e}:${t}`;return this.metadataCache.get(n,async()=>{let n=await this.client.meta.getItem(e,t);return n&&n.item?n.item:n})}))}getCached(e){return this.metadataCache.getCachedSync(e)}getCacheStats(){return this.metadataCache.getStats()}invalidateCache(e){this.metadataCache.invalidate(e)}clearCache(){this.metadataCache.clear()}async uploadFile(e,t,n){await this.connect();let r=new FormData;r.append(`file`,t),n?.recordId&&r.append(`recordId`,n.recordId),n?.fieldName&&r.append(`fieldName`,n.fieldName),n?.metadata&&r.append(`metadata`,JSON.stringify(n.metadata));let i=`${this.baseUrl}/api/data/${encodeURIComponent(e)}/upload`,a=await fetch(i,{method:`POST`,body:r,headers:{...this.getAuthHeaders()}});if(!a.ok)throw new s((await a.json().catch(()=>({message:a.statusText}))).message||`Upload failed with status ${a.status}`,`UPLOAD_ERROR`,a.status);return a.json()}async uploadFiles(e,t,n){await this.connect();let r=new FormData;t.forEach((e,t)=>{r.append(`files`,e,e.name||`file-${t}`)}),n?.recordId&&r.append(`recordId`,n.recordId),n?.fieldName&&r.append(`fieldName`,n.fieldName),n?.metadata&&r.append(`metadata`,JSON.stringify(n.metadata));let i=`${this.baseUrl}/api/data/${encodeURIComponent(e)}/upload`,a=await fetch(i,{method:`POST`,body:r,headers:{...this.getAuthHeaders()}});if(!a.ok)throw new s((await a.json().catch(()=>({message:a.statusText}))).message||`Upload failed with status ${a.status}`,`UPLOAD_ERROR`,a.status);return a.json()}async cancelPendingApproval(e,t){await this.connect();let n=`${this.baseUrl}/api/v1/approvals/requests?recordId=${encodeURIComponent(t)}&object=${encodeURIComponent(e)}`,r=await this.fetchImpl(n,{method:`GET`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()}});if(!r.ok)throw new s(`Failed to look up approval requests (status ${r.status})`,`APPROVAL_LOOKUP_FAILED`,r.status);let i=await r.json().catch(()=>({})),a=(Array.isArray(i)?i:i?.data??[]).find(e=>e?.status===`pending`||e?.status===`in_approval`);if(!a?.id)throw new s(`No pending approval request found for this record`,`NO_PENDING_REQUEST`,404);let o=`${this.baseUrl}/api/v1/approvals/requests/${encodeURIComponent(a.id)}/recall`,c=await this.fetchImpl(o,{method:`POST`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()},body:JSON.stringify({})});if(!c.ok){let e=await c.json().catch(()=>({}));throw new s(e?.error||e?.message||`Recall failed with status ${c.status}`,e?.code||`APPROVAL_RECALL_FAILED`,c.status)}let l=await c.json().catch(()=>({}));return{requestId:a.id,status:l?.data?.request?.status??`recalled`}}getAuthHeaders(){let e={};return this.token&&(e.Authorization=`Bearer ${this.token}`),e}};export{te as n,h as r,ae as t};