@constructive-io/sheets 0.13.1 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +10 -1
  2. package/dist/advanced.cjs +554 -716
  3. package/dist/advanced.cjs.map +1 -1
  4. package/dist/advanced.d.cts +2 -2
  5. package/dist/advanced.d.ts +2 -2
  6. package/dist/advanced.js +4 -4
  7. package/dist/auth.cjs.map +1 -1
  8. package/dist/auth.js +2 -2
  9. package/dist/{chunk-PZL2BCWF.js → chunk-6Y7CZ5VS.js} +2 -2
  10. package/dist/chunk-6Y7CZ5VS.js.map +1 -0
  11. package/dist/{chunk-AYMXT3ME.js → chunk-BGL6EBTE.js} +108 -202
  12. package/dist/chunk-BGL6EBTE.js.map +1 -0
  13. package/dist/{chunk-MXVNIKES.js → chunk-BYAYBXVB.js} +2 -2
  14. package/dist/{chunk-5QPNOKMA.js → chunk-ER3FIDK7.js} +444 -458
  15. package/dist/chunk-ER3FIDK7.js.map +1 -0
  16. package/dist/chunk-GZM2CSTR.js +279 -0
  17. package/dist/chunk-GZM2CSTR.js.map +1 -0
  18. package/dist/{chunk-H5HR5HUJ.js → chunk-YJZFHL2D.js} +1 -1
  19. package/dist/chunk-YJZFHL2D.js.map +1 -0
  20. package/dist/{date-editor-ZFNDKYBD.js → date-editor-G26WKILO.js} +2 -2
  21. package/dist/{grid-cell-types-Pbe2m2tE.d.ts → grid-cell-types-C2-ocDS7.d.cts} +45 -5
  22. package/dist/{grid-cell-types-Pbe2m2tE.d.cts → grid-cell-types-C2-ocDS7.d.ts} +45 -5
  23. package/dist/index.cjs +782 -637
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +106 -112
  26. package/dist/index.d.ts +106 -112
  27. package/dist/index.js +234 -134
  28. package/dist/index.js.map +1 -1
  29. package/dist/{sheets-context-Cu3Ec_ca.d.ts → sheets-context-CHUVJCff.d.ts} +32 -31
  30. package/dist/{sheets-context-CY1RmDKL.d.cts → sheets-context-C_MkTxXm.d.cts} +32 -31
  31. package/dist/testing.cjs +121 -87
  32. package/dist/testing.cjs.map +1 -1
  33. package/dist/testing.d.cts +2 -2
  34. package/dist/testing.d.ts +2 -2
  35. package/dist/testing.js +16 -4
  36. package/dist/testing.js.map +1 -1
  37. package/package.json +5 -4
  38. package/dist/chunk-5QPNOKMA.js.map +0 -1
  39. package/dist/chunk-AYMXT3ME.js.map +0 -1
  40. package/dist/chunk-H5HR5HUJ.js.map +0 -1
  41. package/dist/chunk-PZL2BCWF.js.map +0 -1
  42. package/dist/chunk-ZKANUG3F.js +0 -123
  43. package/dist/chunk-ZKANUG3F.js.map +0 -1
  44. /package/dist/{chunk-MXVNIKES.js.map → chunk-BYAYBXVB.js.map} +0 -0
  45. /package/dist/{date-editor-ZFNDKYBD.js.map → date-editor-G26WKILO.js.map} +0 -0
@@ -2,19 +2,26 @@ import * as react from 'react';
2
2
  import { QueryClient } from '@tanstack/react-query';
3
3
  import { DocumentNode } from 'graphql';
4
4
  import { TypedDocumentString, FieldSelection, CleanTable, MetaQuery, MutationOptions } from '@constructive-io/data';
5
- import { b as CellType, S as SheetsCell, C as CellCreationMetadata, c as CellCategory, E as EditorProps } from './grid-cell-types-Pbe2m2tE.js';
5
+ import { b as CellType, S as SheetsCell, C as CellCreationMetadata, c as CellCategory, E as EditorProps } from './grid-cell-types-C2-ocDS7.js';
6
6
 
7
7
  type ExecutableDocument = TypedDocumentString<any, any> | DocumentNode | string | unknown;
8
8
  type SheetsExecuteFn = <T = unknown>(document: ExecutableDocument, variables?: Record<string, unknown>) => Promise<T>;
9
- /**
10
- * Result of an upload through the seam. `url` is the only guaranteed field;
11
- * the REST upload endpoint also returns `{ filename, mime, size }` (and may
12
- * return server-internal extras). Keeping it open-ended lets callers read the
13
- * richer metadata while a bare `{ url }` (e.g. the mock) still satisfies it.
14
- */
15
- type SheetsUploadResult = {
16
- url: string;
17
- } & Record<string, unknown>;
9
+ /** Durable file metadata for image and upload columns. */
10
+ interface SheetsFileValue {
11
+ id: string;
12
+ key: string;
13
+ bucket_id: string;
14
+ mime: string;
15
+ size: number;
16
+ filename: string;
17
+ /** Public URL supplied by storage, when available. */
18
+ url?: string;
19
+ }
20
+ interface SheetsUploadResult {
21
+ file: SheetsFileValue;
22
+ /** Optional download URL for immediate use. It can expire. */
23
+ url?: string;
24
+ }
18
25
  /**
19
26
  * Optional upload metadata carried through the seam (third arg). Lets an
20
27
  * injected `executeUpload` see the destination field/row and report progress.
@@ -32,25 +39,7 @@ interface SheetsUploadOptions {
32
39
  }
33
40
  type SheetsUploadFn = (file: File, path?: string, options?: SheetsUploadOptions) => Promise<SheetsUploadResult>;
34
41
  declare function createSheetsExecute(config: SheetsConfig, getToken: () => string | null): SheetsExecuteFn;
35
- /**
36
- * Presigned-URL cell-upload seam.
37
- *
38
- * Replaces the legacy multipart `<endpoint>/upload` POST entirely. The flow:
39
- * 1. Read + SHA-256 hash the file bytes (Web Crypto)
40
- * 2. Discover (cached per endpoint) the upload op + downloadUrl-by-id field
41
- * via GraphQL introspection — the root `upload<Type>File` mutation, matched
42
- * by FIELD/TYPE SHAPE (LOCKED: no hardcoded names)
43
- * 3. Call the upload op with input `{ bucketKey, contentHash, contentType,
44
- * size, filename }` — NO `ownerId` (app-scoped buckets have no owner_id)
45
- * 4. If `uploadUrl` is non-null, PUT the raw bytes to it with ONLY the signed
46
- * `Content-Type` header (NO Authorization). Skipped when `deduplicated`.
47
- * 5. Resolve the stable public `downloadUrl` for the returned fileId.
48
- *
49
- * Returns `{ url, filename, mime, size, key, fileId }` where `url` is the stable
50
- * download URL — the same cell value shape callers/Step-2 already consume.
51
- *
52
- * `path` is ignored (content-addressed buckets key on `contentHash`).
53
- */
42
+ /** Creates an uploader for storage. Direct callers may use the supplied endpoint as storage. */
54
43
  declare function createSheetsUpload(config: SheetsConfig, getToken: () => string | null): SheetsUploadFn;
55
44
 
56
45
  /**
@@ -86,6 +75,7 @@ interface CellProps {
86
75
  isEditing: boolean;
87
76
  onStartEdit: () => void;
88
77
  disabled: boolean;
78
+ readOnlyReason?: string;
89
79
  }
90
80
 
91
81
  /** Schema-only inputs used to DETECT a cell type. Never the runtime value. */
@@ -190,6 +180,10 @@ interface SheetsAuthEmbedded {
190
180
  interface SheetsAuthStandalone {
191
181
  mode: 'standalone';
192
182
  }
183
+ interface SheetsStorageTransport {
184
+ endpoint: string;
185
+ execute: SheetsExecuteFn;
186
+ }
193
187
  interface SheetsConfig {
194
188
  /** Data endpoint (app-public GraphQL) */
195
189
  endpoint: string;
@@ -207,7 +201,12 @@ interface SheetsConfig {
207
201
  execute?: SheetsExecuteFn;
208
202
  /** Optional: inject custom upload function */
209
203
  executeUpload?: SheetsUploadFn;
210
- /** Optional upload settings. `bucketKey` defaults to "public". */
204
+ /** Storage endpoint for media uploads and download URL lookups. */
205
+ storage?: {
206
+ endpoint: string;
207
+ execute?: SheetsExecuteFn;
208
+ };
209
+ /** Explicit bucket override. Omit to use the tenant's public default. */
211
210
  upload?: {
212
211
  bucketKey?: string;
213
212
  };
@@ -231,6 +230,8 @@ interface SheetsContextValue {
231
230
  config: SheetsConfig;
232
231
  execute: SheetsExecuteFn;
233
232
  executeUpload: SheetsUploadFn;
233
+ storage?: SheetsStorageTransport;
234
+ canUpload: boolean;
234
235
  scopeKey: SheetsScopeKey;
235
236
  }
236
237
  interface SheetsScopeKey {
@@ -241,4 +242,4 @@ interface SheetsScopeKey {
241
242
  declare const SheetsContext: react.Context<SheetsContextValue | null>;
242
243
  declare function useSheetsContext(): SheetsContextValue;
243
244
 
244
- export { type AdapterListQuery as A, type CellProps as C, type SheetsExecuteFn as S, type SheetsUploadFn as a, type SheetsConfig as b, type CellTypeDefinition as c, type SheetsCellRenderContext as d, type CellTypeMatchInput as e, type SheetsScopeKey as f, type SheetsBackendAdapter as g, type AdapterListResult as h, type AdapterPageInfo as i, type AdapterTableContext as j, type CellColumnDescriptor as k, type CellTypePlugin as l, type SheetsAuthEmbedded as m, type SheetsAuthStandalone as n, SheetsContext as o, type SheetsContextValue as p, type SheetsLogger as q, createSheetsExecute as r, createSheetsUpload as s, defineCellType as t, useSheetsContext as u };
245
+ export { type AdapterListQuery as A, type CellProps as C, type SheetsExecuteFn as S, type SheetsUploadFn as a, type SheetsConfig as b, type CellTypeDefinition as c, type SheetsCellRenderContext as d, type CellTypeMatchInput as e, type SheetsScopeKey as f, type SheetsFileValue as g, type SheetsBackendAdapter as h, type AdapterListResult as i, type AdapterPageInfo as j, type AdapterTableContext as k, type CellColumnDescriptor as l, type CellTypePlugin as m, type SheetsAuthEmbedded as n, type SheetsAuthStandalone as o, SheetsContext as p, type SheetsContextValue as q, type SheetsLogger as r, type SheetsUploadResult as s, createSheetsExecute as t, createSheetsUpload as u, defineCellType as v, useSheetsContext as w };
@@ -2,19 +2,26 @@ import * as react from 'react';
2
2
  import { QueryClient } from '@tanstack/react-query';
3
3
  import { DocumentNode } from 'graphql';
4
4
  import { TypedDocumentString, FieldSelection, CleanTable, MetaQuery, MutationOptions } from '@constructive-io/data';
5
- import { b as CellType, S as SheetsCell, C as CellCreationMetadata, c as CellCategory, E as EditorProps } from './grid-cell-types-Pbe2m2tE.cjs';
5
+ import { b as CellType, S as SheetsCell, C as CellCreationMetadata, c as CellCategory, E as EditorProps } from './grid-cell-types-C2-ocDS7.cjs';
6
6
 
7
7
  type ExecutableDocument = TypedDocumentString<any, any> | DocumentNode | string | unknown;
8
8
  type SheetsExecuteFn = <T = unknown>(document: ExecutableDocument, variables?: Record<string, unknown>) => Promise<T>;
9
- /**
10
- * Result of an upload through the seam. `url` is the only guaranteed field;
11
- * the REST upload endpoint also returns `{ filename, mime, size }` (and may
12
- * return server-internal extras). Keeping it open-ended lets callers read the
13
- * richer metadata while a bare `{ url }` (e.g. the mock) still satisfies it.
14
- */
15
- type SheetsUploadResult = {
16
- url: string;
17
- } & Record<string, unknown>;
9
+ /** Durable file metadata for image and upload columns. */
10
+ interface SheetsFileValue {
11
+ id: string;
12
+ key: string;
13
+ bucket_id: string;
14
+ mime: string;
15
+ size: number;
16
+ filename: string;
17
+ /** Public URL supplied by storage, when available. */
18
+ url?: string;
19
+ }
20
+ interface SheetsUploadResult {
21
+ file: SheetsFileValue;
22
+ /** Optional download URL for immediate use. It can expire. */
23
+ url?: string;
24
+ }
18
25
  /**
19
26
  * Optional upload metadata carried through the seam (third arg). Lets an
20
27
  * injected `executeUpload` see the destination field/row and report progress.
@@ -32,25 +39,7 @@ interface SheetsUploadOptions {
32
39
  }
33
40
  type SheetsUploadFn = (file: File, path?: string, options?: SheetsUploadOptions) => Promise<SheetsUploadResult>;
34
41
  declare function createSheetsExecute(config: SheetsConfig, getToken: () => string | null): SheetsExecuteFn;
35
- /**
36
- * Presigned-URL cell-upload seam.
37
- *
38
- * Replaces the legacy multipart `<endpoint>/upload` POST entirely. The flow:
39
- * 1. Read + SHA-256 hash the file bytes (Web Crypto)
40
- * 2. Discover (cached per endpoint) the upload op + downloadUrl-by-id field
41
- * via GraphQL introspection — the root `upload<Type>File` mutation, matched
42
- * by FIELD/TYPE SHAPE (LOCKED: no hardcoded names)
43
- * 3. Call the upload op with input `{ bucketKey, contentHash, contentType,
44
- * size, filename }` — NO `ownerId` (app-scoped buckets have no owner_id)
45
- * 4. If `uploadUrl` is non-null, PUT the raw bytes to it with ONLY the signed
46
- * `Content-Type` header (NO Authorization). Skipped when `deduplicated`.
47
- * 5. Resolve the stable public `downloadUrl` for the returned fileId.
48
- *
49
- * Returns `{ url, filename, mime, size, key, fileId }` where `url` is the stable
50
- * download URL — the same cell value shape callers/Step-2 already consume.
51
- *
52
- * `path` is ignored (content-addressed buckets key on `contentHash`).
53
- */
42
+ /** Creates an uploader for storage. Direct callers may use the supplied endpoint as storage. */
54
43
  declare function createSheetsUpload(config: SheetsConfig, getToken: () => string | null): SheetsUploadFn;
55
44
 
56
45
  /**
@@ -86,6 +75,7 @@ interface CellProps {
86
75
  isEditing: boolean;
87
76
  onStartEdit: () => void;
88
77
  disabled: boolean;
78
+ readOnlyReason?: string;
89
79
  }
90
80
 
91
81
  /** Schema-only inputs used to DETECT a cell type. Never the runtime value. */
@@ -190,6 +180,10 @@ interface SheetsAuthEmbedded {
190
180
  interface SheetsAuthStandalone {
191
181
  mode: 'standalone';
192
182
  }
183
+ interface SheetsStorageTransport {
184
+ endpoint: string;
185
+ execute: SheetsExecuteFn;
186
+ }
193
187
  interface SheetsConfig {
194
188
  /** Data endpoint (app-public GraphQL) */
195
189
  endpoint: string;
@@ -207,7 +201,12 @@ interface SheetsConfig {
207
201
  execute?: SheetsExecuteFn;
208
202
  /** Optional: inject custom upload function */
209
203
  executeUpload?: SheetsUploadFn;
210
- /** Optional upload settings. `bucketKey` defaults to "public". */
204
+ /** Storage endpoint for media uploads and download URL lookups. */
205
+ storage?: {
206
+ endpoint: string;
207
+ execute?: SheetsExecuteFn;
208
+ };
209
+ /** Explicit bucket override. Omit to use the tenant's public default. */
211
210
  upload?: {
212
211
  bucketKey?: string;
213
212
  };
@@ -231,6 +230,8 @@ interface SheetsContextValue {
231
230
  config: SheetsConfig;
232
231
  execute: SheetsExecuteFn;
233
232
  executeUpload: SheetsUploadFn;
233
+ storage?: SheetsStorageTransport;
234
+ canUpload: boolean;
234
235
  scopeKey: SheetsScopeKey;
235
236
  }
236
237
  interface SheetsScopeKey {
@@ -241,4 +242,4 @@ interface SheetsScopeKey {
241
242
  declare const SheetsContext: react.Context<SheetsContextValue | null>;
242
243
  declare function useSheetsContext(): SheetsContextValue;
243
244
 
244
- export { type AdapterListQuery as A, type CellProps as C, type SheetsExecuteFn as S, type SheetsUploadFn as a, type SheetsConfig as b, type CellTypeDefinition as c, type SheetsCellRenderContext as d, type CellTypeMatchInput as e, type SheetsScopeKey as f, type SheetsBackendAdapter as g, type AdapterListResult as h, type AdapterPageInfo as i, type AdapterTableContext as j, type CellColumnDescriptor as k, type CellTypePlugin as l, type SheetsAuthEmbedded as m, type SheetsAuthStandalone as n, SheetsContext as o, type SheetsContextValue as p, type SheetsLogger as q, createSheetsExecute as r, createSheetsUpload as s, defineCellType as t, useSheetsContext as u };
245
+ export { type AdapterListQuery as A, type CellProps as C, type SheetsExecuteFn as S, type SheetsUploadFn as a, type SheetsConfig as b, type CellTypeDefinition as c, type SheetsCellRenderContext as d, type CellTypeMatchInput as e, type SheetsScopeKey as f, type SheetsFileValue as g, type SheetsBackendAdapter as h, type AdapterListResult as i, type AdapterPageInfo as j, type AdapterTableContext as k, type CellColumnDescriptor as l, type CellTypePlugin as m, type SheetsAuthEmbedded as n, type SheetsAuthStandalone as o, SheetsContext as p, type SheetsContextValue as q, type SheetsLogger as r, type SheetsUploadResult as s, createSheetsExecute as t, createSheetsUpload as u, defineCellType as v, useSheetsContext as w };
package/dist/testing.cjs CHANGED
@@ -62,9 +62,14 @@ async function sha256HexFromBuffer(buffer) {
62
62
  }
63
63
  return hex;
64
64
  }
65
- var capabilityCache = /* @__PURE__ */ new Map();
66
- function discoverUploadCapability(endpoint, execute) {
67
- const cached = capabilityCache.get(endpoint);
65
+ var capabilityCache = /* @__PURE__ */ new WeakMap();
66
+ async function discoverStorageCapabilities(endpoint, execute) {
67
+ let endpoints = capabilityCache.get(execute);
68
+ if (!endpoints) {
69
+ endpoints = /* @__PURE__ */ new Map();
70
+ capabilityCache.set(execute, endpoints);
71
+ }
72
+ const cached = endpoints.get(endpoint);
68
73
  if (cached) return cached;
69
74
  const promise = (async () => {
70
75
  const data = await execute((0, import_graphql.getIntrospectionQuery)());
@@ -72,12 +77,21 @@ function discoverUploadCapability(endpoint, execute) {
72
77
  if (!schema) {
73
78
  throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
74
79
  }
75
- return resolveUploadCapability(schema);
80
+ return resolveStorageCapabilities(schema);
76
81
  })();
77
- promise.catch(() => capabilityCache.delete(endpoint));
78
- capabilityCache.set(endpoint, promise);
82
+ promise.catch(() => endpoints.delete(endpoint));
83
+ endpoints.set(endpoint, promise);
79
84
  return promise;
80
85
  }
86
+ async function discoverUploadCapability(endpoint, execute) {
87
+ const { upload } = await discoverStorageCapabilities(endpoint, execute);
88
+ if (!upload) capabilityCache.get(execute)?.delete(endpoint);
89
+ return requireUploadCapability(upload);
90
+ }
91
+ function requireUploadCapability(upload) {
92
+ if (!upload) throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
93
+ return upload;
94
+ }
81
95
  function namedTypeName(ref) {
82
96
  let cur = ref;
83
97
  while (cur && (cur.kind === "NON_NULL" || cur.kind === "LIST")) {
@@ -93,7 +107,7 @@ function isListTypeRef(ref) {
93
107
  return cur?.kind === "LIST";
94
108
  }
95
109
  var PK_FIELD_NAME = "id";
96
- function resolveUploadCapability(schema) {
110
+ function resolveStorageCapabilities(schema) {
97
111
  const typeByName = /* @__PURE__ */ new Map();
98
112
  for (const t of schema.types) {
99
113
  if (t.name) typeByName.set(t.name, t);
@@ -112,7 +126,7 @@ function resolveUploadCapability(schema) {
112
126
  const present = new Set(t.inputFields.map((f) => f.name));
113
127
  return names.every((n) => present.has(n));
114
128
  };
115
- const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "deduplicated"];
129
+ const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "key", "deduplicated"];
116
130
  const INPUT_FIELDS = ["contentHash", "bucketKey", "contentType", "size"];
117
131
  const mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;
118
132
  const queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;
@@ -122,80 +136,69 @@ function resolveUploadCapability(schema) {
122
136
  if (!inputArg) continue;
123
137
  const inputTypeName = namedTypeName(inputArg.type);
124
138
  const payloadTypeName = namedTypeName(field.type);
125
- if (inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
126
- upload = { uploadFieldName: field.name, inputTypeName };
127
- break;
139
+ if (inputTypeName && inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
140
+ const payloadFields = typeByName.get(payloadTypeName ?? "")?.fields;
141
+ const candidate = {
142
+ uploadFieldName: field.name,
143
+ inputTypeName,
144
+ hasFileProjection: payloadFields?.some(
145
+ (f) => f.name === "file" && !isListTypeRef(f.type) && namedTypeName(f.type) === "JSON"
146
+ ) ?? false
147
+ };
148
+ if (field.name === "uploadAppFile") {
149
+ upload = candidate;
150
+ break;
151
+ }
152
+ upload ??= candidate;
128
153
  }
129
154
  }
130
- if (!upload) {
131
- throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
132
- }
133
- const downloadById = resolveDownloadByIdField(schema, typeByName, queryType, upload.uploadFieldName);
134
- const uploadedTypeName = upload.uploadFieldName.replace(/^upload/, "");
135
- const fileTypeName = typeByName.has(uploadedTypeName) ? uploadedTypeName : downloadById.fileTypeName;
136
- let remove = {};
137
- for (const field of mutationType?.fields ?? []) {
138
- const inputArg = field.args.find((a) => a.name === "input");
139
- const inputTypeName = namedTypeName(inputArg?.type);
140
- const inputFields = inputTypeName ? typeByName.get(inputTypeName)?.inputFields : null;
141
- if (!inputTypeName || !inputFields?.some((f) => f.name === PK_FIELD_NAME)) continue;
142
- if (!inputFields.every((f) => f.name === PK_FIELD_NAME || f.name === "clientMutationId")) continue;
143
- const payload = typeByName.get(namedTypeName(field.type) ?? "");
144
- if (payload?.fields?.some((f) => namedTypeName(f.type) === fileTypeName)) {
145
- remove = { deleteFieldName: field.name, deleteInputTypeName: inputTypeName };
146
- break;
155
+ const fileTypes = /* @__PURE__ */ new Set();
156
+ for (const t of schema.types) {
157
+ if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
158
+ fileTypes.add(t.name);
147
159
  }
148
160
  }
161
+ const uploadType = upload?.uploadFieldName.replace(/^upload/, "") ?? "AppFile";
162
+ const uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);
163
+ const preferredPreviewType = fileTypes.has("AppFile") ? "AppFile" : uploadType;
164
+ const previewType = fileTypes.has(preferredPreviewType) ? preferredPreviewType : uploadDownload?.fileTypeName ?? preferredPreviewType;
165
+ const download = previewType === uploadType ? uploadDownload : resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);
166
+ const batch = resolveConnectionDownloadField(typeByName, queryType, fileTypes, previewType, true);
149
167
  return {
150
- ...upload,
151
- ...downloadById,
152
- ...remove
168
+ upload: upload ? { ...upload, download: uploadDownload } : null,
169
+ download,
170
+ batch
153
171
  };
154
172
  }
155
- async function deleteUploadedFileRow(execute, cap, fileId) {
156
- if (!cap.deleteFieldName || !cap.deleteInputTypeName) return;
157
- const mutation = `
158
- mutation SheetsUploadCleanup($input: ${cap.deleteInputTypeName}!) {
159
- ${cap.deleteFieldName}(input: $input) { __typename }
160
- }
161
- `.trim();
162
- try {
163
- await execute(mutation, { input: { [PK_FIELD_NAME]: fileId } });
164
- } catch {
165
- }
166
- }
167
- function resolveDownloadByIdField(schema, typeByName, queryType, uploadFieldName) {
168
- const fileTypesWithDownloadUrl = /* @__PURE__ */ new Set();
169
- for (const t of schema.types) {
170
- if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
171
- fileTypesWithDownloadUrl.add(t.name);
172
- }
173
- }
173
+ function resolveDownloadByIdField(typeByName, queryType, fileTypesWithDownloadUrl, preferred) {
174
+ let singular = null;
174
175
  for (const field of queryType?.fields ?? []) {
175
176
  const returnTypeName = namedTypeName(field.type);
176
177
  if (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;
177
178
  if (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {
178
- return {
179
+ const candidate = {
179
180
  fileByIdField: field.name,
180
181
  fileByIdArgName: "id",
181
182
  fileTypeName: returnTypeName,
182
183
  idScalarName: namedTypeName(field.args[0].type) ?? void 0
183
184
  };
185
+ if (returnTypeName === preferred) return candidate;
186
+ singular ??= candidate;
184
187
  }
185
188
  }
186
- const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName);
187
- if (connection) return connection;
189
+ const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);
190
+ if (connection?.fileTypeName === preferred) return connection;
191
+ if (singular || connection) return singular ?? connection;
188
192
  const nodeField = queryType?.fields?.find(
189
193
  (f) => f.name === "node" && f.args.some((a) => a.name === "nodeId")
190
194
  );
191
195
  if (nodeField && fileTypesWithDownloadUrl.size > 0) {
192
- const preferred = uploadFieldName.replace(/^upload/, "");
193
196
  const fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0];
194
197
  return { fileByIdField: "node", fileByIdArgName: "nodeId", fileTypeName };
195
198
  }
196
- throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
199
+ return null;
197
200
  }
198
- function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName) {
201
+ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred, batch = false) {
199
202
  const EQUALITY_OPERATORS = ["equalTo", "eq"];
200
203
  const candidates = [];
201
204
  for (const field of queryType?.fields ?? []) {
@@ -210,6 +213,8 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
210
213
  });
211
214
  if (!nodesField) continue;
212
215
  const fileTypeName = namedTypeName(nodesField.type);
216
+ if (batch && (fileTypeName !== preferred || !typeByName.get(fileTypeName)?.fields?.some((field2) => field2.name === PK_FIELD_NAME))) continue;
217
+ const connectionHasFirst = field.args.some((arg) => arg.name === "first");
213
218
  for (const arg of field.args) {
214
219
  const filterTypeName = namedTypeName(arg.type);
215
220
  const filterType = filterTypeName ? typeByName.get(filterTypeName) : null;
@@ -219,7 +224,7 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
219
224
  const idFieldTypeName = namedTypeName(idField.type);
220
225
  const idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;
221
226
  if (idFieldType?.kind === "INPUT_OBJECT" && idFieldType.inputFields) {
222
- const opField = EQUALITY_OPERATORS.map(
227
+ const opField = batch ? idFieldType.inputFields.find((f) => f.name === "in" && isListTypeRef(f.type)) : EQUALITY_OPERATORS.map(
223
228
  (op) => idFieldType.inputFields.find((f) => f.name === op)
224
229
  ).find((f) => f != null);
225
230
  if (opField) {
@@ -231,13 +236,14 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
231
236
  connectionFilterArgName: arg.name,
232
237
  connectionIdField: idField.name,
233
238
  connectionIdOperator: opField.name,
234
- connectionNodesField: nodesField.name
239
+ connectionNodesField: nodesField.name,
240
+ connectionHasFirst
235
241
  });
236
242
  break;
237
243
  }
238
244
  continue;
239
245
  }
240
- if (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName) {
246
+ if (!batch && (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName)) {
241
247
  candidates.push({
242
248
  fileByIdField: field.name,
243
249
  fileByIdArgName: "connection",
@@ -245,14 +251,14 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
245
251
  idScalarName: idFieldTypeName ?? void 0,
246
252
  connectionFilterArgName: arg.name,
247
253
  connectionIdField: idField.name,
248
- connectionNodesField: nodesField.name
254
+ connectionNodesField: nodesField.name,
255
+ connectionHasFirst
249
256
  });
250
257
  break;
251
258
  }
252
259
  }
253
260
  }
254
261
  if (candidates.length === 0) return null;
255
- const preferred = uploadFieldName.replace(/^upload/, "");
256
262
  return candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];
257
263
  }
258
264
  async function callUploadOp(execute, cap, input) {
@@ -263,12 +269,13 @@ async function callUploadOp(execute, cap, input) {
263
269
  fileId
264
270
  key
265
271
  deduplicated
272
+ file
266
273
  }
267
274
  }
268
275
  `.trim();
269
276
  const data = await execute(mutation, {
270
277
  input: {
271
- bucketKey: input.bucketKey,
278
+ ...input.bucketKey === void 0 ? { isPublic: true } : { bucketKey: input.bucketKey },
272
279
  contentHash: input.contentHash,
273
280
  contentType: input.contentType,
274
281
  size: input.size,
@@ -279,6 +286,10 @@ async function callUploadOp(execute, cap, input) {
279
286
  if (!payload) {
280
287
  throw import_data.createError.badRequest("Upload failed: no payload returned from upload mutation.");
281
288
  }
289
+ const file = payload.file;
290
+ if (!file || typeof file.id !== "string" || typeof file.key !== "string" || typeof file.bucket_id !== "string" || typeof file.mime !== "string" || typeof file.size !== "number") {
291
+ throw import_data.createError.badRequest("Upload failed: server returned an invalid file projection.");
292
+ }
282
293
  return payload;
283
294
  }
284
295
  var STORAGE_UPLOAD_BLOCKED_MESSAGE = "Upload failed: the storage server didn't accept the upload from this site. Check the bucket's allowed origins (CORS) and your connection.";
@@ -367,7 +378,7 @@ async function fetchDownloadUrl(execute, cap, fileId) {
367
378
  const filterLiteral = cap.connectionIdOperator ? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }` : `{ ${idField}: $id }`;
368
379
  const query2 = `
369
380
  query SheetsDownloadUrl($id: ${idScalar2}!) {
370
- ${cap.fileByIdField}(${filterArg}: ${filterLiteral}, first: 1) {
381
+ ${cap.fileByIdField}(${filterArg}: ${filterLiteral}${cap.connectionHasFirst ? ", first: 1" : ""}) {
371
382
  ${nodesField} {
372
383
  downloadUrl
373
384
  }
@@ -491,17 +502,26 @@ function createSheetsExecute(config, getToken) {
491
502
  return result.data;
492
503
  };
493
504
  }
494
- function createSheetsUpload(config, getToken) {
495
- const execute = config.execute ?? createSheetsExecute(config, getToken);
505
+ function resolveStorageTransport(config, getToken) {
506
+ const endpoint = config.storage?.endpoint;
507
+ if (!endpoint) return void 0;
508
+ return {
509
+ endpoint,
510
+ execute: config.storage?.execute ?? createSheetsExecute({ ...config, endpoint }, getToken)
511
+ };
512
+ }
513
+ function createPresignedSheetsUpload({ endpoint, execute }, bucketKey) {
496
514
  return async (file, _path, options) => {
497
- if (!config.endpoint) {
515
+ if (!endpoint) {
498
516
  throw import_data2.createError.badRequest("No GraphQL endpoint configured.");
499
517
  }
500
- const bucketKey = config.upload?.bucketKey ?? "public";
518
+ const cap = await discoverUploadCapability(endpoint, execute);
519
+ if (!cap.hasFileProjection) {
520
+ throw import_data2.createError.badRequest("Uploads require a storage mutation that returns a file projection.");
521
+ }
501
522
  const contentType = file.type || "application/octet-stream";
502
523
  const buffer = await file.arrayBuffer();
503
524
  const contentHash = await sha256HexFromBuffer(buffer);
504
- const cap = await discoverUploadCapability(config.endpoint, execute);
505
525
  const payload = await callUploadOp(execute, cap, {
506
526
  bucketKey,
507
527
  contentHash,
@@ -513,24 +533,19 @@ function createSheetsUpload(config, getToken) {
513
533
  if (!payload.uploadUrl) {
514
534
  throw import_data2.createError.badRequest("Upload failed: server returned no uploadUrl for a non-deduplicated file.");
515
535
  }
516
- try {
517
- await presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);
518
- } catch (error) {
519
- await deleteUploadedFileRow(execute, cap, payload.fileId);
520
- throw error;
521
- }
536
+ await presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);
522
537
  } else {
523
538
  options?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });
524
539
  }
525
- const url = await fetchDownloadUrl(execute, cap, payload.fileId);
526
- return {
527
- url,
528
- filename: file.name,
529
- mime: file.type,
530
- size: file.size,
531
- key: payload.key,
532
- fileId: payload.fileId
540
+ const result = {
541
+ file: { ...payload.file, filename: payload.file.filename ?? file.name }
533
542
  };
543
+ if (!cap.download) return result;
544
+ try {
545
+ return { ...result, url: await fetchDownloadUrl(execute, cap.download, payload.fileId) };
546
+ } catch {
547
+ return result;
548
+ }
534
549
  };
535
550
  }
536
551
 
@@ -1141,6 +1156,7 @@ var sheetsQueryKeys = {
1141
1156
  root: ["sheets"],
1142
1157
  scope: (scope) => ["sheets", scope],
1143
1158
  meta: (scope) => [...sheetsQueryKeys.scope(scope), "meta"],
1159
+ mediaUrl: (scope, endpoint, id) => [...sheetsQueryKeys.scope(scope), "media-url", endpoint, id],
1144
1160
  typeFields: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "type-fields", typeName],
1145
1161
  enumValues: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "enum-values", typeName],
1146
1162
  relations: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "relations", tableName],
@@ -1156,6 +1172,9 @@ var sheetsQueryKeys = {
1156
1172
 
1157
1173
  // src/context/sheets-provider.tsx
1158
1174
  var import_jsx_runtime = require("react/jsx-runtime");
1175
+ var unavailableUpload = async () => {
1176
+ throw new Error("Uploads need a storage endpoint");
1177
+ };
1159
1178
  function SheetsProvider({ config, children }) {
1160
1179
  const providerInstanceId = (0, import_react3.useId)();
1161
1180
  const storeRef = (0, import_react3.useRef)(null);
@@ -1214,10 +1233,13 @@ function SheetsProvider({ config, children }) {
1214
1233
  if (config.execute) return config.execute;
1215
1234
  return createSheetsExecute(config, getToken);
1216
1235
  }, [config, getToken]);
1236
+ const storage = (0, import_react3.useMemo)(() => resolveStorageTransport(config, getToken), [config, getToken]);
1237
+ const bucketKey = config.upload?.bucketKey;
1217
1238
  const executeUpload = (0, import_react3.useMemo)(() => {
1218
1239
  if (config.executeUpload) return config.executeUpload;
1219
- return createSheetsUpload(config, getToken);
1220
- }, [config, getToken]);
1240
+ return storage ? createPresignedSheetsUpload(storage, bucketKey) : unavailableUpload;
1241
+ }, [config.executeUpload, storage, bucketKey]);
1242
+ const canUpload = Boolean(config.executeUpload || storage);
1221
1243
  const configuredIdentityKey = config.auth.mode === "embedded" ? config.auth.getIdentityKey?.() ?? null : standaloneIdentityKey;
1222
1244
  const activeToken = config.auth.mode === "embedded" ? config.auth.getToken() : standaloneAccessToken;
1223
1245
  const authGenerationRef = (0, import_react3.useRef)({ mode: config.auth.mode, token: activeToken, generation: 0 });
@@ -1243,8 +1265,8 @@ function SheetsProvider({ config, children }) {
1243
1265
  };
1244
1266
  }, [queryClient, scopeKey]);
1245
1267
  const contextValue = (0, import_react3.useMemo)(
1246
- () => ({ config, execute, executeUpload, scopeKey }),
1247
- [config, execute, executeUpload, scopeKey]
1268
+ () => ({ config, execute, executeUpload, storage, canUpload, scopeKey }),
1269
+ [config, execute, executeUpload, storage, canUpload, scopeKey]
1248
1270
  );
1249
1271
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_query.QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsStoreContext.Provider, { value: store, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsContext.Provider, { value: contextValue, children }) }) });
1250
1272
  }
@@ -1457,7 +1479,19 @@ function createMockExecute(opts) {
1457
1479
  },
1458
1480
  at: Date.now()
1459
1481
  });
1460
- return { url: "mock://uploaded/" + name };
1482
+ const url = "mock://uploaded/" + name;
1483
+ return {
1484
+ file: {
1485
+ id: "mock-file-" + mutations.length,
1486
+ key: name,
1487
+ bucket_id: "mock-bucket",
1488
+ filename: name,
1489
+ mime: file.type || "application/octet-stream",
1490
+ size: file.size,
1491
+ url
1492
+ },
1493
+ url
1494
+ };
1461
1495
  };
1462
1496
  function reset() {
1463
1497
  mutations.length = 0;