@constructive-io/sheets 0.14.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +231 -157
  2. package/dist/advanced.cjs +7192 -3840
  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 +5 -5
  7. package/dist/auth.cjs.map +1 -1
  8. package/dist/auth.js +3 -3
  9. package/dist/chunk-CJ4PRA64.js +312 -0
  10. package/dist/chunk-CJ4PRA64.js.map +1 -0
  11. package/dist/chunk-II3MSNRO.js +18 -0
  12. package/dist/chunk-II3MSNRO.js.map +1 -0
  13. package/dist/{chunk-BYAYBXVB.js → chunk-J7KK4UWI.js} +6 -6
  14. package/dist/chunk-MBSHDF55.js +839 -0
  15. package/dist/chunk-MBSHDF55.js.map +1 -0
  16. package/dist/chunk-MOFFS5WQ.js +128 -0
  17. package/dist/chunk-MOFFS5WQ.js.map +1 -0
  18. package/dist/chunk-VCBY2AMT.js +8920 -0
  19. package/dist/chunk-VCBY2AMT.js.map +1 -0
  20. package/dist/{chunk-YJZFHL2D.js → chunk-ZOQDSOMO.js} +50 -312
  21. package/dist/chunk-ZOQDSOMO.js.map +1 -0
  22. package/dist/date-editor-ORCB43ZM.js +346 -0
  23. package/dist/date-editor-ORCB43ZM.js.map +1 -0
  24. package/dist/{grid-cell-types-C2-ocDS7.d.cts → grid-cell-types-YNIVK4hN.d.cts} +71 -18
  25. package/dist/{grid-cell-types-C2-ocDS7.d.ts → grid-cell-types-YNIVK4hN.d.ts} +71 -18
  26. package/dist/index.cjs +22733 -12052
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +1432 -266
  29. package/dist/index.d.ts +1432 -266
  30. package/dist/index.js +12688 -6097
  31. package/dist/index.js.map +1 -1
  32. package/dist/sheets-context-Bb7ZoNBg.d.cts +436 -0
  33. package/dist/sheets-context-CPuf31LS.d.ts +436 -0
  34. package/dist/testing.cjs +1170 -589
  35. package/dist/testing.cjs.map +1 -1
  36. package/dist/testing.d.cts +80 -11
  37. package/dist/testing.d.ts +80 -11
  38. package/dist/testing.js +778 -147
  39. package/dist/testing.js.map +1 -1
  40. package/package.json +4 -5
  41. package/dist/chunk-4EZ6A23C.js +0 -44
  42. package/dist/chunk-4EZ6A23C.js.map +0 -1
  43. package/dist/chunk-6Y7CZ5VS.js +0 -168
  44. package/dist/chunk-6Y7CZ5VS.js.map +0 -1
  45. package/dist/chunk-BGL6EBTE.js +0 -446
  46. package/dist/chunk-BGL6EBTE.js.map +0 -1
  47. package/dist/chunk-ER3FIDK7.js +0 -4383
  48. package/dist/chunk-ER3FIDK7.js.map +0 -1
  49. package/dist/chunk-GZM2CSTR.js +0 -279
  50. package/dist/chunk-GZM2CSTR.js.map +0 -1
  51. package/dist/chunk-X7DHTSOX.js +0 -21
  52. package/dist/chunk-X7DHTSOX.js.map +0 -1
  53. package/dist/chunk-YJZFHL2D.js.map +0 -1
  54. package/dist/date-editor-G26WKILO.js +0 -358
  55. package/dist/date-editor-G26WKILO.js.map +0 -1
  56. package/dist/map-picker-ZUGGOIZS.js +0 -290
  57. package/dist/map-picker-ZUGGOIZS.js.map +0 -1
  58. package/dist/sheets-context-CHUVJCff.d.ts +0 -245
  59. package/dist/sheets-context-C_MkTxXm.d.cts +0 -245
  60. /package/dist/{chunk-BYAYBXVB.js.map → chunk-J7KK4UWI.js.map} +0 -0
@@ -1 +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/context/sheets-upload-presigned.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","../src/hooks/query-keys.ts","../src/testing/meta-contract-fixture.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';\nexport * from './meta-contract-fixture';\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, SheetsUploadResult } from '../context/sheets-execute';\nimport { createMetaContractFixture } from './meta-contract-fixture';\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\t/** GraphQL field names in PK order. Defaults to `['id']` when an id field exists. */\n\tprimaryKeyFields?: string[];\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, primaryKeyFields: ReadonlySet<string>) {\n\treturn {\n\t\tname: field.name,\n\t\tisPrimaryKey: primaryKeyFields.has(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\tconst primaryKeyFields = table.primaryKeyFields ?? (\n\t\ttable.fields.some((field) => field.name === 'id') ? ['id'] : []\n\t);\n\tconst primaryKeySet = new Set(primaryKeyFields);\n\tconst primaryKeyMetaFields = table.fields\n\t\t.filter((field) => primaryKeySet.has(field.name))\n\t\t.map((field) => buildMetaField(field, primaryKeySet));\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((field) => buildMetaField(field, primaryKeySet)),\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: {\n\t\t\tprimaryKey: primaryKeyMetaFields.length > 0\n\t\t\t\t? { name: `${table.name}_pkey`, fields: primaryKeyMetaFields }\n\t\t\t\t: null,\n\t\t\tunique: [],\n\t\t\tforeignKey: [],\n\t\t},\n\t\tforeignKeyConstraints: [],\n\t\tprimaryKeyConstraints: primaryKeyMetaFields.length > 0\n\t\t\t? [{ name: `${table.name}_pkey`, fields: primaryKeyMetaFields }]\n\t\t\t: [],\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. Contract preflight, then `_meta` data.\n\t\tif (query.includes('ConstructiveMetaContract')) {\n\t\t\treturn createMetaContractFixture() as T;\n\t\t}\n\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<SheetsUploadResult> => {\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\tconst url = 'mock://uploaded/' + name;\n\t\treturn {\n\t\t\tfile: {\n\t\t\t\tid: 'mock-file-' + mutations.length,\n\t\t\t\tkey: name,\n\t\t\t\tbucket_id: 'mock-bucket',\n\t\t\t\tfilename: name,\n\t\t\t\tmime: file.type || 'application/octet-stream',\n\t\t\t\tsize: file.size,\n\t\t\t\turl,\n\t\t\t},\n\t\t\turl,\n\t\t};\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, 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","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 { 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","/**\n * Presigned-URL upload helpers for the sheets cell-upload seam.\n *\n * Replaces the legacy multipart `<endpoint>/upload` POST. The flow is:\n * 1. SHA-256 hash the file bytes (Web Crypto, zero new deps)\n * 2. Call the presigned upload op (discovered via introspection) to get a\n * presigned PUT url + fileId\n * 3. PUT the raw bytes to that url (only Content-Type, NO Authorization)\n * 4. Return the file projection and try to resolve an optional download URL\n *\n * The server confirms PUTs and expires rows that never received one.\n *\n * Runtime introspection finds root mutations with the presigned upload shape\n * and prefers `uploadAppFile` when multiple storage planes are exposed.\n *\n * The downloadUrl-by-id field is likewise shape-discovered. Three read shapes,\n * preferred in order: the inflected singular `appFile(id:)`; a filtered\n * connection `appFiles(where:{id:{equalTo:$id}}){ nodes { downloadUrl } }`\n * (Relay-disabled backends); and the Relay `node(nodeId:)` fallback.\n */\n\nimport { getIntrospectionQuery } from 'graphql';\n\nimport { createError } from '@constructive-io/data';\n\nimport type { SheetsStorageTransport } from './sheets-context';\nimport type { SheetsExecuteFn, SheetsFileValue } from './sheets-execute';\n\n// ============================================================================\n// Capability discovery types\n// ============================================================================\n\nexport interface UploadCapability {\n\t/** Upload mutation field name, discovered by shape, e.g. 'uploadAppFile'. */\n\tuploadFieldName: string;\n\t/** The upload input object type name, e.g. 'UploadAppFileInput'. */\n\tinputTypeName: string;\n\thasFileProjection: boolean;\n\tdownload: DownloadByIdResult | null;\n}\n\ninterface DownloadByIdResult {\n\t/** Query field used to resolve downloadUrl by id, e.g. 'appFile' | 'node' | 'appFiles'. */\n\tfileByIdField: string;\n\t/**\n\t * Which downloadUrl-by-id resolution shape was discovered:\n\t * - 'id' inflected singular `appFile(id:)`\n\t * - 'connection' filtered connection `appFiles(where:{id:{equalTo:$id}}){ nodes { downloadUrl } }`\n\t * - 'nodeId' Relay `node(nodeId:)` (last-resort fallback)\n\t */\n\tfileByIdArgName: 'id' | 'nodeId' | 'connection';\n\t/** The file object type name (used to spread `... on <Type>` on the Relay node path). */\n\tfileTypeName: string;\n\t/** The GraphQL scalar type name for the `$id` variable (e.g. 'UUID'), discovered by shape. */\n\tidScalarName?: string;\n\t/** connection kind only — the filter arg name on the connection field, e.g. 'where' | 'filter' | 'condition'. */\n\tconnectionFilterArgName?: string;\n\t/** connection kind only — the id field name inside the filter input, e.g. 'id'. */\n\tconnectionIdField?: string;\n\t/** connection kind only — the equality operator field for style (a), e.g. 'equalTo'. Absent for condition style (b). */\n\tconnectionIdOperator?: string;\n\t/** connection kind only — the field on the connection object holding the file rows, e.g. 'nodes'. */\n\tconnectionNodesField?: string;\n\tconnectionHasFirst?: boolean;\n}\n\ninterface StorageCapabilities {\n\tupload: UploadCapability | null;\n\tdownload: DownloadByIdResult | null;\n\tbatch: DownloadByIdResult | null;\n}\n\ninterface UploadPayload {\n\tuploadUrl: string | null;\n\tfileId: string;\n\tkey: string;\n\tdeduplicated: boolean;\n\tfile: Omit<SheetsFileValue, 'filename'> & { filename?: string | null };\n}\n\n// ============================================================================\n// SHA-256 (Web Crypto)\n// ============================================================================\n\n/**\n * SHA-256 hex digest of an already-read ArrayBuffer. Lowercase, 64 chars —\n * matches the server regex `^[a-f0-9]{64}$`. We reuse the same buffer for the\n * PUT body to avoid a second `file.arrayBuffer()` read.\n */\nexport async function sha256HexFromBuffer(buffer: ArrayBuffer): Promise<string> {\n\tif (!globalThis.crypto?.subtle) {\n\t\tthrow createError.badRequest('Web Crypto (crypto.subtle) is unavailable; cannot hash file for upload.');\n\t}\n\tconst digest = await crypto.subtle.digest('SHA-256', buffer);\n\tconst bytes = new Uint8Array(digest);\n\tlet hex = '';\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\thex += bytes[i].toString(16).padStart(2, '0');\n\t}\n\treturn hex;\n}\n\n// ============================================================================\n// Introspection-based capability discovery (cached per endpoint)\n// ============================================================================\n\nlet capabilityCache = new WeakMap<SheetsExecuteFn, Map<string, Promise<StorageCapabilities>>>();\n\n/** Test-only: clear cached storage capabilities between cases. */\nexport function __resetUploadCapabilityCache(): void {\n\tcapabilityCache = new WeakMap();\n}\n\n/**\n * Share storage introspection across uploads and previews using this executor\n * and endpoint. A read-only storage endpoint can still resolve previews.\n */\nasync function discoverStorageCapabilities(endpoint: string, execute: SheetsExecuteFn): Promise<StorageCapabilities> {\n\tlet endpoints = capabilityCache.get(execute);\n\tif (!endpoints) {\n\t\tendpoints = new Map();\n\t\tcapabilityCache.set(execute, endpoints);\n\t}\n\tconst cached = endpoints.get(endpoint);\n\tif (cached) return cached;\n\n\tconst promise = (async () => {\n\t\tconst data = await execute<{ __schema: IntrospectionSchema }>(getIntrospectionQuery());\n\t\tconst schema = data?.__schema;\n\t\tif (!schema) {\n\t\t\tthrow createError.badRequest('Uploads are not enabled for this endpoint.');\n\t\t}\n\t\treturn resolveStorageCapabilities(schema);\n\t})();\n\n\t// Don't cache a rejected discovery — let the next attempt retry.\n\tpromise.catch(() => endpoints.delete(endpoint));\n\tendpoints.set(endpoint, promise);\n\treturn promise;\n}\n\nexport async function discoverUploadCapability(endpoint: string, execute: SheetsExecuteFn): Promise<UploadCapability> {\n\tconst { upload } = await discoverStorageCapabilities(endpoint, execute);\n\tif (!upload) capabilityCache.get(execute)?.delete(endpoint);\n\treturn requireUploadCapability(upload);\n}\n\nfunction requireUploadCapability(upload: UploadCapability | null): UploadCapability {\n\tif (!upload) throw createError.badRequest('Uploads are not enabled for this endpoint.');\n\treturn upload;\n}\n\n// --- Minimal introspection shapes (only what discovery reads) ---\n\n// Loose, structural shapes for the slice of introspection that discovery\n// reads. `ofType` recurses with `any` so hand-built fixtures and the real\n// `IntrospectionQuery['__schema']` (from `graphql`) both satisfy these without\n// exact-match friction — discovery validates by runtime shape regardless.\ninterface IntrospectionTypeRef {\n\tkind: string;\n\tname?: string | null;\n\tofType?: any;\n}\n\ninterface IntrospectionInputValue {\n\tname: string;\n\ttype: IntrospectionTypeRef;\n}\n\ninterface IntrospectionField {\n\tname: string;\n\targs: ReadonlyArray<IntrospectionInputValue>;\n\ttype: IntrospectionTypeRef;\n}\n\ninterface IntrospectionType {\n\tkind: string;\n\tname?: string | null;\n\tfields?: ReadonlyArray<IntrospectionField> | null;\n\tinputFields?: ReadonlyArray<IntrospectionInputValue> | null;\n}\n\n/** Loose structural shape of an introspection `__schema` (accepts fixtures + real). */\nexport interface IntrospectionSchema {\n\tqueryType?: { name: string } | null;\n\tmutationType?: { name: string } | null;\n\ttypes: ReadonlyArray<IntrospectionType>;\n}\n\n/** Unwrap NON_NULL / LIST wrappers down to the named type. */\nfunction namedTypeName(ref: IntrospectionTypeRef | null | undefined): string | null {\n\tlet cur = ref;\n\twhile (cur && (cur.kind === 'NON_NULL' || cur.kind === 'LIST')) {\n\t\tcur = cur.ofType ?? null;\n\t}\n\treturn cur?.name ?? null;\n}\n\n/**\n * True if `ref` is a LIST (optionally NON_NULL-wrapped) at the outer level, i.e.\n * the field is plural. Unwraps only leading NON_NULL wrappers (e.g. `[AppFile]!`)\n * before checking for the LIST — distinguishes `nodes: [AppFile]` from a singular\n * `appFile: AppFile`.\n */\nfunction isListTypeRef(ref: IntrospectionTypeRef | null | undefined): boolean {\n\tlet cur = ref;\n\twhile (cur && cur.kind === 'NON_NULL') {\n\t\tcur = cur.ofType ?? null;\n\t}\n\treturn cur?.kind === 'LIST';\n}\n\n/**\n * PostGraphile names the primary-key column `id` on every row type, so the\n * filter input field that selects a single file by primary key is `id`. This is\n * the same convention the singular by-id branch (`appFile(id:)`) relies on.\n */\nconst PK_FIELD_NAME = 'id';\n\n/**\n * Pure resolver over an introspection __schema. Exported for direct unit tests\n * (no fetch). Matches by field/type shape, with an AppFile preference.\n */\nexport function resolveUploadCapability(schema: IntrospectionSchema): UploadCapability {\n\treturn requireUploadCapability(resolveStorageCapabilities(schema).upload);\n}\n\nfunction resolveStorageCapabilities(schema: IntrospectionSchema): StorageCapabilities {\n\tconst typeByName = new Map<string, IntrospectionType>();\n\tfor (const t of schema.types) {\n\t\tif (t.name) typeByName.set(t.name, t);\n\t}\n\n\tconst objectHasFields = (typeName: string | null, names: string[]): boolean => {\n\t\tif (!typeName) return false;\n\t\tconst t = typeByName.get(typeName);\n\t\tif (!t?.fields) return false;\n\t\tconst present = new Set(t.fields.map((f) => f.name));\n\t\treturn names.every((n) => present.has(n));\n\t};\n\n\tconst inputHasFields = (typeName: string | null, names: string[]): boolean => {\n\t\tif (!typeName) return false;\n\t\tconst t = typeByName.get(typeName);\n\t\tif (!t?.inputFields) return false;\n\t\tconst present = new Set(t.inputFields.map((f) => f.name));\n\t\treturn names.every((n) => present.has(n));\n\t};\n\n\tconst PAYLOAD_FIELDS = ['uploadUrl', 'fileId', 'key', 'deduplicated'];\n\tconst INPUT_FIELDS = ['contentHash', 'bucketKey', 'contentType', 'size'];\n\n\tconst mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;\n\tconst queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;\n\n\t// rootUpload discovery: a Mutation field with a single `input` arg whose input\n\t// type carries the upload-input shape and whose payload carries the\n\t// upload-payload shape. (The legacy bucket-centric `requestUploadUrl` shape was\n\t// removed from the backend on 2026-05-08; only the root upload mutation exists.)\n\tlet upload: Omit<UploadCapability, 'download'> | null = null;\n\n\tfor (const field of mutationType?.fields ?? []) {\n\t\tconst inputArg = field.args.find((a) => a.name === 'input');\n\t\tif (!inputArg) continue;\n\t\tconst inputTypeName = namedTypeName(inputArg.type);\n\t\tconst payloadTypeName = namedTypeName(field.type);\n\t\tif (\n\t\t\tinputTypeName &&\n\t\t\tinputHasFields(inputTypeName, INPUT_FIELDS) &&\n\t\t\tobjectHasFields(payloadTypeName, PAYLOAD_FIELDS)\n\t\t) {\n\t\t\tconst payloadFields = typeByName.get(payloadTypeName ?? '')?.fields;\n\t\t\tconst candidate = {\n\t\t\t\tuploadFieldName: field.name,\n\t\t\t\tinputTypeName,\n\t\t\t\thasFileProjection: payloadFields?.some(\n\t\t\t\t\t(f) => f.name === 'file' && !isListTypeRef(f.type) && namedTypeName(f.type) === 'JSON',\n\t\t\t\t) ?? false,\n\t\t\t};\n\t\t\tif (field.name === 'uploadAppFile') {\n\t\t\t\tupload = candidate;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tupload ??= candidate;\n\t\t}\n\t}\n\n\tconst fileTypes = new Set<string>();\n\tfor (const t of schema.types) {\n\t\tif (t.kind === 'OBJECT' && t.name && t.fields?.some((f) => f.name === 'downloadUrl')) {\n\t\t\tfileTypes.add(t.name);\n\t\t}\n\t}\n\n\tconst uploadType = upload?.uploadFieldName.replace(/^upload/, '') ?? 'AppFile';\n\tconst uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);\n\tconst preferredPreviewType = fileTypes.has('AppFile') ? 'AppFile' : uploadType;\n\tconst previewType = fileTypes.has(preferredPreviewType)\n\t\t? preferredPreviewType\n\t\t: uploadDownload?.fileTypeName ?? preferredPreviewType;\n\tconst download = previewType === uploadType\n\t\t? uploadDownload\n\t\t: resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);\n\tconst batch = resolveConnectionDownloadField(typeByName, queryType, fileTypes, previewType, true);\n\n\treturn {\n\t\tupload: upload ? { ...upload, download: uploadDownload } : null,\n\t\tdownload,\n\t\tbatch,\n\t};\n}\n\nfunction resolveDownloadByIdField(\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tfileTypesWithDownloadUrl: Set<string>,\n\tpreferred: string,\n): DownloadByIdResult | null {\n\t// 1. Look for an inflected by-id form: a Query field whose return type has a\n\t// `downloadUrl` field and that takes a single `id` arg. e.g. appFile(id:).\n\t// The `$id` variable type is the actual scalar of that id arg (NOT a\n\t// hardcoded UUID) — derived by shape.\n\tlet singular: DownloadByIdResult | null = null;\n\tfor (const field of queryType?.fields ?? []) {\n\t\tconst returnTypeName = namedTypeName(field.type);\n\t\tif (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;\n\t\tif (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {\n\t\t\tconst candidate: DownloadByIdResult = {\n\t\t\t\tfileByIdField: field.name,\n\t\t\t\tfileByIdArgName: 'id',\n\t\t\t\tfileTypeName: returnTypeName,\n\t\t\t\tidScalarName: namedTypeName(field.args[0].type) ?? undefined,\n\t\t\t};\n\t\t\tif (returnTypeName === preferred) return candidate;\n\t\t\tsingular ??= candidate;\n\t\t}\n\t}\n\n\t// 2. Connection fallback (Relay-disabled backends, incl. the live tenant API):\n\t// a Query field returning a connection whose `nodes` element is a\n\t// downloadUrl-bearing file type, filtered by id. e.g.\n\t// appFiles(where: { id: { equalTo: $id } }, first: 1) { nodes { downloadUrl } }\n\t// All names (connection field, filter arg, id field, equality operator,\n\t// nodes field, id scalar) are discovered by SHAPE, never hardcoded.\n\t// Preferred over the Relay node path: it consumes the raw fileId directly,\n\t// so it needs no client-side global-id construction.\n\tconst connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);\n\tif (connection?.fileTypeName === preferred) return connection;\n\tif (singular || connection) return singular ?? connection;\n\n\t// 3. Relay fallback: `node(nodeId: ID!)`. Last resort — only when neither a\n\t// singular `id` accessor nor a filtered connection exists. Caller spreads\n\t// `... on <FileType> { downloadUrl }` and encodes the global id.\n\tconst nodeField = queryType?.fields?.find(\n\t\t(f) => f.name === 'node' && f.args.some((a) => a.name === 'nodeId'),\n\t);\n\tif (nodeField && fileTypesWithDownloadUrl.size > 0) {\n\t\t// Deterministic file type for the inline fragment: prefer the type named\n\t\t// after the upload op (uploadAppFile → AppFile); else the first-declared\n\t\t// downloadUrl-bearing type. (Was alphabetical `.sort()[0]`, which could pick\n\t\t// the wrong type when several expose downloadUrl, e.g. DataRoomFile.)\n\t\tconst fileTypeName = fileTypesWithDownloadUrl.has(preferred)\n\t\t\t? preferred\n\t\t\t: [...fileTypesWithDownloadUrl][0];\n\t\treturn { fileByIdField: 'node', fileByIdArgName: 'nodeId', fileTypeName };\n\t}\n\n\treturn null;\n}\n\n/**\n * Discover a filtered connection for single or batched download lookups.\n * The single-file path supports two filter input styles:\n * (a) operator filter — `where: { id: { equalTo: $id } }` (connection-filter\n * plugin): the id field's input type carries an equality operator.\n * (b) condition filter — `condition: { id: $id }`: the id field is the scalar\n * directly.\n */\nfunction resolveConnectionDownloadField(\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tfileTypesWithDownloadUrl: Set<string>,\n\tpreferred: string,\n\tbatch = false,\n): DownloadByIdResult | null {\n\t// Equality operator names we recognize on a filter-input field, in priority\n\t// order (exact-match equality first).\n\tconst EQUALITY_OPERATORS = ['equalTo', 'eq'];\n\n\t// Collect every matching connection, then pick deterministically — a tenant\n\t// with multiple @storageFiles tables exposes several file connections\n\t// (appFiles, dataRoomFiles, …), all carrying downloadUrl-bearing nodes.\n\tconst candidates: DownloadByIdResult[] = [];\n\n\tfor (const field of queryType?.fields ?? []) {\n\t\tconst connTypeName = namedTypeName(field.type);\n\t\tif (!connTypeName) continue;\n\t\tconst connType = typeByName.get(connTypeName);\n\t\tif (connType?.kind !== 'OBJECT' || !connType.fields) continue;\n\n\t\t// Find the `nodes` field whose element type is a downloadUrl-bearing file.\n\t\t// Require it to be a LIST (plural) so a singular `appFile: AppFile` field on\n\t\t// some object does NOT false-match as a connection (fetchDownloadUrl indexes\n\t\t// [nodesField][0], which only makes sense on an array).\n\t\tconst nodesField = connType.fields.find((f) => {\n\t\t\tif (!isListTypeRef(f.type)) return false;\n\t\t\tconst elem = namedTypeName(f.type);\n\t\t\treturn elem != null && fileTypesWithDownloadUrl.has(elem);\n\t\t});\n\t\tif (!nodesField) continue;\n\t\tconst fileTypeName = namedTypeName(nodesField.type) as string;\n\t\tif (batch && (fileTypeName !== preferred ||\n\t\t\t!typeByName.get(fileTypeName)?.fields?.some((field) => field.name === PK_FIELD_NAME))) continue;\n\t\tconst connectionHasFirst = field.args.some((arg) => arg.name === 'first');\n\n\t\t// Find a filter arg whose input type has an `id` field.\n\t\tfor (const arg of field.args) {\n\t\t\tconst filterTypeName = namedTypeName(arg.type);\n\t\t\tconst filterType = filterTypeName ? typeByName.get(filterTypeName) : null;\n\t\t\tif (filterType?.kind !== 'INPUT_OBJECT' || !filterType.inputFields) continue;\n\t\t\tconst idField = filterType.inputFields.find((f) => f.name === PK_FIELD_NAME);\n\t\t\tif (!idField) continue;\n\n\t\t\tconst idFieldTypeName = namedTypeName(idField.type);\n\t\t\tconst idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;\n\n\t\t\t// Style (a): the id field is itself an input type carrying an equality\n\t\t\t// operator (e.g. UUIDFilter.equalTo). The `$id` scalar is the operator's\n\t\t\t// type.\n\t\t\tif (idFieldType?.kind === 'INPUT_OBJECT' && idFieldType.inputFields) {\n\t\t\t\tconst opField = batch\n\t\t\t\t\t? idFieldType.inputFields.find((f) => f.name === 'in' && isListTypeRef(f.type))\n\t\t\t\t\t: EQUALITY_OPERATORS.map((op) =>\n\t\t\t\t\t\tidFieldType.inputFields!.find((f) => f.name === op),\n\t\t\t\t\t).find((f) => f != null);\n\t\t\t\tif (opField) {\n\t\t\t\t\tcandidates.push({\n\t\t\t\t\t\tfileByIdField: field.name,\n\t\t\t\t\t\tfileByIdArgName: 'connection',\n\t\t\t\t\t\tfileTypeName,\n\t\t\t\t\t\tidScalarName: namedTypeName(opField.type) ?? undefined,\n\t\t\t\t\t\tconnectionFilterArgName: arg.name,\n\t\t\t\t\t\tconnectionIdField: idField.name,\n\t\t\t\t\t\tconnectionIdOperator: opField.name,\n\t\t\t\t\t\tconnectionNodesField: nodesField.name,\n\t\t\t\t\t\tconnectionHasFirst,\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// This filter lacks the operator needed for this lookup.\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Style (b): the id field is a scalar directly (condition style). The\n\t\t\t// `$id` scalar is that field's type.\n\t\t\tif (!batch && (idFieldType?.kind === 'SCALAR' || (!idFieldType && idFieldTypeName))) {\n\t\t\t\tcandidates.push({\n\t\t\t\t\tfileByIdField: field.name,\n\t\t\t\t\tfileByIdArgName: 'connection',\n\t\t\t\t\tfileTypeName,\n\t\t\t\t\tidScalarName: idFieldTypeName ?? undefined,\n\t\t\t\t\tconnectionFilterArgName: arg.name,\n\t\t\t\t\tconnectionIdField: idField.name,\n\t\t\t\t\tconnectionNodesField: nodesField.name,\n\t\t\t\t\tconnectionHasFirst,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (candidates.length === 0) return null;\n\n\t// Deterministic pick: prefer the connection whose file type matches the upload\n\t// op (uploadAppFile → AppFile), else the first-declared. This is the LIVE\n\t// production path — the only downloadUrl shape on a Relay-disabled, unique-\n\t// lookup-disabled tenant API — so resolving the WRONG file connection (e.g.\n\t// reading a DataRoomFile id through appFiles) yields 0 nodes and fails every\n\t// upload. Mirrors the node-branch determinism, where it matters far more.\n\treturn candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];\n}\n\n// ============================================================================\n// Upload op call\n// ============================================================================\n\ninterface UploadOpInput {\n\tbucketKey?: string;\n\tcontentHash: string;\n\tcontentType: string;\n\tsize: number;\n\tfilename: string;\n}\n\n/**\n * Invoke the discovered upload op and normalize its payload.\n * App-scoped buckets have NO owner_id column, so `ownerId` is NEVER sent.\n */\nexport async function callUploadOp(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\n\tinput: UploadOpInput,\n): Promise<UploadPayload> {\n\tconst mutation = `\n\t\tmutation SheetsUpload($input: ${cap.inputTypeName}!) {\n\t\t\t${cap.uploadFieldName}(input: $input) {\n\t\t\t\tuploadUrl\n\t\t\t\tfileId\n\t\t\t\tkey\n\t\t\t\tdeduplicated\n\t\t\t\tfile\n\t\t\t}\n\t\t}\n\t`.trim();\n\tconst data = await execute<Record<string, UploadPayload | null>>(mutation, {\n\t\tinput: {\n\t\t\t...(input.bucketKey === undefined ? { isPublic: true } : { bucketKey: input.bucketKey }),\n\t\t\tcontentHash: input.contentHash,\n\t\t\tcontentType: input.contentType,\n\t\t\tsize: input.size,\n\t\t\tfilename: input.filename,\n\t\t},\n\t});\n\tconst payload = data?.[cap.uploadFieldName];\n\tif (!payload) {\n\t\tthrow createError.badRequest('Upload failed: no payload returned from upload mutation.');\n\t}\n\tconst file = payload.file;\n\tif (\n\t\t!file || typeof file.id !== 'string' || typeof file.key !== 'string' ||\n\t\ttypeof file.bucket_id !== 'string' || typeof file.mime !== 'string' || typeof file.size !== 'number'\n\t) {\n\t\tthrow createError.badRequest('Upload failed: server returned an invalid file projection.');\n\t}\n\treturn payload;\n}\n\n// ============================================================================\n// Presigned PUT\n// ============================================================================\n\n/**\n * PUT the raw bytes to the presigned url. Sends ONLY the signed `Content-Type`\n * header — NO Authorization (the signature lives in the url query string), no\n * cookies, no Accept override. The browser supplies Content-Length from the body.\n *\n * When `onProgress` is provided and XHR is available, uses XHR for byte\n * progress; otherwise a plain fetch PUT.\n */\n/**\n * A PUT the browser could not complete. The GraphQL API answered moments ago, so\n * the usual cause is the bucket's CORS rule (no allowed origin for this site) rather\n * than the connection; browsers do not expose which.\n */\nexport const STORAGE_UPLOAD_BLOCKED_MESSAGE =\n\t\"Upload failed: the storage server didn't accept the upload from this site. Check the bucket's allowed origins (CORS) and your connection.\";\n\nfunction storageUnreachableError() {\n\treturn createError.graphql(STORAGE_UPLOAD_BLOCKED_MESSAGE, 'STORAGE_UPLOAD_BLOCKED');\n}\n\nexport async function presignedPut(\n\turl: string,\n\tbuffer: ArrayBuffer,\n\tcontentType: string,\n\tonProgress?: (progress: { loaded: number; total: number; percentage: number }) => void,\n): Promise<void> {\n\tconst total = buffer.byteLength;\n\n\tif (onProgress && typeof XMLHttpRequest !== 'undefined') {\n\t\tawait putWithXHR(url, buffer, contentType, total, onProgress);\n\t\treturn;\n\t}\n\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, {\n\t\t\tmethod: 'PUT',\n\t\t\theaders: { 'Content-Type': contentType },\n\t\t\tbody: buffer,\n\t\t});\n\t} catch {\n\t\tthrow storageUnreachableError();\n\t}\n\n\tif (!response.ok) {\n\t\tconst body = await response.text().catch(() => '');\n\t\tthrow createError.badRequest(`Upload failed: ${response.status} ${response.statusText}${body ? ` — ${body}` : ''}`);\n\t}\n\tonProgress?.({ loaded: total, total, percentage: 100 });\n}\n\nfunction putWithXHR(\n\turl: string,\n\tbuffer: ArrayBuffer,\n\tcontentType: string,\n\ttotal: number,\n\tonProgress: (progress: { loaded: number; total: number; percentage: number }) => void,\n): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst xhr = new XMLHttpRequest();\n\t\txhr.open('PUT', url);\n\t\txhr.setRequestHeader('Content-Type', contentType);\n\n\t\txhr.upload.addEventListener('progress', (event) => {\n\t\t\tif (event.lengthComputable) {\n\t\t\t\tonProgress({\n\t\t\t\t\tloaded: event.loaded,\n\t\t\t\t\ttotal: event.total,\n\t\t\t\t\tpercentage: Math.round((event.loaded / event.total) * 100),\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\txhr.addEventListener('load', () => {\n\t\t\tif (xhr.status >= 200 && xhr.status < 300) {\n\t\t\t\tonProgress({ loaded: total, total, percentage: 100 });\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\treject(createError.badRequest(`Upload failed: ${xhr.status} ${xhr.statusText}${xhr.responseText ? ` — ${xhr.responseText}` : ''}`));\n\t\t\t}\n\t\t});\n\n\t\txhr.addEventListener('error', () => reject(storageUnreachableError()));\n\n\t\txhr.send(buffer);\n\t});\n}\n\n// ============================================================================\n// downloadUrl resolution\n// ============================================================================\n\n/**\n * Encode a PostGraphile global id (Relay `node` id) from a row's primary key,\n * using the default base64JSON codec: `base64(JSON.stringify([typeName, pk]))`.\n */\nfunction toGlobalId(typeName: string, id: string): string {\n\tif (typeof btoa !== 'function') {\n\t\tthrow createError.badRequest('Cannot encode the file node id: btoa is unavailable in this environment.');\n\t}\n\treturn btoa(JSON.stringify([typeName, id]));\n}\n\n/**\n * Resolve a file's download URL for immediate use. It can be a signed URL\n * with an expiration, so only the storage projection belongs in the cell.\n */\nexport async function fetchDownloadUrl(\n\texecute: SheetsExecuteFn,\n\tcap: DownloadByIdResult,\n\tfileId: string,\n): Promise<string> {\n\tif (cap.fileByIdArgName === 'nodeId') {\n\t\t// The upload payload returns the RAW primary key as `fileId`, but\n\t\t// `node(nodeId:)` expects the opaque PostGraphile global id. Encode it with\n\t\t// the default base64JSON codec (`base64([typeName, pk])`). NOTE: the live\n\t\t// tenant API is Relay-disabled and resolves via the connection branch; this\n\t\t// path is mock-covered only and assumes the default node-id codec.\n\t\tconst nodeId = toGlobalId(cap.fileTypeName, fileId);\n\t\tconst query = `\n\t\t\tquery SheetsDownloadUrl($nodeId: ID!) {\n\t\t\t\t${cap.fileByIdField}(nodeId: $nodeId) {\n\t\t\t\t\t... on ${cap.fileTypeName} {\n\t\t\t\t\t\tdownloadUrl\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`.trim();\n\t\tconst data = await execute<Record<string, { downloadUrl?: string | null } | null>>(query, { nodeId });\n\t\tconst node = data?.[cap.fileByIdField];\n\t\tconst url = node?.downloadUrl;\n\t\tif (!url) {\n\t\t\tthrow createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\t\t}\n\t\treturn url;\n\t}\n\n\t// Connection fallback (Relay-disabled): filter the connection by id and read\n\t// the first node's downloadUrl. The filter literal is built per the discovered\n\t// style — operator (`{ id: { equalTo: $id } }`) or condition (`{ id: $id }`).\n\tif (cap.fileByIdArgName === 'connection') {\n\t\tconst idScalar = cap.idScalarName ?? 'ID';\n\t\tconst filterArg = cap.connectionFilterArgName as string;\n\t\tconst idField = cap.connectionIdField as string;\n\t\tconst nodesField = cap.connectionNodesField as string;\n\t\tconst filterLiteral = cap.connectionIdOperator\n\t\t\t? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }`\n\t\t\t: `{ ${idField}: $id }`;\n\t\tconst query = `\n\t\t\tquery SheetsDownloadUrl($id: ${idScalar}!) {\n\t\t\t\t${cap.fileByIdField}(${filterArg}: ${filterLiteral}${cap.connectionHasFirst ? ', first: 1' : ''}) {\n\t\t\t\t\t${nodesField} {\n\t\t\t\t\t\tdownloadUrl\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`.trim();\n\t\tconst data = await execute<Record<string, Record<string, Array<{ downloadUrl?: string | null }> | null> | null>>(\n\t\t\tquery,\n\t\t\t{ id: fileId },\n\t\t);\n\t\tconst conn = data?.[cap.fileByIdField];\n\t\tconst url = conn?.[nodesField]?.[0]?.downloadUrl;\n\t\tif (!url) {\n\t\t\tthrow createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\t\t}\n\t\treturn url;\n\t}\n\n\tconst idScalar = cap.idScalarName ?? 'ID';\n\tconst query = `\n\t\tquery SheetsDownloadUrl($id: ${idScalar}!) {\n\t\t\t${cap.fileByIdField}(id: $id) {\n\t\t\t\tid\n\t\t\t\tdownloadUrl\n\t\t\t}\n\t\t}\n\t`.trim();\n\tconst data = await execute<Record<string, { downloadUrl?: string | null } | null>>(query, { id: fileId });\n\tconst file = data?.[cap.fileByIdField];\n\tconst url = file?.downloadUrl;\n\tif (!url) {\n\t\tthrow createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\t}\n\treturn url;\n}\n\n/** Resolve URLs for one batch of visible images. Missing or unreadable IDs have no entry. */\nexport async function fetchMediaDownloadUrls(\n\t{ endpoint, execute }: SheetsStorageTransport,\n\tgetActiveIds: () => readonly string[],\n): Promise<Map<string, string>> {\n\tconst { batch, download } = await discoverStorageCapabilities(endpoint, execute);\n\tconst ids = getActiveIds();\n\tconst urls = new Map<string, string>();\n\tif (ids.length === 0) return urls;\n\tif (batch) {\n\t\tconst first = batch.connectionHasFirst ? `, first: ${ids.length}` : '';\n\t\tconst query = `query SheetsMediaDownloadUrls($ids: [${batch.idScalarName ?? 'ID'}!]!) {\n\t\t\t${batch.fileByIdField}(${batch.connectionFilterArgName}: {\n\t\t\t\t${batch.connectionIdField}: { in: $ids }\n\t\t\t}${first}) { ${batch.connectionNodesField} { id downloadUrl } }\n\t\t}`;\n\t\ttype FileNode = { id: string; downloadUrl: string | null };\n\t\tconst data = await execute<Record<string, Record<string, (FileNode | null)[] | null> | null>>(query, { ids });\n\t\tfor (const row of data?.[batch.fileByIdField]?.[batch.connectionNodesField!] ?? []) {\n\t\t\tif (row?.downloadUrl) urls.set(row.id, row.downloadUrl);\n\t\t}\n\t} else if (download) {\n\t\tconst results = await Promise.allSettled(ids.map((id) => fetchDownloadUrl(execute, download, id)));\n\t\tresults.forEach((result, index) => {\n\t\t\tif (result.status === 'fulfilled') urls.set(ids[index], result.value);\n\t\t});\n\t}\n\treturn urls;\n}\n\n/**\n * Resolve a file's signed `downloadUrl` by id — the public entry point for callers\n * OUTSIDE the upload flow (e.g. a storage browser fetching the preview/copy link for\n * an already-uploaded file).\n *\n * `downloadUrl` is a Grafast computed field, so it cannot be selected through the\n * runtime query builder (`buildSelect` intersects the select against pg columns and\n * drops computed fields). This discovers the by-id field using cached introspection\n * and reads it through the SAME resolver the upload path uses. Returns null on any\n * failure — a missing url is not exceptional for the caller (it just disables\n * copy/download), so the throwing internals are swallowed here.\n */\nexport async function resolveDownloadUrl(\n\texecute: SheetsExecuteFn,\n\tendpoint: string,\n\tfileId: string,\n): Promise<string | null> {\n\ttry {\n\t\tconst { download } = await discoverStorageCapabilities(endpoint, execute);\n\t\treturn download ? await fetchDownloadUrl(execute, download, fileId) : null;\n\t} catch {\n\t\treturn null;\n\t}\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","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","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\tidentityKey?: string | null;\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\tif (parsed.identityKey != null && typeof parsed.identityKey !== 'string') return null;\n\t\treturn parsed;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function setStoredToken(\n\tdatabaseId: string,\n\taccessToken: string,\n\texpiresAt: string,\n\tidentityKey?: string | null,\n): void {\n\tconst storage = getStorage();\n\tif (!storage) return;\n\n\ttry {\n\t\tconst data: StoredToken = { accessToken, expiresAt, identityKey };\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","import type { SheetsScopeKey } from '../context/sheets-context';\n\nexport function isSheetsScopeKey(value: unknown): value is SheetsScopeKey {\n\tif (!value || typeof value !== 'object') return false;\n\tconst candidate = value as Record<string, unknown>;\n\treturn 'databaseId' in candidate && 'endpoint' in candidate && 'identityKey' in candidate;\n}\n\nexport function reuseSheetsPlaceholderData<T>(\n\tpreviousData: T | undefined,\n\tpreviousQueryKey: readonly unknown[] | undefined,\n\tcurrentScope: SheetsScopeKey,\n): T | undefined {\n\tconst previousScope = previousQueryKey?.[1];\n\tif (!isSheetsScopeKey(previousScope)) return undefined;\n\tif (previousScope.databaseId !== currentScope.databaseId) return undefined;\n\tif (previousScope.endpoint !== currentScope.endpoint) return undefined;\n\tif (previousScope.identityKey !== currentScope.identityKey) return undefined;\n\treturn previousData;\n}\n\nexport const sheetsQueryKeys = {\n\troot: ['sheets'] as const,\n\tscope: (scope: SheetsScopeKey) => ['sheets', scope] as const,\n\tmeta: (scope: SheetsScopeKey) => [...sheetsQueryKeys.scope(scope), 'meta'] as const,\n\tmediaUrl: (scope: SheetsScopeKey, endpoint: string | undefined, id: string | null) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'media-url', endpoint, id] as const,\n\ttypeFields: (scope: SheetsScopeKey, typeName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'type-fields', typeName] as const,\n\tenumValues: (scope: SheetsScopeKey, typeName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'enum-values', typeName] as const,\n\trelations: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'relations', tableName] as const,\n\ttable: (scope: SheetsScopeKey, tableName: string) => [...sheetsQueryKeys.scope(scope), 'table', tableName] as const,\n\ttableRows: (scope: SheetsScopeKey, tableName: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableName), 'rows', options] as const,\n\ttableRow: (scope: SheetsScopeKey, tableName: string, id: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableName), 'row', id] as const,\n\ttableCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown> | null) =>\n\t\t[...sheetsQueryKeys.table(scope, tableName), 'count', where] as const,\n\tinfiniteTable: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'infinite-table', tableName] as const,\n\tinfiniteTablePage: (scope: SheetsScopeKey, tableName: string, pageIndex: number, options: unknown) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableName), 'page', pageIndex, options] as const,\n\tinfiniteTableTotalCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown>) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableName), 'totalCount', where] as const,\n\tcursorTable: (scope: SheetsScopeKey, tableName: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'cursor-table', tableName, options] as const,\n} as const;\n","import { META_CONTRACT_REQUIREMENTS, type MetaContractIntrospectionQuery } from '@constructive-io/data';\n\nconst fields = (names: readonly string[]) => names.map((name) => ({ name }));\n\n/** Current `_meta` type signature for tests using an injected execute seam. */\nexport function createMetaContractFixture(): MetaContractIntrospectionQuery {\n\treturn Object.fromEntries(\n\t\tObject.entries(META_CONTRACT_REQUIREMENTS).map(([alias, requirement]) => [\n\t\t\talias,\n\t\t\t{ name: requirement.typeName, fields: fields(requirement.fields) },\n\t\t]),\n\t) as MetaContractIntrospectionQuery;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaA,IAAAA,gBAAwB;AACxB,IAAAC,kBAAsB;AAEtB,IAAAC,sBAA4B;AAE5B,IAAAC,eAMO;;;ACxBP,IAAAC,gBAAkD;AAClD,yBAAiD;AACjD,IAAAC,kBAA2D;;;ACF3D,mBAA0C;AAiFnC,IAAM,oBAAgB,4BAAyC,IAAI;;;AChF1E,IAAAC,kBAAsB;AAEtB,IAAAC,eAAoE;;;ACkBpE,qBAAsC;AAEtC,kBAA4B;AAkE5B,eAAsB,oBAAoB,QAAsC;AAC/E,MAAI,CAAC,WAAW,QAAQ,QAAQ;AAC/B,UAAM,wBAAY,WAAW,yEAAyE;AAAA,EACvG;AACA,QAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,MAAM;AAC3D,QAAM,QAAQ,IAAI,WAAW,MAAM;AACnC,MAAI,MAAM;AACV,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACtC,WAAO,MAAM,CAAC,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AAAA,EAC7C;AACA,SAAO;AACR;AAMA,IAAI,kBAAkB,oBAAI,QAAoE;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AW,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_zustand","import_graphql","import_data","field","query","data","url","idScalar","import_data","import_react","import_inflekt","import_data","import_data","fields","active","useZustandStore","store","import_data","import_jsx_runtime","documentToString"]}
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/context/sheets-upload-presigned.ts","../src/context/sheets-upload-discovery.ts","../src/store/sheets-store.ts","../src/store/draft-rows-slice.ts","../src/auth/utils/token-store.ts","../src/utils/sheets-logger.ts","../src/utils/sheets-i18n.ts","../src/hooks/query-keys.ts","../src/testing/meta-schema.ts","../src/testing/model-backend.ts","../src/testing/meta-contract-fixture.ts","../src/testing/model-backend-uploads.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';\nexport * from './meta-contract-fixture';\nexport { createModelBackend } from './model-backend';\nexport type { ModelBackend, ModelBackendOptions, ModelBackendUploadOptions, RecordedUpload } from './model-backend';\nexport { buildMetaSchemaSdl } from './meta-schema';\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: an\n// in-memory backend that serves `_meta`, schema introspection, list\n// connections, and create/update/delete mutations, while recording every\n// mutation for assertions.\n//\n// The tables are described as `MockTable`s. They become a `_meta` response and\n// a PostGraphile-shaped schema (see `meta-schema.ts`), and every document the\n// grid sends runs through graphql-js against that schema (see\n// `model-backend.ts`), so a document the schema would reject fails the test.\nimport { useMemo } from 'react';\nimport { buildSchema } from 'graphql';\nimport { QueryClient } from '@tanstack/react-query';\n\nimport {\n\ttoCamelCasePlural,\n\ttoCreateMutationName,\n\ttoUpdateMutationName,\n\ttoDeleteMutationName,\n} from '@constructive-io/data';\nimport type { MetaQuery, MetaschemaTable } from '@constructive-io/data';\n\nimport { SheetsProvider } from '../context/sheets-provider';\nimport type { SheetsExecuteFn, SheetsUploadFn, SheetsUploadOptions, SheetsUploadResult } from '../context/sheets-execute';\nimport { buildMetaSchemaSdl } from './meta-schema';\nimport { createModelBackend, type RecordedMutation } from './model-backend';\n\nexport type { RecordedMutation } from './model-backend';\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\t/** GraphQL field names in PK order. Defaults to `['id']` when an id field exists. */\n\tprimaryKeyFields?: string[];\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// Meta response synthesis\n// ============================================================================\n\nfunction buildMetaField(field: MockTableField, primaryKeyFields: ReadonlySet<string>) {\n\treturn {\n\t\tname: field.name,\n\t\tisPrimaryKey: primaryKeyFields.has(field.name),\n\t\tisForeignKey: false,\n\t\tisNotNull: false,\n\t\thasDefault: false,\n\t\tdescription: null,\n\t\tenumValues: null,\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\tencoding: null,\n\t\t},\n\t};\n}\n\nfunction buildMetaTable(table: MockTable): MetaschemaTable {\n\tconst primaryKeyFields = table.primaryKeyFields ?? (\n\t\ttable.fields.some((field) => field.name === 'id') ? ['id'] : []\n\t);\n\tconst primaryKeySet = new Set(primaryKeyFields);\n\tconst primaryKeyMetaFields = table.fields\n\t\t.filter((field) => primaryKeySet.has(field.name))\n\t\t.map((field) => buildMetaField(field, primaryKeySet));\n\tconst hasKey = primaryKeyMetaFields.length > 0;\n\treturn {\n\t\tname: table.name,\n\t\tschemaName: 'public',\n\t\tquery: {\n\t\t\tall: toCamelCasePlural(table.name),\n\t\t\tone: null,\n\t\t\tcreate: toCreateMutationName(table.name),\n\t\t\tupdate: hasKey ? toUpdateMutationName(table.name) : null,\n\t\t\tdelete: hasKey ? toDeleteMutationName(table.name) : null,\n\t\t},\n\t\tfields: table.fields.map((field) => buildMetaField(field, primaryKeySet)),\n\t\tinflection: {\n\t\t\ttableType: table.name,\n\t\t\tallRows: toCamelCasePlural(table.name),\n\t\t\tconnection: `${table.name}Connection`,\n\t\t\tfilterType: `${table.name}Filter`,\n\t\t\torderByType: `${table.name}OrderBy`,\n\t\t},\n\t\tindexes: [],\n\t\tconstraints: {\n\t\t\tprimaryKey: hasKey ? { name: `${table.name}_pkey`, fields: primaryKeyMetaFields } : null,\n\t\t\tunique: [],\n\t\t\tforeignKey: [],\n\t\t},\n\t\tforeignKeyConstraints: [],\n\t\tprimaryKeyConstraints: hasKey ? [{ name: `${table.name}_pkey`, fields: primaryKeyMetaFields }] : [],\n\t\tuniqueConstraints: [],\n\t\trelations: { belongsTo: [], has: [], hasOne: [], hasMany: [], manyToMany: [] },\n\t\tstorage: null,\n\t\tsearch: null,\n\t\ti18n: null,\n\t\trealtime: null,\n\t\tscope: null,\n\t};\n}\n\nfunction buildMetaResponse(tables: MockTable[]): MetaQuery {\n\treturn { _meta: { tables: tables.map(buildMetaTable) } };\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\nexport function createMockExecute(opts: MockSheetsOptions): MockExecuteHandle {\n\tconst meta = buildMetaResponse(opts.tables);\n\tconst metaTables = (meta._meta?.tables ?? []).filter((table): table is MetaschemaTable => table != null);\n\tconst backend = createModelBackend({\n\t\tschema: buildSchema(buildMetaSchemaSdl(metaTables)),\n\t\tmeta,\n\t\t// The row arrays are shared with the caller's MockTables, so tests see writes in place.\n\t\trows: Object.fromEntries(opts.tables.map((table) => [table.name, table.rows])),\n\t\tonMutation: opts.onMutation,\n\t});\n\tconst { mutations } = backend;\n\n\tconst executeUpload: SheetsUploadFn = async (\n\t\tfile: File,\n\t\tpath?: string,\n\t\toptions?: SheetsUploadOptions,\n\t): Promise<SheetsUploadResult> => {\n\t\tconst name = (file as File)?.name ?? 'file';\n\t\tconst upload: RecordedMutation = {\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\tmutations.push(upload);\n\t\topts.onMutation?.(upload);\n\t\tconst url = 'mock://uploaded/' + name;\n\t\treturn {\n\t\t\tfile: {\n\t\t\t\tid: 'mock-file-' + mutations.length,\n\t\t\t\tkey: name,\n\t\t\t\tbucket_id: 'mock-bucket',\n\t\t\t\tfilename: name,\n\t\t\t\tmime: file.type || 'application/octet-stream',\n\t\t\t\tsize: file.size,\n\t\t\t\turl,\n\t\t\t},\n\t\t\turl,\n\t\t};\n\t};\n\n\tfunction reset() {\n\t\tmutations.length = 0;\n\t}\n\n\treturn { execute: backend.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, 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","import { createContext, useContext } from 'react';\nimport type { QueryClient } from '@tanstack/react-query';\n\nimport type { DisplayFieldOverrides } from '@constructive-io/data';\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';\nimport type { SheetsUploadConfig } from '../uploads/upload-config';\nimport type { SheetsViewStorage } from '../grid/views/view-storage';\nimport type { SheetsMapConfig } from '../utils/map-settings';\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/**\n\t * Fields that label a record of a table (relation chips, pickers, record\n\t * titles), keyed by `TableModel.key` or table name, in priority order.\n\t * Tables without an entry use the built-in display rule.\n\t */\n\tdisplayFields?: DisplayFieldOverrides;\n\t/** Optional: BCP-47 locale for locale-aware date/number formatting (default 'en-US'). */\n\tlocale?: string;\n\t/**\n\t * The geometry editor's map: tile URL and attribution, and the place search endpoint.\n\t * Default: OpenStreetMap tiles and Nominatim search. `tiles: 'off'` edits shapes as\n\t * GeoJSON text; `placeSearch: 'off'` removes the search box. With a\n\t * Content-Security-Policy, allow the tile host in `img-src` and the search endpoint in\n\t * `connect-src`.\n\t */\n\tmap?: SheetsMapConfig;\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/** Upload choices (bucket, owner, files table, per-column overrides); every field is optional. */\n\tupload?: SheetsUploadConfig;\n\t/**\n\t * Where saved views are kept. Default: this browser's local storage, keyed by endpoint,\n\t * database, identity and table. A host can supply server storage.\n\t */\n\tviews?: SheetsViewStorage;\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 { DocumentNode } from 'graphql';\nimport { print } from 'graphql';\n\nimport { ConstructiveError, createError, isAuthenticationCode, parseGraphQLError, TypedDocumentString } from '@constructive-io/data';\n\nimport type { SheetsConfig, SheetsStorageTransport } from './sheets-context';\nimport { createPresignedSheetsUpload } from './sheets-upload-presigned';\n\n// The presigned uploader lives with the upload protocol; it stays importable from here.\nexport { createPresignedSheetsUpload };\n\n// ============================================================================\n// Types\n// ============================================================================\n\ntype ExecutableDocument = TypedDocumentString<any, any> | DocumentNode | string | unknown;\n\n/** Per-request options. An executor that does not support one ignores it. */\nexport interface SheetsExecuteOptions {\n\t/** Aborts the request, for example when the filter or sort it was for has changed. */\n\tsignal?: AbortSignal;\n}\n\nexport type SheetsExecuteFn = <T = unknown>(\n\tdocument: ExecutableDocument,\n\tvariables?: Record<string, unknown>,\n\toptions?: SheetsExecuteOptions,\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\n/** One error of a GraphQL response. */\nexport interface SheetsResponseError {\n\tmessage: string;\n\tpath?: ReadonlyArray<string | number>;\n\textensions?: { code?: string; context?: Record<string, unknown> };\n}\n\ninterface GraphQLResponse {\n\tdata?: unknown;\n\terrors?: SheetsResponseError[];\n}\n\n/** The data a response carried beside its errors. */\nexport interface SheetsPartialResult {\n\tdata: unknown;\n\terrors: readonly SheetsResponseError[];\n}\n\nconst PARTIAL_RESULT = 'partialResult';\nconst RESPONSE_ERRORS = 'responseErrors';\n\n/**\n * Keep a response's errors, and its data when it has some, on the error thrown\n * for it. Every error of the response stays readable (`responseErrorsOf`), and\n * a read whose rows came back with field errors (a float NaN cell) can keep\n * the rows (`partialResultOf`). Callers that only look at the thrown error see\n * it as before.\n */\nexport function withResponseErrors<E extends Error>(error: E, data: unknown, errors: readonly SheetsResponseError[]): E {\n\tObject.defineProperty(error, RESPONSE_ERRORS, { value: errors, enumerable: false, configurable: true });\n\tif (data != null) {\n\t\tObject.defineProperty(error, PARTIAL_RESULT, {\n\t\t\tvalue: { data, errors } satisfies SheetsPartialResult,\n\t\t\tenumerable: false,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\treturn error;\n}\n\n/** Every error of the response an error was thrown for, or null when it did not come from a GraphQL response. */\nexport function responseErrorsOf(error: unknown): readonly SheetsResponseError[] | null {\n\tconst errors = error && typeof error === 'object' ? (error as Record<string, unknown>)[RESPONSE_ERRORS] : null;\n\treturn Array.isArray(errors) ? (errors as SheetsResponseError[]) : null;\n}\n\n/** The data an error's response carried, or null. */\nexport function partialResultOf(error: unknown): SheetsPartialResult | null {\n\tconst partial = error && typeof error === 'object' ? (error as Record<string, unknown>)[PARTIAL_RESULT] : null;\n\treturn partial && typeof partial === 'object' ? (partial as SheetsPartialResult) : null;\n}\n\nfunction parseGraphQLResponse(response: GraphQLResponse, onAuthError?: () => void): ConstructiveError | null {\n\tif (!response.errors?.length) return null;\n\n\t// Only an explicit code (the shared list in @constructive-io/data) means the session is\n\t// gone. A permission error that mentions \"unauthorized\" in its text must not log the user out.\n\tif (response.errors.some((candidate) => isAuthenticationCode(candidate.extensions?.code))) {\n\t\tonAuthError?.();\n\t\treturn createError.unauthorized('Authentication required. Please log in again.');\n\t}\n\n\tconst error = response.errors[0];\n\tconst code = error.extensions?.code;\n\tconst message = error.message || 'GraphQL query failed';\n\n\t// A suspended database keeps its `context.reason` (billing or admin) for the paused screen.\n\tif (code === 'ACCESS_SUSPENDED') return parseGraphQLError(error);\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\toptions?: SheetsExecuteOptions,\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\t...(options?.signal ? { signal: options.signal } : {}),\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\tconst body = (await response.json().catch((): null => null)) as GraphQLResponse | null;\n\t\t\t\tconst refusal = body?.errors?.[0];\n\t\t\t\tconst forbidden = refusal?.extensions?.code === 'ACCESS_SUSPENDED'\n\t\t\t\t\t? parseGraphQLError(refusal)\n\t\t\t\t\t: createError.forbidden('You do not have permission to perform this action.');\n\t\t\t\tthrow body?.errors?.length ? withResponseErrors(forbidden, null, body.errors) : forbidden;\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()) as GraphQLResponse;\n\t\t\t\tif (body.errors?.length) {\n\t\t\t\t\tthrow withResponseErrors(\n\t\t\t\t\t\tcreateError.graphql(body.errors[0]!.message || `Request failed: ${status}`, body.errors[0]!.extensions?.code),\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\tbody.errors,\n\t\t\t\t\t);\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\t// A lost session or a suspended database never hands back partial rows.\n\t\t\tconst keepsData = !['UNAUTHENTICATED', 'ACCESS_SUSPENDED'].includes(graphqlError.code);\n\t\t\tthrow withResponseErrors(graphqlError, keepsData ? result.data : null, result.errors ?? []);\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 { ConstructiveError } from '@constructive-io/data';\n","/**\n * The presigned upload protocol, shared by every upload path.\n *\n * 1. Hash the file (SHA-256, Web Crypto). The server needs the hash before it\n * issues the URL: it names the object and is signed into the PUT.\n * 2. Ask the upload mutation for a presigned PUT URL. A `deduplicated` answer\n * means the bytes are already stored: no PUT.\n * 3. PUT the bytes with the payload's `uploadHeaders`, unchanged (the URL is\n * signed over them: Content-Type, the checksum, the file row id). No\n * Authorization header; the signature is in the URL.\n * 4. An expired URL is requested again once.\n *\n * The server confirms the PUT later (a background job) and expires rows that\n * never received one, so a cancelled or failed PUT leaves nothing behind.\n *\n * The model-driven path (`uploads/`) names the upload mutation from the storage\n * service's `_meta`. The shape discovery in `sheets-upload-discovery.ts` is the\n * FALLBACK for a storage service whose `_meta` names no upload mutation.\n */\n\nimport { createError } from '@constructive-io/data';\n\n// ============================================================================\n// Upload payload\n// ============================================================================\n\n/**\n * The file projection the upload mutation returns: what an image or upload\n * column stores. The server may add keys (image `versions`); they are kept as returned.\n */\nexport interface FileProjection {\n\tid: string;\n\tkey: string;\n\tbucket_id?: string;\n\tmime?: string;\n\tsize?: number;\n\tfilename?: string;\n\t/** Durable public URL; set only for a public bucket. */\n\turl?: string;\n}\n\n/** The upload mutation's answer, normalized. */\nexport interface UploadPayload {\n\tuploadUrl: string | null;\n\t/** Headers the PUT must send unchanged, or null on a server that does not return them. */\n\tuploadHeaders: Record<string, string> | null;\n\tfileId: string;\n\tkey: string;\n\tdeduplicated: boolean;\n\t/** When the upload URL expires (ISO time), or null. */\n\texpiresAt: string | null;\n\tfile: FileProjection;\n}\n\n/** Payload fields the client selects when the payload type has them. */\nexport const UPLOAD_PAYLOAD_FIELDS = ['uploadUrl', 'uploadHeaders', 'fileId', 'key', 'deduplicated', 'expiresAt', 'file'] as const;\n\nfunction headersOf(value: unknown): Record<string, string> | null {\n\tlet parsed = value;\n\tif (typeof parsed === 'string') {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed) as unknown;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;\n\tconst entries = Object.entries(parsed as Record<string, unknown>);\n\tif (!entries.every(([, header]) => typeof header === 'string')) return null;\n\treturn Object.fromEntries(entries) as Record<string, string>;\n}\n\nfunction projectionOf(value: unknown): FileProjection | null {\n\tlet parsed = value;\n\tif (typeof parsed === 'string') {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed) as unknown;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;\n\tconst projection = parsed as Record<string, unknown>;\n\treturn isFileProjection(projection) ? projection : null;\n}\n\n/** A projection names its file by `id` and `key`; the server may add more keys, which are kept. */\nfunction isFileProjection(value: Record<string, unknown>): value is Record<string, unknown> & FileProjection {\n\treturn typeof value.id === 'string' && typeof value.key === 'string';\n}\n\n// ============================================================================\n// Unfinished uploads: the file row an upload left behind\n// ============================================================================\n\n/**\n * The file row the storage service created for an upload that did not finish\n * (a refused or blocked PUT, a cancel, an answer without an upload URL). Sheets\n * never deletes it: the storage service expires a row that never received its\n * bytes. A host with its own cleanup rule reads it from the error.\n */\nexport interface UnfinishedUpload {\n\t/** Id of the files table row. */\n\tfileId: string;\n\t/** GraphQL type name of the files table, or null when the upload path does not know it. */\n\tfilesType: string | null;\n\t/** `TableModel.key` of the files table, or null when the upload path does not know it. */\n\tfilesTableKey: string | null;\n}\n\nconst UNFINISHED_UPLOAD = 'unfinishedUpload';\n\n/** The file row an upload error left on the storage service, or null when the server issued none. */\nexport function unfinishedUploadOf(error: unknown): UnfinishedUpload | null {\n\tconst value = error && typeof error === 'object' ? (error as Record<string, unknown>)[UNFINISHED_UPLOAD] : null;\n\treturn value && typeof value === 'object' ? (value as UnfinishedUpload) : null;\n}\n\n/**\n * Record on `error` the file row its upload left. An id already recorded is kept\n * (it is the newest one); a files table is filled in when the error has none. An\n * error without a file id is returned unchanged.\n */\nexport function withUnfinishedUpload(error: unknown, upload: Partial<UnfinishedUpload>): unknown {\n\tif (!error || typeof error !== 'object') return error;\n\tconst recorded = unfinishedUploadOf(error);\n\tconst fileId = recorded?.fileId ?? upload.fileId;\n\tif (!fileId) return error;\n\tconst value: UnfinishedUpload = {\n\t\tfileId,\n\t\tfilesType: recorded?.filesType ?? upload.filesType ?? null,\n\t\tfilesTableKey: recorded?.filesTableKey ?? upload.filesTableKey ?? null,\n\t};\n\tObject.defineProperty(error, UNFINISHED_UPLOAD, { value, enumerable: false, configurable: true, writable: true });\n\treturn error;\n}\n\n/** Normalize a raw upload payload. Throws when it cannot be used. */\nexport function readUploadPayload(raw: unknown): UploadPayload {\n\tif (!raw || typeof raw !== 'object') {\n\t\tthrow createError.badRequest('Upload failed: the storage service returned no answer.');\n\t}\n\tconst payload = raw as Record<string, unknown>;\n\tconst file = projectionOf(payload.file);\n\tif (!file) {\n\t\tthrow createError.badRequest('Upload failed: the server returned an invalid file projection.');\n\t}\n\tconst deduplicated = payload.deduplicated === true;\n\tconst uploadUrl = typeof payload.uploadUrl === 'string' && payload.uploadUrl ? payload.uploadUrl : null;\n\tif (!deduplicated && !uploadUrl) {\n\t\t// The server created the row; it is left to expire, and the error names it.\n\t\tthrow withUnfinishedUpload(createError.badRequest('Upload failed: the server returned no uploadUrl for a new file.'), {\n\t\t\tfileId: typeof payload.fileId === 'string' ? payload.fileId : file.id,\n\t\t});\n\t}\n\treturn {\n\t\tuploadUrl,\n\t\tuploadHeaders: headersOf(payload.uploadHeaders),\n\t\tfileId: typeof payload.fileId === 'string' ? payload.fileId : file.id,\n\t\tkey: typeof payload.key === 'string' ? payload.key : file.key,\n\t\tdeduplicated,\n\t\texpiresAt: typeof payload.expiresAt === 'string' ? payload.expiresAt : null,\n\t\tfile,\n\t};\n}\n\n// ============================================================================\n// SHA-256 (Web Crypto)\n// ============================================================================\n\n/**\n * Largest file the browser hashes. Web Crypto has no streaming digest, so the\n * whole file is read into memory once to hash it (the digest may copy it once\n * more). The PUT then sends the `File` itself, which the browser streams from\n * disk, so no second copy is kept for the upload. A streaming digest would need\n * a JavaScript SHA-256 implementation; until one is worth a dependency, files\n * above this size are refused with a clear message.\n */\nexport const MAX_HASHED_FILE_BYTES = 512 * 1024 * 1024;\n\nfunction hex(digest: ArrayBuffer): string {\n\tconst bytes = new Uint8Array(digest);\n\tlet out = '';\n\tfor (let i = 0; i < bytes.length; i++) out += bytes[i]!.toString(16).padStart(2, '0');\n\treturn out;\n}\n\nfunction requireSubtle(): SubtleCrypto {\n\tif (!globalThis.crypto?.subtle) {\n\t\tthrow createError.badRequest('This browser cannot hash files (Web Crypto is unavailable), so it cannot upload them.');\n\t}\n\treturn globalThis.crypto.subtle;\n}\n\n/** Lowercase hex SHA-256 of an already-read buffer (64 chars, as the server expects). */\nexport async function sha256HexFromBuffer(buffer: ArrayBuffer): Promise<string> {\n\treturn hex(await requireSubtle().digest('SHA-256', buffer));\n}\n\n/** The bytes of a blob. `Blob.arrayBuffer` where the browser has it, else a FileReader. */\nfunction readBytes(file: Blob): Promise<ArrayBuffer> {\n\tif (typeof file.arrayBuffer === 'function') return file.arrayBuffer();\n\treturn new Promise((resolve, reject) => {\n\t\tconst reader = new FileReader();\n\t\treader.onload = () => resolve(reader.result as ArrayBuffer);\n\t\treader.onerror = () => reject(reader.error ?? new Error('The file could not be read.'));\n\t\treader.readAsArrayBuffer(file);\n\t});\n}\n\n/** Lowercase hex SHA-256 of a file. Refuses files above {@link MAX_HASHED_FILE_BYTES}. */\nexport async function sha256HexOfFile(file: Blob): Promise<string> {\n\tif (file.size > MAX_HASHED_FILE_BYTES) {\n\t\tthrow createError.badRequest(\n\t\t\t`This file is too large to upload from the browser (the limit is ${MAX_HASHED_FILE_BYTES / (1024 * 1024)} MB).`,\n\t\t);\n\t}\n\tconst subtle = requireSubtle();\n\treturn hex(await subtle.digest('SHA-256', await readBytes(file)));\n}\n\n// ============================================================================\n// Presigned PUT\n// ============================================================================\n\n/** Header a checksum-bound presigned PUT carries (base64 of the raw digest). */\nexport const CHECKSUM_SHA256_HEADER = 'x-amz-checksum-sha256';\n/** Header a row-bound presigned PUT carries (the file row id). */\nexport const UPLOAD_ID_HEADER = 'x-amz-meta-upload-id';\n\n/** Hex SHA-256 to base64 of the raw digest, the encoding `x-amz-checksum-sha256` carries. */\nexport function sha256HexToBase64(contentHash: string): string {\n\tconst pairs = contentHash.match(/.{2}/g) ?? [];\n\tlet binary = '';\n\tfor (const pair of pairs) binary += String.fromCharCode(parseInt(pair, 16));\n\treturn btoa(binary);\n}\n\n/**\n * Headers for a server that signs the checksum and the row id but does not\n * return `uploadHeaders` yet. A current server returns them, and they are sent\n * as returned.\n */\nexport function fallbackPutHeaders(contentType: string, contentHash?: string, uploadId?: string): Record<string, string> {\n\treturn {\n\t\t'Content-Type': contentType,\n\t\t...(contentHash ? { [CHECKSUM_SHA256_HEADER]: sha256HexToBase64(contentHash) } : {}),\n\t\t...(uploadId ? { [UPLOAD_ID_HEADER]: uploadId } : {}),\n\t};\n}\n\n/**\n * A PUT the browser could not complete. The API answered moments ago, so the\n * usual cause is the bucket's CORS rule (no allowed origin for this site);\n * browsers do not say which. The words are for the person uploading; the code\n * `STORAGE_UPLOAD_BLOCKED` is for hosts and logs.\n */\nexport const STORAGE_UPLOAD_BLOCKED_MESSAGE =\n\t\"Upload failed: file storage didn't accept uploads from this site, or the connection dropped. If it keeps failing, ask an admin to allow this site in the storage settings.\";\n\nconst PUT_RESPONSE = 'putResponse';\n\n/** The storage server answered the PUT with an error status. The response is kept on the error. */\nfunction putRejected(status: number, statusText: string, body: string) {\n\tconst error = createError.badRequest(`Upload failed: ${status} ${statusText}${body ? ` — ${body}` : ''}`);\n\tObject.defineProperty(error, PUT_RESPONSE, { value: { status, body }, enumerable: false });\n\treturn error;\n}\n\n/** The status and body of a rejected PUT, or null for any other error. */\nexport function putResponseOf(error: unknown): { status: number; body: string } | null {\n\tconst response = error && typeof error === 'object' ? (error as Record<string, unknown>)[PUT_RESPONSE] : null;\n\treturn response && typeof response === 'object' ? (response as { status: number; body: string }) : null;\n}\n\nexport interface UploadProgressEvent {\n\tloaded: number;\n\ttotal: number;\n\tpercentage: number;\n}\n\nexport interface PutFileOptions {\n\theaders: Record<string, string>;\n\tonProgress?: (progress: UploadProgressEvent) => void;\n\tsignal?: AbortSignal;\n}\n\nfunction abortError(): Error {\n\treturn typeof DOMException === 'function'\n\t\t? new DOMException('The upload was cancelled.', 'AbortError')\n\t\t: Object.assign(new Error('The upload was cancelled.'), { name: 'AbortError' });\n}\n\n/** True for the error a cancelled upload rejects with. */\nexport function isAbortError(error: unknown): boolean {\n\treturn Boolean(error && typeof error === 'object' && (error as { name?: unknown }).name === 'AbortError');\n}\n\nfunction blockedError() {\n\treturn createError.graphql(STORAGE_UPLOAD_BLOCKED_MESSAGE, 'STORAGE_UPLOAD_BLOCKED');\n}\n\nfunction putWithXhr(url: string, body: Blob | ArrayBuffer, options: PutFileOptions, total: number): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst xhr = new XMLHttpRequest();\n\t\tconst onAbort = () => xhr.abort();\n\t\tconst done = () => options.signal?.removeEventListener('abort', onAbort);\n\t\txhr.open('PUT', url);\n\t\tfor (const [name, value] of Object.entries(options.headers)) xhr.setRequestHeader(name, value);\n\t\txhr.upload.addEventListener('progress', (event) => {\n\t\t\tif (!event.lengthComputable || event.total === 0) return;\n\t\t\toptions.onProgress?.({ loaded: event.loaded, total: event.total, percentage: Math.round((event.loaded / event.total) * 100) });\n\t\t});\n\t\txhr.addEventListener('load', () => {\n\t\t\tdone();\n\t\t\tif (xhr.status >= 200 && xhr.status < 300) {\n\t\t\t\toptions.onProgress?.({ loaded: total, total, percentage: 100 });\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\treject(putRejected(xhr.status, xhr.statusText, xhr.responseText ?? ''));\n\t\t\t}\n\t\t});\n\t\txhr.addEventListener('error', () => {\n\t\t\tdone();\n\t\t\treject(blockedError());\n\t\t});\n\t\txhr.addEventListener('abort', () => {\n\t\t\tdone();\n\t\t\treject(abortError());\n\t\t});\n\t\toptions.signal?.addEventListener('abort', onAbort, { once: true });\n\t\txhr.send(body);\n\t});\n}\n\n/** PUT bytes to a presigned URL with exactly the given headers. Uses XHR when progress is wanted and XHR exists. */\nexport async function putFile(url: string, body: Blob | ArrayBuffer, options: PutFileOptions): Promise<void> {\n\tif (options.signal?.aborted) throw abortError();\n\tconst total = body instanceof ArrayBuffer ? body.byteLength : body.size;\n\tif (options.onProgress && typeof XMLHttpRequest !== 'undefined') {\n\t\tawait putWithXhr(url, body, options, total);\n\t\treturn;\n\t}\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, {\n\t\t\tmethod: 'PUT',\n\t\t\theaders: options.headers,\n\t\t\tbody,\n\t\t\t...(options.signal ? { signal: options.signal } : {}),\n\t\t});\n\t} catch (error) {\n\t\tif (isAbortError(error)) throw abortError();\n\t\tthrow blockedError();\n\t}\n\tif (!response.ok) {\n\t\tthrow putRejected(response.status, response.statusText, await response.text().catch(() => ''));\n\t}\n\toptions.onProgress?.({ loaded: total, total, percentage: 100 });\n}\n\n/**\n * PUT an already-read buffer. Kept for callers of the earlier API; new code\n * uses {@link putFile} with the payload's `uploadHeaders`.\n */\nexport async function presignedPut(\n\turl: string,\n\tbuffer: ArrayBuffer,\n\tcontentType: string,\n\tonProgress?: (progress: UploadProgressEvent) => void,\n\tcontentHash?: string,\n\tuploadId?: string,\n): Promise<void> {\n\tawait putFile(url, buffer, { headers: fallbackPutHeaders(contentType, contentHash, uploadId), onProgress });\n}\n\n// ============================================================================\n// Transfer: hash, request, PUT, one renewal of an expired URL\n// ============================================================================\n\nexport interface UploadRequestInput {\n\tcontentHash: string;\n\tcontentType: string;\n\tsize: number;\n\tfilename: string;\n}\n\n/** Sends the upload mutation for one file. The signal aborts the request when the user cancels. */\nexport type UploadRequester = (input: UploadRequestInput, signal?: AbortSignal) => Promise<UploadPayload>;\n\nfunction isExpired(payload: UploadPayload, now = Date.now()): boolean {\n\tif (!payload.expiresAt) return false;\n\tconst expiry = Date.parse(payload.expiresAt);\n\treturn Number.isFinite(expiry) && expiry <= now;\n}\n\n/** S3 answers an expired presigned URL with 403 (\"Request has expired\"). */\nfunction looksExpired(error: unknown, payload: UploadPayload): boolean {\n\tconst response = putResponseOf(error);\n\tif (response?.status !== 403) return false;\n\treturn isExpired(payload) || /expired/i.test(response.body);\n}\n\nexport interface TransferOptions {\n\tonProgress?: (progress: UploadProgressEvent) => void;\n\tsignal?: AbortSignal;\n}\n\n/**\n * Upload one file through a requester: hash, request, PUT with the returned\n * headers. A URL that expired before or during the PUT is requested again once.\n * Any error after the server issued a file id carries it (`unfinishedUploadOf`);\n * the row itself is left for the storage service to expire.\n */\nexport async function transferFile(file: File, request: UploadRequester, options: TransferOptions = {}): Promise<UploadPayload> {\n\tconst contentType = file.type || 'application/octet-stream';\n\tconst contentHash = await sha256HexOfFile(file);\n\tif (options.signal?.aborted) throw abortError();\n\tconst input: UploadRequestInput = { contentHash, contentType, size: file.size, filename: file.name };\n\n\tlet payload = await request(input, options.signal);\n\t// From here on the server has issued a file id: the newest `payload` names it.\n\tconst putOrRenew = async (): Promise<UploadPayload> => {\n\t\tfor (let renewals = 0; ; renewals += 1) {\n\t\t\tif (payload.deduplicated) {\n\t\t\t\toptions.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\tif (options.signal?.aborted) throw abortError();\n\t\t\tif (isExpired(payload) && renewals === 0) {\n\t\t\t\tpayload = await request(input, options.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait putFile(payload.uploadUrl!, file, {\n\t\t\t\t\theaders: payload.uploadHeaders ?? fallbackPutHeaders(contentType, contentHash, payload.fileId),\n\t\t\t\t\tonProgress: options.onProgress,\n\t\t\t\t\tsignal: options.signal,\n\t\t\t\t});\n\t\t\t\treturn payload;\n\t\t\t} catch (error) {\n\t\t\t\tif (renewals > 0 || !looksExpired(error, payload)) throw error;\n\t\t\t\tpayload = await request(input, options.signal);\n\t\t\t}\n\t\t}\n\t};\n\ttry {\n\t\treturn await putOrRenew();\n\t} catch (error) {\n\t\tthrow withUnfinishedUpload(error, { fileId: payload.fileId });\n\t}\n}\n\n// ============================================================================\n// The fallback discovery, re-exported for callers of the earlier API\n// ============================================================================\n\nexport {\n\t__resetUploadCapabilityCache,\n\tcallUploadOp,\n\tcreatePresignedSheetsUpload,\n\tdiscoverSoleUploadCapability,\n\tdiscoverUploadCapability,\n\tfetchDownloadUrl,\n\tfetchMediaDownloadUrls,\n\trequestDiscoveredUpload,\n\tresolveDownloadUrl,\n\tresolveUploadCapability,\n} from './sheets-upload-discovery';\nexport type { IntrospectionSchema, LegacyUploadPayload, UploadCapability } from './sheets-upload-discovery';\n","/**\n * The FALLBACK upload path: shape discovery over the full introspection.\n *\n * Used only for a storage service whose `_meta` names no upload mutation (an\n * older server), and by hosts that call `createSheetsUpload` directly. It reads\n * the full introspection once per endpoint and finds root mutations with the\n * upload input and payload shape, and the fields that resolve a download URL by\n * file id. The model-driven path in `uploads/` replaces all of this when the\n * storage `_meta` names the upload mutation.\n */\n\nimport { getIntrospectionQuery } from 'graphql';\n\nimport { createError } from '@constructive-io/data';\n\nimport type { SheetsStorageTransport } from './sheets-context';\nimport type { SheetsExecuteFn, SheetsFileValue, SheetsUploadFn, SheetsUploadResult } from './sheets-execute';\nimport {\n\tUPLOAD_PAYLOAD_FIELDS,\n\treadUploadPayload,\n\ttransferFile,\n\twithUnfinishedUpload,\n\ttype FileProjection,\n\ttype UploadPayload,\n} from './sheets-upload-presigned';\n\n// ============================================================================\n// Shape discovery over the full introspection (cached per endpoint)\n// ============================================================================\n\nexport interface UploadCapability {\n\t/** Upload mutation field name, discovered by shape. */\n\tuploadFieldName: string;\n\t/** The upload input object type name. */\n\tinputTypeName: string;\n\thasFileProjection: boolean;\n\t/** Payload fields the mutation returns. Discovery sets it; a capability built by hand may leave it out. */\n\tpayloadFieldNames?: readonly string[];\n\t/** Input fields the mutation accepts. Discovery sets it; a capability built by hand may leave it out. */\n\tinputFieldNames?: readonly string[];\n\tdownload: DownloadByIdResult | null;\n}\n\ninterface DownloadByIdResult {\n\t/** Query field used to resolve downloadUrl by id. */\n\tfileByIdField: string;\n\t/** 'id' singular accessor, 'connection' filtered connection, 'nodeId' Relay node. */\n\tfileByIdArgName: 'id' | 'nodeId' | 'connection';\n\t/** The file object type name. */\n\tfileTypeName: string;\n\tidScalarName?: string;\n\tconnectionFilterArgName?: string;\n\tconnectionIdField?: string;\n\tconnectionIdOperator?: string;\n\tconnectionNodesField?: string;\n\tconnectionHasFirst?: boolean;\n}\n\ninterface StorageCapabilities {\n\t/** The op `discoverUploadCapability(endpoint, execute)` returns: `uploadAppFile`, else the first op that takes a `bucketKey`. */\n\tupload: UploadCapability | null;\n\t/** Every root upload op the endpoint exposes, one per storage plane. */\n\tuploads: Omit<UploadCapability, 'download'>[];\n\t/** The endpoint's only upload op, with its download lookup; null when it has none or several. */\n\tsole: UploadCapability | null;\n\tdownload: DownloadByIdResult | null;\n\tbatch: DownloadByIdResult | null;\n}\n\nlet capabilityCache = new WeakMap<SheetsExecuteFn, Map<string, Promise<StorageCapabilities>>>();\n\n/** Test-only: clear cached storage capabilities between cases. */\nexport function __resetUploadCapabilityCache(): void {\n\tcapabilityCache = new WeakMap();\n}\n\nasync function discoverStorageCapabilities(endpoint: string, execute: SheetsExecuteFn): Promise<StorageCapabilities> {\n\tlet endpoints = capabilityCache.get(execute);\n\tif (!endpoints) {\n\t\tendpoints = new Map();\n\t\tcapabilityCache.set(execute, endpoints);\n\t}\n\tconst cached = endpoints.get(endpoint);\n\tif (cached) return cached;\n\n\tconst promise = (async () => {\n\t\tconst data = await execute<{ __schema: IntrospectionSchema }>(getIntrospectionQuery());\n\t\tconst schema = data?.__schema;\n\t\tif (!schema) throw createError.badRequest('Uploads are not enabled for this endpoint.');\n\t\treturn resolveStorageCapabilities(schema);\n\t})();\n\t// Don't cache a rejected discovery: let the next attempt retry.\n\tpromise.catch(() => endpoints.delete(endpoint));\n\tendpoints.set(endpoint, promise);\n\treturn promise;\n}\n\n/**\n * The endpoint's upload op. Name it when the endpoint serves several storage\n * planes; the named op must still carry the upload shape.\n */\nexport async function discoverUploadCapability(\n\tendpoint: string,\n\texecute: SheetsExecuteFn,\n\tuploadFieldName?: string,\n): Promise<UploadCapability> {\n\tconst { upload, uploads } = await discoverStorageCapabilities(endpoint, execute);\n\tif (uploadFieldName) {\n\t\tconst named = uploads.find((candidate) => candidate.uploadFieldName === uploadFieldName);\n\t\tif (!named) throw createError.badRequest(`Uploads are not enabled for this endpoint: it has no ${uploadFieldName}.`);\n\t\treturn { ...named, download: null };\n\t}\n\tif (!upload) capabilityCache.get(execute)?.delete(endpoint);\n\treturn requireUploadCapability(upload);\n}\n\n/**\n * The fallback's upload op for the grid: exactly one plane, or a reason. The\n * grid never picks between several planes by name.\n */\nexport async function discoverSoleUploadCapability(storage: SheetsStorageTransport): Promise<UploadCapability> {\n\tconst { uploads, sole } = await discoverStorageCapabilities(storage.endpoint, storage.execute);\n\tif (uploads.length > 1) {\n\t\tthrow createError.badRequest('The storage service has several file stores, and none is chosen for this column.');\n\t}\n\tif (!sole) {\n\t\tcapabilityCache.get(storage.execute)?.delete(storage.endpoint);\n\t\tthrow createError.badRequest('Uploads are not enabled for this storage service.');\n\t}\n\treturn sole;\n}\n\nfunction requireUploadCapability(upload: UploadCapability | null): UploadCapability {\n\tif (!upload) throw createError.badRequest('Uploads are not enabled for this endpoint.');\n\treturn upload;\n}\n\n// --- Minimal introspection shapes (only what discovery reads) ---\n\ninterface IntrospectionTypeRef {\n\tkind: string;\n\tname?: string | null;\n\tofType?: IntrospectionTypeRef | null;\n}\n\ninterface IntrospectionInputValue {\n\tname: string;\n\ttype: IntrospectionTypeRef;\n}\n\ninterface IntrospectionField {\n\tname: string;\n\targs: ReadonlyArray<IntrospectionInputValue>;\n\ttype: IntrospectionTypeRef;\n}\n\ninterface IntrospectionType {\n\tkind: string;\n\tname?: string | null;\n\tfields?: ReadonlyArray<IntrospectionField> | null;\n\tinputFields?: ReadonlyArray<IntrospectionInputValue> | null;\n}\n\n/** Loose structural shape of an introspection `__schema` (accepts fixtures and real results). */\nexport interface IntrospectionSchema {\n\tqueryType?: { name: string } | null;\n\tmutationType?: { name: string } | null;\n\ttypes: ReadonlyArray<IntrospectionType>;\n}\n\nfunction namedTypeName(ref: IntrospectionTypeRef | null | undefined): string | null {\n\tlet cur = ref;\n\twhile (cur && (cur.kind === 'NON_NULL' || cur.kind === 'LIST')) cur = cur.ofType ?? null;\n\treturn cur?.name ?? null;\n}\n\n/** True when the outer wrapper (after NON_NULL) is a LIST. */\nfunction isListTypeRef(ref: IntrospectionTypeRef | null | undefined): boolean {\n\tlet cur = ref;\n\twhile (cur && cur.kind === 'NON_NULL') cur = cur.ofType ?? null;\n\treturn cur?.kind === 'LIST';\n}\n\n/**\n * The fallback reads the file row by an `id` field, as the projection names it.\n * The model-driven path reads the files table's real key instead.\n */\nconst PK_FIELD_NAME = 'id';\n\n/** Pure resolver over an introspection `__schema`, for direct tests. */\nexport function resolveUploadCapability(schema: IntrospectionSchema): UploadCapability {\n\treturn requireUploadCapability(resolveStorageCapabilities(schema).upload);\n}\n\nfunction resolveStorageCapabilities(schema: IntrospectionSchema): StorageCapabilities {\n\tconst typeByName = new Map<string, IntrospectionType>();\n\tfor (const t of schema.types) {\n\t\tif (t.name) typeByName.set(t.name, t);\n\t}\n\n\tconst objectHasFields = (typeName: string | null, names: string[]): boolean => {\n\t\tconst t = typeName ? typeByName.get(typeName) : undefined;\n\t\tif (!t?.fields) return false;\n\t\tconst present = new Set(t.fields.map((f) => f.name));\n\t\treturn names.every((n) => present.has(n));\n\t};\n\n\tconst inputHasFields = (typeName: string | null, names: string[]): boolean => {\n\t\tconst t = typeName ? typeByName.get(typeName) : undefined;\n\t\tif (!t?.inputFields) return false;\n\t\tconst present = new Set(t.inputFields.map((f) => f.name));\n\t\treturn names.every((n) => present.has(n));\n\t};\n\n\tconst PAYLOAD_FIELDS = ['uploadUrl', 'fileId', 'key', 'deduplicated'];\n\tconst INPUT_FIELDS = ['contentHash', 'contentType', 'size'];\n\t// The earlier API only knew ops that take a `bucketKey`; its pick keeps that rule.\n\tconst LEGACY_INPUT_FIELDS = [...INPUT_FIELDS, 'bucketKey'];\n\n\tconst mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;\n\tconst queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;\n\n\tlet upload: Omit<UploadCapability, 'download'> | null = null;\n\tconst uploads: Omit<UploadCapability, 'download'>[] = [];\n\n\tfor (const field of mutationType?.fields ?? []) {\n\t\tconst inputArg = field.args.find((a) => a.name === 'input');\n\t\tif (!inputArg) continue;\n\t\tconst inputTypeName = namedTypeName(inputArg.type);\n\t\tconst payloadTypeName = namedTypeName(field.type);\n\t\tif (inputTypeName && inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {\n\t\t\tconst payloadFields = typeByName.get(payloadTypeName ?? '')?.fields ?? [];\n\t\t\tconst candidate = {\n\t\t\t\tuploadFieldName: field.name,\n\t\t\t\tinputTypeName,\n\t\t\t\thasFileProjection: payloadFields.some(\n\t\t\t\t\t(f) => f.name === 'file' && !isListTypeRef(f.type) && namedTypeName(f.type) === 'JSON',\n\t\t\t\t),\n\t\t\t\tpayloadFieldNames: payloadFields.map((f) => f.name),\n\t\t\t\tinputFieldNames: (typeByName.get(inputTypeName)?.inputFields ?? []).map((f) => f.name),\n\t\t\t};\n\t\t\tuploads.push(candidate);\n\t\t\t// The pick of the earlier API (`discoverUploadCapability` without a name, and\n\t\t\t// `createSheetsUpload`). The grid's fallback (`discoverSoleUploadCapability`)\n\t\t\t// refuses to choose between planes.\n\t\t\tif (!inputHasFields(inputTypeName, LEGACY_INPUT_FIELDS) || (upload?.uploadFieldName === 'uploadAppFile')) continue;\n\t\t\tif (field.name === 'uploadAppFile') upload = candidate;\n\t\t\telse upload ??= candidate;\n\t\t}\n\t}\n\n\tconst fileTypes = new Set<string>();\n\tfor (const t of schema.types) {\n\t\tif (t.kind === 'OBJECT' && t.name && t.fields?.some((f) => f.name === 'downloadUrl')) fileTypes.add(t.name);\n\t}\n\n\t// Legacy: the file type is read from the upload op's name (uploadAppFile → AppFile).\n\t// Only this fallback does so; the model-driven path reads it from `_meta`.\n\tconst uploadType = upload?.uploadFieldName.replace(/^upload/, '') ?? 'AppFile';\n\tconst uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);\n\tconst preferredPreviewType = fileTypes.has('AppFile') ? 'AppFile' : uploadType;\n\tconst previewType = fileTypes.has(preferredPreviewType)\n\t\t? preferredPreviewType\n\t\t: uploadDownload?.fileTypeName ?? preferredPreviewType;\n\tconst download = previewType === uploadType\n\t\t? uploadDownload\n\t\t: resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);\n\tconst batch = resolveConnectionDownloadField(typeByName, queryType, fileTypes, previewType, true);\n\n\tconst only = uploads.length === 1 ? uploads[0]! : null;\n\tconst sole = only\n\t\t? {\n\t\t\t...only,\n\t\t\tdownload: only === upload\n\t\t\t\t? uploadDownload\n\t\t\t\t: resolveDownloadByIdField(typeByName, queryType, fileTypes, only.uploadFieldName.replace(/^upload/, '')),\n\t\t}\n\t\t: null;\n\n\treturn {\n\t\tupload: upload ? { ...upload, download: uploadDownload } : null,\n\t\tuploads,\n\t\tsole,\n\t\tdownload,\n\t\tbatch,\n\t};\n}\n\nfunction resolveDownloadByIdField(\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tfileTypesWithDownloadUrl: Set<string>,\n\tpreferred: string,\n): DownloadByIdResult | null {\n\t// 1. A singular by-id accessor, e.g. appFile(id:).\n\tlet singular: DownloadByIdResult | null = null;\n\tfor (const field of queryType?.fields ?? []) {\n\t\tconst returnTypeName = namedTypeName(field.type);\n\t\tif (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;\n\t\tif (field.args.length === 1 && field.args[0]!.name === PK_FIELD_NAME) {\n\t\t\tconst candidate: DownloadByIdResult = {\n\t\t\t\tfileByIdField: field.name,\n\t\t\t\tfileByIdArgName: 'id',\n\t\t\t\tfileTypeName: returnTypeName,\n\t\t\t\tidScalarName: namedTypeName(field.args[0]!.type) ?? undefined,\n\t\t\t};\n\t\t\tif (returnTypeName === preferred) return candidate;\n\t\t\tsingular ??= candidate;\n\t\t}\n\t}\n\n\t// 2. A connection filtered by id (Relay-disabled backends).\n\tconst connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);\n\tif (connection?.fileTypeName === preferred) return connection;\n\tif (singular || connection) return singular ?? connection;\n\n\t// 3. Relay `node(nodeId:)`, last resort.\n\tconst nodeField = queryType?.fields?.find((f) => f.name === 'node' && f.args.some((a) => a.name === 'nodeId'));\n\tif (nodeField && fileTypesWithDownloadUrl.size > 0) {\n\t\tconst fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0]!;\n\t\treturn { fileByIdField: 'node', fileByIdArgName: 'nodeId', fileTypeName };\n\t}\n\treturn null;\n}\n\nfunction resolveConnectionDownloadField(\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tfileTypesWithDownloadUrl: Set<string>,\n\tpreferred: string,\n\tbatch = false,\n): DownloadByIdResult | null {\n\tconst EQUALITY_OPERATORS = ['equalTo', 'eq'];\n\tconst candidates: DownloadByIdResult[] = [];\n\n\tfor (const field of queryType?.fields ?? []) {\n\t\tconst connTypeName = namedTypeName(field.type);\n\t\tif (!connTypeName) continue;\n\t\tconst connType = typeByName.get(connTypeName);\n\t\tif (connType?.kind !== 'OBJECT' || !connType.fields) continue;\n\n\t\tconst nodesField = connType.fields.find((f) => {\n\t\t\tif (!isListTypeRef(f.type)) return false;\n\t\t\tconst elem = namedTypeName(f.type);\n\t\t\treturn elem != null && fileTypesWithDownloadUrl.has(elem);\n\t\t});\n\t\tif (!nodesField) continue;\n\t\tconst fileTypeName = namedTypeName(nodesField.type) as string;\n\t\tif (batch && (fileTypeName !== preferred ||\n\t\t\t!typeByName.get(fileTypeName)?.fields?.some((candidate) => candidate.name === PK_FIELD_NAME))) continue;\n\t\tconst connectionHasFirst = field.args.some((arg) => arg.name === 'first');\n\n\t\tfor (const arg of field.args) {\n\t\t\tconst filterTypeName = namedTypeName(arg.type);\n\t\t\tconst filterType = filterTypeName ? typeByName.get(filterTypeName) : null;\n\t\t\tif (filterType?.kind !== 'INPUT_OBJECT' || !filterType.inputFields) continue;\n\t\t\tconst idField = filterType.inputFields.find((f) => f.name === PK_FIELD_NAME);\n\t\t\tif (!idField) continue;\n\n\t\t\tconst idFieldTypeName = namedTypeName(idField.type);\n\t\t\tconst idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;\n\n\t\t\tif (idFieldType?.kind === 'INPUT_OBJECT' && idFieldType.inputFields) {\n\t\t\t\tconst inputFields = idFieldType.inputFields;\n\t\t\t\tconst opField = batch\n\t\t\t\t\t? inputFields.find((f) => f.name === 'in' && isListTypeRef(f.type))\n\t\t\t\t\t: EQUALITY_OPERATORS.map((op) => inputFields.find((f) => f.name === op)).find((f) => f != null);\n\t\t\t\tif (opField) {\n\t\t\t\t\tcandidates.push({\n\t\t\t\t\t\tfileByIdField: field.name,\n\t\t\t\t\t\tfileByIdArgName: 'connection',\n\t\t\t\t\t\tfileTypeName,\n\t\t\t\t\t\tidScalarName: namedTypeName(opField.type) ?? undefined,\n\t\t\t\t\t\tconnectionFilterArgName: arg.name,\n\t\t\t\t\t\tconnectionIdField: idField.name,\n\t\t\t\t\t\tconnectionIdOperator: opField.name,\n\t\t\t\t\t\tconnectionNodesField: nodesField.name,\n\t\t\t\t\t\tconnectionHasFirst,\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!batch && (idFieldType?.kind === 'SCALAR' || (!idFieldType && idFieldTypeName))) {\n\t\t\t\tcandidates.push({\n\t\t\t\t\tfileByIdField: field.name,\n\t\t\t\t\tfileByIdArgName: 'connection',\n\t\t\t\t\tfileTypeName,\n\t\t\t\t\tidScalarName: idFieldTypeName ?? undefined,\n\t\t\t\t\tconnectionFilterArgName: arg.name,\n\t\t\t\t\tconnectionIdField: idField.name,\n\t\t\t\t\tconnectionNodesField: nodesField.name,\n\t\t\t\t\tconnectionHasFirst,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (candidates.length === 0) return null;\n\treturn candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0]!;\n}\n\n// ============================================================================\n// Fallback: upload op call\n// ============================================================================\n\ninterface UploadOpInput {\n\tbucketKey?: string;\n\tisPublic?: boolean;\n\tdatabaseId?: string;\n\tcontentHash: string;\n\tcontentType: string;\n\tsize: number;\n\tfilename: string;\n}\n\n/**\n * The upload input for a discovered op. Only input fields the op really has are\n * sent (all of them when the capability lists none); `ownerId` never is (the\n * fallback cannot know an owner, so an entity-scoped plane fails there with the\n * server's message).\n */\nfunction uploadInputOf(cap: UploadCapability, input: UploadOpInput): Record<string, unknown> {\n\tconst inputFields = new Set(cap.inputFieldNames ?? []);\n\tconst has = (name: string) => inputFields.size === 0 || inputFields.has(name);\n\tconst bucket = input.bucketKey !== undefined\n\t\t? (has('bucketKey') ? { bucketKey: input.bucketKey } : {})\n\t\t: (has('isPublic') ? { isPublic: input.isPublic ?? true } : {});\n\treturn {\n\t\t...bucket,\n\t\t...(input.databaseId !== undefined && inputFields.has('databaseId') ? { databaseId: input.databaseId } : {}),\n\t\tcontentHash: input.contentHash,\n\t\tcontentType: input.contentType,\n\t\tsize: input.size,\n\t\t...(has('filename') ? { filename: input.filename } : {}),\n\t};\n}\n\nfunction uploadMutation(cap: UploadCapability, payloadFields: readonly string[]): string {\n\treturn `\n\t\tmutation SheetsUpload($input: ${cap.inputTypeName}!) {\n\t\t\t${cap.uploadFieldName}(input: $input) {\n\t\t\t\t${payloadFields.join('\\n\\t\\t\\t\\t')}\n\t\t\t}\n\t\t}\n\t`.trim();\n}\n\n/** Payload fields of the earlier API, selected when the op's payload fields are not known. */\nconst LEGACY_PAYLOAD_FIELDS = ['uploadUrl', 'fileId', 'key', 'deduplicated', 'file'] as const;\n\n/** Invoke a discovered upload op and normalize its payload (strict: see `readUploadPayload`). */\nexport async function requestDiscoveredUpload(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\n\tinput: UploadOpInput,\n\tsignal?: AbortSignal,\n): Promise<UploadPayload> {\n\tconst payloadFields = cap.payloadFieldNames?.length\n\t\t? UPLOAD_PAYLOAD_FIELDS.filter((name) => cap.payloadFieldNames!.includes(name))\n\t\t: LEGACY_PAYLOAD_FIELDS;\n\tconst data = await execute<Record<string, unknown>>(uploadMutation(cap, payloadFields), { input: uploadInputOf(cap, input) }, { signal });\n\treturn readUploadPayload(data?.[cap.uploadFieldName]);\n}\n\n/** The payload of the earlier API: the server's answer as it was sent. */\nexport interface LegacyUploadPayload {\n\tuploadUrl: string | null;\n\tfileId: string;\n\tkey: string;\n\tdeduplicated: boolean;\n\tfile: Omit<SheetsFileValue, 'filename'> & { filename?: string | null };\n}\n\n/**\n * Earlier API: send the discovered upload op and return its payload as the\n * server sent it. The file projection must carry an id, key, bucket, type and\n * size, and nothing is added to it. A new file without an `uploadUrl` is left\n * to the caller, which knows the `fileId` and can remove the row.\n */\nexport async function callUploadOp(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\n\tinput: UploadOpInput,\n): Promise<LegacyUploadPayload> {\n\tconst data = await execute<Record<string, LegacyUploadPayload | null>>(uploadMutation(cap, LEGACY_PAYLOAD_FIELDS), {\n\t\tinput: uploadInputOf(cap, input),\n\t});\n\tconst payload = data?.[cap.uploadFieldName];\n\tif (!payload) {\n\t\tthrow createError.badRequest('Upload failed: no payload returned from upload mutation.');\n\t}\n\tconst file = payload.file;\n\tif (\n\t\t!file || typeof file.id !== 'string' || typeof file.key !== 'string' ||\n\t\ttypeof file.bucket_id !== 'string' || typeof file.mime !== 'string' || typeof file.size !== 'number'\n\t) {\n\t\tthrow createError.badRequest('Upload failed: server returned an invalid file projection.');\n\t}\n\treturn payload;\n}\n\nfunction projectionToFileValue(file: FileProjection, fallbackName: string, fallbackMime: string): SheetsFileValue {\n\treturn {\n\t\t...file,\n\t\tbucket_id: typeof file.bucket_id === 'string' ? file.bucket_id : '',\n\t\tmime: typeof file.mime === 'string' ? file.mime : fallbackMime,\n\t\tsize: typeof file.size === 'number' ? file.size : 0,\n\t\tfilename: typeof file.filename === 'string' ? file.filename : fallbackName,\n\t};\n}\n\n/**\n * An uploader over the fallback discovery, for hosts that call\n * `createSheetsUpload` directly. The grid uses the model-driven path instead.\n */\nexport function createPresignedSheetsUpload(\n\t{ endpoint, execute }: SheetsStorageTransport,\n\tbucketKey?: string,\n): SheetsUploadFn {\n\treturn async (file, _path, options) => {\n\t\tif (!endpoint) throw createError.badRequest('No GraphQL endpoint configured.');\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\t\tlet payload: UploadPayload;\n\t\ttry {\n\t\t\tpayload = await transferFile(\n\t\t\t\tfile,\n\t\t\t\t(input) => requestDiscoveredUpload(execute, cap, { ...input, bucketKey }),\n\t\t\t\t{ onProgress: options?.onProgress },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow withUnfinishedUpload(error, { filesType: cap.download?.fileTypeName ?? null });\n\t\t}\n\t\tconst result: SheetsUploadResult = {\n\t\t\tfile: projectionToFileValue(payload.file, file.name, file.type || 'application/octet-stream'),\n\t\t};\n\t\tif (!cap.download) return result;\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\n// ============================================================================\n// Fallback: downloadUrl resolution\n// ============================================================================\n\n/** Encode a PostGraphile global id with the default base64JSON codec. */\nfunction toGlobalId(typeName: string, id: string): string {\n\tif (typeof btoa !== 'function') {\n\t\tthrow createError.badRequest('Cannot encode the file node id: btoa is unavailable in this environment.');\n\t}\n\treturn btoa(JSON.stringify([typeName, id]));\n}\n\n/** Resolve one file's download URL through a discovered accessor. The URL can expire. */\nexport async function fetchDownloadUrl(execute: SheetsExecuteFn, cap: DownloadByIdResult, fileId: string): Promise<string> {\n\tconst missing = () => createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\tif (cap.fileByIdArgName === 'nodeId') {\n\t\tconst nodeId = toGlobalId(cap.fileTypeName, fileId);\n\t\tconst query = `\n\t\t\tquery SheetsDownloadUrl($nodeId: ID!) {\n\t\t\t\t${cap.fileByIdField}(nodeId: $nodeId) {\n\t\t\t\t\t... on ${cap.fileTypeName} {\n\t\t\t\t\t\tdownloadUrl\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`.trim();\n\t\tconst data = await execute<Record<string, { downloadUrl?: string | null } | null>>(query, { nodeId });\n\t\tconst url = data?.[cap.fileByIdField]?.downloadUrl;\n\t\tif (!url) throw missing();\n\t\treturn url;\n\t}\n\n\tif (cap.fileByIdArgName === 'connection') {\n\t\tconst idScalar = cap.idScalarName ?? 'ID';\n\t\tconst filterArg = cap.connectionFilterArgName as string;\n\t\tconst idField = cap.connectionIdField as string;\n\t\tconst nodesField = cap.connectionNodesField as string;\n\t\tconst filterLiteral = cap.connectionIdOperator\n\t\t\t? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }`\n\t\t\t: `{ ${idField}: $id }`;\n\t\tconst query = `\n\t\t\tquery SheetsDownloadUrl($id: ${idScalar}!) {\n\t\t\t\t${cap.fileByIdField}(${filterArg}: ${filterLiteral}${cap.connectionHasFirst ? ', first: 1' : ''}) {\n\t\t\t\t\t${nodesField} {\n\t\t\t\t\t\tdownloadUrl\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`.trim();\n\t\tconst data = await execute<Record<string, Record<string, Array<{ downloadUrl?: string | null }> | null> | null>>(\n\t\t\tquery,\n\t\t\t{ id: fileId },\n\t\t);\n\t\tconst url = data?.[cap.fileByIdField]?.[nodesField]?.[0]?.downloadUrl;\n\t\tif (!url) throw missing();\n\t\treturn url;\n\t}\n\n\tconst idScalar = cap.idScalarName ?? 'ID';\n\tconst query = `\n\t\tquery SheetsDownloadUrl($id: ${idScalar}!) {\n\t\t\t${cap.fileByIdField}(id: $id) {\n\t\t\t\tid\n\t\t\t\tdownloadUrl\n\t\t\t}\n\t\t}\n\t`.trim();\n\tconst data = await execute<Record<string, { downloadUrl?: string | null } | null>>(query, { id: fileId });\n\tconst url = data?.[cap.fileByIdField]?.downloadUrl;\n\tif (!url) throw missing();\n\treturn url;\n}\n\n/** Resolve URLs for one batch of visible files through the fallback discovery. Missing IDs have no entry. */\nexport async function fetchMediaDownloadUrls(\n\t{ endpoint, execute }: SheetsStorageTransport,\n\tgetActiveIds: () => readonly string[],\n): Promise<Map<string, string>> {\n\tconst { batch, download } = await discoverStorageCapabilities(endpoint, execute);\n\tconst ids = getActiveIds();\n\tconst urls = new Map<string, string>();\n\tif (ids.length === 0) return urls;\n\tif (batch) {\n\t\tconst first = batch.connectionHasFirst ? `, first: ${ids.length}` : '';\n\t\tconst query = `query SheetsMediaDownloadUrls($ids: [${batch.idScalarName ?? 'ID'}!]!) {\n\t\t\t${batch.fileByIdField}(${batch.connectionFilterArgName}: {\n\t\t\t\t${batch.connectionIdField}: { in: $ids }\n\t\t\t}${first}) { ${batch.connectionNodesField} { id downloadUrl } }\n\t\t}`;\n\t\ttype FileNode = { id: string; downloadUrl: string | null };\n\t\tconst data = await execute<Record<string, Record<string, (FileNode | null)[] | null> | null>>(query, { ids });\n\t\tfor (const row of data?.[batch.fileByIdField]?.[batch.connectionNodesField!] ?? []) {\n\t\t\tif (row?.downloadUrl) urls.set(row.id, row.downloadUrl);\n\t\t}\n\t} else if (download) {\n\t\tconst results = await Promise.allSettled(ids.map((id) => fetchDownloadUrl(execute, download, id)));\n\t\tresults.forEach((result, index) => {\n\t\t\tif (result.status === 'fulfilled') urls.set(ids[index]!, result.value);\n\t\t});\n\t}\n\treturn urls;\n}\n\n/**\n * Resolve a file's signed `downloadUrl` by id, for callers outside the grid\n * (a storage browser's copy link). Returns null on any failure.\n */\nexport async function resolveDownloadUrl(execute: SheetsExecuteFn, endpoint: string, fileId: string): Promise<string | null> {\n\ttry {\n\t\tconst { download } = await discoverStorageCapabilities(endpoint, execute);\n\t\treturn download ? await fetchDownloadUrl(execute, download, fileId) : null;\n\t} catch {\n\t\treturn null;\n\t}\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';\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 & SheetsAuthState;\n\nexport function createSheetsStore(): StoreApi<SheetsStoreState> {\n return createStore<SheetsStoreState>((set) => ({\n // Draft rows\n ...createDraftRowsSlice(set),\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","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);\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);\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 // Untouched: the key exists (so a meta sync keeps the cell) but holds no value, so\n // the create leaves it out and the database default applies. A value the user set,\n // null and '' included, is sent as given.\n template[column] = undefined;\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\n// A draft row is identified by its DraftMeta (`draftRowId`), never by a value: every\n// column starts empty, so a key column the user must type (a key with no default)\n// is an ordinary editable cell and is sent on create.\nfunction initializeValuesFromTemplate(template: Record<string, unknown>): 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 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","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\tidentityKey?: string | null;\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\tif (parsed.identityKey != null && typeof parsed.identityKey !== 'string') return null;\n\t\treturn parsed;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function setStoredToken(\n\tdatabaseId: string,\n\taccessToken: string,\n\texpiresAt: string,\n\tidentityKey?: string | null,\n): void {\n\tconst storage = getStorage();\n\tif (!storage) return;\n\n\ttry {\n\t\tconst data: StoredToken = { accessToken, expiresAt, identityKey };\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","import type { SheetsScopeKey } from '../context/sheets-context';\n\nexport function isSheetsScopeKey(value: unknown): value is SheetsScopeKey {\n\tif (!value || typeof value !== 'object') return false;\n\tconst candidate = value as Record<string, unknown>;\n\treturn 'databaseId' in candidate && 'endpoint' in candidate && 'identityKey' in candidate;\n}\n\nexport function reuseSheetsPlaceholderData<T>(\n\tpreviousData: T | undefined,\n\tpreviousQueryKey: readonly unknown[] | undefined,\n\tcurrentScope: SheetsScopeKey,\n): T | undefined {\n\tconst previousScope = previousQueryKey?.[1];\n\tif (!isSheetsScopeKey(previousScope)) return undefined;\n\tif (previousScope.databaseId !== currentScope.databaseId) return undefined;\n\tif (previousScope.endpoint !== currentScope.endpoint) return undefined;\n\tif (previousScope.identityKey !== currentScope.identityKey) return undefined;\n\treturn previousData;\n}\n\n/**\n * Cache-key segments for a table reference. A `TableModel.key`\n * (`schema.Name`) becomes `[Name, schema]`, a bare name `[Name]`. Tables in\n * different schemas get different entries, and a key built from a bare name is\n * a prefix of every schema's entry, so invalidating by name still reaches them.\n */\nexport function tableKeySegments(tableRef: string): readonly string[] {\n\tconst dot = tableRef.lastIndexOf('.');\n\treturn dot === -1 ? [tableRef] : [tableRef.slice(dot + 1), tableRef.slice(0, dot)];\n}\n\nexport const sheetsQueryKeys = {\n\troot: ['sheets'] as const,\n\tscope: (scope: SheetsScopeKey) => ['sheets', scope] as const,\n\tmeta: (scope: SheetsScopeKey) => [...sheetsQueryKeys.scope(scope), 'meta'] as const,\n\t/** One table model, per `_meta` version and display override. */\n\ttableModel: (scope: SheetsScopeKey, tableKey: string, metaVersion: number, displayKey: string | null) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'table-model', ...tableKeySegments(tableKey), metaVersion, displayKey] as const,\n\tmediaUrl: (scope: SheetsScopeKey, endpoint: string | undefined, id: string | null) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'media-url', endpoint, id] as const,\n\trelations: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'relations', ...tableKeySegments(tableName)] as const,\n\ttable: (scope: SheetsScopeKey, tableRef: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'table', ...tableKeySegments(tableRef)] as const,\n\ttableRows: (scope: SheetsScopeKey, tableRef: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableRef), 'rows', options] as const,\n\ttableRow: (scope: SheetsScopeKey, tableRef: string, id: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableRef), 'row', id] as const,\n\ttableCount: (scope: SheetsScopeKey, tableRef: string, where?: Readonly<Record<string, unknown>> | null) =>\n\t\t[...sheetsQueryKeys.table(scope, tableRef), 'count', where] as const,\n\tinfiniteTable: (scope: SheetsScopeKey, tableRef: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'infinite-table', ...tableKeySegments(tableRef)] as const,\n\tinfiniteTablePage: (scope: SheetsScopeKey, tableRef: string, pageIndex: number, options: unknown) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableRef), 'page', pageIndex, options] as const,\n\tinfiniteTableTotalCount: (scope: SheetsScopeKey, tableRef: string, where?: Readonly<Record<string, unknown>>) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableRef), 'totalCount', where] as const,\n\tcursorTable: (scope: SheetsScopeKey, tableRef: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'cursor-table', ...tableKeySegments(tableRef), options] as const,\n} as const;\n\n/**\n * Mutation keys. Every mutation a Sheets hook creates sits under its table's\n * query key, `[...table(scope, tableRef), 'mutation', operation, ...detail]`, so\n * `useIsMutating({ mutationKey: sheetsMutationKeys.table(scope, ref) })` counts\n * every write in flight on that table.\n */\nexport const sheetsMutationKeys = {\n\t/** Every mutation of a table, or one operation of it when `operation` is given. */\n\ttable: (scope: SheetsScopeKey, tableRef: string, operation?: string, ...detail: readonly unknown[]) =>\n\t\toperation === undefined\n\t\t\t? ([...sheetsQueryKeys.table(scope, tableRef), 'mutation'] as const)\n\t\t\t: ([...sheetsQueryKeys.table(scope, tableRef), 'mutation', operation, ...detail] as const),\n} as const;\n","// A PostGraphile-shaped schema (SDL) synthesized from `_meta` tables.\n//\n// For mock backends whose tables are described only by `_meta` (the `/testing`\n// MockTable list, the Storybook fixtures). Names come from `_meta.query`; the\n// shapes follow PostGraphile: a connection per table, a filter input with\n// per-scalar operator inputs and `and`/`or`/`not`, an order-by enum, and\n// create/update/delete mutations whose input carries the record, the patch and\n// the primary key. Captured schemas do not need this.\nimport {\n\tgetRowIdentityDefinition,\n\ttoCamelCaseSingular,\n\ttype MetaschemaField,\n\ttype MetaschemaTable,\n} from '@constructive-io/data';\n\nconst BUILT_IN_SCALARS = new Set(['String', 'Int', 'Float', 'Boolean', 'ID']);\nconst ORDERED_SCALARS = new Set(['Int', 'Float', 'BigInt', 'BigFloat', 'Date', 'Datetime', 'Time', 'String', 'UUID']);\n\nfunction constantCase(name: string): string {\n\treturn name\n\t\t.replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n\t\t.replace(/[^A-Za-z0-9]+/g, '_')\n\t\t.toUpperCase();\n}\n\nfunction fieldsOf(table: MetaschemaTable): MetaschemaField[] {\n\treturn (table.fields ?? []).filter((field): field is MetaschemaField => Boolean(field?.name));\n}\n\nfunction typeRef(field: MetaschemaField): string {\n\treturn field.type.isArray ? `[${field.type.gqlType}]` : field.type.gqlType;\n}\n\nfunction operatorType(field: MetaschemaField): string {\n\treturn field.type.isArray ? `${field.type.gqlType}ListFilter` : `${field.type.gqlType}Filter`;\n}\n\nfunction scalarFilter(scalar: string): string {\n\tconst ordered = ORDERED_SCALARS.has(scalar)\n\t\t? `lessThan: ${scalar} lessThanOrEqualTo: ${scalar} greaterThan: ${scalar} greaterThanOrEqualTo: ${scalar}`\n\t\t: '';\n\tconst text = scalar === 'String'\n\t\t? 'includes: String notIncludes: String includesInsensitive: String notIncludesInsensitive: String startsWith: String startsWithInsensitive: String endsWith: String endsWithInsensitive: String equalToInsensitive: String'\n\t\t: '';\n\treturn `input ${scalar}Filter { isNull: Boolean equalTo: ${scalar} notEqualTo: ${scalar} distinctFrom: ${scalar} notDistinctFrom: ${scalar} in: [${scalar}!] notIn: [${scalar}!] ${ordered} ${text} }`;\n}\n\nfunction listFilter(scalar: string): string {\n\treturn `input ${scalar}ListFilter { isNull: Boolean equalTo: [${scalar}] notEqualTo: [${scalar}] contains: [${scalar}] anyEqualTo: ${scalar} }`;\n}\n\n/** Relation fields on the row type. A relation named like a column is left out: the column wins. */\nfunction relationFields(table: MetaschemaTable, names: ReadonlySet<string>): string[] {\n\tconst relations = table.relations;\n\tconst columns = new Set(fieldsOf(table).map((field) => field.name));\n\tconst fields: string[] = [];\n\tconst add = (fieldName: string, definition: string) => {\n\t\tif (!columns.has(fieldName)) fields.push(definition);\n\t};\n\tfor (const relation of relations?.belongsTo ?? []) {\n\t\tif (relation?.fieldName && names.has(relation.references.name)) add(relation.fieldName, `${relation.fieldName}: ${relation.references.name}`);\n\t}\n\tfor (const relation of relations?.hasOne ?? []) {\n\t\tif (relation?.fieldName && names.has(relation.referencedBy.name)) add(relation.fieldName, `${relation.fieldName}: ${relation.referencedBy.name}`);\n\t}\n\tfor (const relation of relations?.hasMany ?? []) {\n\t\tif (relation?.fieldName && names.has(relation.referencedBy.name)) {\n\t\t\tadd(relation.fieldName, `${relation.fieldName}(first: Int): ${relation.referencedBy.name}Connection!`);\n\t\t}\n\t}\n\tfor (const relation of relations?.manyToMany ?? []) {\n\t\tif (relation?.fieldName && names.has(relation.rightTable.name)) {\n\t\t\tadd(relation.fieldName, `${relation.fieldName}(first: Int): ${relation.rightTable.name}Connection!`);\n\t\t}\n\t}\n\treturn fields;\n}\n\nfunction tableTypes(table: MetaschemaTable, names: ReadonlySet<string>): string[] {\n\tconst name = table.name;\n\tconst fields = fieldsOf(table);\n\tconst identity = getRowIdentityDefinition(table);\n\tconst primaryKey = identity.status === 'keyed' ? identity.fields.map((field) => field.fieldName) : [];\n\tconst record = toCamelCaseSingular(name);\n\tconst requiredOnCreate = (field: MetaschemaField) =>\n\t\t!primaryKey.includes(field.name) && Boolean(field.isNotNull) && !field.hasDefault;\n\tconst columns = fields.map((field) => `${field.name}: ${typeRef(field)}`).join(' ');\n\tconst keyFields = primaryKey\n\t\t.map((key) => fields.find((field) => field.name === key))\n\t\t.filter((field): field is MetaschemaField => Boolean(field))\n\t\t.map((field) => `${field.name}: ${typeRef(field)}!`)\n\t\t.join(' ');\n\n\tconst sdl = [\n\t\t`type ${name} { ${[columns, ...relationFields(table, names)].join(' ')} }`,\n\t\t`type ${name}Connection { nodes: [${name}]! totalCount: Int! pageInfo: PageInfo! }`,\n\t\t`input ${name}Filter { ${fields.map((field) => `${field.name}: ${operatorType(field)}`).join(' ')} and: [${name}Filter!] or: [${name}Filter!] not: ${name}Filter }`,\n\t\t`enum ${name}OrderBy { NATURAL ${primaryKey.length > 0 ? 'PRIMARY_KEY_ASC PRIMARY_KEY_DESC' : ''} ${fields.map((field) => `${constantCase(field.name)}_ASC ${constantCase(field.name)}_DESC`).join(' ')} }`,\n\t];\n\tif (table.query?.create) {\n\t\tsdl.push(\n\t\t\t`input ${name}Input { ${fields.map((field) => `${field.name}: ${typeRef(field)}${requiredOnCreate(field) ? '!' : ''}`).join(' ')} }`,\n\t\t\t`input Create${name}Input { clientMutationId: String ${record}: ${name}Input! }`,\n\t\t\t`type Create${name}Payload { clientMutationId: String ${record}: ${name} }`,\n\t\t);\n\t}\n\tif (table.query?.update && keyFields) {\n\t\tsdl.push(\n\t\t\t`input ${name}Patch { ${columns} }`,\n\t\t\t`input Update${name}Input { clientMutationId: String ${keyFields} ${record}Patch: ${name}Patch! }`,\n\t\t\t`type Update${name}Payload { clientMutationId: String ${record}: ${name} }`,\n\t\t);\n\t}\n\tif (table.query?.delete && keyFields) {\n\t\tsdl.push(\n\t\t\t`input Delete${name}Input { clientMutationId: String ${keyFields} }`,\n\t\t\t`type Delete${name}Payload { clientMutationId: String ${record}: ${name} }`,\n\t\t);\n\t}\n\treturn sdl;\n}\n\n/** Root query and mutation fields, named by `_meta.query`. */\nfunction rootFields(tables: readonly MetaschemaTable[]) {\n\tconst query: string[] = [];\n\tconst mutation: string[] = [];\n\tfor (const table of tables) {\n\t\tconst name = table.name;\n\t\tconst ops = table.query;\n\t\tif (ops?.all) {\n\t\t\tquery.push(`${ops.all}(first: Int, offset: Int, after: Cursor, where: ${name}Filter, orderBy: [${name}OrderBy!]): ${name}Connection`);\n\t\t}\n\t\tconst keyed = getRowIdentityDefinition(table).status === 'keyed';\n\t\tif (ops?.create) mutation.push(`${ops.create}(input: Create${name}Input!): Create${name}Payload`);\n\t\tif (ops?.update && keyed) mutation.push(`${ops.update}(input: Update${name}Input!): Update${name}Payload`);\n\t\tif (ops?.delete && keyed) mutation.push(`${ops.delete}(input: Delete${name}Input!): Delete${name}Payload`);\n\t}\n\treturn { query, mutation };\n}\n\n/** SDL for the tables, with every scalar, operator input and root field they need. */\nexport function buildMetaSchemaSdl(tables: readonly MetaschemaTable[]): string {\n\tconst names = new Set(tables.map((table) => table.name));\n\tconst fields = tables.flatMap(fieldsOf);\n\tconst scalars = new Set(fields.map((field) => field.type.gqlType));\n\tconst listScalars = new Set(fields.filter((field) => field.type.isArray).map((field) => field.type.gqlType));\n\tconst { query, mutation } = rootFields(tables);\n\n\treturn [\n\t\t'scalar Cursor',\n\t\t...[...scalars].filter((scalar) => !BUILT_IN_SCALARS.has(scalar) && scalar !== 'Cursor').map((scalar) => `scalar ${scalar}`),\n\t\t'type PageInfo { hasNextPage: Boolean! hasPreviousPage: Boolean! startCursor: Cursor endCursor: Cursor }',\n\t\t'input BooleanFilter { isNull: Boolean equalTo: Boolean notEqualTo: Boolean }',\n\t\t...[...scalars].filter((scalar) => scalar !== 'Boolean').map(scalarFilter),\n\t\t...[...listScalars].map(listFilter),\n\t\t...tables.flatMap((table) => tableTypes(table, names)),\n\t\t`type Query { ${query.join(' ') || 'noop: Boolean'} }`,\n\t\tmutation.length > 0 ? `type Mutation { ${mutation.join(' ')} }` : '',\n\t].filter(Boolean).join('\\n');\n}\n","// An in-memory GraphQL backend for tests and stories, driven by the table models.\n//\n// Every document runs through graphql-js against a real schema (a captured\n// introspection or SDL), so a document the schema rejects fails the test the\n// way the server would. Root fields are answered from in-memory rows: the\n// table models say which root field lists, creates, updates or deletes which\n// table, and how relation fields join rows. `_meta` is served from the given\n// response; schema introspection is answered by graphql-js itself.\nimport {\n\tdefaultFieldResolver,\n\tgraphql,\n\tisAbstractType,\n\tparse,\n\tprint,\n\tvalidate,\n\ttype DocumentNode,\n\ttype GraphQLFieldResolver,\n\ttype GraphQLSchema,\n} from 'graphql';\n\nimport {\n\tcreateError,\n\tcreateTableModelResolver,\n\tmetaTablesOf,\n\ttableKeyOf,\n\ttype ColumnModel,\n\ttype MetaQuery,\n\ttype RelationModel,\n\ttype TableModel,\n} from '@constructive-io/data';\n\nimport { withResponseErrors, type SheetsExecuteFn } from '../context/sheets-execute';\nimport { createMetaContractFixture } from './meta-contract-fixture';\nimport {\n\tcreateUploadService,\n\ttype ModelBackendUploadOptions,\n\ttype RecordedUpload,\n\ttype UploadService,\n} from './model-backend-uploads';\n\nexport type { ModelBackendUploadOptions, RecordedUpload } from './model-backend-uploads';\n\ntype Row = Record<string, unknown>;\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 ModelBackendOptions {\n\t/** The schema the backend serves. */\n\tschema: GraphQLSchema;\n\t/** The `_meta` response the backend serves. */\n\tmeta: MetaQuery;\n\t/** Rows per table (GraphQL type name). Changed in place by mutations. */\n\trows: Record<string, Row[]>;\n\t/** Called after every recorded mutation. */\n\tonMutation?: (mutation: RecordedMutation) => void;\n\t/** How the storage upload mutations behave. */\n\tuploads?: ModelBackendUploadOptions;\n\t/**\n\t * Rows a row rule hides from this writer. An update or a delete of such a row, like one of a\n\t * row that is gone, changes nothing and answers with an empty record and no error, as the\n\t * server does.\n\t */\n\twriteHidden?: (tableName: string, row: Row) => boolean;\n}\n\nexport interface ModelBackend {\n\texecute: SheetsExecuteFn;\n\t/** Every create, update, delete and upload mutation, in order. */\n\tmutations: RecordedMutation[];\n\t/** Every upload request with its input and outcome, in order. */\n\tuploads: RecordedUpload[];\n\t/** The rows, per table, as the backend holds them now. */\n\trows: Record<string, Row[]>;\n\t/** Mark a file row live, as the confirm step does after the PUT. */\n\tconfirmUpload(fileId: string): void;\n}\n\nconst ROW_MODEL = Symbol('row-model');\ntype StoredRow = Row & { [ROW_MODEL]?: TableModel };\n\nfunction documentSource(document: unknown): 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) return print(document as DocumentNode);\n\treturn String(document ?? '');\n}\n\nfunction sameValue(left: unknown, right: unknown): boolean {\n\tif (left === right) return true;\n\tif (left == null || right == null) return false;\n\treturn JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction compare(left: unknown, right: unknown): number {\n\tif (left == null && right == null) return 0;\n\tif (left == null) return -1;\n\tif (right == null) return 1;\n\tconst leftNumber = typeof left === 'number' ? left : Number(left);\n\tconst rightNumber = typeof right === 'number' ? right : Number(right);\n\tif (typeof left !== 'boolean' && Number.isFinite(leftNumber) && Number.isFinite(rightNumber) && String(left).trim() !== '' && String(right).trim() !== '') {\n\t\treturn leftNumber - rightNumber;\n\t}\n\treturn String(left).localeCompare(String(right));\n}\n\nfunction matchesOperator(value: unknown, operator: string, operand: unknown): boolean {\n\tconst text = (input: unknown) => String(input ?? '').toLowerCase();\n\tswitch (operator) {\n\t\tcase 'isNull': return operand ? value == null : value != null;\n\t\tcase 'equalTo': return sameValue(value, operand);\n\t\tcase 'notEqualTo': return !sameValue(value, operand);\n\t\tcase 'distinctFrom': return !sameValue(value, operand);\n\t\tcase 'notDistinctFrom': return sameValue(value, operand);\n\t\tcase 'in': return Array.isArray(operand) && operand.some((item) => sameValue(value, item));\n\t\tcase 'notIn': return Array.isArray(operand) && !operand.some((item) => sameValue(value, item));\n\t\tcase 'lessThan': return value != null && compare(value, operand) < 0;\n\t\tcase 'lessThanOrEqualTo': return value != null && compare(value, operand) <= 0;\n\t\tcase 'greaterThan': return value != null && compare(value, operand) > 0;\n\t\tcase 'greaterThanOrEqualTo': return value != null && compare(value, operand) >= 0;\n\t\tcase 'includes': return String(value ?? '').includes(String(operand));\n\t\tcase 'notIncludes': return !String(value ?? '').includes(String(operand));\n\t\tcase 'includesInsensitive': return text(value).includes(text(operand));\n\t\tcase 'notIncludesInsensitive': return !text(value).includes(text(operand));\n\t\tcase 'startsWith': return String(value ?? '').startsWith(String(operand));\n\t\tcase 'notStartsWith': return !String(value ?? '').startsWith(String(operand));\n\t\tcase 'startsWithInsensitive': return text(value).startsWith(text(operand));\n\t\tcase 'notStartsWithInsensitive': return !text(value).startsWith(text(operand));\n\t\tcase 'endsWith': return String(value ?? '').endsWith(String(operand));\n\t\tcase 'notEndsWith': return !String(value ?? '').endsWith(String(operand));\n\t\tcase 'endsWithInsensitive': return text(value).endsWith(text(operand));\n\t\tcase 'notEndsWithInsensitive': return !text(value).endsWith(text(operand));\n\t\tcase 'equalToInsensitive': return text(value) === text(operand);\n\t\tcase 'notEqualToInsensitive': return text(value) !== text(operand);\n\t\tcase 'inInsensitive': return Array.isArray(operand) && operand.some((item) => text(value) === text(item));\n\t\tcase 'notInInsensitive': return Array.isArray(operand) && !operand.some((item) => text(value) === text(item));\n\t\tcase 'anyEqualTo': return Array.isArray(value) && value.some((item) => sameValue(item, operand));\n\t\tcase 'anyNotEqualTo': return Array.isArray(value) && value.some((item) => !sameValue(item, operand));\n\t\tcase 'contains': return Array.isArray(value) && Array.isArray(operand) && operand.every((item) => value.some((entry) => sameValue(entry, item)));\n\t\tcase 'containedBy': return Array.isArray(value) && Array.isArray(operand) && value.every((entry) => operand.some((item) => sameValue(entry, item)));\n\t\tcase 'overlaps': return Array.isArray(value) && Array.isArray(operand) && value.some((entry) => operand.some((item) => sameValue(entry, item)));\n\t\tdefault:\n\t\t\tthrow createError.badRequest(`The mock backend does not support the \"${operator}\" filter.`);\n\t}\n}\n\n/** Rows linked to a row through one relation, with the model of the linked table. */\ntype RelatedRows = (model: TableModel, row: Row, relation: RelationModel) => { target: TableModel | null; rows: Row[] };\n\nfunction matchesFilter(\n\tmodel: TableModel,\n\trow: Row,\n\tfilter: Record<string, unknown> | null | undefined,\n\trelated: RelatedRows,\n): boolean {\n\tif (!filter) return true;\n\tconst matches = (target: TableModel, candidate: Row, condition: unknown) =>\n\t\tmatchesFilter(target, candidate, condition as Record<string, unknown>, related);\n\treturn Object.entries(filter).every(([key, condition]) => {\n\t\tif (condition === undefined || condition === null) return true;\n\t\tif (key === 'and') return (condition as Record<string, unknown>[]).every((part) => matches(model, row, part));\n\t\tif (key === 'or') return (condition as Record<string, unknown>[]).some((part) => matches(model, row, part));\n\t\tif (key === 'not') return !matches(model, row, condition);\n\t\tconst column = model.columns.find((candidate) => candidate.filter?.field === key);\n\t\tif (column) {\n\t\t\treturn Object.entries(condition as Record<string, unknown>).every(([operator, operand]) =>\n\t\t\t\tmatchesOperator(row[column.name], operator, operand),\n\t\t\t);\n\t\t}\n\t\tif (key === model.search?.unifiedSearchField) {\n\t\t\t// Combined search, approximated as a case-insensitive substring over the text columns.\n\t\t\tconst needle = String(condition).toLowerCase();\n\t\t\treturn model.columns.some(\n\t\t\t\t(candidate) => candidate.value.kind === 'text' && String(row[candidate.name] ?? '').toLowerCase().includes(needle),\n\t\t\t);\n\t\t}\n\t\tconst byExists = model.relations.find((relation) => relation.filter?.exists === key);\n\t\tif (byExists) return (related(model, row, byExists).rows.length > 0) === Boolean(condition);\n\t\tconst relation = model.relations.find((candidate) => candidate.filter?.field === key);\n\t\tconst filter = relation?.filter;\n\t\tif (!relation || !filter) throw createError.badRequest(`The mock backend does not filter by \"${key}\".`);\n\t\tconst { target, rows } = related(model, row, relation);\n\t\tconst nested = condition as Record<string, unknown>;\n\t\tif (!filter.many) {\n\t\t\tif (Object.keys(nested).length === 0) return true;\n\t\t\treturn Boolean(target && rows[0] && matches(target, rows[0], nested));\n\t\t}\n\t\tconst many = filter.many;\n\t\treturn Object.entries(nested).every(([quantifier, inner]) => {\n\t\t\tconst test = (candidate: Row) => Boolean(target) && matches(target!, candidate, inner);\n\t\t\tif (quantifier === many.some) return rows.some(test);\n\t\t\tif (quantifier === many.every) return rows.every(test);\n\t\t\tif (quantifier === many.none) return !rows.some(test);\n\t\t\tthrow createError.badRequest(`The mock backend does not support the \"${quantifier}\" relation filter.`);\n\t\t});\n\t});\n}\n\nfunction sortRows(model: TableModel, rows: Row[], orderBy: unknown): Row[] {\n\tconst values = Array.isArray(orderBy) ? (orderBy as string[]) : [];\n\tconst keys = values.flatMap((value) => {\n\t\tif (value === 'NATURAL') return [];\n\t\tif (value === 'PRIMARY_KEY_ASC' || value === 'PRIMARY_KEY_DESC') {\n\t\t\treturn model.primaryKey.map((field) => ({ field, desc: value === 'PRIMARY_KEY_DESC' }));\n\t\t}\n\t\tconst column = model.columns.find((candidate) => candidate.sort?.asc === value || candidate.sort?.desc === value);\n\t\tif (!column) throw createError.badRequest(`The mock backend does not sort by \"${value}\".`);\n\t\treturn [{ field: column.name, desc: column.sort?.desc === value }];\n\t});\n\tif (keys.length === 0) return rows;\n\treturn [...rows].sort((left, right) => {\n\t\tfor (const { field, desc } of keys) {\n\t\t\tconst order = compare(left[field], right[field]);\n\t\t\tif (order !== 0) return desc ? -order : order;\n\t\t}\n\t\treturn 0;\n\t});\n}\n\n/** A list page: `first`/`offset`/`after` over rows already filtered and sorted. Cursors are row positions. */\nfunction page(rows: Row[], args: Record<string, unknown>) {\n\tconst afterIndex = typeof args.after === 'string' && args.after !== '' ? Number(args.after) : Number.NaN;\n\tconst start = Number.isFinite(afterIndex) ? afterIndex : typeof args.offset === 'number' ? args.offset : 0;\n\tconst end = typeof args.first === 'number' ? start + args.first : rows.length;\n\tconst nodes = rows.slice(start, end);\n\treturn {\n\t\tnodes,\n\t\ttotalCount: rows.length,\n\t\tpageInfo: {\n\t\t\thasNextPage: end < rows.length,\n\t\t\thasPreviousPage: start > 0,\n\t\t\tstartCursor: nodes.length > 0 ? String(start) : null,\n\t\t\tendCursor: nodes.length > 0 ? String(start + nodes.length) : null,\n\t\t},\n\t};\n}\n\nfunction keyMatches(row: Row, key: Record<string, unknown>): boolean {\n\treturn Object.entries(key).every(([field, value]) => sameValue(row[field], value));\n}\n\nlet generatedIds = 0;\n\nfunction generatedKey(column: ColumnModel): unknown {\n\tgeneratedIds += 1;\n\tif (column.value.kind === 'uuid') return `00000000-0000-4000-8000-${String(generatedIds).padStart(12, '0')}`;\n\tif (column.value.kind === 'integer' || column.value.kind === 'bigint') {\n\t\treturn column.value.kind === 'bigint' ? String(100000 + generatedIds) : 100000 + generatedIds;\n\t}\n\treturn `mock-${generatedIds}`;\n}\n\n/**\n * The stored value for a written value. Geometry is written as GeoJSON and\n * read as an object with `geojson`; everything else is stored as written.\n */\nfunction storedValue(schema: GraphQLSchema, column: ColumnModel, written: unknown, previous: unknown): unknown {\n\tif (column.value.kind !== 'geometry' || written == null) return written;\n\tconst prior = previous && typeof previous === 'object' ? (previous as Row) : {};\n\tconst type = schema.getType(column.value.typeName);\n\tconst concrete = prior.__typename ?? (type && isAbstractType(type) ? schema.getPossibleTypes(type)[0]?.name : undefined);\n\treturn { ...prior, ...(concrete ? { __typename: concrete } : {}), geojson: written, srid: prior.srid ?? 0 };\n}\n\nexport function createModelBackend(options: ModelBackendOptions): ModelBackend {\n\tconst { schema, meta } = options;\n\tconst rows = options.rows;\n\tconst mutations: RecordedMutation[] = [];\n\tconst uploads: RecordedUpload[] = [];\n\tlet uploadService: UploadService | null = null;\n\tconst hasMetaTypes = Boolean(schema.getType('MetaTable'));\n\n\tconst introspect: SheetsExecuteFn = async <T>(document: unknown, variables?: Record<string, unknown>) => {\n\t\tconst result = await graphql({ schema, source: documentSource(document), variableValues: variables });\n\t\tif (result.errors?.length) throw createError.graphql(result.errors[0]!.message);\n\t\treturn result.data as T;\n\t};\n\n\tlet modelsPromise: Promise<TableModel[]> | null = null;\n\tconst models = () => {\n\t\tmodelsPromise ??= (async () => {\n\t\t\tconst resolver = createTableModelResolver(meta);\n\t\t\tconst resolved: TableModel[] = [];\n\t\t\tfor (const table of metaTablesOf(meta)) resolved.push(await resolver.resolve(introspect, tableKeyOf(table)));\n\t\t\treturn resolved;\n\t\t})();\n\t\treturn modelsPromise;\n\t};\n\n\tconst tableRows = (model: TableModel) => (rows[model.name] ??= []);\n\tconst stored = (model: TableModel, row: Row): StoredRow => Object.assign({ ...row }, { [ROW_MODEL]: model });\n\tconst record = (op: RecordedMutation['op'], model: TableModel, variables: Record<string, unknown> | undefined) => {\n\t\tconst mutation = { op, tableName: model.name, variables: variables ?? {}, at: Date.now() };\n\t\tmutations.push(mutation);\n\t\toptions.onMutation?.(mutation);\n\t};\n\n\tfunction relatedRowsIn(all: TableModel[]): RelatedRows {\n\t\treturn (_model, row, relation) => {\n\t\t\tconst target = all.find((candidate) => candidate.key === relation.targetKey) ?? null;\n\t\t\tif (target && relation.junction) {\n\t\t\t\tconst junction = all.find((candidate) => candidate.key === relation.junction!.tableKey);\n\t\t\t\tconst links = junction\n\t\t\t\t\t? tableRows(junction).filter((link) => relation.junction!.left.every((pair) => sameValue(link[pair.junction], row[pair.local])))\n\t\t\t\t\t: [];\n\t\t\t\treturn {\n\t\t\t\t\ttarget,\n\t\t\t\t\trows: tableRows(target).filter((candidate) =>\n\t\t\t\t\t\tlinks.some((link) => relation.junction!.right.every((pair) => sameValue(candidate[pair.remote], link[pair.junction]))),\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (target && relation.keys.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\ttarget,\n\t\t\t\t\trows: tableRows(target).filter((candidate) =>\n\t\t\t\t\t\trelation.keys.every((pair) => sameValue(candidate[pair.remote], row[pair.local])),\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { target, rows: [] };\n\t\t};\n\t}\n\n\tfunction relationValue(all: TableModel[], model: TableModel, row: Row, relation: RelationModel, args: Record<string, unknown>) {\n\t\tconst { target, rows: related } = relatedRowsIn(all)(model, row, relation);\n\t\tconst nodes = related.map((entry) => stored(target!, entry));\n\t\tif (relation.shape === 'object') return nodes[0] ?? null;\n\t\tconst limited = typeof args.first === 'number' ? nodes.slice(0, args.first) : nodes;\n\t\treturn relation.shape === 'list' ? limited : { nodes: limited, totalCount: nodes.length };\n\t}\n\n\tfunction rootResolvers(all: TableModel[], variables: Record<string, unknown> | undefined, files: UploadService) {\n\t\tconst related = relatedRowsIn(all);\n\t\tconst root: Record<string, (args: Record<string, unknown>) => unknown> = {\n\t\t\t...files.rootResolvers((filesModel) => record('upload', filesModel, variables)),\n\t\t};\n\t\tfor (const model of all) {\n\t\t\tconst ops = model.operations;\n\t\t\tif (ops.list) {\n\t\t\t\tconst list = ops.list;\n\t\t\t\troot[list.field] = (args) => {\n\t\t\t\t\tconst filtered = tableRows(model).filter((row) =>\n\t\t\t\t\t\tmatchesFilter(model, row, args[list.filter?.name ?? 'where'] as Record<string, unknown>, related),\n\t\t\t\t\t);\n\t\t\t\t\tconst sorted = sortRows(model, filtered, args[list.orderBy?.name ?? 'orderBy']);\n\t\t\t\t\tconst result = page(sorted, args);\n\t\t\t\t\tconst nodes = result.nodes.map((row) => stored(model, row));\n\t\t\t\t\treturn list.shape === 'list' ? nodes : { ...result, nodes };\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (ops.create) {\n\t\t\t\tconst create = ops.create;\n\t\t\t\troot[create.field] = (args) => {\n\t\t\t\t\trecord('create', model, variables);\n\t\t\t\t\tconst values = ((args[create.input.name] as Row)?.[create.recordField] ?? {}) as Row;\n\t\t\t\t\tfiles.assertFileRefsLive(model, values);\n\t\t\t\t\tconst row: Row = {};\n\t\t\t\t\tfor (const column of model.columns) {\n\t\t\t\t\t\tif (Object.prototype.hasOwnProperty.call(values, column.name)) {\n\t\t\t\t\t\t\trow[column.name] = storedValue(schema, column, values[column.name], undefined);\n\t\t\t\t\t\t} else if (column.isPrimaryKey) {\n\t\t\t\t\t\t\trow[column.name] = generatedKey(column);\n\t\t\t\t\t\t} else if (!column.hasDefault) {\n\t\t\t\t\t\t\trow[column.name] = null;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Left absent: the server applies the column's real default, which neither `_meta`\n\t\t\t\t\t\t\t// nor the schema describes, so the mock does not invent one. Reading it back as a\n\t\t\t\t\t\t\t// non-null field fails, as a null would.\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ttableRows(model).push(row);\n\t\t\t\t\treturn { clientMutationId: null, [create.payloadField]: stored(model, row) };\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (ops.update) {\n\t\t\t\tconst update = ops.update;\n\t\t\t\troot[update.field] = (args) => {\n\t\t\t\t\trecord('update', model, variables);\n\t\t\t\t\tconst input = (args[update.input.name] ?? {}) as Row;\n\t\t\t\t\tconst key = Object.fromEntries(update.keyArgs.map((field) => [field, input[field]]));\n\t\t\t\t\tconst row = tableRows(model).find((candidate) => keyMatches(candidate, key));\n\t\t\t\t\t// No row matched (gone, or hidden by a row rule): nothing changes, no error.\n\t\t\t\t\tif (!row || options.writeHidden?.(model.name, row)) return { clientMutationId: null, [update.payloadField]: null };\n\t\t\t\t\tconst patch = (input[update.patchField] ?? {}) as Row;\n\t\t\t\t\tfiles.assertFileRefsLive(model, patch);\n\t\t\t\t\tfor (const [field, value] of Object.entries(patch)) {\n\t\t\t\t\t\tconst column = model.columns.find((candidate) => candidate.name === field);\n\t\t\t\t\t\trow[field] = column ? storedValue(schema, column, value, row[field]) : value;\n\t\t\t\t\t}\n\t\t\t\t\treturn { clientMutationId: null, [update.payloadField]: stored(model, row) };\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (ops.delete) {\n\t\t\t\tconst remove = ops.delete;\n\t\t\t\troot[remove.field] = (args) => {\n\t\t\t\t\trecord('delete', model, variables);\n\t\t\t\t\tconst input = (args[remove.input.name] ?? {}) as Row;\n\t\t\t\t\tconst key = Object.fromEntries(remove.keyArgs.map((field) => [field, input[field]]));\n\t\t\t\t\tconst list = tableRows(model);\n\t\t\t\t\tconst found = list.findIndex((candidate) => keyMatches(candidate, key));\n\t\t\t\t\tconst index = found !== -1 && options.writeHidden?.(model.name, list[found]!) ? -1 : found;\n\t\t\t\t\tconst [row] = index === -1 ? [] : list.splice(index, 1);\n\t\t\t\t\treturn { clientMutationId: null, ...(remove.payloadField ? { [remove.payloadField]: row ? stored(model, row) : null } : {}) };\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn root;\n\t}\n\n\tconst execute: SheetsExecuteFn = async <T>(document: unknown, variables?: Record<string, unknown>): Promise<T> => {\n\t\tconst source = documentSource(document);\n\t\tif (source.includes('ConstructiveMetaContract') && !hasMetaTypes) return createMetaContractFixture() as T;\n\t\tif (/query ConstructiveMeta\\b/.test(source)) {\n\t\t\t// A server with the Meta types rejects a `_meta` query that asks for a field it lacks.\n\t\t\tconst errors = hasMetaTypes ? validate(schema, parse(source)) : [];\n\t\t\tif (errors.length > 0) throw createError.graphql(errors[0]!.message);\n\t\t\treturn meta as T;\n\t\t}\n\t\tif (/\\b__(schema|type)\\b/.test(source)) return introspect<T>(source, variables);\n\n\t\tconst all = await models();\n\t\tconst files = (uploadService ??= createUploadService(all, tableRows, options.uploads, uploads));\n\t\tconst fieldResolver: GraphQLFieldResolver<unknown, unknown> = (parent, args, context, info) => {\n\t\t\tconst model = (parent as StoredRow | null)?.[ROW_MODEL];\n\t\t\tconst computed = model ? files.resolveField(model, parent as Row, info.fieldName) : null;\n\t\t\tif (computed) return computed.value;\n\t\t\tconst relation = model?.relations.find((candidate) => candidate.fieldName === info.fieldName);\n\t\t\tif (model && relation) return relationValue(all, model, parent as Row, relation, args);\n\t\t\treturn defaultFieldResolver(parent, args, context, info);\n\t\t};\n\t\tconst result = await graphql({\n\t\t\tschema,\n\t\t\tsource,\n\t\t\tvariableValues: variables,\n\t\t\trootValue: rootResolvers(all, variables, files),\n\t\t\tfieldResolver,\n\t\t});\n\t\t// Like the server: field errors come with the data that could be served, and keep their code.\n\t\tif (result.errors?.length) {\n\t\t\tconst first = result.errors[0]!;\n\t\t\tconst code = first.extensions?.code;\n\t\t\tthrow withResponseErrors(\n\t\t\t\tcreateError.graphql(first.message, typeof code === 'string' ? code : undefined),\n\t\t\t\tresult.data,\n\t\t\t\tresult.errors,\n\t\t\t);\n\t\t}\n\t\treturn result.data as T;\n\t};\n\n\tconst confirmUpload = (fileId: string) => {\n\t\tif (uploadService) {\n\t\t\tuploadService.confirm(fileId);\n\t\t\treturn;\n\t\t}\n\t\tfor (const list of Object.values(rows)) {\n\t\t\tfor (const row of list) if (row.id === fileId && 'status' in row) row.status = 'uploaded';\n\t\t}\n\t};\n\n\treturn { execute, mutations, uploads, rows, confirmUpload };\n}\n","import { META_CONTRACT_REQUIREMENTS, type MetaContractIntrospectionQuery } from '@constructive-io/data';\n\nconst fields = (names: readonly string[]) => names.map((name) => ({ name }));\n\n/** Current `_meta` type signature for tests using an injected execute seam. */\nexport function createMetaContractFixture(): MetaContractIntrospectionQuery {\n\treturn Object.fromEntries(\n\t\tObject.entries(META_CONTRACT_REQUIREMENTS).map(([alias, requirement]) => [\n\t\t\talias,\n\t\t\t{ name: requirement.typeName, fields: fields(requirement.fields) },\n\t\t]),\n\t) as MetaContractIntrospectionQuery;\n}\n","// Storage uploads for the model backend.\n//\n// Serves the upload mutations a files table's model names (`storage.upload`),\n// with the server's rules: the bucket is the named one or the public/private\n// default, the content hash must be a SHA-256 hex, the bucket's MIME types and\n// size limit apply, a live row at the same key is a dedup hit, and a new upload\n// creates a files row that list reads see. A write that references a file row\n// that is not live fails like the server's file-reference guard: the message is\n// the bare code `FILE_REF_FILE_NOT_LIVE`, and `extensions` carry `class: 'public'`\n// and `context: { field, file_id, status }`, where `status` is `requested` (the\n// confirm job has not run yet) or `rejected` (it refused the bytes; the row never\n// becomes live). The PUT to the upload URL is not served: tests mock `fetch`/XHR\n// and call `confirmUpload`.\nimport { GraphQLError } from 'graphql';\n\nimport type { TableModel } from '@constructive-io/data';\n\ntype Row = Record<string, unknown>;\n\nexport interface ModelBackendUploadOptions {\n\t/** Answer every upload as already stored: no upload URL, the existing file row or a new live one. */\n\tdeduplicated?: boolean;\n\t/** A new file row stays not live for this many writes that reference it; each of those writes fails. */\n\tnotLiveForWrites?: number;\n\t/**\n\t * The confirm job rejects this upload (its bytes did not match): the new files row is\n\t * `rejected`, `confirmUpload` leaves it so, and every write that references it fails.\n\t */\n\trejectUpload?: (input: Readonly<Row>) => boolean;\n\t/** Fail an upload request: return a message (and optional code), or null to let it through. */\n\tfailure?: (input: Readonly<Row>) => { message: string; code?: string } | null;\n\t/** Address of public buckets, for the projection `url`. Default `https://cdn.mock`. */\n\tpublicUrlPrefix?: string;\n\t/** Address of upload URLs. Default `https://storage.mock/upload`. */\n\tuploadUrlPrefix?: string;\n}\n\nexport interface RecordedUpload {\n\t/** Root mutation field that was called. */\n\tmutation: string;\n\t/** GraphQL type name of the files table. */\n\tfilesTable: string;\n\t/** The per-file input, after defaults from a bulk input. */\n\tinput: Readonly<Row>;\n\toutcome: 'requested' | 'deduplicated' | 'failed';\n\tfileId: string | null;\n\terror: string | null;\n\tat: number;\n}\n\nexport interface UploadService {\n\t/** Every upload request, in order. */\n\treadonly uploads: RecordedUpload[];\n\t/** Root resolvers for the upload mutations. `onRequest` records the mutation. */\n\trootResolvers(onRequest: (files: TableModel) => void): Record<string, (args: Row) => unknown>;\n\t/** Throw the server's error when a write references a file row that is not live. */\n\tassertFileRefsLive(model: TableModel, values: Readonly<Row>): void;\n\t/** The value of a computed files field (the download URL), or null when the field is not one. */\n\tresolveField(model: TableModel, row: Row, fieldName: string): { value: unknown } | null;\n\t/** Mark a file row live, as the confirm step does after the PUT. */\n\tconfirm(fileId: string): void;\n}\n\ninterface StorageSurface {\n\tfiles: TableModel;\n\tbuckets: TableModel | null;\n\t/** Files field that points at the bucket, and the bucket field it references. */\n\tbucketLink: { local: string; remote: string } | null;\n\tmutation: string;\n\tbulkMutation: string | null;\n\tdownloadUrlField: string | null;\n}\n\nconst LIVE_STATUSES = new Set(['uploaded', 'processed']);\nconst UPLOAD_URL_LIFETIME_MS = 15 * 60 * 1000;\n\nfunction fail(message: string, code: string, extensions: Record<string, unknown> = {}): GraphQLError {\n\treturn new GraphQLError(message, { extensions: { code, ...extensions } });\n}\n\nfunction hexToBase64(hex: string): string {\n\tlet binary = '';\n\tfor (let index = 0; index < hex.length; index += 2) binary += String.fromCharCode(Number.parseInt(hex.slice(index, index + 2), 16));\n\treturn btoa(binary);\n}\n\nfunction mimeAllowed(allowed: unknown, contentType: string): boolean {\n\tif (!Array.isArray(allowed) || allowed.length === 0) return true;\n\treturn allowed.some((pattern) => {\n\t\tif (typeof pattern !== 'string') return false;\n\t\tif (pattern === '*/*') return true;\n\t\tif (pattern.endsWith('/*')) return contentType.startsWith(pattern.slice(0, -1));\n\t\treturn contentType === pattern;\n\t});\n}\n\nlet fileIds = 0;\n\nfunction nextFileId(): string {\n\tfileIds += 1;\n\treturn `00000000-0000-4000-9000-${String(fileIds).padStart(12, '0')}`;\n}\n\nfunction surfacesOf(models: readonly TableModel[]): StorageSurface[] {\n\treturn models.flatMap((files) => {\n\t\tconst storage = files.storage;\n\t\tif (storage?.role !== 'files' || !storage.upload?.mutation) return [];\n\t\tconst buckets = models.find((candidate) => candidate.name === storage.bucketsType) ?? null;\n\t\tconst link = files.relations.find(\n\t\t\t(relation) => relation.kind === 'belongsTo' && relation.targetName === storage.bucketsType && relation.keys.length === 1,\n\t\t);\n\t\treturn [{\n\t\t\tfiles,\n\t\t\tbuckets,\n\t\t\tbucketLink: link?.keys[0] ?? null,\n\t\t\tmutation: storage.upload.mutation,\n\t\t\tbulkMutation: storage.upload.bulkMutation,\n\t\t\tdownloadUrlField: storage.downloadUrlField,\n\t\t}];\n\t});\n}\n\nexport function createUploadService(\n\tmodels: readonly TableModel[],\n\ttableRows: (model: TableModel) => Row[],\n\toptions: ModelBackendUploadOptions = {},\n\tuploads: RecordedUpload[] = [],\n): UploadService {\n\tconst surfaces = surfacesOf(models);\n\tconst refusalsLeft = new Map<string, number>();\n\tconst publicUrlPrefix = (options.publicUrlPrefix ?? 'https://cdn.mock').replace(/\\/$/, '');\n\tconst uploadUrlPrefix = (options.uploadUrlPrefix ?? 'https://storage.mock/upload').replace(/\\/$/, '');\n\n\tconst fileRow = (fileId: string): { surface: StorageSurface; row: Row } | null => {\n\t\tfor (const surface of surfaces) {\n\t\t\tconst row = tableRows(surface.files).find((candidate) => candidate.id === fileId);\n\t\t\tif (row) return { surface, row };\n\t\t}\n\t\treturn null;\n\t};\n\n\t/** Set a files field only when the files table has it. */\n\tconst assign = (surface: StorageSurface, row: Row, field: string, value: unknown) => {\n\t\tif (surface.files.columns.some((column) => column.name === field)) row[field] = value;\n\t};\n\n\tfunction resolveBucket(surface: StorageSurface, input: Readonly<Row>): Row {\n\t\tconst buckets = surface.buckets ? tableRows(surface.buckets) : [];\n\t\tconst bucket = typeof input.bucketKey === 'string'\n\t\t\t? buckets.find((candidate) => candidate.key === input.bucketKey)\n\t\t\t: buckets.find((candidate) => (candidate.isPublic === true) === (input.isPublic === true));\n\t\tif (!bucket) throw fail('BUCKET_NOT_FOUND', 'BUCKET_NOT_FOUND');\n\t\treturn bucket;\n\t}\n\n\tfunction projection(fileId: string, key: string, bucket: Row, input: Readonly<Row>): Row {\n\t\treturn {\n\t\t\tid: fileId,\n\t\t\tkey,\n\t\t\tbucket_id: bucket.id,\n\t\t\tmime: input.contentType,\n\t\t\tsize: input.size,\n\t\t\t...(typeof input.filename === 'string' && input.filename ? { filename: input.filename } : {}),\n\t\t\t...(bucket.isPublic === true ? { url: `${publicUrlPrefix}/${key}` } : {}),\n\t\t};\n\t}\n\n\tfunction uploadOne(surface: StorageSurface, mutation: string, input: Readonly<Row>): Row {\n\t\tconst entry: RecordedUpload = {\n\t\t\tmutation, filesTable: surface.files.name, input, outcome: 'failed', fileId: null, error: null, at: Date.now(),\n\t\t};\n\t\tuploads.push(entry);\n\t\ttry {\n\t\t\tconst refused = options.failure?.(input);\n\t\t\tif (refused) throw fail(refused.message, refused.code ?? 'UPLOAD_FAILED');\n\t\t\tconst contentHash = String(input.contentHash ?? '');\n\t\t\tconst contentType = String(input.contentType ?? '');\n\t\t\tif (!/^[0-9a-f]{64}$/i.test(contentHash)) {\n\t\t\t\tthrow fail('INVALID_CONTENT_HASH_FORMAT: must be a 64-char lowercase hex SHA-256', 'INVALID_CONTENT_HASH_FORMAT');\n\t\t\t}\n\t\t\tconst bucket = resolveBucket(surface, input);\n\t\t\tif (!mimeAllowed(bucket.allowedMimeTypes, contentType)) {\n\t\t\t\tthrow fail(`CONTENT_TYPE_NOT_ALLOWED: ${contentType} not in bucket allowed types`, 'CONTENT_TYPE_NOT_ALLOWED');\n\t\t\t}\n\t\t\tconst maxFileSize = bucket.maxFileSize == null ? null : Number(bucket.maxFileSize);\n\t\t\tif (maxFileSize && Number(input.size) > maxFileSize) {\n\t\t\t\tthrow fail(`FILE_TOO_LARGE: exceeds bucket max of ${maxFileSize} bytes`, 'FILE_TOO_LARGE');\n\t\t\t}\n\n\t\t\tconst key = typeof input.key === 'string' && input.key ? input.key : contentHash;\n\t\t\tconst rows = tableRows(surface.files);\n\t\t\tconst link = surface.bucketLink;\n\t\t\tconst inBucket = (row: Row) => !link || row[link.local] === bucket[link.remote];\n\t\t\tconst existing = rows.find((row) => row.key === key && inBucket(row));\n\t\t\tconst live = existing && LIVE_STATUSES.has(String(existing.status));\n\n\t\t\tif (live || options.deduplicated) {\n\t\t\t\tconst fileId = existing && live ? String(existing.id) : createRow(surface, bucket, key, input, 'uploaded');\n\t\t\t\tObject.assign(entry, { outcome: 'deduplicated', fileId });\n\t\t\t\treturn {\n\t\t\t\t\tuploadUrl: null, uploadHeaders: null, fileId, key, deduplicated: true, expiresAt: null,\n\t\t\t\t\tfile: projection(fileId, key, bucket, input),\n\t\t\t\t};\n\t\t\t}\n\t\t\t// A row whose bytes never landed is dropped, and the upload starts again.\n\t\t\tif (existing) rows.splice(rows.indexOf(existing), 1);\n\t\t\tconst rejected = options.rejectUpload?.(input) ?? false;\n\t\t\tconst refusals = rejected ? 0 : options.notLiveForWrites ?? 0;\n\t\t\tconst fileId = createRow(surface, bucket, key, input, rejected ? 'rejected' : refusals > 0 ? 'requested' : 'uploaded');\n\t\t\tif (refusals > 0) refusalsLeft.set(fileId, refusals);\n\t\t\tObject.assign(entry, { outcome: 'requested', fileId });\n\t\t\treturn {\n\t\t\t\tuploadUrl: `${uploadUrlPrefix}/${fileId}`,\n\t\t\t\tuploadHeaders: {\n\t\t\t\t\t'Content-Type': contentType,\n\t\t\t\t\t'x-amz-checksum-sha256': hexToBase64(contentHash),\n\t\t\t\t\t'x-amz-meta-upload-id': fileId,\n\t\t\t\t},\n\t\t\t\tfileId,\n\t\t\t\tkey,\n\t\t\t\tdeduplicated: false,\n\t\t\t\texpiresAt: new Date(Date.now() + UPLOAD_URL_LIFETIME_MS).toISOString(),\n\t\t\t\tfile: projection(fileId, key, bucket, input),\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tentry.error = error instanceof Error ? error.message : String(error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tfunction createRow(surface: StorageSurface, bucket: Row, key: string, input: Readonly<Row>, status: string): string {\n\t\tconst fileId = nextFileId();\n\t\tconst now = new Date().toISOString();\n\t\tconst row: Row = {};\n\t\tfor (const column of surface.files.columns) row[column.name] = null;\n\t\tassign(surface, row, 'id', fileId);\n\t\tif (surface.bucketLink) row[surface.bucketLink.local] = bucket[surface.bucketLink.remote];\n\t\tassign(surface, row, 'key', key);\n\t\tassign(surface, row, 'contentHash', input.contentHash);\n\t\tassign(surface, row, 'mimeType', input.contentType);\n\t\tassign(surface, row, 'size', String(input.size));\n\t\tassign(surface, row, 'filename', input.filename ?? null);\n\t\tassign(surface, row, 'isPublic', bucket.isPublic === true);\n\t\tassign(surface, row, 'status', status);\n\t\tassign(surface, row, 'createdAt', now);\n\t\tassign(surface, row, 'updatedAt', now);\n\t\ttableRows(surface.files).push(row);\n\t\treturn fileId;\n\t}\n\n\treturn {\n\t\tuploads,\n\t\trootResolvers(onRequest) {\n\t\t\tconst root: Record<string, (args: Row) => unknown> = {};\n\t\t\tfor (const surface of surfaces) {\n\t\t\t\troot[surface.mutation] = (args) => {\n\t\t\t\t\tonRequest(surface.files);\n\t\t\t\t\treturn uploadOne(surface, surface.mutation, (args.input ?? {}) as Row);\n\t\t\t\t};\n\t\t\t\tif (surface.bulkMutation) {\n\t\t\t\t\tconst bulk = surface.bulkMutation;\n\t\t\t\t\troot[bulk] = (args) => {\n\t\t\t\t\t\tonRequest(surface.files);\n\t\t\t\t\t\tconst { files = [], ...shared } = (args.input ?? {}) as Row & { files?: Row[] };\n\t\t\t\t\t\treturn { files: files.map((file) => uploadOne(surface, bulk, { ...shared, ...file })) };\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn root;\n\t\t},\n\t\tassertFileRefsLive(model, values) {\n\t\t\tfor (const column of model.columns) {\n\t\t\t\tif (!column.value.file || column.value.file.kind === 'attachment') continue;\n\t\t\t\tconst value = values[column.name];\n\t\t\t\tconst references = (Array.isArray(value) ? value : [value]).filter(\n\t\t\t\t\t(entry): entry is { id: string } => Boolean(entry) && typeof (entry as Row).id === 'string',\n\t\t\t\t);\n\t\t\t\tfor (const { id } of references) {\n\t\t\t\t\tconst found = fileRow(id);\n\t\t\t\t\tif (!found || LIVE_STATUSES.has(String(found.row.status))) continue;\n\t\t\t\t\tconst status = String(found.row.status);\n\t\t\t\t\tconst left = refusalsLeft.get(id) ?? 0;\n\t\t\t\t\tif (left > 0) {\n\t\t\t\t\t\trefusalsLeft.set(id, left - 1);\n\t\t\t\t\t\t// The confirm step catches up after the configured number of refused writes.\n\t\t\t\t\t\tif (left === 1) found.row.status = 'uploaded';\n\t\t\t\t\t}\n\t\t\t\t\tthrow fail('FILE_REF_FILE_NOT_LIVE', 'FILE_REF_FILE_NOT_LIVE', {\n\t\t\t\t\t\tclass: 'public',\n\t\t\t\t\t\tcontext: { field: column.name, file_id: id, status },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tresolveField(model, row, fieldName) {\n\t\t\tconst surface = surfaces.find((candidate) => candidate.files.key === model.key);\n\t\t\tif (!surface || fieldName !== surface.downloadUrlField) return null;\n\t\t\treturn { value: LIVE_STATUSES.has(String(row.status)) ? `https://storage.mock/download/${String(row.key)}` : null };\n\t\t},\n\t\tconfirm(fileId) {\n\t\t\tconst found = fileRow(fileId);\n\t\t\t// A rejected upload stays rejected: the job refused its bytes.\n\t\t\tif (found && found.row.status !== 'rejected') found.row.status = 'uploaded';\n\t\t\trefusalsLeft.delete(fileId);\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACYA,IAAAA,gBAAwB;AACxB,IAAAC,kBAA4B;AAC5B,IAAAC,sBAA4B;AAE5B,IAAAC,eAKO;;;ACrBP,IAAAC,gBAAkD;AAClD,yBAAiD;AACjD,IAAAC,kBAA2D;;;ACF3D,mBAA0C;AAyGnC,IAAM,oBAAgB,4BAAyC,IAAI;;;ACxG1E,IAAAC,kBAAsB;AAEtB,IAAAC,eAA6G;;;ACiB7G,IAAAC,eAA4B;;;ACT5B,qBAAsC;AAEtC,kBAA4B;AAwD5B,IAAI,kBAAkB,oBAAI,QAAoE;AAO9F,eAAe,4BAA4B,UAAkB,SAAwD;AACpH,MAAI,YAAY,gBAAgB,IAAI,OAAO;AAC3C,MAAI,CAAC,WAAW;AACf,gBAAY,oBAAI,IAAI;AACpB,oBAAgB,IAAI,SAAS,SAAS;AAAA,EACvC;AACA,QAAM,SAAS,UAAU,IAAI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MACD;AAAA,MAEC;AAAA;AAAA,EACF;AAEF;AAMO,IAAM,eAA0B;AAAA,EACtC,MAAM;AAAA,EACN,QAAQ;AAAA,IACP,EAAE,MAAM,MAAM,SAAS,QAAQ,QAAQ,OAAO;AAAA,IAC9C,EAAE,MAAM,QAAQ,SAAS,UAAU,QAAQ,OAAO;AAAA,IAClD,EAAE,MAAM,SAAS,SAAS,UAAU,QAAQ,OAAO;AAAA,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_zustand","import_graphql","import_data","import_data","query","data","url","idScalar","import_data","import_react","active","useZustandStore","store","import_data","fields","import_graphql","import_data","import_data","import_graphql","hex","fileId","relation","filter","import_jsx_runtime"]}