@constructive-io/sheets 0.13.1 → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -1
- package/dist/advanced.cjs +554 -716
- package/dist/advanced.cjs.map +1 -1
- package/dist/advanced.d.cts +2 -2
- package/dist/advanced.d.ts +2 -2
- package/dist/advanced.js +4 -4
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.js +2 -2
- package/dist/{chunk-PZL2BCWF.js → chunk-6Y7CZ5VS.js} +2 -2
- package/dist/chunk-6Y7CZ5VS.js.map +1 -0
- package/dist/{chunk-AYMXT3ME.js → chunk-BGL6EBTE.js} +108 -202
- package/dist/chunk-BGL6EBTE.js.map +1 -0
- package/dist/{chunk-MXVNIKES.js → chunk-BYAYBXVB.js} +2 -2
- package/dist/{chunk-5QPNOKMA.js → chunk-ER3FIDK7.js} +444 -458
- package/dist/chunk-ER3FIDK7.js.map +1 -0
- package/dist/chunk-GZM2CSTR.js +279 -0
- package/dist/chunk-GZM2CSTR.js.map +1 -0
- package/dist/{chunk-H5HR5HUJ.js → chunk-YJZFHL2D.js} +1 -1
- package/dist/chunk-YJZFHL2D.js.map +1 -0
- package/dist/{date-editor-ZFNDKYBD.js → date-editor-G26WKILO.js} +2 -2
- package/dist/{grid-cell-types-Pbe2m2tE.d.ts → grid-cell-types-C2-ocDS7.d.cts} +45 -5
- package/dist/{grid-cell-types-Pbe2m2tE.d.cts → grid-cell-types-C2-ocDS7.d.ts} +45 -5
- package/dist/index.cjs +782 -637
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +106 -112
- package/dist/index.d.ts +106 -112
- package/dist/index.js +234 -134
- package/dist/index.js.map +1 -1
- package/dist/{sheets-context-Cu3Ec_ca.d.ts → sheets-context-CHUVJCff.d.ts} +32 -31
- package/dist/{sheets-context-CY1RmDKL.d.cts → sheets-context-C_MkTxXm.d.cts} +32 -31
- package/dist/testing.cjs +121 -87
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +2 -2
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +16 -4
- package/dist/testing.js.map +1 -1
- package/package.json +5 -4
- package/dist/chunk-5QPNOKMA.js.map +0 -1
- package/dist/chunk-AYMXT3ME.js.map +0 -1
- package/dist/chunk-H5HR5HUJ.js.map +0 -1
- package/dist/chunk-PZL2BCWF.js.map +0 -1
- package/dist/chunk-ZKANUG3F.js +0 -123
- package/dist/chunk-ZKANUG3F.js.map +0 -1
- /package/dist/{chunk-MXVNIKES.js.map → chunk-BYAYBXVB.js.map} +0 -0
- /package/dist/{date-editor-ZFNDKYBD.js.map → date-editor-G26WKILO.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context/sheets-upload-presigned.ts","../src/context/sheets-execute.ts","../src/hooks/query-keys.ts"],"sourcesContent":["/**\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. Resolve the stable public `downloadUrl` for the fileId\n *\n * `confirmUpload` is intentionally skipped: the backend plugin creates the file\n * row inside the upload op, so `downloadUrl` resolves immediately.\n *\n * The upload op is discovered via runtime introspection, matched by FIELD/TYPE\n * SHAPE (never a hardcoded name): a root mutation `upload<Type>File(input: {...})`\n * whose input + payload carry the upload shape.\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 { SheetsExecuteFn } 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\t/** Query field used to resolve the stable 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\t/**\n\t * Delete-by-id mutation for the uploaded file type, e.g. 'deleteAppFile', when the\n\t * schema grants one. Used to remove the row the upload op created when its PUT fails.\n\t */\n\tdeleteFieldName?: string;\n\t/** The delete input object type name, e.g. 'DeleteAppFileInput'. */\n\tdeleteInputTypeName?: string;\n}\n\ninterface UploadPayload {\n\tuploadUrl: string | null;\n\tfileId: string;\n\tkey: string;\n\tdeduplicated: boolean;\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\nconst capabilityCache = new Map<string, Promise<UploadCapability>>();\n\n/** Test-only: clear the per-endpoint capability cache between cases. */\nexport function __resetUploadCapabilityCache(): void {\n\tcapabilityCache.clear();\n}\n\n/**\n * Discover the upload op + downloadUrl-by-id field for an endpoint, by shape.\n * Cached per `endpoint`; concurrent uploads share one in-flight introspection.\n */\nexport function discoverUploadCapability(endpoint: string, execute: SheetsExecuteFn): Promise<UploadCapability> {\n\tconst cached = capabilityCache.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 resolveUploadCapability(schema);\n\t})();\n\n\t// Don't cache a rejected discovery — let the next attempt retry.\n\tpromise.catch(() => capabilityCache.delete(endpoint));\n\tcapabilityCache.set(endpoint, promise);\n\treturn promise;\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, never by a literal name.\n */\nexport function resolveUploadCapability(schema: IntrospectionSchema): UploadCapability {\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', '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: Pick<UploadCapability, 'uploadFieldName' | 'inputTypeName'> | 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\tinputHasFields(inputTypeName, INPUT_FIELDS) &&\n\t\t\tobjectHasFields(payloadTypeName, PAYLOAD_FIELDS)\n\t\t) {\n\t\t\tupload = { uploadFieldName: field.name, inputTypeName: inputTypeName as string };\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!upload) {\n\t\tthrow createError.badRequest('Uploads are not enabled for this endpoint.');\n\t}\n\n\t// --- File object type + by-id field for downloadUrl ---\n\tconst downloadById = resolveDownloadByIdField(schema, typeByName, queryType, upload.uploadFieldName);\n\n\t// --- Delete-by-id for the uploaded file type (optional) ---\n\t// A Mutation field whose `input` carries only `id` (+ clientMutationId) and whose\n\t// payload exposes the file type. The update mutation also takes `id` but carries a\n\t// patch field, so it never matches.\n\tconst uploadedTypeName = upload.uploadFieldName.replace(/^upload/, '');\n\tconst fileTypeName = typeByName.has(uploadedTypeName) ? uploadedTypeName : downloadById.fileTypeName;\n\tlet remove: Pick<UploadCapability, 'deleteFieldName' | 'deleteInputTypeName'> = {};\n\tfor (const field of mutationType?.fields ?? []) {\n\t\tconst inputArg = field.args.find((a) => a.name === 'input');\n\t\tconst inputTypeName = namedTypeName(inputArg?.type);\n\t\tconst inputFields = inputTypeName ? typeByName.get(inputTypeName)?.inputFields : null;\n\t\tif (!inputTypeName || !inputFields?.some((f) => f.name === PK_FIELD_NAME)) continue;\n\t\tif (!inputFields.every((f) => f.name === PK_FIELD_NAME || f.name === 'clientMutationId')) continue;\n\t\tconst payload = typeByName.get(namedTypeName(field.type) ?? '');\n\t\tif (payload?.fields?.some((f) => namedTypeName(f.type) === fileTypeName)) {\n\t\t\tremove = { deleteFieldName: field.name, deleteInputTypeName: inputTypeName };\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn {\n\t\t...upload,\n\t\t...downloadById,\n\t\t...remove,\n\t};\n}\n\n/**\n * Best-effort removal of the row the upload op created, for a PUT that failed.\n * Without it, a module that never confirms uploads lists a file whose bytes were\n * never stored. Failures are swallowed: the caller reports the original PUT error.\n */\nexport async function deleteUploadedFileRow(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\n\tfileId: string,\n): Promise<void> {\n\tif (!cap.deleteFieldName || !cap.deleteInputTypeName) return;\n\tconst mutation = `\n\t\tmutation SheetsUploadCleanup($input: ${cap.deleteInputTypeName}!) {\n\t\t\t${cap.deleteFieldName}(input: $input) { __typename }\n\t\t}\n\t`.trim();\n\ttry {\n\t\tawait execute(mutation, { input: { [PK_FIELD_NAME]: fileId } });\n\t} catch {\n\t\t// Best effort: the caller rethrows the PUT error, which is the one to report.\n\t}\n}\n\ntype DownloadByIdResult = Omit<UploadCapability, 'uploadFieldName' | 'inputTypeName'>;\n\nfunction resolveDownloadByIdField(\n\tschema: IntrospectionSchema,\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tuploadFieldName: string,\n): DownloadByIdResult {\n\t// The file object type carries a `downloadUrl` field (grounded on\n\t// download-url-field.ts which adds `downloadUrl: String` to @storageFiles).\n\tconst fileTypesWithDownloadUrl = 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\tfileTypesWithDownloadUrl.add(t.name);\n\t\t}\n\t}\n\n\t// 1. Prefer the 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\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\treturn {\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}\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, uploadFieldName);\n\tif (connection) return 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 preferred = uploadFieldName.replace(/^upload/, '');\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\tthrow createError.badRequest('Uploads are not enabled for this endpoint.');\n}\n\n/**\n * Discover a filtered-connection downloadUrl-by-id path. Returns null if the\n * schema exposes no such connection. 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\tuploadFieldName: string,\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\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 = EQUALITY_OPERATORS.map((op) =>\n\t\t\t\t\tidFieldType.inputFields!.find((f) => f.name === op),\n\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});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// id field is an input object but with no recognized equality op — skip.\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 (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});\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\tconst preferred = uploadFieldName.replace(/^upload/, '');\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}\n\t\t}\n\t`.trim();\n\tconst data = await execute<Record<string, UploadPayload | null>>(mutation, {\n\t\tinput: {\n\t\t\tbucketKey: 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\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 the stable public download URL for a file id via the discovered\n * by-id field. For public files the backend returns a permanent public URL\n * (its exact path shape is the backend's concern) — stored opaquely in the cell.\n */\nexport async function fetchDownloadUrl(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\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}, 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/**\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 once per endpoint (cached)\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 cap = await discoverUploadCapability(endpoint, execute);\n\t\treturn await fetchDownloadUrl(execute, cap, fileId);\n\t} catch {\n\t\treturn null;\n\t}\n}\n","import type { DocumentNode } from 'graphql';\nimport { print } from 'graphql';\n\nimport { ConstructiveError, createError, TypedDocumentString } from '@constructive-io/data';\n\nimport type { SheetsConfig } from './sheets-context';\nimport {\n\tcallUploadOp,\n\tdeleteUploadedFileRow,\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/**\n * Result of an upload through the seam. `url` is the only guaranteed field;\n * the REST upload endpoint also returns `{ filename, mime, size }` (and may\n * return server-internal extras). Keeping it open-ended lets callers read the\n * richer metadata while a bare `{ url }` (e.g. the mock) still satisfies it.\n */\nexport type SheetsUploadResult = { url: string } & Record<string, unknown>;\n\n/**\n * Optional upload metadata carried through the seam (third arg). Lets an\n * injected `executeUpload` see the destination field/row and report progress.\n * All fields optional, so existing `(file, path?)` callers stay valid.\n */\nexport interface SheetsUploadOptions {\n\ttableName?: string;\n\tfieldName?: string;\n\trecordId?: string | number;\n\tonProgress?: (progress: { loaded: number; total: number; percentage: number }) => void;\n}\n\nexport type SheetsUploadFn = (\n\tfile: File,\n\tpath?: string,\n\toptions?: SheetsUploadOptions,\n) => Promise<SheetsUploadResult>;\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction documentToString(document: ExecutableDocument): string {\n\tif (typeof document === 'string') return document;\n\tif (document instanceof String) return document.toString();\n\tif (document && typeof document === 'object' && 'kind' in (document as DocumentNode)) {\n\t\treturn print(document as DocumentNode);\n\t}\n\tif (document === null || document === undefined) {\n\t\tthrow createError.badRequest('Invalid GraphQL document: null or undefined');\n\t}\n\treturn String(document);\n}\n\n// ============================================================================\n// GraphQL Response Parsing\n// ============================================================================\n\ninterface GraphQLResponseError {\n\tmessage: string;\n\textensions?: { code?: string };\n}\n\ninterface GraphQLResponse {\n\tdata?: unknown;\n\terrors?: GraphQLResponseError[];\n}\n\nfunction hasAuthMessage(message: string | undefined): boolean {\n\tconst normalized = String(message ?? '').toLowerCase();\n\treturn (\n\t\tnormalized.includes('unauthenticated') ||\n\t\tnormalized.includes('unauthorized') ||\n\t\tnormalized.includes('authentication')\n\t);\n}\n\nfunction parseGraphQLResponse(response: GraphQLResponse, onAuthError?: () => void): 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\n/**\n * Presigned-URL cell-upload seam.\n *\n * Replaces the legacy multipart `<endpoint>/upload` POST entirely. The flow:\n * 1. Read + SHA-256 hash the file bytes (Web Crypto)\n * 2. Discover (cached per endpoint) the upload op + downloadUrl-by-id field\n * via GraphQL introspection — the root `upload<Type>File` mutation, matched\n * by FIELD/TYPE SHAPE (LOCKED: no hardcoded names)\n * 3. Call the upload op with input `{ bucketKey, contentHash, contentType,\n * size, filename }` — NO `ownerId` (app-scoped buckets have no owner_id)\n * 4. If `uploadUrl` is non-null, PUT the raw bytes to it with ONLY the signed\n * `Content-Type` header (NO Authorization). Skipped when `deduplicated`.\n * 5. Resolve the stable public `downloadUrl` for the returned fileId.\n *\n * Returns `{ url, filename, mime, size, key, fileId }` where `url` is the stable\n * download URL — the same cell value shape callers/Step-2 already consume.\n *\n * `path` is ignored (content-addressed buckets key on `contentHash`).\n */\nexport function createSheetsUpload(config: SheetsConfig, getToken: () => string | null): SheetsUploadFn {\n\t// Reuse the kept GraphQL executor so canonical error normalization + onAuthError\n\t// (401/UNAUTHENTICATED) apply to introspection, the upload op, and the\n\t// downloadUrl query alike.\n\tconst execute = config.execute ?? createSheetsExecute(config, getToken);\n\n\treturn async (file: File, _path?: string, options?: SheetsUploadOptions): Promise<SheetsUploadResult> => {\n\t\tif (!config.endpoint) {\n\t\t\tthrow createError.badRequest('No GraphQL endpoint configured.');\n\t\t}\n\n\t\tconst bucketKey = config.upload?.bucketKey ?? 'public';\n\t\tconst contentType = file.type || 'application/octet-stream';\n\n\t\t// Single read of the bytes — reused for both hashing and the PUT body.\n\t\tconst buffer = await file.arrayBuffer();\n\t\tconst contentHash = await sha256HexFromBuffer(buffer);\n\n\t\tconst cap = await discoverUploadCapability(config.endpoint, execute);\n\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\t// Dedup (deduplicated ⇒ uploadUrl === null) means the row + S3 object already\n\t\t// exist; skip the PUT. A non-deduplicated payload MUST carry an uploadUrl — a\n\t\t// null there is a server-contract violation, so fail loudly rather than\n\t\t// resolving a downloadUrl for an object that was never uploaded.\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\ttry {\n\t\t\t\tawait presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);\n\t\t\t} catch (error) {\n\t\t\t\t// The upload op already created the row; drop it so the bucket doesn't list\n\t\t\t\t// a file whose bytes were never stored.\n\t\t\t\tawait deleteUploadedFileRow(execute, cap, payload.fileId);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} else {\n\t\t\toptions?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });\n\t\t}\n\n\t\tconst url = await fetchDownloadUrl(execute, cap, payload.fileId);\n\n\t\treturn {\n\t\t\turl,\n\t\t\tfilename: file.name,\n\t\t\tmime: file.type,\n\t\t\tsize: file.size,\n\t\t\tkey: payload.key,\n\t\t\tfileId: payload.fileId,\n\t\t};\n\t};\n}\n\nexport { ConstructiveError } from '@constructive-io/data';\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\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"],"mappings":";;;AAuBA,SAAS,6BAA6B;AAEtC,SAAS,mBAAmB;AA2D5B,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YAAY,CAAC,OAAuB,aACnC,CAAC,GAAG,gBAAgB,MAAM,KAAK,GAAG,eAAe,QAAQ;AAAA,EAC1D,WAAW,CAAC,OAAuB,cAClC,CAAC,GAAG,gBAAgB,MAAM,KAAK,GAAG,aAAa,SAAS;AAAA,EACzD,OAAO,CAAC,OAAuB,cAAsB,CAAC,GAAG,gBAAgB,MAAM,KAAK,GAAG,SAAS,SAAS;AAAA,EACzG,WAAW,CAAC,OAAuB,WAAmB,YACrD,CAAC,GAAG,gBAAgB,MAAM,OAAO,SAAS,GAAG,QAAQ,OAAO;AAAA,EAC7D,UAAU,CAAC,OAAuB,WAAmB,OACpD,CAAC,GAAG,gBAAgB,MAAM,OAAO,SAAS,GAAG,OAAO,EAAE;AAAA,EACvD,YAAY,CAAC,OAAuB,WAAmB,UACtD,CAAC,GAAG,gBAAgB,MAAM,OAAO,SAAS,GAAG,SAAS,KAAK;AAAA,EAC5D,eAAe,CAAC,OAAuB,cACtC,CAAC,GAAG,gBAAgB,MAAM,KAAK,GAAG,kBAAkB,SAAS;AAAA,EAC9D,mBAAmB,CAAC,OAAuB,WAAmB,WAAmB,YAChF,CAAC,GAAG,gBAAgB,cAAc,OAAO,SAAS,GAAG,QAAQ,WAAW,OAAO;AAAA,EAChF,yBAAyB,CAAC,OAAuB,WAAmB,UACnE,CAAC,GAAG,gBAAgB,cAAc,OAAO,SAAS,GAAG,cAAc,KAAK;AAAA,EACzE,aAAa,CAAC,OAAuB,WAAmB,YACvD,CAAC,GAAG,gBAAgB,MAAM,KAAK,GAAG,gBAAgB,WAAW,OAAO;AACtE;","names":["query","data","url","idScalar","createError","ConstructiveError","createError"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context/sheets-context.ts","../src/store/draft-rows-slice.ts","../src/store/relation-info-slice.ts","../src/utils/relation-utils.ts","../src/store/sheets-store.ts"],"sourcesContent":["import { createContext, useContext } from 'react';\nimport type { QueryClient } from '@tanstack/react-query';\n\nimport type { SheetsExecuteFn, SheetsUploadFn } from './sheets-execute';\nimport type { SheetsLogger } from '../utils/sheets-logger';\nimport type { CellTypePlugin } from '../cell-types/define-cell-type';\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\n\nexport interface SheetsAuthEmbedded {\n\tmode: 'embedded';\n\tgetToken: () => string | null;\n\t/**\n\t * Stable, non-secret identity used to isolate cached data between users.\n\t * Hosts should return the authenticated user/session id, never the token.\n\t * When omitted, the provider uses an opaque key that changes with the token.\n\t */\n\tgetIdentityKey?: () => string | null;\n}\n\nexport interface SheetsAuthStandalone {\n\tmode: 'standalone';\n}\n\nexport interface SheetsConfig {\n\t/** Data endpoint (app-public GraphQL) */\n\tendpoint: string;\n\t/** Auth endpoint (auth GraphQL) — required for standalone mode */\n\tauthEndpoint?: string;\n\t/** Database ID for multi-tenant scoping */\n\tdatabaseId?: string;\n\t/** Auth mode */\n\tauth: SheetsAuthEmbedded | SheetsAuthStandalone;\n\t/** Field type overrides (replaces schema-builder smart tags) */\n\tfieldTypeOverrides?: Record<string, string>;\n\t/** Optional: BCP-47 locale for locale-aware date/number formatting (default 'en-US'). */\n\tlocale?: string;\n\t/** Optional: inject custom execute function */\n\texecute?: SheetsExecuteFn;\n\t/** Optional: inject custom upload function */\n\texecuteUpload?: SheetsUploadFn;\n\t/** Optional upload settings. `bucketKey` defaults to \"public\". */\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\tscopeKey: SheetsScopeKey;\n}\n\nexport interface SheetsScopeKey {\n\tdatabaseId: string | null;\n\tendpoint: string;\n\tidentityKey: string | null;\n}\n\nexport const SheetsContext = createContext<SheetsContextValue | null>(null);\n\nexport function useSheetsContext(): SheetsContextValue {\n\tconst ctx = useContext(SheetsContext);\n\tif (!ctx) {\n\t\tthrow new Error('useSheetsContext must be used within a <SheetsProvider>');\n\t}\n\treturn ctx;\n}\n","import type { RelationInfo } from './relation-info-slice';\n\ntype DraftRowStatus = 'idle' | 'saving' | 'error';\n\nexport interface DraftRow {\n id: string;\n values: Record<string, unknown>;\n status: DraftRowStatus;\n errors: Record<string, string> | null;\n createdAt: number;\n metaVersion: string;\n}\n\ninterface DraftRowsTableState {\n order: string[];\n map: Record<string, DraftRow>;\n template: Record<string, unknown>;\n metaVersion: string;\n columnOrder: string[];\n}\n\nexport function parseDraftTableKey(tableKey: string): { databaseId: string | null; tableName: string } | null {\n const parts = tableKey.split('::');\n if (parts.length === 2) {\n const [databaseId, tableName] = parts;\n if (!databaseId || !tableName) return null;\n return { databaseId, tableName };\n }\n return null;\n}\n\nexport interface DraftRowCreationArgs {\n tableKey: string;\n columnOrder: readonly string[];\n fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>;\n relationInfoByKey?: Record<string, RelationInfo | undefined>;\n metaVersion: string;\n}\n\nexport type DraftRowsSyncArgs = DraftRowCreationArgs;\n\nexport interface DraftRowUpdateArgs {\n tableKey: string;\n draftRowId: string;\n columnKey: string;\n value: unknown;\n extraValues?: Record<string, unknown>;\n}\n\nexport interface DraftRowsSlice {\n draftRowsByTable: Record<string, DraftRowsTableState | undefined>;\n createDraftRow: (args: DraftRowCreationArgs) => string;\n updateDraftCell: (args: DraftRowUpdateArgs) => void;\n removeDraftRow: (tableKey: string, draftRowId: string) => void;\n clearDraftRowsForTable: (tableKey: string) => void;\n clearDraftRowsForDatabase: (databaseId: string) => void;\n clearAllDraftRows: () => void;\n syncDraftRowsWithMeta: (args: DraftRowsSyncArgs) => void;\n setDraftRowStatus: (args: {\n tableKey: string;\n draftRowId: string;\n status: DraftRowStatus;\n errors?: Record<string, string> | null;\n }) => void;\n}\n\ntype DraftFieldMetadata = {\n name?: string | null;\n isNotNull?: boolean | null;\n hasDefault?: boolean | null;\n type?: {\n gqlType?: string | null;\n isArray?: boolean | null;\n pgAlias?: string | null;\n pgType?: string | null;\n subtype?: string | null;\n } | null;\n};\n\ntype DraftRowsSetState = (\n\tpartial: Partial<DraftRowsSlice> | ((state: DraftRowsSlice) => Partial<DraftRowsSlice> | DraftRowsSlice),\n) => void;\n\nexport function createDraftRowsSlice(set: DraftRowsSetState): DraftRowsSlice {\n\treturn {\n draftRowsByTable: {},\n\n createDraftRow: (args) => {\n const { tableKey, columnOrder, fieldMetaByKey, relationInfoByKey, metaVersion } = args;\n\n const effectiveColumnOrder = ensureColumnOrder(columnOrder, fieldMetaByKey, relationInfoByKey);\n const template = buildTemplate(effectiveColumnOrder, relationInfoByKey);\n const draftRowId = `draft:${generateDraftSuffix()}`;\n const values = initializeValuesFromTemplate(template, draftRowId);\n\n set((state: DraftRowsSlice) => {\n const existing = state.draftRowsByTable[tableKey];\n\n const nextOrder = existing ? [...existing.order, draftRowId] : [draftRowId];\n\t const nextMap: Record<string, DraftRow> = {\n\t ...(existing?.map ?? {}),\n [draftRowId]: {\n id: draftRowId,\n values,\n status: 'idle' as const,\n errors: null,\n createdAt: Date.now(),\n metaVersion,\n },\n };\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: {\n order: nextOrder,\n map: nextMap,\n template,\n metaVersion,\n columnOrder: [...effectiveColumnOrder],\n },\n },\n };\n });\n\n return draftRowId;\n },\n\n\t updateDraftCell: ({ tableKey, draftRowId, columnKey, value, extraValues }) => {\n\t set((state: DraftRowsSlice) => {\n\t const tableState = state.draftRowsByTable[tableKey];\n\t if (!tableState) return state;\n\n\t const existingRow = tableState.map[draftRowId];\n\t if (!existingRow) return state;\n\n\t let hasValueChanges = !deepEqual(existingRow.values[columnKey], value);\n\t if (!hasValueChanges && extraValues) {\n\t for (const [key, extraValue] of Object.entries(extraValues)) {\n\t if (!deepEqual(existingRow.values[key], extraValue)) {\n\t hasValueChanges = true;\n\t break;\n\t }\n\t }\n\t }\n\n\t const shouldResetErrors = existingRow.status === 'error' || existingRow.errors !== null;\n\t if (!hasValueChanges && !shouldResetErrors) return state;\n\n\t const updatedValues = hasValueChanges ? { ...existingRow.values, [columnKey]: deepClone(value) } : existingRow.values;\n\t if (hasValueChanges && extraValues) {\n\t for (const [key, extraValue] of Object.entries(extraValues)) {\n\t updatedValues[key] = deepClone(extraValue);\n\t }\n\t }\n\n\t const nextMap: Record<string, DraftRow> = {\n\t ...tableState.map,\n [draftRowId]: {\n ...existingRow,\n values: updatedValues,\n status: existingRow.status === 'error' ? ('idle' as const) : existingRow.status,\n errors: null,\n },\n };\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: {\n ...tableState,\n map: nextMap,\n },\n },\n };\n });\n },\n\n removeDraftRow: (tableKey, draftRowId) => {\n set((state: DraftRowsSlice) => {\n const tableState = state.draftRowsByTable[tableKey];\n if (!tableState) return state;\n if (!tableState.map[draftRowId]) return state;\n\n const nextOrder = tableState.order.filter((id) => id !== draftRowId);\n const nextMap = { ...tableState.map };\n delete nextMap[draftRowId];\n\n const nextTableState: DraftRowsTableState | undefined = nextOrder.length\n ? { ...tableState, order: nextOrder, map: nextMap }\n : undefined;\n\n const nextByTable = { ...state.draftRowsByTable };\n if (nextTableState) {\n nextByTable[tableKey] = nextTableState;\n } else {\n delete nextByTable[tableKey];\n }\n\n return { draftRowsByTable: nextByTable };\n });\n },\n\n clearDraftRowsForTable: (tableKey) => {\n set((state: DraftRowsSlice) => {\n if (!state.draftRowsByTable[tableKey]) return state;\n const nextByTable = { ...state.draftRowsByTable };\n delete nextByTable[tableKey];\n return { draftRowsByTable: nextByTable };\n });\n },\n\n clearDraftRowsForDatabase: (databaseId) => {\n set((state: DraftRowsSlice) => {\n if (!databaseId || !Object.keys(state.draftRowsByTable).length) return state;\n let changed = false;\n const nextByTable: Record<string, DraftRowsTableState | undefined> = { ...state.draftRowsByTable };\n\n for (const tableKey of Object.keys(nextByTable)) {\n const parsed = parseDraftTableKey(tableKey);\n const matchesDatabase = parsed ? parsed.databaseId === databaseId : tableKey.includes(`${databaseId}::`);\n\n if (matchesDatabase) {\n delete nextByTable[tableKey];\n changed = true;\n }\n }\n\n return changed ? { draftRowsByTable: nextByTable } : state;\n });\n },\n\n clearAllDraftRows: () => {\n set((state: DraftRowsSlice) => {\n if (!Object.keys(state.draftRowsByTable).length) return state;\n return { draftRowsByTable: {} };\n });\n },\n\n\t syncDraftRowsWithMeta: (args) => {\n\t const { tableKey, columnOrder, fieldMetaByKey, relationInfoByKey, metaVersion } = args;\n\n\t set((state: DraftRowsSlice) => {\n\t const tableState = state.draftRowsByTable[tableKey];\n\t const effectiveColumnOrder = ensureColumnOrder(columnOrder, fieldMetaByKey, relationInfoByKey);\n\t const template = buildTemplate(effectiveColumnOrder, relationInfoByKey);\n\n\t if (!tableState) {\n\t return state;\n\t }\n\n\t if (tableState.order.length === 0) {\n\t const nextByTable = { ...state.draftRowsByTable };\n\t delete nextByTable[tableKey];\n\t return { draftRowsByTable: nextByTable };\n\t }\n\n\t const isSameMeta =\n\t tableState.metaVersion === metaVersion && shallowEqualArrays(tableState.columnOrder, effectiveColumnOrder);\n\n if (isSameMeta) return state;\n\n const nextMap: Record<string, DraftRow> = {};\n for (const draftId of tableState.order) {\n const row = tableState.map[draftId];\n if (!row) continue;\n\n const mergedValues: Record<string, unknown> = initializeValuesFromTemplate(template, draftId);\n for (const key of Object.keys(row.values)) {\n if (Object.prototype.hasOwnProperty.call(template, key)) {\n mergedValues[key] = deepClone(row.values[key]);\n }\n }\n\n nextMap[draftId] = {\n ...row,\n values: mergedValues,\n metaVersion,\n status: row.status === 'error' ? 'idle' as const : row.status,\n errors: row.status === 'error' ? null : row.errors,\n };\n }\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: {\n order: [...tableState.order],\n map: nextMap,\n template,\n metaVersion,\n columnOrder: [...effectiveColumnOrder],\n },\n },\n };\n });\n },\n\n\t setDraftRowStatus: ({ tableKey, draftRowId, status, errors }) => {\n\t set((state: DraftRowsSlice) => {\n\t const tableState = state.draftRowsByTable[tableKey];\n\t if (!tableState) return state;\n\t const row = tableState.map[draftRowId];\n\t if (!row) return state;\n\t const nextErrors = errors ?? null;\n\t if (row.status === status && shallowEqualRecords(row.errors, nextErrors)) return state;\n\n\t const nextMap: Record<string, DraftRow> = {\n\t ...tableState.map,\n\t [draftRowId]: { ...row, status, errors: nextErrors },\n\t };\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: { ...tableState, map: nextMap },\n },\n };\n });\n },\n };\n}\n\nfunction ensureColumnOrder(\n columnOrder: readonly string[],\n fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>,\n relationInfoByKey?: Record<string, RelationInfo | undefined>,\n): string[] {\n if (columnOrder.length > 0) return [...columnOrder];\n\n const keys = new Set<string>();\n Object.keys(fieldMetaByKey).forEach((key) => {\n if (key) keys.add(key);\n });\n if (relationInfoByKey) {\n Object.keys(relationInfoByKey).forEach((key) => {\n if (key) keys.add(key);\n });\n }\n return Array.from(keys).sort((a, b) => a.localeCompare(b));\n}\n\nfunction buildTemplate(\n columnOrder: readonly string[],\n relationInfoByKey?: Record<string, RelationInfo | undefined>,\n): Record<string, unknown> {\n const template: Record<string, unknown> = {};\n\n for (const column of columnOrder) {\n if (!column) continue;\n const relationInfo = relationInfoByKey?.[column];\n\n if (relationInfo && (relationInfo.kind === 'hasMany' || relationInfo.kind === 'manyToMany')) {\n template[column] = [];\n } else {\n template[column] = null;\n }\n }\n\n return template;\n}\n\nfunction generateDraftSuffix(): string {\n const cryptoObj = typeof globalThis !== 'undefined' ? (globalThis as any).crypto : undefined;\n if (cryptoObj && typeof cryptoObj.getRandomValues === 'function') {\n const buffer = new Uint32Array(1);\n cryptoObj.getRandomValues(buffer);\n return buffer[0].toString(36).slice(0, 8);\n }\n return Math.random().toString(36).slice(2, 10);\n}\n\nfunction initializeValuesFromTemplate(template: Record<string, unknown>, draftRowId: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(template)) {\n result[key] = deepClone(value);\n }\n if (!result.id) result.id = draftRowId;\n return result;\n}\n\nfunction deepClone<T>(value: T): T {\n if (Array.isArray(value)) return value.map((item) => deepClone(item)) as unknown as T;\n if (value instanceof Date) return new Date(value.getTime()) as unknown as T;\n if (value && typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value as Record<string, unknown>)) {\n result[key] = deepClone(val);\n }\n return result as unknown as T;\n }\n\treturn value;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n\tif (Object.is(a, b)) return true;\n\tif (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\tif (a.length !== b.length) return false;\n\t\tfor (let i = 0; i < a.length; i += 1) {\n\t\t\tif (!deepEqual(a[i], b[i])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\tif (a && b && typeof a === 'object' && typeof b === 'object') {\n\t\tconst keysA = Object.keys(a as Record<string, unknown>);\n\t\tconst keysB = Object.keys(b as Record<string, unknown>);\n\t\tif (keysA.length !== keysB.length) return false;\n\t\tfor (const key of keysA) {\n\t\t\tif (!(key in (b as Record<string, unknown>))) return false;\n\t\t\tif (!deepEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nfunction shallowEqualRecords(\n\ta: Record<string, string> | null,\n\tb: Record<string, string> | null,\n): boolean {\n\tif (a === b) return true;\n\tif (!a || !b) return false;\n\tconst keysA = Object.keys(a);\n\tconst keysB = Object.keys(b);\n\tif (keysA.length !== keysB.length) return false;\n\tfor (const key of keysA) {\n\t\tif (a[key] !== b[key]) return false;\n\t}\n\treturn true;\n}\n\nfunction shallowEqualArrays(a: readonly string[], b: readonly string[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\nexport function computeDraftMetaSignature(\n columnOrder: readonly string[],\n fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>,\n relationInfoByKey?: Record<string, RelationInfo | undefined>,\n): string {\n const signatureParts = columnOrder.map((column) => {\n const typeMeta = fieldMetaByKey[column]?.type;\n const relationMeta = relationInfoByKey?.[column];\n\n const typePart = typeMeta\n ? [\n typeMeta.gqlType ?? '',\n typeMeta.isArray ? '1' : '0',\n typeMeta.pgAlias ?? '',\n typeMeta.pgType ?? '',\n typeMeta.subtype ?? '',\n ].join(':')\n : '';\n\n const relationPart = relationMeta\n ? [relationMeta.kind ?? '', relationMeta.foreignKeyField ?? '', relationMeta.relationField ?? ''].join(':')\n : '';\n\n return `${column}|${typePart}|${relationPart}`;\n });\n\n return hashString(signatureParts.join('||'));\n}\n\nfunction hashString(input: string): string {\n let hash = 0;\n for (let i = 0; i < input.length; i += 1) {\n hash = (hash << 5) - hash + input.charCodeAt(i);\n hash |= 0;\n }\n return hash.toString(16);\n}\n","import { pluralize } from 'inflekt';\nimport { cleanTable, pgFieldToCamelCase, type CleanTable, type MetaQuery } from '@constructive-io/data';\nimport { getJunctionTableNames, isJunctionTablePure } from '../utils/relation-utils';\n\nexport type RelationKind = 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany';\n\nexport interface RelationInfo {\n kind: RelationKind;\n relatedTable?: string;\n displayCandidates: string[];\n relationField?: string;\n foreignKeyField?: string;\n junctionTable?: string;\n junctionLeftKeyField?: string;\n junctionRightKeyField?: string;\n displayName?: string;\n}\n\nexport interface RelationInfoSlice {\n relationInfoCache: Record<string, Record<string, RelationInfo>>;\n relationInfoMapCache: Record<string, Map<string, RelationInfo>>;\n setRelationInfoForTable: (tableName: string, info: Record<string, RelationInfo>) => void;\n getRelationInfoForTable: (tableName: string) => Record<string, RelationInfo> | undefined;\n getRelationInfoMapForTable: (tableName: string) => Map<string, RelationInfo> | undefined;\n rebuildRelationInfo: (tableName: string, meta: MetaQuery | undefined) => void;\n ensureRelationInfo: (tableName: string, meta: MetaQuery | undefined) => Record<string, RelationInfo>;\n clearRelationInfoCache: () => void;\n}\n\ninterface RelationInfoState {\n relationInfoCache: Record<string, Record<string, RelationInfo>>;\n relationInfoMapCache: Record<string, Map<string, RelationInfo>>;\n}\n\ntype RelationInfoSetState = (\n partial: Partial<RelationInfoState> | ((state: RelationInfoState) => Partial<RelationInfoState>),\n) => void;\n\ntype RelationInfoGetState = () => RelationInfoState;\n\nfunction toRelationInfoMap(info: Record<string, RelationInfo>): Map<string, RelationInfo> {\n return new Map(Object.entries(info));\n}\n\nfunction setTableRelationInfo(set: RelationInfoSetState, tableName: string, info: Record<string, RelationInfo>): void {\n set((state) => ({\n relationInfoCache: { ...state.relationInfoCache, [tableName]: info },\n relationInfoMapCache: { ...state.relationInfoMapCache, [tableName]: toRelationInfoMap(info) },\n }));\n}\n\nexport function createRelationInfoSlice(set: RelationInfoSetState, get: RelationInfoGetState): RelationInfoSlice {\n return {\n relationInfoCache: {},\n relationInfoMapCache: {},\n setRelationInfoForTable: (tableName, info) => setTableRelationInfo(set, tableName, info),\n getRelationInfoForTable: (tableName) => get().relationInfoCache[tableName],\n getRelationInfoMapForTable: (tableName) => get().relationInfoMapCache[tableName],\n clearRelationInfoCache: () => set({ relationInfoCache: {}, relationInfoMapCache: {} }),\n rebuildRelationInfo: (tableName: string, meta: MetaQuery | undefined) => {\n try {\n const info = buildRelationInfoFromMeta(tableName, meta);\n if (!info) return;\n setTableRelationInfo(set, tableName, info);\n } catch {\n // ignore\n }\n },\n ensureRelationInfo: (tableName: string, meta: MetaQuery | undefined) => {\n const existing = get().relationInfoCache[tableName];\n if (existing) return existing;\n const info = buildRelationInfoFromMeta(tableName, meta) || {};\n if (Object.keys(info).length) {\n setTableRelationInfo(set, tableName, info);\n }\n return info;\n },\n };\n}\n\ntype MetaTableNode = NonNullable<NonNullable<NonNullable<MetaQuery['_meta']>['tables']>[number]>;\n\nfunction toCleanTables(meta: MetaQuery | undefined): CleanTable[] {\n const tables = meta?._meta?.tables ?? [];\n return tables.filter((table): table is MetaTableNode => table != null).map((table) => cleanTable(table));\n}\n\nfunction firstFieldName(fields: Array<{ name: string }>): string | undefined {\n return fields[0]?.name;\n}\n\n/**\n * For hasOne/hasMany relations, find the FK field in the RELATED table that\n * references the current table. relation.keys contains the PK of the current\n * table (e.g. \"id\"), but the relation editor needs the FK in the child table\n * (e.g. \"questionnaireId\") to link/unlink records.\n *\n * Resolution chain:\n * 1. Related table's belongsTo relations (from cleanTable)\n * 2. Related table's foreignKeyConstraints (from raw _meta)\n */\nfunction findForeignKeyInRelatedTable(\n currentTableName: string,\n relatedTableName: string,\n allTables: CleanTable[],\n rawMetaTables: readonly MetaTableNode[],\n): string | undefined {\n // 1. Try belongsTo on the related cleaned table\n const relatedTable = allTables.find((t) => t.name === relatedTableName);\n if (relatedTable) {\n const belongsTo = relatedTable.relations.belongsTo.find(\n (rel) => rel.referencesTable === currentTableName,\n );\n if (belongsTo?.keys?.[0]?.name) return belongsTo.keys[0].name;\n }\n\n // 2. Fall back to foreignKeyConstraints on the raw _meta related table\n const rawRelated = rawMetaTables.find((t) => t.name === relatedTableName);\n if (rawRelated) {\n // v5 nested: constraints.foreignKey[]\n const v5Fks = Array.isArray(rawRelated.constraints) ? [] : rawRelated.constraints?.foreignKey;\n // v4 flat: foreignKeyConstraints[]\n const fks = v5Fks ?? rawRelated.foreignKeyConstraints ?? [];\n for (const fk of fks) {\n if (!fk) continue;\n const refName = fk.refTable?.name;\n // refTable.name is a codec name (camelCase) — match case-insensitively\n if (refName && refName.toLowerCase() === currentTableName.toLowerCase()) {\n const fieldName = fk.fields?.[0]?.name;\n if (fieldName) return pgFieldToCamelCase(fieldName);\n }\n }\n }\n\n return undefined;\n}\n\nexport function buildRelationInfoFromMeta(\n tableName: string,\n meta: MetaQuery | undefined,\n): Record<string, RelationInfo> | null {\n const tables = toCleanTables(meta);\n const table = tables.find((candidate) => candidate.name === tableName);\n if (!table) return null;\n\n const rawMetaTables = (meta?._meta?.tables ?? []).filter(\n (t): t is MetaTableNode => t != null,\n );\n\n const PRIORITY_FIELDS = [\n 'displayName',\n 'fullName',\n 'preferredName',\n 'nickname',\n 'firstName',\n 'lastName',\n 'givenName',\n 'familyName',\n 'username',\n 'handle',\n 'email',\n 'phone',\n 'title',\n 'label',\n 'slug',\n 'code',\n 'name',\n ];\n const NAME_PATTERN = /name/i;\n\n const computeCandidates = (relatedTableName?: string): string[] => {\n if (!relatedTableName) return [];\n const related = tables.find((candidate) => candidate.name === relatedTableName);\n if (!related) return [];\n\n const fieldNamesSet = new Set<string>(related.fields.map((field) => field.name));\n const explicit = PRIORITY_FIELDS.filter((k) => fieldNamesSet.has(k));\n const explicitSet = new Set(explicit);\n\n const nameLike: string[] = [];\n for (const name of fieldNamesSet) {\n if (NAME_PATTERN.test(name) && !explicitSet.has(name)) {\n nameLike.push(name);\n }\n }\n nameLike.sort((a, b) => a.length - b.length);\n\n return Array.from(new Set([...explicit, ...nameLike]));\n };\n\n const info: Record<string, RelationInfo> = {};\n table.relations.belongsTo.forEach((relation) => {\n const displayCandidates = computeCandidates(relation.referencesTable);\n const foreignKeys = relation.keys.map((key) => key.name).filter(Boolean);\n const primaryForeignKey = foreignKeys[0];\n\n if (relation.fieldName) {\n info[relation.fieldName] = {\n kind: 'belongsTo',\n relatedTable: relation.referencesTable,\n displayCandidates,\n relationField: relation.fieldName,\n foreignKeyField: primaryForeignKey,\n };\n }\n\n foreignKeys.forEach((fk) => {\n if (!fk) return;\n info[fk] = {\n kind: 'belongsTo',\n relatedTable: relation.referencesTable,\n displayCandidates,\n relationField: relation.fieldName ?? undefined,\n foreignKeyField: fk,\n };\n });\n });\n table.relations.hasOne.forEach((relation) => {\n if (relation.fieldName) {\n // relation.keys contains the PK of the CURRENT table, not the FK in the\n // related table. Resolve the actual FK field via:\n // 1. Related table's belongsTo (cleanTable)\n // 2. Related table's foreignKeyConstraints (raw _meta)\n const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);\n info[relation.fieldName] = {\n kind: 'hasOne',\n relatedTable: relation.referencedByTable,\n displayCandidates: computeCandidates(relation.referencedByTable),\n relationField: relation.fieldName,\n foreignKeyField: fkInRelated,\n };\n }\n });\n const junctionTableNames = getJunctionTableNames(table.relations, rawMetaTables);\n\n table.relations.hasMany.forEach((relation) => {\n if (!relation.fieldName) return;\n // Skip hasMany relations pointing to junction tables (M:N covers these)\n if (junctionTableNames.has(relation.referencedByTable)) return;\n const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);\n info[relation.fieldName] = {\n kind: 'hasMany',\n relatedTable: relation.referencedByTable,\n displayCandidates: computeCandidates(relation.referencedByTable),\n relationField: relation.fieldName,\n foreignKeyField: fkInRelated,\n };\n });\n table.relations.manyToMany.forEach((relation) => {\n if (relation.fieldName) {\n // Prefer direct key fields from enriched cleanTable()\n let junctionLeftKeyField = relation.junctionLeftKeyFields?.[0];\n let junctionRightKeyField = relation.junctionRightKeyFields?.[0];\n\n // Fallback: derive from junction table's belongsTo relations\n if (!junctionLeftKeyField || !junctionRightKeyField) {\n const junctionTableName = relation.junctionTable;\n const junctionTable = junctionTableName\n ? tables.find((candidate) => candidate.name === junctionTableName)\n : undefined;\n const junctionBelongsTo = junctionTable?.relations.belongsTo ?? [];\n if (!junctionLeftKeyField) {\n const leftRelation = junctionBelongsTo.find((entry) => entry.referencesTable === tableName);\n junctionLeftKeyField = firstFieldName(leftRelation?.keys ?? []);\n }\n if (!junctionRightKeyField) {\n const rightRelation = junctionBelongsTo.find((entry) => entry.referencesTable === relation.rightTable);\n junctionRightKeyField = firstFieldName(rightRelation?.keys ?? []);\n }\n }\n\n // Skip non-pure junction tables — they have required fields beyond the\n // two FK columns, so the manyToMany editor cannot produce valid mutations.\n if (!isJunctionTablePure(relation.junctionTable, junctionLeftKeyField, junctionRightKeyField, rawMetaTables)) {\n return;\n }\n\n info[relation.fieldName] = {\n kind: 'manyToMany',\n relatedTable: relation.rightTable,\n displayCandidates: computeCandidates(relation.rightTable),\n relationField: relation.fieldName,\n junctionTable: relation.junctionTable,\n junctionLeftKeyField,\n junctionRightKeyField,\n displayName: pluralize(relation.rightTable),\n };\n }\n });\n\n return info;\n}\n","import { singularize } from \"inflekt\";\nimport { pgFieldToCamelCase, type CleanTable, type CleanRelations, type MetaQuery } from \"@constructive-io/data\";\n\ntype PrimitiveId = string | number | null;\n\ntype MetaTable = NonNullable<NonNullable<NonNullable<MetaQuery[\"_meta\"]>[\"tables\"]>[number]>;\n\n\n/**\n * Convert a camelCase plural codec name (as used in raw _meta relation references)\n * to PascalCase singular (matching `_meta.tables[].name` format).\n * e.g. \"formResponses\" → \"FormResponse\"\n */\nfunction codecNameToTableName(name: string): string {\n if (!name) return name;\n const singular = singularize(name);\n return singular.charAt(0).toUpperCase() + singular.slice(1);\n}\n\n/**\n * Derive all relation field names from raw table metadata relations.\n * Filters out hasMany entries that point to junction tables (those are surfaced via manyToMany),\n * and deduplicates manyToMany entries targeting the same table.\n */\nexport function getAllRelationFields(\n relations: MetaTable[\"relations\"] | null | undefined,\n metaTables?: readonly MetaTable[],\n): string[] {\n if (!relations) return [];\n\n const out: string[] = [];\n const push = (fieldName?: string | null) => {\n if (fieldName) out.push(fieldName);\n };\n\n relations.belongsTo?.forEach((rel) => push(rel?.fieldName));\n relations.hasOne?.forEach((rel) => push(rel?.fieldName));\n\n const junctionNames = new Set<string>();\n relations.manyToMany?.forEach((rel) => {\n const jtName = rel?.junctionTable?.name;\n if (!jtName) return;\n // When meta tables are available, skip non-pure junction tables\n if (metaTables) {\n const leftFk = rel?.junctionLeftKeyAttributes?.[0]?.name;\n const rightFk = rel?.junctionRightKeyAttributes?.[0]?.name;\n const leftFkCamel = leftFk ? pgFieldToCamelCase(leftFk) : undefined;\n const rightFkCamel = rightFk ? pgFieldToCamelCase(rightFk) : undefined;\n // Raw _meta codec names need conversion to match MetaTable.name format\n const jtTableName = codecNameToTableName(jtName);\n if (!isJunctionTablePure(jtTableName, leftFkCamel, rightFkCamel, metaTables)) return;\n }\n junctionNames.add(jtName);\n });\n relations.hasMany?.forEach((rel) => {\n const refName = rel?.referencedBy?.name;\n if (refName && junctionNames.has(refName)) return;\n push(rel?.fieldName);\n });\n\n const seenM2N = new Map<string, { fieldName?: string | null }>();\n relations.manyToMany?.forEach((rel) => {\n const target = rel?.rightTable?.name;\n if (!target) return;\n // Skip non-pure junction table M:N relations\n if (metaTables) {\n const jtName = rel?.junctionTable?.name;\n if (jtName) {\n const leftFk = rel?.junctionLeftKeyAttributes?.[0]?.name;\n const rightFk = rel?.junctionRightKeyAttributes?.[0]?.name;\n const leftFkCamel = leftFk ? pgFieldToCamelCase(leftFk) : undefined;\n const rightFkCamel = rightFk ? pgFieldToCamelCase(rightFk) : undefined;\n const jtTableName = codecNameToTableName(jtName);\n if (!isJunctionTablePure(jtTableName, leftFkCamel, rightFkCamel, metaTables)) return;\n }\n }\n seenM2N.set(target, rel);\n });\n seenM2N.forEach((rel) => push(rel?.fieldName));\n\n return Array.from(new Set(out));\n}\n\n/**\n * Check whether a junction table is \"pure\" — i.e. it has no required fields\n * beyond the two FK columns that form the M:N link.\n *\n * Rich entity tables that PostGraphile incidentally detects as junction tables\n * (e.g. `form_response` which has FKs to both `form_question` and `form_section`\n * but also requires `entity_id`, `session_id`, etc.) should NOT be treated as\n * simple junction tables because the manyToMany editor can only set the two FK\n * fields and would produce invalid mutations.\n */\nexport function isJunctionTablePure(\n junctionTableName: string,\n leftFkField: string | undefined,\n rightFkField: string | undefined,\n metaTables: readonly MetaTable[],\n): boolean {\n if (!leftFkField || !rightFkField) return true; // Can't verify, assume pure\n const junctionMeta = metaTables.find((t) => t?.name === junctionTableName);\n if (!junctionMeta?.fields) return true; // No field info available, assume pure\n\n const exemptFields = new Set(['id', leftFkField, rightFkField]);\n\n for (const field of junctionMeta.fields) {\n if (!field?.name) continue;\n const camelName = pgFieldToCamelCase(field.name);\n if (exemptFields.has(camelName)) continue;\n if (field.isNotNull && !field.hasDefault) return false;\n }\n return true;\n}\n\n/**\n * Collect junction table names from M:N relations.\n * Used to suppress hasMany-to-junction columns and hide junction tables from UIs.\n *\n * When `metaTables` is provided, non-pure junction tables (those with extra required\n * fields beyond the two FK columns) are excluded — their hasMany entries should remain\n * visible since the manyToMany editor cannot handle them.\n */\nexport function getJunctionTableNames(\n relations: CleanRelations,\n metaTables?: readonly MetaTable[],\n): Set<string> {\n const names = new Set<string>();\n for (const rel of relations.manyToMany) {\n if (!rel.junctionTable) continue;\n if (metaTables) {\n const leftFk = rel.junctionLeftKeyFields?.[0];\n const rightFk = rel.junctionRightKeyFields?.[0];\n if (!isJunctionTablePure(rel.junctionTable, leftFk, rightFk, metaTables)) continue;\n }\n names.add(rel.junctionTable);\n }\n return names;\n}\n\nfunction extractPrimitiveId(candidate: unknown): PrimitiveId {\n if (candidate === null || candidate === undefined) return null;\n if (typeof candidate === \"string\" || typeof candidate === \"number\") {\n return candidate;\n }\n if (typeof candidate === \"object\") {\n const record = candidate as Record<string, unknown>;\n const id = record.id;\n if (typeof id === \"string\" || typeof id === \"number\") {\n return id;\n }\n }\n return null;\n}\n\nexport function normalizeForeignKeyValue(input: unknown): unknown {\n if (input === undefined) return undefined;\n if (input === null) return null;\n\n if (Array.isArray(input)) {\n return input\n .map((entry) => extractPrimitiveId(entry))\n .filter((entry): entry is PrimitiveId => entry !== undefined);\n }\n\n return extractPrimitiveId(input);\n}\n\n/**\n * Find the foreign key field in a related table that references the current table\n */\nfunction findForeignKeyField(\n currentTableName: string,\n relatedTableName: string,\n allTables?: CleanTable[],\n): string | undefined {\n if (!allTables) return undefined;\n\n // Find the related table\n const relatedTable = allTables.find((table) => table.name === relatedTableName);\n if (!relatedTable) return undefined;\n\n // Look for a belongsTo relation in the related table that references our current table\n const belongsToRelation = relatedTable.relations.belongsTo.find(\n (relation) => relation.referencesTable === currentTableName,\n );\n\n if (belongsToRelation && belongsToRelation.keys?.[0]?.name) {\n return belongsToRelation.keys[0].name;\n }\n\n return undefined;\n}\n\nexport interface RelationshipInfo {\n relationType: \"belongsTo\" | \"hasOne\" | \"hasMany\" | \"manyToMany\";\n relationField: string;\n relatedTableName: string;\n foreignKeyField?: string;\n junctionTableName?: string;\n junctionLeftKey?: string;\n junctionRightKey?: string;\n}\n\n/**\n * Extract relationship information from table metadata for a specific field\n * For hasMany/hasOne relations, we need to find the actual foreign key field in the related table\n */\nexport function getRelationshipInfo(\n currentTable: CleanTable,\n relationFieldName: string,\n allTables?: CleanTable[],\n): RelationshipInfo | null {\n const { relations } = currentTable;\n\n // Check belongsTo relations\n const belongsToRelation = relations.belongsTo.find((rel) => rel.fieldName === relationFieldName);\n if (belongsToRelation) {\n // For belongsTo: get the foreign key field name from the keys array\n const foreignKeyField = belongsToRelation.keys?.[0]?.name;\n return {\n relationType: \"belongsTo\",\n relationField: relationFieldName,\n relatedTableName: belongsToRelation.referencesTable,\n foreignKeyField: foreignKeyField,\n };\n }\n\n // Check hasOne relations\n const hasOneRelation = relations.hasOne.find((rel) => rel.fieldName === relationFieldName);\n if (hasOneRelation) {\n // For hasOne: find the foreign key field in the related table that references our current table\n const foreignKeyField = findForeignKeyField(\n currentTable.name,\n hasOneRelation.referencedByTable,\n allTables,\n );\n return {\n relationType: \"hasOne\",\n relationField: relationFieldName,\n relatedTableName: hasOneRelation.referencedByTable,\n foreignKeyField: foreignKeyField,\n };\n }\n\n // Check hasMany relations\n const hasManyRelation = relations.hasMany.find((rel) => rel.fieldName === relationFieldName);\n if (hasManyRelation) {\n // For hasMany: find the foreign key field in the related table that references our current table\n const foreignKeyField = findForeignKeyField(\n currentTable.name,\n hasManyRelation.referencedByTable,\n allTables,\n );\n return {\n relationType: \"hasMany\",\n relationField: relationFieldName,\n relatedTableName: hasManyRelation.referencedByTable,\n foreignKeyField: foreignKeyField,\n };\n }\n\n // Check manyToMany relations\n const manyToManyRelation = relations.manyToMany.find(\n (rel) => rel.fieldName === relationFieldName,\n );\n if (manyToManyRelation) {\n return {\n relationType: \"manyToMany\",\n relationField: relationFieldName,\n relatedTableName: manyToManyRelation.rightTable,\n junctionTableName: manyToManyRelation.junctionTable,\n junctionLeftKey: manyToManyRelation.junctionLeftKeyFields?.[0],\n junctionRightKey: manyToManyRelation.junctionRightKeyFields?.[0],\n };\n }\n\n return null;\n}\n\n/**\n * Get a display-friendly label from a record using common field patterns\n */\nconst DISPLAY_LABEL_FIELDS = [\n \"name\", \"title\", \"label\", \"displayName\", \"fullName\",\n \"email\", \"username\", \"description\", \"code\",\n];\n\nexport function getRecordDisplayLabel(record: any): string {\n if (!record || typeof record !== \"object\") {\n return String(record || \"\");\n }\n\n // Try common display field patterns\n for (const field of DISPLAY_LABEL_FIELDS) {\n if (record[field] != null && String(record[field]).trim()) {\n return String(record[field]);\n }\n }\n\n // Fallback to ID\n if (record.id != null) {\n return `Record ${record.id}`;\n }\n\n return \"Unknown Record\";\n}\n\n/**\n * Get record ID, handling different ID field patterns\n */\nexport function getRecordId(record: any): string {\n if (!record || typeof record !== \"object\") {\n return String(record || \"\");\n }\n\n // Try common ID field patterns\n const idFields = [\"id\", \"uuid\", \"_id\", \"pk\"];\n\n for (const field of idFields) {\n if (record[field] != null) {\n return String(record[field]);\n }\n }\n\n // Fallback to first field value\n const keys = Object.keys(record);\n if (keys.length > 0) {\n return String(record[keys[0]] || \"\");\n }\n\n return \"\";\n}\n","import { createContext, useContext } from 'react';\nimport { createStore, useStore as useZustandStore, type StoreApi } from 'zustand';\n\nimport { createDraftRowsSlice, type DraftRowsSlice } from './draft-rows-slice';\nimport { createRelationInfoSlice, type RelationInfoSlice } from './relation-info-slice';\n\nexport interface SheetsAuthState {\n isAuthenticated: boolean;\n accessToken: string | null;\n expiresAt: string | null;\n identityKey: string | null;\n setAuthenticated: (token: string, expiresAt: string, identityKey?: string | null) => void;\n setUnauthenticated: () => void;\n}\n\nexport type SheetsStoreState = DraftRowsSlice & RelationInfoSlice & SheetsAuthState;\n\nexport function createSheetsStore(): StoreApi<SheetsStoreState> {\n return createStore<SheetsStoreState>((set, get) => ({\n // Draft rows\n ...createDraftRowsSlice(set),\n\n // Relation info cache\n ...createRelationInfoSlice(set, get),\n\n // Auth state (standalone mode)\n isAuthenticated: false,\n accessToken: null,\n expiresAt: null,\n identityKey: null,\n setAuthenticated: (token: string, expiresAt: string, identityKey = null) =>\n set({ isAuthenticated: true, accessToken: token, expiresAt, identityKey }),\n setUnauthenticated: () => set({ isAuthenticated: false, accessToken: null, expiresAt: null, identityKey: null }),\n }));\n}\n\nexport const SheetsStoreContext = createContext<StoreApi<SheetsStoreState> | null>(null);\n\nexport function useSheetsStore<T>(selector: (state: SheetsStoreState) => T): T {\n const store = useContext(SheetsStoreContext);\n if (!store) {\n throw new Error('useSheetsStore must be used within a <SheetsProvider>');\n }\n return useZustandStore(store, selector);\n}\n\nexport function useSheetsStoreApi(): StoreApi<SheetsStoreState> {\n const store = useContext(SheetsStoreContext);\n if (!store) {\n throw new Error('useSheetsStoreApi must be used within a <SheetsProvider>');\n }\n return store;\n}\n"],"mappings":";;;AAAA,SAAS,eAAe,kBAAkB;AAwEnC,IAAM,gBAAgB,cAAyC,IAAI;AAEnE,SAAS,mBAAuC;AACtD,QAAM,MAAM,WAAW,aAAa;AACpC,MAAI,CAAC,KAAK;AACT,UAAM,IAAI,MAAM,yDAAyD;AAAA,EAC1E;AACA,SAAO;AACR;;;AC3DO,SAAS,mBAAmB,UAA2E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BAAiB,MAAM,aAAa,OAAO,WAAW,YAAY,CAAC;AAAA,IAC3E,oBAAoB,MAAM,IAAI,EAAE,iBAAiB,OAAO,aAAa,MAAM,WAAW,MAAM,aAAa,KAAK,CAAC;AAAA,EACjH,EAAE;AACJ;AAEO,IAAM,qBAAqBC,eAAiD,IAAI;AAEhF,SAAS,eAAkB,UAA6C;AAC7E,QAAM,QAAQC,YAAW,kBAAkB;AAC3C,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,uDAAuD;AAAA,EACzE;AACA,SAAO,gBAAgB,OAAO,QAAQ;AACxC;AAEO,SAAS,oBAAgD;AAC9D,QAAM,QAAQA,YAAW,kBAAkB;AAC3C,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,0DAA0D;AAAA,EAC5E;AACA,SAAO;AACT;","names":["pgFieldToCamelCase","pgFieldToCamelCase","createContext","useContext","createContext","useContext"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cell-types/cell-type-groups.ts","../src/grid/editors/editor-focus-trap.tsx","../src/grid/editors/overlay-presets.ts"],"sourcesContent":["/**\n * Canonical cell-type group constants.\n *\n * Every file that needs to check \"is this cell type a date?\" or \"is this a\n * geometry?\" should import from here instead of maintaining inline arrays.\n *\n * All Sets are typed as `Set<string>` so `.has(cellType)` works without casts.\n */\n\n// ─── Date / Time ────────────────────────────────────────────────────────────\nexport const DATE_TIME_TYPES: Set<string> = new Set(['date', 'datetime', 'timestamptz', 'time']);\n\n// ─── Geometry ───────────────────────────────────────────────────────────────\nexport const GEOMETRY_TYPES: Set<string> = new Set(['geometry', 'geometry-point', 'geometry-collection']);\n\n// ─── Numeric ────────────────────────────────────────────────────────────────\nexport const NUMBER_TYPES: Set<string> = new Set([\n\t'number',\n\t'integer',\n\t'decimal',\n\t'currency',\n\t'smallint',\n\t'percentage',\n\t'rating',\n]);\n\n// ─── Boolean ────────────────────────────────────────────────────────────────\nexport const BOOLEAN_TYPES: Set<string> = new Set(['boolean', 'bit', 'toggle']);\n\n// ─── Array / Collection ─────────────────────────────────────────────────────\nexport const TYPED_ARRAY_TYPES: Set<string> = new Set([\n\t'array',\n\t'text-array',\n\t'uuid-array',\n\t'number-array',\n\t'integer-array',\n\t'date-array',\n\t'tags',\n]);\n\n/** Check for any array-like cell type (typed arrays + generic `-array` suffix) */\nexport function isArrayCellType(cellType: string): boolean {\n\treturn TYPED_ARRAY_TYPES.has(cellType) || cellType.endsWith('-array');\n}\n\n// ─── Structured data (JSON, arrays, interval) ──────────────────────────────\nexport const STRUCTURED_DATA_TYPES: Set<string> = new Set([\n\t'json',\n\t'jsonb',\n\t'array',\n\t'text-array',\n\t'uuid-array',\n\t'number-array',\n\t'integer-array',\n\t'date-array',\n\t'interval',\n]);\n\n// ─── Media ──────────────────────────────────────────────────────────────────\nexport const MEDIA_TYPES: Set<string> = new Set(['image', 'file', 'video', 'audio', 'upload']);\n\n// ─── Enhanced scalar types ──────────────────────────────────────────────────\nexport const ENHANCED_TYPES: Set<string> = new Set([\n\t'email',\n\t'url',\n\t'phone',\n\t'currency',\n\t'percentage',\n\t'color',\n\t'rating',\n\t'tags',\n]);\n\n// ─── Editor behaviour ───────────────────────────────────────────────────────\n\n/** Cell types that use Glide's built-in text editor (no custom overlay). */\nexport const BUILTIN_EDITOR_TYPES: Set<string> = new Set(['text', 'varchar']);\n\n/** Cell types that are never editable (always read-only). */\nexport const NON_EDITABLE_TYPES: Set<string> = new Set(['tsvector']);\n\n/** Cell types that can be activated for viewing but not editing. */\nexport const VIEWER_ONLY_TYPES: Set<string> = new Set(['tsvector']);\n","import React, { useCallback, useEffect, useLayoutEffect, useRef } from 'react';\n\ninterface EditorFocusTrapProps {\n\tchildren: React.ReactNode;\n\tonEscape?: () => void;\n\tonKeyDown?: (e: React.KeyboardEvent) => void;\n\tclassName?: string;\n\tstyle?: React.CSSProperties;\n}\n\nconst FOCUSABLE_SELECTOR = [\n\t'button:not([disabled])',\n\t'input:not([disabled])',\n\t'textarea:not([disabled])',\n\t'select:not([disabled])',\n\t'a[href]',\n\t'[tabindex]:not([tabindex=\"-1\"])',\n].join(', ');\n\n/** Filter to only truly visible focusable elements */\nfunction getVisibleFocusable(container: HTMLElement): HTMLElement[] {\n\treturn Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).filter(\n\t\t(el) => el.offsetParent !== null,\n\t);\n}\n\nexport function EditorFocusTrap({ children, onEscape, onKeyDown, className, style }: EditorFocusTrapProps) {\n\tconst containerRef = useRef<HTMLDivElement>(null);\n\tconst previousActiveElement = useRef<Element | null>(null);\n\n\t// Focus the first visible focusable element synchronously before paint, so the\n\t// editor input is focused instantly on open (no setTimeout settle, no focus-jump\n\t// off an input the user already started typing in). Runs once on mount.\n\tuseLayoutEffect(() => {\n\t\tpreviousActiveElement.current = document.activeElement;\n\n\t\tif (!containerRef.current) return;\n\n\t\tconst visibleElements = getVisibleFocusable(containerRef.current);\n\t\tif (visibleElements.length > 0) {\n\t\t\tvisibleElements[0].focus();\n\t\t} else {\n\t\t\t// If no visible focusable elements, focus the container itself\n\t\t\tcontainerRef.current.focus();\n\t\t}\n\t}, []);\n\n\t// Restore focus to the previously active element when unmounting (only if still\n\t// in DOM).\n\tuseEffect(() => {\n\t\treturn () => {\n\t\t\tif (previousActiveElement.current instanceof HTMLElement && previousActiveElement.current.isConnected) {\n\t\t\t\tpreviousActiveElement.current.focus();\n\t\t\t}\n\t\t};\n\t}, []);\n\n\t// Handle keyboard events — forward all keys to parent, then handle Escape/Tab\n\tconst handleKeyDown = useCallback(\n\t\t(e: React.KeyboardEvent) => {\n\t\t\t// Forward all key events to parent before handling\n\t\t\tonKeyDown?.(e);\n\n\t\t\tif (e.key === 'Escape') {\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\tonEscape?.();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (e.key !== 'Tab') return;\n\n\t\t\tconst container = containerRef.current;\n\t\t\tif (!container) return;\n\n\t\t\tconst focusableElements = getVisibleFocusable(container);\n\t\t\tif (focusableElements.length === 0) return;\n\n\t\t\tconst firstElement = focusableElements[0];\n\t\t\tconst lastElement = focusableElements[focusableElements.length - 1];\n\t\t\tconst activeElement = document.activeElement;\n\n\t\t\tif (e.shiftKey) {\n\t\t\t\t// Shift+Tab: going backwards\n\t\t\t\tif (activeElement === firstElement) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tlastElement.focus();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Tab: going forwards\n\t\t\t\tif (activeElement === lastElement) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tfirstElement.focus();\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t[onEscape, onKeyDown],\n\t);\n\n\treturn (\n\t\t<div\n\t\t\tref={containerRef}\n\t\t\tclassName={className}\n\t\t\tstyle={style}\n\t\t\tonKeyDown={handleKeyDown}\n\t\t\ttabIndex={-1}\n\t\t\trole=\"dialog\"\n\t\t\taria-modal=\"true\"\n\t\t>\n\t\t\t{children}\n\t\t</div>\n\t);\n}\n","/**\n * Standardised overlay width presets for cell editors.\n *\n * Each preset defines `min-w` / `max-w` Tailwind classes so every overlay\n * feels consistent while still fitting its content naturally.\n *\n * Usage:\n * import { OVERLAY } from './overlay-presets';\n * <EditorFocusTrap className={cn(OVERLAY.sm, 'bg-popover …')} />\n */\n\n/** Single-input editors — inet, date, interval, time */\nexport const OVERLAY_SM = 'min-w-[320px] max-w-[480px]';\n\n/** Tag chips / expandable lists — array, url, relation, upload, tsvector */\nexport const OVERLAY_MD = 'min-w-[400px] max-w-[560px]';\n\n/** Rich editors — JSON, image */\nexport const OVERLAY_LG = 'min-w-[480px] max-w-[720px]';\n\n/** Full-width editors — geometry / map */\nexport const OVERLAY_XL = 'min-w-[600px] max-w-4xl';\n\nexport const OVERLAY = {\n\tsm: OVERLAY_SM,\n\tmd: OVERLAY_MD,\n\tlg: OVERLAY_LG,\n\txl: OVERLAY_XL,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,sBAAY,MAAM;AAAA,QACnB;AAAA,MACD,OAAO;AAEN,YAAI,kBAAkB,aAAa;AAClC,YAAE,eAAe;AACjB,uBAAa,MAAM;AAAA,QACpB;AAAA,MACD;AAAA,IACD;AAAA,IACA,CAAC,UAAU,SAAS;AAAA,EACrB;AAEA,SACC;AAAA,IAAC;AAAA;AAAA,MACA,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA,WAAW;AAAA,MACX,UAAU;AAAA,MACV,MAAK;AAAA,MACL,cAAW;AAAA,MAEV;AAAA;AAAA,EACF;AAEF;;;ACpGO,IAAM,aAAa;AAGnB,IAAM,aAAa;AAGnB,IAAM,aAAa;AAGnB,IAAM,aAAa;AAEnB,IAAM,UAAU;AAAA,EACtB,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AACL;","names":[]}
|
package/dist/chunk-ZKANUG3F.js
DELETED
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
import {
|
|
3
|
-
createSheetsExecute,
|
|
4
|
-
createSheetsUpload,
|
|
5
|
-
sheetsQueryKeys
|
|
6
|
-
} from "./chunk-AYMXT3ME.js";
|
|
7
|
-
import {
|
|
8
|
-
getStoredToken
|
|
9
|
-
} from "./chunk-4EZ6A23C.js";
|
|
10
|
-
import {
|
|
11
|
-
SheetsContext,
|
|
12
|
-
SheetsStoreContext,
|
|
13
|
-
createSheetsStore
|
|
14
|
-
} from "./chunk-H5HR5HUJ.js";
|
|
15
|
-
import {
|
|
16
|
-
setSheetsLocale
|
|
17
|
-
} from "./chunk-GGECS2BP.js";
|
|
18
|
-
import {
|
|
19
|
-
setSheetsLogger
|
|
20
|
-
} from "./chunk-X7DHTSOX.js";
|
|
21
|
-
|
|
22
|
-
// src/context/sheets-provider.tsx
|
|
23
|
-
import { useEffect, useId, useMemo, useRef } from "react";
|
|
24
|
-
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
25
|
-
import { useStore as useZustandStore } from "zustand";
|
|
26
|
-
import { jsx } from "react/jsx-runtime";
|
|
27
|
-
function SheetsProvider({ config, children }) {
|
|
28
|
-
const providerInstanceId = useId();
|
|
29
|
-
const storeRef = useRef(null);
|
|
30
|
-
if (!storeRef.current) {
|
|
31
|
-
storeRef.current = createSheetsStore();
|
|
32
|
-
}
|
|
33
|
-
const store = storeRef.current;
|
|
34
|
-
const standaloneIdentityKey = useZustandStore(store, (state) => state.identityKey);
|
|
35
|
-
const standaloneAccessToken = useZustandStore(store, (state) => state.accessToken);
|
|
36
|
-
setSheetsLogger(config.logger);
|
|
37
|
-
setSheetsLocale(config.locale);
|
|
38
|
-
useEffect(() => {
|
|
39
|
-
setSheetsLogger(config.logger);
|
|
40
|
-
setSheetsLocale(config.locale);
|
|
41
|
-
}, [config.logger, config.locale]);
|
|
42
|
-
useEffect(() => {
|
|
43
|
-
const store2 = storeRef.current?.getState();
|
|
44
|
-
if (!store2) return;
|
|
45
|
-
if (config.auth.mode !== "standalone") {
|
|
46
|
-
store2.setUnauthenticated();
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
const databaseId = config.databaseId || "default";
|
|
50
|
-
const stored = getStoredToken(databaseId);
|
|
51
|
-
if (!stored) {
|
|
52
|
-
store2.setUnauthenticated();
|
|
53
|
-
return;
|
|
54
|
-
}
|
|
55
|
-
const expiresAt = new Date(stored.expiresAt);
|
|
56
|
-
if (expiresAt > /* @__PURE__ */ new Date()) {
|
|
57
|
-
store2.setAuthenticated(stored.accessToken, stored.expiresAt, stored.identityKey ?? null);
|
|
58
|
-
return;
|
|
59
|
-
}
|
|
60
|
-
store2.setUnauthenticated();
|
|
61
|
-
}, [config.auth.mode, config.databaseId]);
|
|
62
|
-
const internalQueryClient = useMemo(
|
|
63
|
-
() => new QueryClient({
|
|
64
|
-
defaultOptions: {
|
|
65
|
-
queries: {
|
|
66
|
-
staleTime: 5 * 60 * 1e3,
|
|
67
|
-
gcTime: 30 * 60 * 1e3,
|
|
68
|
-
retry: 1
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
}),
|
|
72
|
-
[]
|
|
73
|
-
);
|
|
74
|
-
const queryClient = config.queryClient ?? internalQueryClient;
|
|
75
|
-
const getToken = useMemo(() => {
|
|
76
|
-
if (config.auth.mode === "embedded") {
|
|
77
|
-
return config.auth.getToken;
|
|
78
|
-
}
|
|
79
|
-
return () => store.getState().accessToken ?? null;
|
|
80
|
-
}, [config.auth, store]);
|
|
81
|
-
const execute = useMemo(() => {
|
|
82
|
-
if (config.execute) return config.execute;
|
|
83
|
-
return createSheetsExecute(config, getToken);
|
|
84
|
-
}, [config, getToken]);
|
|
85
|
-
const executeUpload = useMemo(() => {
|
|
86
|
-
if (config.executeUpload) return config.executeUpload;
|
|
87
|
-
return createSheetsUpload(config, getToken);
|
|
88
|
-
}, [config, getToken]);
|
|
89
|
-
const configuredIdentityKey = config.auth.mode === "embedded" ? config.auth.getIdentityKey?.() ?? null : standaloneIdentityKey;
|
|
90
|
-
const activeToken = config.auth.mode === "embedded" ? config.auth.getToken() : standaloneAccessToken;
|
|
91
|
-
const authGenerationRef = useRef({ mode: config.auth.mode, token: activeToken, generation: 0 });
|
|
92
|
-
if (authGenerationRef.current.mode !== config.auth.mode || authGenerationRef.current.token !== activeToken) {
|
|
93
|
-
authGenerationRef.current = {
|
|
94
|
-
mode: config.auth.mode,
|
|
95
|
-
token: activeToken,
|
|
96
|
-
generation: authGenerationRef.current.generation + 1
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
const identityKey = configuredIdentityKey ?? `anonymous:${providerInstanceId}:${authGenerationRef.current.generation}`;
|
|
100
|
-
const scopeKey = useMemo(
|
|
101
|
-
() => ({
|
|
102
|
-
databaseId: config.databaseId ?? null,
|
|
103
|
-
endpoint: config.endpoint,
|
|
104
|
-
identityKey
|
|
105
|
-
}),
|
|
106
|
-
[config.databaseId, config.endpoint, identityKey]
|
|
107
|
-
);
|
|
108
|
-
useEffect(() => {
|
|
109
|
-
return () => {
|
|
110
|
-
void queryClient.cancelQueries({ queryKey: sheetsQueryKeys.scope(scopeKey) });
|
|
111
|
-
};
|
|
112
|
-
}, [queryClient, scopeKey]);
|
|
113
|
-
const contextValue = useMemo(
|
|
114
|
-
() => ({ config, execute, executeUpload, scopeKey }),
|
|
115
|
-
[config, execute, executeUpload, scopeKey]
|
|
116
|
-
);
|
|
117
|
-
return /* @__PURE__ */ jsx(QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ jsx(SheetsStoreContext.Provider, { value: store, children: /* @__PURE__ */ jsx(SheetsContext.Provider, { value: contextValue, children }) }) });
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
export {
|
|
121
|
-
SheetsProvider
|
|
122
|
-
};
|
|
123
|
-
//# sourceMappingURL=chunk-ZKANUG3F.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context/sheets-provider.tsx"],"sourcesContent":["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 { createSheetsExecute, createSheetsUpload, type SheetsExecuteFn, type SheetsUploadFn } from './sheets-execute';\nimport { createSheetsStore, SheetsStoreContext, type SheetsStoreState } from '../store/sheets-store';\nimport { getStoredToken } from '../auth/utils/token-store';\nimport { setSheetsLogger } from '../utils/sheets-logger';\nimport { setSheetsLocale } from '../utils/sheets-i18n';\nimport { sheetsQueryKeys } from '../hooks/query-keys';\n\ninterface SheetsProviderProps {\n\tconfig: SheetsConfig;\n\tchildren: React.ReactNode;\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\t// Create upload function\n\tconst executeUpload: SheetsUploadFn = useMemo(() => {\n\t\tif (config.executeUpload) return config.executeUpload;\n\t\treturn createSheetsUpload(config, getToken);\n\t}, [config, getToken]);\n\n\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, scopeKey }),\n\t\t[config, execute, executeUpload, scopeKey],\n\t);\n\n\treturn (\n\t\t<QueryClientProvider client={queryClient}>\n\t\t\t<SheetsStoreContext.Provider value={store}>\n\t\t\t\t<SheetsContext.Provider value={contextValue}>{children}</SheetsContext.Provider>\n\t\t\t</SheetsStoreContext.Provider>\n\t\t</QueryClientProvider>\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,WAAW,OAAO,SAAS,cAAc;AAClD,SAAS,aAAa,2BAA2B;AACjD,SAAS,YAAY,uBAAsC;AAqJvD;AAtIG,SAAS,eAAe,EAAE,QAAQ,SAAS,GAAwB;AACzE,QAAM,qBAAqB,MAAM;AAEjC,QAAM,WAAW,OAA0C,IAAI;AAC/D,MAAI,CAAC,SAAS,SAAS;AACtB,aAAS,UAAU,kBAAkB;AAAA,EACtC;AACA,QAAM,QAAQ,SAAS;AACvB,QAAM,wBAAwB,gBAAgB,OAAO,CAAC,UAAU,MAAM,WAAW;AACjF,QAAM,wBAAwB,gBAAgB,OAAO,CAAC,UAAU,MAAM,WAAW;AAGjF,kBAAgB,OAAO,MAAM;AAC7B,kBAAgB,OAAO,MAAM;AAG7B,YAAU,MAAM;AACf,oBAAgB,OAAO,MAAM;AAC7B,oBAAgB,OAAO,MAAM;AAAA,EAC9B,GAAG,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC;AAGjC,YAAU,MAAM;AACf,UAAMA,SAAQ,SAAS,SAAS,SAAS;AACzC,QAAI,CAACA,OAAO;AAEZ,QAAI,OAAO,KAAK,SAAS,cAAc;AAEtC,MAAAA,OAAM,mBAAmB;AACzB;AAAA,IACD;AACA,UAAM,aAAa,OAAO,cAAc;AACxC,UAAM,SAAS,eAAe,UAAU;AACxC,QAA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