@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
@@ -15,9 +15,14 @@ async function sha256HexFromBuffer(buffer) {
15
15
  }
16
16
  return hex;
17
17
  }
18
- var capabilityCache = /* @__PURE__ */ new Map();
19
- function discoverUploadCapability(endpoint, execute) {
20
- const cached = capabilityCache.get(endpoint);
18
+ var capabilityCache = /* @__PURE__ */ new WeakMap();
19
+ async function discoverStorageCapabilities(endpoint, execute) {
20
+ let endpoints = capabilityCache.get(execute);
21
+ if (!endpoints) {
22
+ endpoints = /* @__PURE__ */ new Map();
23
+ capabilityCache.set(execute, endpoints);
24
+ }
25
+ const cached = endpoints.get(endpoint);
21
26
  if (cached) return cached;
22
27
  const promise = (async () => {
23
28
  const data = await execute(getIntrospectionQuery());
@@ -25,12 +30,21 @@ function discoverUploadCapability(endpoint, execute) {
25
30
  if (!schema) {
26
31
  throw createError.badRequest("Uploads are not enabled for this endpoint.");
27
32
  }
28
- return resolveUploadCapability(schema);
33
+ return resolveStorageCapabilities(schema);
29
34
  })();
30
- promise.catch(() => capabilityCache.delete(endpoint));
31
- capabilityCache.set(endpoint, promise);
35
+ promise.catch(() => endpoints.delete(endpoint));
36
+ endpoints.set(endpoint, promise);
32
37
  return promise;
33
38
  }
39
+ async function discoverUploadCapability(endpoint, execute) {
40
+ const { upload } = await discoverStorageCapabilities(endpoint, execute);
41
+ if (!upload) capabilityCache.get(execute)?.delete(endpoint);
42
+ return requireUploadCapability(upload);
43
+ }
44
+ function requireUploadCapability(upload) {
45
+ if (!upload) throw createError.badRequest("Uploads are not enabled for this endpoint.");
46
+ return upload;
47
+ }
34
48
  function namedTypeName(ref) {
35
49
  let cur = ref;
36
50
  while (cur && (cur.kind === "NON_NULL" || cur.kind === "LIST")) {
@@ -46,7 +60,7 @@ function isListTypeRef(ref) {
46
60
  return cur?.kind === "LIST";
47
61
  }
48
62
  var PK_FIELD_NAME = "id";
49
- function resolveUploadCapability(schema) {
63
+ function resolveStorageCapabilities(schema) {
50
64
  const typeByName = /* @__PURE__ */ new Map();
51
65
  for (const t of schema.types) {
52
66
  if (t.name) typeByName.set(t.name, t);
@@ -65,7 +79,7 @@ function resolveUploadCapability(schema) {
65
79
  const present = new Set(t.inputFields.map((f) => f.name));
66
80
  return names.every((n) => present.has(n));
67
81
  };
68
- const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "deduplicated"];
82
+ const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "key", "deduplicated"];
69
83
  const INPUT_FIELDS = ["contentHash", "bucketKey", "contentType", "size"];
70
84
  const mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;
71
85
  const queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;
@@ -75,80 +89,69 @@ function resolveUploadCapability(schema) {
75
89
  if (!inputArg) continue;
76
90
  const inputTypeName = namedTypeName(inputArg.type);
77
91
  const payloadTypeName = namedTypeName(field.type);
78
- if (inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
79
- upload = { uploadFieldName: field.name, inputTypeName };
80
- break;
92
+ if (inputTypeName && inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
93
+ const payloadFields = typeByName.get(payloadTypeName ?? "")?.fields;
94
+ const candidate = {
95
+ uploadFieldName: field.name,
96
+ inputTypeName,
97
+ hasFileProjection: payloadFields?.some(
98
+ (f) => f.name === "file" && !isListTypeRef(f.type) && namedTypeName(f.type) === "JSON"
99
+ ) ?? false
100
+ };
101
+ if (field.name === "uploadAppFile") {
102
+ upload = candidate;
103
+ break;
104
+ }
105
+ upload ??= candidate;
81
106
  }
82
107
  }
83
- if (!upload) {
84
- throw createError.badRequest("Uploads are not enabled for this endpoint.");
85
- }
86
- const downloadById = resolveDownloadByIdField(schema, typeByName, queryType, upload.uploadFieldName);
87
- const uploadedTypeName = upload.uploadFieldName.replace(/^upload/, "");
88
- const fileTypeName = typeByName.has(uploadedTypeName) ? uploadedTypeName : downloadById.fileTypeName;
89
- let remove = {};
90
- for (const field of mutationType?.fields ?? []) {
91
- const inputArg = field.args.find((a) => a.name === "input");
92
- const inputTypeName = namedTypeName(inputArg?.type);
93
- const inputFields = inputTypeName ? typeByName.get(inputTypeName)?.inputFields : null;
94
- if (!inputTypeName || !inputFields?.some((f) => f.name === PK_FIELD_NAME)) continue;
95
- if (!inputFields.every((f) => f.name === PK_FIELD_NAME || f.name === "clientMutationId")) continue;
96
- const payload = typeByName.get(namedTypeName(field.type) ?? "");
97
- if (payload?.fields?.some((f) => namedTypeName(f.type) === fileTypeName)) {
98
- remove = { deleteFieldName: field.name, deleteInputTypeName: inputTypeName };
99
- break;
108
+ const fileTypes = /* @__PURE__ */ new Set();
109
+ for (const t of schema.types) {
110
+ if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
111
+ fileTypes.add(t.name);
100
112
  }
101
113
  }
114
+ const uploadType = upload?.uploadFieldName.replace(/^upload/, "") ?? "AppFile";
115
+ const uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);
116
+ const preferredPreviewType = fileTypes.has("AppFile") ? "AppFile" : uploadType;
117
+ const previewType = fileTypes.has(preferredPreviewType) ? preferredPreviewType : uploadDownload?.fileTypeName ?? preferredPreviewType;
118
+ const download = previewType === uploadType ? uploadDownload : resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);
119
+ const batch = resolveConnectionDownloadField(typeByName, queryType, fileTypes, previewType, true);
102
120
  return {
103
- ...upload,
104
- ...downloadById,
105
- ...remove
121
+ upload: upload ? { ...upload, download: uploadDownload } : null,
122
+ download,
123
+ batch
106
124
  };
107
125
  }
108
- async function deleteUploadedFileRow(execute, cap, fileId) {
109
- if (!cap.deleteFieldName || !cap.deleteInputTypeName) return;
110
- const mutation = `
111
- mutation SheetsUploadCleanup($input: ${cap.deleteInputTypeName}!) {
112
- ${cap.deleteFieldName}(input: $input) { __typename }
113
- }
114
- `.trim();
115
- try {
116
- await execute(mutation, { input: { [PK_FIELD_NAME]: fileId } });
117
- } catch {
118
- }
119
- }
120
- function resolveDownloadByIdField(schema, typeByName, queryType, uploadFieldName) {
121
- const fileTypesWithDownloadUrl = /* @__PURE__ */ new Set();
122
- for (const t of schema.types) {
123
- if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
124
- fileTypesWithDownloadUrl.add(t.name);
125
- }
126
- }
126
+ function resolveDownloadByIdField(typeByName, queryType, fileTypesWithDownloadUrl, preferred) {
127
+ let singular = null;
127
128
  for (const field of queryType?.fields ?? []) {
128
129
  const returnTypeName = namedTypeName(field.type);
129
130
  if (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;
130
131
  if (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {
131
- return {
132
+ const candidate = {
132
133
  fileByIdField: field.name,
133
134
  fileByIdArgName: "id",
134
135
  fileTypeName: returnTypeName,
135
136
  idScalarName: namedTypeName(field.args[0].type) ?? void 0
136
137
  };
138
+ if (returnTypeName === preferred) return candidate;
139
+ singular ??= candidate;
137
140
  }
138
141
  }
139
- const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName);
140
- if (connection) return connection;
142
+ const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);
143
+ if (connection?.fileTypeName === preferred) return connection;
144
+ if (singular || connection) return singular ?? connection;
141
145
  const nodeField = queryType?.fields?.find(
142
146
  (f) => f.name === "node" && f.args.some((a) => a.name === "nodeId")
143
147
  );
144
148
  if (nodeField && fileTypesWithDownloadUrl.size > 0) {
145
- const preferred = uploadFieldName.replace(/^upload/, "");
146
149
  const fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0];
147
150
  return { fileByIdField: "node", fileByIdArgName: "nodeId", fileTypeName };
148
151
  }
149
- throw createError.badRequest("Uploads are not enabled for this endpoint.");
152
+ return null;
150
153
  }
151
- function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName) {
154
+ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred, batch = false) {
152
155
  const EQUALITY_OPERATORS = ["equalTo", "eq"];
153
156
  const candidates = [];
154
157
  for (const field of queryType?.fields ?? []) {
@@ -163,6 +166,8 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
163
166
  });
164
167
  if (!nodesField) continue;
165
168
  const fileTypeName = namedTypeName(nodesField.type);
169
+ if (batch && (fileTypeName !== preferred || !typeByName.get(fileTypeName)?.fields?.some((field2) => field2.name === PK_FIELD_NAME))) continue;
170
+ const connectionHasFirst = field.args.some((arg) => arg.name === "first");
166
171
  for (const arg of field.args) {
167
172
  const filterTypeName = namedTypeName(arg.type);
168
173
  const filterType = filterTypeName ? typeByName.get(filterTypeName) : null;
@@ -172,7 +177,7 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
172
177
  const idFieldTypeName = namedTypeName(idField.type);
173
178
  const idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;
174
179
  if (idFieldType?.kind === "INPUT_OBJECT" && idFieldType.inputFields) {
175
- const opField = EQUALITY_OPERATORS.map(
180
+ const opField = batch ? idFieldType.inputFields.find((f) => f.name === "in" && isListTypeRef(f.type)) : EQUALITY_OPERATORS.map(
176
181
  (op) => idFieldType.inputFields.find((f) => f.name === op)
177
182
  ).find((f) => f != null);
178
183
  if (opField) {
@@ -184,13 +189,14 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
184
189
  connectionFilterArgName: arg.name,
185
190
  connectionIdField: idField.name,
186
191
  connectionIdOperator: opField.name,
187
- connectionNodesField: nodesField.name
192
+ connectionNodesField: nodesField.name,
193
+ connectionHasFirst
188
194
  });
189
195
  break;
190
196
  }
191
197
  continue;
192
198
  }
193
- if (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName) {
199
+ if (!batch && (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName)) {
194
200
  candidates.push({
195
201
  fileByIdField: field.name,
196
202
  fileByIdArgName: "connection",
@@ -198,14 +204,14 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
198
204
  idScalarName: idFieldTypeName ?? void 0,
199
205
  connectionFilterArgName: arg.name,
200
206
  connectionIdField: idField.name,
201
- connectionNodesField: nodesField.name
207
+ connectionNodesField: nodesField.name,
208
+ connectionHasFirst
202
209
  });
203
210
  break;
204
211
  }
205
212
  }
206
213
  }
207
214
  if (candidates.length === 0) return null;
208
- const preferred = uploadFieldName.replace(/^upload/, "");
209
215
  return candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];
210
216
  }
211
217
  async function callUploadOp(execute, cap, input) {
@@ -216,12 +222,13 @@ async function callUploadOp(execute, cap, input) {
216
222
  fileId
217
223
  key
218
224
  deduplicated
225
+ file
219
226
  }
220
227
  }
221
228
  `.trim();
222
229
  const data = await execute(mutation, {
223
230
  input: {
224
- bucketKey: input.bucketKey,
231
+ ...input.bucketKey === void 0 ? { isPublic: true } : { bucketKey: input.bucketKey },
225
232
  contentHash: input.contentHash,
226
233
  contentType: input.contentType,
227
234
  size: input.size,
@@ -232,6 +239,10 @@ async function callUploadOp(execute, cap, input) {
232
239
  if (!payload) {
233
240
  throw createError.badRequest("Upload failed: no payload returned from upload mutation.");
234
241
  }
242
+ const file = payload.file;
243
+ if (!file || typeof file.id !== "string" || typeof file.key !== "string" || typeof file.bucket_id !== "string" || typeof file.mime !== "string" || typeof file.size !== "number") {
244
+ throw createError.badRequest("Upload failed: server returned an invalid file projection.");
245
+ }
235
246
  return payload;
236
247
  }
237
248
  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.";
@@ -320,7 +331,7 @@ async function fetchDownloadUrl(execute, cap, fileId) {
320
331
  const filterLiteral = cap.connectionIdOperator ? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }` : `{ ${idField}: $id }`;
321
332
  const query2 = `
322
333
  query SheetsDownloadUrl($id: ${idScalar2}!) {
323
- ${cap.fileByIdField}(${filterArg}: ${filterLiteral}, first: 1) {
334
+ ${cap.fileByIdField}(${filterArg}: ${filterLiteral}${cap.connectionHasFirst ? ", first: 1" : ""}) {
324
335
  ${nodesField} {
325
336
  downloadUrl
326
337
  }
@@ -355,148 +366,39 @@ async function fetchDownloadUrl(execute, cap, fileId) {
355
366
  }
356
367
  return url;
357
368
  }
369
+ async function fetchMediaDownloadUrls({ endpoint, execute }, getActiveIds) {
370
+ const { batch, download } = await discoverStorageCapabilities(endpoint, execute);
371
+ const ids = getActiveIds();
372
+ const urls = /* @__PURE__ */ new Map();
373
+ if (ids.length === 0) return urls;
374
+ if (batch) {
375
+ const first = batch.connectionHasFirst ? `, first: ${ids.length}` : "";
376
+ const query = `query SheetsMediaDownloadUrls($ids: [${batch.idScalarName ?? "ID"}!]!) {
377
+ ${batch.fileByIdField}(${batch.connectionFilterArgName}: {
378
+ ${batch.connectionIdField}: { in: $ids }
379
+ }${first}) { ${batch.connectionNodesField} { id downloadUrl } }
380
+ }`;
381
+ const data = await execute(query, { ids });
382
+ for (const row of data?.[batch.fileByIdField]?.[batch.connectionNodesField] ?? []) {
383
+ if (row?.downloadUrl) urls.set(row.id, row.downloadUrl);
384
+ }
385
+ } else if (download) {
386
+ const results = await Promise.allSettled(ids.map((id) => fetchDownloadUrl(execute, download, id)));
387
+ results.forEach((result, index) => {
388
+ if (result.status === "fulfilled") urls.set(ids[index], result.value);
389
+ });
390
+ }
391
+ return urls;
392
+ }
358
393
  async function resolveDownloadUrl(execute, endpoint, fileId) {
359
394
  try {
360
- const cap = await discoverUploadCapability(endpoint, execute);
361
- return await fetchDownloadUrl(execute, cap, fileId);
395
+ const { download } = await discoverStorageCapabilities(endpoint, execute);
396
+ return download ? await fetchDownloadUrl(execute, download, fileId) : null;
362
397
  } catch {
363
398
  return null;
364
399
  }
365
400
  }
366
401
 
367
- // src/context/sheets-execute.ts
368
- import { print } from "graphql";
369
- import { ConstructiveError, createError as createError2 } from "@constructive-io/data";
370
- import { ConstructiveError as ConstructiveError2 } from "@constructive-io/data";
371
- function documentToString(document) {
372
- if (typeof document === "string") return document;
373
- if (document instanceof String) return document.toString();
374
- if (document && typeof document === "object" && "kind" in document) {
375
- return print(document);
376
- }
377
- if (document === null || document === void 0) {
378
- throw createError2.badRequest("Invalid GraphQL document: null or undefined");
379
- }
380
- return String(document);
381
- }
382
- function hasAuthMessage(message) {
383
- const normalized = String(message ?? "").toLowerCase();
384
- return normalized.includes("unauthenticated") || normalized.includes("unauthorized") || normalized.includes("authentication");
385
- }
386
- function parseGraphQLResponse(response, onAuthError) {
387
- if (!response.errors?.length) return null;
388
- const error = response.errors[0];
389
- const code = error.extensions?.code;
390
- const message = error.message || "GraphQL query failed";
391
- if (code === "UNAUTHENTICATED" || hasAuthMessage(message)) {
392
- onAuthError?.();
393
- return createError2.unauthorized("Authentication required. Please log in again.");
394
- }
395
- if (code === "FORBIDDEN") {
396
- return createError2.forbidden("You do not have permission to perform this action.");
397
- }
398
- return createError2.graphql(message, code);
399
- }
400
- function createSheetsExecute(config, getToken) {
401
- return async (document, variables) => {
402
- const url = config.endpoint;
403
- if (!url) {
404
- throw createError2.badRequest("No GraphQL endpoint configured.");
405
- }
406
- const token = getToken();
407
- const headers = {
408
- "Content-Type": "application/json",
409
- Accept: "application/graphql-response+json"
410
- };
411
- if (token) {
412
- headers["Authorization"] = `Bearer ${token}`;
413
- }
414
- let response;
415
- try {
416
- response = await fetch(url, {
417
- method: "POST",
418
- headers,
419
- body: JSON.stringify({
420
- query: documentToString(document),
421
- ...variables !== void 0 && { variables }
422
- })
423
- });
424
- } catch (error) {
425
- throw createError2.network(error instanceof Error ? error : void 0);
426
- }
427
- if (!response.ok) {
428
- const { status, statusText } = response;
429
- if (status === 401) {
430
- config.onAuthError?.();
431
- throw createError2.unauthorized("Authentication required. Please log in again.");
432
- }
433
- if (status === 403) {
434
- throw createError2.forbidden("You do not have permission to perform this action.");
435
- }
436
- if (status === 404) {
437
- throw createError2.notFound("The requested endpoint does not exist.");
438
- }
439
- try {
440
- const body = await response.json();
441
- if (body.errors?.length) {
442
- throw createError2.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);
443
- }
444
- } catch (e) {
445
- if (e instanceof ConstructiveError) throw e;
446
- }
447
- throw createError2.badRequest(`Request failed: ${status} ${statusText}`);
448
- }
449
- const result = await response.json();
450
- const graphqlError = parseGraphQLResponse(result, config.onAuthError);
451
- if (graphqlError) {
452
- throw graphqlError;
453
- }
454
- return result.data;
455
- };
456
- }
457
- function createSheetsUpload(config, getToken) {
458
- const execute = config.execute ?? createSheetsExecute(config, getToken);
459
- return async (file, _path, options) => {
460
- if (!config.endpoint) {
461
- throw createError2.badRequest("No GraphQL endpoint configured.");
462
- }
463
- const bucketKey = config.upload?.bucketKey ?? "public";
464
- const contentType = file.type || "application/octet-stream";
465
- const buffer = await file.arrayBuffer();
466
- const contentHash = await sha256HexFromBuffer(buffer);
467
- const cap = await discoverUploadCapability(config.endpoint, execute);
468
- const payload = await callUploadOp(execute, cap, {
469
- bucketKey,
470
- contentHash,
471
- contentType,
472
- size: file.size,
473
- filename: file.name
474
- });
475
- if (!payload.deduplicated) {
476
- if (!payload.uploadUrl) {
477
- throw createError2.badRequest("Upload failed: server returned no uploadUrl for a non-deduplicated file.");
478
- }
479
- try {
480
- await presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);
481
- } catch (error) {
482
- await deleteUploadedFileRow(execute, cap, payload.fileId);
483
- throw error;
484
- }
485
- } else {
486
- options?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });
487
- }
488
- const url = await fetchDownloadUrl(execute, cap, payload.fileId);
489
- return {
490
- url,
491
- filename: file.name,
492
- mime: file.type,
493
- size: file.size,
494
- key: payload.key,
495
- fileId: payload.fileId
496
- };
497
- };
498
- }
499
-
500
402
  // src/hooks/query-keys.ts
501
403
  function isSheetsScopeKey(value) {
502
404
  if (!value || typeof value !== "object") return false;
@@ -515,6 +417,7 @@ var sheetsQueryKeys = {
515
417
  root: ["sheets"],
516
418
  scope: (scope) => ["sheets", scope],
517
419
  meta: (scope) => [...sheetsQueryKeys.scope(scope), "meta"],
420
+ mediaUrl: (scope, endpoint, id) => [...sheetsQueryKeys.scope(scope), "media-url", endpoint, id],
518
421
  typeFields: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "type-fields", typeName],
519
422
  enumValues: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "enum-values", typeName],
520
423
  relations: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "relations", tableName],
@@ -529,12 +432,15 @@ var sheetsQueryKeys = {
529
432
  };
530
433
 
531
434
  export {
435
+ sha256HexFromBuffer,
436
+ discoverUploadCapability,
437
+ callUploadOp,
438
+ presignedPut,
439
+ fetchDownloadUrl,
440
+ fetchMediaDownloadUrls,
532
441
  resolveDownloadUrl,
533
- createSheetsExecute,
534
- createSheetsUpload,
535
- ConstructiveError2 as ConstructiveError,
536
442
  isSheetsScopeKey,
537
443
  reuseSheetsPlaceholderData,
538
444
  sheetsQueryKeys
539
445
  };
540
- //# sourceMappingURL=chunk-AYMXT3ME.js.map
446
+ //# sourceMappingURL=chunk-BGL6EBTE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context/sheets-upload-presigned.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. Return the file projection and try to resolve an optional download URL\n *\n * The server confirms PUTs and expires rows that never received one.\n *\n * Runtime introspection finds root mutations with the presigned upload shape\n * and prefers `uploadAppFile` when multiple storage planes are exposed.\n *\n * The downloadUrl-by-id field is likewise shape-discovered. Three read shapes,\n * preferred in order: the inflected singular `appFile(id:)`; a filtered\n * connection `appFiles(where:{id:{equalTo:$id}}){ nodes { downloadUrl } }`\n * (Relay-disabled backends); and the Relay `node(nodeId:)` fallback.\n */\n\nimport { getIntrospectionQuery } from 'graphql';\n\nimport { createError } from '@constructive-io/data';\n\nimport type { SheetsStorageTransport } from './sheets-context';\nimport type { SheetsExecuteFn, SheetsFileValue } from './sheets-execute';\n\n// ============================================================================\n// Capability discovery types\n// ============================================================================\n\nexport interface UploadCapability {\n\t/** Upload mutation field name, discovered by shape, e.g. 'uploadAppFile'. */\n\tuploadFieldName: string;\n\t/** The upload input object type name, e.g. 'UploadAppFileInput'. */\n\tinputTypeName: string;\n\thasFileProjection: boolean;\n\tdownload: DownloadByIdResult | null;\n}\n\ninterface DownloadByIdResult {\n\t/** Query field used to resolve downloadUrl by id, e.g. 'appFile' | 'node' | 'appFiles'. */\n\tfileByIdField: string;\n\t/**\n\t * Which downloadUrl-by-id resolution shape was discovered:\n\t * - 'id' inflected singular `appFile(id:)`\n\t * - 'connection' filtered connection `appFiles(where:{id:{equalTo:$id}}){ nodes { downloadUrl } }`\n\t * - 'nodeId' Relay `node(nodeId:)` (last-resort fallback)\n\t */\n\tfileByIdArgName: 'id' | 'nodeId' | 'connection';\n\t/** The file object type name (used to spread `... on <Type>` on the Relay node path). */\n\tfileTypeName: string;\n\t/** The GraphQL scalar type name for the `$id` variable (e.g. 'UUID'), discovered by shape. */\n\tidScalarName?: string;\n\t/** connection kind only — the filter arg name on the connection field, e.g. 'where' | 'filter' | 'condition'. */\n\tconnectionFilterArgName?: string;\n\t/** connection kind only — the id field name inside the filter input, e.g. 'id'. */\n\tconnectionIdField?: string;\n\t/** connection kind only — the equality operator field for style (a), e.g. 'equalTo'. Absent for condition style (b). */\n\tconnectionIdOperator?: string;\n\t/** connection kind only — the field on the connection object holding the file rows, e.g. 'nodes'. */\n\tconnectionNodesField?: string;\n\tconnectionHasFirst?: boolean;\n}\n\ninterface StorageCapabilities {\n\tupload: UploadCapability | null;\n\tdownload: DownloadByIdResult | null;\n\tbatch: DownloadByIdResult | null;\n}\n\ninterface UploadPayload {\n\tuploadUrl: string | null;\n\tfileId: string;\n\tkey: string;\n\tdeduplicated: boolean;\n\tfile: Omit<SheetsFileValue, 'filename'> & { filename?: string | null };\n}\n\n// ============================================================================\n// SHA-256 (Web Crypto)\n// ============================================================================\n\n/**\n * SHA-256 hex digest of an already-read ArrayBuffer. Lowercase, 64 chars —\n * matches the server regex `^[a-f0-9]{64}$`. We reuse the same buffer for the\n * PUT body to avoid a second `file.arrayBuffer()` read.\n */\nexport async function sha256HexFromBuffer(buffer: ArrayBuffer): Promise<string> {\n\tif (!globalThis.crypto?.subtle) {\n\t\tthrow createError.badRequest('Web Crypto (crypto.subtle) is unavailable; cannot hash file for upload.');\n\t}\n\tconst digest = await crypto.subtle.digest('SHA-256', buffer);\n\tconst bytes = new Uint8Array(digest);\n\tlet hex = '';\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\thex += bytes[i].toString(16).padStart(2, '0');\n\t}\n\treturn hex;\n}\n\n// ============================================================================\n// Introspection-based capability discovery (cached per endpoint)\n// ============================================================================\n\nlet capabilityCache = new WeakMap<SheetsExecuteFn, Map<string, Promise<StorageCapabilities>>>();\n\n/** Test-only: clear cached storage capabilities between cases. */\nexport function __resetUploadCapabilityCache(): void {\n\tcapabilityCache = new WeakMap();\n}\n\n/**\n * Share storage introspection across uploads and previews using this executor\n * and endpoint. A read-only storage endpoint can still resolve previews.\n */\nasync function discoverStorageCapabilities(endpoint: string, execute: SheetsExecuteFn): Promise<StorageCapabilities> {\n\tlet endpoints = capabilityCache.get(execute);\n\tif (!endpoints) {\n\t\tendpoints = new Map();\n\t\tcapabilityCache.set(execute, endpoints);\n\t}\n\tconst cached = endpoints.get(endpoint);\n\tif (cached) return cached;\n\n\tconst promise = (async () => {\n\t\tconst data = await execute<{ __schema: IntrospectionSchema }>(getIntrospectionQuery());\n\t\tconst schema = data?.__schema;\n\t\tif (!schema) {\n\t\t\tthrow createError.badRequest('Uploads are not enabled for this endpoint.');\n\t\t}\n\t\treturn resolveStorageCapabilities(schema);\n\t})();\n\n\t// Don't cache a rejected discovery — let the next attempt retry.\n\tpromise.catch(() => endpoints.delete(endpoint));\n\tendpoints.set(endpoint, promise);\n\treturn promise;\n}\n\nexport async function discoverUploadCapability(endpoint: string, execute: SheetsExecuteFn): Promise<UploadCapability> {\n\tconst { upload } = await discoverStorageCapabilities(endpoint, execute);\n\tif (!upload) capabilityCache.get(execute)?.delete(endpoint);\n\treturn requireUploadCapability(upload);\n}\n\nfunction requireUploadCapability(upload: UploadCapability | null): UploadCapability {\n\tif (!upload) throw createError.badRequest('Uploads are not enabled for this endpoint.');\n\treturn upload;\n}\n\n// --- Minimal introspection shapes (only what discovery reads) ---\n\n// Loose, structural shapes for the slice of introspection that discovery\n// reads. `ofType` recurses with `any` so hand-built fixtures and the real\n// `IntrospectionQuery['__schema']` (from `graphql`) both satisfy these without\n// exact-match friction — discovery validates by runtime shape regardless.\ninterface IntrospectionTypeRef {\n\tkind: string;\n\tname?: string | null;\n\tofType?: any;\n}\n\ninterface IntrospectionInputValue {\n\tname: string;\n\ttype: IntrospectionTypeRef;\n}\n\ninterface IntrospectionField {\n\tname: string;\n\targs: ReadonlyArray<IntrospectionInputValue>;\n\ttype: IntrospectionTypeRef;\n}\n\ninterface IntrospectionType {\n\tkind: string;\n\tname?: string | null;\n\tfields?: ReadonlyArray<IntrospectionField> | null;\n\tinputFields?: ReadonlyArray<IntrospectionInputValue> | null;\n}\n\n/** Loose structural shape of an introspection `__schema` (accepts fixtures + real). */\nexport interface IntrospectionSchema {\n\tqueryType?: { name: string } | null;\n\tmutationType?: { name: string } | null;\n\ttypes: ReadonlyArray<IntrospectionType>;\n}\n\n/** Unwrap NON_NULL / LIST wrappers down to the named type. */\nfunction namedTypeName(ref: IntrospectionTypeRef | null | undefined): string | null {\n\tlet cur = ref;\n\twhile (cur && (cur.kind === 'NON_NULL' || cur.kind === 'LIST')) {\n\t\tcur = cur.ofType ?? null;\n\t}\n\treturn cur?.name ?? null;\n}\n\n/**\n * True if `ref` is a LIST (optionally NON_NULL-wrapped) at the outer level, i.e.\n * the field is plural. Unwraps only leading NON_NULL wrappers (e.g. `[AppFile]!`)\n * before checking for the LIST — distinguishes `nodes: [AppFile]` from a singular\n * `appFile: AppFile`.\n */\nfunction isListTypeRef(ref: IntrospectionTypeRef | null | undefined): boolean {\n\tlet cur = ref;\n\twhile (cur && cur.kind === 'NON_NULL') {\n\t\tcur = cur.ofType ?? null;\n\t}\n\treturn cur?.kind === 'LIST';\n}\n\n/**\n * PostGraphile names the primary-key column `id` on every row type, so the\n * filter input field that selects a single file by primary key is `id`. This is\n * the same convention the singular by-id branch (`appFile(id:)`) relies on.\n */\nconst PK_FIELD_NAME = 'id';\n\n/**\n * Pure resolver over an introspection __schema. Exported for direct unit tests\n * (no fetch). Matches by field/type shape, with an AppFile preference.\n */\nexport function resolveUploadCapability(schema: IntrospectionSchema): UploadCapability {\n\treturn requireUploadCapability(resolveStorageCapabilities(schema).upload);\n}\n\nfunction resolveStorageCapabilities(schema: IntrospectionSchema): StorageCapabilities {\n\tconst typeByName = new Map<string, IntrospectionType>();\n\tfor (const t of schema.types) {\n\t\tif (t.name) typeByName.set(t.name, t);\n\t}\n\n\tconst objectHasFields = (typeName: string | null, names: string[]): boolean => {\n\t\tif (!typeName) return false;\n\t\tconst t = typeByName.get(typeName);\n\t\tif (!t?.fields) return false;\n\t\tconst present = new Set(t.fields.map((f) => f.name));\n\t\treturn names.every((n) => present.has(n));\n\t};\n\n\tconst inputHasFields = (typeName: string | null, names: string[]): boolean => {\n\t\tif (!typeName) return false;\n\t\tconst t = typeByName.get(typeName);\n\t\tif (!t?.inputFields) return false;\n\t\tconst present = new Set(t.inputFields.map((f) => f.name));\n\t\treturn names.every((n) => present.has(n));\n\t};\n\n\tconst PAYLOAD_FIELDS = ['uploadUrl', 'fileId', 'key', 'deduplicated'];\n\tconst INPUT_FIELDS = ['contentHash', 'bucketKey', 'contentType', 'size'];\n\n\tconst mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;\n\tconst queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;\n\n\t// rootUpload discovery: a Mutation field with a single `input` arg whose input\n\t// type carries the upload-input shape and whose payload carries the\n\t// upload-payload shape. (The legacy bucket-centric `requestUploadUrl` shape was\n\t// removed from the backend on 2026-05-08; only the root upload mutation exists.)\n\tlet upload: Omit<UploadCapability, 'download'> | null = null;\n\n\tfor (const field of mutationType?.fields ?? []) {\n\t\tconst inputArg = field.args.find((a) => a.name === 'input');\n\t\tif (!inputArg) continue;\n\t\tconst inputTypeName = namedTypeName(inputArg.type);\n\t\tconst payloadTypeName = namedTypeName(field.type);\n\t\tif (\n\t\t\tinputTypeName &&\n\t\t\tinputHasFields(inputTypeName, INPUT_FIELDS) &&\n\t\t\tobjectHasFields(payloadTypeName, PAYLOAD_FIELDS)\n\t\t) {\n\t\t\tconst payloadFields = typeByName.get(payloadTypeName ?? '')?.fields;\n\t\t\tconst candidate = {\n\t\t\t\tuploadFieldName: field.name,\n\t\t\t\tinputTypeName,\n\t\t\t\thasFileProjection: payloadFields?.some(\n\t\t\t\t\t(f) => f.name === 'file' && !isListTypeRef(f.type) && namedTypeName(f.type) === 'JSON',\n\t\t\t\t) ?? false,\n\t\t\t};\n\t\t\tif (field.name === 'uploadAppFile') {\n\t\t\t\tupload = candidate;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tupload ??= candidate;\n\t\t}\n\t}\n\n\tconst fileTypes = new Set<string>();\n\tfor (const t of schema.types) {\n\t\tif (t.kind === 'OBJECT' && t.name && t.fields?.some((f) => f.name === 'downloadUrl')) {\n\t\t\tfileTypes.add(t.name);\n\t\t}\n\t}\n\n\tconst uploadType = upload?.uploadFieldName.replace(/^upload/, '') ?? 'AppFile';\n\tconst uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);\n\tconst preferredPreviewType = fileTypes.has('AppFile') ? 'AppFile' : uploadType;\n\tconst previewType = fileTypes.has(preferredPreviewType)\n\t\t? preferredPreviewType\n\t\t: uploadDownload?.fileTypeName ?? preferredPreviewType;\n\tconst download = previewType === uploadType\n\t\t? uploadDownload\n\t\t: resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);\n\tconst batch = resolveConnectionDownloadField(typeByName, queryType, fileTypes, previewType, true);\n\n\treturn {\n\t\tupload: upload ? { ...upload, download: uploadDownload } : null,\n\t\tdownload,\n\t\tbatch,\n\t};\n}\n\nfunction resolveDownloadByIdField(\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tfileTypesWithDownloadUrl: Set<string>,\n\tpreferred: string,\n): DownloadByIdResult | null {\n\t// 1. Look for an inflected by-id form: a Query field whose return type has a\n\t// `downloadUrl` field and that takes a single `id` arg. e.g. appFile(id:).\n\t// The `$id` variable type is the actual scalar of that id arg (NOT a\n\t// hardcoded UUID) — derived by shape.\n\tlet singular: DownloadByIdResult | null = null;\n\tfor (const field of queryType?.fields ?? []) {\n\t\tconst returnTypeName = namedTypeName(field.type);\n\t\tif (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;\n\t\tif (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {\n\t\t\tconst candidate: DownloadByIdResult = {\n\t\t\t\tfileByIdField: field.name,\n\t\t\t\tfileByIdArgName: 'id',\n\t\t\t\tfileTypeName: returnTypeName,\n\t\t\t\tidScalarName: namedTypeName(field.args[0].type) ?? undefined,\n\t\t\t};\n\t\t\tif (returnTypeName === preferred) return candidate;\n\t\t\tsingular ??= candidate;\n\t\t}\n\t}\n\n\t// 2. Connection fallback (Relay-disabled backends, incl. the live tenant API):\n\t// a Query field returning a connection whose `nodes` element is a\n\t// downloadUrl-bearing file type, filtered by id. e.g.\n\t// appFiles(where: { id: { equalTo: $id } }, first: 1) { nodes { downloadUrl } }\n\t// All names (connection field, filter arg, id field, equality operator,\n\t// nodes field, id scalar) are discovered by SHAPE, never hardcoded.\n\t// Preferred over the Relay node path: it consumes the raw fileId directly,\n\t// so it needs no client-side global-id construction.\n\tconst connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);\n\tif (connection?.fileTypeName === preferred) return connection;\n\tif (singular || connection) return singular ?? connection;\n\n\t// 3. Relay fallback: `node(nodeId: ID!)`. Last resort — only when neither a\n\t// singular `id` accessor nor a filtered connection exists. Caller spreads\n\t// `... on <FileType> { downloadUrl }` and encodes the global id.\n\tconst nodeField = queryType?.fields?.find(\n\t\t(f) => f.name === 'node' && f.args.some((a) => a.name === 'nodeId'),\n\t);\n\tif (nodeField && fileTypesWithDownloadUrl.size > 0) {\n\t\t// Deterministic file type for the inline fragment: prefer the type named\n\t\t// after the upload op (uploadAppFile → AppFile); else the first-declared\n\t\t// downloadUrl-bearing type. (Was alphabetical `.sort()[0]`, which could pick\n\t\t// the wrong type when several expose downloadUrl, e.g. DataRoomFile.)\n\t\tconst fileTypeName = fileTypesWithDownloadUrl.has(preferred)\n\t\t\t? preferred\n\t\t\t: [...fileTypesWithDownloadUrl][0];\n\t\treturn { fileByIdField: 'node', fileByIdArgName: 'nodeId', fileTypeName };\n\t}\n\n\treturn null;\n}\n\n/**\n * Discover a filtered connection for single or batched download lookups.\n * The single-file path supports two filter input styles:\n * (a) operator filter — `where: { id: { equalTo: $id } }` (connection-filter\n * plugin): the id field's input type carries an equality operator.\n * (b) condition filter — `condition: { id: $id }`: the id field is the scalar\n * directly.\n */\nfunction resolveConnectionDownloadField(\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tfileTypesWithDownloadUrl: Set<string>,\n\tpreferred: string,\n\tbatch = false,\n): DownloadByIdResult | null {\n\t// Equality operator names we recognize on a filter-input field, in priority\n\t// order (exact-match equality first).\n\tconst EQUALITY_OPERATORS = ['equalTo', 'eq'];\n\n\t// Collect every matching connection, then pick deterministically — a tenant\n\t// with multiple @storageFiles tables exposes several file connections\n\t// (appFiles, dataRoomFiles, …), all carrying downloadUrl-bearing nodes.\n\tconst candidates: DownloadByIdResult[] = [];\n\n\tfor (const field of queryType?.fields ?? []) {\n\t\tconst connTypeName = namedTypeName(field.type);\n\t\tif (!connTypeName) continue;\n\t\tconst connType = typeByName.get(connTypeName);\n\t\tif (connType?.kind !== 'OBJECT' || !connType.fields) continue;\n\n\t\t// Find the `nodes` field whose element type is a downloadUrl-bearing file.\n\t\t// Require it to be a LIST (plural) so a singular `appFile: AppFile` field on\n\t\t// some object does NOT false-match as a connection (fetchDownloadUrl indexes\n\t\t// [nodesField][0], which only makes sense on an array).\n\t\tconst nodesField = connType.fields.find((f) => {\n\t\t\tif (!isListTypeRef(f.type)) return false;\n\t\t\tconst elem = namedTypeName(f.type);\n\t\t\treturn elem != null && fileTypesWithDownloadUrl.has(elem);\n\t\t});\n\t\tif (!nodesField) continue;\n\t\tconst fileTypeName = namedTypeName(nodesField.type) as string;\n\t\tif (batch && (fileTypeName !== preferred ||\n\t\t\t!typeByName.get(fileTypeName)?.fields?.some((field) => field.name === PK_FIELD_NAME))) continue;\n\t\tconst connectionHasFirst = field.args.some((arg) => arg.name === 'first');\n\n\t\t// Find a filter arg whose input type has an `id` field.\n\t\tfor (const arg of field.args) {\n\t\t\tconst filterTypeName = namedTypeName(arg.type);\n\t\t\tconst filterType = filterTypeName ? typeByName.get(filterTypeName) : null;\n\t\t\tif (filterType?.kind !== 'INPUT_OBJECT' || !filterType.inputFields) continue;\n\t\t\tconst idField = filterType.inputFields.find((f) => f.name === PK_FIELD_NAME);\n\t\t\tif (!idField) continue;\n\n\t\t\tconst idFieldTypeName = namedTypeName(idField.type);\n\t\t\tconst idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;\n\n\t\t\t// Style (a): the id field is itself an input type carrying an equality\n\t\t\t// operator (e.g. UUIDFilter.equalTo). The `$id` scalar is the operator's\n\t\t\t// type.\n\t\t\tif (idFieldType?.kind === 'INPUT_OBJECT' && idFieldType.inputFields) {\n\t\t\t\tconst opField = batch\n\t\t\t\t\t? idFieldType.inputFields.find((f) => f.name === 'in' && isListTypeRef(f.type))\n\t\t\t\t\t: EQUALITY_OPERATORS.map((op) =>\n\t\t\t\t\t\tidFieldType.inputFields!.find((f) => f.name === op),\n\t\t\t\t\t).find((f) => f != null);\n\t\t\t\tif (opField) {\n\t\t\t\t\tcandidates.push({\n\t\t\t\t\t\tfileByIdField: field.name,\n\t\t\t\t\t\tfileByIdArgName: 'connection',\n\t\t\t\t\t\tfileTypeName,\n\t\t\t\t\t\tidScalarName: namedTypeName(opField.type) ?? undefined,\n\t\t\t\t\t\tconnectionFilterArgName: arg.name,\n\t\t\t\t\t\tconnectionIdField: idField.name,\n\t\t\t\t\t\tconnectionIdOperator: opField.name,\n\t\t\t\t\t\tconnectionNodesField: nodesField.name,\n\t\t\t\t\t\tconnectionHasFirst,\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// This filter lacks the operator needed for this lookup.\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Style (b): the id field is a scalar directly (condition style). The\n\t\t\t// `$id` scalar is that field's type.\n\t\t\tif (!batch && (idFieldType?.kind === 'SCALAR' || (!idFieldType && idFieldTypeName))) {\n\t\t\t\tcandidates.push({\n\t\t\t\t\tfileByIdField: field.name,\n\t\t\t\t\tfileByIdArgName: 'connection',\n\t\t\t\t\tfileTypeName,\n\t\t\t\t\tidScalarName: idFieldTypeName ?? undefined,\n\t\t\t\t\tconnectionFilterArgName: arg.name,\n\t\t\t\t\tconnectionIdField: idField.name,\n\t\t\t\t\tconnectionNodesField: nodesField.name,\n\t\t\t\t\tconnectionHasFirst,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (candidates.length === 0) return null;\n\n\t// Deterministic pick: prefer the connection whose file type matches the upload\n\t// op (uploadAppFile → AppFile), else the first-declared. This is the LIVE\n\t// production path — the only downloadUrl shape on a Relay-disabled, unique-\n\t// lookup-disabled tenant API — so resolving the WRONG file connection (e.g.\n\t// reading a DataRoomFile id through appFiles) yields 0 nodes and fails every\n\t// upload. Mirrors the node-branch determinism, where it matters far more.\n\treturn candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];\n}\n\n// ============================================================================\n// Upload op call\n// ============================================================================\n\ninterface UploadOpInput {\n\tbucketKey?: string;\n\tcontentHash: string;\n\tcontentType: string;\n\tsize: number;\n\tfilename: string;\n}\n\n/**\n * Invoke the discovered upload op and normalize its payload.\n * App-scoped buckets have NO owner_id column, so `ownerId` is NEVER sent.\n */\nexport async function callUploadOp(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\n\tinput: UploadOpInput,\n): Promise<UploadPayload> {\n\tconst mutation = `\n\t\tmutation SheetsUpload($input: ${cap.inputTypeName}!) {\n\t\t\t${cap.uploadFieldName}(input: $input) {\n\t\t\t\tuploadUrl\n\t\t\t\tfileId\n\t\t\t\tkey\n\t\t\t\tdeduplicated\n\t\t\t\tfile\n\t\t\t}\n\t\t}\n\t`.trim();\n\tconst data = await execute<Record<string, UploadPayload | null>>(mutation, {\n\t\tinput: {\n\t\t\t...(input.bucketKey === undefined ? { isPublic: true } : { bucketKey: input.bucketKey }),\n\t\t\tcontentHash: input.contentHash,\n\t\t\tcontentType: input.contentType,\n\t\t\tsize: input.size,\n\t\t\tfilename: input.filename,\n\t\t},\n\t});\n\tconst payload = data?.[cap.uploadFieldName];\n\tif (!payload) {\n\t\tthrow createError.badRequest('Upload failed: no payload returned from upload mutation.');\n\t}\n\tconst file = payload.file;\n\tif (\n\t\t!file || typeof file.id !== 'string' || typeof file.key !== 'string' ||\n\t\ttypeof file.bucket_id !== 'string' || typeof file.mime !== 'string' || typeof file.size !== 'number'\n\t) {\n\t\tthrow createError.badRequest('Upload failed: server returned an invalid file projection.');\n\t}\n\treturn payload;\n}\n\n// ============================================================================\n// Presigned PUT\n// ============================================================================\n\n/**\n * PUT the raw bytes to the presigned url. Sends ONLY the signed `Content-Type`\n * header — NO Authorization (the signature lives in the url query string), no\n * cookies, no Accept override. The browser supplies Content-Length from the body.\n *\n * When `onProgress` is provided and XHR is available, uses XHR for byte\n * progress; otherwise a plain fetch PUT.\n */\n/**\n * A PUT the browser could not complete. The GraphQL API answered moments ago, so\n * the usual cause is the bucket's CORS rule (no allowed origin for this site) rather\n * than the connection; browsers do not expose which.\n */\nexport const STORAGE_UPLOAD_BLOCKED_MESSAGE =\n\t\"Upload failed: the storage server didn't accept the upload from this site. Check the bucket's allowed origins (CORS) and your connection.\";\n\nfunction storageUnreachableError() {\n\treturn createError.graphql(STORAGE_UPLOAD_BLOCKED_MESSAGE, 'STORAGE_UPLOAD_BLOCKED');\n}\n\nexport async function presignedPut(\n\turl: string,\n\tbuffer: ArrayBuffer,\n\tcontentType: string,\n\tonProgress?: (progress: { loaded: number; total: number; percentage: number }) => void,\n): Promise<void> {\n\tconst total = buffer.byteLength;\n\n\tif (onProgress && typeof XMLHttpRequest !== 'undefined') {\n\t\tawait putWithXHR(url, buffer, contentType, total, onProgress);\n\t\treturn;\n\t}\n\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, {\n\t\t\tmethod: 'PUT',\n\t\t\theaders: { 'Content-Type': contentType },\n\t\t\tbody: buffer,\n\t\t});\n\t} catch {\n\t\tthrow storageUnreachableError();\n\t}\n\n\tif (!response.ok) {\n\t\tconst body = await response.text().catch(() => '');\n\t\tthrow createError.badRequest(`Upload failed: ${response.status} ${response.statusText}${body ? ` — ${body}` : ''}`);\n\t}\n\tonProgress?.({ loaded: total, total, percentage: 100 });\n}\n\nfunction putWithXHR(\n\turl: string,\n\tbuffer: ArrayBuffer,\n\tcontentType: string,\n\ttotal: number,\n\tonProgress: (progress: { loaded: number; total: number; percentage: number }) => void,\n): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst xhr = new XMLHttpRequest();\n\t\txhr.open('PUT', url);\n\t\txhr.setRequestHeader('Content-Type', contentType);\n\n\t\txhr.upload.addEventListener('progress', (event) => {\n\t\t\tif (event.lengthComputable) {\n\t\t\t\tonProgress({\n\t\t\t\t\tloaded: event.loaded,\n\t\t\t\t\ttotal: event.total,\n\t\t\t\t\tpercentage: Math.round((event.loaded / event.total) * 100),\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\txhr.addEventListener('load', () => {\n\t\t\tif (xhr.status >= 200 && xhr.status < 300) {\n\t\t\t\tonProgress({ loaded: total, total, percentage: 100 });\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\treject(createError.badRequest(`Upload failed: ${xhr.status} ${xhr.statusText}${xhr.responseText ? ` — ${xhr.responseText}` : ''}`));\n\t\t\t}\n\t\t});\n\n\t\txhr.addEventListener('error', () => reject(storageUnreachableError()));\n\n\t\txhr.send(buffer);\n\t});\n}\n\n// ============================================================================\n// downloadUrl resolution\n// ============================================================================\n\n/**\n * Encode a PostGraphile global id (Relay `node` id) from a row's primary key,\n * using the default base64JSON codec: `base64(JSON.stringify([typeName, pk]))`.\n */\nfunction toGlobalId(typeName: string, id: string): string {\n\tif (typeof btoa !== 'function') {\n\t\tthrow createError.badRequest('Cannot encode the file node id: btoa is unavailable in this environment.');\n\t}\n\treturn btoa(JSON.stringify([typeName, id]));\n}\n\n/**\n * Resolve a file's download URL for immediate use. It can be a signed URL\n * with an expiration, so only the storage projection belongs in the cell.\n */\nexport async function fetchDownloadUrl(\n\texecute: SheetsExecuteFn,\n\tcap: DownloadByIdResult,\n\tfileId: string,\n): Promise<string> {\n\tif (cap.fileByIdArgName === 'nodeId') {\n\t\t// The upload payload returns the RAW primary key as `fileId`, but\n\t\t// `node(nodeId:)` expects the opaque PostGraphile global id. Encode it with\n\t\t// the default base64JSON codec (`base64([typeName, pk])`). NOTE: the live\n\t\t// tenant API is Relay-disabled and resolves via the connection branch; this\n\t\t// path is mock-covered only and assumes the default node-id codec.\n\t\tconst nodeId = toGlobalId(cap.fileTypeName, fileId);\n\t\tconst query = `\n\t\t\tquery SheetsDownloadUrl($nodeId: ID!) {\n\t\t\t\t${cap.fileByIdField}(nodeId: $nodeId) {\n\t\t\t\t\t... on ${cap.fileTypeName} {\n\t\t\t\t\t\tdownloadUrl\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`.trim();\n\t\tconst data = await execute<Record<string, { downloadUrl?: string | null } | null>>(query, { nodeId });\n\t\tconst node = data?.[cap.fileByIdField];\n\t\tconst url = node?.downloadUrl;\n\t\tif (!url) {\n\t\t\tthrow createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\t\t}\n\t\treturn url;\n\t}\n\n\t// Connection fallback (Relay-disabled): filter the connection by id and read\n\t// the first node's downloadUrl. The filter literal is built per the discovered\n\t// style — operator (`{ id: { equalTo: $id } }`) or condition (`{ id: $id }`).\n\tif (cap.fileByIdArgName === 'connection') {\n\t\tconst idScalar = cap.idScalarName ?? 'ID';\n\t\tconst filterArg = cap.connectionFilterArgName as string;\n\t\tconst idField = cap.connectionIdField as string;\n\t\tconst nodesField = cap.connectionNodesField as string;\n\t\tconst filterLiteral = cap.connectionIdOperator\n\t\t\t? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }`\n\t\t\t: `{ ${idField}: $id }`;\n\t\tconst query = `\n\t\t\tquery SheetsDownloadUrl($id: ${idScalar}!) {\n\t\t\t\t${cap.fileByIdField}(${filterArg}: ${filterLiteral}${cap.connectionHasFirst ? ', first: 1' : ''}) {\n\t\t\t\t\t${nodesField} {\n\t\t\t\t\t\tdownloadUrl\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`.trim();\n\t\tconst data = await execute<Record<string, Record<string, Array<{ downloadUrl?: string | null }> | null> | null>>(\n\t\t\tquery,\n\t\t\t{ id: fileId },\n\t\t);\n\t\tconst conn = data?.[cap.fileByIdField];\n\t\tconst url = conn?.[nodesField]?.[0]?.downloadUrl;\n\t\tif (!url) {\n\t\t\tthrow createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\t\t}\n\t\treturn url;\n\t}\n\n\tconst idScalar = cap.idScalarName ?? 'ID';\n\tconst query = `\n\t\tquery SheetsDownloadUrl($id: ${idScalar}!) {\n\t\t\t${cap.fileByIdField}(id: $id) {\n\t\t\t\tid\n\t\t\t\tdownloadUrl\n\t\t\t}\n\t\t}\n\t`.trim();\n\tconst data = await execute<Record<string, { downloadUrl?: string | null } | null>>(query, { id: fileId });\n\tconst file = data?.[cap.fileByIdField];\n\tconst url = file?.downloadUrl;\n\tif (!url) {\n\t\tthrow createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\t}\n\treturn url;\n}\n\n/** Resolve URLs for one batch of visible images. Missing or unreadable IDs have no entry. */\nexport async function fetchMediaDownloadUrls(\n\t{ endpoint, execute }: SheetsStorageTransport,\n\tgetActiveIds: () => readonly string[],\n): Promise<Map<string, string>> {\n\tconst { batch, download } = await discoverStorageCapabilities(endpoint, execute);\n\tconst ids = getActiveIds();\n\tconst urls = new Map<string, string>();\n\tif (ids.length === 0) return urls;\n\tif (batch) {\n\t\tconst first = batch.connectionHasFirst ? `, first: ${ids.length}` : '';\n\t\tconst query = `query SheetsMediaDownloadUrls($ids: [${batch.idScalarName ?? 'ID'}!]!) {\n\t\t\t${batch.fileByIdField}(${batch.connectionFilterArgName}: {\n\t\t\t\t${batch.connectionIdField}: { in: $ids }\n\t\t\t}${first}) { ${batch.connectionNodesField} { id downloadUrl } }\n\t\t}`;\n\t\ttype FileNode = { id: string; downloadUrl: string | null };\n\t\tconst data = await execute<Record<string, Record<string, (FileNode | null)[] | null> | null>>(query, { ids });\n\t\tfor (const row of data?.[batch.fileByIdField]?.[batch.connectionNodesField!] ?? []) {\n\t\t\tif (row?.downloadUrl) urls.set(row.id, row.downloadUrl);\n\t\t}\n\t} else if (download) {\n\t\tconst results = await Promise.allSettled(ids.map((id) => fetchDownloadUrl(execute, download, id)));\n\t\tresults.forEach((result, index) => {\n\t\t\tif (result.status === 'fulfilled') urls.set(ids[index], result.value);\n\t\t});\n\t}\n\treturn urls;\n}\n\n/**\n * Resolve a file's signed `downloadUrl` by id — the public entry point for callers\n * OUTSIDE the upload flow (e.g. a storage browser fetching the preview/copy link for\n * an already-uploaded file).\n *\n * `downloadUrl` is a Grafast computed field, so it cannot be selected through the\n * runtime query builder (`buildSelect` intersects the select against pg columns and\n * drops computed fields). This discovers the by-id field using cached introspection\n * and reads it through the SAME resolver the upload path uses. Returns null on any\n * failure — a missing url is not exceptional for the caller (it just disables\n * copy/download), so the throwing internals are swallowed here.\n */\nexport async function resolveDownloadUrl(\n\texecute: SheetsExecuteFn,\n\tendpoint: string,\n\tfileId: string,\n): Promise<string | null> {\n\ttry {\n\t\tconst { download } = await discoverStorageCapabilities(endpoint, execute);\n\t\treturn download ? await fetchDownloadUrl(execute, download, fileId) : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n","import type { SheetsScopeKey } from '../context/sheets-context';\n\nexport function isSheetsScopeKey(value: unknown): value is SheetsScopeKey {\n\tif (!value || typeof value !== 'object') return false;\n\tconst candidate = value as Record<string, unknown>;\n\treturn 'databaseId' in candidate && 'endpoint' in candidate && 'identityKey' in candidate;\n}\n\nexport function reuseSheetsPlaceholderData<T>(\n\tpreviousData: T | undefined,\n\tpreviousQueryKey: readonly unknown[] | undefined,\n\tcurrentScope: SheetsScopeKey,\n): T | undefined {\n\tconst previousScope = previousQueryKey?.[1];\n\tif (!isSheetsScopeKey(previousScope)) return undefined;\n\tif (previousScope.databaseId !== currentScope.databaseId) return undefined;\n\tif (previousScope.endpoint !== currentScope.endpoint) return undefined;\n\tif (previousScope.identityKey !== currentScope.identityKey) return undefined;\n\treturn previousData;\n}\n\nexport const sheetsQueryKeys = {\n\troot: ['sheets'] as const,\n\tscope: (scope: SheetsScopeKey) => ['sheets', scope] as const,\n\tmeta: (scope: SheetsScopeKey) => [...sheetsQueryKeys.scope(scope), 'meta'] as const,\n\tmediaUrl: (scope: SheetsScopeKey, endpoint: string | undefined, id: string | null) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'media-url', endpoint, id] as const,\n\ttypeFields: (scope: SheetsScopeKey, typeName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'type-fields', typeName] as const,\n\tenumValues: (scope: SheetsScopeKey, typeName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'enum-values', typeName] as const,\n\trelations: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'relations', tableName] as const,\n\ttable: (scope: SheetsScopeKey, tableName: string) => [...sheetsQueryKeys.scope(scope), 'table', tableName] as const,\n\ttableRows: (scope: SheetsScopeKey, tableName: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableName), 'rows', options] as const,\n\ttableRow: (scope: SheetsScopeKey, tableName: string, id: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableName), 'row', id] as const,\n\ttableCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown> | null) =>\n\t\t[...sheetsQueryKeys.table(scope, tableName), 'count', where] as const,\n\tinfiniteTable: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'infinite-table', tableName] as const,\n\tinfiniteTablePage: (scope: SheetsScopeKey, tableName: string, pageIndex: number, options: unknown) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableName), 'page', pageIndex, options] as const,\n\tinfiniteTableTotalCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown>) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableName), 'totalCount', where] as const,\n\tcursorTable: (scope: SheetsScopeKey, tableName: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'cursor-table', tableName, options] as const,\n} as const;\n"],"mappings":";;;AAqBA,SAAS,6BAA6B;AAEtC,SAAS,mBAAmB;AAkE5B,eAAsB,oBAAoB,QAAsC;AAC/E,MAAI,CAAC,WAAW,QAAQ,QAAQ;AAC/B,UAAM,YAAY,WAAW,yEAAyE;AAAA,EACvG;AACA,QAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,MAAM;AAC3D,QAAM,QAAQ,IAAI,WAAW,MAAM;AACnC,MAAI,MAAM;AACV,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACtC,WAAO,MAAM,CAAC,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AAAA,EAC7C;AACA,SAAO;AACR;AAMA,IAAI,kBAAkB,oBAAI,QAAoE;AAW9F,eAAe,4BAA4B,UAAkB,SAAwD;AACpH,MAAI,YAAY,gBAAgB,IAAI,OAAO;AAC3C,MAAI,CAAC,WAAW;AACf,gBAAY,oBAAI,IAAI;AACpB,oBAAgB,IAAI,SAAS,SAAS;AAAA,EACvC;AACA,QAAM,SAAS,UAAU,IAAI,QAAQ;AACrC,MAAI,OAAQ,QAAO;AAEnB,QAAM,WAAW,YAAY;AAC5B,UAAM,OAAO,MAAM,QAA2C,sBAAsB,CAAC;AACrF,UAAM,SAAS,M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,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":["field","query","data","url","idScalar"]}
@@ -6,7 +6,7 @@ import {
6
6
  useSheetsContext,
7
7
  useSheetsStore,
8
8
  useSheetsStoreApi
9
- } from "./chunk-H5HR5HUJ.js";
9
+ } from "./chunk-YJZFHL2D.js";
10
10
  import {
11
11
  cn
12
12
  } from "./chunk-YDQQA46V.js";
@@ -1285,4 +1285,4 @@ export {
1285
1285
  useSheetsResetPassword,
1286
1286
  SheetsAuthGate
1287
1287
  };
1288
- //# sourceMappingURL=chunk-MXVNIKES.js.map
1288
+ //# sourceMappingURL=chunk-BYAYBXVB.js.map