@constructive-io/sheets 0.3.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.
- package/LICENSE +21 -0
- package/README.md +188 -0
- package/dist/advanced.cjs +5477 -0
- package/dist/advanced.cjs.map +1 -0
- package/dist/advanced.d.cts +83 -0
- package/dist/advanced.d.ts +83 -0
- package/dist/advanced.js +34 -0
- package/dist/advanced.js.map +1 -0
- package/dist/auth.cjs +1396 -0
- package/dist/auth.cjs.map +1 -0
- package/dist/auth.d.cts +60 -0
- package/dist/auth.d.ts +60 -0
- package/dist/auth.js +19 -0
- package/dist/auth.js.map +1 -0
- package/dist/chunk-4PGPVMZB.js +670 -0
- package/dist/chunk-4PGPVMZB.js.map +1 -0
- package/dist/chunk-FNVHSOQQ.js +1314 -0
- package/dist/chunk-FNVHSOQQ.js.map +1 -0
- package/dist/chunk-GGECS2BP.js +17 -0
- package/dist/chunk-GGECS2BP.js.map +1 -0
- package/dist/chunk-GLVZSPV2.js +43 -0
- package/dist/chunk-GLVZSPV2.js.map +1 -0
- package/dist/chunk-H4JJTMP5.js +160 -0
- package/dist/chunk-H4JJTMP5.js.map +1 -0
- package/dist/chunk-ODUBS2NL.js +100 -0
- package/dist/chunk-ODUBS2NL.js.map +1 -0
- package/dist/chunk-PZL2BCWF.js +168 -0
- package/dist/chunk-PZL2BCWF.js.map +1 -0
- package/dist/chunk-TU7ATZ4X.js +4494 -0
- package/dist/chunk-TU7ATZ4X.js.map +1 -0
- package/dist/chunk-X7DHTSOX.js +21 -0
- package/dist/chunk-X7DHTSOX.js.map +1 -0
- package/dist/chunk-YDQQA46V.js +13 -0
- package/dist/chunk-YDQQA46V.js.map +1 -0
- package/dist/date-editor-CXKKGNL6.js +361 -0
- package/dist/date-editor-CXKKGNL6.js.map +1 -0
- package/dist/editor-props-M6Dh0P9f.d.cts +245 -0
- package/dist/editor-props-M6Dh0P9f.d.ts +245 -0
- package/dist/index.cjs +15861 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1650 -0
- package/dist/index.d.ts +1650 -0
- package/dist/index.js +8470 -0
- package/dist/index.js.map +1 -0
- package/dist/map-picker-VTKDS6CM.js +290 -0
- package/dist/map-picker-VTKDS6CM.js.map +1 -0
- package/dist/sheets-context-CojEFlaY.d.cts +214 -0
- package/dist/sheets-context-Da55TTR9.d.ts +214 -0
- package/dist/testing.cjs +1113 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +45 -0
- package/dist/testing.d.ts +45 -0
- package/dist/testing.js +269 -0
- package/dist/testing.js.map +1 -0
- package/package.json +144 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/testing/index.ts","../src/testing/mock-sheets-provider.tsx","../src/context/sheets-provider.tsx","../src/context/sheets-context.ts","../src/context/sheets-execute.ts","../src/store/sheets-store.ts","../src/store/draft-rows-slice.ts","../src/store/relation-info-slice.ts","../src/utils/relation-utils.ts","../src/auth/utils/token-store.ts","../src/utils/sheets-logger.ts","../src/utils/sheets-i18n.ts"],"sourcesContent":["// Public '/testing' subpath — consumer test harness for @constructive-io/sheets.\n// Not part of the core graph; bundled separately so production consumers never\n// pull in the in-memory mock backend.\nexport * from './mock-sheets-provider';\n","// Consumer test harness for @constructive-io/sheets.\n//\n// Shipped at the '/testing' subpath — NOT part of the core graph. Lets a\n// consumer mount a <Sheets> grid in jsdom/vitest with zero network: a tiny\n// in-memory PostGraphile-shaped backend that serves the `_meta` introspection,\n// list connections, and create/update/delete mutations, while recording every\n// mutation for assertions.\n//\n// This file intentionally uses a few test-grade casts on the mock GraphQL\n// responses (see the `as unknown as MetaQuery` in `buildMetaResponse` and the\n// `as File` narrowing in `executeUpload`). It is a deliberately partial\n// PostGraphile emulator — just enough to render a grid and assert mutations —\n// so the casts are scoped, documented, and never leak into the core graph.\nimport { useMemo } from 'react';\nimport { print } from 'graphql';\nimport type { DocumentNode } from 'graphql';\nimport { QueryClient } from '@tanstack/react-query';\n\nimport {\n\ttoCamelCasePlural,\n\ttoCamelCaseSingular,\n\ttoCreateMutationName,\n\ttoUpdateMutationName,\n\ttoDeleteMutationName,\n} from '@constructive-io/data';\nimport type { MetaQuery } from '@constructive-io/data';\n\nimport { SheetsProvider } from '../context/sheets-provider';\nimport type { SheetsExecuteFn, SheetsUploadFn, SheetsUploadOptions } from '../context/sheets-execute';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface MockTableField {\n\tname: string;\n\tgqlType: string;\n\tisArray?: boolean;\n\tpgType?: string;\n\tsubtype?: string;\n}\n\nexport interface MockTable {\n\tname: string;\n\tfields: MockTableField[];\n\trows: Record<string, unknown>[];\n}\n\nexport interface RecordedMutation {\n\top: 'create' | 'update' | 'delete' | 'upload';\n\ttableName: string;\n\tvariables: Record<string, unknown>;\n\tat: number;\n}\n\nexport interface MockSheetsOptions {\n\ttables: MockTable[];\n\tonMutation?: (m: RecordedMutation) => void;\n}\n\nexport interface MockExecuteHandle {\n\texecute: SheetsExecuteFn;\n\texecuteUpload: SheetsUploadFn;\n\tmutations: RecordedMutation[];\n\treset(): void;\n}\n\n// ============================================================================\n// Document stringification (mirrors context/sheets-execute.ts)\n// ============================================================================\n\ntype ExecutableDocument = DocumentNode | string | unknown;\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\treturn String(document ?? '');\n}\n\n// ============================================================================\n// Meta response synthesis\n// ============================================================================\n\nfunction buildMetaField(field: MockTableField) {\n\treturn {\n\t\tname: field.name,\n\t\tisNotNull: false,\n\t\thasDefault: false,\n\t\ttype: {\n\t\t\tgqlType: field.gqlType,\n\t\t\tisArray: field.isArray ?? false,\n\t\t\tpgType: field.pgType ?? 'text',\n\t\t\tisNotNull: false,\n\t\t\thasDefault: false,\n\t\t\tsubtype: field.subtype ?? null,\n\t\t},\n\t};\n}\n\nfunction buildMetaTable(table: MockTable) {\n\treturn {\n\t\tname: table.name,\n\t\tschemaName: 'public',\n\t\tquery: {\n\t\t\tall: toCamelCasePlural(table.name),\n\t\t\tcreate: toCreateMutationName(table.name),\n\t\t\tdelete: toDeleteMutationName(table.name),\n\t\t\tone: toCamelCaseSingular(table.name),\n\t\t\tupdate: toUpdateMutationName(table.name),\n\t\t},\n\t\tfields: table.fields.map(buildMetaField),\n\t\tinflection: {\n\t\t\tallRows: toCamelCasePlural(table.name),\n\t\t\tconnection: toCamelCasePlural(table.name),\n\t\t\ttableType: table.name,\n\t\t},\n\t\tindexes: [],\n\t\tconstraints: { primaryKey: null, unique: [], foreignKey: [] },\n\t\tforeignKeyConstraints: [],\n\t\tprimaryKeyConstraints: [],\n\t\tuniqueConstraints: [],\n\t\trelations: { belongsTo: [], has: [], hasOne: [], hasMany: [], manyToMany: [] },\n\t};\n}\n\n// Pragmatic test-grade cast: we synthesize a loose subset of the `_meta`\n// introspection shape (enough for cleanTable + the grid render path). The full\n// MetaschemaTable union has many optional v4/v5 fields we don't populate, so a\n// single structural cast keeps this fixture readable without re-declaring the\n// entire schema. This is test-only code on a separate subpath.\nfunction buildMetaResponse(tables: MockTable[]): MetaQuery {\n\treturn {\n\t\t_meta: {\n\t\t\ttables: tables.map(buildMetaTable),\n\t\t},\n\t} as unknown as MetaQuery;\n}\n\n// ============================================================================\n// List response synthesis\n// ============================================================================\n\nfunction buildListResponse(table: MockTable): Record<string, unknown> {\n\tconst field = toCamelCasePlural(table.name);\n\treturn {\n\t\t[field]: {\n\t\t\tnodes: table.rows,\n\t\t\ttotalCount: table.rows.length,\n\t\t\tpageInfo: {\n\t\t\t\thasNextPage: false,\n\t\t\t\thasPreviousPage: false,\n\t\t\t\tendCursor: null,\n\t\t\t\tstartCursor: null,\n\t\t\t},\n\t\t},\n\t};\n}\n\n// ============================================================================\n// Mutation row synthesis\n// ============================================================================\n\nlet mockIdCounter = 0;\n\nfunction synthesizeId(): string {\n\tmockIdCounter += 1;\n\treturn `mock-${mockIdCounter}`;\n}\n\nfunction extractMutationInput(variables: Record<string, unknown> | undefined): Record<string, unknown> {\n\tconst input = variables?.input;\n\treturn input && typeof input === 'object' ? (input as Record<string, unknown>) : {};\n}\n\nfunction synthesizeCreatedRow(\n\ttable: MockTable,\n\tsingular: string,\n\tvariables: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tconst input = extractMutationInput(variables);\n\tconst data = (input[singular] as Record<string, unknown>) ?? {};\n\tconst row: Record<string, unknown> = { id: synthesizeId(), ...data };\n\ttable.rows.push(row);\n\treturn row;\n}\n\nfunction synthesizeUpdatedRow(\n\ttable: MockTable,\n\tvariables: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tconst input = extractMutationInput(variables);\n\tconst id = input.id;\n\t// Patch field name varies by entity (e.g. `userPatch`); take the first\n\t// object-valued non-id key as the patch payload.\n\tlet patch: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(input)) {\n\t\tif (key === 'id') continue;\n\t\tif (value && typeof value === 'object') {\n\t\t\tpatch = value as Record<string, unknown>;\n\t\t\tbreak;\n\t\t}\n\t}\n\tconst existing = table.rows.find((r) => r.id === id);\n\tconst merged: Record<string, unknown> = { ...(existing ?? { id }), ...patch };\n\tif (existing) {\n\t\tObject.assign(existing, patch);\n\t} else {\n\t\ttable.rows.push(merged);\n\t}\n\treturn merged;\n}\n\n// ============================================================================\n// Detection helpers\n// ============================================================================\n\nfunction isMetaQuery(query: string): boolean {\n\treturn query.includes('_meta');\n}\n\nfunction isMutationDocument(query: string): boolean {\n\t// PostGraphile mutation docs are `mutation Xxx(...) { ... }`; a leading\n\t// `mutation` keyword disambiguates them from list queries that may select a\n\t// relation field whose name collides with a mutation name as a substring.\n\treturn /(^|\\s)mutation(\\s|\\{)/.test(query);\n}\n\nfunction findMutationTable(\n\tquery: string,\n\ttables: MockTable[],\n): { table: MockTable; op: 'create' | 'update' | 'delete'; mutationName: string; singular: string } | null {\n\t// Longest-match: a table whose mutation name is a substring of another's\n\t// (e.g. createUser vs createUserProfile) must not win over the exact one.\n\tlet best: { table: MockTable; op: 'create' | 'update' | 'delete'; mutationName: string; singular: string } | null = null;\n\tfor (const table of tables) {\n\t\tconst candidates: Array<{ op: 'create' | 'update' | 'delete'; mutationName: string }> = [\n\t\t\t{ op: 'create', mutationName: toCreateMutationName(table.name) },\n\t\t\t{ op: 'update', mutationName: toUpdateMutationName(table.name) },\n\t\t\t{ op: 'delete', mutationName: toDeleteMutationName(table.name) },\n\t\t];\n\t\tfor (const c of candidates) {\n\t\t\tif (query.includes(c.mutationName) && (!best || c.mutationName.length > best.mutationName.length)) {\n\t\t\t\tbest = { table, op: c.op, mutationName: c.mutationName, singular: toCamelCaseSingular(table.name) };\n\t\t\t}\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction findListTable(query: string, tables: MockTable[]): MockTable | null {\n\t// Longest-match for the same substring-collision reason.\n\tlet best: MockTable | null = null;\n\tlet bestLen = 0;\n\tfor (const table of tables) {\n\t\tconst plural = toCamelCasePlural(table.name);\n\t\tif (query.includes(plural) && plural.length > bestLen) {\n\t\t\tbest = table;\n\t\t\tbestLen = plural.length;\n\t\t}\n\t}\n\treturn best;\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\nexport function createMockExecute(opts: MockSheetsOptions): MockExecuteHandle {\n\tconst mutations: RecordedMutation[] = [];\n\n\tfunction record(m: RecordedMutation) {\n\t\tmutations.push(m);\n\t\topts.onMutation?.(m);\n\t}\n\n\tconst execute: SheetsExecuteFn = async <T = unknown>(\n\t\tdocument: ExecutableDocument,\n\t\tvariables?: Record<string, unknown>,\n\t): Promise<T> => {\n\t\tconst query = documentToString(document);\n\n\t\t// 1. Introspection (_meta) — detected by the `_meta` selection.\n\t\tif (isMetaQuery(query)) {\n\t\t\treturn buildMetaResponse(opts.tables) as T;\n\t\t}\n\n\t\t// 2. Mutations — detected by a create/update/delete mutation name.\n\t\tconst mutationMatch = isMutationDocument(query) ? findMutationTable(query, opts.tables) : null;\n\t\tif (mutationMatch) {\n\t\t\tconst { table, op, mutationName, singular } = mutationMatch;\n\t\t\trecord({ op, tableName: table.name, variables: variables ?? {}, at: Date.now() });\n\n\t\t\tif (op === 'delete') {\n\t\t\t\tconst input = extractMutationInput(variables);\n\t\t\t\tconst id = input.id ?? null;\n\t\t\t\ttable.rows = table.rows.filter((r) => r.id !== id);\n\t\t\t\treturn { [mutationName]: { deletedNodeId: id, clientMutationId: null } } as T;\n\t\t\t}\n\n\t\t\tconst row =\n\t\t\t\top === 'create'\n\t\t\t\t\t? synthesizeCreatedRow(table, singular, variables)\n\t\t\t\t\t: synthesizeUpdatedRow(table, variables);\n\t\t\treturn { [mutationName]: { [singular]: row } } as T;\n\t\t}\n\n\t\t// 3. List query (table connection) — detected by the camelPlural field.\n\t\tconst listTable = findListTable(query, opts.tables);\n\t\tif (listTable) {\n\t\t\treturn buildListResponse(listTable) as T;\n\t\t}\n\n\t\t// Unknown operation: return an empty object so callers degrade gracefully.\n\t\treturn {} as T;\n\t};\n\n\tconst executeUpload: SheetsUploadFn = async (\n\t\tfile: File,\n\t\tpath?: string,\n\t\toptions?: SheetsUploadOptions,\n\t): Promise<{ url: string }> => {\n\t\tconst name = (file as File)?.name ?? 'file';\n\t\trecord({\n\t\t\top: 'upload',\n\t\t\ttableName: options?.tableName ?? '',\n\t\t\tvariables: {\n\t\t\t\tname,\n\t\t\t\t...(path !== undefined && { path }),\n\t\t\t\t...(options?.fieldName !== undefined && { fieldName: options.fieldName }),\n\t\t\t\t...(options?.recordId !== undefined && { recordId: options.recordId }),\n\t\t\t},\n\t\t\tat: Date.now(),\n\t\t});\n\t\treturn { url: 'mock://uploaded/' + name };\n\t};\n\n\tfunction reset() {\n\t\tmutations.length = 0;\n\t}\n\n\treturn { execute, executeUpload, mutations, reset };\n}\n\n// ============================================================================\n// Provider\n// ============================================================================\n\nexport interface MockSheetsProviderProps {\n\toptions: MockSheetsOptions;\n\tchildren: React.ReactNode;\n}\n\nexport function MockSheetsProvider({ options, children }: MockSheetsProviderProps) {\n\t// Build the mock backend + an isolated QueryClient ONCE per mount. Tests that\n\t// need a fresh harness should remount (e.g. via `key`), so an empty dep array\n\t// is correct — `options` is treated as mount-time configuration.\n\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\tconst { execute, executeUpload } = useMemo(() => createMockExecute(options), []);\n\n\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\tconst queryClient = useMemo(\n\t\t() =>\n\t\t\tnew QueryClient({\n\t\t\t\tdefaultOptions: {\n\t\t\t\t\tqueries: { retry: false, gcTime: 0 },\n\t\t\t\t\tmutations: { retry: false },\n\t\t\t\t},\n\t\t\t}),\n\t\t[],\n\t);\n\n\treturn (\n\t\t<SheetsProvider\n\t\t\tconfig={{\n\t\t\t\tendpoint: 'mock://sheets',\n\t\t\t\tauth: { mode: 'embedded', getToken: () => 'test' },\n\t\t\t\texecute,\n\t\t\t\texecuteUpload,\n\t\t\t\tqueryClient,\n\t\t\t}}\n\t\t>\n\t\t\t{children}\n\t\t</SheetsProvider>\n\t);\n}\n\n// ============================================================================\n// Ready fixture\n// ============================================================================\n\nexport const usersFixture: MockTable = {\n\tname: 'users',\n\tfields: [\n\t\t{ name: 'id', gqlType: 'UUID', pgType: 'uuid' },\n\t\t{ name: 'name', gqlType: 'String', pgType: 'text' },\n\t\t{ name: 'email', gqlType: 'String', pgType: 'text' },\n\t\t{ name: 'isActive', gqlType: 'Boolean', pgType: 'boolean' },\n\t\t{ name: 'createdAt', gqlType: 'Datetime', pgType: 'timestamptz' },\n\t],\n\trows: [\n\t\t{\n\t\t\tid: '00000000-0000-0000-0000-000000000001',\n\t\t\tname: 'Ada Lovelace',\n\t\t\temail: 'ada@example.com',\n\t\t\tisActive: true,\n\t\t\tcreatedAt: '2024-01-01T00:00:00Z',\n\t\t},\n\t\t{\n\t\t\tid: '00000000-0000-0000-0000-000000000002',\n\t\t\tname: 'Alan Turing',\n\t\t\temail: 'alan@example.com',\n\t\t\tisActive: false,\n\t\t\tcreatedAt: '2024-01-02T00:00:00Z',\n\t\t},\n\t],\n};\n","import { useEffect, useMemo, useRef } from 'react';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\n\nimport { SheetsContext, type SheetsConfig, type SheetsContextValue, type SheetsScopeKey } from './sheets-context';\nimport { createSheetsExecute, createSheetsUpload, type SheetsExecuteFn, type SheetsUploadFn } 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';\n\nimport type { StoreApi } from 'zustand';\n\ninterface SheetsProviderProps {\n\tconfig: SheetsConfig;\n\tchildren: React.ReactNode;\n}\n\nexport function SheetsProvider({ config, children }: SheetsProviderProps) {\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\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);\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 () => storeRef.current?.getState().accessToken ?? null;\n\t}, [config.auth]);\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\t// Create upload function\n\tconst executeUpload: SheetsUploadFn = useMemo(() => {\n\t\tif (config.executeUpload) return config.executeUpload;\n\t\treturn createSheetsUpload(config, getToken);\n\t}, [config, getToken]);\n\n\t// Scope key for React Query cache isolation\n\tconst scopeKey: SheetsScopeKey = useMemo(\n\t\t() => ({\n\t\t\tdatabaseId: config.databaseId ?? null,\n\t\t\tendpoint: config.endpoint,\n\t\t}),\n\t\t[config.databaseId, config.endpoint],\n\t);\n\n\tconst contextValue: SheetsContextValue = useMemo(\n\t\t() => ({ config, execute, executeUpload, scopeKey }),\n\t\t[config, execute, executeUpload, scopeKey],\n\t);\n\n\treturn (\n\t\t<QueryClientProvider client={queryClient}>\n\t\t\t<SheetsStoreContext.Provider value={storeRef.current}>\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","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}\n\nexport interface SheetsAuthStandalone {\n\tmode: 'standalone';\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/** 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\tscopeKey: SheetsScopeKey;\n}\n\nexport interface SheetsScopeKey {\n\tdatabaseId: string | null;\n\tendpoint: string;\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 { DocumentNode } from 'graphql';\nimport { print } from 'graphql';\n\nimport { createError, DataError, TypedDocumentString } from '@constructive-io/data';\n\nimport type { SheetsConfig } from './sheets-context';\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/**\n * Result of an upload through the seam. `url` is the only guaranteed field;\n * the REST upload endpoint also returns `{ filename, mime, size }` (and may\n * return server-internal extras). Keeping it open-ended lets callers read the\n * richer metadata while a bare `{ url }` (e.g. the mock) still satisfies it.\n */\nexport type SheetsUploadResult = { url: string } & Record<string, unknown>;\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): DataError | 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 DataError) 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 createSheetsUpload(config: SheetsConfig, getToken: () => string | null): SheetsUploadFn {\n\t// `path` is appended to the form when present; `options` carries optional\n\t// field/row metadata + progress for injected implementations. The default\n\t// REST transport has no progress channel, so onProgress is a no-op here.\n\treturn async (file: File, path?: string): Promise<SheetsUploadResult> => {\n\t\tif (!config.endpoint) {\n\t\t\tthrow createError.badRequest('No GraphQL endpoint configured.');\n\t\t}\n\t\tconst url = config.endpoint.replace(/\\/graphql\\/?$/, '/upload');\n\t\tconst token = getToken();\n\n\t\tconst formData = new FormData();\n\t\tformData.append('file', file);\n\t\tif (path) formData.append('path', path);\n\n\t\tconst headers: Record<string, string> = {};\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: formData,\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\tif (response.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 (response.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\ttry {\n\t\t\t\tconst body = (await response.json()) as GraphQLResponse;\n\t\t\t\tconst graphqlError = parseGraphQLResponse(body, config.onAuthError);\n\t\t\t\tif (graphqlError) {\n\t\t\t\t\tthrow graphqlError;\n\t\t\t\t}\n\t\t\t\tif (body.errors?.length) {\n\t\t\t\t\tconst firstError = body.errors[0];\n\t\t\t\t\tthrow createError.graphql(firstError.message || 'Upload failed', firstError.extensions?.code);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof DataError) throw error;\n\t\t\t}\n\t\t\t// Specific user-facing messages for the common REST upload failures.\n\t\t\t// Reached only when the body carried no GraphQL auth/error to surface.\n\t\t\tif (response.status === 400) throw createError.badRequest('No file provided for upload.');\n\t\t\tif (response.status === 413) throw createError.badRequest('File is too large. Maximum size is 10 MB.');\n\t\t\tthrow createError.badRequest(`Upload failed: ${response.status} ${response.statusText}`);\n\t\t}\n\n\t\tconst result = (await response.json()) as GraphQLResponse;\n\t\tif (result.errors?.length) {\n\t\t\tconst graphqlError = parseGraphQLResponse(result, config.onAuthError);\n\t\t\tif (graphqlError) {\n\t\t\t\tthrow graphqlError;\n\t\t\t}\n\t\t\tconst firstError = result.errors[0];\n\t\t\tthrow createError.graphql(firstError.message || 'Upload failed', firstError.extensions?.code);\n\t\t}\n\n\t\treturn result as SheetsUploadResult;\n\t};\n}\n\nexport { DataError } from '@constructive-io/data';\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 setAuthenticated: (token: string, expiresAt: string) => 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 setAuthenticated: (token: string, expiresAt: string) =>\n set({ isAuthenticated: true, accessToken: token, expiresAt }),\n setUnauthenticated: () => set({ isAuthenticated: false, accessToken: null, expiresAt: 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","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 const nextMap = {\n ...(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 = {\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 = {\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","const KEY_PREFIX = 'sheets-auth-token';\n\nfunction storageKey(databaseId: string): string {\n\treturn `${KEY_PREFIX}:${databaseId}`;\n}\n\nfunction getStorage(): Storage | null {\n\tif (typeof window === 'undefined') return null;\n\ttry {\n\t\treturn window.localStorage;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport interface StoredToken {\n\taccessToken: string;\n\texpiresAt: string;\n}\n\nexport function getStoredToken(databaseId: string): StoredToken | null {\n\tconst storage = getStorage();\n\tif (!storage) return null;\n\n\ttry {\n\t\tconst raw = storage.getItem(storageKey(databaseId));\n\t\tif (!raw) return null;\n\t\tconst parsed = JSON.parse(raw) as StoredToken;\n\t\tif (!parsed.accessToken || !parsed.expiresAt) return null;\n\t\treturn parsed;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function setStoredToken(databaseId: string, accessToken: string, expiresAt: string): void {\n\tconst storage = getStorage();\n\tif (!storage) return;\n\n\ttry {\n\t\tconst data: StoredToken = { accessToken, expiresAt };\n\t\tstorage.setItem(storageKey(databaseId), JSON.stringify(data));\n\t} catch {\n\t\t// Silently fail — localStorage might be full or unavailable\n\t}\n}\n\nexport function clearStoredToken(databaseId: string): void {\n\tconst storage = getStorage();\n\tif (!storage) return;\n\n\ttry {\n\t\tstorage.removeItem(storageKey(databaseId));\n\t} catch {\n\t\t// Silently fail\n\t}\n}\n","/**\n * Injectable logger seam for @constructive-io/sheets.\n *\n * The host app may provide a custom logger via SheetsConfig.logger. The provider\n * installs it into this module singleton (see sheets-provider.tsx), so any module\n * or hook can log without threading the logger through props/context.\n *\n * Default behaviour matches the prior console.* calls. `debug` is omitted from the\n * default logger (no-op) so verbose diagnostics stay silent unless a host opts in.\n */\nexport interface SheetsLogger {\n\tdebug?(msg: string, ctx?: unknown): void;\n\twarn(msg: string, ctx?: unknown): void;\n\terror(msg: string, ctx?: unknown): void;\n}\n\nconst defaultLogger: SheetsLogger = {\n\twarn: (...a) => console.warn(...a),\n\terror: (...a) => console.error(...a),\n\t// debug omitted = no-op\n};\n\nlet active: SheetsLogger = defaultLogger;\n\n/**\n * Install (or reset) the active logger. Pass a host logger to override; pass\n * null/undefined to restore the default. Host overrides are merged over the\n * default so a partial logger still gets working warn/error.\n */\nexport function setSheetsLogger(l?: SheetsLogger | null): void {\n\tactive = l ? { ...defaultLogger, ...l } : defaultLogger;\n}\n\n/** Get the active logger. Safe to call anywhere (returns the default until set). */\nexport function sheetsLogger(): SheetsLogger {\n\treturn active;\n}\n","/**\n * Locale seam for @constructive-io/sheets.\n *\n * The host app may set a BCP-47 locale via SheetsConfig.locale. The provider\n * installs it into this module singleton (see sheets-provider.tsx), so any cell\n * renderer / editor can format dates and numbers locale-aware without threading\n * the locale through props/context. Defaults to 'en-US' (the prior hardcoded\n * behavior), so omitting `locale` changes nothing.\n */\nconst DEFAULT_LOCALE = 'en-US';\n\nlet active: string = DEFAULT_LOCALE;\n\n/** Install (or reset) the active locale. Pass null/undefined to restore the default. */\nexport function setSheetsLocale(locale?: string | null): void {\n\tactive = locale || DEFAULT_LOCALE;\n}\n\n/** Get the active locale (BCP-47). Safe to call anywhere; returns 'en-US' until set. */\nexport function sheetsLocale(): string {\n\treturn active;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaA,IAAAA,gBAAwB;AACxB,IAAAC,kBAAsB;AAEtB,IAAAC,sBAA4B;AAE5B,IAAAC,eAMO;;;ACxBP,IAAAC,gBAA2C;AAC3C,yBAAiD;;;ACDjD,mBAA0C;AA+DnC,IAAM,oBAAgB,4BAAyC,IAAI;;;AC9D1E,qBAAsB;AAEtB,kBAA4D;AAqP5D,IAAAC,eAA0B;AAxM1B,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,eAAO,sBAAM,QAAwB;AAAA,EACtC;AACA,MAAI,aAAa,QAAQ,aAAa,QAAW;AAChD,UAAM,wBAAY,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,aAA4C;AACpG,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;AAC1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A,IACnD,EAAE,MAAM,YAAY,SAAS,WAAW,QAAQ,UAAU;AAAA,IAC1D,EAAE,MAAM,aAAa,SAAS,YAAY,QAAQ,cAAc;AAAA,EACjE;AAAA,EACA,MAAM;AAAA,IACL;AAAA,MACC,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,OAAO;AAAA,MACP,UAAU;AAAA,MACV,WAAW;AAAA,IACZ;AAAA,IACA;AAAA,MACC,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,OAAO;AAAA,MACP,UAAU;AAAA,MACV,WAAW;AAAA,IACZ;AAAA,EACD;AACD;","names":["import_react","import_graphql","import_react_query","import_data","import_react","import_data","import_react","import_inflekt","import_data","import_data","active","import_jsx_runtime","documentToString"]}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
+
import { S as SheetsExecuteFn, a as SheetsUploadFn } from './sheets-context-CojEFlaY.cjs';
|
|
3
|
+
import 'react';
|
|
4
|
+
import '@tanstack/react-query';
|
|
5
|
+
import 'graphql';
|
|
6
|
+
import '@constructive-io/data';
|
|
7
|
+
import './editor-props-M6Dh0P9f.cjs';
|
|
8
|
+
|
|
9
|
+
interface MockTableField {
|
|
10
|
+
name: string;
|
|
11
|
+
gqlType: string;
|
|
12
|
+
isArray?: boolean;
|
|
13
|
+
pgType?: string;
|
|
14
|
+
subtype?: string;
|
|
15
|
+
}
|
|
16
|
+
interface MockTable {
|
|
17
|
+
name: string;
|
|
18
|
+
fields: MockTableField[];
|
|
19
|
+
rows: Record<string, unknown>[];
|
|
20
|
+
}
|
|
21
|
+
interface RecordedMutation {
|
|
22
|
+
op: 'create' | 'update' | 'delete' | 'upload';
|
|
23
|
+
tableName: string;
|
|
24
|
+
variables: Record<string, unknown>;
|
|
25
|
+
at: number;
|
|
26
|
+
}
|
|
27
|
+
interface MockSheetsOptions {
|
|
28
|
+
tables: MockTable[];
|
|
29
|
+
onMutation?: (m: RecordedMutation) => void;
|
|
30
|
+
}
|
|
31
|
+
interface MockExecuteHandle {
|
|
32
|
+
execute: SheetsExecuteFn;
|
|
33
|
+
executeUpload: SheetsUploadFn;
|
|
34
|
+
mutations: RecordedMutation[];
|
|
35
|
+
reset(): void;
|
|
36
|
+
}
|
|
37
|
+
declare function createMockExecute(opts: MockSheetsOptions): MockExecuteHandle;
|
|
38
|
+
interface MockSheetsProviderProps {
|
|
39
|
+
options: MockSheetsOptions;
|
|
40
|
+
children: React.ReactNode;
|
|
41
|
+
}
|
|
42
|
+
declare function MockSheetsProvider({ options, children }: MockSheetsProviderProps): react_jsx_runtime.JSX.Element;
|
|
43
|
+
declare const usersFixture: MockTable;
|
|
44
|
+
|
|
45
|
+
export { type MockExecuteHandle, type MockSheetsOptions, MockSheetsProvider, type MockSheetsProviderProps, type MockTable, type MockTableField, type RecordedMutation, createMockExecute, usersFixture };
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
+
import { S as SheetsExecuteFn, a as SheetsUploadFn } from './sheets-context-Da55TTR9.js';
|
|
3
|
+
import 'react';
|
|
4
|
+
import '@tanstack/react-query';
|
|
5
|
+
import 'graphql';
|
|
6
|
+
import '@constructive-io/data';
|
|
7
|
+
import './editor-props-M6Dh0P9f.js';
|
|
8
|
+
|
|
9
|
+
interface MockTableField {
|
|
10
|
+
name: string;
|
|
11
|
+
gqlType: string;
|
|
12
|
+
isArray?: boolean;
|
|
13
|
+
pgType?: string;
|
|
14
|
+
subtype?: string;
|
|
15
|
+
}
|
|
16
|
+
interface MockTable {
|
|
17
|
+
name: string;
|
|
18
|
+
fields: MockTableField[];
|
|
19
|
+
rows: Record<string, unknown>[];
|
|
20
|
+
}
|
|
21
|
+
interface RecordedMutation {
|
|
22
|
+
op: 'create' | 'update' | 'delete' | 'upload';
|
|
23
|
+
tableName: string;
|
|
24
|
+
variables: Record<string, unknown>;
|
|
25
|
+
at: number;
|
|
26
|
+
}
|
|
27
|
+
interface MockSheetsOptions {
|
|
28
|
+
tables: MockTable[];
|
|
29
|
+
onMutation?: (m: RecordedMutation) => void;
|
|
30
|
+
}
|
|
31
|
+
interface MockExecuteHandle {
|
|
32
|
+
execute: SheetsExecuteFn;
|
|
33
|
+
executeUpload: SheetsUploadFn;
|
|
34
|
+
mutations: RecordedMutation[];
|
|
35
|
+
reset(): void;
|
|
36
|
+
}
|
|
37
|
+
declare function createMockExecute(opts: MockSheetsOptions): MockExecuteHandle;
|
|
38
|
+
interface MockSheetsProviderProps {
|
|
39
|
+
options: MockSheetsOptions;
|
|
40
|
+
children: React.ReactNode;
|
|
41
|
+
}
|
|
42
|
+
declare function MockSheetsProvider({ options, children }: MockSheetsProviderProps): react_jsx_runtime.JSX.Element;
|
|
43
|
+
declare const usersFixture: MockTable;
|
|
44
|
+
|
|
45
|
+
export { type MockExecuteHandle, type MockSheetsOptions, MockSheetsProvider, type MockSheetsProviderProps, type MockTable, type MockTableField, type RecordedMutation, createMockExecute, usersFixture };
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import {
|
|
3
|
+
SheetsProvider
|
|
4
|
+
} from "./chunk-ODUBS2NL.js";
|
|
5
|
+
import "./chunk-H4JJTMP5.js";
|
|
6
|
+
import "./chunk-GLVZSPV2.js";
|
|
7
|
+
import "./chunk-4PGPVMZB.js";
|
|
8
|
+
import "./chunk-GGECS2BP.js";
|
|
9
|
+
import "./chunk-X7DHTSOX.js";
|
|
10
|
+
|
|
11
|
+
// src/testing/mock-sheets-provider.tsx
|
|
12
|
+
import { useMemo } from "react";
|
|
13
|
+
import { print } from "graphql";
|
|
14
|
+
import { QueryClient } from "@tanstack/react-query";
|
|
15
|
+
import {
|
|
16
|
+
toCamelCasePlural,
|
|
17
|
+
toCamelCaseSingular,
|
|
18
|
+
toCreateMutationName,
|
|
19
|
+
toUpdateMutationName,
|
|
20
|
+
toDeleteMutationName
|
|
21
|
+
} from "@constructive-io/data";
|
|
22
|
+
import { jsx } from "react/jsx-runtime";
|
|
23
|
+
function documentToString(document) {
|
|
24
|
+
if (typeof document === "string") return document;
|
|
25
|
+
if (document instanceof String) return document.toString();
|
|
26
|
+
if (document && typeof document === "object" && "kind" in document) {
|
|
27
|
+
return print(document);
|
|
28
|
+
}
|
|
29
|
+
return String(document ?? "");
|
|
30
|
+
}
|
|
31
|
+
function buildMetaField(field) {
|
|
32
|
+
return {
|
|
33
|
+
name: field.name,
|
|
34
|
+
isNotNull: false,
|
|
35
|
+
hasDefault: false,
|
|
36
|
+
type: {
|
|
37
|
+
gqlType: field.gqlType,
|
|
38
|
+
isArray: field.isArray ?? false,
|
|
39
|
+
pgType: field.pgType ?? "text",
|
|
40
|
+
isNotNull: false,
|
|
41
|
+
hasDefault: false,
|
|
42
|
+
subtype: field.subtype ?? null
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function buildMetaTable(table) {
|
|
47
|
+
return {
|
|
48
|
+
name: table.name,
|
|
49
|
+
schemaName: "public",
|
|
50
|
+
query: {
|
|
51
|
+
all: toCamelCasePlural(table.name),
|
|
52
|
+
create: toCreateMutationName(table.name),
|
|
53
|
+
delete: toDeleteMutationName(table.name),
|
|
54
|
+
one: toCamelCaseSingular(table.name),
|
|
55
|
+
update: toUpdateMutationName(table.name)
|
|
56
|
+
},
|
|
57
|
+
fields: table.fields.map(buildMetaField),
|
|
58
|
+
inflection: {
|
|
59
|
+
allRows: toCamelCasePlural(table.name),
|
|
60
|
+
connection: toCamelCasePlural(table.name),
|
|
61
|
+
tableType: table.name
|
|
62
|
+
},
|
|
63
|
+
indexes: [],
|
|
64
|
+
constraints: { primaryKey: null, unique: [], foreignKey: [] },
|
|
65
|
+
foreignKeyConstraints: [],
|
|
66
|
+
primaryKeyConstraints: [],
|
|
67
|
+
uniqueConstraints: [],
|
|
68
|
+
relations: { belongsTo: [], has: [], hasOne: [], hasMany: [], manyToMany: [] }
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
function buildMetaResponse(tables) {
|
|
72
|
+
return {
|
|
73
|
+
_meta: {
|
|
74
|
+
tables: tables.map(buildMetaTable)
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function buildListResponse(table) {
|
|
79
|
+
const field = toCamelCasePlural(table.name);
|
|
80
|
+
return {
|
|
81
|
+
[field]: {
|
|
82
|
+
nodes: table.rows,
|
|
83
|
+
totalCount: table.rows.length,
|
|
84
|
+
pageInfo: {
|
|
85
|
+
hasNextPage: false,
|
|
86
|
+
hasPreviousPage: false,
|
|
87
|
+
endCursor: null,
|
|
88
|
+
startCursor: null
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
var mockIdCounter = 0;
|
|
94
|
+
function synthesizeId() {
|
|
95
|
+
mockIdCounter += 1;
|
|
96
|
+
return `mock-${mockIdCounter}`;
|
|
97
|
+
}
|
|
98
|
+
function extractMutationInput(variables) {
|
|
99
|
+
const input = variables?.input;
|
|
100
|
+
return input && typeof input === "object" ? input : {};
|
|
101
|
+
}
|
|
102
|
+
function synthesizeCreatedRow(table, singular, variables) {
|
|
103
|
+
const input = extractMutationInput(variables);
|
|
104
|
+
const data = input[singular] ?? {};
|
|
105
|
+
const row = { id: synthesizeId(), ...data };
|
|
106
|
+
table.rows.push(row);
|
|
107
|
+
return row;
|
|
108
|
+
}
|
|
109
|
+
function synthesizeUpdatedRow(table, variables) {
|
|
110
|
+
const input = extractMutationInput(variables);
|
|
111
|
+
const id = input.id;
|
|
112
|
+
let patch = {};
|
|
113
|
+
for (const [key, value] of Object.entries(input)) {
|
|
114
|
+
if (key === "id") continue;
|
|
115
|
+
if (value && typeof value === "object") {
|
|
116
|
+
patch = value;
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const existing = table.rows.find((r) => r.id === id);
|
|
121
|
+
const merged = { ...existing ?? { id }, ...patch };
|
|
122
|
+
if (existing) {
|
|
123
|
+
Object.assign(existing, patch);
|
|
124
|
+
} else {
|
|
125
|
+
table.rows.push(merged);
|
|
126
|
+
}
|
|
127
|
+
return merged;
|
|
128
|
+
}
|
|
129
|
+
function isMetaQuery(query) {
|
|
130
|
+
return query.includes("_meta");
|
|
131
|
+
}
|
|
132
|
+
function isMutationDocument(query) {
|
|
133
|
+
return /(^|\s)mutation(\s|\{)/.test(query);
|
|
134
|
+
}
|
|
135
|
+
function findMutationTable(query, tables) {
|
|
136
|
+
let best = null;
|
|
137
|
+
for (const table of tables) {
|
|
138
|
+
const candidates = [
|
|
139
|
+
{ op: "create", mutationName: toCreateMutationName(table.name) },
|
|
140
|
+
{ op: "update", mutationName: toUpdateMutationName(table.name) },
|
|
141
|
+
{ op: "delete", mutationName: toDeleteMutationName(table.name) }
|
|
142
|
+
];
|
|
143
|
+
for (const c of candidates) {
|
|
144
|
+
if (query.includes(c.mutationName) && (!best || c.mutationName.length > best.mutationName.length)) {
|
|
145
|
+
best = { table, op: c.op, mutationName: c.mutationName, singular: toCamelCaseSingular(table.name) };
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return best;
|
|
150
|
+
}
|
|
151
|
+
function findListTable(query, tables) {
|
|
152
|
+
let best = null;
|
|
153
|
+
let bestLen = 0;
|
|
154
|
+
for (const table of tables) {
|
|
155
|
+
const plural = toCamelCasePlural(table.name);
|
|
156
|
+
if (query.includes(plural) && plural.length > bestLen) {
|
|
157
|
+
best = table;
|
|
158
|
+
bestLen = plural.length;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return best;
|
|
162
|
+
}
|
|
163
|
+
function createMockExecute(opts) {
|
|
164
|
+
const mutations = [];
|
|
165
|
+
function record(m) {
|
|
166
|
+
mutations.push(m);
|
|
167
|
+
opts.onMutation?.(m);
|
|
168
|
+
}
|
|
169
|
+
const execute = async (document, variables) => {
|
|
170
|
+
const query = documentToString(document);
|
|
171
|
+
if (isMetaQuery(query)) {
|
|
172
|
+
return buildMetaResponse(opts.tables);
|
|
173
|
+
}
|
|
174
|
+
const mutationMatch = isMutationDocument(query) ? findMutationTable(query, opts.tables) : null;
|
|
175
|
+
if (mutationMatch) {
|
|
176
|
+
const { table, op, mutationName, singular } = mutationMatch;
|
|
177
|
+
record({ op, tableName: table.name, variables: variables ?? {}, at: Date.now() });
|
|
178
|
+
if (op === "delete") {
|
|
179
|
+
const input = extractMutationInput(variables);
|
|
180
|
+
const id = input.id ?? null;
|
|
181
|
+
table.rows = table.rows.filter((r) => r.id !== id);
|
|
182
|
+
return { [mutationName]: { deletedNodeId: id, clientMutationId: null } };
|
|
183
|
+
}
|
|
184
|
+
const row = op === "create" ? synthesizeCreatedRow(table, singular, variables) : synthesizeUpdatedRow(table, variables);
|
|
185
|
+
return { [mutationName]: { [singular]: row } };
|
|
186
|
+
}
|
|
187
|
+
const listTable = findListTable(query, opts.tables);
|
|
188
|
+
if (listTable) {
|
|
189
|
+
return buildListResponse(listTable);
|
|
190
|
+
}
|
|
191
|
+
return {};
|
|
192
|
+
};
|
|
193
|
+
const executeUpload = async (file, path, options) => {
|
|
194
|
+
const name = file?.name ?? "file";
|
|
195
|
+
record({
|
|
196
|
+
op: "upload",
|
|
197
|
+
tableName: options?.tableName ?? "",
|
|
198
|
+
variables: {
|
|
199
|
+
name,
|
|
200
|
+
...path !== void 0 && { path },
|
|
201
|
+
...options?.fieldName !== void 0 && { fieldName: options.fieldName },
|
|
202
|
+
...options?.recordId !== void 0 && { recordId: options.recordId }
|
|
203
|
+
},
|
|
204
|
+
at: Date.now()
|
|
205
|
+
});
|
|
206
|
+
return { url: "mock://uploaded/" + name };
|
|
207
|
+
};
|
|
208
|
+
function reset() {
|
|
209
|
+
mutations.length = 0;
|
|
210
|
+
}
|
|
211
|
+
return { execute, executeUpload, mutations, reset };
|
|
212
|
+
}
|
|
213
|
+
function MockSheetsProvider({ options, children }) {
|
|
214
|
+
const { execute, executeUpload } = useMemo(() => createMockExecute(options), []);
|
|
215
|
+
const queryClient = useMemo(
|
|
216
|
+
() => new QueryClient({
|
|
217
|
+
defaultOptions: {
|
|
218
|
+
queries: { retry: false, gcTime: 0 },
|
|
219
|
+
mutations: { retry: false }
|
|
220
|
+
}
|
|
221
|
+
}),
|
|
222
|
+
[]
|
|
223
|
+
);
|
|
224
|
+
return /* @__PURE__ */ jsx(
|
|
225
|
+
SheetsProvider,
|
|
226
|
+
{
|
|
227
|
+
config: {
|
|
228
|
+
endpoint: "mock://sheets",
|
|
229
|
+
auth: { mode: "embedded", getToken: () => "test" },
|
|
230
|
+
execute,
|
|
231
|
+
executeUpload,
|
|
232
|
+
queryClient
|
|
233
|
+
},
|
|
234
|
+
children
|
|
235
|
+
}
|
|
236
|
+
);
|
|
237
|
+
}
|
|
238
|
+
var usersFixture = {
|
|
239
|
+
name: "users",
|
|
240
|
+
fields: [
|
|
241
|
+
{ name: "id", gqlType: "UUID", pgType: "uuid" },
|
|
242
|
+
{ name: "name", gqlType: "String", pgType: "text" },
|
|
243
|
+
{ name: "email", gqlType: "String", pgType: "text" },
|
|
244
|
+
{ name: "isActive", gqlType: "Boolean", pgType: "boolean" },
|
|
245
|
+
{ name: "createdAt", gqlType: "Datetime", pgType: "timestamptz" }
|
|
246
|
+
],
|
|
247
|
+
rows: [
|
|
248
|
+
{
|
|
249
|
+
id: "00000000-0000-0000-0000-000000000001",
|
|
250
|
+
name: "Ada Lovelace",
|
|
251
|
+
email: "ada@example.com",
|
|
252
|
+
isActive: true,
|
|
253
|
+
createdAt: "2024-01-01T00:00:00Z"
|
|
254
|
+
},
|
|
255
|
+
{
|
|
256
|
+
id: "00000000-0000-0000-0000-000000000002",
|
|
257
|
+
name: "Alan Turing",
|
|
258
|
+
email: "alan@example.com",
|
|
259
|
+
isActive: false,
|
|
260
|
+
createdAt: "2024-01-02T00:00:00Z"
|
|
261
|
+
}
|
|
262
|
+
]
|
|
263
|
+
};
|
|
264
|
+
export {
|
|
265
|
+
MockSheetsProvider,
|
|
266
|
+
createMockExecute,
|
|
267
|
+
usersFixture
|
|
268
|
+
};
|
|
269
|
+
//# sourceMappingURL=testing.js.map
|