@constructive-io/schema-builder 0.2.0 → 0.2.1

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 (131) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/card-widths-CmIxkRfh.cjs +28 -0
  3. package/dist/card-widths-CmIxkRfh.cjs.map +1 -0
  4. package/dist/card-widths-pI4Kw4Xz.js +22 -0
  5. package/dist/card-widths-pI4Kw4Xz.js.map +1 -0
  6. package/dist/core-WwCS0CKu.cjs +66 -0
  7. package/dist/core-WwCS0CKu.cjs.map +1 -0
  8. package/dist/core-kx6KjxE5.js +49 -0
  9. package/dist/core-kx6KjxE5.js.map +1 -0
  10. package/dist/core.cjs +14 -212
  11. package/dist/core.d.cts +3 -54
  12. package/dist/core.d.ts +3 -54
  13. package/dist/core.js +3 -200
  14. package/dist/create-table-card-BzNKfpXO.cjs +7726 -0
  15. package/dist/create-table-card-BzNKfpXO.cjs.map +1 -0
  16. package/dist/create-table-card-pZ0Aq6rr.js +7685 -0
  17. package/dist/create-table-card-pZ0Aq6rr.js.map +1 -0
  18. package/dist/delete-confirm-dialog-Ch4tWj6B.cjs +42 -0
  19. package/dist/delete-confirm-dialog-Ch4tWj6B.cjs.map +1 -0
  20. package/dist/delete-confirm-dialog-K0AWE643.js +37 -0
  21. package/dist/delete-confirm-dialog-K0AWE643.js.map +1 -0
  22. package/dist/empty-state-card-DMn8ADRq.cjs +62 -0
  23. package/dist/empty-state-card-DMn8ADRq.cjs.map +1 -0
  24. package/dist/empty-state-card-Dnn36JVH.js +57 -0
  25. package/dist/empty-state-card-Dnn36JVH.js.map +1 -0
  26. package/dist/fields.cjs +8 -7763
  27. package/dist/fields.d.cts +39 -39
  28. package/dist/fields.d.ts +39 -39
  29. package/dist/fields.js +2 -7735
  30. package/dist/generated-types-DZMUyNBH.d.cts +27 -0
  31. package/dist/generated-types-DZMUyNBH.d.ts +27 -0
  32. package/dist/index-9h0EROdb.d.cts +56 -0
  33. package/dist/index-CwQ9QpxA.d.ts +7 -0
  34. package/dist/index-DOWB1UBK.d.cts +56 -0
  35. package/dist/index-DOWB1UBK.d.ts +56 -0
  36. package/dist/index-Dgb_e3AP.d.cts +7 -0
  37. package/dist/index-p_NegPQ5.d.ts +56 -0
  38. package/dist/index.cjs +736 -13712
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.d.cts +4 -10
  41. package/dist/index.d.ts +4 -10
  42. package/dist/index.js +725 -13680
  43. package/dist/index.js.map +1 -1
  44. package/dist/indexes-view-CJ1WQKdp.js +736 -0
  45. package/dist/indexes-view-CJ1WQKdp.js.map +1 -0
  46. package/dist/indexes-view-peIv6QUZ.cjs +759 -0
  47. package/dist/indexes-view-peIv6QUZ.cjs.map +1 -0
  48. package/dist/indexes.cjs +6 -1041
  49. package/dist/indexes.d.cts +27 -27
  50. package/dist/indexes.d.ts +27 -27
  51. package/dist/indexes.js +2 -1016
  52. package/dist/invalidate-database-entities-9DsT5NlP.cjs +2862 -0
  53. package/dist/invalidate-database-entities-9DsT5NlP.cjs.map +1 -0
  54. package/dist/invalidate-database-entities-CmmOT3S0.js +2559 -0
  55. package/dist/invalidate-database-entities-CmmOT3S0.js.map +1 -0
  56. package/dist/keyboard-activation-BQiV0scm.js +13 -0
  57. package/dist/keyboard-activation-BQiV0scm.js.map +1 -0
  58. package/dist/keyboard-activation-D-L0IU6Y.cjs +19 -0
  59. package/dist/keyboard-activation-D-L0IU6Y.cjs.map +1 -0
  60. package/dist/policies-view-BRbpbyB6.js +1018 -0
  61. package/dist/policies-view-BRbpbyB6.js.map +1 -0
  62. package/dist/policies-view-H1HTjpmv.cjs +1023 -0
  63. package/dist/policies-view-H1HTjpmv.cjs.map +1 -0
  64. package/dist/policies.cjs +10 -5939
  65. package/dist/policies.d.cts +55 -50
  66. package/dist/policies.d.ts +55 -50
  67. package/dist/policies.js +4 -5911
  68. package/dist/policy-config-form-BwyK7DGV.js +2502 -0
  69. package/dist/policy-config-form-BwyK7DGV.js.map +1 -0
  70. package/dist/policy-config-form-CefFo6Fw.cjs +2629 -0
  71. package/dist/policy-config-form-CefFo6Fw.cjs.map +1 -0
  72. package/dist/policy-types-D_sYWb-b.d.cts +81 -0
  73. package/dist/policy-types-D_sYWb-b.d.ts +81 -0
  74. package/dist/query-BmN_qO0W.js +171 -0
  75. package/dist/query-BmN_qO0W.js.map +1 -0
  76. package/dist/query-DU-KZleN.cjs +212 -0
  77. package/dist/query-DU-KZleN.cjs.map +1 -0
  78. package/dist/relationships-view-B5TAcPHU.cjs +2452 -0
  79. package/dist/relationships-view-B5TAcPHU.cjs.map +1 -0
  80. package/dist/relationships-view-DbwFh5r-.js +2417 -0
  81. package/dist/relationships-view-DbwFh5r-.js.map +1 -0
  82. package/dist/relationships.cjs +9 -4328
  83. package/dist/relationships.d.cts +93 -92
  84. package/dist/relationships.d.ts +93 -92
  85. package/dist/relationships.js +2 -4300
  86. package/dist/rolldown-runtime-D_qnwXdH.cjs +35 -0
  87. package/dist/schema-builder-sidebar-Ctu621Vw.cjs +604 -0
  88. package/dist/schema-builder-sidebar-Ctu621Vw.cjs.map +1 -0
  89. package/dist/schema-builder-sidebar-VR-Ctidc.js +593 -0
  90. package/dist/schema-builder-sidebar-VR-Ctidc.js.map +1 -0
  91. package/dist/table-editor-C-hHz3DJ.cjs +1935 -0
  92. package/dist/table-editor-C-hHz3DJ.cjs.map +1 -0
  93. package/dist/table-editor-IVp3B4nG.js +1906 -0
  94. package/dist/table-editor-IVp3B4nG.js.map +1 -0
  95. package/dist/tables.cjs +6 -5643
  96. package/dist/tables.d.cts +22 -21
  97. package/dist/tables.d.ts +22 -21
  98. package/dist/tables.js +3 -5618
  99. package/dist/testing.cjs +63 -62
  100. package/dist/testing.cjs.map +1 -1
  101. package/dist/testing.d.cts +4 -4
  102. package/dist/testing.d.ts +4 -4
  103. package/dist/testing.js +62 -61
  104. package/dist/testing.js.map +1 -1
  105. package/dist/types-GUrH1Qny.d.cts +200 -0
  106. package/dist/types-GUrH1Qny.d.ts +200 -0
  107. package/dist/use-update-table-C7v3gRyG.cjs +291 -0
  108. package/dist/use-update-table-C7v3gRyG.cjs.map +1 -0
  109. package/dist/use-update-table-Dz6knGoH.js +244 -0
  110. package/dist/use-update-table-Dz6knGoH.js.map +1 -0
  111. package/package.json +6 -6
  112. package/dist/core.cjs.map +0 -1
  113. package/dist/core.js.map +0 -1
  114. package/dist/fields.cjs.map +0 -1
  115. package/dist/fields.js.map +0 -1
  116. package/dist/generated-types-CnAlqHU_.d.cts +0 -25
  117. package/dist/generated-types-CnAlqHU_.d.ts +0 -25
  118. package/dist/indexes.cjs.map +0 -1
  119. package/dist/indexes.js.map +0 -1
  120. package/dist/policies.cjs.map +0 -1
  121. package/dist/policies.js.map +0 -1
  122. package/dist/policy-types-CEYAR5TN.d.cts +0 -79
  123. package/dist/policy-types-CEYAR5TN.d.ts +0 -79
  124. package/dist/relationships.cjs.map +0 -1
  125. package/dist/relationships.js.map +0 -1
  126. package/dist/tables.cjs.map +0 -1
  127. package/dist/tables.js.map +0 -1
  128. package/dist/types-Du86atZ8.d.cts +0 -199
  129. package/dist/types-Du86atZ8.d.ts +0 -199
  130. package/dist/types-bX2dCrdl.d.cts +0 -52
  131. package/dist/types-bX2dCrdl.d.ts +0 -52
@@ -1,4302 +1,4 @@
1
1
  'use client';
2
- import { createContext, useState, useMemo, useCallback, useEffect, useContext, useRef } from 'react';
3
- import { Button } from '@constructive-io/ui/button';
4
- import { Combobox, ComboboxInput, ComboboxPopup, ComboboxEmpty, ComboboxList, ComboboxItem } from '@constructive-io/ui/combobox';
5
- import { Input } from '@constructive-io/ui/input';
6
- import { Label } from '@constructive-io/ui/label';
7
- import { ScrollArea } from '@constructive-io/ui/scroll-area';
8
- import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue, SelectRichItem, SelectFieldItem } from '@constructive-io/ui/select';
9
- import { Switch } from '@constructive-io/ui/switch';
10
- import { toast } from '@constructive-io/ui/toast';
11
- import { Link2, Trash2, CornerDownRight, Table2, Shield, Target, Zap, Loader2, ChevronRight, Info, Share2, Waypoints, Check, Layers, Lock, Unlock, Network, Link, UserCheck, Users, Clock, Eye, Globe, User, CheckIcon, XIcon, RotateCcwIcon, PencilIcon, Plus } from 'lucide-react';
12
- import * as FluentContextSelector from '@fluentui/react-context-selector';
13
- import { useStore } from 'zustand';
14
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
15
- import { useQueryClient, useMutation, useQuery } from '@tanstack/react-query';
16
- import * as NodeTypes from 'node-type-registry';
17
- import { RelationManyToMany, RelationHasMany, RelationBelongsTo, RelationHasOne } from 'node-type-registry';
18
- import { clsx } from 'clsx';
19
- import { twMerge } from 'tailwind-merge';
20
- import { Tooltip, TooltipTrigger, TooltipContent } from '@constructive-io/ui/tooltip';
21
- import { ResponsiveDiagram } from '@constructive-io/ui/responsive-diagram';
22
- import { useCardStack } from '@constructive-io/ui/stack';
23
- import { AlertDialog, AlertDialogContent, AlertDialogHeader, AlertDialogTitle, AlertDialogDescription, AlertDialogFooter, AlertDialogCancel, AlertDialogAction } from '@constructive-io/ui/alert-dialog';
2
+ import { a as useUpdateForeignKey, i as useDeleteForeignKey, n as useCreateForeignKey, o as useRelationProvision, r as useCreateManyToMany, t as RelationshipsView } from "./relationships-view-DbwFh5r-.js";
24
3
 
25
- // src/schema/schema-builder-core/lib/schema/types.ts
26
- var RelationshipTypes = {
27
- ONE_TO_ONE: "one-to-one",
28
- ONE_TO_MANY: "one-to-many",
29
- MANY_TO_MANY: "many-to-many"
30
- };
31
- var ForeignKeyActions = {
32
- CASCADE: "c",
33
- RESTRICT: "r",
34
- SET_NULL: "n",
35
- SET_DEFAULT: "d",
36
- NO_ACTION: "a"
37
- };
38
- var ForeignKeyActionLabels = {
39
- [ForeignKeyActions.CASCADE]: "Cascade",
40
- [ForeignKeyActions.RESTRICT]: "Restrict",
41
- [ForeignKeyActions.SET_NULL]: "Set null",
42
- [ForeignKeyActions.SET_DEFAULT]: "Set default",
43
- [ForeignKeyActions.NO_ACTION]: "No action"
44
- };
45
- var SchemaBuilderContext = createContext(null);
46
- function useSchemaBuilder() {
47
- const value = useContext(SchemaBuilderContext);
48
- if (!value) throw new Error("SchemaBuilderProvider is missing");
49
- return value;
50
- }
51
- function useSchemaBuilderStore(selector) {
52
- const { store } = useSchemaBuilder();
53
- return useStore(store, selector);
54
- }
55
- function schemaBuilderQueryKey(scope, feature, operation, variables = {}) {
56
- return [
57
- "@constructive-io/schema-builder",
58
- scope.orgId,
59
- scope.databaseId,
60
- scope.userId ?? null,
61
- feature,
62
- operation,
63
- variables
64
- ];
65
- }
66
-
67
- // src/compat/admin-sdk.ts
68
- function useAdminSdkClient() {
69
- const { adapter, scope } = useSchemaBuilder();
70
- return {
71
- fetchAppPermissionsQuery: (variables, signal) => adapter.policies.appPermissions(variables, { scope, signal }),
72
- fetchOrgPermissionsQuery: (variables, signal) => adapter.policies.orgPermissions(variables, { scope, signal })
73
- };
74
- }
75
- var featureByMutation = {
76
- createField: "fields",
77
- createForeignKeyConstraint: "relationships",
78
- createIndex: "indexes",
79
- createPrimaryKeyConstraint: "fields",
80
- createTableGrant: "policies",
81
- createTable: "policies",
82
- createUniqueConstraint: "fields",
83
- deleteField: "fields",
84
- deleteForeignKeyConstraint: "relationships",
85
- deleteIndex: "indexes",
86
- deletePolicy: "policies",
87
- deletePrimaryKeyConstraint: "fields",
88
- deleteTable: "tables",
89
- deleteUniqueConstraint: "fields",
90
- updateField: "fields",
91
- updateForeignKeyConstraint: "relationships",
92
- updateIndex: "indexes",
93
- updatePolicy: "policies",
94
- updatePrimaryKeyConstraint: "fields",
95
- updateTable: "tables"
96
- };
97
- function useGeneratedMutation(operation, options) {
98
- const { adapter, scope, onInvalidate } = useSchemaBuilder();
99
- const feature = featureByMutation[operation];
100
- const operationFn = adapter[feature][operation];
101
- const selection = options?.selection?.fields;
102
- return useMutation({
103
- mutationFn: (variables) => operationFn(variables, { scope, selection }),
104
- onSuccess: () => onInvalidate?.({ scope, feature, operation })
105
- });
106
- }
107
- function useSchemaBuilderSdkClient() {
108
- const { adapter, scope } = useSchemaBuilder();
109
- const bind = (operation) => (variables, signal) => adapter.core[operation](variables, { scope, signal });
110
- return {
111
- fetchApiSchemasQuery: bind("apiSchemas"),
112
- fetchApisQuery: bind("apis"),
113
- fetchDatabasesQuery: bind("databases"),
114
- fetchFieldsQuery: bind("fields"),
115
- fetchForeignKeyConstraintsQuery: bind("foreignKeyConstraints"),
116
- fetchIndicesQuery: bind("indices"),
117
- fetchPoliciesQuery: bind("policies"),
118
- fetchPrimaryKeyConstraintsQuery: bind("primaryKeyConstraints"),
119
- fetchSchemasQuery: bind("schemas"),
120
- fetchTableQuery: bind("table"),
121
- fetchTablesQuery: bind("tables"),
122
- fetchUniqueConstraintsQuery: bind("uniqueConstraints")
123
- };
124
- }
125
- var apiKeys = { all: ["schema-builder", "apis"] };
126
- var domainKeys = {
127
- all: ["schema-builder", "domains"],
128
- lists: () => ["schema-builder", "domains", "list"]
129
- };
130
- var schemaKeys = { all: ["schema-builder", "schemas"] };
131
- var siteKeys = { all: ["schema-builder", "sites"] };
132
- var useCreateFieldMutation = (options) => useGeneratedMutation("createField", options);
133
- var useCreateForeignKeyConstraintMutation = (options) => useGeneratedMutation("createForeignKeyConstraint", options);
134
- var useCreatePrimaryKeyConstraintMutation = (options) => useGeneratedMutation("createPrimaryKeyConstraint", options);
135
- var useCreateTableGrantMutation = (options) => useGeneratedMutation("createTableGrant", options);
136
- var useCreateTableMutation = (options) => useGeneratedMutation("createTable", options);
137
- var useCreateUniqueConstraintMutation = (options) => useGeneratedMutation("createUniqueConstraint", options);
138
- var useDeleteForeignKeyConstraintMutation = (options) => useGeneratedMutation("deleteForeignKeyConstraint", options);
139
- var useUpdateForeignKeyConstraintMutation = (options) => useGeneratedMutation("updateForeignKeyConstraint", options);
140
-
141
- // src/compat/block-config.tsx
142
- function useSchemaBuilderRuntime() {
143
- const runtime = useSchemaBuilder();
144
- return {
145
- ...runtime,
146
- setCurrentDatabaseApi: (api) => runtime.store.getState().setCurrentDatabaseApi(api)
147
- };
148
- }
149
- function useSchemaBuilderRuntimeStore(selector) {
150
- return useSchemaBuilderStore(selector);
151
- }
152
-
153
- // src/schema/schema-builder-core/lib/gql/hooks/schema-builder/transformers/field-type-mapper.ts
154
- var SQL_KEYWORDS = /* @__PURE__ */ new Set([
155
- "CURRENT_TIMESTAMP",
156
- "CURRENT_DATE",
157
- "CURRENT_TIME",
158
- "LOCALTIME",
159
- "LOCALTIMESTAMP",
160
- "CURRENT_ROLE",
161
- "CURRENT_USER",
162
- "SESSION_USER",
163
- "USER",
164
- "CURRENT_CATALOG",
165
- "CURRENT_SCHEMA"
166
- ]);
167
- function toFieldType(typeName) {
168
- const raw = (typeName ?? "").trim();
169
- let base = raw;
170
- let dims = 0;
171
- while (base.endsWith("[]")) {
172
- base = base.slice(0, -2);
173
- dims += 1;
174
- }
175
- base = base.trim();
176
- const result = { name: base };
177
- if (dims > 0) result.array_dimensions = dims;
178
- return result;
179
- }
180
- function parseScalarLiteral(token) {
181
- const t = token.trim();
182
- if (t === "") return "";
183
- if (t === "true") return true;
184
- if (t === "false") return false;
185
- if (t.toLowerCase() === "null") return null;
186
- if (/^-?\d+(\.\d+)?$/.test(t)) return Number(t);
187
- if (t.startsWith("'") && t.endsWith("'") || t.startsWith('"') && t.endsWith('"')) {
188
- return t.slice(1, -1);
189
- }
190
- return t;
191
- }
192
- function toFieldDefault(def) {
193
- const raw = String(def).trim();
194
- if (raw === "") return void 0;
195
- if (SQL_KEYWORDS.has(raw.toUpperCase())) {
196
- return { sql_keyword: raw.toUpperCase() };
197
- }
198
- const fnMatch = raw.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([\s\S]*)\)$/);
199
- if (fnMatch) {
200
- const fnName = fnMatch[1];
201
- const argsRaw = fnMatch[2].trim();
202
- const result = { function: fnName };
203
- if (argsRaw !== "") {
204
- const args = argsRaw.split(",").map((a) => parseScalarLiteral(a));
205
- if (args.length > 0) result.args = args;
206
- }
207
- return result;
208
- }
209
- if (raw === "true") return { value: true };
210
- if (raw === "false") return { value: false };
211
- if (/^-?\d+(\.\d+)?$/.test(raw)) return { value: Number(raw) };
212
- if (raw.startsWith("'") && raw.endsWith("'") || raw.startsWith('"') && raw.endsWith('"')) {
213
- return { value: raw.slice(1, -1) };
214
- }
215
- return { value: raw };
216
- }
217
- function fieldTypeToTypeName(t) {
218
- if (t == null) return "";
219
- if (typeof t === "string") return t;
220
- if (typeof t === "object") {
221
- const obj = t;
222
- if (typeof obj.name === "string") {
223
- const dims = typeof obj.array_dimensions === "number" && obj.array_dimensions > 0 ? obj.array_dimensions : 0;
224
- return obj.name + "[]".repeat(dims);
225
- }
226
- }
227
- return "";
228
- }
229
-
230
- // src/schema/schema-builder-core/lib/gql/hooks/schema-builder/use-accessible-databases.ts
231
- var accessibleDatabasesQueryKeys = {
232
- all: ["accessible-databases"]};
233
- var databaseConstraintsQueryKeys = {
234
- all: ["database-constraints"]};
235
-
236
- // src/schema/schema-builder-core/lib/gql/hooks/schema-builder/use-schema-builder-selectors.ts
237
- var fluentContextSelector = FluentContextSelector.default ?? FluentContextSelector;
238
- var { createContext: createContext2, useContextSelector } = fluentContextSelector;
239
- var EMPTY_STORE_SCHEMAS = [];
240
- var EMPTY_SCHEMAS = EMPTY_STORE_SCHEMAS;
241
- var NOOP_SELECT_ORG = (_orgId) => void 0;
242
- var NOOP_SELECT_SCHEMA = (_schemaKey) => void 0;
243
- var NOOP_SET_ACTIVE_TAB = (_tab) => void 0;
244
- var IS_CUSTOM_SCHEMA = (schemaKey) => schemaKey.startsWith("custom-");
245
- var SchemaBuilderDataContext = createContext2(null);
246
- function useSchemaBuilderDataSelector(selector) {
247
- return useContextSelector(SchemaBuilderDataContext, (state) => {
248
- if (!state) {
249
- throw new Error("SchemaBuilderDataProvider is missing");
250
- }
251
- return selector(state);
252
- });
253
- }
254
- function useSchemaBuilderSelectors() {
255
- const {
256
- scope,
257
- store,
258
- selectField: selectFieldFromContext,
259
- selectTable: selectTableFromContext
260
- } = useSchemaBuilderRuntime();
261
- const selectedFieldId = useSchemaBuilderRuntimeStore((state) => state.selectedFieldId);
262
- const currentDatabaseApi = useSchemaBuilderRuntimeStore((state) => state.currentDatabaseApi);
263
- const selectedOrgId = scope.orgId;
264
- const activeTab = "schemas";
265
- const customSchemas = EMPTY_SCHEMAS;
266
- const selectOrg = NOOP_SELECT_ORG;
267
- const selectSchema = NOOP_SELECT_SCHEMA;
268
- const selectField = useCallback(
269
- (fieldId) => selectFieldFromContext(fieldId),
270
- [selectFieldFromContext]
271
- );
272
- const clearAllSelections = useCallback(() => {
273
- selectTableFromContext(null);
274
- selectFieldFromContext(null);
275
- }, [selectTableFromContext, selectFieldFromContext]);
276
- const setActiveTab = NOOP_SET_ACTIVE_TAB;
277
- const setCurrentDatabaseApi = useCallback(
278
- (api) => store.getState().setCurrentDatabaseApi(api),
279
- [store]
280
- );
281
- const availableSchemas = useSchemaBuilderDataSelector((state) => state.availableSchemas);
282
- const selectedSchemaKey = useSchemaBuilderDataSelector((state) => state.selectedSchemaKey);
283
- const currentSchemaInfo = useSchemaBuilderDataSelector((state) => state.currentSchemaInfo);
284
- const currentSchema = useSchemaBuilderDataSelector((state) => state.currentSchema);
285
- const currentTable = useSchemaBuilderDataSelector((state) => state.currentTable);
286
- const selectedTableId = useSchemaBuilderDataSelector((state) => state.selectedTableId);
287
- const isLoading = useSchemaBuilderDataSelector((state) => state.isLoading);
288
- const isFetching = useSchemaBuilderDataSelector((state) => state.isFetching);
289
- const error = useSchemaBuilderDataSelector((state) => state.error);
290
- const refetch = useSchemaBuilderDataSelector((state) => state.refetch);
291
- const selectTableFromProvider = useSchemaBuilderDataSelector((state) => state.selectTable);
292
- const currentField = useMemo(
293
- () => currentTable?.fields.find((f) => f.id === selectedFieldId) ?? null,
294
- [currentTable, selectedFieldId]
295
- );
296
- const currentDatabase = useMemo(() => {
297
- if (!currentSchemaInfo?.databaseInfo) return null;
298
- return {
299
- schemaKey: selectedSchemaKey,
300
- databaseId: currentSchemaInfo.databaseInfo.id,
301
- name: currentSchemaInfo.databaseInfo.name,
302
- label: currentSchemaInfo.databaseInfo.label ?? null,
303
- schemaId: currentSchemaInfo.databaseInfo.schemaId ?? null
304
- };
305
- }, [currentSchemaInfo, selectedSchemaKey]);
306
- const isCustomSchema = IS_CUSTOM_SCHEMA;
307
- const getSchemaByKey = useCallback(
308
- (key) => availableSchemas.find((schema) => schema.key === key) ?? null,
309
- [availableSchemas]
310
- );
311
- const selectTable = useCallback(
312
- (tableId, tableName) => {
313
- selectTableFromProvider(tableId, tableName);
314
- selectField(null);
315
- },
316
- [selectTableFromProvider, selectField]
317
- );
318
- return {
319
- // Entity selection state
320
- selectedOrgId,
321
- selectedSchemaKey,
322
- selectedTableId,
323
- selectedFieldId,
324
- activeTab,
325
- // Entity selection actions (with cascade clearing)
326
- selectOrg,
327
- selectSchema,
328
- selectTable,
329
- selectField,
330
- clearAllSelections,
331
- setActiveTab,
332
- // Derived data
333
- availableSchemas,
334
- currentSchema,
335
- currentTable,
336
- currentField,
337
- currentDatabase,
338
- // API state (from Zustand)
339
- currentDatabaseApi,
340
- setCurrentDatabaseApi,
341
- // Helpers
342
- isCustomSchema,
343
- getSchemaByKey,
344
- // Loading/error
345
- isLoading,
346
- isFetching,
347
- error,
348
- refetch,
349
- // Custom schemas
350
- customSchemas
351
- };
352
- }
353
- var BACKEND_MANAGED_POLICY_TYPES = /* @__PURE__ */ new Set(["AuthzNotReadOnly"]);
354
- var databasePoliciesQueryKeys = {
355
- all: ["database-policies"],
356
- byDatabase: (databaseId) => ["database-policies", databaseId]
357
- };
358
- function useDatabasePolicies(databaseId, options = {}) {
359
- const isEnabled = options.enabled !== false && Boolean(databaseId);
360
- const { scope } = useSchemaBuilderRuntime();
361
- const { fetchFieldsQuery, fetchPoliciesQuery, fetchSchemasQuery, fetchTablesQuery } = useSchemaBuilderSdkClient();
362
- return useQuery({
363
- queryKey: schemaBuilderQueryKey(scope, "core", "databasePolicies", { databaseId }),
364
- queryFn: async () => {
365
- const tablesResult = await fetchTablesQuery({
366
- selection: {
367
- fields: { id: true, name: true, useRls: true, category: true, schemaId: true },
368
- where: { databaseId: { equalTo: databaseId } },
369
- orderBy: ["NAME_ASC"]
370
- }
371
- });
372
- const tables = tablesResult.tables?.nodes ?? [];
373
- if (tables.length === 0) {
374
- return [];
375
- }
376
- const tableIds = tables.map((t) => t.id).filter((id) => !!id);
377
- const schemaIds = [...new Set(tables.map((t) => t.schemaId).filter((id) => !!id))];
378
- const [schemasResult, fieldsResult, policiesResult] = await Promise.all([
379
- schemaIds.length > 0 ? fetchSchemasQuery({ selection: { fields: { id: true, schemaName: true }, where: { id: { in: schemaIds } } } }) : Promise.resolve({ schemas: { nodes: [] } }),
380
- tableIds.length > 0 ? fetchFieldsQuery({ selection: { fields: { id: true, name: true, type: true, fieldOrder: true, smartTags: true, tableId: true }, where: { tableId: { in: tableIds } } } }) : Promise.resolve({ fields: { nodes: [] } }),
381
- tableIds.length > 0 ? fetchPoliciesQuery({
382
- selection: {
383
- fields: { id: true, name: true, granteeName: true, privilege: true, permissive: true, disabled: true, policyType: true, data: true, createdAt: true, updatedAt: true, tableId: true },
384
- where: { tableId: { in: tableIds } },
385
- orderBy: ["CREATED_AT_DESC"]
386
- }
387
- }) : Promise.resolve({ policies: { nodes: [] } })
388
- ]);
389
- const schemaMap = /* @__PURE__ */ new Map();
390
- for (const schema of schemasResult.schemas?.nodes ?? []) {
391
- if (schema.id) {
392
- schemaMap.set(schema.id, {
393
- id: schema.id,
394
- schemaName: schema.schemaName ?? ""
395
- });
396
- }
397
- }
398
- const fieldsByTable = /* @__PURE__ */ new Map();
399
- for (const field of fieldsResult.fields?.nodes ?? []) {
400
- if (field.tableId) {
401
- const existing = fieldsByTable.get(field.tableId) ?? [];
402
- existing.push({
403
- id: field.id ?? "",
404
- name: field.name ?? "",
405
- // type is now a structured FieldType object; reduce to its type-name string.
406
- type: fieldTypeToTypeName(field.type),
407
- fieldOrder: field.fieldOrder ?? null,
408
- smartTags: field.smartTags ?? null
409
- });
410
- fieldsByTable.set(field.tableId, existing);
411
- }
412
- }
413
- const policiesByTable = /* @__PURE__ */ new Map();
414
- for (const policy of policiesResult.policies?.nodes ?? []) {
415
- if (!policy.tableId) continue;
416
- if (policy.policyType && BACKEND_MANAGED_POLICY_TYPES.has(policy.policyType)) continue;
417
- const existing = policiesByTable.get(policy.tableId) ?? [];
418
- existing.push({
419
- id: policy.id ?? "",
420
- name: policy.name ?? null,
421
- granteeName: policy.granteeName ?? null,
422
- privilege: policy.privilege ?? null,
423
- permissive: policy.permissive ?? null,
424
- disabled: policy.disabled ?? null,
425
- policyType: policy.policyType ?? null,
426
- data: policy.data ?? null,
427
- createdAt: policy.createdAt ?? null,
428
- updatedAt: policy.updatedAt ?? null
429
- });
430
- policiesByTable.set(policy.tableId, existing);
431
- }
432
- return tables.map((table) => ({
433
- id: table.id ?? "",
434
- name: table.name ?? "",
435
- useRls: table.useRls ?? false,
436
- policies: policiesByTable.get(table.id ?? "") ?? [],
437
- fields: fieldsByTable.get(table.id ?? "") ?? [],
438
- schema: table.schemaId ? schemaMap.get(table.schemaId) ?? null : null,
439
- category: table.category ?? null
440
- }));
441
- },
442
- enabled: isEnabled,
443
- staleTime: 5 * 60 * 1e3,
444
- refetchOnMount: isEnabled,
445
- refetchOnWindowFocus: false,
446
- refetchOnReconnect: false
447
- });
448
- }
449
- function useModuleMutation(operation, options) {
450
- const { adapter, scope, onInvalidate } = useSchemaBuilder();
451
- const feature = "relationships" ;
452
- const operationFn = adapter[feature][operation];
453
- const selection = options?.selection?.fields;
454
- return useMutation({
455
- mutationFn: (variables) => operationFn(variables, { scope, selection }),
456
- onSuccess: () => onInvalidate?.({ scope, feature, operation })
457
- });
458
- }
459
- var useCreateRelationProvisionMutation = (options) => useModuleMutation("createRelationProvision", options);
460
- var blueprintTemplateKeys = { all: ["schema-builder", "blueprint-templates"] };
461
-
462
- // src/schema/schema-builder-core/lib/data/mutation-input.ts
463
- var asFieldIds = (ids) => ids;
464
-
465
- // src/schema/schema-builder-core/lib/data/policy-provisioning.ts
466
- var MEMBERSHIP_TYPES = {
467
- ORGANIZATION: 2};
468
- var POLICY_PROVISIONING_CONFIG = {
469
- AuthzDirectOwner: {
470
- category: "has-module",
471
- hasDataNode: true,
472
- dataNodeType: "DataDirectOwner",
473
- fieldOverrides: {
474
- entity_field: {
475
- type: "string",
476
- required: true,
477
- label: "Owner Field Name",
478
- placeholder: "owner_id",
479
- description: "Column that stores the owner user ID",
480
- defaultValue: "owner_id"
481
- }
482
- }
483
- },
484
- AuthzEntityMembership: {
485
- category: "has-module",
486
- hasDataNode: true,
487
- dataNodeType: "DataEntityMembership",
488
- fieldOverrides: {
489
- entity_field: {
490
- type: "string",
491
- required: true,
492
- label: "Entity Field Name",
493
- placeholder: "entity_id",
494
- description: "Column referencing the org/group",
495
- defaultValue: "entity_id"
496
- },
497
- membership_type: {
498
- type: "integer",
499
- hidden: true,
500
- defaultValue: MEMBERSHIP_TYPES.ORGANIZATION
501
- },
502
- permission: {
503
- type: "string",
504
- component: "permission-select",
505
- label: "Required Permission",
506
- description: "Optional permission the user must have"
507
- },
508
- is_admin: {
509
- type: "boolean",
510
- label: "Admins",
511
- description: "People with admin access can view this."
512
- },
513
- is_owner: {
514
- type: "boolean",
515
- label: "Owners",
516
- description: "People who own the membership can view this."
517
- }
518
- }
519
- },
520
- AuthzDirectOwnerAny: {
521
- category: "needs-fields",
522
- hasDataNode: false,
523
- fieldOverrides: {
524
- entity_fields: {
525
- type: "uuid[]",
526
- required: true,
527
- label: "Owner Fields",
528
- description: "UUID columns to check for ownership (OR logic)",
529
- defaultValue: ["owner_id"],
530
- pgType: "uuid"
531
- }
532
- }
533
- },
534
- AuthzAppMembership: {
535
- category: "no-fields",
536
- hasDataNode: false,
537
- fieldOverrides: {
538
- permission: {
539
- type: "string",
540
- component: "permission-select",
541
- label: "Required Permission",
542
- description: "Optional permission the user must have"
543
- },
544
- is_admin: {
545
- type: "boolean",
546
- label: "Admins",
547
- description: "People with admin access can view this."
548
- },
549
- is_owner: {
550
- type: "boolean",
551
- label: "Owners",
552
- description: "People who own the membership can view this."
553
- }
554
- }
555
- },
556
- AuthzPublishable: {
557
- category: "has-module",
558
- hasDataNode: true,
559
- dataNodeType: "DataPublishable",
560
- fieldOverrides: {
561
- is_published_field: {
562
- type: "string",
563
- label: "Published Flag Field",
564
- placeholder: "is_published",
565
- defaultValue: "is_published"
566
- },
567
- published_at_field: {
568
- type: "string",
569
- label: "Published At Field",
570
- placeholder: "published_at",
571
- defaultValue: "published_at"
572
- },
573
- require_published_at: {
574
- type: "boolean",
575
- label: "Require Published At",
576
- description: "Also require that the publish date has passed",
577
- defaultValue: true
578
- }
579
- }
580
- },
581
- AuthzTemporal: {
582
- category: "needs-fields",
583
- hasDataNode: false,
584
- fieldOverrides: {
585
- valid_from_field: {
586
- type: "string",
587
- required: true,
588
- label: "Valid From Field",
589
- placeholder: "valid_from",
590
- description: "Column for start time",
591
- defaultValue: "valid_from",
592
- pgType: "timestamptz"
593
- },
594
- valid_until_field: {
595
- type: "string",
596
- required: true,
597
- label: "Valid Until Field",
598
- placeholder: "valid_until",
599
- description: "Column for end time",
600
- defaultValue: "valid_until",
601
- pgType: "timestamptz"
602
- },
603
- valid_from_inclusive: {
604
- type: "boolean",
605
- label: "Include Start",
606
- description: "Include start boundary",
607
- defaultValue: true
608
- },
609
- valid_until_inclusive: {
610
- type: "boolean",
611
- label: "Include End",
612
- description: "Include end boundary",
613
- defaultValue: false
614
- }
615
- }
616
- },
617
- AuthzMemberList: {
618
- category: "needs-fields",
619
- hasDataNode: false,
620
- fieldOverrides: {
621
- array_field: {
622
- type: "string",
623
- required: true,
624
- label: "Member List Field",
625
- placeholder: "allowed_users",
626
- description: "Column containing list of user IDs",
627
- defaultValue: "allowed_users",
628
- pgType: "uuid[]"
629
- }
630
- }
631
- },
632
- AuthzRelatedMemberList: {
633
- category: "needs-table",
634
- hasDataNode: false,
635
- fieldOverrides: {
636
- owned_schema: {
637
- hidden: true
638
- },
639
- owned_table: {
640
- type: "string",
641
- required: true,
642
- component: "table-select",
643
- label: "Related Table",
644
- placeholder: "groups",
645
- description: "Table containing the member list"
646
- },
647
- owned_table_key: {
648
- type: "uuid",
649
- required: true,
650
- label: "Member List Column",
651
- placeholder: "member_ids",
652
- description: "List column in related table",
653
- dependsOn: "owned_table"
654
- },
655
- owned_table_ref_key: {
656
- type: "uuid",
657
- required: true,
658
- label: "Reference Key",
659
- placeholder: "id",
660
- description: "FK column in related table",
661
- dependsOn: "owned_table"
662
- },
663
- this_object_key: {
664
- type: "uuid",
665
- required: true,
666
- label: "Foreign Key",
667
- placeholder: "group_id",
668
- description: "FK on this table to related table"
669
- }
670
- }
671
- },
672
- AuthzRelatedEntityMembership: {
673
- category: "needs-table",
674
- hasDataNode: false,
675
- fieldOverrides: {
676
- entity_field: {
677
- type: "uuid",
678
- required: true,
679
- label: "Foreign Key Field",
680
- description: "Field on this table referencing the linked table"
681
- },
682
- membership_type: {
683
- type: "integer",
684
- required: true,
685
- component: "membership-type-select",
686
- label: "Membership Scope"
687
- },
688
- obj_schema: {
689
- hidden: true
690
- },
691
- obj_table: {
692
- type: "string",
693
- required: true,
694
- component: "table-select",
695
- label: "Linked Table",
696
- description: "Table to check for membership"
697
- },
698
- obj_field: {
699
- type: "uuid",
700
- required: true,
701
- label: "Entity Field on Linked Table",
702
- description: "Field containing entity ID for membership check",
703
- dependsOn: "obj_table"
704
- },
705
- permission: {
706
- type: "string",
707
- component: "permission-select",
708
- label: "Required Permission"
709
- },
710
- is_admin: {
711
- type: "boolean",
712
- label: "Admins",
713
- description: "People with admin access can view this."
714
- },
715
- is_owner: {
716
- type: "boolean",
717
- label: "Owners",
718
- description: "People who own the membership can view this."
719
- }
720
- }
721
- },
722
- AuthzOrgHierarchy: {
723
- category: "has-module",
724
- hasDataNode: true,
725
- dataNodeType: "DataOwnershipInEntity",
726
- disabled: true,
727
- fieldOverrides: {
728
- direction: {
729
- type: "string",
730
- required: true,
731
- label: "Direction",
732
- description: "Which direction to traverse the org hierarchy",
733
- defaultValue: "down",
734
- options: [
735
- { value: "down", label: "Down", description: "Managers can see their subordinates" },
736
- { value: "up", label: "Up", description: "Subordinates can see their managers" }
737
- ]
738
- },
739
- entity_field: {
740
- type: "string",
741
- label: "Entity Field Name",
742
- placeholder: "entity_id",
743
- description: "Field referencing the org entity",
744
- defaultValue: "entity_id"
745
- },
746
- anchor_field: {
747
- type: "string",
748
- required: true,
749
- label: "Anchor Field",
750
- placeholder: "owner_id",
751
- description: "Field referencing the user (e.g., owner_id)",
752
- defaultValue: "owner_id"
753
- },
754
- max_depth: {
755
- type: "integer",
756
- label: "Max Depth",
757
- description: "Optional max depth to limit visibility"
758
- }
759
- }
760
- },
761
- AuthzAllowAll: {
762
- category: "no-fields",
763
- hasDataNode: false
764
- },
765
- AuthzDenyAll: {
766
- category: "no-fields",
767
- hasDataNode: false
768
- },
769
- AuthzComposite: {
770
- category: "no-fields",
771
- hasDataNode: false
772
- }
773
- };
774
- var DATA_NODE_GENERATED_FIELDS = {
775
- DataDirectOwner: [
776
- {
777
- name: "owner_id",
778
- type: "uuid",
779
- nullable: false,
780
- description: "References the owning user"
781
- }
782
- ],
783
- DataEntityMembership: [
784
- {
785
- name: "entity_id",
786
- type: "uuid",
787
- nullable: false,
788
- description: "References the organization or group"
789
- }
790
- ],
791
- DataOwnershipInEntity: [
792
- {
793
- name: "owner_id",
794
- type: "uuid",
795
- nullable: false,
796
- description: "References the owning user"
797
- },
798
- {
799
- name: "entity_id",
800
- type: "uuid",
801
- nullable: false,
802
- description: "References the organization or group"
803
- }
804
- ],
805
- DataPublishable: [
806
- {
807
- name: "is_published",
808
- type: "boolean",
809
- nullable: false,
810
- description: "Whether the record is published"
811
- },
812
- {
813
- name: "published_at",
814
- type: "timestamptz",
815
- nullable: true,
816
- description: "When the record was published"
817
- }
818
- ],
819
- DataTimestamps: [
820
- {
821
- name: "created_at",
822
- type: "timestamptz",
823
- nullable: false,
824
- description: "When the record was created"
825
- },
826
- {
827
- name: "updated_at",
828
- type: "timestamptz",
829
- nullable: false,
830
- description: "When the record was last updated"
831
- }
832
- ],
833
- DataPeoplestamps: [
834
- {
835
- name: "created_by",
836
- type: "uuid",
837
- nullable: true,
838
- description: "User who created the record"
839
- },
840
- {
841
- name: "updated_by",
842
- type: "uuid",
843
- nullable: true,
844
- description: "User who last updated the record"
845
- }
846
- ],
847
- DataSoftDelete: [
848
- {
849
- name: "is_deleted",
850
- type: "boolean",
851
- nullable: false,
852
- description: "Whether the record is soft-deleted"
853
- },
854
- {
855
- name: "deleted_at",
856
- type: "timestamptz",
857
- nullable: true,
858
- description: "When the record was deleted"
859
- }
860
- ]
861
- };
862
- function getDataNodeForPolicy(policyType) {
863
- return POLICY_PROVISIONING_CONFIG[policyType]?.dataNodeType;
864
- }
865
- function getGeneratedFields(dataNodeType) {
866
- return DATA_NODE_GENERATED_FIELDS[dataNodeType] ?? [];
867
- }
868
- function sanitizePolicyData(data) {
869
- const sanitized = {};
870
- for (const [key, value] of Object.entries(data)) {
871
- if (value === void 0 || value === null) {
872
- continue;
873
- }
874
- if (typeof value === "string" && value.trim() === "") {
875
- continue;
876
- }
877
- if (Array.isArray(value) && value.length === 0) {
878
- continue;
879
- }
880
- sanitized[key] = value;
881
- }
882
- return sanitized;
883
- }
884
- function buildNodeDataForDataNodeType(dataNodeType, policyData) {
885
- if (!dataNodeType) {
886
- return {};
887
- }
888
- const data = {};
889
- if (dataNodeType === "DataDirectOwner") {
890
- if (policyData.entity_field && policyData.entity_field !== "owner_id") {
891
- data.owner_field_name = policyData.entity_field;
892
- }
893
- }
894
- if (dataNodeType === "DataEntityMembership") {
895
- if (policyData.entity_field && policyData.entity_field !== "entity_id") {
896
- data.entity_field_name = policyData.entity_field;
897
- }
898
- }
899
- if (dataNodeType === "DataOwnershipInEntity") {
900
- if (policyData.entity_field && policyData.entity_field !== "entity_id") {
901
- data.entity_field_name = policyData.entity_field;
902
- }
903
- if (policyData.anchor_field && policyData.anchor_field !== "owner_id") {
904
- data.owner_field_name = policyData.anchor_field;
905
- }
906
- }
907
- return data;
908
- }
909
- function buildNodeData(policyType, policyData) {
910
- return buildNodeDataForDataNodeType(getDataNodeForPolicy(policyType), policyData);
911
- }
912
-
913
- // src/schema/schema-builder-core/lib/constants/membership-types.ts
914
- var MEMBERSHIP_TYPES2 = {
915
- APP: 1,
916
- ORGANIZATION: 2};
917
-
918
- // src/schema/schema-builder-core/components/policies/policy-config.ts
919
- var paramOf = (def) => def.parameter_schema.properties;
920
- var POLICY_TYPE_UI_CONFIG = {
921
- // === MOST COMMON ===
922
- AuthzDirectOwner: {
923
- fallbackTitle: NodeTypes.AuthzDirectOwner.display_name,
924
- description: NodeTypes.AuthzDirectOwner.description,
925
- icon: User,
926
- category: "has-module",
927
- hasDataNode: true,
928
- dataNodeType: NodeTypes.DataDirectOwner.name,
929
- fieldOverrides: {
930
- entity_field: {
931
- type: "string",
932
- required: true,
933
- label: "Owner Field Name",
934
- placeholder: "owner_id",
935
- description: paramOf(NodeTypes.AuthzDirectOwner)?.entity_field?.description,
936
- defaultValue: "owner_id"
937
- }
938
- }
939
- },
940
- AuthzEntityMembership: {
941
- fallbackTitle: NodeTypes.AuthzEntityMembership.display_name,
942
- description: NodeTypes.AuthzEntityMembership.description,
943
- icon: Shield,
944
- category: "has-module",
945
- hasDataNode: true,
946
- dataNodeType: NodeTypes.DataEntityMembership.name,
947
- fieldOverrides: {
948
- entity_field: {
949
- type: "string",
950
- required: true,
951
- label: "Entity Field Name",
952
- placeholder: "entity_id",
953
- description: paramOf(NodeTypes.AuthzEntityMembership)?.entity_field?.description,
954
- defaultValue: "entity_id"
955
- },
956
- membership_type: {
957
- type: "integer",
958
- hidden: true,
959
- defaultValue: MEMBERSHIP_TYPES2.ORGANIZATION
960
- },
961
- permission: {
962
- type: "string",
963
- component: "permission-select",
964
- label: "Required Permission",
965
- description: paramOf(NodeTypes.AuthzEntityMembership)?.permission?.description
966
- },
967
- is_admin: {
968
- type: "boolean",
969
- label: "Admins",
970
- description: paramOf(NodeTypes.AuthzEntityMembership)?.is_admin?.description
971
- },
972
- is_owner: {
973
- type: "boolean",
974
- label: "Owners",
975
- description: paramOf(NodeTypes.AuthzEntityMembership)?.is_owner?.description
976
- }
977
- }
978
- },
979
- // === OWNERSHIP PATTERNS ===
980
- AuthzDirectOwnerAny: {
981
- fallbackTitle: NodeTypes.AuthzDirectOwnerAny.display_name,
982
- description: NodeTypes.AuthzDirectOwnerAny.description,
983
- icon: Users,
984
- category: "needs-fields",
985
- hasDataNode: false,
986
- fieldOverrides: {
987
- entity_fields: {
988
- type: "uuid[]",
989
- required: true,
990
- label: "Owner Fields",
991
- description: paramOf(NodeTypes.AuthzDirectOwnerAny)?.entity_fields?.description,
992
- defaultValue: ["owner_id"],
993
- pgType: "uuid"
994
- }
995
- }
996
- },
997
- AuthzAppMembership: {
998
- fallbackTitle: NodeTypes.AuthzAppMembership.display_name,
999
- description: NodeTypes.AuthzAppMembership.description,
1000
- icon: Globe,
1001
- category: "no-fields",
1002
- hasDataNode: false,
1003
- fieldOverrides: {
1004
- permission: {
1005
- type: "string",
1006
- component: "permission-select",
1007
- label: "Required Permission",
1008
- description: paramOf(NodeTypes.AuthzAppMembership)?.permission?.description
1009
- },
1010
- is_admin: {
1011
- type: "boolean",
1012
- label: "Admins",
1013
- description: paramOf(NodeTypes.AuthzAppMembership)?.is_admin?.description
1014
- },
1015
- is_owner: {
1016
- type: "boolean",
1017
- label: "Owners",
1018
- description: paramOf(NodeTypes.AuthzAppMembership)?.is_owner?.description
1019
- }
1020
- }
1021
- },
1022
- // === TEMPORAL/PUBLISHING PATTERNS ===
1023
- AuthzPublishable: {
1024
- fallbackTitle: NodeTypes.AuthzPublishable.display_name,
1025
- description: NodeTypes.AuthzPublishable.description,
1026
- icon: Eye,
1027
- category: "has-module",
1028
- hasDataNode: true,
1029
- dataNodeType: NodeTypes.DataPublishable.name,
1030
- fieldOverrides: {
1031
- is_published_field: {
1032
- type: "string",
1033
- label: "Published Flag Field",
1034
- placeholder: "is_published",
1035
- description: paramOf(NodeTypes.AuthzPublishable)?.is_published_field?.description,
1036
- defaultValue: paramOf(NodeTypes.AuthzPublishable)?.is_published_field?.default ?? "is_published"
1037
- },
1038
- published_at_field: {
1039
- type: "string",
1040
- label: "Published At Field",
1041
- placeholder: "published_at",
1042
- description: paramOf(NodeTypes.AuthzPublishable)?.published_at_field?.description,
1043
- defaultValue: paramOf(NodeTypes.AuthzPublishable)?.published_at_field?.default ?? "published_at"
1044
- },
1045
- require_published_at: {
1046
- type: "boolean",
1047
- label: "Require Published At",
1048
- description: paramOf(NodeTypes.AuthzPublishable)?.require_published_at?.description,
1049
- defaultValue: paramOf(NodeTypes.AuthzPublishable)?.require_published_at?.default ?? true
1050
- }
1051
- }
1052
- },
1053
- AuthzTemporal: {
1054
- fallbackTitle: NodeTypes.AuthzTemporal.display_name,
1055
- description: NodeTypes.AuthzTemporal.description,
1056
- icon: Clock,
1057
- category: "needs-fields",
1058
- hasDataNode: false,
1059
- fieldOverrides: {
1060
- valid_from_field: {
1061
- type: "string",
1062
- required: true,
1063
- label: "Valid From Field",
1064
- placeholder: "valid_from",
1065
- description: paramOf(NodeTypes.AuthzTemporal)?.valid_from_field?.description,
1066
- defaultValue: "valid_from",
1067
- pgType: "timestamptz"
1068
- },
1069
- valid_until_field: {
1070
- type: "string",
1071
- required: true,
1072
- label: "Valid Until Field",
1073
- placeholder: "valid_until",
1074
- description: paramOf(NodeTypes.AuthzTemporal)?.valid_until_field?.description,
1075
- defaultValue: "valid_until",
1076
- pgType: "timestamptz"
1077
- },
1078
- valid_from_inclusive: {
1079
- type: "boolean",
1080
- label: "Include Start",
1081
- description: paramOf(NodeTypes.AuthzTemporal)?.valid_from_inclusive?.description,
1082
- defaultValue: paramOf(NodeTypes.AuthzTemporal)?.valid_from_inclusive?.default ?? true
1083
- },
1084
- valid_until_inclusive: {
1085
- type: "boolean",
1086
- label: "Include End",
1087
- description: paramOf(NodeTypes.AuthzTemporal)?.valid_until_inclusive?.description,
1088
- defaultValue: paramOf(NodeTypes.AuthzTemporal)?.valid_until_inclusive?.default ?? false
1089
- }
1090
- }
1091
- },
1092
- // === LIST/ARRAY-BASED (deprioritized) ===
1093
- AuthzMemberList: {
1094
- fallbackTitle: NodeTypes.AuthzMemberList.display_name,
1095
- description: NodeTypes.AuthzMemberList.description,
1096
- icon: Users,
1097
- category: "needs-fields",
1098
- hasDataNode: false,
1099
- fieldOverrides: {
1100
- array_field: {
1101
- type: "string",
1102
- required: true,
1103
- label: "Member List Field",
1104
- placeholder: "allowed_users",
1105
- description: paramOf(NodeTypes.AuthzMemberList)?.array_field?.description,
1106
- defaultValue: "allowed_users",
1107
- pgType: "uuid[]"
1108
- }
1109
- }
1110
- },
1111
- AuthzRelatedMemberList: {
1112
- fallbackTitle: NodeTypes.AuthzRelatedMemberList.display_name,
1113
- description: NodeTypes.AuthzRelatedMemberList.description,
1114
- icon: UserCheck,
1115
- category: "needs-table",
1116
- hasDataNode: false,
1117
- fieldOverrides: {
1118
- owned_schema: {
1119
- hidden: true
1120
- // Injected dynamically from current database context at submit time
1121
- },
1122
- owned_table: {
1123
- type: "string",
1124
- required: true,
1125
- component: "table-select",
1126
- label: "Related Table",
1127
- placeholder: "groups",
1128
- description: paramOf(NodeTypes.AuthzRelatedMemberList)?.owned_table?.description
1129
- },
1130
- owned_table_key: {
1131
- type: "uuid",
1132
- required: true,
1133
- label: "Member List Column",
1134
- placeholder: "member_ids",
1135
- description: paramOf(NodeTypes.AuthzRelatedMemberList)?.owned_table_key?.description,
1136
- dependsOn: "owned_table"
1137
- },
1138
- owned_table_ref_key: {
1139
- type: "uuid",
1140
- required: true,
1141
- label: "Reference Key",
1142
- placeholder: "id",
1143
- description: paramOf(NodeTypes.AuthzRelatedMemberList)?.owned_table_ref_key?.description,
1144
- dependsOn: "owned_table"
1145
- },
1146
- this_object_key: {
1147
- type: "uuid",
1148
- required: true,
1149
- label: "Foreign Key",
1150
- placeholder: "group_id",
1151
- description: paramOf(NodeTypes.AuthzRelatedMemberList)?.this_object_key?.description
1152
- }
1153
- }
1154
- },
1155
- AuthzRelatedEntityMembership: {
1156
- fallbackTitle: NodeTypes.AuthzRelatedEntityMembership.display_name,
1157
- description: NodeTypes.AuthzRelatedEntityMembership.description,
1158
- icon: Link,
1159
- category: "needs-table",
1160
- hasDataNode: false,
1161
- fieldOverrides: {
1162
- entity_field: {
1163
- type: "uuid",
1164
- required: true,
1165
- label: "Foreign Key Field",
1166
- description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.entity_field?.description
1167
- },
1168
- membership_type: {
1169
- type: "integer",
1170
- required: true,
1171
- component: "membership-type-select",
1172
- label: "Membership Scope",
1173
- description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.membership_type?.description
1174
- },
1175
- obj_schema: {
1176
- hidden: true
1177
- // Injected dynamically from current database context at submit time
1178
- },
1179
- obj_table: {
1180
- type: "string",
1181
- required: true,
1182
- component: "table-select",
1183
- label: "Linked Table",
1184
- description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.obj_table?.description
1185
- },
1186
- obj_field: {
1187
- type: "uuid",
1188
- required: true,
1189
- label: "Entity Field on Linked Table",
1190
- description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.obj_field?.description,
1191
- dependsOn: "obj_table"
1192
- },
1193
- permission: {
1194
- type: "string",
1195
- component: "permission-select",
1196
- label: "Required Permission",
1197
- description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.permission?.description
1198
- },
1199
- is_admin: {
1200
- type: "boolean",
1201
- label: "Admins",
1202
- description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.is_admin?.description
1203
- },
1204
- is_owner: {
1205
- type: "boolean",
1206
- label: "Owners",
1207
- description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.is_owner?.description
1208
- }
1209
- }
1210
- },
1211
- AuthzOrgHierarchy: {
1212
- fallbackTitle: NodeTypes.AuthzOrgHierarchy.display_name,
1213
- description: NodeTypes.AuthzOrgHierarchy.description,
1214
- icon: Network,
1215
- category: "has-module",
1216
- hasDataNode: true,
1217
- dataNodeType: NodeTypes.DataOwnershipInEntity.name,
1218
- disabled: true,
1219
- fieldOverrides: {
1220
- direction: {
1221
- type: "string",
1222
- required: true,
1223
- label: "Direction",
1224
- description: paramOf(NodeTypes.AuthzOrgHierarchy)?.direction?.description,
1225
- defaultValue: "down",
1226
- options: [
1227
- { value: "down", label: "Down", description: "Managers can see their subordinates" },
1228
- { value: "up", label: "Up", description: "Subordinates can see their managers" }
1229
- ]
1230
- },
1231
- entity_field: {
1232
- type: "string",
1233
- label: "Entity Field Name",
1234
- placeholder: "entity_id",
1235
- description: paramOf(NodeTypes.AuthzOrgHierarchy)?.entity_field?.description,
1236
- defaultValue: paramOf(NodeTypes.AuthzOrgHierarchy)?.entity_field?.default ?? "entity_id"
1237
- },
1238
- anchor_field: {
1239
- type: "string",
1240
- required: true,
1241
- label: "Anchor Field",
1242
- placeholder: "owner_id",
1243
- description: paramOf(NodeTypes.AuthzOrgHierarchy)?.anchor_field?.description,
1244
- defaultValue: "owner_id"
1245
- },
1246
- max_depth: {
1247
- type: "integer",
1248
- label: "Max Depth",
1249
- description: paramOf(NodeTypes.AuthzOrgHierarchy)?.max_depth?.description
1250
- }
1251
- }
1252
- },
1253
- // === SIMPLE POLICIES ===
1254
- AuthzAllowAll: {
1255
- fallbackTitle: NodeTypes.AuthzAllowAll.display_name,
1256
- description: NodeTypes.AuthzAllowAll.description,
1257
- icon: Unlock,
1258
- category: "no-fields",
1259
- hasDataNode: false
1260
- },
1261
- AuthzDenyAll: {
1262
- fallbackTitle: NodeTypes.AuthzDenyAll.display_name,
1263
- description: NodeTypes.AuthzDenyAll.description,
1264
- icon: Lock,
1265
- category: "no-fields",
1266
- hasDataNode: false
1267
- },
1268
- // === COMPOSITE POLICY ===
1269
- AuthzComposite: {
1270
- fallbackTitle: NodeTypes.AuthzComposite.display_name,
1271
- description: NodeTypes.AuthzComposite.description,
1272
- icon: Layers,
1273
- category: "no-fields",
1274
- hasDataNode: false
1275
- }
1276
- };
1277
- var DATA_NODE_GENERATED_FIELDS2 = {
1278
- DataDirectOwner: [
1279
- {
1280
- name: "owner_id",
1281
- type: "uuid",
1282
- nullable: false,
1283
- description: "References the owning user"
1284
- }
1285
- ],
1286
- DataEntityMembership: [
1287
- {
1288
- name: "entity_id",
1289
- type: "uuid",
1290
- nullable: false,
1291
- description: "References the organization or group"
1292
- }
1293
- ],
1294
- DataOwnershipInEntity: [
1295
- {
1296
- name: "owner_id",
1297
- type: "uuid",
1298
- nullable: false,
1299
- description: "References the owning user"
1300
- },
1301
- {
1302
- name: "entity_id",
1303
- type: "uuid",
1304
- nullable: false,
1305
- description: "References the organization or group"
1306
- }
1307
- ],
1308
- DataPublishable: [
1309
- {
1310
- name: "is_published",
1311
- type: "boolean",
1312
- nullable: false,
1313
- description: "Whether the record is published"
1314
- },
1315
- {
1316
- name: "published_at",
1317
- type: "timestamptz",
1318
- nullable: true,
1319
- description: "When the record was published"
1320
- }
1321
- ],
1322
- DataTimestamps: [
1323
- {
1324
- name: "created_at",
1325
- type: "timestamptz",
1326
- nullable: false,
1327
- description: "When the record was created"
1328
- },
1329
- {
1330
- name: "updated_at",
1331
- type: "timestamptz",
1332
- nullable: false,
1333
- description: "When the record was last updated"
1334
- }
1335
- ],
1336
- DataPeoplestamps: [
1337
- {
1338
- name: "created_by",
1339
- type: "uuid",
1340
- nullable: true,
1341
- description: "User who created the record"
1342
- },
1343
- {
1344
- name: "updated_by",
1345
- type: "uuid",
1346
- nullable: true,
1347
- description: "User who last updated the record"
1348
- }
1349
- ],
1350
- DataSoftDelete: [
1351
- {
1352
- name: "is_deleted",
1353
- type: "boolean",
1354
- nullable: false,
1355
- description: "Whether the record is soft-deleted"
1356
- },
1357
- {
1358
- name: "deleted_at",
1359
- type: "timestamptz",
1360
- nullable: true,
1361
- description: "When the record was deleted"
1362
- }
1363
- ]
1364
- };
1365
- function getGeneratedFields2(dataNodeType) {
1366
- return getGeneratedFields(dataNodeType);
1367
- }
1368
- function getGeneratedFieldMappings(policyType) {
1369
- if (!policyType.dataNodeType) return void 0;
1370
- const generatedFields = DATA_NODE_GENERATED_FIELDS2[policyType.dataNodeType];
1371
- if (!generatedFields) return void 0;
1372
- const generatedFieldNames = new Set(generatedFields.map((f) => f.name));
1373
- const result = {};
1374
- for (const [policyKey, override] of Object.entries(policyType.fieldOverrides ?? {})) {
1375
- const defaultValue = override?.defaultValue;
1376
- if (typeof defaultValue === "string" && generatedFieldNames.has(defaultValue)) {
1377
- result[defaultValue] = { policyKey, defaultValue };
1378
- }
1379
- }
1380
- return Object.keys(result).length > 0 ? result : void 0;
1381
- }
1382
- function getDataNodeForPolicy2(policyType) {
1383
- return getDataNodeForPolicy(policyType);
1384
- }
1385
- function sanitizePolicyData2(data) {
1386
- return sanitizePolicyData(data);
1387
- }
1388
- function buildNodeData2(policyData, policyType) {
1389
- return buildNodeData(policyType.name, policyData);
1390
- }
1391
-
1392
- // src/schema/schema-builder-core/lib/gql/hooks/dashboard/dashboard-query-keys.ts
1393
- function isDashboardCacheScopeKey(value) {
1394
- if (!value || typeof value !== "object") return false;
1395
- const candidate = value;
1396
- return "databaseId" in candidate && "endpoint" in candidate;
1397
- }
1398
- var databaseTablesQueryKeys = {
1399
- all: ["database-tables"],
1400
- byDatabase: (databaseId) => [...databaseTablesQueryKeys.all, { databaseId }],
1401
- byDatabaseWithOptions: (databaseId, options) => [...databaseTablesQueryKeys.byDatabase(databaseId), options]
1402
- };
1403
- var userDatabasesQueryKeys = {
1404
- all: ["user-databases"]};
1405
-
1406
- // src/schema/schema-builder-core/lib/gql/hooks/schema-builder/modules/invalidate-database-entities.ts
1407
- var invalidateQueryKey = (queryClient, queryKey) => queryClient.invalidateQueries({ queryKey });
1408
- function invalidateDashboardQueries(queryClient, databaseId) {
1409
- const matchesDashboard = (queryKey) => {
1410
- const [root, scope] = queryKey;
1411
- if (root !== "sheets") return false;
1412
- if (!databaseId) return true;
1413
- return isDashboardCacheScopeKey(scope) && scope.databaseId === databaseId;
1414
- };
1415
- queryClient.removeQueries({
1416
- predicate: (query) => {
1417
- if (!matchesDashboard(query.queryKey)) return false;
1418
- const type = query.queryKey[2];
1419
- return type === "meta" || type === "relations";
1420
- }
1421
- });
1422
- return queryClient.invalidateQueries({
1423
- predicate: (query) => matchesDashboard(query.queryKey)
1424
- });
1425
- }
1426
- async function invalidateDatabaseEntities(queryClient, databaseId) {
1427
- const tasks = [];
1428
- tasks.push(invalidateQueryKey(queryClient, ["@constructive-io/schema-builder"]));
1429
- if (databaseId) {
1430
- tasks.push(invalidateQueryKey(queryClient, databaseTablesQueryKeys.byDatabase(databaseId)));
1431
- tasks.push(invalidateQueryKey(queryClient, databasePoliciesQueryKeys.byDatabase(databaseId)));
1432
- tasks.push(invalidateQueryKey(queryClient, domainKeys.lists()));
1433
- tasks.push(invalidateQueryKey(queryClient, ["database-table"]));
1434
- }
1435
- tasks.push(invalidateDashboardQueries(queryClient, databaseId));
1436
- tasks.push(invalidateQueryKey(queryClient, userDatabasesQueryKeys.all));
1437
- tasks.push(invalidateQueryKey(queryClient, accessibleDatabasesQueryKeys.all));
1438
- tasks.push(invalidateQueryKey(queryClient, databaseConstraintsQueryKeys.all));
1439
- tasks.push(invalidateQueryKey(queryClient, apiKeys.all));
1440
- tasks.push(invalidateQueryKey(queryClient, schemaKeys.all));
1441
- tasks.push(invalidateQueryKey(queryClient, siteKeys.all));
1442
- tasks.push(invalidateQueryKey(queryClient, blueprintTemplateKeys.all));
1443
- tasks.push(invalidateQueryKey(queryClient, databaseTablesQueryKeys.all));
1444
- tasks.push(invalidateQueryKey(queryClient, databasePoliciesQueryKeys.all));
1445
- tasks.push(invalidateQueryKey(queryClient, domainKeys.all));
1446
- await Promise.allSettled(tasks);
1447
- }
1448
-
1449
- // src/schema/schema-builder-core/lib/policies/provision-helpers.ts
1450
- var ALL_CRUD_PRIVILEGES = [
1451
- ["select", "*"],
1452
- ["insert", "*"],
1453
- ["update", "*"],
1454
- ["delete", "*"]
1455
- ];
1456
- function buildGrants(roles = ["authenticated"], privileges = ALL_CRUD_PRIVILEGES) {
1457
- return [{ roles, privileges }];
1458
- }
1459
- function buildPolicyEntry(type, opts = {}) {
1460
- const entry = { $type: type };
1461
- if (opts.data && Object.keys(opts.data).length > 0) entry.data = opts.data;
1462
- if (opts.privileges && opts.privileges.length > 0) entry.privileges = opts.privileges;
1463
- if (opts.policy_role) entry.policy_role = opts.policy_role;
1464
- if (opts.permissive !== void 0) entry.permissive = opts.permissive;
1465
- if (opts.policy_name) entry.policy_name = opts.policy_name;
1466
- return entry;
1467
- }
1468
-
1469
- // src/schema/schema-builder-policies/components/policies/policy-hooks.ts
1470
- function buildPolicyTypesFromUIConfig() {
1471
- return Object.entries(POLICY_TYPE_UI_CONFIG).filter(([, c]) => !c.disabled).map(([name, uiConfig]) => ({
1472
- name,
1473
- title: uiConfig.fallbackTitle,
1474
- description: uiConfig.description,
1475
- icon: uiConfig.icon,
1476
- category: uiConfig.category,
1477
- hasDataNode: uiConfig.hasDataNode,
1478
- dataNodeType: uiConfig.dataNodeType,
1479
- generatedFields: uiConfig.dataNodeType ? getGeneratedFields2(uiConfig.dataNodeType) : [],
1480
- fieldOverrides: uiConfig.fieldOverrides,
1481
- advancedFields: uiConfig.advancedFields,
1482
- diagramKey: name
1483
- }));
1484
- }
1485
- function usePolicyTypes() {
1486
- const policyTypes = useMemo(() => {
1487
- return buildPolicyTypesFromUIConfig();
1488
- }, []);
1489
- return {
1490
- policyTypes,
1491
- isLoading: false,
1492
- error: null
1493
- };
1494
- }
1495
- function resolveFormFieldType(override) {
1496
- if (override.component) {
1497
- return override.component;
1498
- }
1499
- switch (override.type) {
1500
- case "boolean":
1501
- return "boolean";
1502
- case "integer":
1503
- return "number";
1504
- case "uuid":
1505
- return "field-select";
1506
- case "uuid[]":
1507
- return "field-multi-select";
1508
- case "string":
1509
- default:
1510
- return "text";
1511
- }
1512
- }
1513
- function buildFormFields(overrides) {
1514
- if (!overrides) return [];
1515
- const fields = [];
1516
- for (const [key, override] of Object.entries(overrides)) {
1517
- if (override.hidden) continue;
1518
- if (!override.type && !override.component) continue;
1519
- fields.push({
1520
- key,
1521
- type: resolveFormFieldType(override),
1522
- label: override.label ?? formatKeyAsLabel(key),
1523
- description: override.description,
1524
- placeholder: override.placeholder,
1525
- required: override.required ?? false,
1526
- defaultValue: override.defaultValue,
1527
- dependsOn: override.dependsOn,
1528
- options: override.options,
1529
- pgType: override.pgType
1530
- });
1531
- }
1532
- return fields;
1533
- }
1534
- function formatKeyAsLabel(key) {
1535
- return key.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
1536
- }
1537
- function useFormSchema(policyType) {
1538
- return useMemo(() => {
1539
- if (!policyType) {
1540
- return {
1541
- mainFields: [],
1542
- advancedFields: [],
1543
- allFields: []
1544
- };
1545
- }
1546
- const allFields = buildFormFields(policyType.fieldOverrides);
1547
- const advancedKeys = new Set(policyType.advancedFields ?? []);
1548
- const mainFields = allFields.filter((f) => !advancedKeys.has(f.key));
1549
- const advancedFields = allFields.filter((f) => advancedKeys.has(f.key));
1550
- return {
1551
- mainFields,
1552
- advancedFields,
1553
- allFields
1554
- };
1555
- }, [policyType]);
1556
- }
1557
- function getDefaultFormValues(policyType) {
1558
- if (!policyType) return {};
1559
- const fields = buildFormFields(policyType.fieldOverrides);
1560
- const defaults = {};
1561
- for (const field of fields) {
1562
- if (field.defaultValue !== void 0) {
1563
- defaults[field.key] = field.defaultValue;
1564
- }
1565
- }
1566
- if (policyType.fieldOverrides) {
1567
- for (const [key, override] of Object.entries(policyType.fieldOverrides)) {
1568
- if (override.hidden && override.defaultValue !== void 0 && defaults[key] === void 0) {
1569
- defaults[key] = override.defaultValue;
1570
- }
1571
- }
1572
- }
1573
- return defaults;
1574
- }
1575
-
1576
- // src/schema/schema-builder-relationships/lib/gql/hooks/schema-builder/use-relation-provision.ts
1577
- var RELATION_TYPE_MAP = {
1578
- "one-to-one": RelationHasOne.name,
1579
- "belongs-to": RelationBelongsTo.name,
1580
- "one-to-many": RelationHasMany.name,
1581
- "many-to-many": RelationManyToMany.name
1582
- };
1583
- function useRelationProvision(options) {
1584
- const queryClient = useQueryClient();
1585
- const { selectTable, currentDatabase, currentSchema } = useSchemaBuilderSelectors();
1586
- const createProvisionMutation = useCreateRelationProvisionMutation({
1587
- selection: {
1588
- fields: {
1589
- id: true,
1590
- outFieldId: true,
1591
- outJunctionTableId: true,
1592
- outSourceFieldId: true,
1593
- outTargetFieldId: true
1594
- }
1595
- }
1596
- });
1597
- return useMutation({
1598
- mutationFn: async (input) => {
1599
- const databaseId = currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId;
1600
- if (!databaseId) throw new Error("Database ID not found");
1601
- const relationType = RELATION_TYPE_MAP[input.relationshipType];
1602
- if (!relationType) throw new Error(`Unsupported relationship type: ${input.relationshipType}`);
1603
- const isManyToMany = input.relationshipType === "many-to-many";
1604
- let derivedNodes;
1605
- let resolvedPolicyData = input.policyData ?? {};
1606
- if (isManyToMany) {
1607
- const policyName = input.policyType || "AuthzAllowAll";
1608
- const dataNode = getDataNodeForPolicy2(policyName);
1609
- if (input.policyTypeObj) {
1610
- const defaults = getDefaultFormValues(input.policyTypeObj);
1611
- resolvedPolicyData = { ...defaults, ...resolvedPolicyData };
1612
- resolvedPolicyData = sanitizePolicyData2(resolvedPolicyData);
1613
- }
1614
- const nodes = [];
1615
- if (!input.useCompositeKey) {
1616
- nodes.push({ $type: "DataId" });
1617
- }
1618
- if (dataNode) {
1619
- const baseNodeData = input.policyTypeObj ? buildNodeData2(resolvedPolicyData, input.policyTypeObj) : {};
1620
- nodes.push({ $type: dataNode, ...Object.keys(baseNodeData).length > 0 ? { data: baseNodeData } : {} });
1621
- }
1622
- if (nodes.length > 0) {
1623
- derivedNodes = nodes;
1624
- }
1625
- }
1626
- const result = await createProvisionMutation.mutateAsync({
1627
- databaseId,
1628
- relationType,
1629
- sourceTableId: input.sourceTableId,
1630
- targetTableId: input.targetTableId,
1631
- ...input.deleteAction && { deleteAction: input.deleteAction },
1632
- ...input.fieldName && { fieldName: input.fieldName },
1633
- ...input.isRequired !== void 0 && { isRequired: input.isRequired },
1634
- ...input.junctionTableName && { junctionTableName: input.junctionTableName },
1635
- ...input.useCompositeKey !== void 0 && { useCompositeKey: input.useCompositeKey },
1636
- ...input.sourceFieldName && { sourceFieldName: input.sourceFieldName },
1637
- ...input.targetFieldName && { targetFieldName: input.targetFieldName },
1638
- ...derivedNodes && { nodes: derivedNodes },
1639
- ...input.exposeInApi !== void 0 && { exposeInApi: input.exposeInApi },
1640
- // M2M: junction table gets grants + a single policy
1641
- ...isManyToMany && {
1642
- grants: buildGrants(),
1643
- policies: [
1644
- buildPolicyEntry(input.policyType || "AuthzAllowAll", {
1645
- permissive: true,
1646
- ...Object.keys(resolvedPolicyData).length > 0 && { data: resolvedPolicyData }
1647
- })
1648
- ]
1649
- }
1650
- });
1651
- const provision = result.createRelationProvision?.relationProvision;
1652
- if (!provision) throw new Error("Failed to create relation provision");
1653
- return {
1654
- outFieldId: provision.outFieldId ?? null,
1655
- outJunctionTableId: provision.outJunctionTableId ?? null,
1656
- outSourceFieldId: provision.outSourceFieldId ?? null,
1657
- outTargetFieldId: provision.outTargetFieldId ?? null
1658
- };
1659
- },
1660
- onSuccess: async (_result, input) => {
1661
- await invalidateDatabaseEntities(queryClient, currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId);
1662
- if (!options?.skipTableSelect) {
1663
- selectTable(input.sourceTableId);
1664
- }
1665
- },
1666
- onError: (error) => {
1667
- console.error("Failed to provision relation:", error);
1668
- }
1669
- });
1670
- }
1671
- async function getTableByName(databaseId, tableName, client) {
1672
- try {
1673
- const tableResult = await client.fetchTablesQuery({
1674
- selection: {
1675
- fields: { id: true, name: true, useRls: true },
1676
- where: { databaseId: { equalTo: databaseId }, name: { equalTo: tableName } },
1677
- first: 1
1678
- }
1679
- });
1680
- const table = tableResult?.tables?.nodes?.[0];
1681
- if (!table?.id) {
1682
- return null;
1683
- }
1684
- const fieldsResult = await client.fetchFieldsQuery({
1685
- selection: {
1686
- fields: { id: true, name: true },
1687
- where: { tableId: { equalTo: table.id } }
1688
- }
1689
- });
1690
- const fields = fieldsResult?.fields?.nodes ?? [];
1691
- return {
1692
- id: table.id,
1693
- name: table.name ?? tableName,
1694
- useRls: table.useRls ?? false,
1695
- fields: fields.map((f) => ({
1696
- id: f.id ?? "",
1697
- name: f.name ?? ""
1698
- })).filter((f) => f.id && f.name)
1699
- };
1700
- } catch (error) {
1701
- console.error(`Failed to fetch table ${tableName}:`, error);
1702
- return null;
1703
- }
1704
- }
1705
- function resolveFieldIds(table, fieldNames) {
1706
- const fieldIds = [];
1707
- for (const fieldName of fieldNames) {
1708
- const field = table.fields.find((f) => f.name === fieldName);
1709
- if (field) {
1710
- fieldIds.push(field.id);
1711
- } else {
1712
- console.warn(`Field ${fieldName} not found in table ${table.name}, skipping from grant`);
1713
- }
1714
- }
1715
- return fieldIds;
1716
- }
1717
- function useCreateTableGrant() {
1718
- const queryClient = useQueryClient();
1719
- const sdkClient = useSchemaBuilderSdkClient();
1720
- const createGrantMutation = useCreateTableGrantMutation({ selection: { fields: { id: true } } });
1721
- return useMutation({
1722
- mutationFn: async (input) => {
1723
- const { databaseId, tableName, privileges, fieldNames, roleName = "authenticated" } = input;
1724
- const table = await getTableByName(databaseId, tableName, sdkClient);
1725
- if (!table) {
1726
- throw new Error(`Table ${tableName} not found`);
1727
- }
1728
- let fieldIds;
1729
- if (fieldNames && fieldNames.length > 0) {
1730
- fieldIds = resolveFieldIds(table, fieldNames);
1731
- if (fieldIds.length === 0) {
1732
- throw new Error(`No valid fields found for grant on table ${tableName}`);
1733
- }
1734
- }
1735
- const results = [];
1736
- for (const privilege of privileges) {
1737
- try {
1738
- const grantInput = {
1739
- tableId: table.id,
1740
- privilege,
1741
- granteeName: roleName,
1742
- ...fieldIds && fieldIds.length > 0 && { fieldIds }
1743
- };
1744
- const result = await createGrantMutation.mutateAsync(
1745
- grantInput
1746
- );
1747
- results.push(result);
1748
- } catch (error) {
1749
- const isDuplicate = error?.message?.includes("already exists") || error?.message?.includes("duplicate key") || error?.message?.includes("unique constraint") || error?.message?.includes("unique violation");
1750
- if (isDuplicate) {
1751
- continue;
1752
- }
1753
- throw new Error(`Failed to create ${privilege} grant on ${tableName}: ${error.message}`);
1754
- }
1755
- }
1756
- return results;
1757
- },
1758
- onSuccess: async (_result, variables) => {
1759
- await invalidateDatabaseEntities(queryClient, variables.databaseId);
1760
- },
1761
- onError: (error) => {
1762
- console.error("Failed to create table grant:", error);
1763
- }
1764
- });
1765
- }
1766
-
1767
- // src/schema/schema-builder-relationships/lib/gql/hooks/schema-builder/use-relationship-mutations.ts
1768
- function useCreateForeignKey() {
1769
- const queryClient = useQueryClient();
1770
- const { selectTable, currentDatabase, currentSchema } = useSchemaBuilderSelectors();
1771
- const createFkMutation = useCreateForeignKeyConstraintMutation({ selection: { fields: { id: true, name: true } } });
1772
- const createUniqueMutation = useCreateUniqueConstraintMutation({ selection: { fields: { id: true } } });
1773
- return useMutation({
1774
- mutationFn: async (input) => {
1775
- const databaseId = currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId;
1776
- if (!databaseId) {
1777
- throw new Error("Database ID not found");
1778
- }
1779
- const refUniqueConstraintName = `${input.refTableId}_${input.refFieldIds.join("_")}_ref_unique`.slice(0, 63);
1780
- try {
1781
- await createUniqueMutation.mutateAsync({
1782
- tableId: input.refTableId,
1783
- databaseId,
1784
- fieldIds: asFieldIds(input.refFieldIds),
1785
- name: refUniqueConstraintName,
1786
- type: "u"
1787
- });
1788
- } catch (error) {
1789
- const errorMessage = error instanceof Error ? error.message : "";
1790
- if (!errorMessage.includes("already exists") && !errorMessage.includes("duplicate")) {
1791
- throw error;
1792
- }
1793
- }
1794
- const result = await createFkMutation.mutateAsync({
1795
- databaseId,
1796
- tableId: input.tableId,
1797
- fieldIds: asFieldIds(input.fieldIds),
1798
- refTableId: input.refTableId,
1799
- refFieldIds: asFieldIds(input.refFieldIds),
1800
- name: input.name ?? void 0,
1801
- deleteAction: input.deleteAction ?? "a",
1802
- updateAction: input.updateAction ?? "a",
1803
- type: "f",
1804
- smartTags: input.relationshipType ? { relationshipType: input.relationshipType } : void 0
1805
- });
1806
- const createdFk = result.createForeignKeyConstraint?.foreignKeyConstraint;
1807
- if (!createdFk?.id) {
1808
- throw new Error("Failed to create foreign key constraint");
1809
- }
1810
- if (input.relationshipType === RelationshipTypes.ONE_TO_ONE) {
1811
- const fkName = input.name || createdFk.name || "fk";
1812
- const uniqueName = fkName.replace(/_fkey\d*$/, "_unique");
1813
- await createUniqueMutation.mutateAsync({
1814
- tableId: input.tableId,
1815
- databaseId,
1816
- fieldIds: asFieldIds(input.fieldIds),
1817
- name: uniqueName,
1818
- type: "u"
1819
- });
1820
- }
1821
- return { id: createdFk.id, name: createdFk.name ?? "" };
1822
- },
1823
- onSuccess: async (_createdForeignKey, variables) => {
1824
- await invalidateDatabaseEntities(queryClient, currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId);
1825
- selectTable(variables.tableId);
1826
- },
1827
- onError: (error) => {
1828
- console.error("Failed to create foreign key constraint:", error);
1829
- }
1830
- });
1831
- }
1832
- function useUpdateForeignKey() {
1833
- const queryClient = useQueryClient();
1834
- const { selectTable, selectedTableId, currentDatabase, currentSchema } = useSchemaBuilderSelectors();
1835
- const updateFkMutation = useUpdateForeignKeyConstraintMutation({ selection: { fields: { id: true, name: true } } });
1836
- return useMutation({
1837
- mutationFn: async (input) => {
1838
- const patch = {};
1839
- if (input.name !== void 0) patch.name = input.name;
1840
- if (input.fieldIds !== void 0) patch.fieldIds = input.fieldIds;
1841
- if (input.refTableId !== void 0) patch.refTableId = input.refTableId;
1842
- if (input.refFieldIds !== void 0) patch.refFieldIds = input.refFieldIds;
1843
- if (input.deleteAction !== void 0) patch.deleteAction = input.deleteAction;
1844
- if (input.updateAction !== void 0) patch.updateAction = input.updateAction;
1845
- const result = await updateFkMutation.mutateAsync({ id: input.id, foreignKeyConstraintPatch: patch });
1846
- const updatedFk = result.updateForeignKeyConstraint?.foreignKeyConstraint;
1847
- if (!updatedFk?.id) {
1848
- throw new Error("Failed to update foreign key constraint");
1849
- }
1850
- return { id: updatedFk.id, name: updatedFk.name ?? "" };
1851
- },
1852
- onSuccess: async () => {
1853
- await invalidateDatabaseEntities(queryClient, currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId);
1854
- if (selectedTableId) {
1855
- selectTable(selectedTableId);
1856
- }
1857
- },
1858
- onError: (error) => {
1859
- console.error("Failed to update foreign key constraint:", error);
1860
- }
1861
- });
1862
- }
1863
- function useDeleteForeignKey() {
1864
- const queryClient = useQueryClient();
1865
- const { selectTable, selectedTableId, currentDatabase, currentSchema } = useSchemaBuilderSelectors();
1866
- const deleteFkMutation = useDeleteForeignKeyConstraintMutation({ selection: { fields: { id: true } } });
1867
- return useMutation({
1868
- mutationFn: async (input) => {
1869
- await deleteFkMutation.mutateAsync({ id: input.id });
1870
- return { id: input.id };
1871
- },
1872
- onSuccess: async () => {
1873
- await invalidateDatabaseEntities(queryClient, currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId);
1874
- if (selectedTableId) {
1875
- selectTable(selectedTableId);
1876
- }
1877
- },
1878
- onError: (error) => {
1879
- console.error("Failed to delete foreign key constraint:", error);
1880
- }
1881
- });
1882
- }
1883
- function useCreateManyToMany() {
1884
- const queryClient = useQueryClient();
1885
- const { selectTable, currentDatabase, currentSchema } = useSchemaBuilderSelectors();
1886
- const { mutateAsync: createGrant } = useCreateTableGrant();
1887
- const createTableMutation = useCreateTableMutation({ selection: { fields: { id: true, name: true } } });
1888
- const createFieldMutation = useCreateFieldMutation({ selection: { fields: { id: true } } });
1889
- const createPkMutation = useCreatePrimaryKeyConstraintMutation({ selection: { fields: { id: true } } });
1890
- const createFkMutation = useCreateForeignKeyConstraintMutation({ selection: { fields: { id: true } } });
1891
- const createUniqueMutation = useCreateUniqueConstraintMutation({ selection: { fields: { id: true } } });
1892
- return useMutation({
1893
- mutationFn: async (input) => {
1894
- const databaseId = currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId;
1895
- const schemaId = currentDatabase?.schemaId ?? currentSchema?.metadata?.schemaId;
1896
- if (!databaseId || !schemaId) {
1897
- throw new Error("Database ID or Schema ID not found");
1898
- }
1899
- const deleteAction = input.deleteAction ?? ForeignKeyActions.CASCADE;
1900
- const updateAction = input.updateAction ?? ForeignKeyActions.NO_ACTION;
1901
- const tableResult = await createTableMutation.mutateAsync({
1902
- name: input.junctionTableName,
1903
- databaseId,
1904
- schemaId
1905
- });
1906
- const junctionTable = tableResult.createTable?.table;
1907
- if (!junctionTable?.id || !junctionTable?.name) {
1908
- throw new Error("Failed to create junction table");
1909
- }
1910
- const junctionTableId = junctionTable.id;
1911
- const junctionTableName = junctionTable.name;
1912
- const idFieldResult = await createFieldMutation.mutateAsync({
1913
- name: "id",
1914
- // type/defaultValue are structured JSONB objects in the metaschema now.
1915
- type: toFieldType("uuid"),
1916
- tableId: junctionTableId,
1917
- databaseId,
1918
- isRequired: true,
1919
- defaultValue: toFieldDefault("uuidv7()")
1920
- });
1921
- const idField = idFieldResult.createField?.field;
1922
- if (!idField?.id) {
1923
- throw new Error("Failed to create id field");
1924
- }
1925
- const idFieldId = idField.id;
1926
- await createPkMutation.mutateAsync({
1927
- tableId: junctionTableId,
1928
- databaseId,
1929
- fieldIds: asFieldIds([idFieldId]),
1930
- name: `${input.junctionTableName}_pkey`,
1931
- type: "p"
1932
- });
1933
- const fieldAName = `${input.tableAName}_id`;
1934
- const fieldBName = `${input.tableBName}_id`;
1935
- const fieldAResult = await createFieldMutation.mutateAsync({
1936
- name: fieldAName,
1937
- // type is a structured JSONB object in the metaschema now.
1938
- type: toFieldType("uuid"),
1939
- tableId: junctionTableId,
1940
- databaseId,
1941
- isRequired: true
1942
- });
1943
- const fieldA = fieldAResult.createField?.field;
1944
- if (!fieldA?.id) {
1945
- throw new Error("Failed to create FK field for table A");
1946
- }
1947
- const fieldAId = fieldA.id;
1948
- const fieldBResult = await createFieldMutation.mutateAsync({
1949
- name: fieldBName,
1950
- // type is a structured JSONB object in the metaschema now.
1951
- type: toFieldType("uuid"),
1952
- tableId: junctionTableId,
1953
- databaseId,
1954
- isRequired: true
1955
- });
1956
- const fieldB = fieldBResult.createField?.field;
1957
- if (!fieldB?.id) {
1958
- throw new Error("Failed to create FK field for table B");
1959
- }
1960
- const fieldBId = fieldB.id;
1961
- await createFkMutation.mutateAsync({
1962
- databaseId,
1963
- tableId: junctionTableId,
1964
- fieldIds: asFieldIds([fieldAId]),
1965
- refTableId: input.tableAId,
1966
- refFieldIds: asFieldIds([input.tableAPrimaryKeyFieldId]),
1967
- name: `${input.junctionTableName}_${input.tableAName}_fkey`,
1968
- deleteAction,
1969
- updateAction,
1970
- type: "f"
1971
- });
1972
- await createFkMutation.mutateAsync({
1973
- databaseId,
1974
- tableId: junctionTableId,
1975
- fieldIds: asFieldIds([fieldBId]),
1976
- refTableId: input.tableBId,
1977
- refFieldIds: asFieldIds([input.tableBPrimaryKeyFieldId]),
1978
- name: `${input.junctionTableName}_${input.tableBName}_fkey`,
1979
- deleteAction,
1980
- updateAction,
1981
- type: "f"
1982
- });
1983
- await createUniqueMutation.mutateAsync({
1984
- tableId: junctionTableId,
1985
- databaseId,
1986
- fieldIds: asFieldIds([fieldAId, fieldBId]),
1987
- name: `${input.junctionTableName}_pair_unique`,
1988
- type: "u"
1989
- });
1990
- await createGrant({
1991
- databaseId,
1992
- tableName: junctionTableName,
1993
- privileges: ["select", "insert", "update", "delete"],
1994
- roleName: "authenticated"
1995
- }).catch((error) => {
1996
- console.warn(`Failed to grant permissions for junction table: ${error instanceof Error ? error.message : "Unknown error"}`);
1997
- });
1998
- return {
1999
- junctionTableId,
2000
- junctionTableName
2001
- };
2002
- },
2003
- onSuccess: async (result) => {
2004
- await invalidateDatabaseEntities(queryClient, currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId);
2005
- if (result?.junctionTableId && result?.junctionTableName) {
2006
- selectTable(result.junctionTableId, result.junctionTableName);
2007
- }
2008
- },
2009
- onError: (error) => {
2010
- console.error("Failed to create many-to-many relationship:", error);
2011
- }
2012
- });
2013
- }
2014
- function cn(...inputs) {
2015
- return twMerge(clsx(inputs));
2016
- }
2017
- function getAccessSummary(fields, values) {
2018
- const enabled = fields.filter((f) => values[f.key] === true || values[f.key] === "true");
2019
- if (enabled.length === 0) return "Members";
2020
- const labels = enabled.map((f) => f.label);
2021
- if (labels.length === 1) return `Members who are ${labels[0]}`;
2022
- return `Members who are ${labels.slice(0, -1).join(", ")} or ${labels[labels.length - 1]}`;
2023
- }
2024
- function AccessControlGroup({ fields, values, onChange, disabled }) {
2025
- const summary = getAccessSummary(fields, values);
2026
- return /* @__PURE__ */ jsxs("div", { "data-chat-component": "access-control-group", className: "rounded-lg border", children: [
2027
- /* @__PURE__ */ jsxs("div", { className: "px-4 pt-4 pb-3", children: [
2028
- /* @__PURE__ */ jsx("h4", { className: "text-balance text-sm font-semibold", children: "Who can access this?" }),
2029
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: "Limit access to certain members. Choose which types of members can access." })
2030
- ] }),
2031
- fields.map((field) => {
2032
- const checked = values[field.key] === true || values[field.key] === "true";
2033
- return /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-t px-4 py-3", children: [
2034
- /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1 space-y-0.5", children: [
2035
- /* @__PURE__ */ jsx("p", { className: "text-sm font-medium leading-none", children: field.label }),
2036
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: field.description })
2037
- ] }),
2038
- /* @__PURE__ */ jsx(
2039
- Switch,
2040
- {
2041
- checked,
2042
- onCheckedChange: (v) => onChange(field.key, v),
2043
- disabled
2044
- }
2045
- )
2046
- ] }, field.key);
2047
- }),
2048
- /* @__PURE__ */ jsx("div", { className: "border-t px-4 py-3", children: /* @__PURE__ */ jsxs("p", { className: "text-xs", children: [
2049
- /* @__PURE__ */ jsx("span", { className: "font-semibold", children: "Access:" }),
2050
- " ",
2051
- summary
2052
- ] }) })
2053
- ] });
2054
- }
2055
- function AutoGeneratedFieldsInfo({
2056
- fields,
2057
- value,
2058
- onChange,
2059
- fieldMappings,
2060
- disabled
2061
- }) {
2062
- const [editingField, setEditingField] = useState(null);
2063
- const [editValue, setEditValue] = useState("");
2064
- if (!fields.length) return null;
2065
- const handleStartEdit = (fieldName, currentValue) => {
2066
- setEditingField(fieldName);
2067
- setEditValue(currentValue);
2068
- };
2069
- const handleSave = (fieldName) => {
2070
- const mapping = fieldMappings?.[fieldName];
2071
- if (mapping && onChange && editValue.trim()) {
2072
- onChange(mapping.policyKey, editValue.trim());
2073
- }
2074
- setEditingField(null);
2075
- setEditValue("");
2076
- };
2077
- const handleCancel = () => {
2078
- setEditingField(null);
2079
- setEditValue("");
2080
- };
2081
- const handleKeyDown = (e, fieldName) => {
2082
- if (e.key === "Enter") {
2083
- handleSave(fieldName);
2084
- } else if (e.key === "Escape") {
2085
- handleCancel();
2086
- }
2087
- };
2088
- const getDisplayName = (field) => {
2089
- const mapping = fieldMappings?.[field.name];
2090
- if (mapping && value) {
2091
- const customValue = value[mapping.policyKey];
2092
- if (typeof customValue === "string" && customValue !== mapping.defaultValue) {
2093
- return customValue;
2094
- }
2095
- }
2096
- return field.name;
2097
- };
2098
- const hasFieldMapping = (fieldName) => {
2099
- return !!fieldMappings?.[fieldName] && !!onChange;
2100
- };
2101
- const handleReset = (fieldName) => {
2102
- const mapping = fieldMappings?.[fieldName];
2103
- if (mapping && onChange) {
2104
- onChange(mapping.policyKey, mapping.defaultValue);
2105
- setEditValue(mapping.defaultValue);
2106
- }
2107
- };
2108
- return /* @__PURE__ */ jsxs("div", { className: "border-border/60 overflow-hidden rounded-lg border", children: [
2109
- /* @__PURE__ */ jsxs("div", { className: "bg-muted/50 flex items-center gap-2 border-b px-4 py-2.5", children: [
2110
- /* @__PURE__ */ jsx(Table2, { className: "text-muted-foreground h-4 w-4" }),
2111
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-xs font-medium", children: "The following fields will be auto-generated:" })
2112
- ] }),
2113
- /* @__PURE__ */ jsx("div", { className: "divide-border divide-y", children: fields.map((field) => {
2114
- const displayName = getDisplayName(field);
2115
- const canEdit = hasFieldMapping(field.name);
2116
- const isEditing = editingField === field.name;
2117
- return /* @__PURE__ */ jsxs("div", { className: "space-y-1 px-4 py-3", children: [
2118
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
2119
- isEditing ? /* @__PURE__ */ jsxs(Fragment, { children: [
2120
- /* @__PURE__ */ jsx(
2121
- Input,
2122
- {
2123
- type: "text",
2124
- value: editValue,
2125
- onChange: (e) => setEditValue(e.target.value),
2126
- onKeyDown: (e) => handleKeyDown(e, field.name),
2127
- className: "w-40 text-xs",
2128
- size: "sm",
2129
- autoFocus: true
2130
- }
2131
- ),
2132
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-0.5", children: [
2133
- /* @__PURE__ */ jsxs(Tooltip, { children: [
2134
- /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
2135
- "button",
2136
- {
2137
- type: "button",
2138
- onClick: () => handleSave(field.name),
2139
- "aria-label": `Save ${displayName} field name`,
2140
- className: "hover:bg-muted text-muted-foreground hover:text-foreground grid size-10 place-items-center rounded-lg\n transition-[background-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.96]",
2141
- children: /* @__PURE__ */ jsx(CheckIcon, { className: "h-3.5 w-3.5" })
2142
- }
2143
- ) }),
2144
- /* @__PURE__ */ jsx(TooltipContent, { children: "Save" })
2145
- ] }),
2146
- /* @__PURE__ */ jsxs(Tooltip, { children: [
2147
- /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
2148
- "button",
2149
- {
2150
- type: "button",
2151
- onClick: handleCancel,
2152
- "aria-label": "Cancel field name edit",
2153
- className: "hover:bg-muted text-muted-foreground hover:text-foreground grid size-10 place-items-center rounded-lg\n transition-[background-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.96]",
2154
- children: /* @__PURE__ */ jsx(XIcon, { className: "h-3.5 w-3.5" })
2155
- }
2156
- ) }),
2157
- /* @__PURE__ */ jsx(TooltipContent, { children: "Cancel" })
2158
- ] }),
2159
- /* @__PURE__ */ jsxs(Tooltip, { children: [
2160
- /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
2161
- "button",
2162
- {
2163
- type: "button",
2164
- onClick: () => handleReset(field.name),
2165
- "aria-label": `Reset ${displayName} field name`,
2166
- className: "hover:bg-muted text-muted-foreground hover:text-foreground grid size-10 place-items-center rounded-lg\n transition-[background-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.96]",
2167
- children: /* @__PURE__ */ jsx(RotateCcwIcon, { className: "h-3.5 w-3.5" })
2168
- }
2169
- ) }),
2170
- /* @__PURE__ */ jsx(TooltipContent, { children: "Reset to default" })
2171
- ] })
2172
- ] })
2173
- ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
2174
- /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: displayName }),
2175
- canEdit && /* @__PURE__ */ jsxs(Tooltip, { children: [
2176
- /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
2177
- "button",
2178
- {
2179
- type: "button",
2180
- onClick: () => handleStartEdit(field.name, displayName),
2181
- disabled,
2182
- "aria-label": `Edit ${displayName} field name`,
2183
- className: "hover:bg-muted text-muted-foreground hover:text-foreground grid size-10 place-items-center rounded-lg opacity-60\n transition-[background-color,color,opacity,scale] duration-150 ease-out hover:opacity-100 motion-safe:active:scale-[0.96]\n disabled:cursor-not-allowed disabled:opacity-30\n disabled:hover:bg-transparent",
2184
- children: /* @__PURE__ */ jsx(PencilIcon, { className: "h-3 w-3" })
2185
- }
2186
- ) }),
2187
- /* @__PURE__ */ jsx(TooltipContent, { children: "Edit field name" })
2188
- ] })
2189
- ] }),
2190
- /* @__PURE__ */ jsx("span", { className: "bg-muted text-muted-foreground rounded px-1.5 py-0.5 font-mono text-[10px] font-medium", children: field.type })
2191
- ] }),
2192
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: field.description })
2193
- ] }, field.name);
2194
- }) })
2195
- ] });
2196
- }
2197
- function usePermissions(options = {}) {
2198
- const isEnabled = options.enabled !== false;
2199
- const { scope } = useSchemaBuilderRuntime();
2200
- const { fetchAppPermissionsQuery, fetchOrgPermissionsQuery } = useAdminSdkClient();
2201
- return useQuery({
2202
- queryKey: schemaBuilderQueryKey(scope, "policies", "permissions"),
2203
- queryFn: async () => {
2204
- const [appResult, orgResult] = await Promise.all([
2205
- fetchAppPermissionsQuery({ selection: { fields: { id: true, name: true, bitnum: true, bitstr: true, description: true }, orderBy: ["NAME_ASC"] } }),
2206
- fetchOrgPermissionsQuery({ selection: { fields: { id: true, name: true, bitnum: true, bitstr: true, description: true }, orderBy: ["NAME_ASC"] } })
2207
- ]);
2208
- const appPermissions = (appResult.appPermissions?.nodes ?? []).map((node) => ({
2209
- id: node.id ?? "",
2210
- name: node.name ?? "",
2211
- bitnum: node.bitnum ?? null,
2212
- bitstr: node.bitstr ?? null,
2213
- description: node.description ?? null
2214
- }));
2215
- const membershipPermissions = (orgResult.orgPermissions?.nodes ?? []).map((node) => ({
2216
- id: node.id ?? "",
2217
- name: node.name ?? "",
2218
- bitnum: node.bitnum ?? null,
2219
- bitstr: node.bitstr ?? null,
2220
- description: node.description ?? null
2221
- }));
2222
- return {
2223
- appPermissions,
2224
- membershipPermissions
2225
- };
2226
- },
2227
- enabled: isEnabled,
2228
- staleTime: 5 * 60 * 1e3,
2229
- refetchOnMount: isEnabled,
2230
- refetchOnWindowFocus: false,
2231
- refetchOnReconnect: false
2232
- });
2233
- }
2234
- function normalizeValue(value) {
2235
- if (Array.isArray(value)) return value.map((v) => String(v));
2236
- if (typeof value === "string") return value.trim() ? [value] : [];
2237
- return [];
2238
- }
2239
- function MultiValueFieldEditor({
2240
- value,
2241
- onChange,
2242
- disabled,
2243
- emptyText = "No fields yet",
2244
- addButtonText = "Add field",
2245
- typeBadge
2246
- }) {
2247
- const normalizedValue = useMemo(() => normalizeValue(value), [value]);
2248
- const idsRef = useRef([]);
2249
- const inputRefs = useRef([]);
2250
- const pendingFocusIndex = useRef(null);
2251
- useEffect(() => {
2252
- const nextIds = idsRef.current.slice(0, normalizedValue.length);
2253
- while (nextIds.length < normalizedValue.length) {
2254
- nextIds.push(`mv-${crypto.randomUUID()}`);
2255
- }
2256
- idsRef.current = nextIds;
2257
- }, [normalizedValue.length]);
2258
- useEffect(() => {
2259
- if (pendingFocusIndex.current === null) return;
2260
- const idx = pendingFocusIndex.current;
2261
- const el = inputRefs.current[idx] ?? null;
2262
- if (el) {
2263
- el.focus();
2264
- el.select();
2265
- }
2266
- pendingFocusIndex.current = null;
2267
- }, [normalizedValue.length]);
2268
- const addOption = useCallback(() => {
2269
- pendingFocusIndex.current = normalizedValue.length;
2270
- idsRef.current = [...idsRef.current, `mv-${crypto.randomUUID()}`];
2271
- onChange([...normalizedValue, ""]);
2272
- }, [normalizedValue, onChange]);
2273
- const updateOption = useCallback(
2274
- (index, nextValue) => {
2275
- const next = normalizedValue.slice();
2276
- next[index] = nextValue;
2277
- onChange(next);
2278
- },
2279
- [normalizedValue, onChange]
2280
- );
2281
- const removeOption = useCallback(
2282
- (index) => {
2283
- idsRef.current = idsRef.current.filter((_, i) => i !== index);
2284
- onChange(normalizedValue.filter((_, i) => i !== index));
2285
- },
2286
- [normalizedValue, onChange]
2287
- );
2288
- const insertAfter = useCallback(
2289
- (index) => {
2290
- const next = normalizedValue.slice();
2291
- next.splice(index + 1, 0, "");
2292
- const nextIds = idsRef.current.slice();
2293
- nextIds.splice(index + 1, 0, `mv-${crypto.randomUUID()}`);
2294
- idsRef.current = nextIds;
2295
- pendingFocusIndex.current = index + 1;
2296
- onChange(next);
2297
- },
2298
- [normalizedValue, onChange]
2299
- );
2300
- const rowIds = idsRef.current;
2301
- return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
2302
- /* @__PURE__ */ jsx("div", { className: "space-y-2", children: normalizedValue.length === 0 ? /* @__PURE__ */ jsx("div", { className: "text-muted-foreground rounded-md border border-dashed p-3 text-xs", children: emptyText }) : normalizedValue.map((opt, index) => /* @__PURE__ */ jsxs(
2303
- "div",
2304
- {
2305
- className: "bg-background flex items-center gap-2 rounded-md border px-2 py-1.5",
2306
- children: [
2307
- /* @__PURE__ */ jsx(
2308
- Input,
2309
- {
2310
- ref: (el) => {
2311
- inputRefs.current[index] = el;
2312
- },
2313
- value: opt,
2314
- onChange: (e) => updateOption(index, e.target.value),
2315
- onKeyDown: (e) => {
2316
- if (e.key === "Enter") {
2317
- e.preventDefault();
2318
- insertAfter(index);
2319
- }
2320
- },
2321
- disabled,
2322
- className: "h-8 border-none shadow-none focus-visible:ring-0"
2323
- }
2324
- ),
2325
- typeBadge && /* @__PURE__ */ jsx("span", { className: "text-muted-foreground shrink-0 text-xs", children: typeBadge }),
2326
- /* @__PURE__ */ jsx(
2327
- Button,
2328
- {
2329
- type: "button",
2330
- variant: "ghost",
2331
- size: "sm",
2332
- onClick: () => removeOption(index),
2333
- disabled,
2334
- className: "text-muted-foreground/80 hover:text-destructive h-8 w-8 p-0",
2335
- "aria-label": "Remove field",
2336
- children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
2337
- }
2338
- )
2339
- ]
2340
- },
2341
- rowIds[index] ?? `mv-${index}`
2342
- )) }),
2343
- /* @__PURE__ */ jsx("div", { className: "pt-1", children: /* @__PURE__ */ jsxs(
2344
- Button,
2345
- {
2346
- type: "button",
2347
- variant: "outline",
2348
- size: "sm",
2349
- onClick: addOption,
2350
- disabled,
2351
- className: "h-7 gap-1.5 px-2",
2352
- children: [
2353
- /* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" }),
2354
- addButtonText
2355
- ]
2356
- }
2357
- ) })
2358
- ] });
2359
- }
2360
- var MEMBERSHIP_TYPE_OPTIONS2 = [
2361
- { value: "1", label: "App Member", description: "Check membership to the application" },
2362
- { value: "2", label: "Organization Member", description: "Check membership to an organization" },
2363
- { value: "3", label: "Group Member", description: "Check membership to a group" }
2364
- ];
2365
- var MEMBERSHIP_LABEL_MAP = {
2366
- "1": "App Member",
2367
- "2": "Organization Member",
2368
- "3": "Group Member"
2369
- };
2370
- var normalizeFieldType = (type) => (type ?? "").toLowerCase();
2371
- var isUuidType = (type) => {
2372
- const t = normalizeFieldType(type);
2373
- return (t === "uuid" || t === "uuid!") && !t.includes("[");
2374
- };
2375
- var isUuidArrayType = (type) => {
2376
- const t = normalizeFieldType(type);
2377
- return t === "uuid[]" || t === "uuid[]!" || t.startsWith("uuid[");
2378
- };
2379
- function getFieldsFromTable(tables, tableName) {
2380
- const table = tables.find((t) => t.name === tableName);
2381
- return table?.fields?.slice().sort((a, b) => (a.fieldOrder ?? 0) - (b.fieldOrder ?? 0)).map((f) => ({ name: f.name, type: f.type ?? null })) ?? [];
2382
- }
2383
- function TableSelectField({
2384
- field,
2385
- value,
2386
- onChange,
2387
- disabled,
2388
- tables
2389
- }) {
2390
- const tableOptions = useMemo(
2391
- () => tables.filter((t) => t.category === "APP").map((t) => ({ label: t.name, value: t.id })),
2392
- [tables]
2393
- );
2394
- const selectedTable = tables.find((t) => t.name === value);
2395
- const selectedOption = tableOptions.find((o) => o.value === selectedTable?.id) ?? null;
2396
- return /* @__PURE__ */ jsxs(
2397
- Combobox,
2398
- {
2399
- items: tableOptions,
2400
- value: selectedOption,
2401
- onValueChange: (next) => {
2402
- if (next) {
2403
- const table = tables.find((t) => t.id === next.value);
2404
- if (table) onChange(table.name);
2405
- }
2406
- },
2407
- children: [
2408
- /* @__PURE__ */ jsx(ComboboxInput, { placeholder: field.placeholder ?? "Search tables...", showClear: false }),
2409
- /* @__PURE__ */ jsxs(ComboboxPopup, { children: [
2410
- /* @__PURE__ */ jsx(ComboboxEmpty, { children: "No tables found" }),
2411
- /* @__PURE__ */ jsx(ComboboxList, { className: "scrollbar-neutral-thin max-h-[180px] overflow-y-auto", children: (table) => /* @__PURE__ */ jsx(ComboboxItem, { value: table, children: /* @__PURE__ */ jsx("span", { className: "truncate", children: table.label }) }, table.value) })
2412
- ] })
2413
- ]
2414
- }
2415
- );
2416
- }
2417
- function expectsUuidArray(key) {
2418
- return key === "owned_table_key";
2419
- }
2420
- function expectsUuid(key) {
2421
- return key.includes("_key") || key.includes("_ref_key");
2422
- }
2423
- function DependentFieldSelectField({
2424
- field,
2425
- value,
2426
- onChange,
2427
- disabled,
2428
- tables,
2429
- formData
2430
- }) {
2431
- const dependentTableName = field.dependsOn ? formData[field.dependsOn] : "";
2432
- const isUuidArrayField = expectsUuidArray(field.key);
2433
- const isUuidField = expectsUuid(field.key) && !isUuidArrayField;
2434
- const hasTypeFilter = isUuidField || isUuidArrayField;
2435
- const { fieldOptions, allFieldCount } = useMemo(() => {
2436
- if (!dependentTableName) return { fieldOptions: [], allFieldCount: 0 };
2437
- const allFields = getFieldsFromTable(tables, dependentTableName);
2438
- let filtered = allFields;
2439
- if (isUuidArrayField) {
2440
- filtered = allFields.filter((f) => isUuidArrayType(f.type));
2441
- } else if (isUuidField) {
2442
- filtered = allFields.filter((f) => isUuidType(f.type));
2443
- }
2444
- return { fieldOptions: filtered, allFieldCount: allFields.length };
2445
- }, [dependentTableName, tables, field.key, isUuidArrayField, isUuidField]);
2446
- const isDisabled = disabled || !dependentTableName;
2447
- const placeholder = !dependentTableName ? "Select table first" : field.placeholder ?? "Select field";
2448
- const typeLabel = isUuidArrayField ? "UUID array" : "UUID";
2449
- const hasHiddenFields = hasTypeFilter && allFieldCount > fieldOptions.length;
2450
- return /* @__PURE__ */ jsxs(Select, { value: value || "", onValueChange: onChange, disabled: isDisabled, children: [
2451
- /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder }) }),
2452
- /* @__PURE__ */ jsx(SelectContent, { className: "max-h-48", children: !dependentTableName ? /* @__PURE__ */ jsx("div", { className: "text-muted-foreground py-4 text-center text-xs", children: "Select a table first" }) : fieldOptions.length === 0 ? /* @__PURE__ */ jsx("div", { className: "text-muted-foreground py-4 text-center text-xs", children: hasTypeFilter ? `No ${typeLabel} fields on "${dependentTableName}"` : "No fields available" }) : /* @__PURE__ */ jsxs(Fragment, { children: [
2453
- fieldOptions.map((f) => /* @__PURE__ */ jsx(SelectFieldItem, { value: f.name, name: f.name, type: f.type ?? void 0 }, f.name)),
2454
- hasHiddenFields && /* @__PURE__ */ jsxs("div", { className: "text-muted-foreground flex items-center gap-1.5 border-t px-2 py-1.5 text-xs", children: [
2455
- /* @__PURE__ */ jsx(Info, { className: "h-3 w-3 shrink-0" }),
2456
- /* @__PURE__ */ jsxs("span", { children: [
2457
- "Non-",
2458
- typeLabel,
2459
- " fields are hidden"
2460
- ] })
2461
- ] })
2462
- ] }) })
2463
- ] });
2464
- }
2465
- function PermissionSelectField({
2466
- field,
2467
- value,
2468
- onChange,
2469
- disabled,
2470
- formData
2471
- }) {
2472
- const { data: permissions, isLoading } = usePermissions();
2473
- const membershipType = formData?.membership_type;
2474
- const isAppLevel = membershipType === MEMBERSHIP_TYPES2.APP;
2475
- const permissionsList = isAppLevel ? permissions?.appPermissions || [] : permissions?.membershipPermissions || [];
2476
- return /* @__PURE__ */ jsxs(Select, { value: value || "", onValueChange: (v) => onChange(v || void 0), disabled, children: [
2477
- /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(
2478
- SelectValue,
2479
- {
2480
- placeholder: isLoading ? "Loading..." : `Select ${isAppLevel ? "app" : "membership"} permission`
2481
- }
2482
- ) }),
2483
- /* @__PURE__ */ jsx(SelectContent, { className: "max-h-48", children: permissionsList.filter((p) => p.name).map((permission) => /* @__PURE__ */ jsx(
2484
- SelectRichItem,
2485
- {
2486
- value: permission.name,
2487
- label: permission.name ?? void 0,
2488
- description: permission.description
2489
- },
2490
- permission.id
2491
- )) })
2492
- ] });
2493
- }
2494
- function DynamicFormField({ field, value, onChange, disabled, tables, formData }) {
2495
- const hasTables = tables && tables.length > 0;
2496
- const renderField = () => {
2497
- switch (field.type) {
2498
- case "table-select":
2499
- if (hasTables) {
2500
- return /* @__PURE__ */ jsx(
2501
- TableSelectField,
2502
- {
2503
- field,
2504
- value: value ?? "",
2505
- onChange,
2506
- disabled,
2507
- tables
2508
- }
2509
- );
2510
- }
2511
- return /* @__PURE__ */ jsx(
2512
- Input,
2513
- {
2514
- type: "text",
2515
- value: value ?? "",
2516
- onChange: (e) => onChange(e.target.value),
2517
- placeholder: field.placeholder,
2518
- disabled
2519
- }
2520
- );
2521
- case "field-select":
2522
- if (field.dependsOn && hasTables && formData) {
2523
- return /* @__PURE__ */ jsx(
2524
- DependentFieldSelectField,
2525
- {
2526
- field,
2527
- value: value ?? "",
2528
- onChange,
2529
- disabled,
2530
- tables,
2531
- formData
2532
- }
2533
- );
2534
- }
2535
- return /* @__PURE__ */ jsx(
2536
- Input,
2537
- {
2538
- type: "text",
2539
- value: value ?? "",
2540
- onChange: (e) => onChange(e.target.value),
2541
- placeholder: field.placeholder,
2542
- disabled
2543
- }
2544
- );
2545
- case "field-multi-select":
2546
- return /* @__PURE__ */ jsx(
2547
- MultiValueFieldEditor,
2548
- {
2549
- value,
2550
- onChange,
2551
- disabled,
2552
- emptyText: "No fields added yet",
2553
- addButtonText: "Add field",
2554
- typeBadge: field.pgType
2555
- }
2556
- );
2557
- case "membership-type-select":
2558
- return /* @__PURE__ */ jsxs(
2559
- Select,
2560
- {
2561
- value: value !== null && value !== void 0 ? String(value) : "",
2562
- onValueChange: (v) => onChange(parseInt(v, 10)),
2563
- disabled,
2564
- children: [
2565
- /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Select scope", children: value !== null && value !== void 0 ? MEMBERSHIP_LABEL_MAP[String(value)] ?? String(value) : void 0 }) }),
2566
- /* @__PURE__ */ jsx(SelectContent, { children: MEMBERSHIP_TYPE_OPTIONS2.map((opt) => /* @__PURE__ */ jsx(SelectRichItem, { value: opt.value, label: opt.label, description: opt.description }, opt.value)) })
2567
- ]
2568
- }
2569
- );
2570
- case "permission-select":
2571
- return /* @__PURE__ */ jsx(
2572
- PermissionSelectField,
2573
- {
2574
- field,
2575
- value: value ?? void 0,
2576
- onChange,
2577
- disabled,
2578
- formData
2579
- }
2580
- );
2581
- case "boolean":
2582
- return null;
2583
- // Rendered inline in the wrapper below
2584
- case "number":
2585
- return /* @__PURE__ */ jsx(
2586
- Input,
2587
- {
2588
- type: "number",
2589
- value: value !== null && value !== void 0 ? String(value) : "",
2590
- onChange: (e) => onChange(e.target.value ? parseInt(e.target.value, 10) : null),
2591
- placeholder: field.placeholder,
2592
- disabled
2593
- }
2594
- );
2595
- case "text":
2596
- default:
2597
- if (field.options) {
2598
- const selectedLabel = field.options.find((o) => o.value === value)?.label;
2599
- return /* @__PURE__ */ jsxs(Select, { value: value ?? "", onValueChange: onChange, disabled, children: [
2600
- /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: field.placeholder ?? "Select...", children: selectedLabel }) }),
2601
- /* @__PURE__ */ jsx(SelectContent, { children: field.options.map((opt) => /* @__PURE__ */ jsx(SelectRichItem, { value: opt.value, label: opt.label, description: opt.description }, opt.value)) })
2602
- ] });
2603
- }
2604
- return /* @__PURE__ */ jsx(
2605
- Input,
2606
- {
2607
- type: "text",
2608
- value: value ?? "",
2609
- onChange: (e) => onChange(e.target.value),
2610
- placeholder: field.placeholder,
2611
- disabled
2612
- }
2613
- );
2614
- }
2615
- };
2616
- if (field.type === "boolean") {
2617
- return /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between rounded-lg border px-4 py-3 pt-2.5", children: [
2618
- /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
2619
- /* @__PURE__ */ jsxs(Label, { className: "inline-flex items-center text-sm font-medium", children: [
2620
- field.label,
2621
- !field.required && /* @__PURE__ */ jsx("span", { className: "text-muted-foreground ml-1 text-xs font-normal", children: "(optional)" })
2622
- ] }),
2623
- field.description && /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: field.description })
2624
- ] }),
2625
- /* @__PURE__ */ jsx(Switch, { checked: value === true || value === "true", onCheckedChange: (v) => onChange(v), disabled })
2626
- ] });
2627
- }
2628
- return /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
2629
- /* @__PURE__ */ jsxs(Label, { className: "inline-flex items-center", children: [
2630
- field.label,
2631
- !field.required && /* @__PURE__ */ jsx("span", { className: "text-muted-foreground ml-1 text-xs font-normal", children: "(optional)" })
2632
- ] }),
2633
- field.description && /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs mb-2", children: field.description }),
2634
- renderField()
2635
- ] });
2636
- }
2637
- var ACCESS_CONTROL_KEYS = /* @__PURE__ */ new Set(["is_admin", "is_owner"]);
2638
- function PolicyConfigForm({
2639
- policyType,
2640
- value,
2641
- onChange,
2642
- disabled,
2643
- hideAutoGeneratedInfo
2644
- }) {
2645
- const { mainFields: allMainFields, advancedFields: allAdvancedFields } = useFormSchema(policyType);
2646
- const { currentDatabase } = useSchemaBuilderSelectors();
2647
- const databaseId = currentDatabase?.databaseId ?? "";
2648
- const { data: tables = [] } = useDatabasePolicies(databaseId, { enabled: Boolean(databaseId) });
2649
- const allFields = useMemo(() => [...allMainFields, ...allAdvancedFields], [allMainFields, allAdvancedFields]);
2650
- const handleFieldChange = (key, fieldValue) => {
2651
- const updates = { [key]: fieldValue };
2652
- for (const f of allFields) {
2653
- if (f.dependsOn === key) {
2654
- updates[f.key] = f.type === "field-multi-select" ? [] : "";
2655
- }
2656
- }
2657
- onChange({ ...value, ...updates });
2658
- };
2659
- const fieldMappings = useMemo(() => getGeneratedFieldMappings(policyType), [policyType]);
2660
- const inlineEditedKeys = useMemo(() => {
2661
- if (!fieldMappings) return /* @__PURE__ */ new Set();
2662
- return new Set(Object.values(fieldMappings).map((m) => m.policyKey));
2663
- }, [fieldMappings]);
2664
- const filteredFields = useMemo(() => {
2665
- if (hideAutoGeneratedInfo) return allFields;
2666
- return allFields.filter((field) => !inlineEditedKeys.has(field.key));
2667
- }, [allFields, inlineEditedKeys, hideAutoGeneratedInfo]);
2668
- const accessControlFields = useMemo(
2669
- () => filteredFields.filter((f) => ACCESS_CONTROL_KEYS.has(f.key)),
2670
- [filteredFields]
2671
- );
2672
- const regularFields = useMemo(
2673
- () => filteredFields.filter((f) => !ACCESS_CONTROL_KEYS.has(f.key)),
2674
- [filteredFields]
2675
- );
2676
- const hasNoConfig = filteredFields.length === 0 && policyType.generatedFields.length === 0 && inlineEditedKeys.size === 0;
2677
- return /* @__PURE__ */ jsxs("div", { "data-chat-component": "policy-config-form", "data-chat-policy-type": policyType.name, className: "space-y-4", children: [
2678
- !hideAutoGeneratedInfo && /* @__PURE__ */ jsx(
2679
- AutoGeneratedFieldsInfo,
2680
- {
2681
- fields: policyType.generatedFields,
2682
- value,
2683
- onChange: handleFieldChange,
2684
- fieldMappings,
2685
- disabled
2686
- }
2687
- ),
2688
- regularFields.length > 0 && /* @__PURE__ */ jsx("div", { className: "space-y-4", children: regularFields.map((field) => /* @__PURE__ */ jsx(
2689
- DynamicFormField,
2690
- {
2691
- field,
2692
- value: value[field.key],
2693
- onChange: (v) => handleFieldChange(field.key, v),
2694
- disabled,
2695
- tables,
2696
- formData: value
2697
- },
2698
- field.key
2699
- )) }),
2700
- accessControlFields.length > 0 && /* @__PURE__ */ jsx(
2701
- AccessControlGroup,
2702
- {
2703
- fields: accessControlFields,
2704
- values: value,
2705
- onChange: handleFieldChange,
2706
- disabled
2707
- }
2708
- ),
2709
- hasNoConfig && /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-sm italic", children: "This policy type requires no configuration." })
2710
- ] });
2711
- }
2712
- var MD_RADIUS = 28;
2713
- var SM_RADIUS = 24;
2714
- var MD_ICON_SIZE = 24;
2715
- var SM_ICON_SIZE = 20;
2716
- var FONT_FAMILY = "'Inter', system-ui, sans-serif";
2717
- var LABEL_FONT_SIZE = 12;
2718
- var TOP_LABEL_FONT_SIZE = 10;
2719
- var NODE_TOTAL_HEIGHT = 76;
2720
- var CENTER_Y = 28;
2721
- var LABEL_Y = NODE_TOTAL_HEIGHT - 6;
2722
- var DiagramModeCtx = createContext("light");
2723
- DiagramModeCtx.Provider;
2724
- function SvgIcon({ x, y, size, color, icon }) {
2725
- const scale = size / 24;
2726
- const tx = x - size / 2;
2727
- const ty = y - size / 2;
2728
- return /* @__PURE__ */ jsx("g", { transform: `translate(${tx},${ty}) scale(${scale})`, fill: "none", stroke: color, strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: icon.elements.map((el, i) => {
2729
- if (el.tag === "path") return /* @__PURE__ */ jsx("path", { d: el.attrs.d }, i);
2730
- if (el.tag === "circle") return /* @__PURE__ */ jsx("circle", { cx: el.attrs.cx, cy: el.attrs.cy, r: el.attrs.r }, i);
2731
- if (el.tag === "ellipse")
2732
- return /* @__PURE__ */ jsx("ellipse", { cx: el.attrs.cx, cy: el.attrs.cy, rx: el.attrs.rx, ry: el.attrs.ry }, i);
2733
- return null;
2734
- }) });
2735
- }
2736
- function SvgDiagramNode({ x, icon, label, theme, size = "md", stacked, outlined }) {
2737
- const r = size === "sm" ? SM_RADIUS : MD_RADIUS;
2738
- const iconSize = size === "sm" ? SM_ICON_SIZE : MD_ICON_SIZE;
2739
- const cy = CENTER_Y;
2740
- const bg = outlined ? theme.bg : theme.fill;
2741
- return /* @__PURE__ */ jsxs("g", { children: [
2742
- stacked && /* @__PURE__ */ jsxs(Fragment, { children: [
2743
- /* @__PURE__ */ jsx("circle", { cx: x - 8, cy: cy - 6, r, fill: theme.bg, stroke: theme.border, strokeWidth: "2" }),
2744
- /* @__PURE__ */ jsx("circle", { cx: x - 4, cy: cy - 3, r, fill: theme.bg, stroke: theme.border, strokeWidth: "2" })
2745
- ] }),
2746
- /* @__PURE__ */ jsx("circle", { cx: x, cy, r, fill: bg, stroke: theme.border, strokeWidth: "2" }),
2747
- /* @__PURE__ */ jsx(SvgIcon, { x, y: cy, size: iconSize, color: theme.primary, icon }),
2748
- /* @__PURE__ */ jsx("text", { x, y: LABEL_Y, textAnchor: "middle", fontSize: LABEL_FONT_SIZE, fill: theme.text, style: { fontFamily: FONT_FAMILY }, children: label })
2749
- ] });
2750
- }
2751
- function nodeWidth(size = "md", stacked) {
2752
- const r = size === "sm" ? SM_RADIUS : MD_RADIUS;
2753
- const diameter = r * 2;
2754
- return stacked ? diameter + 8 : diameter;
2755
- }
2756
- function SvgConnector({ x, width, theme, topLabel, topLabelFilled, dashed }) {
2757
- const cy = CENTER_Y;
2758
- const dotR = 4;
2759
- return /* @__PURE__ */ jsxs("g", { children: [
2760
- /* @__PURE__ */ jsx("circle", { cx: x + 6, cy, r: dotR, fill: theme.connector }),
2761
- /* @__PURE__ */ jsx(
2762
- "line",
2763
- {
2764
- x1: x + 10,
2765
- y1: cy,
2766
- x2: x + width - 10,
2767
- y2: cy,
2768
- stroke: theme.connectorLight,
2769
- strokeWidth: "2.5",
2770
- strokeLinecap: "round",
2771
- ...dashed ? { strokeDasharray: "4 3" } : {}
2772
- }
2773
- ),
2774
- /* @__PURE__ */ jsx("circle", { cx: x + width - 6, cy, r: dotR, fill: theme.connector }),
2775
- topLabel && /* @__PURE__ */ jsx(
2776
- SvgTopLabel,
2777
- {
2778
- cx: x + width / 2,
2779
- y: 4,
2780
- label: topLabel,
2781
- filled: topLabelFilled,
2782
- theme
2783
- }
2784
- )
2785
- ] });
2786
- }
2787
- function SvgFanConnector({ x, theme, topLabel, topLabelFilled }) {
2788
- const flatWidth = topLabel ? Math.max(24, topLabelBoxWidth(topLabel) + 4) : 24;
2789
- const fanStartX = x + flatWidth + 4;
2790
- const fanMidX = fanStartX + 3;
2791
- const totalWidth = flatWidth + 36;
2792
- const fanTipX = x + totalWidth - 6;
2793
- const cy = CENTER_Y;
2794
- const fanSpread = 14;
2795
- const startDotCx = x + 6;
2796
- const endDots = [
2797
- { cx: fanTipX, cy: cy - fanSpread },
2798
- { cx: fanTipX, cy },
2799
- { cx: fanTipX, cy: cy + fanSpread }
2800
- ];
2801
- return /* @__PURE__ */ jsxs("g", { children: [
2802
- /* @__PURE__ */ jsx("line", { x1: startDotCx, y1: cy, x2: fanMidX, y2: cy, stroke: theme.connectorLight, strokeWidth: "2.5", strokeLinecap: "round" }),
2803
- endDots.map((dot, i) => /* @__PURE__ */ jsx("line", { x1: fanMidX, y1: cy, x2: dot.cx, y2: dot.cy, stroke: theme.connector, strokeWidth: "2", strokeLinecap: "round" }, i)),
2804
- /* @__PURE__ */ jsx("circle", { cx: startDotCx, cy, r: 4, fill: theme.connector }),
2805
- /* @__PURE__ */ jsx("circle", { cx: fanMidX, cy, r: 3, fill: theme.connector }),
2806
- endDots.map((dot, i) => /* @__PURE__ */ jsx("circle", { cx: dot.cx, cy: dot.cy, r: 3, fill: theme.connector }, i)),
2807
- topLabel && /* @__PURE__ */ jsx(
2808
- SvgTopLabel,
2809
- {
2810
- cx: x + (flatWidth + 6) / 2,
2811
- y: 4,
2812
- label: topLabel,
2813
- filled: topLabelFilled,
2814
- theme
2815
- }
2816
- )
2817
- ] });
2818
- }
2819
- function fanConnectorWidth(topLabel) {
2820
- const flatWidth = topLabel ? Math.max(24, topLabelBoxWidth(topLabel) + 4) : 24;
2821
- return flatWidth + 36;
2822
- }
2823
- function connectorWidthForLabel(label, minWidth = 40) {
2824
- if (!label) return minWidth;
2825
- const boxW = topLabelBoxWidth(label);
2826
- return Math.max(minWidth, boxW + 16);
2827
- }
2828
- var TOP_LABEL_MAX_CHARS = 12;
2829
- var TOP_LABEL_CHAR_WIDTH = 5.5;
2830
- var TOP_LABEL_PAD_X = 6;
2831
- function truncateLabel(label, maxChars = TOP_LABEL_MAX_CHARS) {
2832
- return label.length > maxChars ? label.slice(0, maxChars - 1) + "\u2026" : label;
2833
- }
2834
- function topLabelBoxWidth(label) {
2835
- const display = truncateLabel(label);
2836
- return display.length * TOP_LABEL_CHAR_WIDTH + TOP_LABEL_PAD_X * 2;
2837
- }
2838
- function SvgTopLabel({ cx, y, label, filled, theme }) {
2839
- const display = truncateLabel(label);
2840
- const padY = 3;
2841
- const textWidth = display.length * TOP_LABEL_CHAR_WIDTH;
2842
- const rectW = textWidth + TOP_LABEL_PAD_X * 2;
2843
- const rectH = TOP_LABEL_FONT_SIZE + padY * 2;
2844
- const rx = cx - rectW / 2;
2845
- return /* @__PURE__ */ jsxs("g", { children: [
2846
- /* @__PURE__ */ jsx(
2847
- "rect",
2848
- {
2849
- x: rx,
2850
- y,
2851
- width: rectW,
2852
- height: rectH,
2853
- rx: 3,
2854
- fill: filled ? theme.fill : theme.bg,
2855
- stroke: filled ? theme.primary : theme.border,
2856
- strokeWidth: "1",
2857
- ...!filled ? { strokeDasharray: "3 2" } : {}
2858
- }
2859
- ),
2860
- /* @__PURE__ */ jsx(
2861
- "text",
2862
- {
2863
- x: cx,
2864
- y: y + rectH / 2 + TOP_LABEL_FONT_SIZE * 0.35,
2865
- textAnchor: "middle",
2866
- fontSize: TOP_LABEL_FONT_SIZE,
2867
- fontWeight: "500",
2868
- fill: theme.primary,
2869
- style: { fontFamily: FONT_FAMILY },
2870
- children: display
2871
- }
2872
- )
2873
- ] });
2874
- }
2875
-
2876
- // src/schema/schema-builder-core/components/policies/policy-diagram/svg-icons.ts
2877
- var DATABASE_ICON = {
2878
- elements: [
2879
- { tag: "ellipse", attrs: { cx: 12, cy: 5, rx: 9, ry: 3 } },
2880
- { tag: "path", attrs: { d: "M3 5V19A9 3 0 0 0 21 19V5" } },
2881
- { tag: "path", attrs: { d: "M3 12A9 3 0 0 0 21 12" } }
2882
- ]
2883
- };
2884
- var TABLE2_ICON = {
2885
- elements: [
2886
- {
2887
- tag: "path",
2888
- attrs: {
2889
- d: "M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18"
2890
- }
2891
- }
2892
- ]
2893
- };
2894
-
2895
- // src/schema/schema-builder-relationships/components/table-editor/relationships/relationship-diagram-themes.ts
2896
- var AMBIENT_LIGHT = { bg: "#ffffff", text: "#4B5563", muted: "#9CA3AF" };
2897
- var AMBIENT_DARK = { bg: "#1e293b", text: "#D1D5DB", muted: "#6B7280" };
2898
- var RELATIONSHIP_THEMES = {
2899
- "one-to-one": {
2900
- light: { primary: "#A855F7", fill: "#F3E8FF", border: "#D8B4FE", connector: "#A855F7", connectorLight: "#E9D5FF", ...AMBIENT_LIGHT },
2901
- dark: { primary: "#C084FC", fill: "#3B0764", border: "#7E22CE", connector: "#C084FC", connectorLight: "#9333EA", ...AMBIENT_DARK }
2902
- },
2903
- "belongs-to": {
2904
- light: { primary: "#22C55E", fill: "#F0FDF4", border: "#86EFAC", connector: "#22C55E", connectorLight: "#BBF7D0", ...AMBIENT_LIGHT },
2905
- dark: { primary: "#4ADE80", fill: "#052E16", border: "#166534", connector: "#4ADE80", connectorLight: "#15803D", ...AMBIENT_DARK }
2906
- },
2907
- "one-to-many": {
2908
- light: { primary: "#3B82F6", fill: "#DBEAFE", border: "#93C5FD", connector: "#3B82F6", connectorLight: "#BFDBFE", ...AMBIENT_LIGHT },
2909
- dark: { primary: "#60A5FA", fill: "#172554", border: "#1E40AF", connector: "#60A5FA", connectorLight: "#2563EB", ...AMBIENT_DARK }
2910
- },
2911
- "many-to-many": {
2912
- light: { primary: "#F59E0B", fill: "#FEF3C7", border: "#FCD34D", connector: "#F59E0B", connectorLight: "#FDE68A", ...AMBIENT_LIGHT },
2913
- dark: { primary: "#FBBF24", fill: "#451A03", border: "#92400E", connector: "#FBBF24", connectorLight: "#B45309", ...AMBIENT_DARK }
2914
- }
2915
- };
2916
- function getRelationshipTheme(type, mode = "light") {
2917
- return RELATIONSHIP_THEMES[type][mode];
2918
- }
2919
- var GAP = 8;
2920
- var FAN_MARGIN_RIGHT = 4;
2921
- var PAD = 12;
2922
- function layoutHorizontal(widths) {
2923
- let x = 0;
2924
- const centers = [];
2925
- for (let i = 0; i < widths.length; i++) {
2926
- if (i > 0) x += GAP;
2927
- centers.push(x + widths[i] / 2);
2928
- x += widths[i];
2929
- }
2930
- return { totalWidth: x, centers };
2931
- }
2932
- function svgProps(w, h = NODE_TOTAL_HEIGHT) {
2933
- return {
2934
- width: w + PAD * 2,
2935
- height: h + PAD * 2,
2936
- viewBox: `${-PAD} ${-PAD} ${w + PAD * 2} ${h + PAD * 2}`,
2937
- fill: "none"
2938
- };
2939
- }
2940
- function fanLeftX(center, topLabel) {
2941
- const w = fanConnectorWidth(topLabel);
2942
- return center - w / 2;
2943
- }
2944
- function useMode() {
2945
- const { colorMode: resolvedTheme } = useSchemaBuilderRuntime();
2946
- return resolvedTheme === "dark" ? "dark" : "light";
2947
- }
2948
- function OneToOneDiagram({ sourceTable, targetTable, fieldName }) {
2949
- const mode = useMode();
2950
- const theme = getRelationshipTheme("one-to-one", mode);
2951
- const connW = connectorWidthForLabel(fieldName, 60);
2952
- const widths = [nodeWidth("md"), connW, nodeWidth("md")];
2953
- const { totalWidth, centers } = layoutHorizontal(widths);
2954
- return /* @__PURE__ */ jsxs("svg", { ...svgProps(totalWidth), children: [
2955
- /* @__PURE__ */ jsx(SvgDiagramNode, { x: centers[0], icon: TABLE2_ICON, label: sourceTable, theme }),
2956
- /* @__PURE__ */ jsx(
2957
- SvgConnector,
2958
- {
2959
- x: centers[1] - connW / 2,
2960
- width: connW,
2961
- theme,
2962
- topLabel: fieldName,
2963
- topLabelFilled: fieldName !== "fk"
2964
- }
2965
- ),
2966
- /* @__PURE__ */ jsx(SvgDiagramNode, { x: centers[2], icon: TABLE2_ICON, label: targetTable, theme })
2967
- ] });
2968
- }
2969
- function SvgFanConnectorReversed({
2970
- x,
2971
- theme,
2972
- topLabel,
2973
- topLabelFilled
2974
- }) {
2975
- const flatWidth = topLabel ? Math.max(24, topLabelBoxWidth(topLabel) + 4) : 24;
2976
- const totalWidth = flatWidth + 36;
2977
- const cy = CENTER_Y;
2978
- const fanSpread = 14;
2979
- const fanTipX = x + 6;
2980
- const fanMidX = x + totalWidth - flatWidth - 7;
2981
- const endDotCx = x + totalWidth - 6;
2982
- const startDots = [
2983
- { cx: fanTipX, cy: cy - fanSpread },
2984
- { cx: fanTipX, cy },
2985
- { cx: fanTipX, cy: cy + fanSpread }
2986
- ];
2987
- return /* @__PURE__ */ jsxs("g", { children: [
2988
- startDots.map((dot, i) => /* @__PURE__ */ jsx("line", { x1: dot.cx, y1: dot.cy, x2: fanMidX, y2: cy, stroke: theme.connector, strokeWidth: "2", strokeLinecap: "round" }, i)),
2989
- /* @__PURE__ */ jsx("line", { x1: fanMidX, y1: cy, x2: endDotCx, y2: cy, stroke: theme.connectorLight, strokeWidth: "2.5", strokeLinecap: "round" }),
2990
- startDots.map((dot, i) => /* @__PURE__ */ jsx("circle", { cx: dot.cx, cy: dot.cy, r: 3, fill: theme.connector }, i)),
2991
- /* @__PURE__ */ jsx("circle", { cx: fanMidX, cy, r: 3, fill: theme.connector }),
2992
- /* @__PURE__ */ jsx("circle", { cx: endDotCx, cy, r: 4, fill: theme.connector }),
2993
- topLabel && /* @__PURE__ */ jsx(
2994
- SvgTopLabel,
2995
- {
2996
- cx: fanMidX + (endDotCx - fanMidX) / 2,
2997
- y: 4,
2998
- label: topLabel,
2999
- filled: topLabelFilled,
3000
- theme
3001
- }
3002
- )
3003
- ] });
3004
- }
3005
- function BelongsToDiagram({ sourceTable, targetTable, fieldName }) {
3006
- const mode = useMode();
3007
- const theme = getRelationshipTheme("belongs-to", mode);
3008
- const fanW = fanConnectorWidth(fieldName);
3009
- const widths = [nodeWidth("md", true), FAN_MARGIN_RIGHT + fanW, nodeWidth("md")];
3010
- const { totalWidth, centers } = layoutHorizontal(widths);
3011
- return /* @__PURE__ */ jsxs("svg", { ...svgProps(totalWidth), children: [
3012
- /* @__PURE__ */ jsx(SvgDiagramNode, { x: centers[0], icon: DATABASE_ICON, label: sourceTable, theme, stacked: true, outlined: true }),
3013
- /* @__PURE__ */ jsx(
3014
- SvgFanConnectorReversed,
3015
- {
3016
- x: fanLeftX(centers[1], fieldName),
3017
- theme,
3018
- topLabel: fieldName,
3019
- topLabelFilled: fieldName !== "fk"
3020
- }
3021
- ),
3022
- /* @__PURE__ */ jsx(SvgDiagramNode, { x: centers[2], icon: TABLE2_ICON, label: targetTable, theme })
3023
- ] });
3024
- }
3025
- function OneToManyDiagram({ sourceTable, targetTable, fieldName }) {
3026
- const mode = useMode();
3027
- const theme = getRelationshipTheme("one-to-many", mode);
3028
- const fanW = fanConnectorWidth(fieldName);
3029
- const widths = [nodeWidth("md"), fanW + FAN_MARGIN_RIGHT, nodeWidth("md", true)];
3030
- const { totalWidth, centers } = layoutHorizontal(widths);
3031
- return /* @__PURE__ */ jsxs("svg", { ...svgProps(totalWidth), children: [
3032
- /* @__PURE__ */ jsx(SvgDiagramNode, { x: centers[0], icon: TABLE2_ICON, label: sourceTable, theme }),
3033
- /* @__PURE__ */ jsx(
3034
- SvgFanConnector,
3035
- {
3036
- x: fanLeftX(centers[1], fieldName),
3037
- theme,
3038
- topLabel: fieldName,
3039
- topLabelFilled: fieldName !== "fk"
3040
- }
3041
- ),
3042
- /* @__PURE__ */ jsx(SvgDiagramNode, { x: centers[2], icon: DATABASE_ICON, label: targetTable, theme, stacked: true, outlined: true })
3043
- ] });
3044
- }
3045
- function ManyToManyDiagram({ sourceTable, targetTable, junctionTable, sourceFkName, targetFkName }) {
3046
- const mode = useMode();
3047
- const theme = getRelationshipTheme("many-to-many", mode);
3048
- const srcFk = sourceFkName || `${sourceTable}_id`;
3049
- const tgtFk = targetFkName || `${targetTable}_id`;
3050
- const srcFanW = fanConnectorWidth(srcFk);
3051
- const tgtFanW = fanConnectorWidth(tgtFk);
3052
- const widths = [nodeWidth("sm"), srcFanW + FAN_MARGIN_RIGHT, nodeWidth("sm"), FAN_MARGIN_RIGHT + tgtFanW, nodeWidth("sm")];
3053
- const { totalWidth, centers } = layoutHorizontal(widths);
3054
- return /* @__PURE__ */ jsxs("svg", { ...svgProps(totalWidth), children: [
3055
- /* @__PURE__ */ jsx(SvgDiagramNode, { x: centers[0], icon: TABLE2_ICON, label: sourceTable, theme, size: "sm" }),
3056
- /* @__PURE__ */ jsx(
3057
- SvgFanConnectorReversed,
3058
- {
3059
- x: fanLeftX(centers[1], srcFk),
3060
- theme,
3061
- topLabel: srcFk,
3062
- topLabelFilled: true
3063
- }
3064
- ),
3065
- /* @__PURE__ */ jsx(SvgDiagramNode, { x: centers[2], icon: DATABASE_ICON, label: junctionTable, theme, size: "sm" }),
3066
- /* @__PURE__ */ jsx(
3067
- SvgFanConnector,
3068
- {
3069
- x: fanLeftX(centers[3], tgtFk),
3070
- theme,
3071
- topLabel: tgtFk,
3072
- topLabelFilled: true
3073
- }
3074
- ),
3075
- /* @__PURE__ */ jsx(SvgDiagramNode, { x: centers[4], icon: TABLE2_ICON, label: targetTable, theme, size: "sm" })
3076
- ] });
3077
- }
3078
- function RelationshipDiagram({
3079
- type,
3080
- sourceTable,
3081
- targetTable,
3082
- fieldName = "fk",
3083
- junctionTable = "junction",
3084
- sourceFkName,
3085
- targetFkName,
3086
- className
3087
- }) {
3088
- return /* @__PURE__ */ jsxs(ResponsiveDiagram, { className, children: [
3089
- type === "one-to-one" && /* @__PURE__ */ jsx(OneToOneDiagram, { sourceTable, targetTable, fieldName }),
3090
- type === "belongs-to" && /* @__PURE__ */ jsx(BelongsToDiagram, { sourceTable, targetTable, fieldName }),
3091
- type === "one-to-many" && /* @__PURE__ */ jsx(OneToManyDiagram, { sourceTable, targetTable, fieldName }),
3092
- type === "many-to-many" && /* @__PURE__ */ jsx(
3093
- ManyToManyDiagram,
3094
- {
3095
- sourceTable,
3096
- targetTable,
3097
- junctionTable,
3098
- sourceFkName,
3099
- targetFkName
3100
- }
3101
- )
3102
- ] });
3103
- }
3104
- var TYPE_OPTIONS = [
3105
- {
3106
- type: "one-to-one",
3107
- icon: Link2,
3108
- title: "One-to-One",
3109
- subtitle: "Exactly one each",
3110
- colors: {
3111
- iconBg: "bg-purple-500/10",
3112
- iconText: "text-purple-600 dark:text-purple-400",
3113
- selectedBorder: "border-purple-500",
3114
- selectedBg: "bg-purple-500/5",
3115
- checkBg: "bg-purple-500"
3116
- }
3117
- },
3118
- {
3119
- type: "belongs-to",
3120
- icon: Share2,
3121
- iconClassName: "rotate-180",
3122
- title: "Belongs To",
3123
- subtitle: "Many belong to one",
3124
- colors: {
3125
- iconBg: "bg-green-500/10",
3126
- iconText: "text-green-600 dark:text-green-400",
3127
- selectedBorder: "border-green-500",
3128
- selectedBg: "bg-green-500/5",
3129
- checkBg: "bg-green-500"
3130
- }
3131
- },
3132
- {
3133
- type: "one-to-many",
3134
- icon: Share2,
3135
- title: "One-to-Many",
3136
- subtitle: "One has many",
3137
- colors: {
3138
- iconBg: "bg-blue-500/10",
3139
- iconText: "text-blue-600 dark:text-blue-400",
3140
- selectedBorder: "border-blue-500",
3141
- selectedBg: "bg-blue-500/5",
3142
- checkBg: "bg-blue-500"
3143
- }
3144
- },
3145
- {
3146
- type: "many-to-many",
3147
- icon: Waypoints,
3148
- title: "Many-to-Many",
3149
- subtitle: "Linked via join table",
3150
- colors: {
3151
- iconBg: "bg-amber-500/10",
3152
- iconText: "text-amber-600 dark:text-amber-400",
3153
- selectedBorder: "border-amber-500",
3154
- selectedBg: "bg-amber-500/5",
3155
- checkBg: "bg-amber-500"
3156
- }
3157
- }
3158
- ];
3159
- function RelationshipTypeSelector({ value, onChange, disabled }) {
3160
- return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
3161
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs font-semibold tracking-wide uppercase", children: "Select type" }),
3162
- /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-2", children: TYPE_OPTIONS.map((option) => {
3163
- const Icon = option.icon;
3164
- const isSelected = value === option.type;
3165
- return /* @__PURE__ */ jsxs(
3166
- "button",
3167
- {
3168
- type: "button",
3169
- onClick: () => onChange(option.type),
3170
- disabled,
3171
- className: cn(
3172
- `border-border relative flex min-h-10 items-center gap-2 rounded-lg border px-3 py-2.5 text-left
3173
- transition-[background-color,border-color,box-shadow,scale] duration-150 ease-out motion-safe:active:scale-[0.96]`,
3174
- !isSelected && "disabled:pointer-events-none disabled:opacity-70",
3175
- isSelected && "disabled:pointer-events-none",
3176
- isSelected ? [option.colors.selectedBorder, option.colors.selectedBg] : "hover:border-border/80 hover:bg-muted/30"
3177
- ),
3178
- children: [
3179
- isSelected && /* @__PURE__ */ jsx("div", { className: "absolute top-2 right-2", children: /* @__PURE__ */ jsx("div", { className: cn("flex h-4 w-4 items-center justify-center rounded-full", option.colors.checkBg), children: /* @__PURE__ */ jsx(Check, { className: "h-2.5 w-2.5 text-white", strokeWidth: 3 }) }) }),
3180
- /* @__PURE__ */ jsx("div", { className: cn("flex h-7 w-7 shrink-0 items-center justify-center rounded-md", option.colors.iconBg), children: /* @__PURE__ */ jsx(Icon, { className: cn("h-4 w-4", option.colors.iconText, option.iconClassName) }) }),
3181
- /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1 pr-4", children: [
3182
- /* @__PURE__ */ jsx("h3", { className: "text-balance text-xs leading-tight font-semibold", children: option.title }),
3183
- /* @__PURE__ */ jsx("p", { className: cn("text-muted-foreground text-[10px]", isSelected && option.colors.iconText), children: option.subtitle })
3184
- ] })
3185
- ]
3186
- },
3187
- option.type
3188
- );
3189
- }) })
3190
- ] });
3191
- }
3192
- function TableCombobox({
3193
- tables,
3194
- value,
3195
- onChange,
3196
- placeholder = "Select table",
3197
- disabled
3198
- }) {
3199
- const options = tables.map((t) => ({ value: t.id, label: t.name, table: t }));
3200
- const selected = options.find((o) => o.value === value) ?? null;
3201
- return /* @__PURE__ */ jsxs(
3202
- Combobox,
3203
- {
3204
- items: options,
3205
- value: selected,
3206
- onValueChange: (next) => next && onChange(next.value),
3207
- filter: (item, q) => item.label.toLowerCase().includes(q.toLowerCase()),
3208
- disabled,
3209
- children: [
3210
- /* @__PURE__ */ jsx(ComboboxInput, { placeholder, showClear: false }),
3211
- /* @__PURE__ */ jsxs(ComboboxPopup, { children: [
3212
- /* @__PURE__ */ jsx(ComboboxEmpty, { children: "No tables found" }),
3213
- /* @__PURE__ */ jsx(ComboboxList, { children: (option) => /* @__PURE__ */ jsx(ComboboxItem, { value: option, children: option.label }, option.value) })
3214
- ] })
3215
- ]
3216
- }
3217
- );
3218
- }
3219
- function FieldCombobox({
3220
- fields,
3221
- value,
3222
- onChange,
3223
- placeholder = "Select field",
3224
- disabled
3225
- }) {
3226
- const selectedField = fields.find((f) => f.id === value);
3227
- const options = fields.map((f) => ({
3228
- value: f.id,
3229
- label: selectedField?.id === f.id ? `${f.name} ` : f.name,
3230
- field: f
3231
- }));
3232
- const selected = options.find((o) => o.value === value) ?? null;
3233
- return /* @__PURE__ */ jsxs("div", { className: "relative", children: [
3234
- /* @__PURE__ */ jsxs(
3235
- Combobox,
3236
- {
3237
- items: options,
3238
- value: selected,
3239
- onValueChange: (next) => next && onChange(next.value),
3240
- filter: (item, q) => {
3241
- const lower = q.toLowerCase();
3242
- return item.field.name.toLowerCase().includes(lower) || item.field.type.toLowerCase().includes(lower);
3243
- },
3244
- disabled,
3245
- children: [
3246
- /* @__PURE__ */ jsx(ComboboxInput, { placeholder, showClear: false }),
3247
- /* @__PURE__ */ jsxs(ComboboxPopup, { children: [
3248
- /* @__PURE__ */ jsx(ComboboxEmpty, { children: "No fields found" }),
3249
- /* @__PURE__ */ jsx(ComboboxList, { children: (option) => /* @__PURE__ */ jsx(ComboboxItem, { value: option, children: /* @__PURE__ */ jsxs("div", { className: "flex w-full items-center justify-between gap-2", children: [
3250
- /* @__PURE__ */ jsx("span", { children: option.field.name }),
3251
- /* @__PURE__ */ jsx("span", { className: "bg-muted text-muted-foreground rounded px-1.5 py-0.5 font-mono text-[10px]", children: option.field.type })
3252
- ] }) }, option.value) })
3253
- ] })
3254
- ]
3255
- }
3256
- ),
3257
- selectedField && /* @__PURE__ */ jsx(
3258
- "span",
3259
- {
3260
- className: "bg-muted text-muted-foreground pointer-events-none absolute top-1/2 right-9 -translate-y-1/2\n rounded px-1.5 py-0.5 font-mono text-[10px]",
3261
- children: selectedField.type
3262
- }
3263
- )
3264
- ] });
3265
- }
3266
- var isSystemTable = (category) => category === "CORE" || category === "MODULE";
3267
- var RelationshipCard = ({
3268
- editingRelationship,
3269
- sourceTable: directSourceTable,
3270
- prefilledSourceTableId,
3271
- prefilledTargetTableId,
3272
- card
3273
- }) => {
3274
- const editingConstraint = editingRelationship?.constraint ?? null;
3275
- const { currentSchema, currentTable: selectedTable, currentDatabase } = useSchemaBuilderSelectors();
3276
- const relationProvisionMutation = useRelationProvision();
3277
- const updateForeignKeyMutation = useUpdateForeignKey();
3278
- const { policyTypes } = usePolicyTypes();
3279
- const databaseId = currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId ?? "";
3280
- const { data: tablesWithPolicies = [] } = useDatabasePolicies(databaseId, { enabled: !!databaseId });
3281
- const tables = currentSchema?.tables || [];
3282
- const defaultSourceTableId = useMemo(() => {
3283
- if (directSourceTable) return directSourceTable.id;
3284
- if (prefilledSourceTableId) return prefilledSourceTableId;
3285
- return selectedTable?.id || "";
3286
- }, [directSourceTable, prefilledSourceTableId, selectedTable?.id]);
3287
- const [relationshipType, setRelationshipType] = useState(RelationshipTypes.ONE_TO_ONE);
3288
- const [sourceTableId, setSourceTableId] = useState(defaultSourceTableId);
3289
- const [sourceFieldId, setSourceFieldId] = useState("");
3290
- const [targetTableId, setTargetTableId] = useState(prefilledTargetTableId || "");
3291
- const [targetFieldId, setTargetFieldId] = useState("");
3292
- const [onDelete, setOnDelete] = useState(ForeignKeyActions.NO_ACTION);
3293
- const [junctionTableName, setJunctionTableName] = useState("");
3294
- const [showAdvanced, setShowAdvanced] = useState(false);
3295
- const [fieldNameOverride, setFieldNameOverride] = useState("");
3296
- const [isRequired, setIsRequired] = useState(true);
3297
- const [useCompositeKey, setUseCompositeKey] = useState(true);
3298
- const [sourceFieldName, setSourceFieldName] = useState("");
3299
- const [targetFieldName, setTargetFieldName] = useState("");
3300
- const [exposeInApi, setExposeInApi] = useState(true);
3301
- const [selectedPolicyTypeName, setSelectedPolicyTypeName] = useState("AuthzAllowAll");
3302
- const [policyData, setPolicyData] = useState({});
3303
- const isEditMode = editingConstraint !== null;
3304
- const isManyToMany = relationshipType === RelationshipTypes.MANY_TO_MANY;
3305
- const isFkType = !isManyToMany;
3306
- const isM2MEdit = isEditMode && isManyToMany;
3307
- const sourceTable = useMemo(() => tables.find((t) => t.id === sourceTableId), [tables, sourceTableId]);
3308
- const targetTable = useMemo(() => tables.find((t) => t.id === targetTableId), [tables, targetTableId]);
3309
- const availableSourceTables = useMemo(() => tables.filter((t) => !isSystemTable(t.category)), [tables]);
3310
- const availableTargetTables = useMemo(
3311
- () => tables.filter((t) => (isEditMode || t.id !== sourceTableId) && !isSystemTable(t.category)),
3312
- [tables, sourceTableId, isEditMode]
3313
- );
3314
- const sourceFields = sourceTable?.fields || [];
3315
- const targetFields = targetTable?.fields || [];
3316
- const existingTableNames = useMemo(() => new Set(tables.map((t) => t.name.toLowerCase())), [tables]);
3317
- const isJunctionNameTaken = useMemo(
3318
- () => junctionTableName.trim() && existingTableNames.has(junctionTableName.trim().toLowerCase()),
3319
- [junctionTableName, existingTableNames]
3320
- );
3321
- const inferredPolicyTypeName = useMemo(() => {
3322
- const tableData = tablesWithPolicies.find((t) => t.id === sourceTableId);
3323
- if (!tableData?.policies?.length) return "AuthzAllowAll";
3324
- const readPolicy = tableData.policies.find((p) => p.privilege === "SELECT" && p.policyType);
3325
- const resolved = readPolicy?.policyType ?? tableData.policies.find((p) => p.policyType)?.policyType ?? "AuthzAllowAll";
3326
- return resolved === "AuthzComposite" ? "AuthzDirectOwner" : resolved;
3327
- }, [tablesWithPolicies, sourceTableId]);
3328
- const selectedPolicyType = useMemo(
3329
- () => policyTypes.find((pt) => pt.name === selectedPolicyTypeName) ?? null,
3330
- [policyTypes, selectedPolicyTypeName]
3331
- );
3332
- useEffect(() => {
3333
- if (editingRelationship) {
3334
- const { constraint, sourceTable: relSource, targetTable: relTarget, relationshipType: relType } = editingRelationship;
3335
- setOnDelete(constraint.onDelete || ForeignKeyActions.NO_ACTION);
3336
- setRelationshipType(relType);
3337
- setJunctionTableName("");
3338
- if (relType === "many-to-many") {
3339
- const actualTarget = tables.find((t) => t.name === editingRelationship.withTableName);
3340
- setTargetTableId(actualTarget?.id || "");
3341
- } else {
3342
- setTargetTableId(relTarget?.id || "");
3343
- const srcField = relSource?.fields.find((f) => f.name === editingRelationship.sourceFieldName);
3344
- const tgtField = relTarget?.fields.find((f) => f.name === editingRelationship.targetFieldName);
3345
- setSourceFieldId(srcField?.id || "");
3346
- setTargetFieldId(tgtField?.id || "");
3347
- }
3348
- }
3349
- }, [editingRelationship, tables]);
3350
- const m2mEditInfo = useMemo(() => {
3351
- if (!isM2MEdit || !editingRelationship) return null;
3352
- const junction = editingRelationship.targetTable;
3353
- if (!junction) return null;
3354
- const actualTarget = tables.find((t) => t.name === editingRelationship.withTableName);
3355
- const srcFkName = editingRelationship.targetFieldName;
3356
- const junctionFks = (junction.constraints || []).filter(
3357
- (c) => c.type === "foreign_key"
3358
- );
3359
- const targetFk = junctionFks.find((c) => c.referencedTable === actualTarget?.id);
3360
- const tgtFkName = targetFk ? junction.fields.find((f) => f.id === targetFk.fields[0])?.name || "" : "";
3361
- const pk = (junction.constraints || []).find((c) => c.type === "primary_key");
3362
- const hasCompositePk = pk ? pk.fields.length > 1 : false;
3363
- return { junctionName: junction.name, srcFkName, tgtFkName, hasCompositePk };
3364
- }, [isM2MEdit, editingRelationship, tables]);
3365
- useEffect(() => {
3366
- if (!isManyToMany) {
3367
- setJunctionTableName("");
3368
- setSourceFieldName("");
3369
- setTargetFieldName("");
3370
- }
3371
- setSelectedPolicyTypeName(inferredPolicyTypeName);
3372
- setPolicyData({});
3373
- }, [isManyToMany, inferredPolicyTypeName]);
3374
- useEffect(() => {
3375
- if (selectedPolicyType) {
3376
- setPolicyData(getDefaultFormValues(selectedPolicyType));
3377
- }
3378
- }, [selectedPolicyTypeName]);
3379
- const handleSourceTableChange = useCallback((tableId) => {
3380
- setSourceTableId(tableId);
3381
- setTargetTableId((prev) => prev === tableId ? "" : prev);
3382
- }, []);
3383
- const handleTargetTableChange = useCallback((tableId) => {
3384
- setTargetTableId(tableId);
3385
- setTargetFieldId("");
3386
- }, []);
3387
- const handleSave = useCallback(async () => {
3388
- if (!sourceTable) {
3389
- toast.error({ message: "No source table selected" });
3390
- return;
3391
- }
3392
- if (!targetTableId) {
3393
- toast.error({ message: "Please select a target table" });
3394
- return;
3395
- }
3396
- if (isManyToMany) {
3397
- try {
3398
- await relationProvisionMutation.mutateAsync({
3399
- relationshipType,
3400
- sourceTableId: sourceTable.id,
3401
- targetTableId,
3402
- ...junctionTableName.trim() && { junctionTableName: junctionTableName.trim() },
3403
- useCompositeKey,
3404
- exposeInApi,
3405
- ...sourceFieldName.trim() && { sourceFieldName: sourceFieldName.trim() },
3406
- ...targetFieldName.trim() && { targetFieldName: targetFieldName.trim() },
3407
- policyType: selectedPolicyTypeName,
3408
- policyData,
3409
- policyTypeObj: selectedPolicyType ?? void 0
3410
- });
3411
- toast.success({
3412
- message: "Many-to-many relationship created",
3413
- description: junctionTableName.trim() ? `Junction table "${junctionTableName}" created.` : "Junction table created."
3414
- });
3415
- card.close();
3416
- } catch (error) {
3417
- toast.error({
3418
- message: "Failed to create relationship",
3419
- description: error instanceof Error ? error.message : "An error occurred"
3420
- });
3421
- }
3422
- return;
3423
- }
3424
- if (isEditMode && editingConstraint) {
3425
- try {
3426
- await updateForeignKeyMutation.mutateAsync({
3427
- id: editingConstraint.id,
3428
- deleteAction: onDelete
3429
- });
3430
- toast.success({ message: "Relationship updated" });
3431
- card.close();
3432
- } catch (error) {
3433
- toast.error({
3434
- message: "Failed to update relationship",
3435
- description: error instanceof Error ? error.message : "An error occurred"
3436
- });
3437
- }
3438
- return;
3439
- }
3440
- try {
3441
- await relationProvisionMutation.mutateAsync({
3442
- relationshipType,
3443
- sourceTableId: sourceTable.id,
3444
- targetTableId,
3445
- deleteAction: onDelete,
3446
- ...fieldNameOverride.trim() && { fieldName: fieldNameOverride.trim() },
3447
- ...isRequired !== void 0 && { isRequired }
3448
- });
3449
- toast.success({ message: "Relationship created" });
3450
- card.close();
3451
- } catch (error) {
3452
- toast.error({
3453
- message: "Failed to create relationship",
3454
- description: error instanceof Error ? error.message : "An error occurred"
3455
- });
3456
- }
3457
- }, [
3458
- sourceTable,
3459
- targetTableId,
3460
- isManyToMany,
3461
- junctionTableName,
3462
- relationshipType,
3463
- onDelete,
3464
- isEditMode,
3465
- editingConstraint,
3466
- fieldNameOverride,
3467
- isRequired,
3468
- useCompositeKey,
3469
- exposeInApi,
3470
- sourceFieldName,
3471
- targetFieldName,
3472
- selectedPolicyTypeName,
3473
- selectedPolicyType,
3474
- policyData,
3475
- relationProvisionMutation,
3476
- updateForeignKeyMutation,
3477
- card
3478
- ]);
3479
- const isPending = relationProvisionMutation.isPending || updateForeignKeyMutation.isPending;
3480
- const canSaveM2M = isManyToMany && sourceTableId && targetTableId;
3481
- const initialOnDelete = editingRelationship?.constraint.onDelete || ForeignKeyActions.NO_ACTION;
3482
- const canSaveEditFK = isEditMode && isFkType && onDelete !== initialOnDelete;
3483
- const canSaveCreateFK = !isEditMode && isFkType && sourceTableId && targetTableId;
3484
- const canSave = canSaveM2M || canSaveEditFK || canSaveCreateFK;
3485
- const sourceTableName = sourceTable?.name || "source";
3486
- const targetTableName = targetTable?.name || "target";
3487
- const isOneToMany = relationshipType === RelationshipTypes.ONE_TO_MANY;
3488
- const fkDerivedTable = isOneToMany ? sourceTable : targetTable;
3489
- const diagramFieldName = fieldNameOverride.trim() || (fkDerivedTable ? `${fkDerivedTable.name}_id` : "fk");
3490
- const diagramJunctionName = m2mEditInfo?.junctionName || junctionTableName.trim() || (sourceTable && targetTable ? [sourceTable.name, targetTable.name].sort().join("_") : "junction");
3491
- const sourceFkPlaceholder = sourceTable ? `${sourceTable.name}_id (auto)` : "Auto-derived";
3492
- const targetFkPlaceholder = targetTable ? `${targetTable.name}_id (auto)` : "Auto-derived";
3493
- return /* @__PURE__ */ jsxs(
3494
- "div",
3495
- {
3496
- "data-chat-component": "relationship-card",
3497
- "data-chat-relationship-type": relationshipType,
3498
- "data-chat-source-table": sourceTable?.name ?? "",
3499
- "data-chat-target-table": targetTable?.name ?? "",
3500
- className: "flex h-full flex-col",
3501
- children: [
3502
- /* @__PURE__ */ jsx(ScrollArea, { className: "min-h-0 flex-1", children: /* @__PURE__ */ jsxs("div", { className: "space-y-6 p-6", children: [
3503
- /* @__PURE__ */ jsx(
3504
- RelationshipTypeSelector,
3505
- {
3506
- value: relationshipType,
3507
- onChange: setRelationshipType,
3508
- disabled: isEditMode
3509
- }
3510
- ),
3511
- /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
3512
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs font-semibold tracking-wide uppercase", children: "Connect tables" }),
3513
- /* @__PURE__ */ jsx(
3514
- RelationshipDiagram,
3515
- {
3516
- type: relationshipType,
3517
- sourceTable: sourceTableName,
3518
- targetTable: targetTableName,
3519
- fieldName: isManyToMany ? void 0 : diagramFieldName,
3520
- junctionTable: isManyToMany ? diagramJunctionName : void 0,
3521
- sourceFkName: isManyToMany ? m2mEditInfo?.srcFkName || sourceFieldName.trim() || void 0 : void 0,
3522
- targetFkName: isManyToMany ? m2mEditInfo?.tgtFkName || targetFieldName.trim() || void 0 : void 0
3523
- }
3524
- ),
3525
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3526
- /* @__PURE__ */ jsx(Label, { children: "Source table" }),
3527
- /* @__PURE__ */ jsx(
3528
- TableCombobox,
3529
- {
3530
- tables: availableSourceTables,
3531
- value: sourceTableId,
3532
- onChange: handleSourceTableChange,
3533
- placeholder: "Select source table",
3534
- disabled: isEditMode
3535
- }
3536
- )
3537
- ] }),
3538
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3539
- /* @__PURE__ */ jsx(Label, { children: "Target table" }),
3540
- /* @__PURE__ */ jsx(
3541
- TableCombobox,
3542
- {
3543
- tables: availableTargetTables,
3544
- value: targetTableId,
3545
- onChange: handleTargetTableChange,
3546
- placeholder: "Select target table",
3547
- disabled: isEditMode
3548
- }
3549
- )
3550
- ] }),
3551
- isManyToMany && /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
3552
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
3553
- /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
3554
- /* @__PURE__ */ jsx(Label, { children: "Use composite primary key" }),
3555
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: (isM2MEdit ? m2mEditInfo?.hasCompositePk : useCompositeKey) ? "Each source\u2013target pair can only appear once." : "Rows get a UUID id \u2014 pairs are not enforced as unique." })
3556
- ] }),
3557
- /* @__PURE__ */ jsx(
3558
- Switch,
3559
- {
3560
- checked: isM2MEdit ? m2mEditInfo?.hasCompositePk ?? true : useCompositeKey,
3561
- onCheckedChange: setUseCompositeKey,
3562
- disabled: isM2MEdit
3563
- }
3564
- )
3565
- ] }),
3566
- /* @__PURE__ */ jsx("div", { className: "bg-muted/50 rounded-md px-3 py-2 font-mono text-xs", children: (isM2MEdit ? m2mEditInfo?.hasCompositePk : useCompositeKey) ? /* @__PURE__ */ jsxs(Fragment, { children: [
3567
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "PK" }),
3568
- " (",
3569
- sourceTable?.name || "source",
3570
- "_id,",
3571
- " ",
3572
- targetTable?.name || "target",
3573
- "_id)"
3574
- ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
3575
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "PK" }),
3576
- " id",
3577
- " ",
3578
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "uuid" })
3579
- ] }) }),
3580
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
3581
- /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
3582
- /* @__PURE__ */ jsx(Label, { children: "Expose in GraphQL API" }),
3583
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: "Makes this many-to-many relation directly queryable in the GraphQL API." })
3584
- ] }),
3585
- /* @__PURE__ */ jsx(
3586
- Switch,
3587
- {
3588
- checked: isM2MEdit ? editingRelationship?.provision?.exposeInApi ?? true : exposeInApi,
3589
- onCheckedChange: setExposeInApi,
3590
- disabled: isM2MEdit
3591
- }
3592
- )
3593
- ] })
3594
- ] }),
3595
- isM2MEdit && m2mEditInfo && /* @__PURE__ */ jsxs(Fragment, { children: [
3596
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3597
- /* @__PURE__ */ jsx(Label, { children: "Junction table name" }),
3598
- /* @__PURE__ */ jsx(Input, { value: m2mEditInfo.junctionName, disabled: true })
3599
- ] }),
3600
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3601
- /* @__PURE__ */ jsx(Label, { children: "Source FK name" }),
3602
- /* @__PURE__ */ jsx(Input, { value: m2mEditInfo.srcFkName, disabled: true })
3603
- ] }),
3604
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3605
- /* @__PURE__ */ jsx(Label, { children: "Target FK name" }),
3606
- /* @__PURE__ */ jsx(Input, { value: m2mEditInfo.tgtFkName, disabled: true })
3607
- ] })
3608
- ] }),
3609
- isEditMode && isFkType && /* @__PURE__ */ jsxs(Fragment, { children: [
3610
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3611
- /* @__PURE__ */ jsx(Label, { children: "Source field" }),
3612
- /* @__PURE__ */ jsx(
3613
- FieldCombobox,
3614
- {
3615
- fields: sourceFields,
3616
- value: sourceFieldId,
3617
- onChange: setSourceFieldId,
3618
- placeholder: "Select field",
3619
- disabled: true
3620
- }
3621
- )
3622
- ] }),
3623
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3624
- /* @__PURE__ */ jsx(Label, { children: "Target field" }),
3625
- /* @__PURE__ */ jsx(
3626
- FieldCombobox,
3627
- {
3628
- fields: targetFields,
3629
- value: targetFieldId,
3630
- onChange: setTargetFieldId,
3631
- placeholder: "Select field",
3632
- disabled: true
3633
- }
3634
- )
3635
- ] })
3636
- ] }),
3637
- isFkType && /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3638
- /* @__PURE__ */ jsx(Label, { children: "On delete" }),
3639
- /* @__PURE__ */ jsxs(Select, { value: onDelete, onValueChange: (v) => setOnDelete(v), children: [
3640
- /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx("span", { children: ForeignKeyActionLabels[onDelete] }) }),
3641
- /* @__PURE__ */ jsx(SelectContent, { children: Object.entries(ForeignKeyActions).map(([key, value]) => /* @__PURE__ */ jsx(SelectItem, { value, children: ForeignKeyActionLabels[value] }, key)) })
3642
- ] })
3643
- ] })
3644
- ] }),
3645
- !isEditMode && /* @__PURE__ */ jsxs("div", { className: "border-border/60 rounded-lg border", children: [
3646
- /* @__PURE__ */ jsxs(
3647
- "button",
3648
- {
3649
- type: "button",
3650
- onClick: () => setShowAdvanced(!showAdvanced),
3651
- className: "flex min-h-10 w-full items-center gap-2 rounded-lg px-4 py-3 text-left text-sm font-medium\n transition-[background-color,scale] duration-150 ease-out hover:bg-muted/40 motion-safe:active:scale-[0.96]",
3652
- "aria-expanded": showAdvanced,
3653
- children: [
3654
- /* @__PURE__ */ jsx(
3655
- ChevronRight,
3656
- {
3657
- className: cn("text-muted-foreground h-4 w-4 transition-transform", showAdvanced && "rotate-90")
3658
- }
3659
- ),
3660
- "Advanced"
3661
- ]
3662
- }
3663
- ),
3664
- showAdvanced && /* @__PURE__ */ jsxs("div", { className: "space-y-4 border-t px-4 pt-3 pb-4", children: [
3665
- isFkType && /* @__PURE__ */ jsxs(Fragment, { children: [
3666
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3667
- /* @__PURE__ */ jsx(Label, { children: "Foreign key field name" }),
3668
- /* @__PURE__ */ jsx(
3669
- Input,
3670
- {
3671
- value: fieldNameOverride,
3672
- onChange: (e) => setFieldNameOverride(e.target.value),
3673
- placeholder: targetTable ? `${targetTable.name}_id (auto)` : "Auto-derived"
3674
- }
3675
- ),
3676
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: "Leave empty to auto-derive from the target table name." })
3677
- ] }),
3678
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
3679
- /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
3680
- /* @__PURE__ */ jsx(Label, { children: "Foreign key field required" }),
3681
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: "Whether the foreign key field is NOT NULL." })
3682
- ] }),
3683
- /* @__PURE__ */ jsx(Switch, { checked: isRequired, onCheckedChange: setIsRequired })
3684
- ] })
3685
- ] }),
3686
- isManyToMany && /* @__PURE__ */ jsxs(Fragment, { children: [
3687
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3688
- /* @__PURE__ */ jsx(Label, { children: "Junction table name" }),
3689
- /* @__PURE__ */ jsx(
3690
- Input,
3691
- {
3692
- value: junctionTableName,
3693
- onChange: (e) => setJunctionTableName(e.target.value),
3694
- placeholder: sourceTable && targetTable ? `${[sourceTable.name, targetTable.name].sort().join("_")} (auto)` : "Auto-derived",
3695
- className: isJunctionNameTaken ? "border-destructive" : ""
3696
- }
3697
- ),
3698
- isJunctionNameTaken ? /* @__PURE__ */ jsx("p", { className: "text-destructive text-xs", children: "Table name already exists" }) : /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: "Leave empty to auto-derive from table names." })
3699
- ] }),
3700
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3701
- /* @__PURE__ */ jsx(Label, { children: "Source FK name" }),
3702
- /* @__PURE__ */ jsx(
3703
- Input,
3704
- {
3705
- value: sourceFieldName,
3706
- onChange: (e) => setSourceFieldName(e.target.value),
3707
- placeholder: sourceFkPlaceholder
3708
- }
3709
- )
3710
- ] }),
3711
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3712
- /* @__PURE__ */ jsx(Label, { children: "Target FK name" }),
3713
- /* @__PURE__ */ jsx(
3714
- Input,
3715
- {
3716
- value: targetFieldName,
3717
- onChange: (e) => setTargetFieldName(e.target.value),
3718
- placeholder: targetFkPlaceholder
3719
- }
3720
- )
3721
- ] }),
3722
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3723
- /* @__PURE__ */ jsx(Label, { children: "Junction table policy" }),
3724
- /* @__PURE__ */ jsxs(Select, { value: selectedPolicyTypeName, onValueChange: setSelectedPolicyTypeName, children: [
3725
- /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
3726
- selectedPolicyType && /* @__PURE__ */ jsx(selectedPolicyType.icon, { className: "text-muted-foreground h-4 w-4 shrink-0" }),
3727
- /* @__PURE__ */ jsx("span", { children: selectedPolicyType?.title || selectedPolicyTypeName })
3728
- ] }) }),
3729
- /* @__PURE__ */ jsx(SelectContent, { children: policyTypes.filter((pt) => pt.name !== "AuthzComposite").map((pt) => {
3730
- const Icon = pt.icon;
3731
- return /* @__PURE__ */ jsx(SelectItem, { value: pt.name, children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
3732
- /* @__PURE__ */ jsx(Icon, { className: "text-muted-foreground h-4 w-4 shrink-0" }),
3733
- /* @__PURE__ */ jsx("span", { children: pt.title })
3734
- ] }) }, pt.name);
3735
- }) })
3736
- ] }),
3737
- selectedPolicyType && selectedPolicyTypeName === inferredPolicyTypeName && inferredPolicyTypeName !== "AuthzAllowAll" && /* @__PURE__ */ jsxs("div", { className: "text-muted-foreground flex items-start gap-2 text-xs", children: [
3738
- /* @__PURE__ */ jsx(Info, { className: "mt-0.5 h-3 w-3 shrink-0" }),
3739
- /* @__PURE__ */ jsx("span", { children: "Inherited from source table\u2019s policy." })
3740
- ] }),
3741
- selectedPolicyType && (selectedPolicyTypeName !== inferredPolicyTypeName || inferredPolicyTypeName === "AuthzAllowAll") && /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: selectedPolicyType.description })
3742
- ] }),
3743
- selectedPolicyType && selectedPolicyTypeName !== "AuthzAllowAll" && (selectedPolicyType.fieldOverrides && Object.keys(selectedPolicyType.fieldOverrides).length > 0 || selectedPolicyType.generatedFields.length > 0) && /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
3744
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs font-semibold tracking-wide uppercase", children: "Policy config" }),
3745
- /* @__PURE__ */ jsx(PolicyConfigForm, { policyType: selectedPolicyType, value: policyData, onChange: setPolicyData })
3746
- ] })
3747
- ] })
3748
- ] })
3749
- ] })
3750
- ] }) }),
3751
- /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2 border-t px-4 py-3", children: [
3752
- /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => card.close(), disabled: isPending, children: isM2MEdit ? "Close" : "Cancel" }),
3753
- !isM2MEdit && /* @__PURE__ */ jsxs(Button, { onClick: handleSave, disabled: !canSave || isPending, children: [
3754
- isPending && /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }),
3755
- isEditMode ? "Update Relationship" : "Create Relationship"
3756
- ] })
3757
- ] })
3758
- ]
3759
- }
3760
- );
3761
- };
3762
- function EmptyStateCard({
3763
- icon: Icon,
3764
- title,
3765
- description,
3766
- actionLabel,
3767
- actionIcon: ActionIcon,
3768
- onAction,
3769
- actionTestId,
3770
- features,
3771
- className
3772
- }) {
3773
- return /* @__PURE__ */ jsx("div", { className: cn("@container flex w-full items-center justify-center py-12", className), children: /* @__PURE__ */ jsxs("div", { className: "bg-card border-border max-w-2xl rounded-lg border p-6 @md:p-8", children: [
3774
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center text-center", children: [
3775
- /* @__PURE__ */ jsx("div", { className: "border-primary/20 bg-primary/10 mb-4 flex h-20 w-20 items-center justify-center rounded-2xl border", children: /* @__PURE__ */ jsx(Icon, { className: "text-primary h-10 w-10" }) }),
3776
- /* @__PURE__ */ jsx("h2", { className: "mb-2 text-balance text-xl font-semibold", children: title }),
3777
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground mb-6 max-w-lg text-sm", children: description }),
3778
- actionLabel && onAction && /* @__PURE__ */ jsxs(Button, { onClick: onAction, size: "xl", className: "px-12", "data-testid": actionTestId, children: [
3779
- ActionIcon && /* @__PURE__ */ jsx(ActionIcon, { className: "mr-2 h-4 w-4" }),
3780
- actionLabel
3781
- ] })
3782
- ] }),
3783
- features && features.length > 0 && /* @__PURE__ */ jsx("div", { className: "border-border mt-8 grid grid-cols-1 gap-4 border-t pt-6 @sm:grid-cols-3", children: features.map((feature) => /* @__PURE__ */ jsxs(
3784
- "div",
3785
- {
3786
- className: "flex flex-row items-center gap-3 text-left @sm:flex-col @sm:items-center @sm:gap-0 @sm:text-center",
3787
- children: [
3788
- /* @__PURE__ */ jsx("div", { className: "bg-muted flex h-10 w-10 shrink-0 items-center justify-center rounded-lg @sm:mb-2", children: /* @__PURE__ */ jsx(feature.icon, { className: "text-muted-foreground h-5 w-5" }) }),
3789
- /* @__PURE__ */ jsxs("div", { children: [
3790
- /* @__PURE__ */ jsx("h3", { className: "mb-0.5 text-balance text-sm font-medium @sm:mb-1", children: feature.title }),
3791
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: feature.description })
3792
- ] })
3793
- ]
3794
- },
3795
- feature.title
3796
- )) })
3797
- ] }) });
3798
- }
3799
- function RelationshipEmptyState({ onCreateClick, tableName }) {
3800
- return /* @__PURE__ */ jsx(
3801
- EmptyStateCard,
3802
- {
3803
- icon: Link2,
3804
- title: tableName ? /* @__PURE__ */ jsxs(Fragment, { children: [
3805
- "No relationships for ",
3806
- tableName
3807
- ] }) : "Create your first relationship",
3808
- description: tableName ? `Add a relationship to connect ${tableName} to other tables. This helps organize your data and maintain consistency.` : "Connect your tables to establish relationships. This helps organize your data and maintain consistency.",
3809
- actionLabel: "Create Relationship",
3810
- actionIcon: Link2,
3811
- onAction: onCreateClick,
3812
- features: [
3813
- { icon: Shield, title: "Data Integrity", description: "Maintain consistency across tables" },
3814
- { icon: Target, title: "Referential Actions", description: "Control cascade & deletion behavior" },
3815
- { icon: Zap, title: "Query Optimization", description: "Efficient joins & data retrieval" }
3816
- ]
3817
- }
3818
- );
3819
- }
3820
- function useRelationProvisionsQuery(variables) {
3821
- const { adapter, scope } = useSchemaBuilder();
3822
- const { enabled = true, ...operationVariables } = variables;
3823
- return useQuery({
3824
- queryKey: ["schema-builder", scope, "relationProvisions", operationVariables],
3825
- queryFn: ({ signal }) => adapter.relationships.relationProvisions(operationVariables, { scope, signal }),
3826
- enabled
3827
- });
3828
- }
3829
-
3830
- // src/schema/schema-builder-core/lib/keyboard-activation.ts
3831
- function handleActivationKeyDown(event, activate, disabled = false) {
3832
- if (event.target !== event.currentTarget || disabled) return;
3833
- if (event.key === "Enter" || event.key === " ") {
3834
- event.preventDefault();
3835
- activate();
3836
- }
3837
- }
3838
- function DeleteConfirmDialog({
3839
- entityType,
3840
- entityName,
3841
- open,
3842
- onOpenChange,
3843
- onConfirm,
3844
- isPending
3845
- }) {
3846
- return /* @__PURE__ */ jsx(AlertDialog, { open, onOpenChange: (next) => !next && !isPending && onOpenChange(false), children: /* @__PURE__ */ jsxs(AlertDialogContent, { children: [
3847
- /* @__PURE__ */ jsxs(AlertDialogHeader, { children: [
3848
- /* @__PURE__ */ jsxs(AlertDialogTitle, { children: [
3849
- "Delete ",
3850
- entityType
3851
- ] }),
3852
- /* @__PURE__ */ jsxs(AlertDialogDescription, { children: [
3853
- "Are you sure you want to delete",
3854
- " ",
3855
- /* @__PURE__ */ jsxs("strong", { className: "text-foreground", children: [
3856
- "\u201C",
3857
- entityName,
3858
- "\u201D"
3859
- ] }),
3860
- "? This action cannot be undone."
3861
- ] })
3862
- ] }),
3863
- /* @__PURE__ */ jsxs(AlertDialogFooter, { children: [
3864
- /* @__PURE__ */ jsx(AlertDialogCancel, { disabled: isPending, children: "Cancel" }),
3865
- /* @__PURE__ */ jsxs(
3866
- AlertDialogAction,
3867
- {
3868
- onClick: onConfirm,
3869
- disabled: isPending,
3870
- className: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
3871
- children: [
3872
- isPending ? /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }) : null,
3873
- isPending ? "Deleting..." : "Delete"
3874
- ]
3875
- }
3876
- )
3877
- ] })
3878
- ] }) });
3879
- }
3880
- var PROVISION_TYPE_MAP = {
3881
- [RelationHasOne.name]: "one-to-one",
3882
- [RelationBelongsTo.name]: "belongs-to",
3883
- [RelationHasMany.name]: "one-to-many",
3884
- [RelationManyToMany.name]: "many-to-many"
3885
- };
3886
- function isForeignKeyConstraint(constraint) {
3887
- return typeof constraint === "object" && constraint != null && "type" in constraint && constraint.type === "foreign_key";
3888
- }
3889
- function resolveFieldName(table, fieldId) {
3890
- if (!fieldId) return "";
3891
- return table?.fields.find((field) => field.id === fieldId)?.name || fieldId;
3892
- }
3893
- function findProvision(constraint, sourceTableId, provisions) {
3894
- const fkFieldId = constraint.fields[0];
3895
- if (fkFieldId) {
3896
- const byField = provisions.find((p) => p.outFieldId === fkFieldId);
3897
- if (byField) return byField;
3898
- }
3899
- const targetTableId = constraint.referencedTable;
3900
- return provisions.find(
3901
- (p) => p.sourceTableId === sourceTableId && p.targetTableId === targetTableId
3902
- );
3903
- }
3904
- function resolveRelationshipType(constraint, provision) {
3905
- if (provision?.relationType) {
3906
- const mapped = PROVISION_TYPE_MAP[provision.relationType];
3907
- if (mapped) return mapped;
3908
- }
3909
- return constraint.smartTags?.relationshipType || "one-to-many";
3910
- }
3911
- function getTableRelationships(currentTable, tables, provisions = []) {
3912
- if (!currentTable) return [];
3913
- const relationships = [];
3914
- const seenConstraintIds = /* @__PURE__ */ new Set();
3915
- const ownForeignKeys = (currentTable.constraints || []).filter(isForeignKeyConstraint);
3916
- for (const constraint of ownForeignKeys) {
3917
- seenConstraintIds.add(constraint.id);
3918
- const targetTable = tables.find((table) => table.id === constraint.referencedTable);
3919
- const provision = findProvision(constraint, currentTable.id, provisions);
3920
- relationships.push({
3921
- constraint,
3922
- sourceTable: currentTable,
3923
- targetTable,
3924
- sourceFieldName: resolveFieldName(currentTable, constraint.fields[0]),
3925
- targetFieldName: resolveFieldName(targetTable, constraint.referencedFields?.[0]),
3926
- relationshipType: resolveRelationshipType(constraint, provision),
3927
- provision
3928
- });
3929
- }
3930
- for (const otherTable of tables) {
3931
- if (otherTable.id === currentTable.id) continue;
3932
- const otherFks = (otherTable.constraints || []).filter(isForeignKeyConstraint);
3933
- const referencesCurrent = otherFks.filter((c) => c.referencedTable === currentTable.id);
3934
- for (const constraint of referencesCurrent) {
3935
- if (seenConstraintIds.has(constraint.id)) continue;
3936
- seenConstraintIds.add(constraint.id);
3937
- const provision = findProvision(constraint, otherTable.id, provisions);
3938
- let relationshipType = resolveRelationshipType(constraint, provision);
3939
- let withTableName;
3940
- const m2mProvision = provisions.find(
3941
- (p) => p.relationType === RelationManyToMany.name && p.outJunctionTableId === otherTable.id && (p.sourceTableId === currentTable.id || p.targetTableId === currentTable.id)
3942
- );
3943
- if (m2mProvision) {
3944
- relationshipType = "many-to-many";
3945
- const actualTargetId = m2mProvision.sourceTableId === currentTable.id ? m2mProvision.targetTableId : m2mProvision.sourceTableId;
3946
- const actualTarget = tables.find((t) => t.id === actualTargetId);
3947
- withTableName = actualTarget?.name;
3948
- }
3949
- if (relationshipType === "one-to-many" || relationshipType === "one-to-one" || relationshipType === "many-to-many") {
3950
- relationships.push({
3951
- constraint,
3952
- sourceTable: currentTable,
3953
- targetTable: otherTable,
3954
- sourceFieldName: resolveFieldName(currentTable, constraint.referencedFields?.[0]),
3955
- targetFieldName: resolveFieldName(otherTable, constraint.fields[0]),
3956
- relationshipType,
3957
- provision: m2mProvision ?? provision,
3958
- withTableName
3959
- });
3960
- } else {
3961
- relationships.push({
3962
- constraint,
3963
- sourceTable: otherTable,
3964
- targetTable: currentTable,
3965
- sourceFieldName: resolveFieldName(otherTable, constraint.fields[0]),
3966
- targetFieldName: resolveFieldName(currentTable, constraint.referencedFields?.[0]),
3967
- relationshipType,
3968
- provision
3969
- });
3970
- }
3971
- }
3972
- }
3973
- relationships.sort((a, b) => {
3974
- const aTime = a.constraint.createdAt || "";
3975
- const bTime = b.constraint.createdAt || "";
3976
- return bTime.localeCompare(aTime);
3977
- });
3978
- return relationships;
3979
- }
3980
- var RELATIONSHIP_STYLES = {
3981
- "one-to-one": {
3982
- bg: "bg-purple-500/10",
3983
- border: "border-purple-500/30",
3984
- text: "text-purple-600 dark:text-purple-400",
3985
- label: "One to One",
3986
- shortLabel: "1:1"
3987
- },
3988
- "belongs-to": {
3989
- bg: "bg-green-500/10",
3990
- border: "border-green-500/30",
3991
- text: "text-green-600 dark:text-green-400",
3992
- label: "Belongs To",
3993
- shortLabel: "BT"
3994
- },
3995
- "one-to-many": {
3996
- bg: "bg-blue-500/10",
3997
- border: "border-blue-500/30",
3998
- text: "text-blue-600 dark:text-blue-400",
3999
- label: "One to Many",
4000
- shortLabel: "1:N"
4001
- },
4002
- "many-to-many": {
4003
- bg: "bg-amber-500/10",
4004
- border: "border-amber-500/30",
4005
- text: "text-amber-600 dark:text-amber-400",
4006
- label: "Many to Many",
4007
- shortLabel: "N:M"
4008
- }
4009
- };
4010
- function MiniConnector({ type }) {
4011
- if (type === "one-to-one") {
4012
- return /* @__PURE__ */ jsxs("svg", { width: "32", height: "16", viewBox: "0 0 32 16", fill: "none", className: "shrink-0", children: [
4013
- /* @__PURE__ */ jsx("circle", { cx: "4", cy: "8", r: "3", fill: "currentColor", fillOpacity: "0.3", stroke: "currentColor", strokeWidth: "1.5" }),
4014
- /* @__PURE__ */ jsx("line", { x1: "8", y1: "8", x2: "24", y2: "8", stroke: "currentColor", strokeWidth: "1.5", strokeDasharray: "2 2" }),
4015
- /* @__PURE__ */ jsx("circle", { cx: "28", cy: "8", r: "3", fill: "currentColor", fillOpacity: "0.3", stroke: "currentColor", strokeWidth: "1.5" })
4016
- ] });
4017
- }
4018
- if (type === "belongs-to") {
4019
- return /* @__PURE__ */ jsxs("svg", { width: "32", height: "16", viewBox: "0 0 32 16", fill: "none", className: "shrink-0", children: [
4020
- /* @__PURE__ */ jsx("circle", { cx: "6", cy: "3", r: "2", fill: "currentColor" }),
4021
- /* @__PURE__ */ jsx("circle", { cx: "4", cy: "8", r: "2", fill: "currentColor" }),
4022
- /* @__PURE__ */ jsx("circle", { cx: "6", cy: "13", r: "2", fill: "currentColor" }),
4023
- /* @__PURE__ */ jsx("line", { x1: "10", y1: "8", x2: "20", y2: "8", stroke: "currentColor", strokeWidth: "1.5" }),
4024
- /* @__PURE__ */ jsx("path", { d: "M18 5L22 8L18 11", stroke: "currentColor", strokeWidth: "1.5", fill: "none", strokeLinecap: "round" }),
4025
- /* @__PURE__ */ jsx("circle", { cx: "28", cy: "8", r: "3", fill: "currentColor", fillOpacity: "0.3", stroke: "currentColor", strokeWidth: "1.5" })
4026
- ] });
4027
- }
4028
- if (type === "one-to-many") {
4029
- return /* @__PURE__ */ jsxs("svg", { width: "32", height: "16", viewBox: "0 0 32 16", fill: "none", className: "shrink-0", children: [
4030
- /* @__PURE__ */ jsx("circle", { cx: "4", cy: "8", r: "3", fill: "currentColor", fillOpacity: "0.3", stroke: "currentColor", strokeWidth: "1.5" }),
4031
- /* @__PURE__ */ jsx("line", { x1: "8", y1: "8", x2: "20", y2: "8", stroke: "currentColor", strokeWidth: "1.5" }),
4032
- /* @__PURE__ */ jsx("path", { d: "M18 5L22 8L18 11", stroke: "currentColor", strokeWidth: "1.5", fill: "none", strokeLinecap: "round" }),
4033
- /* @__PURE__ */ jsx("circle", { cx: "26", cy: "3", r: "2", fill: "currentColor" }),
4034
- /* @__PURE__ */ jsx("circle", { cx: "28", cy: "8", r: "2", fill: "currentColor" }),
4035
- /* @__PURE__ */ jsx("circle", { cx: "26", cy: "13", r: "2", fill: "currentColor" })
4036
- ] });
4037
- }
4038
- return /* @__PURE__ */ jsxs("svg", { width: "32", height: "16", viewBox: "0 0 32 16", fill: "none", className: "shrink-0", children: [
4039
- /* @__PURE__ */ jsx("circle", { cx: "4", cy: "3", r: "2", fill: "currentColor" }),
4040
- /* @__PURE__ */ jsx("circle", { cx: "2", cy: "8", r: "2", fill: "currentColor" }),
4041
- /* @__PURE__ */ jsx("circle", { cx: "4", cy: "13", r: "2", fill: "currentColor" }),
4042
- /* @__PURE__ */ jsx("line", { x1: "8", y1: "8", x2: "24", y2: "8", stroke: "currentColor", strokeWidth: "1.5" }),
4043
- /* @__PURE__ */ jsx("circle", { cx: "28", cy: "3", r: "2", fill: "currentColor" }),
4044
- /* @__PURE__ */ jsx("circle", { cx: "30", cy: "8", r: "2", fill: "currentColor" }),
4045
- /* @__PURE__ */ jsx("circle", { cx: "28", cy: "13", r: "2", fill: "currentColor" })
4046
- ] });
4047
- }
4048
- function NoTableSelectedState() {
4049
- return /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-1 flex-col items-center justify-center p-6", children: [
4050
- /* @__PURE__ */ jsx("div", { className: "bg-muted/50 mb-4 flex h-16 w-16 items-center justify-center rounded-full", children: /* @__PURE__ */ jsx(Table2, { className: "text-muted-foreground h-8 w-8" }) }),
4051
- /* @__PURE__ */ jsx("h3", { className: "mb-1 text-balance text-lg font-semibold", children: "No table selected" }),
4052
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground max-w-sm text-center text-sm", children: "Select a table from the sidebar to view and manage its relationships." })
4053
- ] });
4054
- }
4055
- function RelationshipsView() {
4056
- const [deleteTarget, setDeleteTarget] = useState(null);
4057
- const [isDeleting, setIsDeleting] = useState(false);
4058
- const stack = useCardStack();
4059
- const { currentTable, currentSchema, currentDatabase } = useSchemaBuilderSelectors();
4060
- const deleteForeignKeyMutation = useDeleteForeignKey();
4061
- const tables = currentSchema?.tables || [];
4062
- const databaseId = currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId ?? "";
4063
- const { data: provisionsData } = useRelationProvisionsQuery({
4064
- selection: {
4065
- fields: {
4066
- id: true,
4067
- relationType: true,
4068
- sourceTableId: true,
4069
- targetTableId: true,
4070
- outFieldId: true,
4071
- outJunctionTableId: true,
4072
- exposeInApi: true
4073
- },
4074
- where: databaseId ? { databaseId: { equalTo: databaseId } } : void 0
4075
- },
4076
- enabled: !!databaseId
4077
- });
4078
- const provisions = useMemo(() => {
4079
- const nodes = provisionsData?.relationProvisions?.nodes;
4080
- if (!nodes) return [];
4081
- return nodes.map((n) => ({
4082
- id: n.id,
4083
- relationType: n.relationType ?? null,
4084
- sourceTableId: n.sourceTableId ?? null,
4085
- targetTableId: n.targetTableId ?? null,
4086
- outFieldId: n.outFieldId ?? null,
4087
- outJunctionTableId: n.outJunctionTableId ?? null,
4088
- exposeInApi: n.exposeInApi ?? null
4089
- }));
4090
- }, [provisionsData]);
4091
- const relationships = useMemo(
4092
- () => getTableRelationships(currentTable, tables, provisions),
4093
- [currentTable, tables, provisions]
4094
- );
4095
- const handleOpenCreate = () => {
4096
- if (!currentTable) return;
4097
- stack.push({
4098
- id: "relationship-new",
4099
- title: "Create Relationship",
4100
- Component: RelationshipCard,
4101
- props: {
4102
- editingRelationship: null,
4103
- sourceTable: currentTable
4104
- },
4105
- width: 540
4106
- });
4107
- };
4108
- const handleOpenEdit = (rel) => {
4109
- const sourceTable = rel.sourceTable ?? currentTable;
4110
- if (!sourceTable) return;
4111
- stack.push({
4112
- id: `relationship-edit-${rel.constraint.id}`,
4113
- title: "Edit Relationship",
4114
- Component: RelationshipCard,
4115
- props: {
4116
- editingRelationship: rel,
4117
- sourceTable
4118
- },
4119
- width: 540
4120
- });
4121
- };
4122
- const handleDeleteRequest = (constraintId, constraintName) => {
4123
- setDeleteTarget({ id: constraintId, name: constraintName });
4124
- };
4125
- const handleDeleteConfirm = async () => {
4126
- if (!deleteTarget) return;
4127
- setIsDeleting(true);
4128
- try {
4129
- await deleteForeignKeyMutation.mutateAsync({ id: deleteTarget.id });
4130
- toast.success({ message: "Relationship deleted" });
4131
- setDeleteTarget(null);
4132
- } catch (error) {
4133
- toast.error({
4134
- message: "Failed to delete relationship",
4135
- description: error instanceof Error ? error.message : "An error occurred"
4136
- });
4137
- } finally {
4138
- setIsDeleting(false);
4139
- }
4140
- };
4141
- if (!currentTable) {
4142
- return /* @__PURE__ */ jsx(NoTableSelectedState, {});
4143
- }
4144
- const hasRelationships = relationships.length > 0;
4145
- function renderRelationshipCard(rel) {
4146
- const style = RELATIONSHIP_STYLES[rel.relationshipType];
4147
- const isM2M = !!rel.withTableName;
4148
- let junctionTargetFieldName;
4149
- let targetPkFieldName;
4150
- if (isM2M && rel.targetTable) {
4151
- const junction = rel.targetTable;
4152
- const actualTarget = tables.find((t) => t.name === rel.withTableName);
4153
- if (actualTarget) {
4154
- const junctionFk = (junction.constraints || []).find(
4155
- (c) => c.type === "foreign_key" && c.referencedTable === actualTarget.id
4156
- );
4157
- if (junctionFk) {
4158
- junctionTargetFieldName = junction.fields.find((f) => f.id === junctionFk.fields[0])?.name;
4159
- targetPkFieldName = actualTarget.fields.find((f) => f.id === junctionFk.referencedFields?.[0])?.name;
4160
- }
4161
- }
4162
- }
4163
- return /* @__PURE__ */ jsxs(
4164
- "div",
4165
- {
4166
- role: "button",
4167
- tabIndex: 0,
4168
- "data-testid": "relationship-row",
4169
- onClick: () => handleOpenEdit(rel),
4170
- onKeyDown: (event) => {
4171
- handleActivationKeyDown(event, () => handleOpenEdit(rel));
4172
- },
4173
- className: cn(
4174
- `group relative cursor-pointer rounded-xl border p-4 transition-[background-color,border-color,box-shadow,scale]
4175
- duration-150 ease-out motion-safe:active:scale-[0.96]`,
4176
- "border-border/60 hover:border-border/80 hover:bg-muted/30"
4177
- ),
4178
- children: [
4179
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
4180
- /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-2", children: [
4181
- /* @__PURE__ */ jsx(Link2, { className: "text-muted-foreground h-4 w-4 shrink-0" }),
4182
- /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-semibold", children: rel.constraint.name }),
4183
- /* @__PURE__ */ jsx(
4184
- "span",
4185
- {
4186
- className: cn(
4187
- "shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold tracking-wide uppercase",
4188
- style.bg,
4189
- style.text,
4190
- "border",
4191
- style.border
4192
- ),
4193
- children: style.label
4194
- }
4195
- )
4196
- ] }),
4197
- /* @__PURE__ */ jsx(
4198
- Button,
4199
- {
4200
- variant: "ghost",
4201
- size: "sm",
4202
- "aria-label": "Delete relationship",
4203
- className: "text-muted-foreground hover:text-destructive hover:bg-destructive/10 h-8 w-8 shrink-0 p-0",
4204
- onClick: (e) => {
4205
- e.stopPropagation();
4206
- handleDeleteRequest(rel.constraint.id, rel.constraint.name || "this relationship");
4207
- },
4208
- children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
4209
- }
4210
- )
4211
- ] }),
4212
- isM2M ? /* @__PURE__ */ jsxs("div", { className: "mt-3 space-y-2", children: [
4213
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
4214
- /* @__PURE__ */ jsxs("div", { className: "bg-background truncate rounded-md border px-3 py-1.5 font-mono text-sm", children: [
4215
- /* @__PURE__ */ jsx("span", { className: "text-foreground", children: rel.sourceTable?.name || "?" }),
4216
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "." }),
4217
- /* @__PURE__ */ jsx("span", { className: style.text, children: rel.sourceFieldName || "?" })
4218
- ] }),
4219
- /* @__PURE__ */ jsx("span", { className: style.text, children: /* @__PURE__ */ jsx(MiniConnector, { type: "many-to-many" }) }),
4220
- /* @__PURE__ */ jsx("div", { className: "bg-muted/50 truncate rounded-md border border-dashed px-3 py-1.5 font-mono text-sm", children: /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: rel.targetTable?.name || "?" }) }),
4221
- /* @__PURE__ */ jsx("span", { className: style.text, children: /* @__PURE__ */ jsx(MiniConnector, { type: "many-to-many" }) }),
4222
- /* @__PURE__ */ jsxs("div", { className: "bg-background truncate rounded-md border px-3 py-1.5 font-mono text-sm", children: [
4223
- /* @__PURE__ */ jsx("span", { className: "text-foreground", children: rel.withTableName }),
4224
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "." }),
4225
- /* @__PURE__ */ jsx("span", { className: style.text, children: targetPkFieldName || "id" })
4226
- ] })
4227
- ] }),
4228
- /* @__PURE__ */ jsxs("div", { className: "text-muted-foreground flex items-center gap-1.5 pl-1 font-mono text-[10px]", children: [
4229
- /* @__PURE__ */ jsx("span", { children: "via" }),
4230
- /* @__PURE__ */ jsx("span", { className: "bg-muted rounded px-1.5 py-0.5", children: rel.targetFieldName || "?" }),
4231
- /* @__PURE__ */ jsx("span", { children: "&" }),
4232
- /* @__PURE__ */ jsx("span", { className: "bg-muted rounded px-1.5 py-0.5", children: junctionTargetFieldName || "?" })
4233
- ] })
4234
- ] }) : /* @__PURE__ */ jsxs("div", { className: "mt-3 flex items-center gap-3", children: [
4235
- /* @__PURE__ */ jsxs("div", { className: "bg-background truncate rounded-md border px-3 py-1.5 font-mono text-sm", children: [
4236
- /* @__PURE__ */ jsx("span", { className: "text-foreground", children: rel.sourceTable?.name || "?" }),
4237
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "." }),
4238
- /* @__PURE__ */ jsx("span", { className: style.text, children: rel.sourceFieldName || "?" })
4239
- ] }),
4240
- /* @__PURE__ */ jsx("span", { className: style.text, children: /* @__PURE__ */ jsx(MiniConnector, { type: rel.relationshipType }) }),
4241
- /* @__PURE__ */ jsxs("div", { className: "bg-background truncate rounded-md border px-3 py-1.5 font-mono text-sm", children: [
4242
- /* @__PURE__ */ jsx("span", { className: "text-foreground", children: rel.targetTable?.name || "?" }),
4243
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "." }),
4244
- /* @__PURE__ */ jsx("span", { className: style.text, children: rel.targetFieldName || "?" })
4245
- ] })
4246
- ] }),
4247
- /* @__PURE__ */ jsx("div", { className: "mt-3 flex items-center justify-between gap-4 border-t pt-3", children: /* @__PURE__ */ jsxs("div", { className: "text-muted-foreground flex items-center gap-1.5 text-xs", children: [
4248
- /* @__PURE__ */ jsx(CornerDownRight, { className: "h-3 w-3" }),
4249
- /* @__PURE__ */ jsx("span", { children: "On Delete:" }),
4250
- /* @__PURE__ */ jsx("span", { className: "text-foreground/70 font-medium", children: ForeignKeyActionLabels[rel.constraint.onDelete ?? ForeignKeyActions.NO_ACTION] })
4251
- ] }) })
4252
- ]
4253
- },
4254
- rel.constraint.id
4255
- );
4256
- }
4257
- return /* @__PURE__ */ jsxs(Fragment, { children: [
4258
- /* @__PURE__ */ jsx(
4259
- "div",
4260
- {
4261
- "data-chat-component": "relationships-view",
4262
- "data-chat-relationship-count": String(relationships.length),
4263
- className: "flex min-h-0 flex-1 flex-col overflow-auto p-6",
4264
- children: !hasRelationships ? /* @__PURE__ */ jsx(RelationshipEmptyState, { onCreateClick: handleOpenCreate, tableName: currentTable.name }) : /* @__PURE__ */ jsxs("div", { className: "mx-auto w-full min-w-80 max-w-4xl space-y-6", children: [
4265
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-4", children: [
4266
- /* @__PURE__ */ jsxs("div", { children: [
4267
- /* @__PURE__ */ jsx("h2", { className: "text-balance text-xl font-semibold tracking-tight", children: "Relationships" }),
4268
- /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground mt-1 text-sm", children: [
4269
- relationships.length,
4270
- " connection",
4271
- relationships.length !== 1 ? "s" : "",
4272
- " for",
4273
- " ",
4274
- /* @__PURE__ */ jsx("code", { className: "bg-muted rounded px-1.5 py-0.5 font-mono text-xs", children: currentTable.name })
4275
- ] })
4276
- ] }),
4277
- /* @__PURE__ */ jsxs(Button, { onClick: handleOpenCreate, children: [
4278
- /* @__PURE__ */ jsx(Link2, { className: "mr-2 h-4 w-4" }),
4279
- "Add Relationship"
4280
- ] })
4281
- ] }),
4282
- /* @__PURE__ */ jsx("div", { className: "space-y-3", children: relationships.map(renderRelationshipCard) })
4283
- ] })
4284
- }
4285
- ),
4286
- /* @__PURE__ */ jsx(
4287
- DeleteConfirmDialog,
4288
- {
4289
- entityType: "Relationship",
4290
- entityName: deleteTarget?.name ?? null,
4291
- open: !!deleteTarget,
4292
- onOpenChange: () => setDeleteTarget(null),
4293
- onConfirm: handleDeleteConfirm,
4294
- isPending: isDeleting
4295
- }
4296
- )
4297
- ] });
4298
- }
4299
-
4300
- export { RelationshipsView, useCreateForeignKey, useCreateManyToMany, useDeleteForeignKey, useRelationProvision, useUpdateForeignKey };
4301
- //# sourceMappingURL=relationships.js.map
4302
- //# sourceMappingURL=relationships.js.map
4
+ export { RelationshipsView, useCreateForeignKey, useCreateManyToMany, useDeleteForeignKey, useRelationProvision, useUpdateForeignKey };