@constructive-io/sheets 0.13.0 → 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 +555 -680
  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-26J3DVW7.js → chunk-BGL6EBTE.js} +116 -173
  12. package/dist/chunk-BGL6EBTE.js.map +1 -0
  13. package/dist/{chunk-MXVNIKES.js → chunk-BYAYBXVB.js} +2 -2
  14. package/dist/{chunk-CBXNKMN6.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 +789 -607
  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 +128 -57
  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-26J3DVW7.js.map +0 -1
  39. package/dist/chunk-CBXNKMN6.js.map +0 -1
  40. package/dist/chunk-H5HR5HUJ.js.map +0 -1
  41. package/dist/chunk-HETVHNMD.js +0 -123
  42. package/dist/chunk-HETVHNMD.js.map +0 -1
  43. package/dist/chunk-PZL2BCWF.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
package/dist/advanced.cjs CHANGED
@@ -166,7 +166,7 @@ var init_cell_type_groups = __esm({
166
166
  "date-array",
167
167
  "tags"
168
168
  ]);
169
- MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file", "video", "audio", "upload"]);
169
+ MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file", "video", "audio", "upload", "attachment"]);
170
170
  }
171
171
  });
172
172
 
@@ -1579,14 +1579,29 @@ function GeometryEditorDom({ value, fieldMeta, onCommit, onCancel }) {
1579
1579
  }
1580
1580
 
1581
1581
  // src/grid-dom/editors/image-editor.tsx
1582
- var import_react17 = require("react");
1582
+ var import_react16 = require("react");
1583
1583
 
1584
1584
  // src/grid/editors/image-editor.tsx
1585
- var import_react15 = require("react");
1585
+ var import_react14 = require("react");
1586
1586
  var import_lucide_react4 = require("lucide-react");
1587
- var import_react16 = require("motion/react");
1587
+ var import_react15 = require("motion/react");
1588
1588
  var import_toast = require("@constructive-io/ui/toast");
1589
1589
 
1590
+ // src/hooks/use-sheets-upload.ts
1591
+ var import_react_query3 = require("@tanstack/react-query");
1592
+ var import_data8 = require("@constructive-io/data");
1593
+
1594
+ // src/adapter/postgraphile-adapter.ts
1595
+ var import_graphql = require("graphql");
1596
+ var import_data7 = require("@constructive-io/data");
1597
+
1598
+ // src/hooks/use-sheets-table.ts
1599
+ var import_react10 = require("react");
1600
+ var import_react_query2 = require("@tanstack/react-query");
1601
+
1602
+ // src/hooks/use-sheets-meta.ts
1603
+ var import_react_query = require("@tanstack/react-query");
1604
+
1590
1605
  // src/context/sheets-context.ts
1591
1606
  var import_react9 = require("react");
1592
1607
  var SheetsContext = (0, import_react9.createContext)(null);
@@ -1598,43 +1613,6 @@ function useSheetsContext() {
1598
1613
  return ctx;
1599
1614
  }
1600
1615
 
1601
- // src/store/sheets-store.ts
1602
- var import_react10 = require("react");
1603
- var import_zustand = require("zustand");
1604
- var SheetsStoreContext = (0, import_react10.createContext)(null);
1605
- function useSheetsStore(selector) {
1606
- const store = (0, import_react10.useContext)(SheetsStoreContext);
1607
- if (!store) {
1608
- throw new Error("useSheetsStore must be used within a <SheetsProvider>");
1609
- }
1610
- return (0, import_zustand.useStore)(store, selector);
1611
- }
1612
- function useSheetsStoreApi() {
1613
- const store = (0, import_react10.useContext)(SheetsStoreContext);
1614
- if (!store) {
1615
- throw new Error("useSheetsStoreApi must be used within a <SheetsProvider>");
1616
- }
1617
- return store;
1618
- }
1619
-
1620
- // src/hooks/use-sheets-upload.ts
1621
- var import_react12 = require("react");
1622
- var import_react_query3 = require("@tanstack/react-query");
1623
- var import_data11 = require("@constructive-io/data");
1624
-
1625
- // src/hooks/use-sheets-meta.ts
1626
- var import_react_query2 = require("@tanstack/react-query");
1627
-
1628
- // src/adapter/postgraphile-adapter.ts
1629
- var import_data7 = require("@constructive-io/data");
1630
-
1631
- // src/hooks/use-sheets-table.ts
1632
- var import_react11 = require("react");
1633
- var import_react_query = require("@tanstack/react-query");
1634
- var import_data4 = require("@constructive-io/data");
1635
- var import_data5 = require("@constructive-io/data");
1636
- var import_data6 = require("@constructive-io/data");
1637
-
1638
1616
  // src/hooks/query-keys.ts
1639
1617
  function isSheetsScopeKey(value) {
1640
1618
  if (!value || typeof value !== "object") return false;
@@ -1653,6 +1631,7 @@ var sheetsQueryKeys = {
1653
1631
  root: ["sheets"],
1654
1632
  scope: (scope) => ["sheets", scope],
1655
1633
  meta: (scope) => [...sheetsQueryKeys.scope(scope), "meta"],
1634
+ mediaUrl: (scope, endpoint, id) => [...sheetsQueryKeys.scope(scope), "media-url", endpoint, id],
1656
1635
  typeFields: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "type-fields", typeName],
1657
1636
  enumValues: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "enum-values", typeName],
1658
1637
  relations: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "relations", tableName],
@@ -1666,6 +1645,30 @@ var sheetsQueryKeys = {
1666
1645
  cursorTable: (scope, tableName, options) => [...sheetsQueryKeys.scope(scope), "cursor-table", tableName, options]
1667
1646
  };
1668
1647
 
1648
+ // src/hooks/use-sheets-meta.ts
1649
+ var metaKey = (scope) => sheetsQueryKeys.meta(scope);
1650
+ function useSheetsMeta(options = {}) {
1651
+ const { enabled = true } = options;
1652
+ const { execute, scopeKey } = useSheetsContext();
1653
+ const adapter = useSheetsAdapter();
1654
+ return (0, import_react_query.useQuery)({
1655
+ queryKey: metaKey(scopeKey),
1656
+ queryFn: () => adapter.fetchMeta(execute),
1657
+ staleTime: 5 * 60 * 1e3,
1658
+ // 5 min - finite so invalidation + remount triggers refetch
1659
+ gcTime: 30 * 60 * 1e3,
1660
+ // 30 min - survive long schema-editing sessions
1661
+ refetchOnMount: true,
1662
+ // Respect staleTime and refetch stale metadata on mount
1663
+ enabled
1664
+ });
1665
+ }
1666
+
1667
+ // src/hooks/use-sheets-table.ts
1668
+ var import_data4 = require("@constructive-io/data");
1669
+ var import_data5 = require("@constructive-io/data");
1670
+ var import_data6 = require("@constructive-io/data");
1671
+
1669
1672
  // src/hooks/relation-field-resolution.ts
1670
1673
  var import_inflekt = require("inflekt");
1671
1674
  var import_data = require("@constructive-io/data");
@@ -1981,20 +1984,20 @@ function transformToPostGraphileVariables(table, options = {}) {
1981
1984
  return variables;
1982
1985
  }
1983
1986
  function useSheetsTable(tableName, options = {}) {
1984
- const queryClient = (0, import_react_query.useQueryClient)();
1987
+ const queryClient = (0, import_react_query2.useQueryClient)();
1985
1988
  const { execute, scopeKey } = useSheetsContext();
1986
1989
  const { data: meta } = useSheetsMeta();
1987
1990
  const adapter = useSheetsAdapter();
1988
- const metaTables = (0, import_react11.useMemo)(() => {
1991
+ const metaTables = (0, import_react10.useMemo)(() => {
1989
1992
  if (!meta?._meta?.tables) return [];
1990
1993
  return meta._meta.tables.filter((candidate) => candidate != null);
1991
1994
  }, [meta]);
1992
- const tables = (0, import_react11.useMemo)(() => metaTables.map(import_data4.cleanTable), [metaTables]);
1993
- const table = (0, import_react11.useMemo)(
1995
+ const tables = (0, import_react10.useMemo)(() => metaTables.map(import_data4.cleanTable), [metaTables]);
1996
+ const table = (0, import_react10.useMemo)(
1994
1997
  () => tables.find((candidate) => candidate.name === tableName) ?? null,
1995
1998
  [tables, tableName]
1996
1999
  );
1997
- const tableMeta = (0, import_react11.useMemo)(
2000
+ const tableMeta = (0, import_react10.useMemo)(
1998
2001
  () => metaTables.find((candidate) => candidate.name === tableName) ?? null,
1999
2002
  [metaTables, tableName]
2000
2003
  );
@@ -2022,7 +2025,7 @@ function useSheetsTable(tableName, options = {}) {
2022
2025
  isLoading,
2023
2026
  error,
2024
2027
  refetch
2025
- } = (0, import_react_query.useQuery)({
2028
+ } = (0, import_react_query2.useQuery)({
2026
2029
  queryKey: sheetsTableQueryKeys.tableRows(scopeKey, tableName, finalQueryOptions),
2027
2030
  queryFn: async () => {
2028
2031
  if (!table) {
@@ -2065,7 +2068,7 @@ function useSheetsTable(tableName, options = {}) {
2065
2068
  });
2066
2069
  const rowsData = data?.rows ?? [];
2067
2070
  const totalCount = data?.totalCount ?? 0;
2068
- const createMutation = (0, import_react_query.useMutation)({
2071
+ const createMutation = (0, import_react_query2.useMutation)({
2069
2072
  mutationKey: sheetsTableMutationKeys.create(scopeKey, tableName),
2070
2073
  mutationFn: async (data2) => {
2071
2074
  if (!table || !tableMeta) {
@@ -2088,7 +2091,7 @@ function useSheetsTable(tableName, options = {}) {
2088
2091
  }
2089
2092
  }
2090
2093
  });
2091
- const updateMutation = (0, import_react_query.useMutation)({
2094
+ const updateMutation = (0, import_react_query2.useMutation)({
2092
2095
  mutationKey: sheetsTableMutationKeys.update(scopeKey, tableName),
2093
2096
  mutationFn: async ({ id, patch }) => {
2094
2097
  if (!table || !tableMeta) {
@@ -2142,7 +2145,7 @@ function useSheetsTable(tableName, options = {}) {
2142
2145
  }
2143
2146
  }
2144
2147
  });
2145
- const deleteMutation = (0, import_react_query.useMutation)({
2148
+ const deleteMutation = (0, import_react_query2.useMutation)({
2146
2149
  mutationKey: sheetsTableMutationKeys.delete(scopeKey, tableName),
2147
2150
  mutationFn: async (idOrPk) => {
2148
2151
  if (!table || !tableMeta) {
@@ -2344,11 +2347,17 @@ function createPostGraphileAdapter() {
2344
2347
  },
2345
2348
  async updateRow(ctx, id, patch, execute, options = {}) {
2346
2349
  const { table, allTables, tableName } = ctx;
2347
- const doc = (0, import_data7.buildPostGraphileUpdate)(table, allTables, {
2350
+ const mutationName = (0, import_data7.toUpdateMutationName)(tableName, table);
2351
+ const returning = options.returning && table.fields.filter((field) => options.returning?.includes(field.name)).map((field) => (0, import_graphql.print)((0, import_data7.getCustomAstForCleanField)(field))).join(" ");
2352
+ const payloadTable = returning && table.query ? { ...table, query: { ...table.query, one: null } } : table;
2353
+ const singularName = (0, import_data7.toCamelCaseSingular)(tableName, payloadTable);
2354
+ const patchFieldName = (0, import_data7.toPatchFieldName)(tableName, payloadTable);
2355
+ const doc = returning ? `mutation SheetsUpdateFields($input: ${mutationName[0].toUpperCase()}${mutationName.slice(1)}Input!) {
2356
+ ${mutationName}(input: $input) { ${singularName} { ${returning} } }
2357
+ }` : (0, import_data7.buildPostGraphileUpdate)(table, allTables, {
2348
2358
  ...options,
2349
2359
  fieldSelection: options.fieldSelection || "display"
2350
2360
  });
2351
- const patchFieldName = (0, import_data7.toPatchFieldName)(tableName, table);
2352
2361
  const sanitizedPatch = (0, import_data7.prepareUpdateInput)(patch);
2353
2362
  if (Object.keys(sanitizedPatch).length === 0) return null;
2354
2363
  const normalizedPatch = normalizeMutationEnums(ctx, sanitizedPatch, execute);
@@ -2359,8 +2368,6 @@ function createPostGraphileAdapter() {
2359
2368
  }
2360
2369
  };
2361
2370
  const result = await execute(doc, variables);
2362
- const mutationName = (0, import_data7.toUpdateMutationName)(tableName, table);
2363
- const singularName = (0, import_data7.toCamelCaseSingular)(tableName, table);
2364
2371
  const updatedRow = result[mutationName]?.[singularName] ?? null;
2365
2372
  return updatedRow;
2366
2373
  },
@@ -2382,61 +2389,125 @@ function useSheetsAdapter() {
2382
2389
  return config.adapter ?? defaultAdapter;
2383
2390
  }
2384
2391
 
2385
- // src/hooks/use-sheets-meta.ts
2386
- var metaKey = (scope) => sheetsQueryKeys.meta(scope);
2387
- function useSheetsMeta(options = {}) {
2388
- const { enabled = true } = options;
2389
- const { execute, scopeKey } = useSheetsContext();
2392
+ // src/hooks/use-sheets-upload.ts
2393
+ async function executeFieldUpload({ table: meta, allTables, fieldName, recordId }, file, { execute, executeUpload, adapter, onProgress }) {
2394
+ assertSheetsMutationAllowed(meta, "update");
2395
+ const identity = resolveSheetsIdentifier(meta, recordId);
2396
+ if (identity.status !== "identified") {
2397
+ throw new Error(`Cannot resolve a primary-key identity for table '${meta.name}'.`);
2398
+ }
2399
+ const table = (0, import_data8.cleanTable)(meta);
2400
+ const field = table.fields.find(({ name }) => name === fieldName);
2401
+ if (!field) throw new Error(`Field '${fieldName}' not found in table '${meta.name}'.`);
2402
+ const isAttachment = field.type.pgAlias?.toLowerCase() === "attachment" || field.type.pgType?.toLowerCase() === "attachment";
2403
+ let value = null;
2404
+ if (file) {
2405
+ const { file: projection } = await executeUpload(file, void 0, {
2406
+ tableName: meta.name,
2407
+ fieldName,
2408
+ recordId: typeof identity.identifier === "object" ? void 0 : identity.identifier,
2409
+ onProgress
2410
+ });
2411
+ if (isAttachment) {
2412
+ if (!projection.url) throw new Error("attachment columns need a public bucket with a public URL prefix");
2413
+ value = projection.url;
2414
+ } else {
2415
+ value = {
2416
+ ...projection,
2417
+ filename: projection.filename ?? file.name,
2418
+ mime: projection.mime ?? (file.type || "application/octet-stream")
2419
+ };
2420
+ }
2421
+ }
2422
+ const updatedRow = await adapter.updateRow(
2423
+ { table, tableName: meta.name, allTables: allTables?.map(import_data8.cleanTable) ?? [table] },
2424
+ identity.identifier,
2425
+ { [fieldName]: value },
2426
+ execute,
2427
+ { returning: [fieldName] }
2428
+ );
2429
+ if (!updatedRow || !Object.hasOwn(updatedRow, fieldName)) {
2430
+ throw new Error(`Update did not return '${fieldName}'.`);
2431
+ }
2432
+ const saved = updatedRow[fieldName];
2433
+ if (value === null) {
2434
+ if (saved === null) return null;
2435
+ } else if (isAttachment) {
2436
+ if (typeof saved === "string" && saved) return saved;
2437
+ } else if (saved && typeof saved === "object" && !Array.isArray(saved)) {
2438
+ return saved;
2439
+ }
2440
+ throw new Error(`Update returned an unexpected value for '${fieldName}'.`);
2441
+ }
2442
+ function useSheetsFieldUpload(tableName, fieldName, recordId, options = {}) {
2443
+ const queryClient = (0, import_react_query3.useQueryClient)();
2444
+ const { execute, executeUpload, scopeKey } = useSheetsContext();
2445
+ const { data: meta } = useSheetsMeta();
2390
2446
  const adapter = useSheetsAdapter();
2391
- return (0, import_react_query2.useQuery)({
2392
- queryKey: metaKey(scopeKey),
2393
- queryFn: () => adapter.fetchMeta(execute),
2394
- staleTime: 5 * 60 * 1e3,
2395
- // 5 min - finite so invalidation + remount triggers refetch
2396
- gcTime: 30 * 60 * 1e3,
2397
- // 30 min - survive long schema-editing sessions
2398
- refetchOnMount: true,
2399
- // Respect staleTime and refetch stale metadata on mount
2400
- enabled
2447
+ const allTables = meta?._meta?.tables?.filter((entry) => entry != null);
2448
+ const table = allTables?.find(({ name }) => name === tableName);
2449
+ function resolveRowIdentifier(row) {
2450
+ if (!table) return null;
2451
+ const identity = resolveSheetsRowIdentity(table, row);
2452
+ return identity.status === "identified" ? identity.identifier : null;
2453
+ }
2454
+ async function persist(id, file) {
2455
+ if (!table) throw new Error(`Table '${tableName}' not found.`);
2456
+ return executeFieldUpload(
2457
+ { table, allTables, fieldName, recordId: id },
2458
+ file,
2459
+ { execute, executeUpload, adapter, onProgress: options.onProgress }
2460
+ );
2461
+ }
2462
+ function invalidate() {
2463
+ void queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.table(scopeKey, tableName) });
2464
+ }
2465
+ async function write(id, file) {
2466
+ const value = await persist(id, file);
2467
+ invalidate();
2468
+ return value;
2469
+ }
2470
+ const mutation = (0, import_react_query3.useMutation)({
2471
+ mutationKey: [...sheetsQueryKeys.table(scopeKey, tableName), "field-upload", fieldName, recordId],
2472
+ mutationFn: (file) => {
2473
+ if (recordId == null) throw new Error("Missing record context for upload");
2474
+ return persist(recordId, file);
2475
+ },
2476
+ onSuccess: (value) => {
2477
+ options.onSuccess?.(value);
2478
+ invalidate();
2479
+ },
2480
+ onError: options.onError
2401
2481
  });
2482
+ return { ...mutation, write, resolveRowIdentifier };
2402
2483
  }
2403
2484
 
2404
- // src/hooks/use-sheets-upload.ts
2405
- var import_data12 = require("@constructive-io/data");
2485
+ // src/hooks/use-sheets-media-url.ts
2486
+ var import_react11 = require("react");
2487
+ var import_react_query4 = require("@tanstack/react-query");
2406
2488
 
2407
- // src/context/sheets-execute.ts
2489
+ // src/context/sheets-upload-presigned.ts
2408
2490
  var import_graphql2 = require("graphql");
2409
2491
  var import_data9 = require("@constructive-io/data");
2410
-
2411
- // src/context/sheets-upload-presigned.ts
2412
- var import_graphql = require("graphql");
2413
- var import_data8 = require("@constructive-io/data");
2414
- async function sha256HexFromBuffer(buffer) {
2415
- if (!globalThis.crypto?.subtle) {
2416
- throw import_data8.createError.badRequest("Web Crypto (crypto.subtle) is unavailable; cannot hash file for upload.");
2417
- }
2418
- const digest = await crypto.subtle.digest("SHA-256", buffer);
2419
- const bytes = new Uint8Array(digest);
2420
- let hex = "";
2421
- for (let i = 0; i < bytes.length; i++) {
2422
- hex += bytes[i].toString(16).padStart(2, "0");
2423
- }
2424
- return hex;
2425
- }
2426
- var capabilityCache = /* @__PURE__ */ new Map();
2427
- function discoverUploadCapability(endpoint, execute) {
2428
- const cached = capabilityCache.get(endpoint);
2492
+ var capabilityCache = /* @__PURE__ */ new WeakMap();
2493
+ async function discoverStorageCapabilities(endpoint, execute) {
2494
+ let endpoints = capabilityCache.get(execute);
2495
+ if (!endpoints) {
2496
+ endpoints = /* @__PURE__ */ new Map();
2497
+ capabilityCache.set(execute, endpoints);
2498
+ }
2499
+ const cached = endpoints.get(endpoint);
2429
2500
  if (cached) return cached;
2430
2501
  const promise = (async () => {
2431
- const data = await execute((0, import_graphql.getIntrospectionQuery)());
2502
+ const data = await execute((0, import_graphql2.getIntrospectionQuery)());
2432
2503
  const schema = data?.__schema;
2433
2504
  if (!schema) {
2434
- throw import_data8.createError.badRequest("Uploads are not enabled for this endpoint.");
2505
+ throw import_data9.createError.badRequest("Uploads are not enabled for this endpoint.");
2435
2506
  }
2436
- return resolveUploadCapability(schema);
2507
+ return resolveStorageCapabilities(schema);
2437
2508
  })();
2438
- promise.catch(() => capabilityCache.delete(endpoint));
2439
- capabilityCache.set(endpoint, promise);
2509
+ promise.catch(() => endpoints.delete(endpoint));
2510
+ endpoints.set(endpoint, promise);
2440
2511
  return promise;
2441
2512
  }
2442
2513
  function namedTypeName(ref) {
@@ -2454,7 +2525,7 @@ function isListTypeRef(ref) {
2454
2525
  return cur?.kind === "LIST";
2455
2526
  }
2456
2527
  var PK_FIELD_NAME = "id";
2457
- function resolveUploadCapability(schema) {
2528
+ function resolveStorageCapabilities(schema) {
2458
2529
  const typeByName = /* @__PURE__ */ new Map();
2459
2530
  for (const t of schema.types) {
2460
2531
  if (t.name) typeByName.set(t.name, t);
@@ -2473,7 +2544,7 @@ function resolveUploadCapability(schema) {
2473
2544
  const present = new Set(t.inputFields.map((f) => f.name));
2474
2545
  return names.every((n) => present.has(n));
2475
2546
  };
2476
- const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "deduplicated"];
2547
+ const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "key", "deduplicated"];
2477
2548
  const INPUT_FIELDS = ["contentHash", "bucketKey", "contentType", "size"];
2478
2549
  const mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;
2479
2550
  const queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;
@@ -2483,52 +2554,69 @@ function resolveUploadCapability(schema) {
2483
2554
  if (!inputArg) continue;
2484
2555
  const inputTypeName = namedTypeName(inputArg.type);
2485
2556
  const payloadTypeName = namedTypeName(field.type);
2486
- if (inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
2487
- upload = { uploadFieldName: field.name, inputTypeName };
2488
- break;
2557
+ if (inputTypeName && inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
2558
+ const payloadFields = typeByName.get(payloadTypeName ?? "")?.fields;
2559
+ const candidate = {
2560
+ uploadFieldName: field.name,
2561
+ inputTypeName,
2562
+ hasFileProjection: payloadFields?.some(
2563
+ (f) => f.name === "file" && !isListTypeRef(f.type) && namedTypeName(f.type) === "JSON"
2564
+ ) ?? false
2565
+ };
2566
+ if (field.name === "uploadAppFile") {
2567
+ upload = candidate;
2568
+ break;
2569
+ }
2570
+ upload ??= candidate;
2489
2571
  }
2490
2572
  }
2491
- if (!upload) {
2492
- throw import_data8.createError.badRequest("Uploads are not enabled for this endpoint.");
2493
- }
2494
- const downloadById = resolveDownloadByIdField(schema, typeByName, queryType, upload.uploadFieldName);
2495
- return {
2496
- ...upload,
2497
- ...downloadById
2498
- };
2499
- }
2500
- function resolveDownloadByIdField(schema, typeByName, queryType, uploadFieldName) {
2501
- const fileTypesWithDownloadUrl = /* @__PURE__ */ new Set();
2573
+ const fileTypes = /* @__PURE__ */ new Set();
2502
2574
  for (const t of schema.types) {
2503
2575
  if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
2504
- fileTypesWithDownloadUrl.add(t.name);
2576
+ fileTypes.add(t.name);
2505
2577
  }
2506
2578
  }
2579
+ const uploadType = upload?.uploadFieldName.replace(/^upload/, "") ?? "AppFile";
2580
+ const uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);
2581
+ const preferredPreviewType = fileTypes.has("AppFile") ? "AppFile" : uploadType;
2582
+ const previewType = fileTypes.has(preferredPreviewType) ? preferredPreviewType : uploadDownload?.fileTypeName ?? preferredPreviewType;
2583
+ const download = previewType === uploadType ? uploadDownload : resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);
2584
+ const batch = resolveConnectionDownloadField(typeByName, queryType, fileTypes, previewType, true);
2585
+ return {
2586
+ upload: upload ? { ...upload, download: uploadDownload } : null,
2587
+ download,
2588
+ batch
2589
+ };
2590
+ }
2591
+ function resolveDownloadByIdField(typeByName, queryType, fileTypesWithDownloadUrl, preferred) {
2592
+ let singular = null;
2507
2593
  for (const field of queryType?.fields ?? []) {
2508
2594
  const returnTypeName = namedTypeName(field.type);
2509
2595
  if (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;
2510
2596
  if (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {
2511
- return {
2597
+ const candidate = {
2512
2598
  fileByIdField: field.name,
2513
2599
  fileByIdArgName: "id",
2514
2600
  fileTypeName: returnTypeName,
2515
2601
  idScalarName: namedTypeName(field.args[0].type) ?? void 0
2516
2602
  };
2603
+ if (returnTypeName === preferred) return candidate;
2604
+ singular ??= candidate;
2517
2605
  }
2518
2606
  }
2519
- const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName);
2520
- if (connection) return connection;
2607
+ const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);
2608
+ if (connection?.fileTypeName === preferred) return connection;
2609
+ if (singular || connection) return singular ?? connection;
2521
2610
  const nodeField = queryType?.fields?.find(
2522
2611
  (f) => f.name === "node" && f.args.some((a) => a.name === "nodeId")
2523
2612
  );
2524
2613
  if (nodeField && fileTypesWithDownloadUrl.size > 0) {
2525
- const preferred = uploadFieldName.replace(/^upload/, "");
2526
2614
  const fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0];
2527
2615
  return { fileByIdField: "node", fileByIdArgName: "nodeId", fileTypeName };
2528
2616
  }
2529
- throw import_data8.createError.badRequest("Uploads are not enabled for this endpoint.");
2617
+ return null;
2530
2618
  }
2531
- function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName) {
2619
+ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred, batch = false) {
2532
2620
  const EQUALITY_OPERATORS = ["equalTo", "eq"];
2533
2621
  const candidates = [];
2534
2622
  for (const field of queryType?.fields ?? []) {
@@ -2543,6 +2631,8 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
2543
2631
  });
2544
2632
  if (!nodesField) continue;
2545
2633
  const fileTypeName = namedTypeName(nodesField.type);
2634
+ if (batch && (fileTypeName !== preferred || !typeByName.get(fileTypeName)?.fields?.some((field2) => field2.name === PK_FIELD_NAME))) continue;
2635
+ const connectionHasFirst = field.args.some((arg) => arg.name === "first");
2546
2636
  for (const arg of field.args) {
2547
2637
  const filterTypeName = namedTypeName(arg.type);
2548
2638
  const filterType = filterTypeName ? typeByName.get(filterTypeName) : null;
@@ -2552,7 +2642,7 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
2552
2642
  const idFieldTypeName = namedTypeName(idField.type);
2553
2643
  const idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;
2554
2644
  if (idFieldType?.kind === "INPUT_OBJECT" && idFieldType.inputFields) {
2555
- const opField = EQUALITY_OPERATORS.map(
2645
+ const opField = batch ? idFieldType.inputFields.find((f) => f.name === "in" && isListTypeRef(f.type)) : EQUALITY_OPERATORS.map(
2556
2646
  (op) => idFieldType.inputFields.find((f) => f.name === op)
2557
2647
  ).find((f) => f != null);
2558
2648
  if (opField) {
@@ -2564,13 +2654,14 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
2564
2654
  connectionFilterArgName: arg.name,
2565
2655
  connectionIdField: idField.name,
2566
2656
  connectionIdOperator: opField.name,
2567
- connectionNodesField: nodesField.name
2657
+ connectionNodesField: nodesField.name,
2658
+ connectionHasFirst
2568
2659
  });
2569
2660
  break;
2570
2661
  }
2571
2662
  continue;
2572
2663
  }
2573
- if (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName) {
2664
+ if (!batch && (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName)) {
2574
2665
  candidates.push({
2575
2666
  fileByIdField: field.name,
2576
2667
  fileByIdArgName: "connection",
@@ -2578,93 +2669,19 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
2578
2669
  idScalarName: idFieldTypeName ?? void 0,
2579
2670
  connectionFilterArgName: arg.name,
2580
2671
  connectionIdField: idField.name,
2581
- connectionNodesField: nodesField.name
2672
+ connectionNodesField: nodesField.name,
2673
+ connectionHasFirst
2582
2674
  });
2583
2675
  break;
2584
2676
  }
2585
2677
  }
2586
2678
  }
2587
2679
  if (candidates.length === 0) return null;
2588
- const preferred = uploadFieldName.replace(/^upload/, "");
2589
2680
  return candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];
2590
2681
  }
2591
- async function callUploadOp(execute, cap, input) {
2592
- const mutation = `
2593
- mutation SheetsUpload($input: ${cap.inputTypeName}!) {
2594
- ${cap.uploadFieldName}(input: $input) {
2595
- uploadUrl
2596
- fileId
2597
- key
2598
- deduplicated
2599
- }
2600
- }
2601
- `.trim();
2602
- const data = await execute(mutation, {
2603
- input: {
2604
- bucketKey: input.bucketKey,
2605
- contentHash: input.contentHash,
2606
- contentType: input.contentType,
2607
- size: input.size,
2608
- filename: input.filename
2609
- }
2610
- });
2611
- const payload = data?.[cap.uploadFieldName];
2612
- if (!payload) {
2613
- throw import_data8.createError.badRequest("Upload failed: no payload returned from upload mutation.");
2614
- }
2615
- return payload;
2616
- }
2617
- async function presignedPut(url, buffer, contentType, onProgress) {
2618
- const total = buffer.byteLength;
2619
- if (onProgress && typeof XMLHttpRequest !== "undefined") {
2620
- await putWithXHR(url, buffer, contentType, total, onProgress);
2621
- return;
2622
- }
2623
- let response;
2624
- try {
2625
- response = await fetch(url, {
2626
- method: "PUT",
2627
- headers: { "Content-Type": contentType },
2628
- body: buffer
2629
- });
2630
- } catch (error) {
2631
- throw import_data8.createError.network(error instanceof Error ? error : void 0);
2632
- }
2633
- if (!response.ok) {
2634
- const body = await response.text().catch(() => "");
2635
- throw import_data8.createError.badRequest(`Upload failed: ${response.status} ${response.statusText}${body ? ` \u2014 ${body}` : ""}`);
2636
- }
2637
- onProgress?.({ loaded: total, total, percentage: 100 });
2638
- }
2639
- function putWithXHR(url, buffer, contentType, total, onProgress) {
2640
- return new Promise((resolve, reject) => {
2641
- const xhr = new XMLHttpRequest();
2642
- xhr.open("PUT", url);
2643
- xhr.setRequestHeader("Content-Type", contentType);
2644
- xhr.upload.addEventListener("progress", (event) => {
2645
- if (event.lengthComputable) {
2646
- onProgress({
2647
- loaded: event.loaded,
2648
- total: event.total,
2649
- percentage: Math.round(event.loaded / event.total * 100)
2650
- });
2651
- }
2652
- });
2653
- xhr.addEventListener("load", () => {
2654
- if (xhr.status >= 200 && xhr.status < 300) {
2655
- onProgress({ loaded: total, total, percentage: 100 });
2656
- resolve();
2657
- } else {
2658
- reject(import_data8.createError.badRequest(`Upload failed: ${xhr.status} ${xhr.statusText}${xhr.responseText ? ` \u2014 ${xhr.responseText}` : ""}`));
2659
- }
2660
- });
2661
- xhr.addEventListener("error", () => reject(import_data8.createError.network()));
2662
- xhr.send(buffer);
2663
- });
2664
- }
2665
2682
  function toGlobalId(typeName, id) {
2666
2683
  if (typeof btoa !== "function") {
2667
- throw import_data8.createError.badRequest("Cannot encode the file node id: btoa is unavailable in this environment.");
2684
+ throw import_data9.createError.badRequest("Cannot encode the file node id: btoa is unavailable in this environment.");
2668
2685
  }
2669
2686
  return btoa(JSON.stringify([typeName, id]));
2670
2687
  }
@@ -2684,7 +2701,7 @@ async function fetchDownloadUrl(execute, cap, fileId) {
2684
2701
  const node = data2?.[cap.fileByIdField];
2685
2702
  const url2 = node?.downloadUrl;
2686
2703
  if (!url2) {
2687
- throw import_data8.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2704
+ throw import_data9.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2688
2705
  }
2689
2706
  return url2;
2690
2707
  }
@@ -2696,7 +2713,7 @@ async function fetchDownloadUrl(execute, cap, fileId) {
2696
2713
  const filterLiteral = cap.connectionIdOperator ? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }` : `{ ${idField}: $id }`;
2697
2714
  const query2 = `
2698
2715
  query SheetsDownloadUrl($id: ${idScalar2}!) {
2699
- ${cap.fileByIdField}(${filterArg}: ${filterLiteral}, first: 1) {
2716
+ ${cap.fileByIdField}(${filterArg}: ${filterLiteral}${cap.connectionHasFirst ? ", first: 1" : ""}) {
2700
2717
  ${nodesField} {
2701
2718
  downloadUrl
2702
2719
  }
@@ -2710,7 +2727,7 @@ async function fetchDownloadUrl(execute, cap, fileId) {
2710
2727
  const conn = data2?.[cap.fileByIdField];
2711
2728
  const url2 = conn?.[nodesField]?.[0]?.downloadUrl;
2712
2729
  if (!url2) {
2713
- throw import_data8.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2730
+ throw import_data9.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2714
2731
  }
2715
2732
  return url2;
2716
2733
  }
@@ -2727,260 +2744,33 @@ async function fetchDownloadUrl(execute, cap, fileId) {
2727
2744
  const file = data?.[cap.fileByIdField];
2728
2745
  const url = file?.downloadUrl;
2729
2746
  if (!url) {
2730
- throw import_data8.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2747
+ throw import_data9.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2731
2748
  }
2732
2749
  return url;
2733
2750
  }
2734
-
2735
- // src/context/sheets-execute.ts
2736
- var import_data10 = require("@constructive-io/data");
2737
- function documentToString(document2) {
2738
- if (typeof document2 === "string") return document2;
2739
- if (document2 instanceof String) return document2.toString();
2740
- if (document2 && typeof document2 === "object" && "kind" in document2) {
2741
- return (0, import_graphql2.print)(document2);
2742
- }
2743
- if (document2 === null || document2 === void 0) {
2744
- throw import_data9.createError.badRequest("Invalid GraphQL document: null or undefined");
2745
- }
2746
- return String(document2);
2747
- }
2748
- function hasAuthMessage(message) {
2749
- const normalized = String(message ?? "").toLowerCase();
2750
- return normalized.includes("unauthenticated") || normalized.includes("unauthorized") || normalized.includes("authentication");
2751
- }
2752
- function parseGraphQLResponse(response, onAuthError) {
2753
- if (!response.errors?.length) return null;
2754
- const error = response.errors[0];
2755
- const code = error.extensions?.code;
2756
- const message = error.message || "GraphQL query failed";
2757
- if (code === "UNAUTHENTICATED" || hasAuthMessage(message)) {
2758
- onAuthError?.();
2759
- return import_data9.createError.unauthorized("Authentication required. Please log in again.");
2760
- }
2761
- if (code === "FORBIDDEN") {
2762
- return import_data9.createError.forbidden("You do not have permission to perform this action.");
2763
- }
2764
- return import_data9.createError.graphql(message, code);
2765
- }
2766
- function createSheetsExecute(config, getToken) {
2767
- return async (document2, variables) => {
2768
- const url = config.endpoint;
2769
- if (!url) {
2770
- throw import_data9.createError.badRequest("No GraphQL endpoint configured.");
2771
- }
2772
- const token = getToken();
2773
- const headers = {
2774
- "Content-Type": "application/json",
2775
- Accept: "application/graphql-response+json"
2776
- };
2777
- if (token) {
2778
- headers["Authorization"] = `Bearer ${token}`;
2779
- }
2780
- let response;
2781
- try {
2782
- response = await fetch(url, {
2783
- method: "POST",
2784
- headers,
2785
- body: JSON.stringify({
2786
- query: documentToString(document2),
2787
- ...variables !== void 0 && { variables }
2788
- })
2789
- });
2790
- } catch (error) {
2791
- throw import_data9.createError.network(error instanceof Error ? error : void 0);
2792
- }
2793
- if (!response.ok) {
2794
- const { status, statusText } = response;
2795
- if (status === 401) {
2796
- config.onAuthError?.();
2797
- throw import_data9.createError.unauthorized("Authentication required. Please log in again.");
2798
- }
2799
- if (status === 403) {
2800
- throw import_data9.createError.forbidden("You do not have permission to perform this action.");
2801
- }
2802
- if (status === 404) {
2803
- throw import_data9.createError.notFound("The requested endpoint does not exist.");
2804
- }
2805
- try {
2806
- const body = await response.json();
2807
- if (body.errors?.length) {
2808
- throw import_data9.createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);
2809
- }
2810
- } catch (e) {
2811
- if (e instanceof import_data9.ConstructiveError) throw e;
2812
- }
2813
- throw import_data9.createError.badRequest(`Request failed: ${status} ${statusText}`);
2814
- }
2815
- const result = await response.json();
2816
- const graphqlError = parseGraphQLResponse(result, config.onAuthError);
2817
- if (graphqlError) {
2818
- throw graphqlError;
2819
- }
2820
- return result.data;
2821
- };
2822
- }
2823
- function createSheetsUpload(config, getToken) {
2824
- const execute = config.execute ?? createSheetsExecute(config, getToken);
2825
- return async (file, _path, options) => {
2826
- if (!config.endpoint) {
2827
- throw import_data9.createError.badRequest("No GraphQL endpoint configured.");
2751
+ async function fetchMediaDownloadUrls({ endpoint, execute }, getActiveIds) {
2752
+ const { batch, download } = await discoverStorageCapabilities(endpoint, execute);
2753
+ const ids = getActiveIds();
2754
+ const urls = /* @__PURE__ */ new Map();
2755
+ if (ids.length === 0) return urls;
2756
+ if (batch) {
2757
+ const first = batch.connectionHasFirst ? `, first: ${ids.length}` : "";
2758
+ const query = `query SheetsMediaDownloadUrls($ids: [${batch.idScalarName ?? "ID"}!]!) {
2759
+ ${batch.fileByIdField}(${batch.connectionFilterArgName}: {
2760
+ ${batch.connectionIdField}: { in: $ids }
2761
+ }${first}) { ${batch.connectionNodesField} { id downloadUrl } }
2762
+ }`;
2763
+ const data = await execute(query, { ids });
2764
+ for (const row of data?.[batch.fileByIdField]?.[batch.connectionNodesField] ?? []) {
2765
+ if (row?.downloadUrl) urls.set(row.id, row.downloadUrl);
2828
2766
  }
2829
- const bucketKey = config.upload?.bucketKey ?? "public";
2830
- const contentType = file.type || "application/octet-stream";
2831
- const buffer = await file.arrayBuffer();
2832
- const contentHash = await sha256HexFromBuffer(buffer);
2833
- const cap = await discoverUploadCapability(config.endpoint, execute);
2834
- const payload = await callUploadOp(execute, cap, {
2835
- bucketKey,
2836
- contentHash,
2837
- contentType,
2838
- size: file.size,
2839
- filename: file.name
2767
+ } else if (download) {
2768
+ const results = await Promise.allSettled(ids.map((id) => fetchDownloadUrl(execute, download, id)));
2769
+ results.forEach((result, index) => {
2770
+ if (result.status === "fulfilled") urls.set(ids[index], result.value);
2840
2771
  });
2841
- if (!payload.deduplicated) {
2842
- if (!payload.uploadUrl) {
2843
- throw import_data9.createError.badRequest("Upload failed: server returned no uploadUrl for a non-deduplicated file.");
2844
- }
2845
- await presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);
2846
- } else {
2847
- options?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });
2848
- }
2849
- const url = await fetchDownloadUrl(execute, cap, payload.fileId);
2850
- return {
2851
- url,
2852
- filename: file.name,
2853
- mime: file.type,
2854
- size: file.size,
2855
- key: payload.key,
2856
- fileId: payload.fileId
2857
- };
2858
- };
2859
- }
2860
-
2861
- // src/hooks/use-sheets-upload.ts
2862
- function resolveUploadNaming(tableName, table) {
2863
- return {
2864
- mutationName: (0, import_data12.toUpdateMutationName)(tableName, table),
2865
- singularName: (0, import_data12.toCamelCaseSingular)(tableName, table),
2866
- patchFieldName: (0, import_data12.toPatchFieldName)(tableName, table),
2867
- updateInputTypeName: (0, import_data12.toUpdateInputTypeName)(tableName)
2868
- };
2869
- }
2870
- function resolveTransport(endpoint, getToken, options) {
2871
- if (options?.execute && options?.executeUpload) {
2872
- return { execute: options.execute, executeUpload: options.executeUpload };
2873
- }
2874
- const config = {
2875
- endpoint,
2876
- auth: { mode: "standalone" },
2877
- onAuthError: options?.onAuthError
2878
- };
2879
- return {
2880
- execute: createSheetsExecute(config, getToken),
2881
- executeUpload: createSheetsUpload(config, getToken)
2882
- };
2883
- }
2884
- async function executeFieldUpload(tableName, fieldName, recordId, file, endpoint, getToken, naming, options) {
2885
- if (!endpoint && !(options?.execute && options?.executeUpload)) {
2886
- throw new Error("No endpoint configured. Select a database API or use Direct Connect.");
2887
- }
2888
- const { execute, executeUpload } = resolveTransport(endpoint, getToken, options);
2889
- const uploadResult = await executeUpload(file, void 0, {
2890
- tableName,
2891
- fieldName,
2892
- recordId,
2893
- onProgress: options?.onProgress
2894
- });
2895
- const resolvedNaming = naming ?? resolveUploadNaming(tableName);
2896
- const patchValue = {
2897
- ...uploadResult.url != null && { url: uploadResult.url },
2898
- ...uploadResult.filename != null && { filename: uploadResult.filename },
2899
- ...uploadResult.mime != null && { mime: uploadResult.mime },
2900
- ...uploadResult.size != null && { size: uploadResult.size }
2901
- };
2902
- const mutationString = `
2903
- mutation ${resolvedNaming.mutationName}Mutation($input: ${resolvedNaming.updateInputTypeName}!) {
2904
- ${resolvedNaming.mutationName}(input: $input) {
2905
- ${resolvedNaming.singularName} {
2906
- id
2907
- ${fieldName}
2908
- }
2909
- }
2910
- }
2911
- `.trim();
2912
- const result = await execute(mutationString, {
2913
- input: {
2914
- id: recordId,
2915
- [resolvedNaming.patchFieldName]: {
2916
- [fieldName]: patchValue
2917
- }
2918
- }
2919
- });
2920
- const updatedRecord = result?.[resolvedNaming.mutationName]?.[resolvedNaming.singularName];
2921
- if (!updatedRecord) {
2922
- throw new Error("Upload succeeded but no data returned from patch");
2923
- }
2924
- const uploadedFileData = updatedRecord[fieldName];
2925
- if (!uploadedFileData) {
2926
- throw new Error(`Upload succeeded but ${fieldName} field not found in response`);
2927
2772
  }
2928
- const fileObject = typeof uploadedFileData === "object" ? uploadedFileData : null;
2929
- return {
2930
- url: fileObject?.url || uploadedFileData,
2931
- filename: fileObject?.filename || file.name,
2932
- mime: fileObject?.mime || file.type,
2933
- size: fileObject?.size || file.size
2934
- };
2935
- }
2936
- function useSheetsFieldUpload(tableName, fieldName, recordId, options = {}) {
2937
- const queryClient = (0, import_react_query3.useQueryClient)();
2938
- const { scopeKey, config, execute, executeUpload } = useSheetsContext();
2939
- const storeApi = useSheetsStoreApi();
2940
- const { data: meta } = useSheetsMeta();
2941
- const table = (0, import_react12.useMemo)(() => {
2942
- if (!meta?._meta?.tables) return null;
2943
- const candidate = meta._meta.tables.find((item) => item?.name === tableName);
2944
- return candidate ? (0, import_data11.cleanTable)(candidate) : null;
2945
- }, [meta, tableName]);
2946
- const resolvedNaming = (0, import_react12.useMemo)(() => resolveUploadNaming(tableName, table), [tableName, table]);
2947
- const getToken = (0, import_react12.useMemo)(() => {
2948
- if (config.auth.mode === "embedded") {
2949
- return config.auth.getToken;
2950
- }
2951
- return () => storeApi.getState().accessToken;
2952
- }, [config.auth, storeApi]);
2953
- const tableRef = (0, import_react12.useRef)(tableName);
2954
- const fieldRef = (0, import_react12.useRef)(fieldName);
2955
- const idRef = (0, import_react12.useRef)(recordId);
2956
- (0, import_react12.useEffect)(() => {
2957
- tableRef.current = tableName;
2958
- fieldRef.current = fieldName;
2959
- idRef.current = recordId;
2960
- }, [tableName, fieldName, recordId]);
2961
- return (0, import_react_query3.useMutation)({
2962
- mutationKey: ["sheets", scopeKey, "field-upload", tableName, fieldName, recordId],
2963
- mutationFn: async (file) => {
2964
- return executeFieldUpload(
2965
- tableRef.current,
2966
- fieldRef.current,
2967
- idRef.current,
2968
- file,
2969
- config.endpoint,
2970
- getToken,
2971
- resolvedNaming,
2972
- { onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress }
2973
- );
2974
- },
2975
- onSuccess: (data) => {
2976
- options.onSuccess?.(data);
2977
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });
2978
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });
2979
- },
2980
- onError: (error) => {
2981
- options.onError?.(error);
2982
- }
2983
- });
2773
+ return urls;
2984
2774
  }
2985
2775
 
2986
2776
  // src/utils/file.utils.ts
@@ -3000,14 +2790,18 @@ var getImageUrl = (imageValue) => {
3000
2790
  }
3001
2791
  return null;
3002
2792
  };
2793
+ function getMediaFileId(value) {
2794
+ if (!value || typeof value !== "object") return null;
2795
+ const { id } = value;
2796
+ return typeof id === "string" && id ? id : null;
2797
+ }
3003
2798
  var getImageMetadata = (imageValue) => {
3004
2799
  if (!imageValue || typeof imageValue !== "object") return null;
3005
2800
  const obj = imageValue;
3006
2801
  return {
3007
2802
  filename: obj.filename || obj.name || "Unknown",
3008
- size: obj.size || obj.fileSize || 0,
3009
- mime: obj.mime || obj.type || obj.contentType || "unknown",
3010
- url: getImageUrl(imageValue) || ""
2803
+ size: typeof obj.size === "number" ? obj.size : typeof obj.fileSize === "number" ? obj.fileSize : void 0,
2804
+ mime: obj.mime || obj.type || obj.contentType || "unknown"
3011
2805
  };
3012
2806
  };
3013
2807
  var formatFileSize = (bytes) => {
@@ -3018,28 +2812,106 @@ var formatFileSize = (bytes) => {
3018
2812
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
3019
2813
  };
3020
2814
 
2815
+ // src/hooks/use-sheets-media-url.ts
2816
+ var MAX_BATCH_SIZE = 100;
2817
+ var REFRESH_INTERVAL = 50 * 60 * 1e3;
2818
+ var UNRESOLVED_STALE_TIME = 60 * 1e3;
2819
+ var loaders = /* @__PURE__ */ new WeakMap();
2820
+ function createMediaLoader(storage) {
2821
+ let pending = [];
2822
+ async function fetchBatch(requests) {
2823
+ const getActiveIds = () => [...new Set(requests.filter(({ signal }) => !signal.aborted).map(({ id }) => id))];
2824
+ try {
2825
+ const urls = getActiveIds().length ? await fetchMediaDownloadUrls(storage, getActiveIds) : null;
2826
+ for (const request of requests) {
2827
+ request.resolve(request.signal.aborted ? null : urls?.get(request.id) ?? null);
2828
+ }
2829
+ } catch (error) {
2830
+ for (const request of requests) request.reject(error);
2831
+ }
2832
+ }
2833
+ function flush() {
2834
+ const requests = pending;
2835
+ pending = [];
2836
+ for (let start = 0; start < requests.length; start += MAX_BATCH_SIZE) {
2837
+ void fetchBatch(requests.slice(start, start + MAX_BATCH_SIZE));
2838
+ }
2839
+ }
2840
+ return (id, signal) => new Promise((resolve, reject) => {
2841
+ if (pending.length === 0) queueMicrotask(flush);
2842
+ pending.push({ id, signal, resolve, reject });
2843
+ });
2844
+ }
2845
+ function getMediaLoader(storage, scopeKey) {
2846
+ let scopes = loaders.get(storage);
2847
+ if (!scopes) {
2848
+ scopes = /* @__PURE__ */ new WeakMap();
2849
+ loaders.set(storage, scopes);
2850
+ }
2851
+ let load = scopes.get(scopeKey);
2852
+ if (!load) {
2853
+ load = createMediaLoader(storage);
2854
+ scopes.set(scopeKey, load);
2855
+ }
2856
+ return load;
2857
+ }
2858
+ function useSheetsMediaUrl(value, previewImage = true) {
2859
+ const { storage, scopeKey } = useSheetsContext();
2860
+ const durableUrl = getImageUrl(value);
2861
+ const id = getMediaFileId(value);
2862
+ const endpoint = storage?.endpoint;
2863
+ const resource = (0, import_react11.useMemo)(() => ({ scopeKey, endpoint, id }), [scopeKey, endpoint, id]);
2864
+ const query = (0, import_react_query4.useQuery)({
2865
+ queryKey: sheetsQueryKeys.mediaUrl(scopeKey, endpoint, id),
2866
+ queryFn: storage && id && previewImage && !durableUrl ? ({ signal }) => getMediaLoader(storage, scopeKey)(id, signal) : import_react_query4.skipToken,
2867
+ staleTime: (query2) => query2.state.data ? REFRESH_INTERVAL : UNRESOLVED_STALE_TIME,
2868
+ gcTime: REFRESH_INTERVAL,
2869
+ refetchInterval: (query2) => query2.state.data && query2.state.status === "success" ? REFRESH_INTERVAL : false,
2870
+ refetchOnWindowFocus: true,
2871
+ retry: false
2872
+ });
2873
+ const signedUrl = previewImage && !durableUrl && !query.isPlaceholderData ? query.data ?? null : null;
2874
+ const [failed, setFailed] = (0, import_react11.useState)(null);
2875
+ const retried = (0, import_react11.useRef)(null);
2876
+ const { refetch } = query;
2877
+ const onImageError = (0, import_react11.useCallback)(() => {
2878
+ if (!signedUrl) return;
2879
+ setFailed({ resource, url: signedUrl });
2880
+ if (retried.current === resource) return;
2881
+ retried.current = resource;
2882
+ void refetch({ cancelRefetch: false });
2883
+ }, [refetch, resource, signedUrl]);
2884
+ const onImageLoad = (0, import_react11.useCallback)(() => {
2885
+ if (retried.current !== resource) return;
2886
+ retried.current = null;
2887
+ setFailed(null);
2888
+ }, [resource]);
2889
+ const url = durableUrl ?? (failed?.resource === resource && failed.url === signedUrl ? null : signedUrl);
2890
+ return { url, durableUrl, id, isLoading: query.isFetching && !url, onImageError, onImageLoad };
2891
+ }
2892
+
3021
2893
  // src/grid/editors/image-editor.tsx
3022
2894
  init_sheets_logger();
3023
2895
 
3024
2896
  // src/utils/use-image-status.ts
3025
- var import_react13 = require("react");
2897
+ var import_react12 = require("react");
3026
2898
  function useImageStatus(src) {
3027
- const [status, setStatus] = (0, import_react13.useState)("idle");
3028
- (0, import_react13.useEffect)(() => {
3029
- if (!src) return setStatus("idle");
3030
- setStatus("loading");
2899
+ const [result, setResult] = (0, import_react12.useState)();
2900
+ (0, import_react12.useEffect)(() => {
2901
+ if (!src) return;
3031
2902
  const img = new Image();
3032
- img.src = src;
3033
- const onLoad = () => setStatus("loaded");
3034
- const onError = () => setStatus("error");
2903
+ const onLoad = () => setResult({ src, status: "loaded" });
2904
+ const onError = () => setResult({ src, status: "error" });
3035
2905
  img.addEventListener("load", onLoad);
3036
2906
  img.addEventListener("error", onError);
2907
+ img.src = src;
3037
2908
  return () => {
3038
2909
  img.removeEventListener("load", onLoad);
3039
2910
  img.removeEventListener("error", onError);
3040
2911
  };
3041
2912
  }, [src]);
3042
- return status;
2913
+ if (!src) return "idle";
2914
+ return result?.src === src ? result.status : "loading";
3043
2915
  }
3044
2916
 
3045
2917
  // src/grid/editors/image-editor.tsx
@@ -3047,7 +2919,7 @@ var import_button5 = require("@constructive-io/ui/button");
3047
2919
  var import_skeleton = require("@constructive-io/ui/skeleton");
3048
2920
 
3049
2921
  // src/utils/image-with-fallback.tsx
3050
- var import_react14 = require("react");
2922
+ var import_react13 = require("react");
3051
2923
  init_cn();
3052
2924
  var import_jsx_runtime10 = require("react/jsx-runtime");
3053
2925
  function ImageWithFallback({
@@ -3060,14 +2932,14 @@ function ImageWithFallback({
3060
2932
  className,
3061
2933
  ...imgProps
3062
2934
  }) {
3063
- const fallbacks = (0, import_react14.useMemo)(() => {
2935
+ const fallbacks = (0, import_react13.useMemo)(() => {
3064
2936
  const legacyFallbacks = [];
3065
2937
  if (loadingElement) legacyFallbacks.push(loadingElement);
3066
2938
  if (fallbackElement) legacyFallbacks.push(fallbackElement);
3067
2939
  const primaryFallbacks = fallback === void 0 ? [] : Array.isArray(fallback) ? fallback : [fallback];
3068
2940
  return [...primaryFallbacks, ...legacyFallbacks];
3069
2941
  }, [fallback, fallbackElement, loadingElement]);
3070
- const [currentSrcIndex, setCurrentSrcIndex] = (0, import_react14.useState)(0);
2942
+ const [currentSrcIndex, setCurrentSrcIndex] = (0, import_react13.useState)(0);
3071
2943
  const currentSrc = currentSrcIndex === 0 ? src : fallbacks[currentSrcIndex - 1];
3072
2944
  const status = useImageStatus(typeof currentSrc === "string" ? currentSrc : void 0);
3073
2945
  if (status === "error" && currentSrcIndex < fallbacks.length) {
@@ -3109,9 +2981,6 @@ function ImageWithFallback({
3109
2981
  init_editor_focus_trap();
3110
2982
  init_overlay_presets();
3111
2983
  var import_jsx_runtime11 = require("react/jsx-runtime");
3112
- function normalizeUploadResponse(data) {
3113
- return { url: data.url, filename: data.filename, size: data.size, mime: data.mime };
3114
- }
3115
2984
  var dropzoneTransition = { duration: 0.15, ease: [0.2, 0, 0, 1] };
3116
2985
  function RemoveButton({ onClick, label }) {
3117
2986
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "absolute top-2 right-2", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
@@ -3130,13 +2999,14 @@ function RemoveButton({ onClick, label }) {
3130
2999
  }
3131
3000
  function FilePreview({ name, size, mime }) {
3132
3001
  const hasMime = !!mime && mime !== "unknown";
3002
+ const hasSize = size !== void 0;
3133
3003
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "flex size-full flex-col items-center justify-center gap-2 p-4 text-center", children: [
3134
3004
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "bg-muted/60 flex size-12 shrink-0 items-center justify-center rounded-lg", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.FileIcon, { className: "text-muted-foreground size-6" }) }),
3135
3005
  /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "min-w-0 max-w-full", children: [
3136
3006
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { className: "truncate text-sm font-medium", title: name, children: name || "File" }),
3137
- (size || hasMime) && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("p", { className: "text-muted-foreground mt-0.5 text-xs", children: [
3138
- size ? formatFileSize(size) : null,
3139
- size && hasMime ? " \u2022 " : null,
3007
+ (hasSize || hasMime) && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("p", { className: "text-muted-foreground mt-0.5 text-xs", children: [
3008
+ hasSize ? formatFileSize(size) : null,
3009
+ hasSize && hasMime ? " \u2022 " : null,
3140
3010
  hasMime ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: "uppercase", children: mime }) : null
3141
3011
  ] })
3142
3012
  ] })
@@ -3156,72 +3026,79 @@ var ImageEditor = ({
3156
3026
  }) => {
3157
3027
  const noun = acceptAnyFile ? "file" : "image";
3158
3028
  const Noun = acceptAnyFile ? "File" : "Image";
3159
- const [uploadState, setUploadState] = (0, import_react15.useState)("idle");
3160
- const { config } = useSheetsContext();
3161
- const storeApi = useSheetsStoreApi();
3162
- const { maxHeight: overlayMaxHeight } = (0, import_react15.useContext)(OverlayMeasureContext);
3163
- const getToken = (0, import_react15.useMemo)(() => {
3164
- if (config.auth.mode === "embedded") return config.auth.getToken;
3165
- return () => storeApi.getState().accessToken;
3166
- }, [config.auth, storeApi]);
3167
- const fileInputRef = (0, import_react15.useRef)(null);
3168
- const previewUrlRef = (0, import_react15.useRef)(null);
3169
- const committedRecordIdRef = (0, import_react15.useRef)(null);
3029
+ const [uploadState, setUploadState] = (0, import_react14.useState)("idle");
3030
+ const { maxHeight: overlayMaxHeight } = (0, import_react14.useContext)(OverlayMeasureContext);
3031
+ const fileInputRef = (0, import_react14.useRef)(null);
3032
+ const previewUrlRef = (0, import_react14.useRef)(null);
3033
+ const committedRecordIdRef = (0, import_react14.useRef)(null);
3170
3034
  const currentImageData = value ?? null;
3171
- const [imageValue, setImageValue] = (0, import_react15.useState)(currentImageData);
3172
- const [selectedFile, setSelectedFile] = (0, import_react15.useState)(null);
3173
- const [previewUrl, setPreviewUrl] = (0, import_react15.useState)(null);
3174
- const [uploadProgress, setUploadProgress] = (0, import_react15.useState)(null);
3175
- const [isDragging, setIsDragging] = (0, import_react15.useState)(false);
3176
- const [dragErrors, setDragErrors] = (0, import_react15.useState)([]);
3035
+ const [imageValue, setImageValue] = (0, import_react14.useState)(currentImageData);
3036
+ const [selectedFile, setSelectedFile] = (0, import_react14.useState)(null);
3037
+ const [previewUrl, setPreviewUrl] = (0, import_react14.useState)(null);
3038
+ const [uploadProgress, setUploadProgress] = (0, import_react14.useState)(null);
3039
+ const [isDragging, setIsDragging] = (0, import_react14.useState)(false);
3040
+ const [dragErrors, setDragErrors] = (0, import_react14.useState)([]);
3177
3041
  const isSubmittingDraft = uploadState === "submitting-draft";
3178
3042
  const isUploading = uploadState === "uploading";
3043
+ const isClearing = uploadState === "clearing";
3179
3044
  const isBusy = uploadState !== "idle";
3180
- const imageUrl = (0, import_react15.useMemo)(() => getImageUrl(imageValue), [imageValue]);
3181
- const imageMetadata = (0, import_react15.useMemo)(() => getImageMetadata(imageValue), [imageValue]);
3045
+ const imageMetadata = (0, import_react14.useMemo)(() => getImageMetadata(imageValue), [imageValue]);
3182
3046
  const storedMime = imageMetadata?.mime;
3183
3047
  const storedIsImage = !acceptAnyFile || !!storedMime && storedMime.startsWith("image/");
3048
+ const { url: imageUrl, durableUrl, id: storedFileId, isLoading: isResolvingImage, onImageError, onImageLoad } = useSheetsMediaUrl(imageValue, storedIsImage);
3184
3049
  const imageStatus = useImageStatus(storedIsImage ? imageUrl || void 0 : void 0);
3185
- const imageLoadFailed = storedIsImage && imageUrl != null && imageStatus === "error";
3186
- const hasImage = imageUrl != null && !imageLoadFailed && storedIsImage;
3187
- const revokePreviewUrl = (0, import_react15.useCallback)(() => {
3050
+ (0, import_react14.useEffect)(() => {
3051
+ if (imageStatus === "error") onImageError();
3052
+ if (imageStatus === "loaded") onImageLoad();
3053
+ }, [imageStatus, onImageError, onImageLoad]);
3054
+ const imageLoadFailed = storedIsImage && durableUrl != null && imageStatus === "error";
3055
+ const hasImage = (imageUrl != null || isResolvingImage) && !imageLoadFailed && storedIsImage;
3056
+ const hasStoredMedia = Boolean(storedFileId || durableUrl);
3057
+ const clearPending = value != null && imageValue == null;
3058
+ const needsDraftCreation = isDraftRow && committedRecordIdRef.current == null;
3059
+ const selectedIsImage = !acceptAnyFile || (selectedFile?.type.startsWith("image/") ?? false);
3060
+ const revokePreviewUrl = (0, import_react14.useCallback)(() => {
3188
3061
  if (previewUrlRef.current) {
3189
3062
  URL.revokeObjectURL(previewUrlRef.current);
3190
3063
  previewUrlRef.current = null;
3191
3064
  }
3192
3065
  }, []);
3193
- const resetFileState = (0, import_react15.useCallback)(() => {
3066
+ const resetFileState = (0, import_react14.useCallback)(() => {
3194
3067
  revokePreviewUrl();
3195
3068
  setUploadProgress(null);
3196
3069
  setSelectedFile(null);
3197
3070
  setPreviewUrl(null);
3198
3071
  setUploadState("idle");
3199
3072
  }, [revokePreviewUrl]);
3200
- const handleUploadSuccess = (0, import_react15.useCallback)((data) => {
3201
- const normalized = normalizeUploadResponse(data);
3073
+ const finishSave = (0, import_react14.useCallback)((data, message) => {
3202
3074
  resetFileState();
3203
- setImageValue(normalized);
3204
- onSaveComplete?.({ imageData: normalized });
3075
+ setImageValue(data);
3076
+ if (committedRecordIdRef.current == null) {
3077
+ onSaveComplete?.({ imageData: data });
3078
+ } else {
3079
+ onDraftUploadComplete?.();
3080
+ }
3205
3081
  onFinishedEditing();
3206
- import_toast.toast.success({ message: `${Noun} uploaded successfully` });
3207
- }, [resetFileState, onSaveComplete, onFinishedEditing, Noun]);
3208
- const handleUploadError = (0, import_react15.useCallback)((error) => {
3082
+ import_toast.toast.success({ message });
3083
+ }, [resetFileState, onSaveComplete, onDraftUploadComplete, onFinishedEditing]);
3084
+ const handleWriteError = (0, import_react14.useCallback)((error) => {
3209
3085
  setUploadState("idle");
3210
- sheetsLogger().error("[image-editor] upload failed:", error);
3211
- import_toast.toast.error({ message: error.message || "Upload failed" });
3086
+ setUploadProgress(null);
3087
+ sheetsLogger().error("[image-editor] media update failed:", error);
3088
+ import_toast.toast.error({ message: error.message || "Could not save the file" });
3212
3089
  }, []);
3213
- const uploadMutation = useSheetsFieldUpload(tableName || "", fieldName || "", recordId || "", {
3090
+ const uploadMutation = useSheetsFieldUpload(tableName || "", fieldName || "", recordId ?? null, {
3214
3091
  onProgress: setUploadProgress,
3215
- onSuccess: handleUploadSuccess,
3216
- onError: handleUploadError,
3092
+ onSuccess: (data) => finishSave(data, data === null ? `${Noun} cleared` : `${Noun} uploaded successfully`),
3093
+ onError: handleWriteError,
3217
3094
  showToast: false
3218
3095
  });
3219
- const handleRemoveImage = (0, import_react15.useCallback)(() => {
3096
+ const handleRemoveImage = (0, import_react14.useCallback)(() => {
3220
3097
  setImageValue(null);
3221
3098
  setSelectedFile(null);
3222
3099
  setPreviewUrl(null);
3223
3100
  }, []);
3224
- const handleFileSelection = (0, import_react15.useCallback)((acceptedFiles) => {
3101
+ const handleFileSelection = (0, import_react14.useCallback)((acceptedFiles) => {
3225
3102
  if (acceptedFiles.length === 0) return;
3226
3103
  const file = acceptedFiles[0];
3227
3104
  if (!acceptAnyFile) {
@@ -3240,21 +3117,21 @@ var ImageEditor = ({
3240
3117
  previewUrlRef.current = url;
3241
3118
  setPreviewUrl(url);
3242
3119
  }, [revokePreviewUrl, acceptAnyFile]);
3243
- const handleDragEnter = (0, import_react15.useCallback)((e) => {
3120
+ const handleDragEnter = (0, import_react14.useCallback)((e) => {
3244
3121
  e.preventDefault();
3245
3122
  e.stopPropagation();
3246
3123
  setIsDragging(true);
3247
3124
  }, []);
3248
- const handleDragLeave = (0, import_react15.useCallback)((e) => {
3125
+ const handleDragLeave = (0, import_react14.useCallback)((e) => {
3249
3126
  e.preventDefault();
3250
3127
  e.stopPropagation();
3251
3128
  setIsDragging(false);
3252
3129
  }, []);
3253
- const handleDragOver = (0, import_react15.useCallback)((e) => {
3130
+ const handleDragOver = (0, import_react14.useCallback)((e) => {
3254
3131
  e.preventDefault();
3255
3132
  e.stopPropagation();
3256
3133
  }, []);
3257
- const handleDrop = (0, import_react15.useCallback)((e) => {
3134
+ const handleDrop = (0, import_react14.useCallback)((e) => {
3258
3135
  e.preventDefault();
3259
3136
  e.stopPropagation();
3260
3137
  setIsDragging(false);
@@ -3262,129 +3139,126 @@ var ImageEditor = ({
3262
3139
  const files = Array.from(e.dataTransfer.files);
3263
3140
  if (files.length > 0) handleFileSelection(files);
3264
3141
  }, [handleFileSelection]);
3265
- const openFileDialog = (0, import_react15.useCallback)(() => fileInputRef.current?.click(), []);
3266
- const removeFile = (0, import_react15.useCallback)(() => {
3142
+ const openFileDialog = (0, import_react14.useCallback)(() => fileInputRef.current?.click(), []);
3143
+ const removeFile = (0, import_react14.useCallback)(() => {
3267
3144
  revokePreviewUrl();
3268
3145
  setSelectedFile(null);
3269
3146
  setPreviewUrl(null);
3270
3147
  setDragErrors([]);
3271
3148
  }, [revokePreviewUrl]);
3272
- const handleConfirmUpload = (0, import_react15.useCallback)(async () => {
3273
- if (!tableName || !fieldName || !selectedFile) return;
3274
- const committedId = committedRecordIdRef.current ?? recordId;
3275
- if (committedRecordIdRef.current != null) {
3276
- try {
3277
- import_toast.toast.info({ message: `Uploading ${noun}...` });
3278
- setUploadState("uploading");
3279
- const uploadResult = await executeFieldUpload(
3280
- tableName,
3281
- fieldName,
3282
- committedRecordIdRef.current,
3283
- selectedFile,
3284
- config.endpoint,
3285
- getToken,
3286
- void 0,
3287
- { onAuthError: config.onAuthError }
3288
- );
3289
- const normalized = normalizeUploadResponse(uploadResult);
3290
- resetFileState();
3291
- setImageValue(normalized);
3292
- onDraftUploadComplete?.();
3293
- import_toast.toast.success({ message: `${Noun} uploaded successfully` });
3294
- onFinishedEditing();
3295
- } catch (error) {
3296
- onDraftUploadComplete?.();
3297
- setUploadState("idle");
3298
- import_toast.toast.error({ message: error instanceof Error ? error.message : "Upload failed" });
3149
+ const handleConfirmUpload = (0, import_react14.useCallback)(async () => {
3150
+ if (isBusy || !tableName || !fieldName || !selectedFile) return;
3151
+ if (!isDraftRow) {
3152
+ if (recordId == null) {
3153
+ import_toast.toast.error({ message: "Missing record context for upload" });
3154
+ return;
3299
3155
  }
3156
+ setUploadState("uploading");
3157
+ uploadMutation.mutate(selectedFile);
3300
3158
  return;
3301
3159
  }
3302
- if (isDraftRow) {
3303
- if (!onSubmitDraft) {
3304
- import_toast.toast.error({ message: "Cannot upload to draft row - save the row first" });
3305
- return;
3306
- }
3307
- try {
3160
+ let rowPersisted = committedRecordIdRef.current != null;
3161
+ try {
3162
+ const createRow = committedRecordIdRef.current == null;
3163
+ if (createRow) {
3164
+ if (!onSubmitDraft) throw new Error("Cannot upload to draft row - save the row first");
3308
3165
  import_toast.toast.info({ message: "Creating row..." });
3309
3166
  setUploadState("submitting-draft");
3310
- const result = await onSubmitDraft();
3311
- const createdId = result.createdRow?.id;
3312
- if (typeof createdId !== "string" && typeof createdId !== "number") {
3313
- throw new Error("Image uploads require a scalar id primary key.");
3314
- }
3315
- committedRecordIdRef.current = createdId;
3316
- import_toast.toast.info({ message: `Uploading ${noun}...` });
3317
- setUploadState("uploading");
3318
- const uploadResult = await executeFieldUpload(
3319
- tableName,
3320
- fieldName,
3321
- createdId,
3322
- selectedFile,
3323
- config.endpoint,
3324
- getToken,
3325
- void 0,
3326
- { onAuthError: config.onAuthError }
3327
- );
3328
- const normalized = normalizeUploadResponse(uploadResult);
3329
- resetFileState();
3330
- setImageValue(normalized);
3331
- onDraftUploadComplete?.();
3332
- import_toast.toast.success({ message: `Row created and ${noun} uploaded` });
3333
- onFinishedEditing();
3334
- } catch (error) {
3335
- onDraftUploadComplete?.();
3336
- setUploadState("idle");
3337
- import_toast.toast.error({ message: error instanceof Error ? error.message : "Upload failed" });
3167
+ const { createdRow } = await onSubmitDraft();
3168
+ rowPersisted = true;
3169
+ committedRecordIdRef.current = createdRow ? uploadMutation.resolveRowIdentifier(createdRow) : null;
3338
3170
  }
3339
- return;
3171
+ const committedId = committedRecordIdRef.current;
3172
+ if (committedId == null) throw new Error("Uploads require a primary-key identity for the created row.");
3173
+ import_toast.toast.info({ message: `Uploading ${noun}...` });
3174
+ setUploadState("uploading");
3175
+ const saved = await uploadMutation.write(committedId, selectedFile);
3176
+ finishSave(saved, createRow ? `Row created and ${noun} uploaded` : `${Noun} uploaded successfully`);
3177
+ } catch (error) {
3178
+ if (rowPersisted) onDraftUploadComplete?.();
3179
+ handleWriteError(error instanceof Error ? error : new Error("Upload failed"));
3340
3180
  }
3341
- if (!committedId) {
3342
- import_toast.toast.error({ message: "Missing record context for upload" });
3181
+ }, [
3182
+ isBusy,
3183
+ tableName,
3184
+ fieldName,
3185
+ selectedFile,
3186
+ isDraftRow,
3187
+ recordId,
3188
+ uploadMutation,
3189
+ onSubmitDraft,
3190
+ noun,
3191
+ Noun,
3192
+ finishSave,
3193
+ onDraftUploadComplete,
3194
+ handleWriteError
3195
+ ]);
3196
+ const handleSave = (0, import_react14.useCallback)(async () => {
3197
+ if (isBusy) return;
3198
+ if (!clearPending) {
3199
+ onFinishedEditing();
3343
3200
  return;
3344
3201
  }
3345
- setUploadState("uploading");
3346
- uploadMutation.mutate(selectedFile);
3347
- }, [selectedFile, uploadMutation, tableName, fieldName, recordId, isDraftRow, onSubmitDraft, config.endpoint, config.onAuthError, getToken, resetFileState, onDraftUploadComplete, onFinishedEditing, noun, Noun]);
3348
- const handleSave = (0, import_react15.useCallback)(() => {
3349
- if (!imageValue) {
3350
- onFinishedEditing(null);
3202
+ const targetId = committedRecordIdRef.current ?? recordId;
3203
+ if (targetId == null) {
3204
+ if (isDraftRow) {
3205
+ finishSave(null, `${Noun} cleared`);
3206
+ } else {
3207
+ handleWriteError(new Error("Missing record context for clear"));
3208
+ }
3351
3209
  return;
3352
3210
  }
3353
- const url = getImageUrl(imageValue);
3354
- const originalUrl = getImageUrl(value);
3355
- if (url && originalUrl === url) {
3356
- onFinishedEditing();
3211
+ setUploadState("clearing");
3212
+ if (committedRecordIdRef.current == null) {
3213
+ uploadMutation.mutate(null);
3357
3214
  return;
3358
3215
  }
3359
- onFinishedEditing(url ?? value);
3360
- }, [imageValue, value, onFinishedEditing]);
3361
- const handleCancel = (0, import_react15.useCallback)(() => {
3216
+ try {
3217
+ const saved = await uploadMutation.write(targetId, null);
3218
+ finishSave(saved, `${Noun} cleared`);
3219
+ } catch (error) {
3220
+ handleWriteError(error instanceof Error ? error : new Error("Clear failed"));
3221
+ }
3222
+ }, [isBusy, clearPending, onFinishedEditing, recordId, isDraftRow, finishSave, Noun, handleWriteError, uploadMutation]);
3223
+ const handleCancel = (0, import_react14.useCallback)(() => {
3362
3224
  revokePreviewUrl();
3363
3225
  onFinishedEditing();
3364
3226
  }, [revokePreviewUrl, onFinishedEditing]);
3365
- (0, import_react15.useEffect)(() => () => revokePreviewUrl(), [revokePreviewUrl]);
3366
- const handleEditorKeyDown = (0, import_react15.useCallback)((e) => {
3227
+ (0, import_react14.useEffect)(() => () => revokePreviewUrl(), [revokePreviewUrl]);
3228
+ const handleEditorKeyDown = (0, import_react14.useCallback)((e) => {
3367
3229
  if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
3368
3230
  e.preventDefault();
3369
- handleSave();
3231
+ if (selectedFile) void handleConfirmUpload();
3232
+ else void handleSave();
3370
3233
  }
3371
- }, [handleSave]);
3372
- const hasStoredFile = acceptAnyFile && !!imageUrl && !storedIsImage;
3234
+ }, [handleConfirmUpload, handleSave, selectedFile]);
3235
+ const hasStoredFile = hasStoredMedia && !hasImage && !imageLoadFailed;
3373
3236
  const dropzoneKey = isBusy ? "busy" : previewUrl ? "preview" : hasImage ? "loaded" : hasStoredFile ? "file" : imageLoadFailed ? "broken" : "empty";
3374
3237
  const renderDropzoneContent = () => {
3375
3238
  if (isBusy) {
3376
3239
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { "data-state": uploadState, className: "text-muted-foreground flex w-full flex-col items-center justify-center p-6", children: [
3377
3240
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.Loader2, { className: "mb-2 size-6 animate-spin" }),
3378
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { className: "text-sm", children: isSubmittingDraft ? "Creating row..." : `Uploading ${noun}...` }),
3241
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { role: "status", className: "text-sm", children: isSubmittingDraft ? "Creating row..." : isClearing ? `Clearing ${noun}...` : `Uploading ${noun}...` }),
3379
3242
  isUploading && uploadProgress && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "mt-3 w-full max-w-xs", children: [
3380
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "bg-muted h-1.5 overflow-hidden rounded-full", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3243
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3381
3244
  "div",
3382
3245
  {
3383
- className: "bg-primary h-1.5 rounded-full transition-[width] duration-(--duration-slow)",
3384
- style: { width: `${uploadProgress.percentage}%` }
3246
+ role: "progressbar",
3247
+ "aria-label": `Uploading ${noun}`,
3248
+ "aria-valuemin": 0,
3249
+ "aria-valuemax": 100,
3250
+ "aria-valuenow": Math.round(uploadProgress.percentage),
3251
+ className: "bg-muted h-1.5 overflow-hidden rounded-full",
3252
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3253
+ "div",
3254
+ {
3255
+ className: "bg-primary h-1.5 rounded-full transition-[width] duration-(--duration-slow)",
3256
+ style: { width: `${uploadProgress.percentage}%` }
3257
+ }
3258
+ )
3385
3259
  }
3386
- ) }),
3387
- /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("p", { className: "text-muted-foreground mt-1.5 text-center text-xs", children: [
3260
+ ),
3261
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("p", { "aria-hidden": "true", className: "text-muted-foreground mt-1.5 text-center text-xs tabular-nums", children: [
3388
3262
  Math.round(uploadProgress.percentage),
3389
3263
  "%"
3390
3264
  ] })
@@ -3392,7 +3266,6 @@ var ImageEditor = ({
3392
3266
  ] });
3393
3267
  }
3394
3268
  if (previewUrl) {
3395
- const selectedIsImage = !acceptAnyFile || (selectedFile?.type.startsWith("image/") ?? false);
3396
3269
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "relative w-full", style: { height: "13rem" }, children: [
3397
3270
  selectedIsImage ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("img", { src: previewUrl, alt: selectedFile?.name || "Selected file", className: "size-full object-contain p-2" }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(FilePreview, { name: selectedFile?.name, size: selectedFile?.size, mime: selectedFile?.type }),
3398
3271
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(RemoveButton, { onClick: removeFile, label: "Remove selected file" })
@@ -3415,7 +3288,7 @@ var ImageEditor = ({
3415
3288
  }
3416
3289
  if (hasStoredFile) {
3417
3290
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "relative w-full", style: { height: "13rem" }, children: [
3418
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(FilePreview, { name: imageMetadata?.filename, size: imageMetadata?.size, mime: imageMetadata?.mime }),
3291
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(FilePreview, { name: imageMetadata?.filename ?? durableUrl ?? void 0, size: imageMetadata?.size, mime: imageMetadata?.mime }),
3419
3292
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(RemoveButton, { onClick: handleRemoveImage, label: "Remove file" })
3420
3293
  ] });
3421
3294
  }
@@ -3430,12 +3303,12 @@ var ImageEditor = ({
3430
3303
  }
3431
3304
  ),
3432
3305
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { className: "text-sm font-medium", children: "Image unavailable" }),
3433
- imageUrl && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3306
+ durableUrl && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3434
3307
  "p",
3435
3308
  {
3436
3309
  className: "text-muted-foreground mt-1 max-w-full truncate font-mono text-[11px] opacity-50",
3437
- title: imageUrl,
3438
- children: imageUrl
3310
+ title: durableUrl,
3311
+ children: durableUrl
3439
3312
  }
3440
3313
  ),
3441
3314
  /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "mt-3 flex items-center gap-2", children: [
@@ -3498,7 +3371,7 @@ var ImageEditor = ({
3498
3371
  )
3499
3372
  ] });
3500
3373
  };
3501
- const saveLabel = isSubmittingDraft ? "Creating..." : isUploading ? "Uploading..." : imageUrl ? "Save" : "Done";
3374
+ const saveLabel = isSubmittingDraft ? "Creating..." : isClearing ? "Clearing..." : isUploading ? "Uploading..." : hasStoredMedia || clearPending ? "Save" : "Done";
3502
3375
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3503
3376
  EditorFocusTrap,
3504
3377
  {
@@ -3508,7 +3381,7 @@ var ImageEditor = ({
3508
3381
  children: /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { onKeyDown: handleEditorKeyDown, className: "flex min-h-0 flex-1 flex-col", children: [
3509
3382
  /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "flex shrink-0 items-center gap-2 border-b px-6 py-3", children: [
3510
3383
  acceptAnyFile ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.FileIcon, { className: "text-muted-foreground size-4" }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.ImageIcon, { className: "text-muted-foreground size-4" }),
3511
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("h3", { className: "text-sm font-medium", children: imageUrl ? `Edit ${Noun}` : `Add ${Noun}` })
3384
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("h3", { className: "text-sm font-medium", children: hasStoredMedia ? `Edit ${Noun}` : `Add ${Noun}` })
3512
3385
  ] }),
3513
3386
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3514
3387
  "input",
@@ -3538,8 +3411,8 @@ var ImageEditor = ({
3538
3411
  className: "bg-muted/20 hover:bg-muted/30 data-[dragging=true]:bg-accent/50 data-[dragging=true]:border-primary/40\n relative flex cursor-pointer flex-col items-center justify-center overflow-hidden rounded-lg\n border border-dashed border-border/60 transition-colors",
3539
3412
  style: { height: "13rem" },
3540
3413
  onClick: isBusy ? void 0 : openFileDialog,
3541
- children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_react16.AnimatePresence, { mode: "wait", initial: false, children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3542
- import_react16.motion.div,
3414
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_react15.AnimatePresence, { mode: "wait", initial: false, children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3415
+ import_react15.motion.div,
3543
3416
  {
3544
3417
  initial: { opacity: 0 },
3545
3418
  animate: { opacity: 1 },
@@ -3556,7 +3429,7 @@ var ImageEditor = ({
3556
3429
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.AlertCircleIcon, { className: "size-3 shrink-0" }),
3557
3430
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { children: dragErrors[0] })
3558
3431
  ] }),
3559
- !isBusy && (selectedFile || imageMetadata && hasImage) && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "text-muted-foreground mt-2 text-center text-xs", children: selectedFile ? /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_jsx_runtime11.Fragment, { children: [
3432
+ !isBusy && (selectedFile ? selectedIsImage : imageMetadata && hasImage) && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "text-muted-foreground mt-2 text-center text-xs", children: selectedFile ? /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_jsx_runtime11.Fragment, { children: [
3560
3433
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: "font-medium", children: selectedFile.name }),
3561
3434
  " \u2022 ",
3562
3435
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { children: formatFileSize(selectedFile.size) }),
@@ -3576,7 +3449,7 @@ var ImageEditor = ({
3576
3449
  ] }) }),
3577
3450
  /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "flex shrink-0 justify-end gap-2 border-t px-6 py-3", children: [
3578
3451
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_button5.Button, { type: "button", variant: "outline", size: "sm", onClick: handleCancel, disabled: isBusy, children: "Cancel" }),
3579
- selectedFile && !isBusy ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_button5.Button, { type: "button", size: "sm", onClick: handleConfirmUpload, children: isDraftRow ? "Create Row & Upload" : "Upload & Save" }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_button5.Button, { type: "button", size: "sm", onClick: handleSave, disabled: isBusy, children: [
3452
+ selectedFile && !isBusy ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_button5.Button, { type: "button", size: "sm", onClick: handleConfirmUpload, children: needsDraftCreation ? "Create Row & Upload" : "Upload & Save" }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_button5.Button, { type: "button", size: "sm", onClick: handleSave, disabled: isBusy, children: [
3580
3453
  isBusy && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.Loader2, { className: "size-3.5 animate-spin" }),
3581
3454
  saveLabel
3582
3455
  ] })
@@ -3594,21 +3467,19 @@ function ImageEditorDom({
3594
3467
  cell,
3595
3468
  colKey,
3596
3469
  rowId,
3470
+ rowIdentifier,
3597
3471
  tableName,
3598
3472
  onCommitPatch,
3599
3473
  onCancel,
3600
3474
  onSubmitDraftRow,
3601
3475
  onInvalidateData
3602
3476
  }) {
3603
- const isDraftRow = rowId.startsWith(DRAFT_PREFIX);
3477
+ const isDraftRow = rowIdentifier == null && rowId.startsWith(DRAFT_PREFIX);
3604
3478
  const cellType = cell.meta?.cellType;
3605
3479
  const acceptAnyFile = cellType != null && cellType !== "image";
3606
3480
  const handleSaveComplete = onCommitPatch ? (saveData) => onCommitPatch({ [colKey]: saveData.imageData }) : void 0;
3607
- const handleSubmitDraft = isDraftRow && onSubmitDraftRow ? async () => {
3608
- const createdRow = await onSubmitDraftRow(rowId);
3609
- return { createdRow };
3610
- } : void 0;
3611
- return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { "data-slot": "image-editor", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_react17.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "h-64 w-full min-w-[480px] animate-pulse rounded-lg bg-muted" }), children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
3481
+ const handleSubmitDraft = isDraftRow && onSubmitDraftRow ? () => onSubmitDraftRow(rowId) : void 0;
3482
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { "data-slot": "image-editor", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_react16.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "h-64 w-full min-w-[480px] animate-pulse rounded-lg bg-muted" }), children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
3612
3483
  ImageEditor,
3613
3484
  {
3614
3485
  value,
@@ -3616,7 +3487,7 @@ function ImageEditorDom({
3616
3487
  onFinishedEditing: () => onCancel(),
3617
3488
  tableName,
3618
3489
  fieldName: colKey,
3619
- recordId: rowId,
3490
+ recordId: rowIdentifier ?? null,
3620
3491
  onSaveComplete: handleSaveComplete,
3621
3492
  isDraftRow,
3622
3493
  onSubmitDraft: handleSubmitDraft,
@@ -3626,7 +3497,7 @@ function ImageEditorDom({
3626
3497
  }
3627
3498
 
3628
3499
  // src/grid/editors/inet-editor.tsx
3629
- var import_react18 = require("react");
3500
+ var import_react17 = require("react");
3630
3501
  var import_button6 = require("@constructive-io/ui/button");
3631
3502
  init_editor_focus_trap();
3632
3503
  init_overlay_presets();
@@ -3676,26 +3547,26 @@ function getInetType(value) {
3676
3547
  }
3677
3548
  var InetEditor = ({ value, onFinishedEditing }) => {
3678
3549
  const currentInetData = typeof value === "string" ? value : "";
3679
- const [editingValue, setEditingValue] = (0, import_react18.useState)(currentInetData);
3680
- const [validationError, setValidationError] = (0, import_react18.useState)("");
3681
- const keyContainerRef = (0, import_react18.useRef)(null);
3682
- const handleSave = (0, import_react18.useCallback)(() => {
3550
+ const [editingValue, setEditingValue] = (0, import_react17.useState)(currentInetData);
3551
+ const [validationError, setValidationError] = (0, import_react17.useState)("");
3552
+ const keyContainerRef = (0, import_react17.useRef)(null);
3553
+ const handleSave = (0, import_react17.useCallback)(() => {
3683
3554
  if (editingValue.trim() && !isValidInet(editingValue.trim())) {
3684
3555
  setValidationError("Invalid IP address or CIDR");
3685
3556
  return;
3686
3557
  }
3687
3558
  onFinishedEditing(editingValue.trim());
3688
3559
  }, [editingValue, onFinishedEditing]);
3689
- const handleCancel = (0, import_react18.useCallback)(() => {
3560
+ const handleCancel = (0, import_react17.useCallback)(() => {
3690
3561
  onFinishedEditing();
3691
3562
  }, [onFinishedEditing]);
3692
- const handleInputChange = (0, import_react18.useCallback)((e) => {
3563
+ const handleInputChange = (0, import_react17.useCallback)((e) => {
3693
3564
  setEditingValue(e.target.value);
3694
3565
  setValidationError("");
3695
3566
  }, []);
3696
- const actionsRef = (0, import_react18.useRef)({ handleSave, handleCancel });
3567
+ const actionsRef = (0, import_react17.useRef)({ handleSave, handleCancel });
3697
3568
  actionsRef.current = { handleSave, handleCancel };
3698
- (0, import_react18.useEffect)(() => {
3569
+ (0, import_react17.useEffect)(() => {
3699
3570
  const el = keyContainerRef.current;
3700
3571
  if (!el) return;
3701
3572
  const handler = (e) => {
@@ -3781,7 +3652,7 @@ function InetEditorDom({ value, onCommit, onCancel }) {
3781
3652
  }
3782
3653
 
3783
3654
  // src/grid/editors/interval-editor.tsx
3784
- var import_react19 = require("react");
3655
+ var import_react18 = require("react");
3785
3656
  var import_lucide_react5 = require("lucide-react");
3786
3657
  var import_button7 = require("@constructive-io/ui/button");
3787
3658
  var import_input = require("@constructive-io/ui/input");
@@ -3831,14 +3702,14 @@ function formatIntervalValue(interval) {
3831
3702
  }
3832
3703
  var IntervalEditor = ({ value, onFinishedEditing }) => {
3833
3704
  const currentIntervalData = typeof value === "string" ? value : "";
3834
- const [editingValue, setEditingValue] = (0, import_react19.useState)(() => parseIntervalValue(currentIntervalData));
3835
- const handleSave = (0, import_react19.useCallback)(() => {
3705
+ const [editingValue, setEditingValue] = (0, import_react18.useState)(() => parseIntervalValue(currentIntervalData));
3706
+ const handleSave = (0, import_react18.useCallback)(() => {
3836
3707
  onFinishedEditing(JSON.stringify(editingValue));
3837
3708
  }, [editingValue, onFinishedEditing]);
3838
- const handleCancel = (0, import_react19.useCallback)(() => {
3709
+ const handleCancel = (0, import_react18.useCallback)(() => {
3839
3710
  onFinishedEditing();
3840
3711
  }, [onFinishedEditing]);
3841
- const handleInputChange = (0, import_react19.useCallback)((field, newValue) => {
3712
+ const handleInputChange = (0, import_react18.useCallback)((field, newValue) => {
3842
3713
  const numValue = parseInt(newValue) || 0;
3843
3714
  setEditingValue((prev) => ({
3844
3715
  ...prev,
@@ -3846,7 +3717,7 @@ var IntervalEditor = ({ value, onFinishedEditing }) => {
3846
3717
  // Ensure non-negative values
3847
3718
  }));
3848
3719
  }, []);
3849
- const handleEditorKeyDown = (0, import_react19.useCallback)(
3720
+ const handleEditorKeyDown = (0, import_react18.useCallback)(
3850
3721
  (e) => {
3851
3722
  if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
3852
3723
  e.preventDefault();
@@ -3956,7 +3827,7 @@ function IntervalEditorDom({ value, onCommit, onCancel }) {
3956
3827
  }
3957
3828
 
3958
3829
  // src/grid/editors/json-editor.tsx
3959
- var import_react20 = require("react");
3830
+ var import_react19 = require("react");
3960
3831
  var import_button8 = require("@constructive-io/ui/button");
3961
3832
  init_editor_focus_trap();
3962
3833
  init_overlay_presets();
@@ -3990,18 +3861,18 @@ function highlightJson(json) {
3990
3861
  );
3991
3862
  }
3992
3863
  function JsonEditor({ value, onChange, onFinished }) {
3993
- const [text, setText] = (0, import_react20.useState)(() => typeof value === "string" ? value : JSON.stringify(value, null, 2));
3994
- const textareaRef = (0, import_react20.useRef)(null);
3995
- const preRef = (0, import_react20.useRef)(null);
3996
- const keyContainerRef = (0, import_react20.useRef)(null);
3997
- const { parsed, valid } = (0, import_react20.useMemo)(() => {
3864
+ const [text, setText] = (0, import_react19.useState)(() => typeof value === "string" ? value : JSON.stringify(value, null, 2));
3865
+ const textareaRef = (0, import_react19.useRef)(null);
3866
+ const preRef = (0, import_react19.useRef)(null);
3867
+ const keyContainerRef = (0, import_react19.useRef)(null);
3868
+ const { parsed, valid } = (0, import_react19.useMemo)(() => {
3998
3869
  try {
3999
3870
  return { parsed: JSON.parse(text), valid: true };
4000
3871
  } catch {
4001
3872
  return { parsed: text, valid: false };
4002
3873
  }
4003
3874
  }, [text]);
4004
- const handleChange = (0, import_react20.useCallback)(
3875
+ const handleChange = (0, import_react19.useCallback)(
4005
3876
  (e) => {
4006
3877
  const next = e.target.value;
4007
3878
  setText(next);
@@ -4012,11 +3883,11 @@ function JsonEditor({ value, onChange, onFinished }) {
4012
3883
  },
4013
3884
  [onChange]
4014
3885
  );
4015
- const handleCancel = (0, import_react20.useCallback)(() => onFinished(void 0), [onFinished]);
4016
- const handleSave = (0, import_react20.useCallback)(() => {
3886
+ const handleCancel = (0, import_react19.useCallback)(() => onFinished(void 0), [onFinished]);
3887
+ const handleSave = (0, import_react19.useCallback)(() => {
4017
3888
  if (valid) onFinished(parsed);
4018
3889
  }, [onFinished, parsed, valid]);
4019
- const handleScroll = (0, import_react20.useCallback)(() => {
3890
+ const handleScroll = (0, import_react19.useCallback)(() => {
4020
3891
  const ta = textareaRef.current;
4021
3892
  const pre = preRef.current;
4022
3893
  if (ta && pre) {
@@ -4024,9 +3895,9 @@ function JsonEditor({ value, onChange, onFinished }) {
4024
3895
  pre.scrollLeft = ta.scrollLeft;
4025
3896
  }
4026
3897
  }, []);
4027
- const actionsRef = (0, import_react20.useRef)({ handleSave, handleCancel });
3898
+ const actionsRef = (0, import_react19.useRef)({ handleSave, handleCancel });
4028
3899
  actionsRef.current = { handleSave, handleCancel };
4029
- (0, import_react20.useEffect)(() => {
3900
+ (0, import_react19.useEffect)(() => {
4030
3901
  const el = keyContainerRef.current;
4031
3902
  if (!el) return;
4032
3903
  const handler = (e) => {
@@ -4061,7 +3932,7 @@ function JsonEditor({ value, onChange, onFinished }) {
4061
3932
  el.addEventListener("keydown", handler);
4062
3933
  return () => el.removeEventListener("keydown", handler);
4063
3934
  }, []);
4064
- const highlighted = (0, import_react20.useMemo)(() => highlightJson(text), [text]);
3935
+ const highlighted = (0, import_react19.useMemo)(() => highlightJson(text), [text]);
4065
3936
  const isMac = typeof navigator !== "undefined" && MAC_UA_RE4.test(navigator.userAgent);
4066
3937
  const modKey = isMac ? "\u2318" : "Ctrl";
4067
3938
  return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(EditorFocusTrap, { onEscape: handleCancel, className: `bg-popover ${OVERLAY.lg} rounded-lg border p-2.5 shadow-lg`, children: /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)("div", { ref: keyContainerRef, children: [
@@ -4132,7 +4003,7 @@ function JsonEditorDom({ value, onCommit, onCancel }) {
4132
4003
  }
4133
4004
 
4134
4005
  // src/grid-dom/editors/number-editor.tsx
4135
- var import_react21 = require("react");
4006
+ var import_react20 = require("react");
4136
4007
  var import_button9 = require("@constructive-io/ui/button");
4137
4008
  init_overlay_presets();
4138
4009
  init_cn();
@@ -4148,8 +4019,8 @@ function parseValue(text) {
4148
4019
  return Number(trimmed);
4149
4020
  }
4150
4021
  function NumberEditorDom({ value, initialText, colKey, fieldMeta, onCommit, onCancel }) {
4151
- const [text, setText] = (0, import_react21.useState)(() => initialText != null ? initialText : seedText(value));
4152
- const escapedRef = (0, import_react21.useRef)(false);
4022
+ const [text, setText] = (0, import_react20.useState)(() => initialText != null ? initialText : seedText(value));
4023
+ const escapedRef = (0, import_react20.useRef)(false);
4153
4024
  const parsed = parseValue(text);
4154
4025
  const canSave = parsed === null || Number.isFinite(parsed);
4155
4026
  function commit() {
@@ -4205,33 +4076,33 @@ NumberEditorDom.commitsOnBlur = true;
4205
4076
  // src/grid/editors/relation-editor.tsx
4206
4077
  var import_react25 = require("react");
4207
4078
  var import_lucide_react6 = require("lucide-react");
4208
- var import_react_query5 = require("@tanstack/react-query");
4079
+ var import_react_query6 = require("@tanstack/react-query");
4209
4080
 
4210
4081
  // src/hooks/use-sheets-table-cursor.ts
4211
- var import_react22 = require("react");
4212
- var import_react_query4 = require("@tanstack/react-query");
4213
- var import_data13 = require("@constructive-io/data");
4214
- var import_data14 = require("@constructive-io/data");
4215
- var import_data15 = require("@constructive-io/data");
4082
+ var import_react21 = require("react");
4083
+ var import_react_query5 = require("@tanstack/react-query");
4084
+ var import_data10 = require("@constructive-io/data");
4085
+ var import_data11 = require("@constructive-io/data");
4086
+ var import_data12 = require("@constructive-io/data");
4216
4087
  function useSheetsTableCursor(tableName, options = {}) {
4217
- const queryClient = (0, import_react_query4.useQueryClient)();
4088
+ const queryClient = (0, import_react_query5.useQueryClient)();
4218
4089
  const { execute, scopeKey } = useSheetsContext();
4219
4090
  const { data: meta } = useSheetsMeta();
4220
4091
  const adapter = useSheetsAdapter();
4221
- const tables = (0, import_react22.useMemo)(() => {
4092
+ const tables = (0, import_react21.useMemo)(() => {
4222
4093
  if (!meta?._meta?.tables) return [];
4223
- return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data13.cleanTable)(metaTable));
4094
+ return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data10.cleanTable)(metaTable));
4224
4095
  }, [meta]);
4225
- const table = (0, import_react22.useMemo)(
4096
+ const table = (0, import_react21.useMemo)(
4226
4097
  () => tables.find((candidate) => candidate.name === tableName) ?? null,
4227
4098
  [tables, tableName]
4228
4099
  );
4229
4100
  const { enabled = true, select: fieldSelection, pageSize = 20, where, orderBy } = options;
4230
- const stableOptions = (0, import_react22.useMemo)(
4101
+ const stableOptions = (0, import_react21.useMemo)(
4231
4102
  () => ({ fieldSelection, where, orderBy }),
4232
4103
  [fieldSelection, where, orderBy]
4233
4104
  );
4234
- const queryOptions = (0, import_react22.useMemo)(
4105
+ const queryOptions = (0, import_react21.useMemo)(
4235
4106
  () => ({
4236
4107
  fieldSelection,
4237
4108
  where,
@@ -4248,11 +4119,11 @@ function useSheetsTableCursor(tableName, options = {}) {
4248
4119
  hasNextPage,
4249
4120
  fetchNextPage,
4250
4121
  error
4251
- } = (0, import_react_query4.useInfiniteQuery)({
4122
+ } = (0, import_react_query5.useInfiniteQuery)({
4252
4123
  queryKey: sheetsQueryKeys.cursorTable(scopeKey, tableName, stableOptions),
4253
4124
  queryFn: async ({ pageParam }) => {
4254
4125
  if (!table) {
4255
- throw import_data14.createError.notFound(`Table '${tableName}' not found`);
4126
+ throw import_data11.createError.notFound(`Table '${tableName}' not found`);
4256
4127
  }
4257
4128
  const cursor = pageParam;
4258
4129
  const variableOptions = {
@@ -4275,7 +4146,7 @@ function useSheetsTableCursor(tableName, options = {}) {
4275
4146
  const validatedOrderByEnum = new Set(variables.orderBy ?? []);
4276
4147
  const availableOrderByFields = new Set(table.fields.map((field) => field.name));
4277
4148
  const validatedOrderBy = orderBy?.filter(
4278
- ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data15.toOrderByEnumValue)(field, direction))
4149
+ ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data12.toOrderByEnumValue)(field, direction))
4279
4150
  );
4280
4151
  const res = await adapter.listRows(
4281
4152
  { table, allTables: tables, tableName },
@@ -4305,11 +4176,11 @@ function useSheetsTableCursor(tableName, options = {}) {
4305
4176
  enabled: enabled && !!table,
4306
4177
  staleTime: 5 * 60 * 1e3
4307
4178
  });
4308
- const flatData = (0, import_react22.useMemo)(
4179
+ const flatData = (0, import_react21.useMemo)(
4309
4180
  () => data?.pages.flatMap((page) => page.rows) ?? [],
4310
4181
  [data]
4311
4182
  );
4312
- const totalCount = (0, import_react22.useMemo)(
4183
+ const totalCount = (0, import_react21.useMemo)(
4313
4184
  () => data?.pages[data.pages.length - 1]?.totalCount ?? 0,
4314
4185
  [data]
4315
4186
  );
@@ -4324,6 +4195,18 @@ function useSheetsTableCursor(tableName, options = {}) {
4324
4195
  };
4325
4196
  }
4326
4197
 
4198
+ // src/store/sheets-store.ts
4199
+ var import_react22 = require("react");
4200
+ var import_zustand = require("zustand");
4201
+ var SheetsStoreContext = (0, import_react22.createContext)(null);
4202
+ function useSheetsStore(selector) {
4203
+ const store = (0, import_react22.useContext)(SheetsStoreContext);
4204
+ if (!store) {
4205
+ throw new Error("useSheetsStore must be used within a <SheetsProvider>");
4206
+ }
4207
+ return (0, import_zustand.useStore)(store, selector);
4208
+ }
4209
+
4327
4210
  // src/grid/editors/relation-editor.tsx
4328
4211
  init_cn();
4329
4212
  var import_badge2 = require("@constructive-io/ui/badge");
@@ -4462,7 +4345,7 @@ var RelationEditor = ({
4462
4345
  }) => {
4463
4346
  const { data: meta } = useSheetsMeta();
4464
4347
  const { scopeKey } = useSheetsContext();
4465
- const queryClient = (0, import_react_query5.useQueryClient)();
4348
+ const queryClient = (0, import_react_query6.useQueryClient)();
4466
4349
  const ensureRelationInfo = useSheetsStore((s) => s.ensureRelationInfo);
4467
4350
  const relationInfoForTable = useSheetsStore((s) => tableName ? s.relationInfoCache[tableName] : void 0);
4468
4351
  const relationEntry = relationInfoForTable?.[fieldName];
@@ -5228,6 +5111,7 @@ var DOM_EDITOR_REGISTRY = {
5228
5111
  video: ImageEditorDom,
5229
5112
  audio: ImageEditorDom,
5230
5113
  upload: ImageEditorDom,
5114
+ attachment: ImageEditorDom,
5231
5115
  // Date/time types
5232
5116
  date: DateEditorDom,
5233
5117
  datetime: DateEditorDom,
@@ -5390,21 +5274,12 @@ var geometrySheetsCellFactory = { canHandle: canHandle3, create: create3 };
5390
5274
 
5391
5275
  // src/cell-model/factories/image.ts
5392
5276
  init_cell_type_groups();
5393
- function resolveMediaUrl(value) {
5394
- if (typeof value === "string") return value;
5395
- if (typeof value === "object" && value) {
5396
- const obj = value;
5397
- return obj.url || obj.src || obj.href || obj.path || "";
5398
- }
5399
- return "";
5400
- }
5401
5277
  var imageSheetsCellFactory = {
5402
5278
  canHandle(cellType) {
5403
- return MEDIA_TYPES.has(cellType);
5279
+ return cellType !== "attachment" && MEDIA_TYPES.has(cellType);
5404
5280
  },
5405
5281
  create(value, metadata) {
5406
- const url = value === null || value === void 0 || value === "" ? "" : resolveMediaUrl(value);
5407
- const data = [url];
5282
+ const data = [getImageUrl(value) ?? ""];
5408
5283
  return {
5409
5284
  kind: "image",
5410
5285
  data,