@constructive-io/sheets 0.3.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +19 -24
  2. package/dist/advanced.cjs +659 -474
  3. package/dist/advanced.cjs.map +1 -1
  4. package/dist/advanced.d.cts +9 -10
  5. package/dist/advanced.d.ts +9 -10
  6. package/dist/advanced.js +3 -3
  7. package/dist/auth.cjs +10 -10
  8. package/dist/auth.cjs.map +1 -1
  9. package/dist/auth.d.cts +5 -4
  10. package/dist/auth.d.ts +5 -4
  11. package/dist/auth.js +3 -3
  12. package/dist/{chunk-GLVZSPV2.js → chunk-4EZ6A23C.js} +4 -3
  13. package/dist/chunk-4EZ6A23C.js.map +1 -0
  14. package/dist/{chunk-FNVHSOQQ.js → chunk-KKAWMVEG.js} +11 -11
  15. package/dist/chunk-KKAWMVEG.js.map +1 -0
  16. package/dist/{chunk-4PGPVMZB.js → chunk-KOZAW264.js} +4 -3
  17. package/dist/chunk-KOZAW264.js.map +1 -0
  18. package/dist/{chunk-ODUBS2NL.js → chunk-KVPVEXWB.js} +40 -17
  19. package/dist/chunk-KVPVEXWB.js.map +1 -0
  20. package/dist/{chunk-TU7ATZ4X.js → chunk-LR64FLWO.js} +301 -410
  21. package/dist/chunk-LR64FLWO.js.map +1 -0
  22. package/dist/chunk-ZETPUEXH.js +494 -0
  23. package/dist/chunk-ZETPUEXH.js.map +1 -0
  24. package/dist/{date-editor-CXKKGNL6.js → date-editor-QT47WY5T.js} +5 -3
  25. package/dist/date-editor-QT47WY5T.js.map +1 -0
  26. package/dist/{editor-props-M6Dh0P9f.d.ts → grid-cell-types-C3ARj148.d.cts} +70 -62
  27. package/dist/{editor-props-M6Dh0P9f.d.cts → grid-cell-types-C3ARj148.d.ts} +70 -62
  28. package/dist/index.cjs +1150 -703
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.d.cts +123 -35
  31. package/dist/index.d.ts +123 -35
  32. package/dist/index.js +323 -99
  33. package/dist/index.js.map +1 -1
  34. package/dist/{sheets-context-CojEFlaY.d.cts → sheets-context-B03WDhZ9.d.cts} +36 -6
  35. package/dist/{sheets-context-Da55TTR9.d.ts → sheets-context-DmVCOgiX.d.ts} +36 -6
  36. package/dist/styles.css +6 -0
  37. package/dist/testing.cjs +476 -108
  38. package/dist/testing.cjs.map +1 -1
  39. package/dist/testing.d.cts +11 -7
  40. package/dist/testing.d.ts +11 -7
  41. package/dist/testing.js +34 -8
  42. package/dist/testing.js.map +1 -1
  43. package/package.json +15 -16
  44. package/dist/chunk-4PGPVMZB.js.map +0 -1
  45. package/dist/chunk-FNVHSOQQ.js.map +0 -1
  46. package/dist/chunk-GLVZSPV2.js.map +0 -1
  47. package/dist/chunk-H4JJTMP5.js +0 -160
  48. package/dist/chunk-H4JJTMP5.js.map +0 -1
  49. package/dist/chunk-ODUBS2NL.js.map +0 -1
  50. package/dist/chunk-TU7ATZ4X.js.map +0 -1
  51. package/dist/date-editor-CXKKGNL6.js.map +0 -1
package/dist/testing.cjs CHANGED
@@ -22,6 +22,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
22
22
  var testing_exports = {};
23
23
  __export(testing_exports, {
24
24
  MockSheetsProvider: () => MockSheetsProvider,
25
+ createMetaContractFixture: () => createMetaContractFixture,
25
26
  createMockExecute: () => createMockExecute,
26
27
  usersFixture: () => usersFixture
27
28
  });
@@ -29,30 +30,357 @@ module.exports = __toCommonJS(testing_exports);
29
30
 
30
31
  // src/testing/mock-sheets-provider.tsx
31
32
  var import_react4 = require("react");
32
- var import_graphql2 = require("graphql");
33
+ var import_graphql3 = require("graphql");
33
34
  var import_react_query2 = require("@tanstack/react-query");
34
- var import_data5 = require("@constructive-io/data");
35
+ var import_data7 = require("@constructive-io/data");
35
36
 
36
37
  // src/context/sheets-provider.tsx
37
38
  var import_react3 = require("react");
38
39
  var import_react_query = require("@tanstack/react-query");
40
+ var import_zustand2 = require("zustand");
39
41
 
40
42
  // src/context/sheets-context.ts
41
43
  var import_react = require("react");
42
44
  var SheetsContext = (0, import_react.createContext)(null);
43
45
 
44
46
  // src/context/sheets-execute.ts
47
+ var import_graphql2 = require("graphql");
48
+ var import_data2 = require("@constructive-io/data");
49
+
50
+ // src/context/sheets-upload-presigned.ts
45
51
  var import_graphql = require("graphql");
46
52
  var import_data = require("@constructive-io/data");
47
- var import_data2 = require("@constructive-io/data");
53
+ async function sha256HexFromBuffer(buffer) {
54
+ if (!globalThis.crypto?.subtle) {
55
+ throw import_data.createError.badRequest("Web Crypto (crypto.subtle) is unavailable; cannot hash file for upload.");
56
+ }
57
+ const digest = await crypto.subtle.digest("SHA-256", buffer);
58
+ const bytes = new Uint8Array(digest);
59
+ let hex = "";
60
+ for (let i = 0; i < bytes.length; i++) {
61
+ hex += bytes[i].toString(16).padStart(2, "0");
62
+ }
63
+ return hex;
64
+ }
65
+ var capabilityCache = /* @__PURE__ */ new Map();
66
+ function discoverUploadCapability(endpoint, execute) {
67
+ const cached = capabilityCache.get(endpoint);
68
+ if (cached) return cached;
69
+ const promise = (async () => {
70
+ const data = await execute((0, import_graphql.getIntrospectionQuery)());
71
+ const schema = data?.__schema;
72
+ if (!schema) {
73
+ throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
74
+ }
75
+ return resolveUploadCapability(schema);
76
+ })();
77
+ promise.catch(() => capabilityCache.delete(endpoint));
78
+ capabilityCache.set(endpoint, promise);
79
+ return promise;
80
+ }
81
+ function namedTypeName(ref) {
82
+ let cur = ref;
83
+ while (cur && (cur.kind === "NON_NULL" || cur.kind === "LIST")) {
84
+ cur = cur.ofType ?? null;
85
+ }
86
+ return cur?.name ?? null;
87
+ }
88
+ function isListTypeRef(ref) {
89
+ let cur = ref;
90
+ while (cur && cur.kind === "NON_NULL") {
91
+ cur = cur.ofType ?? null;
92
+ }
93
+ return cur?.kind === "LIST";
94
+ }
95
+ var PK_FIELD_NAME = "id";
96
+ function resolveUploadCapability(schema) {
97
+ const typeByName = /* @__PURE__ */ new Map();
98
+ for (const t of schema.types) {
99
+ if (t.name) typeByName.set(t.name, t);
100
+ }
101
+ const objectHasFields = (typeName, names) => {
102
+ if (!typeName) return false;
103
+ const t = typeByName.get(typeName);
104
+ if (!t?.fields) return false;
105
+ const present = new Set(t.fields.map((f) => f.name));
106
+ return names.every((n) => present.has(n));
107
+ };
108
+ const inputHasFields = (typeName, names) => {
109
+ if (!typeName) return false;
110
+ const t = typeByName.get(typeName);
111
+ if (!t?.inputFields) return false;
112
+ const present = new Set(t.inputFields.map((f) => f.name));
113
+ return names.every((n) => present.has(n));
114
+ };
115
+ const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "deduplicated"];
116
+ const INPUT_FIELDS = ["contentHash", "bucketKey", "contentType", "size"];
117
+ const mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;
118
+ const queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;
119
+ let upload = null;
120
+ for (const field of mutationType?.fields ?? []) {
121
+ const inputArg = field.args.find((a) => a.name === "input");
122
+ if (!inputArg) continue;
123
+ const inputTypeName = namedTypeName(inputArg.type);
124
+ const payloadTypeName = namedTypeName(field.type);
125
+ if (inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
126
+ upload = { uploadFieldName: field.name, inputTypeName };
127
+ break;
128
+ }
129
+ }
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
+ return {
135
+ ...upload,
136
+ ...downloadById
137
+ };
138
+ }
139
+ function resolveDownloadByIdField(schema, typeByName, queryType, uploadFieldName) {
140
+ const fileTypesWithDownloadUrl = /* @__PURE__ */ new Set();
141
+ for (const t of schema.types) {
142
+ if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
143
+ fileTypesWithDownloadUrl.add(t.name);
144
+ }
145
+ }
146
+ for (const field of queryType?.fields ?? []) {
147
+ const returnTypeName = namedTypeName(field.type);
148
+ if (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;
149
+ if (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {
150
+ return {
151
+ fileByIdField: field.name,
152
+ fileByIdArgName: "id",
153
+ fileTypeName: returnTypeName,
154
+ idScalarName: namedTypeName(field.args[0].type) ?? void 0
155
+ };
156
+ }
157
+ }
158
+ const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName);
159
+ if (connection) return connection;
160
+ const nodeField = queryType?.fields?.find(
161
+ (f) => f.name === "node" && f.args.some((a) => a.name === "nodeId")
162
+ );
163
+ if (nodeField && fileTypesWithDownloadUrl.size > 0) {
164
+ const preferred = uploadFieldName.replace(/^upload/, "");
165
+ const fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0];
166
+ return { fileByIdField: "node", fileByIdArgName: "nodeId", fileTypeName };
167
+ }
168
+ throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
169
+ }
170
+ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName) {
171
+ const EQUALITY_OPERATORS = ["equalTo", "eq"];
172
+ const candidates = [];
173
+ for (const field of queryType?.fields ?? []) {
174
+ const connTypeName = namedTypeName(field.type);
175
+ if (!connTypeName) continue;
176
+ const connType = typeByName.get(connTypeName);
177
+ if (connType?.kind !== "OBJECT" || !connType.fields) continue;
178
+ const nodesField = connType.fields.find((f) => {
179
+ if (!isListTypeRef(f.type)) return false;
180
+ const elem = namedTypeName(f.type);
181
+ return elem != null && fileTypesWithDownloadUrl.has(elem);
182
+ });
183
+ if (!nodesField) continue;
184
+ const fileTypeName = namedTypeName(nodesField.type);
185
+ for (const arg of field.args) {
186
+ const filterTypeName = namedTypeName(arg.type);
187
+ const filterType = filterTypeName ? typeByName.get(filterTypeName) : null;
188
+ if (filterType?.kind !== "INPUT_OBJECT" || !filterType.inputFields) continue;
189
+ const idField = filterType.inputFields.find((f) => f.name === PK_FIELD_NAME);
190
+ if (!idField) continue;
191
+ const idFieldTypeName = namedTypeName(idField.type);
192
+ const idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;
193
+ if (idFieldType?.kind === "INPUT_OBJECT" && idFieldType.inputFields) {
194
+ const opField = EQUALITY_OPERATORS.map(
195
+ (op) => idFieldType.inputFields.find((f) => f.name === op)
196
+ ).find((f) => f != null);
197
+ if (opField) {
198
+ candidates.push({
199
+ fileByIdField: field.name,
200
+ fileByIdArgName: "connection",
201
+ fileTypeName,
202
+ idScalarName: namedTypeName(opField.type) ?? void 0,
203
+ connectionFilterArgName: arg.name,
204
+ connectionIdField: idField.name,
205
+ connectionIdOperator: opField.name,
206
+ connectionNodesField: nodesField.name
207
+ });
208
+ break;
209
+ }
210
+ continue;
211
+ }
212
+ if (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName) {
213
+ candidates.push({
214
+ fileByIdField: field.name,
215
+ fileByIdArgName: "connection",
216
+ fileTypeName,
217
+ idScalarName: idFieldTypeName ?? void 0,
218
+ connectionFilterArgName: arg.name,
219
+ connectionIdField: idField.name,
220
+ connectionNodesField: nodesField.name
221
+ });
222
+ break;
223
+ }
224
+ }
225
+ }
226
+ if (candidates.length === 0) return null;
227
+ const preferred = uploadFieldName.replace(/^upload/, "");
228
+ return candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];
229
+ }
230
+ async function callUploadOp(execute, cap, input) {
231
+ const mutation = `
232
+ mutation SheetsUpload($input: ${cap.inputTypeName}!) {
233
+ ${cap.uploadFieldName}(input: $input) {
234
+ uploadUrl
235
+ fileId
236
+ key
237
+ deduplicated
238
+ }
239
+ }
240
+ `.trim();
241
+ const data = await execute(mutation, {
242
+ input: {
243
+ bucketKey: input.bucketKey,
244
+ contentHash: input.contentHash,
245
+ contentType: input.contentType,
246
+ size: input.size,
247
+ filename: input.filename
248
+ }
249
+ });
250
+ const payload = data?.[cap.uploadFieldName];
251
+ if (!payload) {
252
+ throw import_data.createError.badRequest("Upload failed: no payload returned from upload mutation.");
253
+ }
254
+ return payload;
255
+ }
256
+ async function presignedPut(url, buffer, contentType, onProgress) {
257
+ const total = buffer.byteLength;
258
+ if (onProgress && typeof XMLHttpRequest !== "undefined") {
259
+ await putWithXHR(url, buffer, contentType, total, onProgress);
260
+ return;
261
+ }
262
+ let response;
263
+ try {
264
+ response = await fetch(url, {
265
+ method: "PUT",
266
+ headers: { "Content-Type": contentType },
267
+ body: buffer
268
+ });
269
+ } catch (error) {
270
+ throw import_data.createError.network(error instanceof Error ? error : void 0);
271
+ }
272
+ if (!response.ok) {
273
+ const body = await response.text().catch(() => "");
274
+ throw import_data.createError.badRequest(`Upload failed: ${response.status} ${response.statusText}${body ? ` \u2014 ${body}` : ""}`);
275
+ }
276
+ onProgress?.({ loaded: total, total, percentage: 100 });
277
+ }
278
+ function putWithXHR(url, buffer, contentType, total, onProgress) {
279
+ return new Promise((resolve, reject) => {
280
+ const xhr = new XMLHttpRequest();
281
+ xhr.open("PUT", url);
282
+ xhr.setRequestHeader("Content-Type", contentType);
283
+ xhr.upload.addEventListener("progress", (event) => {
284
+ if (event.lengthComputable) {
285
+ onProgress({
286
+ loaded: event.loaded,
287
+ total: event.total,
288
+ percentage: Math.round(event.loaded / event.total * 100)
289
+ });
290
+ }
291
+ });
292
+ xhr.addEventListener("load", () => {
293
+ if (xhr.status >= 200 && xhr.status < 300) {
294
+ onProgress({ loaded: total, total, percentage: 100 });
295
+ resolve();
296
+ } else {
297
+ reject(import_data.createError.badRequest(`Upload failed: ${xhr.status} ${xhr.statusText}${xhr.responseText ? ` \u2014 ${xhr.responseText}` : ""}`));
298
+ }
299
+ });
300
+ xhr.addEventListener("error", () => reject(import_data.createError.network()));
301
+ xhr.send(buffer);
302
+ });
303
+ }
304
+ function toGlobalId(typeName, id) {
305
+ if (typeof btoa !== "function") {
306
+ throw import_data.createError.badRequest("Cannot encode the file node id: btoa is unavailable in this environment.");
307
+ }
308
+ return btoa(JSON.stringify([typeName, id]));
309
+ }
310
+ async function fetchDownloadUrl(execute, cap, fileId) {
311
+ if (cap.fileByIdArgName === "nodeId") {
312
+ const nodeId = toGlobalId(cap.fileTypeName, fileId);
313
+ const query2 = `
314
+ query SheetsDownloadUrl($nodeId: ID!) {
315
+ ${cap.fileByIdField}(nodeId: $nodeId) {
316
+ ... on ${cap.fileTypeName} {
317
+ downloadUrl
318
+ }
319
+ }
320
+ }
321
+ `.trim();
322
+ const data2 = await execute(query2, { nodeId });
323
+ const node = data2?.[cap.fileByIdField];
324
+ const url2 = node?.downloadUrl;
325
+ if (!url2) {
326
+ throw import_data.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
327
+ }
328
+ return url2;
329
+ }
330
+ if (cap.fileByIdArgName === "connection") {
331
+ const idScalar2 = cap.idScalarName ?? "ID";
332
+ const filterArg = cap.connectionFilterArgName;
333
+ const idField = cap.connectionIdField;
334
+ const nodesField = cap.connectionNodesField;
335
+ const filterLiteral = cap.connectionIdOperator ? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }` : `{ ${idField}: $id }`;
336
+ const query2 = `
337
+ query SheetsDownloadUrl($id: ${idScalar2}!) {
338
+ ${cap.fileByIdField}(${filterArg}: ${filterLiteral}, first: 1) {
339
+ ${nodesField} {
340
+ downloadUrl
341
+ }
342
+ }
343
+ }
344
+ `.trim();
345
+ const data2 = await execute(
346
+ query2,
347
+ { id: fileId }
348
+ );
349
+ const conn = data2?.[cap.fileByIdField];
350
+ const url2 = conn?.[nodesField]?.[0]?.downloadUrl;
351
+ if (!url2) {
352
+ throw import_data.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
353
+ }
354
+ return url2;
355
+ }
356
+ const idScalar = cap.idScalarName ?? "ID";
357
+ const query = `
358
+ query SheetsDownloadUrl($id: ${idScalar}!) {
359
+ ${cap.fileByIdField}(id: $id) {
360
+ id
361
+ downloadUrl
362
+ }
363
+ }
364
+ `.trim();
365
+ const data = await execute(query, { id: fileId });
366
+ const file = data?.[cap.fileByIdField];
367
+ const url = file?.downloadUrl;
368
+ if (!url) {
369
+ throw import_data.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
370
+ }
371
+ return url;
372
+ }
373
+
374
+ // src/context/sheets-execute.ts
375
+ var import_data3 = require("@constructive-io/data");
48
376
  function documentToString(document) {
49
377
  if (typeof document === "string") return document;
50
378
  if (document instanceof String) return document.toString();
51
379
  if (document && typeof document === "object" && "kind" in document) {
52
- return (0, import_graphql.print)(document);
380
+ return (0, import_graphql2.print)(document);
53
381
  }
54
382
  if (document === null || document === void 0) {
55
- throw import_data.createError.badRequest("Invalid GraphQL document: null or undefined");
383
+ throw import_data2.createError.badRequest("Invalid GraphQL document: null or undefined");
56
384
  }
57
385
  return String(document);
58
386
  }
@@ -67,18 +395,18 @@ function parseGraphQLResponse(response, onAuthError) {
67
395
  const message = error.message || "GraphQL query failed";
68
396
  if (code === "UNAUTHENTICATED" || hasAuthMessage(message)) {
69
397
  onAuthError?.();
70
- return import_data.createError.unauthorized("Authentication required. Please log in again.");
398
+ return import_data2.createError.unauthorized("Authentication required. Please log in again.");
71
399
  }
72
400
  if (code === "FORBIDDEN") {
73
- return import_data.createError.forbidden("You do not have permission to perform this action.");
401
+ return import_data2.createError.forbidden("You do not have permission to perform this action.");
74
402
  }
75
- return import_data.createError.graphql(message, code);
403
+ return import_data2.createError.graphql(message, code);
76
404
  }
77
405
  function createSheetsExecute(config, getToken) {
78
406
  return async (document, variables) => {
79
407
  const url = config.endpoint;
80
408
  if (!url) {
81
- throw import_data.createError.badRequest("No GraphQL endpoint configured.");
409
+ throw import_data2.createError.badRequest("No GraphQL endpoint configured.");
82
410
  }
83
411
  const token = getToken();
84
412
  const headers = {
@@ -99,29 +427,29 @@ function createSheetsExecute(config, getToken) {
99
427
  })
100
428
  });
101
429
  } catch (error) {
102
- throw import_data.createError.network(error instanceof Error ? error : void 0);
430
+ throw import_data2.createError.network(error instanceof Error ? error : void 0);
103
431
  }
104
432
  if (!response.ok) {
105
433
  const { status, statusText } = response;
106
434
  if (status === 401) {
107
435
  config.onAuthError?.();
108
- throw import_data.createError.unauthorized("Authentication required. Please log in again.");
436
+ throw import_data2.createError.unauthorized("Authentication required. Please log in again.");
109
437
  }
110
438
  if (status === 403) {
111
- throw import_data.createError.forbidden("You do not have permission to perform this action.");
439
+ throw import_data2.createError.forbidden("You do not have permission to perform this action.");
112
440
  }
113
441
  if (status === 404) {
114
- throw import_data.createError.notFound("The requested endpoint does not exist.");
442
+ throw import_data2.createError.notFound("The requested endpoint does not exist.");
115
443
  }
116
444
  try {
117
445
  const body = await response.json();
118
446
  if (body.errors?.length) {
119
- throw import_data.createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);
447
+ throw import_data2.createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);
120
448
  }
121
449
  } catch (e) {
122
- if (e instanceof import_data.DataError) throw e;
450
+ if (e instanceof import_data2.DataError) throw e;
123
451
  }
124
- throw import_data.createError.badRequest(`Request failed: ${status} ${statusText}`);
452
+ throw import_data2.createError.badRequest(`Request failed: ${status} ${statusText}`);
125
453
  }
126
454
  const result = await response.json();
127
455
  const graphqlError = parseGraphQLResponse(result, config.onAuthError);
@@ -132,64 +460,40 @@ function createSheetsExecute(config, getToken) {
132
460
  };
133
461
  }
134
462
  function createSheetsUpload(config, getToken) {
135
- return async (file, path) => {
463
+ const execute = config.execute ?? createSheetsExecute(config, getToken);
464
+ return async (file, _path, options) => {
136
465
  if (!config.endpoint) {
137
- throw import_data.createError.badRequest("No GraphQL endpoint configured.");
138
- }
139
- const url = config.endpoint.replace(/\/graphql\/?$/, "/upload");
140
- const token = getToken();
141
- const formData = new FormData();
142
- formData.append("file", file);
143
- if (path) formData.append("path", path);
144
- const headers = {};
145
- if (token) {
146
- headers["Authorization"] = `Bearer ${token}`;
147
- }
148
- let response;
149
- try {
150
- response = await fetch(url, {
151
- method: "POST",
152
- headers,
153
- body: formData
154
- });
155
- } catch (error) {
156
- throw import_data.createError.network(error instanceof Error ? error : void 0);
157
- }
158
- if (!response.ok) {
159
- if (response.status === 401) {
160
- config.onAuthError?.();
161
- throw import_data.createError.unauthorized("Authentication required. Please log in again.");
162
- }
163
- if (response.status === 403) {
164
- throw import_data.createError.forbidden("You do not have permission to perform this action.");
165
- }
166
- try {
167
- const body = await response.json();
168
- const graphqlError = parseGraphQLResponse(body, config.onAuthError);
169
- if (graphqlError) {
170
- throw graphqlError;
171
- }
172
- if (body.errors?.length) {
173
- const firstError = body.errors[0];
174
- throw import_data.createError.graphql(firstError.message || "Upload failed", firstError.extensions?.code);
175
- }
176
- } catch (error) {
177
- if (error instanceof import_data.DataError) throw error;
178
- }
179
- if (response.status === 400) throw import_data.createError.badRequest("No file provided for upload.");
180
- if (response.status === 413) throw import_data.createError.badRequest("File is too large. Maximum size is 10 MB.");
181
- throw import_data.createError.badRequest(`Upload failed: ${response.status} ${response.statusText}`);
466
+ throw import_data2.createError.badRequest("No GraphQL endpoint configured.");
182
467
  }
183
- const result = await response.json();
184
- if (result.errors?.length) {
185
- const graphqlError = parseGraphQLResponse(result, config.onAuthError);
186
- if (graphqlError) {
187
- throw graphqlError;
468
+ const bucketKey = config.upload?.bucketKey ?? "public";
469
+ const contentType = file.type || "application/octet-stream";
470
+ const buffer = await file.arrayBuffer();
471
+ const contentHash = await sha256HexFromBuffer(buffer);
472
+ const cap = await discoverUploadCapability(config.endpoint, execute);
473
+ const payload = await callUploadOp(execute, cap, {
474
+ bucketKey,
475
+ contentHash,
476
+ contentType,
477
+ size: file.size,
478
+ filename: file.name
479
+ });
480
+ if (!payload.deduplicated) {
481
+ if (!payload.uploadUrl) {
482
+ throw import_data2.createError.badRequest("Upload failed: server returned no uploadUrl for a non-deduplicated file.");
188
483
  }
189
- const firstError = result.errors[0];
190
- throw import_data.createError.graphql(firstError.message || "Upload failed", firstError.extensions?.code);
484
+ await presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);
485
+ } else {
486
+ options?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });
191
487
  }
192
- return result;
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
+ };
193
497
  };
194
498
  }
195
499
 
@@ -504,11 +808,11 @@ function shallowEqualArrays(a, b) {
504
808
 
505
809
  // src/store/relation-info-slice.ts
506
810
  var import_inflekt2 = require("inflekt");
507
- var import_data4 = require("@constructive-io/data");
811
+ var import_data5 = require("@constructive-io/data");
508
812
 
509
813
  // src/utils/relation-utils.ts
510
814
  var import_inflekt = require("inflekt");
511
- var import_data3 = require("@constructive-io/data");
815
+ var import_data4 = require("@constructive-io/data");
512
816
  function isJunctionTablePure(junctionTableName, leftFkField, rightFkField, metaTables) {
513
817
  if (!leftFkField || !rightFkField) return true;
514
818
  const junctionMeta = metaTables.find((t) => t?.name === junctionTableName);
@@ -516,7 +820,7 @@ function isJunctionTablePure(junctionTableName, leftFkField, rightFkField, metaT
516
820
  const exemptFields = /* @__PURE__ */ new Set(["id", leftFkField, rightFkField]);
517
821
  for (const field of junctionMeta.fields) {
518
822
  if (!field?.name) continue;
519
- const camelName = (0, import_data3.pgFieldToCamelCase)(field.name);
823
+ const camelName = (0, import_data4.pgFieldToCamelCase)(field.name);
520
824
  if (exemptFields.has(camelName)) continue;
521
825
  if (field.isNotNull && !field.hasDefault) return false;
522
826
  }
@@ -575,10 +879,10 @@ function createRelationInfoSlice(set, get) {
575
879
  }
576
880
  function toCleanTables(meta) {
577
881
  const tables = meta?._meta?.tables ?? [];
578
- return tables.filter((table) => table != null).map((table) => (0, import_data4.cleanTable)(table));
882
+ return tables.filter((table) => table != null).map((table) => (0, import_data5.cleanTable)(table));
579
883
  }
580
- function firstFieldName(fields) {
581
- return fields[0]?.name;
884
+ function firstFieldName(fields2) {
885
+ return fields2[0]?.name;
582
886
  }
583
887
  function findForeignKeyInRelatedTable(currentTableName, relatedTableName, allTables, rawMetaTables) {
584
888
  const relatedTable = allTables.find((t) => t.name === relatedTableName);
@@ -597,7 +901,7 @@ function findForeignKeyInRelatedTable(currentTableName, relatedTableName, allTab
597
901
  const refName = fk.refTable?.name;
598
902
  if (refName && refName.toLowerCase() === currentTableName.toLowerCase()) {
599
903
  const fieldName = fk.fields?.[0]?.name;
600
- if (fieldName) return (0, import_data4.pgFieldToCamelCase)(fieldName);
904
+ if (fieldName) return (0, import_data5.pgFieldToCamelCase)(fieldName);
601
905
  }
602
906
  }
603
907
  }
@@ -742,8 +1046,9 @@ function createSheetsStore() {
742
1046
  isAuthenticated: false,
743
1047
  accessToken: null,
744
1048
  expiresAt: null,
745
- setAuthenticated: (token, expiresAt) => set({ isAuthenticated: true, accessToken: token, expiresAt }),
746
- setUnauthenticated: () => set({ isAuthenticated: false, accessToken: null, expiresAt: null })
1049
+ identityKey: null,
1050
+ setAuthenticated: (token, expiresAt, identityKey = null) => set({ isAuthenticated: true, accessToken: token, expiresAt, identityKey }),
1051
+ setUnauthenticated: () => set({ isAuthenticated: false, accessToken: null, expiresAt: null, identityKey: null })
747
1052
  }));
748
1053
  }
749
1054
  var SheetsStoreContext = (0, import_react2.createContext)(null);
@@ -769,6 +1074,7 @@ function getStoredToken(databaseId) {
769
1074
  if (!raw) return null;
770
1075
  const parsed = JSON.parse(raw);
771
1076
  if (!parsed.accessToken || !parsed.expiresAt) return null;
1077
+ if (parsed.identityKey != null && typeof parsed.identityKey !== "string") return null;
772
1078
  return parsed;
773
1079
  } catch {
774
1080
  return null;
@@ -793,13 +1099,35 @@ function setSheetsLocale(locale) {
793
1099
  active2 = locale || DEFAULT_LOCALE;
794
1100
  }
795
1101
 
1102
+ // src/hooks/query-keys.ts
1103
+ var sheetsQueryKeys = {
1104
+ root: ["sheets"],
1105
+ scope: (scope) => ["sheets", scope],
1106
+ meta: (scope) => [...sheetsQueryKeys.scope(scope), "meta"],
1107
+ typeFields: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "type-fields", typeName],
1108
+ enumValues: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "enum-values", typeName],
1109
+ relations: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "relations", tableName],
1110
+ table: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "table", tableName],
1111
+ tableRows: (scope, tableName, options) => [...sheetsQueryKeys.table(scope, tableName), "rows", options],
1112
+ tableRow: (scope, tableName, id) => [...sheetsQueryKeys.table(scope, tableName), "row", id],
1113
+ tableCount: (scope, tableName, where) => [...sheetsQueryKeys.table(scope, tableName), "count", where],
1114
+ infiniteTable: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "infinite-table", tableName],
1115
+ infiniteTablePage: (scope, tableName, pageIndex, options) => [...sheetsQueryKeys.infiniteTable(scope, tableName), "page", pageIndex, options],
1116
+ infiniteTableTotalCount: (scope, tableName, where) => [...sheetsQueryKeys.infiniteTable(scope, tableName), "totalCount", where],
1117
+ cursorTable: (scope, tableName, options) => [...sheetsQueryKeys.scope(scope), "cursor-table", tableName, options]
1118
+ };
1119
+
796
1120
  // src/context/sheets-provider.tsx
797
1121
  var import_jsx_runtime = require("react/jsx-runtime");
798
1122
  function SheetsProvider({ config, children }) {
1123
+ const providerInstanceId = (0, import_react3.useId)();
799
1124
  const storeRef = (0, import_react3.useRef)(null);
800
1125
  if (!storeRef.current) {
801
1126
  storeRef.current = createSheetsStore();
802
1127
  }
1128
+ const store = storeRef.current;
1129
+ const standaloneIdentityKey = (0, import_zustand2.useStore)(store, (state) => state.identityKey);
1130
+ const standaloneAccessToken = (0, import_zustand2.useStore)(store, (state) => state.accessToken);
803
1131
  setSheetsLogger(config.logger);
804
1132
  setSheetsLocale(config.locale);
805
1133
  (0, import_react3.useEffect)(() => {
@@ -807,24 +1135,24 @@ function SheetsProvider({ config, children }) {
807
1135
  setSheetsLocale(config.locale);
808
1136
  }, [config.logger, config.locale]);
809
1137
  (0, import_react3.useEffect)(() => {
810
- const store = storeRef.current?.getState();
811
- if (!store) return;
1138
+ const store2 = storeRef.current?.getState();
1139
+ if (!store2) return;
812
1140
  if (config.auth.mode !== "standalone") {
813
- store.setUnauthenticated();
1141
+ store2.setUnauthenticated();
814
1142
  return;
815
1143
  }
816
1144
  const databaseId = config.databaseId || "default";
817
1145
  const stored = getStoredToken(databaseId);
818
1146
  if (!stored) {
819
- store.setUnauthenticated();
1147
+ store2.setUnauthenticated();
820
1148
  return;
821
1149
  }
822
1150
  const expiresAt = new Date(stored.expiresAt);
823
1151
  if (expiresAt > /* @__PURE__ */ new Date()) {
824
- store.setAuthenticated(stored.accessToken, stored.expiresAt);
1152
+ store2.setAuthenticated(stored.accessToken, stored.expiresAt, stored.identityKey ?? null);
825
1153
  return;
826
1154
  }
827
- store.setUnauthenticated();
1155
+ store2.setUnauthenticated();
828
1156
  }, [config.auth.mode, config.databaseId]);
829
1157
  const internalQueryClient = (0, import_react3.useMemo)(
830
1158
  () => new import_react_query.QueryClient({
@@ -843,8 +1171,8 @@ function SheetsProvider({ config, children }) {
843
1171
  if (config.auth.mode === "embedded") {
844
1172
  return config.auth.getToken;
845
1173
  }
846
- return () => storeRef.current?.getState().accessToken ?? null;
847
- }, [config.auth]);
1174
+ return () => store.getState().accessToken ?? null;
1175
+ }, [config.auth, store]);
848
1176
  const execute = (0, import_react3.useMemo)(() => {
849
1177
  if (config.execute) return config.execute;
850
1178
  return createSheetsExecute(config, getToken);
@@ -853,18 +1181,47 @@ function SheetsProvider({ config, children }) {
853
1181
  if (config.executeUpload) return config.executeUpload;
854
1182
  return createSheetsUpload(config, getToken);
855
1183
  }, [config, getToken]);
1184
+ const configuredIdentityKey = config.auth.mode === "embedded" ? config.auth.getIdentityKey?.() ?? null : standaloneIdentityKey;
1185
+ const activeToken = config.auth.mode === "embedded" ? config.auth.getToken() : standaloneAccessToken;
1186
+ const authGenerationRef = (0, import_react3.useRef)({ mode: config.auth.mode, token: activeToken, generation: 0 });
1187
+ if (authGenerationRef.current.mode !== config.auth.mode || authGenerationRef.current.token !== activeToken) {
1188
+ authGenerationRef.current = {
1189
+ mode: config.auth.mode,
1190
+ token: activeToken,
1191
+ generation: authGenerationRef.current.generation + 1
1192
+ };
1193
+ }
1194
+ const identityKey = configuredIdentityKey ?? `anonymous:${providerInstanceId}:${authGenerationRef.current.generation}`;
856
1195
  const scopeKey = (0, import_react3.useMemo)(
857
1196
  () => ({
858
1197
  databaseId: config.databaseId ?? null,
859
- endpoint: config.endpoint
1198
+ endpoint: config.endpoint,
1199
+ identityKey
860
1200
  }),
861
- [config.databaseId, config.endpoint]
1201
+ [config.databaseId, config.endpoint, identityKey]
862
1202
  );
1203
+ (0, import_react3.useEffect)(() => {
1204
+ return () => {
1205
+ void queryClient.cancelQueries({ queryKey: sheetsQueryKeys.scope(scopeKey) });
1206
+ };
1207
+ }, [queryClient, scopeKey]);
863
1208
  const contextValue = (0, import_react3.useMemo)(
864
1209
  () => ({ config, execute, executeUpload, scopeKey }),
865
1210
  [config, execute, executeUpload, scopeKey]
866
1211
  );
867
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_query.QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsStoreContext.Provider, { value: storeRef.current, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsContext.Provider, { value: contextValue, children }) }) });
1212
+ 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 }) }) });
1213
+ }
1214
+
1215
+ // src/testing/meta-contract-fixture.ts
1216
+ var import_data6 = require("@constructive-io/data");
1217
+ var fields = (names) => names.map((name) => ({ name }));
1218
+ function createMetaContractFixture() {
1219
+ return Object.fromEntries(
1220
+ Object.entries(import_data6.META_CONTRACT_REQUIREMENTS).map(([alias, requirement]) => [
1221
+ alias,
1222
+ { name: requirement.typeName, fields: fields(requirement.fields) }
1223
+ ])
1224
+ );
868
1225
  }
869
1226
 
870
1227
  // src/testing/mock-sheets-provider.tsx
@@ -873,13 +1230,14 @@ function documentToString2(document) {
873
1230
  if (typeof document === "string") return document;
874
1231
  if (document instanceof String) return document.toString();
875
1232
  if (document && typeof document === "object" && "kind" in document) {
876
- return (0, import_graphql2.print)(document);
1233
+ return (0, import_graphql3.print)(document);
877
1234
  }
878
1235
  return String(document ?? "");
879
1236
  }
880
- function buildMetaField(field) {
1237
+ function buildMetaField(field, primaryKeyFields) {
881
1238
  return {
882
1239
  name: field.name,
1240
+ isPrimaryKey: primaryKeyFields.has(field.name),
883
1241
  isNotNull: false,
884
1242
  hasDefault: false,
885
1243
  type: {
@@ -893,26 +1251,33 @@ function buildMetaField(field) {
893
1251
  };
894
1252
  }
895
1253
  function buildMetaTable(table) {
1254
+ const primaryKeyFields = table.primaryKeyFields ?? (table.fields.some((field) => field.name === "id") ? ["id"] : []);
1255
+ const primaryKeySet = new Set(primaryKeyFields);
1256
+ const primaryKeyMetaFields = table.fields.filter((field) => primaryKeySet.has(field.name)).map((field) => buildMetaField(field, primaryKeySet));
896
1257
  return {
897
1258
  name: table.name,
898
1259
  schemaName: "public",
899
1260
  query: {
900
- all: (0, import_data5.toCamelCasePlural)(table.name),
901
- create: (0, import_data5.toCreateMutationName)(table.name),
902
- delete: (0, import_data5.toDeleteMutationName)(table.name),
903
- one: (0, import_data5.toCamelCaseSingular)(table.name),
904
- update: (0, import_data5.toUpdateMutationName)(table.name)
1261
+ all: (0, import_data7.toCamelCasePlural)(table.name),
1262
+ create: (0, import_data7.toCreateMutationName)(table.name),
1263
+ delete: (0, import_data7.toDeleteMutationName)(table.name),
1264
+ one: (0, import_data7.toCamelCaseSingular)(table.name),
1265
+ update: (0, import_data7.toUpdateMutationName)(table.name)
905
1266
  },
906
- fields: table.fields.map(buildMetaField),
1267
+ fields: table.fields.map((field) => buildMetaField(field, primaryKeySet)),
907
1268
  inflection: {
908
- allRows: (0, import_data5.toCamelCasePlural)(table.name),
909
- connection: (0, import_data5.toCamelCasePlural)(table.name),
1269
+ allRows: (0, import_data7.toCamelCasePlural)(table.name),
1270
+ connection: (0, import_data7.toCamelCasePlural)(table.name),
910
1271
  tableType: table.name
911
1272
  },
912
1273
  indexes: [],
913
- constraints: { primaryKey: null, unique: [], foreignKey: [] },
1274
+ constraints: {
1275
+ primaryKey: primaryKeyMetaFields.length > 0 ? { name: `${table.name}_pkey`, fields: primaryKeyMetaFields } : null,
1276
+ unique: [],
1277
+ foreignKey: []
1278
+ },
914
1279
  foreignKeyConstraints: [],
915
- primaryKeyConstraints: [],
1280
+ primaryKeyConstraints: primaryKeyMetaFields.length > 0 ? [{ name: `${table.name}_pkey`, fields: primaryKeyMetaFields }] : [],
916
1281
  uniqueConstraints: [],
917
1282
  relations: { belongsTo: [], has: [], hasOne: [], hasMany: [], manyToMany: [] }
918
1283
  };
@@ -925,7 +1290,7 @@ function buildMetaResponse(tables) {
925
1290
  };
926
1291
  }
927
1292
  function buildListResponse(table) {
928
- const field = (0, import_data5.toCamelCasePlural)(table.name);
1293
+ const field = (0, import_data7.toCamelCasePlural)(table.name);
929
1294
  return {
930
1295
  [field]: {
931
1296
  nodes: table.rows,
@@ -985,13 +1350,13 @@ function findMutationTable(query, tables) {
985
1350
  let best = null;
986
1351
  for (const table of tables) {
987
1352
  const candidates = [
988
- { op: "create", mutationName: (0, import_data5.toCreateMutationName)(table.name) },
989
- { op: "update", mutationName: (0, import_data5.toUpdateMutationName)(table.name) },
990
- { op: "delete", mutationName: (0, import_data5.toDeleteMutationName)(table.name) }
1353
+ { op: "create", mutationName: (0, import_data7.toCreateMutationName)(table.name) },
1354
+ { op: "update", mutationName: (0, import_data7.toUpdateMutationName)(table.name) },
1355
+ { op: "delete", mutationName: (0, import_data7.toDeleteMutationName)(table.name) }
991
1356
  ];
992
1357
  for (const c of candidates) {
993
1358
  if (query.includes(c.mutationName) && (!best || c.mutationName.length > best.mutationName.length)) {
994
- best = { table, op: c.op, mutationName: c.mutationName, singular: (0, import_data5.toCamelCaseSingular)(table.name) };
1359
+ best = { table, op: c.op, mutationName: c.mutationName, singular: (0, import_data7.toCamelCaseSingular)(table.name) };
995
1360
  }
996
1361
  }
997
1362
  }
@@ -1001,7 +1366,7 @@ function findListTable(query, tables) {
1001
1366
  let best = null;
1002
1367
  let bestLen = 0;
1003
1368
  for (const table of tables) {
1004
- const plural = (0, import_data5.toCamelCasePlural)(table.name);
1369
+ const plural = (0, import_data7.toCamelCasePlural)(table.name);
1005
1370
  if (query.includes(plural) && plural.length > bestLen) {
1006
1371
  best = table;
1007
1372
  bestLen = plural.length;
@@ -1017,6 +1382,9 @@ function createMockExecute(opts) {
1017
1382
  }
1018
1383
  const execute = async (document, variables) => {
1019
1384
  const query = documentToString2(document);
1385
+ if (query.includes("ConstructiveMetaContract")) {
1386
+ return createMetaContractFixture();
1387
+ }
1020
1388
  if (isMetaQuery(query)) {
1021
1389
  return buildMetaResponse(opts.tables);
1022
1390
  }