@constructive-io/schema-builder 0.2.0 → 0.4.0

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