@constructive-io/sheets 0.13.1 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +10 -1
  2. package/dist/advanced.cjs +554 -716
  3. package/dist/advanced.cjs.map +1 -1
  4. package/dist/advanced.d.cts +2 -2
  5. package/dist/advanced.d.ts +2 -2
  6. package/dist/advanced.js +4 -4
  7. package/dist/auth.cjs.map +1 -1
  8. package/dist/auth.js +2 -2
  9. package/dist/{chunk-PZL2BCWF.js → chunk-6Y7CZ5VS.js} +2 -2
  10. package/dist/chunk-6Y7CZ5VS.js.map +1 -0
  11. package/dist/{chunk-AYMXT3ME.js → chunk-BGL6EBTE.js} +108 -202
  12. package/dist/chunk-BGL6EBTE.js.map +1 -0
  13. package/dist/{chunk-MXVNIKES.js → chunk-BYAYBXVB.js} +2 -2
  14. package/dist/{chunk-5QPNOKMA.js → chunk-ER3FIDK7.js} +444 -458
  15. package/dist/chunk-ER3FIDK7.js.map +1 -0
  16. package/dist/chunk-GZM2CSTR.js +279 -0
  17. package/dist/chunk-GZM2CSTR.js.map +1 -0
  18. package/dist/{chunk-H5HR5HUJ.js → chunk-YJZFHL2D.js} +1 -1
  19. package/dist/chunk-YJZFHL2D.js.map +1 -0
  20. package/dist/{date-editor-ZFNDKYBD.js → date-editor-G26WKILO.js} +2 -2
  21. package/dist/{grid-cell-types-Pbe2m2tE.d.ts → grid-cell-types-C2-ocDS7.d.cts} +45 -5
  22. package/dist/{grid-cell-types-Pbe2m2tE.d.cts → grid-cell-types-C2-ocDS7.d.ts} +45 -5
  23. package/dist/index.cjs +782 -637
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +106 -112
  26. package/dist/index.d.ts +106 -112
  27. package/dist/index.js +234 -134
  28. package/dist/index.js.map +1 -1
  29. package/dist/{sheets-context-Cu3Ec_ca.d.ts → sheets-context-CHUVJCff.d.ts} +32 -31
  30. package/dist/{sheets-context-CY1RmDKL.d.cts → sheets-context-C_MkTxXm.d.cts} +32 -31
  31. package/dist/testing.cjs +121 -87
  32. package/dist/testing.cjs.map +1 -1
  33. package/dist/testing.d.cts +2 -2
  34. package/dist/testing.d.ts +2 -2
  35. package/dist/testing.js +16 -4
  36. package/dist/testing.js.map +1 -1
  37. package/package.json +5 -4
  38. package/dist/chunk-5QPNOKMA.js.map +0 -1
  39. package/dist/chunk-AYMXT3ME.js.map +0 -1
  40. package/dist/chunk-H5HR5HUJ.js.map +0 -1
  41. package/dist/chunk-PZL2BCWF.js.map +0 -1
  42. package/dist/chunk-ZKANUG3F.js +0 -123
  43. package/dist/chunk-ZKANUG3F.js.map +0 -1
  44. /package/dist/{chunk-MXVNIKES.js.map → chunk-BYAYBXVB.js.map} +0 -0
  45. /package/dist/{date-editor-ZFNDKYBD.js.map → date-editor-G26WKILO.js.map} +0 -0
@@ -0,0 +1,279 @@
1
+ "use client";
2
+ import {
3
+ callUploadOp,
4
+ discoverUploadCapability,
5
+ fetchDownloadUrl,
6
+ presignedPut,
7
+ sha256HexFromBuffer,
8
+ sheetsQueryKeys
9
+ } from "./chunk-BGL6EBTE.js";
10
+ import {
11
+ getStoredToken
12
+ } from "./chunk-4EZ6A23C.js";
13
+ import {
14
+ SheetsContext,
15
+ SheetsStoreContext,
16
+ createSheetsStore
17
+ } from "./chunk-YJZFHL2D.js";
18
+ import {
19
+ setSheetsLocale
20
+ } from "./chunk-GGECS2BP.js";
21
+ import {
22
+ setSheetsLogger
23
+ } from "./chunk-X7DHTSOX.js";
24
+
25
+ // src/context/sheets-execute.ts
26
+ import { print } from "graphql";
27
+ import { ConstructiveError, createError } from "@constructive-io/data";
28
+ import { ConstructiveError as ConstructiveError2 } from "@constructive-io/data";
29
+ function documentToString(document) {
30
+ if (typeof document === "string") return document;
31
+ if (document instanceof String) return document.toString();
32
+ if (document && typeof document === "object" && "kind" in document) {
33
+ return print(document);
34
+ }
35
+ if (document === null || document === void 0) {
36
+ throw createError.badRequest("Invalid GraphQL document: null or undefined");
37
+ }
38
+ return String(document);
39
+ }
40
+ function hasAuthMessage(message) {
41
+ const normalized = String(message ?? "").toLowerCase();
42
+ return normalized.includes("unauthenticated") || normalized.includes("unauthorized") || normalized.includes("authentication");
43
+ }
44
+ function parseGraphQLResponse(response, onAuthError) {
45
+ if (!response.errors?.length) return null;
46
+ const error = response.errors[0];
47
+ const code = error.extensions?.code;
48
+ const message = error.message || "GraphQL query failed";
49
+ if (code === "UNAUTHENTICATED" || hasAuthMessage(message)) {
50
+ onAuthError?.();
51
+ return createError.unauthorized("Authentication required. Please log in again.");
52
+ }
53
+ if (code === "FORBIDDEN") {
54
+ return createError.forbidden("You do not have permission to perform this action.");
55
+ }
56
+ return createError.graphql(message, code);
57
+ }
58
+ function createSheetsExecute(config, getToken) {
59
+ return async (document, variables) => {
60
+ const url = config.endpoint;
61
+ if (!url) {
62
+ throw createError.badRequest("No GraphQL endpoint configured.");
63
+ }
64
+ const token = getToken();
65
+ const headers = {
66
+ "Content-Type": "application/json",
67
+ Accept: "application/graphql-response+json"
68
+ };
69
+ if (token) {
70
+ headers["Authorization"] = `Bearer ${token}`;
71
+ }
72
+ let response;
73
+ try {
74
+ response = await fetch(url, {
75
+ method: "POST",
76
+ headers,
77
+ body: JSON.stringify({
78
+ query: documentToString(document),
79
+ ...variables !== void 0 && { variables }
80
+ })
81
+ });
82
+ } catch (error) {
83
+ throw createError.network(error instanceof Error ? error : void 0);
84
+ }
85
+ if (!response.ok) {
86
+ const { status, statusText } = response;
87
+ if (status === 401) {
88
+ config.onAuthError?.();
89
+ throw createError.unauthorized("Authentication required. Please log in again.");
90
+ }
91
+ if (status === 403) {
92
+ throw createError.forbidden("You do not have permission to perform this action.");
93
+ }
94
+ if (status === 404) {
95
+ throw createError.notFound("The requested endpoint does not exist.");
96
+ }
97
+ try {
98
+ const body = await response.json();
99
+ if (body.errors?.length) {
100
+ throw createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);
101
+ }
102
+ } catch (e) {
103
+ if (e instanceof ConstructiveError) throw e;
104
+ }
105
+ throw createError.badRequest(`Request failed: ${status} ${statusText}`);
106
+ }
107
+ const result = await response.json();
108
+ const graphqlError = parseGraphQLResponse(result, config.onAuthError);
109
+ if (graphqlError) {
110
+ throw graphqlError;
111
+ }
112
+ return result.data;
113
+ };
114
+ }
115
+ function resolveStorageTransport(config, getToken) {
116
+ const endpoint = config.storage?.endpoint;
117
+ if (!endpoint) return void 0;
118
+ return {
119
+ endpoint,
120
+ execute: config.storage?.execute ?? createSheetsExecute({ ...config, endpoint }, getToken)
121
+ };
122
+ }
123
+ function createSheetsUpload(config, getToken) {
124
+ const transport = resolveStorageTransport(config, getToken) ?? {
125
+ endpoint: config.endpoint,
126
+ execute: config.execute ?? createSheetsExecute(config, getToken)
127
+ };
128
+ return createPresignedSheetsUpload(transport, config.upload?.bucketKey);
129
+ }
130
+ function createPresignedSheetsUpload({ endpoint, execute }, bucketKey) {
131
+ return async (file, _path, options) => {
132
+ if (!endpoint) {
133
+ throw createError.badRequest("No GraphQL endpoint configured.");
134
+ }
135
+ const cap = await discoverUploadCapability(endpoint, execute);
136
+ if (!cap.hasFileProjection) {
137
+ throw createError.badRequest("Uploads require a storage mutation that returns a file projection.");
138
+ }
139
+ const contentType = file.type || "application/octet-stream";
140
+ const buffer = await file.arrayBuffer();
141
+ const contentHash = await sha256HexFromBuffer(buffer);
142
+ const payload = await callUploadOp(execute, cap, {
143
+ bucketKey,
144
+ contentHash,
145
+ contentType,
146
+ size: file.size,
147
+ filename: file.name
148
+ });
149
+ if (!payload.deduplicated) {
150
+ if (!payload.uploadUrl) {
151
+ throw createError.badRequest("Upload failed: server returned no uploadUrl for a non-deduplicated file.");
152
+ }
153
+ await presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);
154
+ } else {
155
+ options?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });
156
+ }
157
+ const result = {
158
+ file: { ...payload.file, filename: payload.file.filename ?? file.name }
159
+ };
160
+ if (!cap.download) return result;
161
+ try {
162
+ return { ...result, url: await fetchDownloadUrl(execute, cap.download, payload.fileId) };
163
+ } catch {
164
+ return result;
165
+ }
166
+ };
167
+ }
168
+
169
+ // src/context/sheets-provider.tsx
170
+ import { useEffect, useId, useMemo, useRef } from "react";
171
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
172
+ import { useStore as useZustandStore } from "zustand";
173
+ import { jsx } from "react/jsx-runtime";
174
+ var unavailableUpload = async () => {
175
+ throw new Error("Uploads need a storage endpoint");
176
+ };
177
+ function SheetsProvider({ config, children }) {
178
+ const providerInstanceId = useId();
179
+ const storeRef = useRef(null);
180
+ if (!storeRef.current) {
181
+ storeRef.current = createSheetsStore();
182
+ }
183
+ const store = storeRef.current;
184
+ const standaloneIdentityKey = useZustandStore(store, (state) => state.identityKey);
185
+ const standaloneAccessToken = useZustandStore(store, (state) => state.accessToken);
186
+ setSheetsLogger(config.logger);
187
+ setSheetsLocale(config.locale);
188
+ useEffect(() => {
189
+ setSheetsLogger(config.logger);
190
+ setSheetsLocale(config.locale);
191
+ }, [config.logger, config.locale]);
192
+ useEffect(() => {
193
+ const store2 = storeRef.current?.getState();
194
+ if (!store2) return;
195
+ if (config.auth.mode !== "standalone") {
196
+ store2.setUnauthenticated();
197
+ return;
198
+ }
199
+ const databaseId = config.databaseId || "default";
200
+ const stored = getStoredToken(databaseId);
201
+ if (!stored) {
202
+ store2.setUnauthenticated();
203
+ return;
204
+ }
205
+ const expiresAt = new Date(stored.expiresAt);
206
+ if (expiresAt > /* @__PURE__ */ new Date()) {
207
+ store2.setAuthenticated(stored.accessToken, stored.expiresAt, stored.identityKey ?? null);
208
+ return;
209
+ }
210
+ store2.setUnauthenticated();
211
+ }, [config.auth.mode, config.databaseId]);
212
+ const internalQueryClient = useMemo(
213
+ () => new QueryClient({
214
+ defaultOptions: {
215
+ queries: {
216
+ staleTime: 5 * 60 * 1e3,
217
+ gcTime: 30 * 60 * 1e3,
218
+ retry: 1
219
+ }
220
+ }
221
+ }),
222
+ []
223
+ );
224
+ const queryClient = config.queryClient ?? internalQueryClient;
225
+ const getToken = useMemo(() => {
226
+ if (config.auth.mode === "embedded") {
227
+ return config.auth.getToken;
228
+ }
229
+ return () => store.getState().accessToken ?? null;
230
+ }, [config.auth, store]);
231
+ const execute = useMemo(() => {
232
+ if (config.execute) return config.execute;
233
+ return createSheetsExecute(config, getToken);
234
+ }, [config, getToken]);
235
+ const storage = useMemo(() => resolveStorageTransport(config, getToken), [config, getToken]);
236
+ const bucketKey = config.upload?.bucketKey;
237
+ const executeUpload = useMemo(() => {
238
+ if (config.executeUpload) return config.executeUpload;
239
+ return storage ? createPresignedSheetsUpload(storage, bucketKey) : unavailableUpload;
240
+ }, [config.executeUpload, storage, bucketKey]);
241
+ const canUpload = Boolean(config.executeUpload || storage);
242
+ const configuredIdentityKey = config.auth.mode === "embedded" ? config.auth.getIdentityKey?.() ?? null : standaloneIdentityKey;
243
+ const activeToken = config.auth.mode === "embedded" ? config.auth.getToken() : standaloneAccessToken;
244
+ const authGenerationRef = useRef({ mode: config.auth.mode, token: activeToken, generation: 0 });
245
+ if (authGenerationRef.current.mode !== config.auth.mode || authGenerationRef.current.token !== activeToken) {
246
+ authGenerationRef.current = {
247
+ mode: config.auth.mode,
248
+ token: activeToken,
249
+ generation: authGenerationRef.current.generation + 1
250
+ };
251
+ }
252
+ const identityKey = configuredIdentityKey ?? `anonymous:${providerInstanceId}:${authGenerationRef.current.generation}`;
253
+ const scopeKey = useMemo(
254
+ () => ({
255
+ databaseId: config.databaseId ?? null,
256
+ endpoint: config.endpoint,
257
+ identityKey
258
+ }),
259
+ [config.databaseId, config.endpoint, identityKey]
260
+ );
261
+ useEffect(() => {
262
+ return () => {
263
+ void queryClient.cancelQueries({ queryKey: sheetsQueryKeys.scope(scopeKey) });
264
+ };
265
+ }, [queryClient, scopeKey]);
266
+ const contextValue = useMemo(
267
+ () => ({ config, execute, executeUpload, storage, canUpload, scopeKey }),
268
+ [config, execute, executeUpload, storage, canUpload, scopeKey]
269
+ );
270
+ return /* @__PURE__ */ jsx(QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ jsx(SheetsStoreContext.Provider, { value: store, children: /* @__PURE__ */ jsx(SheetsContext.Provider, { value: contextValue, children }) }) });
271
+ }
272
+
273
+ export {
274
+ createSheetsExecute,
275
+ createSheetsUpload,
276
+ ConstructiveError2 as ConstructiveError,
277
+ SheetsProvider
278
+ };
279
+ //# sourceMappingURL=chunk-GZM2CSTR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context/sheets-execute.ts","../src/context/sheets-provider.tsx"],"sourcesContent":["import type { DocumentNode } from 'graphql';\nimport { print } from 'graphql';\n\nimport { ConstructiveError, createError, TypedDocumentString } from '@constructive-io/data';\n\nimport type { SheetsConfig, SheetsStorageTransport } from './sheets-context';\nimport {\n\tcallUploadOp,\n\tdiscoverUploadCapability,\n\tfetchDownloadUrl,\n\tpresignedPut,\n\tsha256HexFromBuffer,\n} from './sheets-upload-presigned';\n\n// ============================================================================\n// Types\n// ============================================================================\n\ntype ExecutableDocument = TypedDocumentString<any, any> | DocumentNode | string | unknown;\n\nexport type SheetsExecuteFn = <T = unknown>(\n\tdocument: ExecutableDocument,\n\tvariables?: Record<string, unknown>,\n) => Promise<T>;\n\n/** Durable file metadata for image and upload columns. */\nexport interface SheetsFileValue {\n\tid: string;\n\tkey: string;\n\tbucket_id: string;\n\tmime: string;\n\tsize: number;\n\tfilename: string;\n\t/** Public URL supplied by storage, when available. */\n\turl?: string;\n}\n\nexport interface SheetsUploadResult {\n\tfile: SheetsFileValue;\n\t/** Optional download URL for immediate use. It can expire. */\n\turl?: string;\n}\n\n/**\n * Optional upload metadata carried through the seam (third arg). Lets an\n * injected `executeUpload` see the destination field/row and report progress.\n * All fields optional, so existing `(file, path?)` callers stay valid.\n */\nexport interface SheetsUploadOptions {\n\ttableName?: string;\n\tfieldName?: string;\n\trecordId?: string | number;\n\tonProgress?: (progress: { loaded: number; total: number; percentage: number }) => void;\n}\n\nexport type SheetsUploadFn = (\n\tfile: File,\n\tpath?: string,\n\toptions?: SheetsUploadOptions,\n) => Promise<SheetsUploadResult>;\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction documentToString(document: ExecutableDocument): string {\n\tif (typeof document === 'string') return document;\n\tif (document instanceof String) return document.toString();\n\tif (document && typeof document === 'object' && 'kind' in (document as DocumentNode)) {\n\t\treturn print(document as DocumentNode);\n\t}\n\tif (document === null || document === undefined) {\n\t\tthrow createError.badRequest('Invalid GraphQL document: null or undefined');\n\t}\n\treturn String(document);\n}\n\n// ============================================================================\n// GraphQL Response Parsing\n// ============================================================================\n\ninterface GraphQLResponseError {\n\tmessage: string;\n\textensions?: { code?: string };\n}\n\ninterface GraphQLResponse {\n\tdata?: unknown;\n\terrors?: GraphQLResponseError[];\n}\n\nfunction hasAuthMessage(message: string | undefined): boolean {\n\tconst normalized = String(message ?? '').toLowerCase();\n\treturn (\n\t\tnormalized.includes('unauthenticated') ||\n\t\tnormalized.includes('unauthorized') ||\n\t\tnormalized.includes('authentication')\n\t);\n}\n\nfunction parseGraphQLResponse(response: GraphQLResponse, onAuthError?: () => void): ConstructiveError | null {\n\tif (!response.errors?.length) return null;\n\n\tconst error = response.errors[0];\n\tconst code = error.extensions?.code;\n\tconst message = error.message || 'GraphQL query failed';\n\n\tif (code === 'UNAUTHENTICATED' || hasAuthMessage(message)) {\n\t\tonAuthError?.();\n\t\treturn createError.unauthorized('Authentication required. Please log in again.');\n\t}\n\n\tif (code === 'FORBIDDEN') {\n\t\treturn createError.forbidden('You do not have permission to perform this action.');\n\t}\n\n\treturn createError.graphql(message, code);\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\nexport function createSheetsExecute(\n\tconfig: SheetsConfig,\n\tgetToken: () => string | null,\n): SheetsExecuteFn {\n\treturn async <T = unknown>(\n\t\tdocument: ExecutableDocument,\n\t\tvariables?: Record<string, unknown>,\n\t): Promise<T> => {\n\t\tconst url = config.endpoint;\n\t\tif (!url) {\n\t\t\tthrow createError.badRequest('No GraphQL endpoint configured.');\n\t\t}\n\n\t\tconst token = getToken();\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAccept: 'application/graphql-response+json',\n\t\t};\n\t\tif (token) {\n\t\t\theaders['Authorization'] = `Bearer ${token}`;\n\t\t}\n\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await fetch(url, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders,\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tquery: documentToString(document),\n\t\t\t\t\t...(variables !== undefined && { variables }),\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow createError.network(error instanceof Error ? error : undefined);\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\tconst { status, statusText } = response;\n\t\t\tif (status === 401) {\n\t\t\t\tconfig.onAuthError?.();\n\t\t\t\tthrow createError.unauthorized('Authentication required. Please log in again.');\n\t\t\t}\n\t\t\tif (status === 403) {\n\t\t\t\tthrow createError.forbidden('You do not have permission to perform this action.');\n\t\t\t}\n\t\t\tif (status === 404) {\n\t\t\t\tthrow createError.notFound('The requested endpoint does not exist.');\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst body = await response.json();\n\t\t\t\tif (body.errors?.length) {\n\t\t\t\t\tthrow createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof ConstructiveError) throw e;\n\t\t\t}\n\t\t\tthrow createError.badRequest(`Request failed: ${status} ${statusText}`);\n\t\t}\n\n\t\tconst result: GraphQLResponse = await response.json();\n\t\tconst graphqlError = parseGraphQLResponse(result, config.onAuthError);\n\t\tif (graphqlError) {\n\t\t\tthrow graphqlError;\n\t\t}\n\n\t\treturn result.data as T;\n\t};\n}\n\nexport function resolveStorageTransport(\n\tconfig: SheetsConfig,\n\tgetToken: () => string | null,\n): SheetsStorageTransport | undefined {\n\tconst endpoint = config.storage?.endpoint;\n\tif (!endpoint) return undefined;\n\n\treturn {\n\t\tendpoint,\n\t\texecute: config.storage?.execute ?? createSheetsExecute({ ...config, endpoint }, getToken),\n\t};\n}\n\n/** Creates an uploader for storage. Direct callers may use the supplied endpoint as storage. */\nexport function createSheetsUpload(config: SheetsConfig, getToken: () => string | null): SheetsUploadFn {\n\tconst transport = resolveStorageTransport(config, getToken) ?? {\n\t\tendpoint: config.endpoint,\n\t\texecute: config.execute ?? createSheetsExecute(config, getToken),\n\t};\n\treturn createPresignedSheetsUpload(transport, config.upload?.bucketKey);\n}\n\nexport function createPresignedSheetsUpload(\n\t{ endpoint, execute }: SheetsStorageTransport,\n\tbucketKey?: string,\n): SheetsUploadFn {\n\treturn async (file, _path, options) => {\n\t\tif (!endpoint) {\n\t\t\tthrow createError.badRequest('No GraphQL endpoint configured.');\n\t\t}\n\n\t\tconst cap = await discoverUploadCapability(endpoint, execute);\n\t\tif (!cap.hasFileProjection) {\n\t\t\tthrow createError.badRequest('Uploads require a storage mutation that returns a file projection.');\n\t\t}\n\n\t\tconst contentType = file.type || 'application/octet-stream';\n\t\t// Read the file once for both hashing and the PUT body.\n\t\tconst buffer = await file.arrayBuffer();\n\t\tconst contentHash = await sha256HexFromBuffer(buffer);\n\t\tconst payload = await callUploadOp(execute, cap, {\n\t\t\tbucketKey,\n\t\t\tcontentHash,\n\t\t\tcontentType,\n\t\t\tsize: file.size,\n\t\t\tfilename: file.name,\n\t\t});\n\n\t\tif (!payload.deduplicated) {\n\t\t\tif (!payload.uploadUrl) {\n\t\t\t\tthrow createError.badRequest('Upload failed: server returned no uploadUrl for a non-deduplicated file.');\n\t\t\t}\n\t\t\t// The server expires rows whose PUT fails.\n\t\t\tawait presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);\n\t\t} else {\n\t\t\toptions?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });\n\t\t}\n\n\t\tconst result: SheetsUploadResult = {\n\t\t\tfile: { ...payload.file, filename: payload.file.filename ?? file.name },\n\t\t};\n\t\tif (!cap.download) return result;\n\n\t\ttry {\n\t\t\treturn { ...result, url: await fetchDownloadUrl(execute, cap.download, payload.fileId) };\n\t\t} catch {\n\t\t\t// The upload succeeded. The download URL can be requested again later.\n\t\t\treturn result;\n\t\t}\n\t};\n}\n\nexport { ConstructiveError } from '@constructive-io/data';\n","import { useEffect, useId, useMemo, useRef } from 'react';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\nimport { useStore as useZustandStore, type StoreApi } from 'zustand';\n\nimport { SheetsContext, type SheetsConfig, type SheetsContextValue, type SheetsScopeKey } from './sheets-context';\nimport {\n\tcreatePresignedSheetsUpload,\n\tcreateSheetsExecute,\n\tresolveStorageTransport,\n\ttype SheetsExecuteFn,\n\ttype SheetsUploadFn,\n} from './sheets-execute';\nimport { createSheetsStore, SheetsStoreContext, type SheetsStoreState } from '../store/sheets-store';\nimport { getStoredToken } from '../auth/utils/token-store';\nimport { setSheetsLogger } from '../utils/sheets-logger';\nimport { setSheetsLocale } from '../utils/sheets-i18n';\nimport { sheetsQueryKeys } from '../hooks/query-keys';\n\ninterface SheetsProviderProps {\n\tconfig: SheetsConfig;\n\tchildren: React.ReactNode;\n}\n\nconst unavailableUpload: SheetsUploadFn = async () => {\n\tthrow new Error('Uploads need a storage endpoint');\n};\n\nexport function SheetsProvider({ config, children }: SheetsProviderProps) {\n\tconst providerInstanceId = useId();\n\t// Create store once\n\tconst storeRef = useRef<StoreApi<SheetsStoreState> | null>(null);\n\tif (!storeRef.current) {\n\t\tstoreRef.current = createSheetsStore();\n\t}\n\tconst store = storeRef.current;\n\tconst standaloneIdentityKey = useZustandStore(store, (state) => state.identityKey);\n\tconst standaloneAccessToken = useZustandStore(store, (state) => state.accessToken);\n\n\t// Install the host logger + locale synchronously so they apply before first paint.\n\tsetSheetsLogger(config.logger);\n\tsetSheetsLocale(config.locale);\n\n\t// Keep the module singletons in sync if the host swaps them across renders.\n\tuseEffect(() => {\n\t\tsetSheetsLogger(config.logger);\n\t\tsetSheetsLocale(config.locale);\n\t}, [config.logger, config.locale]);\n\n\t// Restore persisted token for standalone mode\n\tuseEffect(() => {\n\t\tconst store = storeRef.current?.getState();\n\t\tif (!store) return;\n\n\t\tif (config.auth.mode !== 'standalone') {\n\t\t\t// Prevent leaking stale standalone tokens when switching auth modes.\n\t\t\tstore.setUnauthenticated();\n\t\t\treturn;\n\t\t}\n\t\tconst databaseId = config.databaseId || 'default';\n\t\tconst stored = getStoredToken(databaseId);\n\t\tif (!stored) {\n\t\t\tstore.setUnauthenticated();\n\t\t\treturn;\n\t\t}\n\n\t\t// Only restore if not expired\n\t\tconst expiresAt = new Date(stored.expiresAt);\n\t\tif (expiresAt > new Date()) {\n\t\t\tstore.setAuthenticated(stored.accessToken, stored.expiresAt, stored.identityKey ?? null);\n\t\t\treturn;\n\t\t}\n\n\t\tstore.setUnauthenticated();\n\t}, [config.auth.mode, config.databaseId]);\n\n\t// Always provide a QueryClient context. If consumer injects one, reuse it.\n\tconst internalQueryClient = useMemo(\n\t\t() =>\n\t\t\tnew QueryClient({\n\t\t\t\tdefaultOptions: {\n\t\t\t\t\tqueries: {\n\t\t\t\t\t\tstaleTime: 5 * 60 * 1000,\n\t\t\t\t\t\tgcTime: 30 * 60 * 1000,\n\t\t\t\t\t\tretry: 1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t[],\n\t);\n\tconst queryClient = config.queryClient ?? internalQueryClient;\n\n\t// Token getter: embedded mode uses config.auth.getToken, standalone uses store\n\tconst getToken = useMemo(() => {\n\t\tif (config.auth.mode === 'embedded') {\n\t\t\treturn config.auth.getToken;\n\t\t}\n\t\t// Standalone: read from store\n\t\treturn () => store.getState().accessToken ?? null;\n\t}, [config.auth, store]);\n\n\t// Create execute function\n\tconst execute: SheetsExecuteFn = useMemo(() => {\n\t\tif (config.execute) return config.execute;\n\t\treturn createSheetsExecute(config, getToken);\n\t}, [config, getToken]);\n\n\tconst storage = useMemo(() => resolveStorageTransport(config, getToken), [config, getToken]);\n\tconst bucketKey = config.upload?.bucketKey;\n\tconst executeUpload: SheetsUploadFn = useMemo(() => {\n\t\tif (config.executeUpload) return config.executeUpload;\n\t\treturn storage ? createPresignedSheetsUpload(storage, bucketKey) : unavailableUpload;\n\t}, [config.executeUpload, storage, bucketKey]);\n\tconst canUpload = Boolean(config.executeUpload || storage);\n\n\tconst configuredIdentityKey =\n\t\tconfig.auth.mode === 'embedded'\n\t\t\t? (config.auth.getIdentityKey?.() ?? null)\n\t\t\t: standaloneIdentityKey;\n\tconst activeToken = config.auth.mode === 'embedded' ? config.auth.getToken() : standaloneAccessToken;\n\tconst authGenerationRef = useRef({ mode: config.auth.mode, token: activeToken, generation: 0 });\n\tif (\n\t\tauthGenerationRef.current.mode !== config.auth.mode ||\n\t\tauthGenerationRef.current.token !== activeToken\n\t) {\n\t\tauthGenerationRef.current = {\n\t\t\tmode: config.auth.mode,\n\t\t\ttoken: activeToken,\n\t\t\tgeneration: authGenerationRef.current.generation + 1,\n\t\t};\n\t}\n\t// If an older host has not supplied a user id, isolate each observed auth\n\t// token generation behind an opaque provider-local key. Tokens never enter\n\t// TanStack Query keys or devtools.\n\tconst identityKey =\n\t\tconfiguredIdentityKey ??\n\t\t`anonymous:${providerInstanceId}:${authGenerationRef.current.generation}`;\n\n\t// Scope metadata, rows, and mutations by endpoint and non-secret identity.\n\tconst scopeKey: SheetsScopeKey = useMemo(\n\t\t() => ({\n\t\t\tdatabaseId: config.databaseId ?? null,\n\t\t\tendpoint: config.endpoint,\n\t\t\tidentityKey,\n\t\t}),\n\t\t[config.databaseId, config.endpoint, identityKey],\n\t);\n\n\t// Changing database, endpoint, or user invalidates in-flight work from the\n\t// previous scope. Its cached data remains isolated under its old key.\n\tuseEffect(() => {\n\t\treturn () => {\n\t\t\tvoid queryClient.cancelQueries({ queryKey: sheetsQueryKeys.scope(scopeKey) });\n\t\t};\n\t}, [queryClient, scopeKey]);\n\n\tconst contextValue: SheetsContextValue = useMemo(\n\t\t() => ({ config, execute, executeUpload, storage, canUpload, scopeKey }),\n\t\t[config, execute, executeUpload, storage, canUpload, scopeKey],\n\t);\n\n\treturn (\n\t\t<QueryClientProvider client={queryClient}>\n\t\t\t<SheetsStoreContext.Provider value={store}>\n\t\t\t\t<SheetsContext.Provider value={contextValue}>{children}</SheetsContext.Provider>\n\t\t\t</SheetsStoreContext.Provider>\n\t\t</QueryClientProvider>\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,aAAa;AAEtB,SAAS,mBAAmB,mBAAwC;AAqQpE,SAAS,qBAAAA,0BAAyB;AAvMlC,SAAS,iBAAiB,UAAsC;AAC/D,MAAI,OAAO,aAAa,SAAU,QAAO;AACzC,MAAI,oBAAoB,OAAQ,QAAO,SAAS,SAAS;AACzD,MAAI,YAAY,OAAO,aAAa,YAAY,UAAW,UAA2B;AACrF,WAAO,MAAM,QAAwB;AAAA,EACtC;AACA,MAAI,aAAa,QAAQ,aAAa,QAAW;AAChD,UAAM,YAAY,WAAW,6CAA6C;AAAA,EAC3E;AACA,SAAO,OAAO,QAAQ;AACvB;AAgBA,SAAS,eAAe,SAAsC;AAC7D,QAAM,aAAa,OAAO,WAAW,EAAE,EAAE,YAAY;AACrD,SACC,WAAW,SAAS,iBAAiB,KACrC,WAAW,SAAS,cAAc,KAClC,WAAW,SAAS,gBAAgB;AAEtC;AAEA,SAAS,qBAAqB,UAA2B,aAAoD;AAC5G,MAAI,CAAC,SAAS,QAAQ,OAAQ,QAAO;AAErC,QAAM,QAAQ,SAAS,OAAO,CAAC;AAC/B,QAAM,OAAO,MAAM,YAAY;AAC/B,QAAM,UAAU,MAAM,WAAW;AAEjC,MAAI,SAAS,qBAAqB,eAAe,OAAO,GAAG;AAC1D,kBAAc;AACd,WAAO,YAAY,aAAa,+CAA+C;AAAA,EAChF;AAEA,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AQ,SAAS,eAAe,SAAS,WAAW,QAAQ;AAAA,EAC9D;AAEA,SACC,oBAAC,uBAAoB,QAAQ,aAC5B,8BAAC,mBAAmB,UAAnB,EAA4B,OAAO,OACnC,8BAAC,cAAc,UAAd,EAAuB,OAAO,cAAe,UAAS,GACxD,GACD;AAEF;","names":["ConstructiveError","store"]}
@@ -668,4 +668,4 @@ export {
668
668
  useSheetsStore,
669
669
  useSheetsStoreApi
670
670
  };
671
- //# sourceMappingURL=chunk-H5HR5HUJ.js.map
671
+ //# sourceMappingURL=chunk-YJZFHL2D.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context/sheets-context.ts","../src/store/draft-rows-slice.ts","../src/store/relation-info-slice.ts","../src/utils/relation-utils.ts","../src/store/sheets-store.ts"],"sourcesContent":["import { createContext, useContext } from 'react';\nimport type { QueryClient } from '@tanstack/react-query';\n\nimport type { SheetsExecuteFn, SheetsUploadFn } from './sheets-execute';\nimport type { SheetsLogger } from '../utils/sheets-logger';\nimport type { CellTypePlugin } from '../cell-types/define-cell-type';\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\n\nexport interface SheetsAuthEmbedded {\n\tmode: 'embedded';\n\tgetToken: () => string | null;\n\t/**\n\t * Stable, non-secret identity used to isolate cached data between users.\n\t * Hosts should return the authenticated user/session id, never the token.\n\t * When omitted, the provider uses an opaque key that changes with the token.\n\t */\n\tgetIdentityKey?: () => string | null;\n}\n\nexport interface SheetsAuthStandalone {\n\tmode: 'standalone';\n}\n\nexport interface SheetsStorageTransport {\n\tendpoint: string;\n\texecute: SheetsExecuteFn;\n}\n\nexport interface SheetsConfig {\n\t/** Data endpoint (app-public GraphQL) */\n\tendpoint: string;\n\t/** Auth endpoint (auth GraphQL) — required for standalone mode */\n\tauthEndpoint?: string;\n\t/** Database ID for multi-tenant scoping */\n\tdatabaseId?: string;\n\t/** Auth mode */\n\tauth: SheetsAuthEmbedded | SheetsAuthStandalone;\n\t/** Field type overrides (replaces schema-builder smart tags) */\n\tfieldTypeOverrides?: Record<string, string>;\n\t/** Optional: BCP-47 locale for locale-aware date/number formatting (default 'en-US'). */\n\tlocale?: string;\n\t/** Optional: inject custom execute function */\n\texecute?: SheetsExecuteFn;\n\t/** Optional: inject custom upload function */\n\texecuteUpload?: SheetsUploadFn;\n\t/** Storage endpoint for media uploads and download URL lookups. */\n\tstorage?: { endpoint: string; execute?: SheetsExecuteFn };\n\t/** Explicit bucket override. Omit to use the tenant's public default. */\n\tupload?: { bucketKey?: string };\n\t/** Optional: inject existing QueryClient */\n\tqueryClient?: QueryClient;\n\t/** Optional: inject a custom backend adapter. Defaults to the PostGraphile adapter. */\n\tadapter?: SheetsBackendAdapter;\n\t/** Optional: provider-level cell-type plugins (consumer override layer). */\n\tplugins?: CellTypePlugin[];\n\t/** Called on 401/UNAUTHENTICATED before the error is thrown. Host app handles token cleanup. */\n\tonAuthError?: () => void;\n\t/** Optional: inject a custom logger. Installed into the module logger singleton by the provider. */\n\tlogger?: SheetsLogger;\n\t/** Optional: called when a grid/editor/mutation/upload error surfaces. Host app handles reporting. */\n\tonError?: (\n\t\terror: unknown,\n\t\tctx?: { source?: 'grid' | 'editor' | 'mutation' | 'upload'; tableName?: string },\n\t) => void;\n}\n\nexport interface SheetsContextValue {\n\tconfig: SheetsConfig;\n\texecute: SheetsExecuteFn;\n\texecuteUpload: SheetsUploadFn;\n\tstorage?: SheetsStorageTransport;\n\tcanUpload: boolean;\n\tscopeKey: SheetsScopeKey;\n}\n\nexport interface SheetsScopeKey {\n\tdatabaseId: string | null;\n\tendpoint: string;\n\tidentityKey: string | null;\n}\n\nexport const SheetsContext = createContext<SheetsContextValue | null>(null);\n\nexport function useSheetsContext(): SheetsContextValue {\n\tconst ctx = useContext(SheetsContext);\n\tif (!ctx) {\n\t\tthrow new Error('useSheetsContext must be used within a <SheetsProvider>');\n\t}\n\treturn ctx;\n}\n","import type { RelationInfo } from './relation-info-slice';\n\ntype DraftRowStatus = 'idle' | 'saving' | 'error';\n\nexport interface DraftRow {\n id: string;\n values: Record<string, unknown>;\n status: DraftRowStatus;\n errors: Record<string, string> | null;\n createdAt: number;\n metaVersion: string;\n}\n\ninterface DraftRowsTableState {\n order: string[];\n map: Record<string, DraftRow>;\n template: Record<string, unknown>;\n metaVersion: string;\n columnOrder: string[];\n}\n\nexport function parseDraftTableKey(tableKey: string): { databaseId: string | null; tableName: string } | null {\n const parts = tableKey.split('::');\n if (parts.length === 2) {\n const [databaseId, tableName] = parts;\n if (!databaseId || !tableName) return null;\n return { databaseId, tableName };\n }\n return null;\n}\n\nexport interface DraftRowCreationArgs {\n tableKey: string;\n columnOrder: readonly string[];\n fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>;\n relationInfoByKey?: Record<string, RelationInfo | undefined>;\n metaVersion: string;\n}\n\nexport type DraftRowsSyncArgs = DraftRowCreationArgs;\n\nexport interface DraftRowUpdateArgs {\n tableKey: string;\n draftRowId: string;\n columnKey: string;\n value: unknown;\n extraValues?: Record<string, unknown>;\n}\n\nexport interface DraftRowsSlice {\n draftRowsByTable: Record<string, DraftRowsTableState | undefined>;\n createDraftRow: (args: DraftRowCreationArgs) => string;\n updateDraftCell: (args: DraftRowUpdateArgs) => void;\n removeDraftRow: (tableKey: string, draftRowId: string) => void;\n clearDraftRowsForTable: (tableKey: string) => void;\n clearDraftRowsForDatabase: (databaseId: string) => void;\n clearAllDraftRows: () => void;\n syncDraftRowsWithMeta: (args: DraftRowsSyncArgs) => void;\n setDraftRowStatus: (args: {\n tableKey: string;\n draftRowId: string;\n status: DraftRowStatus;\n errors?: Record<string, string> | null;\n }) => void;\n}\n\ntype DraftFieldMetadata = {\n name?: string | null;\n isNotNull?: boolean | null;\n hasDefault?: boolean | null;\n type?: {\n gqlType?: string | null;\n isArray?: boolean | null;\n pgAlias?: string | null;\n pgType?: string | null;\n subtype?: string | null;\n } | null;\n};\n\ntype DraftRowsSetState = (\n\tpartial: Partial<DraftRowsSlice> | ((state: DraftRowsSlice) => Partial<DraftRowsSlice> | DraftRowsSlice),\n) => void;\n\nexport function createDraftRowsSlice(set: DraftRowsSetState): DraftRowsSlice {\n\treturn {\n draftRowsByTable: {},\n\n createDraftRow: (args) => {\n const { tableKey, columnOrder, fieldMetaByKey, relationInfoByKey, metaVersion } = args;\n\n const effectiveColumnOrder = ensureColumnOrder(columnOrder, fieldMetaByKey, relationInfoByKey);\n const template = buildTemplate(effectiveColumnOrder, relationInfoByKey);\n const draftRowId = `draft:${generateDraftSuffix()}`;\n const values = initializeValuesFromTemplate(template, draftRowId);\n\n set((state: DraftRowsSlice) => {\n const existing = state.draftRowsByTable[tableKey];\n\n const nextOrder = existing ? [...existing.order, draftRowId] : [draftRowId];\n\t const nextMap: Record<string, DraftRow> = {\n\t ...(existing?.map ?? {}),\n [draftRowId]: {\n id: draftRowId,\n values,\n status: 'idle' as const,\n errors: null,\n createdAt: Date.now(),\n metaVersion,\n },\n };\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: {\n order: nextOrder,\n map: nextMap,\n template,\n metaVersion,\n columnOrder: [...effectiveColumnOrder],\n },\n },\n };\n });\n\n return draftRowId;\n },\n\n\t updateDraftCell: ({ tableKey, draftRowId, columnKey, value, extraValues }) => {\n\t set((state: DraftRowsSlice) => {\n\t const tableState = state.draftRowsByTable[tableKey];\n\t if (!tableState) return state;\n\n\t const existingRow = tableState.map[draftRowId];\n\t if (!existingRow) return state;\n\n\t let hasValueChanges = !deepEqual(existingRow.values[columnKey], value);\n\t if (!hasValueChanges && extraValues) {\n\t for (const [key, extraValue] of Object.entries(extraValues)) {\n\t if (!deepEqual(existingRow.values[key], extraValue)) {\n\t hasValueChanges = true;\n\t break;\n\t }\n\t }\n\t }\n\n\t const shouldResetErrors = existingRow.status === 'error' || existingRow.errors !== null;\n\t if (!hasValueChanges && !shouldResetErrors) return state;\n\n\t const updatedValues = hasValueChanges ? { ...existingRow.values, [columnKey]: deepClone(value) } : existingRow.values;\n\t if (hasValueChanges && extraValues) {\n\t for (const [key, extraValue] of Object.entries(extraValues)) {\n\t updatedValues[key] = deepClone(extraValue);\n\t }\n\t }\n\n\t const nextMap: Record<string, DraftRow> = {\n\t ...tableState.map,\n [draftRowId]: {\n ...existingRow,\n values: updatedValues,\n status: existingRow.status === 'error' ? ('idle' as const) : existingRow.status,\n errors: null,\n },\n };\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: {\n ...tableState,\n map: nextMap,\n },\n },\n };\n });\n },\n\n removeDraftRow: (tableKey, draftRowId) => {\n set((state: DraftRowsSlice) => {\n const tableState = state.draftRowsByTable[tableKey];\n if (!tableState) return state;\n if (!tableState.map[draftRowId]) return state;\n\n const nextOrder = tableState.order.filter((id) => id !== draftRowId);\n const nextMap = { ...tableState.map };\n delete nextMap[draftRowId];\n\n const nextTableState: DraftRowsTableState | undefined = nextOrder.length\n ? { ...tableState, order: nextOrder, map: nextMap }\n : undefined;\n\n const nextByTable = { ...state.draftRowsByTable };\n if (nextTableState) {\n nextByTable[tableKey] = nextTableState;\n } else {\n delete nextByTable[tableKey];\n }\n\n return { draftRowsByTable: nextByTable };\n });\n },\n\n clearDraftRowsForTable: (tableKey) => {\n set((state: DraftRowsSlice) => {\n if (!state.draftRowsByTable[tableKey]) return state;\n const nextByTable = { ...state.draftRowsByTable };\n delete nextByTable[tableKey];\n return { draftRowsByTable: nextByTable };\n });\n },\n\n clearDraftRowsForDatabase: (databaseId) => {\n set((state: DraftRowsSlice) => {\n if (!databaseId || !Object.keys(state.draftRowsByTable).length) return state;\n let changed = false;\n const nextByTable: Record<string, DraftRowsTableState | undefined> = { ...state.draftRowsByTable };\n\n for (const tableKey of Object.keys(nextByTable)) {\n const parsed = parseDraftTableKey(tableKey);\n const matchesDatabase = parsed ? parsed.databaseId === databaseId : tableKey.includes(`${databaseId}::`);\n\n if (matchesDatabase) {\n delete nextByTable[tableKey];\n changed = true;\n }\n }\n\n return changed ? { draftRowsByTable: nextByTable } : state;\n });\n },\n\n clearAllDraftRows: () => {\n set((state: DraftRowsSlice) => {\n if (!Object.keys(state.draftRowsByTable).length) return state;\n return { draftRowsByTable: {} };\n });\n },\n\n\t syncDraftRowsWithMeta: (args) => {\n\t const { tableKey, columnOrder, fieldMetaByKey, relationInfoByKey, metaVersion } = args;\n\n\t set((state: DraftRowsSlice) => {\n\t const tableState = state.draftRowsByTable[tableKey];\n\t const effectiveColumnOrder = ensureColumnOrder(columnOrder, fieldMetaByKey, relationInfoByKey);\n\t const template = buildTemplate(effectiveColumnOrder, relationInfoByKey);\n\n\t if (!tableState) {\n\t return state;\n\t }\n\n\t if (tableState.order.length === 0) {\n\t const nextByTable = { ...state.draftRowsByTable };\n\t delete nextByTable[tableKey];\n\t return { draftRowsByTable: nextByTable };\n\t }\n\n\t const isSameMeta =\n\t tableState.metaVersion === metaVersion && shallowEqualArrays(tableState.columnOrder, effectiveColumnOrder);\n\n if (isSameMeta) return state;\n\n const nextMap: Record<string, DraftRow> = {};\n for (const draftId of tableState.order) {\n const row = tableState.map[draftId];\n if (!row) continue;\n\n const mergedValues: Record<string, unknown> = initializeValuesFromTemplate(template, draftId);\n for (const key of Object.keys(row.values)) {\n if (Object.prototype.hasOwnProperty.call(template, key)) {\n mergedValues[key] = deepClone(row.values[key]);\n }\n }\n\n nextMap[draftId] = {\n ...row,\n values: mergedValues,\n metaVersion,\n status: row.status === 'error' ? 'idle' as const : row.status,\n errors: row.status === 'error' ? null : row.errors,\n };\n }\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: {\n order: [...tableState.order],\n map: nextMap,\n template,\n metaVersion,\n columnOrder: [...effectiveColumnOrder],\n },\n },\n };\n });\n },\n\n\t setDraftRowStatus: ({ tableKey, draftRowId, status, errors }) => {\n\t set((state: DraftRowsSlice) => {\n\t const tableState = state.draftRowsByTable[tableKey];\n\t if (!tableState) return state;\n\t const row = tableState.map[draftRowId];\n\t if (!row) return state;\n\t const nextErrors = errors ?? null;\n\t if (row.status === status && shallowEqualRecords(row.errors, nextErrors)) return state;\n\n\t const nextMap: Record<string, DraftRow> = {\n\t ...tableState.map,\n\t [draftRowId]: { ...row, status, errors: nextErrors },\n\t };\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: { ...tableState, map: nextMap },\n },\n };\n });\n },\n };\n}\n\nfunction ensureColumnOrder(\n columnOrder: readonly string[],\n fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>,\n relationInfoByKey?: Record<string, RelationInfo | undefined>,\n): string[] {\n if (columnOrder.length > 0) return [...columnOrder];\n\n const keys = new Set<string>();\n Object.keys(fieldMetaByKey).forEach((key) => {\n if (key) keys.add(key);\n });\n if (relationInfoByKey) {\n Object.keys(relationInfoByKey).forEach((key) => {\n if (key) keys.add(key);\n });\n }\n return Array.from(keys).sort((a, b) => a.localeCompare(b));\n}\n\nfunction buildTemplate(\n columnOrder: readonly string[],\n relationInfoByKey?: Record<string, RelationInfo | undefined>,\n): Record<string, unknown> {\n const template: Record<string, unknown> = {};\n\n for (const column of columnOrder) {\n if (!column) continue;\n const relationInfo = relationInfoByKey?.[column];\n\n if (relationInfo && (relationInfo.kind === 'hasMany' || relationInfo.kind === 'manyToMany')) {\n template[column] = [];\n } else {\n template[column] = null;\n }\n }\n\n return template;\n}\n\nfunction generateDraftSuffix(): string {\n const cryptoObj = typeof globalThis !== 'undefined' ? (globalThis as any).crypto : undefined;\n if (cryptoObj && typeof cryptoObj.getRandomValues === 'function') {\n const buffer = new Uint32Array(1);\n cryptoObj.getRandomValues(buffer);\n return buffer[0].toString(36).slice(0, 8);\n }\n return Math.random().toString(36).slice(2, 10);\n}\n\nfunction initializeValuesFromTemplate(template: Record<string, unknown>, draftRowId: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(template)) {\n result[key] = deepClone(value);\n }\n if (!result.id) result.id = draftRowId;\n return result;\n}\n\nfunction deepClone<T>(value: T): T {\n if (Array.isArray(value)) return value.map((item) => deepClone(item)) as unknown as T;\n if (value instanceof Date) return new Date(value.getTime()) as unknown as T;\n if (value && typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value as Record<string, unknown>)) {\n result[key] = deepClone(val);\n }\n return result as unknown as T;\n }\n\treturn value;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n\tif (Object.is(a, b)) return true;\n\tif (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\tif (a.length !== b.length) return false;\n\t\tfor (let i = 0; i < a.length; i += 1) {\n\t\t\tif (!deepEqual(a[i], b[i])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\tif (a && b && typeof a === 'object' && typeof b === 'object') {\n\t\tconst keysA = Object.keys(a as Record<string, unknown>);\n\t\tconst keysB = Object.keys(b as Record<string, unknown>);\n\t\tif (keysA.length !== keysB.length) return false;\n\t\tfor (const key of keysA) {\n\t\t\tif (!(key in (b as Record<string, unknown>))) return false;\n\t\t\tif (!deepEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nfunction shallowEqualRecords(\n\ta: Record<string, string> | null,\n\tb: Record<string, string> | null,\n): boolean {\n\tif (a === b) return true;\n\tif (!a || !b) return false;\n\tconst keysA = Object.keys(a);\n\tconst keysB = Object.keys(b);\n\tif (keysA.length !== keysB.length) return false;\n\tfor (const key of keysA) {\n\t\tif (a[key] !== b[key]) return false;\n\t}\n\treturn true;\n}\n\nfunction shallowEqualArrays(a: readonly string[], b: readonly string[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\nexport function computeDraftMetaSignature(\n columnOrder: readonly string[],\n fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>,\n relationInfoByKey?: Record<string, RelationInfo | undefined>,\n): string {\n const signatureParts = columnOrder.map((column) => {\n const typeMeta = fieldMetaByKey[column]?.type;\n const relationMeta = relationInfoByKey?.[column];\n\n const typePart = typeMeta\n ? [\n typeMeta.gqlType ?? '',\n typeMeta.isArray ? '1' : '0',\n typeMeta.pgAlias ?? '',\n typeMeta.pgType ?? '',\n typeMeta.subtype ?? '',\n ].join(':')\n : '';\n\n const relationPart = relationMeta\n ? [relationMeta.kind ?? '', relationMeta.foreignKeyField ?? '', relationMeta.relationField ?? ''].join(':')\n : '';\n\n return `${column}|${typePart}|${relationPart}`;\n });\n\n return hashString(signatureParts.join('||'));\n}\n\nfunction hashString(input: string): string {\n let hash = 0;\n for (let i = 0; i < input.length; i += 1) {\n hash = (hash << 5) - hash + input.charCodeAt(i);\n hash |= 0;\n }\n return hash.toString(16);\n}\n","import { pluralize } from 'inflekt';\nimport { cleanTable, pgFieldToCamelCase, type CleanTable, type MetaQuery } from '@constructive-io/data';\nimport { getJunctionTableNames, isJunctionTablePure } from '../utils/relation-utils';\n\nexport type RelationKind = 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany';\n\nexport interface RelationInfo {\n kind: RelationKind;\n relatedTable?: string;\n displayCandidates: string[];\n relationField?: string;\n foreignKeyField?: string;\n junctionTable?: string;\n junctionLeftKeyField?: string;\n junctionRightKeyField?: string;\n displayName?: string;\n}\n\nexport interface RelationInfoSlice {\n relationInfoCache: Record<string, Record<string, RelationInfo>>;\n relationInfoMapCache: Record<string, Map<string, RelationInfo>>;\n setRelationInfoForTable: (tableName: string, info: Record<string, RelationInfo>) => void;\n getRelationInfoForTable: (tableName: string) => Record<string, RelationInfo> | undefined;\n getRelationInfoMapForTable: (tableName: string) => Map<string, RelationInfo> | undefined;\n rebuildRelationInfo: (tableName: string, meta: MetaQuery | undefined) => void;\n ensureRelationInfo: (tableName: string, meta: MetaQuery | undefined) => Record<string, RelationInfo>;\n clearRelationInfoCache: () => void;\n}\n\ninterface RelationInfoState {\n relationInfoCache: Record<string, Record<string, RelationInfo>>;\n relationInfoMapCache: Record<string, Map<string, RelationInfo>>;\n}\n\ntype RelationInfoSetState = (\n partial: Partial<RelationInfoState> | ((state: RelationInfoState) => Partial<RelationInfoState>),\n) => void;\n\ntype RelationInfoGetState = () => RelationInfoState;\n\nfunction toRelationInfoMap(info: Record<string, RelationInfo>): Map<string, RelationInfo> {\n return new Map(Object.entries(info));\n}\n\nfunction setTableRelationInfo(set: RelationInfoSetState, tableName: string, info: Record<string, RelationInfo>): void {\n set((state) => ({\n relationInfoCache: { ...state.relationInfoCache, [tableName]: info },\n relationInfoMapCache: { ...state.relationInfoMapCache, [tableName]: toRelationInfoMap(info) },\n }));\n}\n\nexport function createRelationInfoSlice(set: RelationInfoSetState, get: RelationInfoGetState): RelationInfoSlice {\n return {\n relationInfoCache: {},\n relationInfoMapCache: {},\n setRelationInfoForTable: (tableName, info) => setTableRelationInfo(set, tableName, info),\n getRelationInfoForTable: (tableName) => get().relationInfoCache[tableName],\n getRelationInfoMapForTable: (tableName) => get().relationInfoMapCache[tableName],\n clearRelationInfoCache: () => set({ relationInfoCache: {}, relationInfoMapCache: {} }),\n rebuildRelationInfo: (tableName: string, meta: MetaQuery | undefined) => {\n try {\n const info = buildRelationInfoFromMeta(tableName, meta);\n if (!info) return;\n setTableRelationInfo(set, tableName, info);\n } catch {\n // ignore\n }\n },\n ensureRelationInfo: (tableName: string, meta: MetaQuery | undefined) => {\n const existing = get().relationInfoCache[tableName];\n if (existing) return existing;\n const info = buildRelationInfoFromMeta(tableName, meta) || {};\n if (Object.keys(info).length) {\n setTableRelationInfo(set, tableName, info);\n }\n return info;\n },\n };\n}\n\ntype MetaTableNode = NonNullable<NonNullable<NonNullable<MetaQuery['_meta']>['tables']>[number]>;\n\nfunction toCleanTables(meta: MetaQuery | undefined): CleanTable[] {\n const tables = meta?._meta?.tables ?? [];\n return tables.filter((table): table is MetaTableNode => table != null).map((table) => cleanTable(table));\n}\n\nfunction firstFieldName(fields: Array<{ name: string }>): string | undefined {\n return fields[0]?.name;\n}\n\n/**\n * For hasOne/hasMany relations, find the FK field in the RELATED table that\n * references the current table. relation.keys contains the PK of the current\n * table (e.g. \"id\"), but the relation editor needs the FK in the child table\n * (e.g. \"questionnaireId\") to link/unlink records.\n *\n * Resolution chain:\n * 1. Related table's belongsTo relations (from cleanTable)\n * 2. Related table's foreignKeyConstraints (from raw _meta)\n */\nfunction findForeignKeyInRelatedTable(\n currentTableName: string,\n relatedTableName: string,\n allTables: CleanTable[],\n rawMetaTables: readonly MetaTableNode[],\n): string | undefined {\n // 1. Try belongsTo on the related cleaned table\n const relatedTable = allTables.find((t) => t.name === relatedTableName);\n if (relatedTable) {\n const belongsTo = relatedTable.relations.belongsTo.find(\n (rel) => rel.referencesTable === currentTableName,\n );\n if (belongsTo?.keys?.[0]?.name) return belongsTo.keys[0].name;\n }\n\n // 2. Fall back to foreignKeyConstraints on the raw _meta related table\n const rawRelated = rawMetaTables.find((t) => t.name === relatedTableName);\n if (rawRelated) {\n // v5 nested: constraints.foreignKey[]\n const v5Fks = Array.isArray(rawRelated.constraints) ? [] : rawRelated.constraints?.foreignKey;\n // v4 flat: foreignKeyConstraints[]\n const fks = v5Fks ?? rawRelated.foreignKeyConstraints ?? [];\n for (const fk of fks) {\n if (!fk) continue;\n const refName = fk.refTable?.name;\n // refTable.name is a codec name (camelCase) — match case-insensitively\n if (refName && refName.toLowerCase() === currentTableName.toLowerCase()) {\n const fieldName = fk.fields?.[0]?.name;\n if (fieldName) return pgFieldToCamelCase(fieldName);\n }\n }\n }\n\n return undefined;\n}\n\nexport function buildRelationInfoFromMeta(\n tableName: string,\n meta: MetaQuery | undefined,\n): Record<string, RelationInfo> | null {\n const tables = toCleanTables(meta);\n const table = tables.find((candidate) => candidate.name === tableName);\n if (!table) return null;\n\n const rawMetaTables = (meta?._meta?.tables ?? []).filter(\n (t): t is MetaTableNode => t != null,\n );\n\n const PRIORITY_FIELDS = [\n 'displayName',\n 'fullName',\n 'preferredName',\n 'nickname',\n 'firstName',\n 'lastName',\n 'givenName',\n 'familyName',\n 'username',\n 'handle',\n 'email',\n 'phone',\n 'title',\n 'label',\n 'slug',\n 'code',\n 'name',\n ];\n const NAME_PATTERN = /name/i;\n\n const computeCandidates = (relatedTableName?: string): string[] => {\n if (!relatedTableName) return [];\n const related = tables.find((candidate) => candidate.name === relatedTableName);\n if (!related) return [];\n\n const fieldNamesSet = new Set<string>(related.fields.map((field) => field.name));\n const explicit = PRIORITY_FIELDS.filter((k) => fieldNamesSet.has(k));\n const explicitSet = new Set(explicit);\n\n const nameLike: string[] = [];\n for (const name of fieldNamesSet) {\n if (NAME_PATTERN.test(name) && !explicitSet.has(name)) {\n nameLike.push(name);\n }\n }\n nameLike.sort((a, b) => a.length - b.length);\n\n return Array.from(new Set([...explicit, ...nameLike]));\n };\n\n const info: Record<string, RelationInfo> = {};\n table.relations.belongsTo.forEach((relation) => {\n const displayCandidates = computeCandidates(relation.referencesTable);\n const foreignKeys = relation.keys.map((key) => key.name).filter(Boolean);\n const primaryForeignKey = foreignKeys[0];\n\n if (relation.fieldName) {\n info[relation.fieldName] = {\n kind: 'belongsTo',\n relatedTable: relation.referencesTable,\n displayCandidates,\n relationField: relation.fieldName,\n foreignKeyField: primaryForeignKey,\n };\n }\n\n foreignKeys.forEach((fk) => {\n if (!fk) return;\n info[fk] = {\n kind: 'belongsTo',\n relatedTable: relation.referencesTable,\n displayCandidates,\n relationField: relation.fieldName ?? undefined,\n foreignKeyField: fk,\n };\n });\n });\n table.relations.hasOne.forEach((relation) => {\n if (relation.fieldName) {\n // relation.keys contains the PK of the CURRENT table, not the FK in the\n // related table. Resolve the actual FK field via:\n // 1. Related table's belongsTo (cleanTable)\n // 2. Related table's foreignKeyConstraints (raw _meta)\n const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);\n info[relation.fieldName] = {\n kind: 'hasOne',\n relatedTable: relation.referencedByTable,\n displayCandidates: computeCandidates(relation.referencedByTable),\n relationField: relation.fieldName,\n foreignKeyField: fkInRelated,\n };\n }\n });\n const junctionTableNames = getJunctionTableNames(table.relations, rawMetaTables);\n\n table.relations.hasMany.forEach((relation) => {\n if (!relation.fieldName) return;\n // Skip hasMany relations pointing to junction tables (M:N covers these)\n if (junctionTableNames.has(relation.referencedByTable)) return;\n const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);\n info[relation.fieldName] = {\n kind: 'hasMany',\n relatedTable: relation.referencedByTable,\n displayCandidates: computeCandidates(relation.referencedByTable),\n relationField: relation.fieldName,\n foreignKeyField: fkInRelated,\n };\n });\n table.relations.manyToMany.forEach((relation) => {\n if (relation.fieldName) {\n // Prefer direct key fields from enriched cleanTable()\n let junctionLeftKeyField = relation.junctionLeftKeyFields?.[0];\n let junctionRightKeyField = relation.junctionRightKeyFields?.[0];\n\n // Fallback: derive from junction table's belongsTo relations\n if (!junctionLeftKeyField || !junctionRightKeyField) {\n const junctionTableName = relation.junctionTable;\n const junctionTable = junctionTableName\n ? tables.find((candidate) => candidate.name === junctionTableName)\n : undefined;\n const junctionBelongsTo = junctionTable?.relations.belongsTo ?? [];\n if (!junctionLeftKeyField) {\n const leftRelation = junctionBelongsTo.find((entry) => entry.referencesTable === tableName);\n junctionLeftKeyField = firstFieldName(leftRelation?.keys ?? []);\n }\n if (!junctionRightKeyField) {\n const rightRelation = junctionBelongsTo.find((entry) => entry.referencesTable === relation.rightTable);\n junctionRightKeyField = firstFieldName(rightRelation?.keys ?? []);\n }\n }\n\n // Skip non-pure junction tables — they have required fields beyond the\n // two FK columns, so the manyToMany editor cannot produce valid mutations.\n if (!isJunctionTablePure(relation.junctionTable, junctionLeftKeyField, junctionRightKeyField, rawMetaTables)) {\n return;\n }\n\n info[relation.fieldName] = {\n kind: 'manyToMany',\n relatedTable: relation.rightTable,\n displayCandidates: computeCandidates(relation.rightTable),\n relationField: relation.fieldName,\n junctionTable: relation.junctionTable,\n junctionLeftKeyField,\n junctionRightKeyField,\n displayName: pluralize(relation.rightTable),\n };\n }\n });\n\n return info;\n}\n","import { singularize } from \"inflekt\";\nimport { pgFieldToCamelCase, type CleanTable, type CleanRelations, type MetaQuery } from \"@constructive-io/data\";\n\ntype PrimitiveId = string | number | null;\n\ntype MetaTable = NonNullable<NonNullable<NonNullable<MetaQuery[\"_meta\"]>[\"tables\"]>[number]>;\n\n\n/**\n * Convert a camelCase plural codec name (as used in raw _meta relation references)\n * to PascalCase singular (matching `_meta.tables[].name` format).\n * e.g. \"formResponses\" → \"FormResponse\"\n */\nfunction codecNameToTableName(name: string): string {\n if (!name) return name;\n const singular = singularize(name);\n return singular.charAt(0).toUpperCase() + singular.slice(1);\n}\n\n/**\n * Derive all relation field names from raw table metadata relations.\n * Filters out hasMany entries that point to junction tables (those are surfaced via manyToMany),\n * and deduplicates manyToMany entries targeting the same table.\n */\nexport function getAllRelationFields(\n relations: MetaTable[\"relations\"] | null | undefined,\n metaTables?: readonly MetaTable[],\n): string[] {\n if (!relations) return [];\n\n const out: string[] = [];\n const push = (fieldName?: string | null) => {\n if (fieldName) out.push(fieldName);\n };\n\n relations.belongsTo?.forEach((rel) => push(rel?.fieldName));\n relations.hasOne?.forEach((rel) => push(rel?.fieldName));\n\n const junctionNames = new Set<string>();\n relations.manyToMany?.forEach((rel) => {\n const jtName = rel?.junctionTable?.name;\n if (!jtName) return;\n // When meta tables are available, skip non-pure junction tables\n if (metaTables) {\n const leftFk = rel?.junctionLeftKeyAttributes?.[0]?.name;\n const rightFk = rel?.junctionRightKeyAttributes?.[0]?.name;\n const leftFkCamel = leftFk ? pgFieldToCamelCase(leftFk) : undefined;\n const rightFkCamel = rightFk ? pgFieldToCamelCase(rightFk) : undefined;\n // Raw _meta codec names need conversion to match MetaTable.name format\n const jtTableName = codecNameToTableName(jtName);\n if (!isJunctionTablePure(jtTableName, leftFkCamel, rightFkCamel, metaTables)) return;\n }\n junctionNames.add(jtName);\n });\n relations.hasMany?.forEach((rel) => {\n const refName = rel?.referencedBy?.name;\n if (refName && junctionNames.has(refName)) return;\n push(rel?.fieldName);\n });\n\n const seenM2N = new Map<string, { fieldName?: string | null }>();\n relations.manyToMany?.forEach((rel) => {\n const target = rel?.rightTable?.name;\n if (!target) return;\n // Skip non-pure junction table M:N relations\n if (metaTables) {\n const jtName = rel?.junctionTable?.name;\n if (jtName) {\n const leftFk = rel?.junctionLeftKeyAttributes?.[0]?.name;\n const rightFk = rel?.junctionRightKeyAttributes?.[0]?.name;\n const leftFkCamel = leftFk ? pgFieldToCamelCase(leftFk) : undefined;\n const rightFkCamel = rightFk ? pgFieldToCamelCase(rightFk) : undefined;\n const jtTableName = codecNameToTableName(jtName);\n if (!isJunctionTablePure(jtTableName, leftFkCamel, rightFkCamel, metaTables)) return;\n }\n }\n seenM2N.set(target, rel);\n });\n seenM2N.forEach((rel) => push(rel?.fieldName));\n\n return Array.from(new Set(out));\n}\n\n/**\n * Check whether a junction table is \"pure\" — i.e. it has no required fields\n * beyond the two FK columns that form the M:N link.\n *\n * Rich entity tables that PostGraphile incidentally detects as junction tables\n * (e.g. `form_response` which has FKs to both `form_question` and `form_section`\n * but also requires `entity_id`, `session_id`, etc.) should NOT be treated as\n * simple junction tables because the manyToMany editor can only set the two FK\n * fields and would produce invalid mutations.\n */\nexport function isJunctionTablePure(\n junctionTableName: string,\n leftFkField: string | undefined,\n rightFkField: string | undefined,\n metaTables: readonly MetaTable[],\n): boolean {\n if (!leftFkField || !rightFkField) return true; // Can't verify, assume pure\n const junctionMeta = metaTables.find((t) => t?.name === junctionTableName);\n if (!junctionMeta?.fields) return true; // No field info available, assume pure\n\n const exemptFields = new Set(['id', leftFkField, rightFkField]);\n\n for (const field of junctionMeta.fields) {\n if (!field?.name) continue;\n const camelName = pgFieldToCamelCase(field.name);\n if (exemptFields.has(camelName)) continue;\n if (field.isNotNull && !field.hasDefault) return false;\n }\n return true;\n}\n\n/**\n * Collect junction table names from M:N relations.\n * Used to suppress hasMany-to-junction columns and hide junction tables from UIs.\n *\n * When `metaTables` is provided, non-pure junction tables (those with extra required\n * fields beyond the two FK columns) are excluded — their hasMany entries should remain\n * visible since the manyToMany editor cannot handle them.\n */\nexport function getJunctionTableNames(\n relations: CleanRelations,\n metaTables?: readonly MetaTable[],\n): Set<string> {\n const names = new Set<string>();\n for (const rel of relations.manyToMany) {\n if (!rel.junctionTable) continue;\n if (metaTables) {\n const leftFk = rel.junctionLeftKeyFields?.[0];\n const rightFk = rel.junctionRightKeyFields?.[0];\n if (!isJunctionTablePure(rel.junctionTable, leftFk, rightFk, metaTables)) continue;\n }\n names.add(rel.junctionTable);\n }\n return names;\n}\n\nfunction extractPrimitiveId(candidate: unknown): PrimitiveId {\n if (candidate === null || candidate === undefined) return null;\n if (typeof candidate === \"string\" || typeof candidate === \"number\") {\n return candidate;\n }\n if (typeof candidate === \"object\") {\n const record = candidate as Record<string, unknown>;\n const id = record.id;\n if (typeof id === \"string\" || typeof id === \"number\") {\n return id;\n }\n }\n return null;\n}\n\nexport function normalizeForeignKeyValue(input: unknown): unknown {\n if (input === undefined) return undefined;\n if (input === null) return null;\n\n if (Array.isArray(input)) {\n return input\n .map((entry) => extractPrimitiveId(entry))\n .filter((entry): entry is PrimitiveId => entry !== undefined);\n }\n\n return extractPrimitiveId(input);\n}\n\n/**\n * Find the foreign key field in a related table that references the current table\n */\nfunction findForeignKeyField(\n currentTableName: string,\n relatedTableName: string,\n allTables?: CleanTable[],\n): string | undefined {\n if (!allTables) return undefined;\n\n // Find the related table\n const relatedTable = allTables.find((table) => table.name === relatedTableName);\n if (!relatedTable) return undefined;\n\n // Look for a belongsTo relation in the related table that references our current table\n const belongsToRelation = relatedTable.relations.belongsTo.find(\n (relation) => relation.referencesTable === currentTableName,\n );\n\n if (belongsToRelation && belongsToRelation.keys?.[0]?.name) {\n return belongsToRelation.keys[0].name;\n }\n\n return undefined;\n}\n\nexport interface RelationshipInfo {\n relationType: \"belongsTo\" | \"hasOne\" | \"hasMany\" | \"manyToMany\";\n relationField: string;\n relatedTableName: string;\n foreignKeyField?: string;\n junctionTableName?: string;\n junctionLeftKey?: string;\n junctionRightKey?: string;\n}\n\n/**\n * Extract relationship information from table metadata for a specific field\n * For hasMany/hasOne relations, we need to find the actual foreign key field in the related table\n */\nexport function getRelationshipInfo(\n currentTable: CleanTable,\n relationFieldName: string,\n allTables?: CleanTable[],\n): RelationshipInfo | null {\n const { relations } = currentTable;\n\n // Check belongsTo relations\n const belongsToRelation = relations.belongsTo.find((rel) => rel.fieldName === relationFieldName);\n if (belongsToRelation) {\n // For belongsTo: get the foreign key field name from the keys array\n const foreignKeyField = belongsToRelation.keys?.[0]?.name;\n return {\n relationType: \"belongsTo\",\n relationField: relationFieldName,\n relatedTableName: belongsToRelation.referencesTable,\n foreignKeyField: foreignKeyField,\n };\n }\n\n // Check hasOne relations\n const hasOneRelation = relations.hasOne.find((rel) => rel.fieldName === relationFieldName);\n if (hasOneRelation) {\n // For hasOne: find the foreign key field in the related table that references our current table\n const foreignKeyField = findForeignKeyField(\n currentTable.name,\n hasOneRelation.referencedByTable,\n allTables,\n );\n return {\n relationType: \"hasOne\",\n relationField: relationFieldName,\n relatedTableName: hasOneRelation.referencedByTable,\n foreignKeyField: foreignKeyField,\n };\n }\n\n // Check hasMany relations\n const hasManyRelation = relations.hasMany.find((rel) => rel.fieldName === relationFieldName);\n if (hasManyRelation) {\n // For hasMany: find the foreign key field in the related table that references our current table\n const foreignKeyField = findForeignKeyField(\n currentTable.name,\n hasManyRelation.referencedByTable,\n allTables,\n );\n return {\n relationType: \"hasMany\",\n relationField: relationFieldName,\n relatedTableName: hasManyRelation.referencedByTable,\n foreignKeyField: foreignKeyField,\n };\n }\n\n // Check manyToMany relations\n const manyToManyRelation = relations.manyToMany.find(\n (rel) => rel.fieldName === relationFieldName,\n );\n if (manyToManyRelation) {\n return {\n relationType: \"manyToMany\",\n relationField: relationFieldName,\n relatedTableName: manyToManyRelation.rightTable,\n junctionTableName: manyToManyRelation.junctionTable,\n junctionLeftKey: manyToManyRelation.junctionLeftKeyFields?.[0],\n junctionRightKey: manyToManyRelation.junctionRightKeyFields?.[0],\n };\n }\n\n return null;\n}\n\n/**\n * Get a display-friendly label from a record using common field patterns\n */\nconst DISPLAY_LABEL_FIELDS = [\n \"name\", \"title\", \"label\", \"displayName\", \"fullName\",\n \"email\", \"username\", \"description\", \"code\",\n];\n\nexport function getRecordDisplayLabel(record: any): string {\n if (!record || typeof record !== \"object\") {\n return String(record || \"\");\n }\n\n // Try common display field patterns\n for (const field of DISPLAY_LABEL_FIELDS) {\n if (record[field] != null && String(record[field]).trim()) {\n return String(record[field]);\n }\n }\n\n // Fallback to ID\n if (record.id != null) {\n return `Record ${record.id}`;\n }\n\n return \"Unknown Record\";\n}\n\n/**\n * Get record ID, handling different ID field patterns\n */\nexport function getRecordId(record: any): string {\n if (!record || typeof record !== \"object\") {\n return String(record || \"\");\n }\n\n // Try common ID field patterns\n const idFields = [\"id\", \"uuid\", \"_id\", \"pk\"];\n\n for (const field of idFields) {\n if (record[field] != null) {\n return String(record[field]);\n }\n }\n\n // Fallback to first field value\n const keys = Object.keys(record);\n if (keys.length > 0) {\n return String(record[keys[0]] || \"\");\n }\n\n return \"\";\n}\n","import { createContext, useContext } from 'react';\nimport { createStore, useStore as useZustandStore, type StoreApi } from 'zustand';\n\nimport { createDraftRowsSlice, type DraftRowsSlice } from './draft-rows-slice';\nimport { createRelationInfoSlice, type RelationInfoSlice } from './relation-info-slice';\n\nexport interface SheetsAuthState {\n isAuthenticated: boolean;\n accessToken: string | null;\n expiresAt: string | null;\n identityKey: string | null;\n setAuthenticated: (token: string, expiresAt: string, identityKey?: string | null) => void;\n setUnauthenticated: () => void;\n}\n\nexport type SheetsStoreState = DraftRowsSlice & RelationInfoSlice & SheetsAuthState;\n\nexport function createSheetsStore(): StoreApi<SheetsStoreState> {\n return createStore<SheetsStoreState>((set, get) => ({\n // Draft rows\n ...createDraftRowsSlice(set),\n\n // Relation info cache\n ...createRelationInfoSlice(set, get),\n\n // Auth state (standalone mode)\n isAuthenticated: false,\n accessToken: null,\n expiresAt: null,\n identityKey: null,\n setAuthenticated: (token: string, expiresAt: string, identityKey = null) =>\n set({ isAuthenticated: true, accessToken: token, expiresAt, identityKey }),\n setUnauthenticated: () => set({ isAuthenticated: false, accessToken: null, expiresAt: null, identityKey: null }),\n }));\n}\n\nexport const SheetsStoreContext = createContext<StoreApi<SheetsStoreState> | null>(null);\n\nexport function useSheetsStore<T>(selector: (state: SheetsStoreState) => T): T {\n const store = useContext(SheetsStoreContext);\n if (!store) {\n throw new Error('useSheetsStore must be used within a <SheetsProvider>');\n }\n return useZustandStore(store, selector);\n}\n\nexport function useSheetsStoreApi(): StoreApi<SheetsStoreState> {\n const store = useContext(SheetsStoreContext);\n if (!store) {\n throw new Error('useSheetsStoreApi must be used within a <SheetsProvider>');\n }\n return store;\n}\n"],"mappings":";;;AAAA,SAAS,eAAe,kBAAkB;AAiFnC,IAAM,gBAAgB,cAAyC,IAAI;AAEnE,SAAS,mBAAuC;AACtD,QAAM,MAAM,WAAW,aAAa;AACpC,MAAI,CAAC,KAAK;AACT,UAAM,IAAI,MAAM,yDAAyD;AAAA,EAC1E;AACA,SAAO;AACR;;;ACpEO,SAAS,mBAAmB,UAA2E;AAC5G,QAAM,QAAQ,SAAS,MAAM,IAAI;AACjC,MAAI,MAAM,WAAW,GAAG;AACtB,UAAM,CAAC,YAAY,SAAS,IAAI;AAChC,QAAI,CAAC,cAAc,CAAC,UAAW,QAAO;AACtC,WAAO,EAAE,YAAY,UAAU;AAAA,EACjC;AACA,SAAO;AACT;AAsDO,SAAS,qBAAqB,KAAwC;AAC5E,SAAO;AAAA,IACJ,kBAAkB,CAAC;AAAA,IAEnB,gBAAgB,CAAC,SAAS;AACxB,YAAM,EAAE,UAAU,aAAa,gBAAgB,mBAAmB,YAAY,IAAI;AAElF,YAAM,uBAAuB,kBAAkB,aAAa,gBAAgB,iBAAiB;AAC7F,YAAM,WAAW,cAAc,sBAAsB,iBAAiB;AACtE,YAAM,aAAa,SAAS,oBAAoB,CAAC;AACjD,YA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;","names":["pgFieldToCamelCase","pgFieldToCamelCase","createContext","useContext","createContext","useContext"]}
@@ -3,7 +3,7 @@ import {
3
3
  DATE_TIME_TYPES,
4
4
  EditorFocusTrap,
5
5
  OVERLAY
6
- } from "./chunk-PZL2BCWF.js";
6
+ } from "./chunk-6Y7CZ5VS.js";
7
7
  import {
8
8
  sheetsLocale
9
9
  } from "./chunk-GGECS2BP.js";
@@ -355,4 +355,4 @@ export {
355
355
  resolveDateType,
356
356
  toLocalDateString
357
357
  };
358
- //# sourceMappingURL=date-editor-ZFNDKYBD.js.map
358
+ //# sourceMappingURL=date-editor-G26WKILO.js.map
@@ -1,5 +1,5 @@
1
1
  import { ComponentType } from 'react';
2
- import { MetaQuery } from '@constructive-io/data';
2
+ import { MetaQuery, RowIdentityValue, TableWriteCapability, MetaTable } from '@constructive-io/data';
3
3
 
4
4
  interface FieldMetadata$1 {
5
5
  name: string;
@@ -21,7 +21,7 @@ interface CellTypeResolution {
21
21
  declare function resolveCellType(fieldName: string, fieldMeta?: FieldMetadata$1): CellTypeResolution;
22
22
  declare function isImageField(fieldMeta?: FieldMetadata$1, fieldName?: string): boolean;
23
23
 
24
- type CellType = 'text' | 'textarea' | 'email' | 'url' | 'phone' | 'citext' | 'bpchar' | 'number' | 'integer' | 'smallint' | 'decimal' | 'currency' | 'percentage' | 'date' | 'datetime' | 'time' | 'timestamptz' | 'interval' | 'boolean' | 'toggle' | 'bit' | 'json' | 'jsonb' | 'array' | 'text-array' | 'uuid-array' | 'number-array' | 'integer-array' | 'date-array' | 'geometry' | 'geometry-point' | 'geometry-collection' | 'inet' | 'image' | 'file' | 'video' | 'audio' | 'upload' | 'uuid' | 'color' | 'rating' | 'tags' | 'tsvector' | 'origin' | 'relation' | 'unknown';
24
+ type CellType = 'text' | 'textarea' | 'email' | 'url' | 'phone' | 'citext' | 'bpchar' | 'number' | 'integer' | 'smallint' | 'decimal' | 'currency' | 'percentage' | 'date' | 'datetime' | 'time' | 'timestamptz' | 'interval' | 'boolean' | 'toggle' | 'bit' | 'json' | 'jsonb' | 'array' | 'text-array' | 'uuid-array' | 'number-array' | 'integer-array' | 'date-array' | 'geometry' | 'geometry-point' | 'geometry-collection' | 'inet' | 'image' | 'file' | 'video' | 'audio' | 'upload' | 'attachment' | 'uuid' | 'color' | 'rating' | 'tags' | 'tsvector' | 'origin' | 'relation' | 'unknown';
25
25
  type CellCategory = 'text' | 'numeric' | 'date' | 'boolean' | 'structured' | 'geometric' | 'network' | 'media' | 'special' | 'other';
26
26
  type CellValue = string | number | boolean | Date | null | undefined | Array<any> | Record<string, any>;
27
27
  interface FieldMetadata {
@@ -175,6 +175,12 @@ interface SheetsCell {
175
175
  };
176
176
  }
177
177
 
178
+ /** Result of submitting a draft row */
179
+ interface DraftSubmitResult {
180
+ /** The created row with its metadata-defined primary-key fields. */
181
+ createdRow: Record<string, unknown> | null;
182
+ }
183
+
178
184
  type RelationKind = 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany';
179
185
  interface RelationInfo {
180
186
  kind: RelationKind;
@@ -199,11 +205,45 @@ interface RelationInfoSlice {
199
205
  }
200
206
  declare function buildRelationInfoFromMeta(tableName: string, meta: MetaQuery | undefined): Record<string, RelationInfo> | null;
201
207
 
208
+ /** A row locator accepted by Sheets CRUD operations. */
209
+ type SheetsRowIdentifier = string | number | Readonly<Record<string, RowIdentityValue>>;
210
+ type SheetsMutationOperation = 'create' | 'update' | 'delete';
211
+ type SheetsRowIdentityResolution = Readonly<{
212
+ status: 'identified';
213
+ /** Backwards-compatible scalar for an ordinary `id` PK; otherwise the PK object. */
214
+ identifier: SheetsRowIdentifier;
215
+ /** GraphQL primary-key input, including renamed and composite keys. */
216
+ primaryKey: Readonly<Record<string, RowIdentityValue>>;
217
+ /** Stable, schema-qualified key used by caches, selection, and editors. */
218
+ key: string;
219
+ }> | Readonly<{
220
+ status: 'unavailable';
221
+ reason: 'no-primary-key' | 'invalid-row';
222
+ }>;
223
+ /**
224
+ * Resolve one server row from `_meta`. The familiar scalar `id` contract is kept
225
+ * for existing adapters, while renamed and composite keys use the full PK input.
226
+ */
227
+ declare function resolveSheetsRowIdentity(table: MetaTable, row: Readonly<Record<string, unknown>>): SheetsRowIdentityResolution;
228
+ /** Resolve a public CRUD identifier through the same `_meta` identity contract. */
229
+ declare function resolveSheetsIdentifier(table: MetaTable, identifier: SheetsRowIdentifier): SheetsRowIdentityResolution;
230
+ /** Build the PostGraphile connection filter used by `findOne`. */
231
+ declare function sheetsIdentifierToWhere(table: MetaTable, identifier: SheetsRowIdentifier): Record<string, {
232
+ equalTo: RowIdentityValue;
233
+ }> | null;
234
+ /** Use scalar IDs as cache keys for compatibility; use serialized identities otherwise. */
235
+ declare function sheetsIdentifierCacheKey(table: MetaTable, identifier: SheetsRowIdentifier): string | number | null;
236
+ /** Stable TanStack/selection/editor key with an index fallback only for non-writable rows. */
237
+ declare function sheetsRowKey(table: MetaTable, row: Readonly<Record<string, unknown>>, index: number): string;
238
+ declare function getSheetsWriteCapability(table: MetaTable | null): TableWriteCapability | null;
239
+ declare function canRunSheetsMutation(capability: TableWriteCapability | null, operation: SheetsMutationOperation): boolean;
240
+
202
241
  interface EditorProps {
203
242
  value: unknown;
204
243
  cell: SheetsCell;
205
244
  colKey: string;
206
245
  rowId: string;
246
+ rowIdentifier?: SheetsRowIdentifier | null;
207
247
  rowIndex: number;
208
248
  tableName?: string;
209
249
  fieldMeta?: FieldMetadata$1;
@@ -224,8 +264,8 @@ interface EditorProps {
224
264
  onCommitPatch?: (patch: Record<string, unknown>) => void;
225
265
  /** Dismiss the overlay with no write. */
226
266
  onCancel: () => void;
227
- /** Self-committing editors: submit a client-side draft row, resolving to the server row. */
228
- onSubmitDraftRow?: (draftRowId: string) => Promise<unknown>;
267
+ /** Self-committing editors: submit a client-side draft row and return its creation result. */
268
+ onSubmitDraftRow?: (draftRowId: string) => Promise<DraftSubmitResult>;
229
269
  /** Self-committing editors: invalidate cached data after an out-of-band mutation. */
230
270
  onInvalidateData?: () => void;
231
271
  /** Geometry pre-computed by the OverlayManager (reused `computeOverlayGeometry`). */
@@ -250,4 +290,4 @@ interface CellCreationMetadata {
250
290
  activationBehavior: 'single-click' | 'double-click';
251
291
  }
252
292
 
253
- export { type BaseCellProps as B, type CellCreationMetadata as C, type EditorProps as E, type FieldMetadata$1 as F, type RelationInfo as R, type SheetsCell as S, type TableSchema as T, type SheetsCellKind as a, type CellType as b, type CellCategory as c, type RelationInfoSlice as d, type CellRegistryEntry as e, type CellRenderer as f, type CellPlugin as g, type ColumnSchema as h, type CellValue as i, type FieldMetadata as j, type RelationKind as k, type RowData as l, buildRelationInfoFromMeta as m, isImageField as n, resolveCellType as r };
293
+ export { type BaseCellProps as B, type CellCreationMetadata as C, type DraftSubmitResult as D, type EditorProps as E, type FieldMetadata$1 as F, type RelationInfo as R, type SheetsCell as S, type TableSchema as T, type SheetsCellKind as a, type CellType as b, type CellCategory as c, type RelationInfoSlice as d, type SheetsRowIdentifier as e, type CellRegistryEntry as f, type CellRenderer as g, type CellPlugin as h, type ColumnSchema as i, type CellValue as j, type FieldMetadata as k, type RelationKind as l, type RowData as m, type SheetsRowIdentityResolution as n, buildRelationInfoFromMeta as o, canRunSheetsMutation as p, getSheetsWriteCapability as q, isImageField as r, resolveCellType as s, resolveSheetsIdentifier as t, resolveSheetsRowIdentity as u, sheetsIdentifierCacheKey as v, sheetsIdentifierToWhere as w, sheetsRowKey as x };