@dimah-s3/db 2.0.0-beta.1 → 2.0.0-beta.10

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 (82) hide show
  1. package/README.md +19 -10
  2. package/dist/adapters/drizzle.d.ts +2 -3
  3. package/dist/adapters/drizzle.d.ts.map +1 -1
  4. package/dist/adapters/kysely.d.ts +1 -1
  5. package/dist/adapters/prisma.d.ts +1 -1
  6. package/dist/cli.d.ts +18 -13
  7. package/dist/cli.d.ts.map +1 -1
  8. package/dist/cli.js +57 -84
  9. package/dist/cli.js.map +1 -1
  10. package/dist/client/db-client.d.ts +1 -1
  11. package/dist/client/db-client.d.ts.map +1 -1
  12. package/dist/client/db-object-source.d.ts +15 -9
  13. package/dist/client/db-object-source.d.ts.map +1 -1
  14. package/dist/client/index.d.ts +3 -3
  15. package/dist/client/index.d.ts.map +1 -1
  16. package/dist/client/index.js +101 -21
  17. package/dist/client/index.js.map +1 -1
  18. package/dist/folder-path.d.ts +17 -4
  19. package/dist/folder-path.d.ts.map +1 -1
  20. package/dist/fuma-db.d.ts +23 -23
  21. package/dist/fuma-db.d.ts.map +1 -1
  22. package/dist/index.d.ts +9 -9
  23. package/dist/index.js +595 -267
  24. package/dist/index.js.map +1 -1
  25. package/dist/plugin/create-database-endpoints.d.ts +46 -22
  26. package/dist/plugin/create-database-endpoints.d.ts.map +1 -1
  27. package/dist/plugin/create-database-lifecycle-hooks.d.ts +4 -4
  28. package/dist/plugin/create-database-lifecycle-hooks.d.ts.map +1 -1
  29. package/dist/plugin/db.d.ts +2 -2
  30. package/dist/plugin/db.d.ts.map +1 -1
  31. package/dist/plugin/object-access.d.ts +2 -2
  32. package/dist/plugin/object-access.d.ts.map +1 -1
  33. package/dist/plugin/public-stores.d.ts +5 -8
  34. package/dist/plugin/public-stores.d.ts.map +1 -1
  35. package/dist/plugin/quota.d.ts +1 -1
  36. package/dist/plugin/schemas.d.ts +25 -11
  37. package/dist/plugin/schemas.d.ts.map +1 -1
  38. package/dist/plugin/scope.d.ts +2 -0
  39. package/dist/plugin/scope.d.ts.map +1 -1
  40. package/dist/plugin/to-db-client-object.d.ts.map +1 -1
  41. package/dist/schema/schema.d.ts +48 -49
  42. package/dist/schema/schema.d.ts.map +1 -1
  43. package/dist/store/create-db-store.d.ts +2 -2
  44. package/dist/store/create-db-store.d.ts.map +1 -1
  45. package/dist/store/folder-store.d.ts +73 -15
  46. package/dist/store/folder-store.d.ts.map +1 -1
  47. package/dist/store/list-cursor.d.ts +3 -1
  48. package/dist/store/list-cursor.d.ts.map +1 -1
  49. package/dist/store/map-row.d.ts +3 -9
  50. package/dist/store/map-row.d.ts.map +1 -1
  51. package/dist/store/object-store.d.ts +20 -10
  52. package/dist/store/object-store.d.ts.map +1 -1
  53. package/dist/store/search-name.d.ts +7 -0
  54. package/dist/store/search-name.d.ts.map +1 -0
  55. package/dist/types/client.d.ts +114 -23
  56. package/dist/types/client.d.ts.map +1 -1
  57. package/dist/types/plugin.d.ts +17 -6
  58. package/dist/types/plugin.d.ts.map +1 -1
  59. package/dist/types/storage-object.d.ts +8 -7
  60. package/dist/types/storage-object.d.ts.map +1 -1
  61. package/package.json +15 -33
  62. package/dist/drizzle/mysql.d.ts +0 -1025
  63. package/dist/drizzle/mysql.d.ts.map +0 -1
  64. package/dist/drizzle/mysql.js +0 -117
  65. package/dist/drizzle/mysql.js.map +0 -1
  66. package/dist/drizzle/pg.d.ts +0 -964
  67. package/dist/drizzle/pg.d.ts.map +0 -1
  68. package/dist/drizzle/pg.js +0 -98
  69. package/dist/drizzle/pg.js.map +0 -1
  70. package/dist/drizzle/shared.d.ts +0 -7
  71. package/dist/drizzle/shared.d.ts.map +0 -1
  72. package/dist/drizzle/sqlite.d.ts +0 -1024
  73. package/dist/drizzle/sqlite.d.ts.map +0 -1
  74. package/dist/drizzle/sqlite.js +0 -101
  75. package/dist/drizzle/sqlite.js.map +0 -1
  76. package/prisma/dimah-s3.prisma +0 -80
  77. package/sql/mysql.sql +0 -59
  78. package/sql/pg.sql +0 -53
  79. package/sql/sqlite.sql +0 -54
  80. package/src/drizzle/mysql.ts +0 -172
  81. package/src/drizzle/pg.ts +0 -140
  82. package/src/drizzle/sqlite.ts +0 -144
package/dist/index.js CHANGED
@@ -1,152 +1,123 @@
1
- import { fumadb } from 'fumadb';
1
+ import { fumadb, UniqueConstraintError } from 'fumadb';
2
2
  import { table, column, idColumn, schema } from 'fumadb/schema';
3
3
  import { definePlugin, isFeatureOn, createS3Endpoint, isAwsNotFound, readUploadMarker, deleteObjectIfMatch } from '@dimah-s3/server/plugins';
4
- import { s3Error, pluginPath, base64UrlDecode, base64UrlEncode } from '@dimah-s3/core';
4
+ import { s3Error, pluginPath, normalizeSearchText, base64UrlDecode, base64UrlEncode, matchesSearchText } from '@dimah-s3/core';
5
5
  import { optionalContentTypeSchema, optionalTrimmedString, routeNameSchema, objectKeySchema, trimmedString, fileNameSchema } from '@dimah-s3/core/schema';
6
6
  import * as z from 'zod';
7
7
  import { AbortMultipartUploadCommand, HeadObjectCommand } from '@aws-sdk/client-s3';
8
8
 
9
9
  // src/fuma-db.ts
10
- function byteCount(name) {
11
- return column(name, "bigint").nullable();
10
+ var BINARY = { mysql: "utf8mb4_bin" };
11
+ var TEXT = { mysql: "utf8mb4_unicode_ci" };
12
+ var SEARCH_NAME_MAX_LENGTH = 1024;
13
+ var LONG_PREFIX = 512;
14
+ var SCOPE_MAX_LENGTH = 255;
15
+ function string(name, length = 255) {
16
+ return column(name, `varchar(${length})`).collate(BINARY);
12
17
  }
13
18
  var storageObject = table("storage_object", {
14
- id: idColumn("id", "varchar(255)").defaultTo$("auto"),
19
+ id: idColumn("id", "varchar(255)").collate(BINARY).defaultTo$("auto"),
15
20
  /** Owner, for example `user:123` or `org:acme`. */
16
- scope: column("scope", "string"),
17
- bucket: column("bucket", "string"),
18
- key: column("key", "string"),
21
+ scope: string("scope", SCOPE_MAX_LENGTH),
22
+ bucket: string("bucket"),
23
+ key: string("key", 1024),
19
24
  /** Named dimah-s3 route that created the object. */
20
- route: column("route", "string"),
21
- /** Logical folder path. `null` is the root. */
22
- folder: column("folder", "string").nullable(),
23
- filename: column("filename", "string"),
24
- contentType: column("content_type", "string").nullable(),
25
+ route: string("route"),
26
+ /** Folder that holds the object. `null` is the root. */
27
+ folderId: string("folder_id").nullable(),
28
+ filename: column("filename", "varchar(255)").collate(TEXT),
29
+ /**
30
+ * `filename` folded for search: lowercase, without accents, with `%`,
31
+ * `_`, and `\` kept literal. Search matches it on every database the
32
+ * same way.
33
+ */
34
+ searchName: string("search_name", SEARCH_NAME_MAX_LENGTH),
35
+ contentType: string("content_type").nullable(),
25
36
  /** Verified size from HeadObject, set on confirm. */
26
- size: byteCount("size"),
37
+ size: column("size", "bigint").nullable(),
27
38
  /** Size the client declared before confirm. Quota counts it while pending. */
28
- declaredSize: byteCount("declared_size"),
29
- eTag: column("e_tag", "string").nullable(),
30
- status: column("status", "string"),
39
+ declaredSize: column("declared_size", "bigint").nullable(),
40
+ eTag: string("e_tag").nullable(),
41
+ status: string("status", 16),
31
42
  /** S3 user metadata of the verified object. */
32
43
  s3Metadata: column("s3_metadata", "json").nullable(),
33
44
  /** App attributes, validated by the plugin's `attributes.schema`. */
34
45
  attributes: column("attributes", "json").nullable(),
35
- acl: column("acl", "string").nullable(),
46
+ acl: string("acl").nullable(),
36
47
  /** Multipart upload ID while the row is pending. */
37
- uploadId: column("upload_id", "string").nullable(),
48
+ uploadId: column("upload_id", "string").collate(BINARY).nullable(),
38
49
  /** Token of the upload ticket that wrote the row. Confirm and purge match it. */
39
- uploadToken: column("upload_token", "string").nullable(),
50
+ uploadToken: string("upload_token", 64).nullable(),
40
51
  /** Confirm deadline of a pending row (the upload ticket's expiry). */
41
52
  expiresAt: column("expires_at", "timestamp").nullable(),
42
53
  confirmedAt: column("confirmed_at", "timestamp").nullable(),
43
54
  createdAt: column("created_at", "timestamp").defaultTo$("now"),
44
55
  updatedAt: column("updated_at", "timestamp").defaultTo$("now"),
45
56
  deletedAt: column("deleted_at", "timestamp").nullable()
46
- }).unique("storage_object_bucket_key_uk", ["bucket", "key"]);
57
+ }).unique("storage_object_bucket_key_uk", ["bucket", "key"], {
58
+ length: { key: LONG_PREFIX }
59
+ }).index("storage_object_scope_folder_idx", [
60
+ "scope",
61
+ "status",
62
+ "folderId",
63
+ "createdAt"
64
+ ]).index("storage_object_scope_updated_idx", ["scope", "status", "updatedAt"]).index("storage_object_scope_filename_idx", ["scope", "status", "filename"]).index("storage_object_scope_size_idx", ["scope", "status", "size"]).index("storage_object_status_expires_idx", ["status", "expiresAt"]);
47
65
  var storageFolder = table("storage_folder", {
48
- id: idColumn("id", "varchar(255)").defaultTo$("auto"),
49
- scope: column("scope", "string"),
50
- /** Full folder path. */
51
- path: column("path", "string"),
52
- /** Path of the containing folder. `null` is the root. */
53
- parent: column("parent", "string").nullable(),
66
+ id: idColumn("id", "varchar(255)").collate(BINARY).defaultTo$("auto"),
67
+ scope: string("scope", SCOPE_MAX_LENGTH),
68
+ /** Id of the containing folder. `""` is the root. */
69
+ parentId: string("parent_id").defaultTo(""),
54
70
  /** Last segment of `path`. */
55
- name: column("name", "string"),
56
- createdAt: column("created_at", "timestamp").defaultTo$("now")
57
- }).unique("storage_folder_scope_path_uk", ["scope", "path"]);
58
- var schemaIndexes = [
59
- {
60
- name: "storage_object_scope_folder_idx",
61
- table: "storage_object",
62
- columns: ["scope", "status", "folder", "created_at"]
63
- },
64
- {
65
- name: "storage_object_scope_updated_idx",
66
- table: "storage_object",
67
- columns: ["scope", "status", "updated_at"]
68
- },
69
- {
70
- name: "storage_object_scope_filename_idx",
71
- table: "storage_object",
72
- columns: ["scope", "status", "filename"]
73
- },
74
- {
75
- name: "storage_object_scope_size_idx",
76
- table: "storage_object",
77
- columns: ["scope", "status", "size"]
78
- },
79
- {
80
- name: "storage_object_status_expires_idx",
81
- table: "storage_object",
82
- columns: ["status", "expires_at"]
83
- },
84
- {
85
- name: "storage_folder_scope_parent_idx",
86
- table: "storage_folder",
87
- columns: ["scope", "parent"]
88
- }
89
- ];
90
- var custom = (sql) => ({ type: "custom", sql });
91
- var PREDECESSOR_VERSION = "0.0.1";
92
- var predecessor = schema({
93
- version: PREDECESSOR_VERSION,
94
- tables: {}
95
- });
71
+ name: string("name"),
72
+ /** `name` folded for search, like `storage_object.search_name`. */
73
+ searchName: string("search_name", SEARCH_NAME_MAX_LENGTH),
74
+ /** Full folder path. */
75
+ path: string("path", 1024),
76
+ createdAt: column("created_at", "timestamp").defaultTo$("now"),
77
+ updatedAt: column("updated_at", "timestamp").defaultTo$("now")
78
+ }).unique("storage_folder_scope_path_uk", ["scope", "path"], {
79
+ length: { path: LONG_PREFIX }
80
+ }).unique("storage_folder_scope_parent_name_uk", ["scope", "parentId", "name"]);
96
81
  var dbSchema = schema({
97
- version: "2.0.0",
82
+ version: "2.2.0",
98
83
  tables: {
99
84
  storageObject,
100
85
  storageFolder
101
- },
102
- async up({ auto }) {
103
- const indexes = schemaIndexes.map((index) => {
104
- const columns = index.columns.map((name) => `"${name}"`).join(", ");
105
- return custom(
106
- `CREATE INDEX IF NOT EXISTS "${index.name}" ON "${index.table}" (${columns})`
107
- );
108
- });
109
- return [...await auto(), ...indexes];
110
86
  }
111
87
  });
112
88
 
113
89
  // src/fuma-db.ts
114
90
  var DimahS3DB = fumadb({
115
91
  namespace: "dimah_s3",
116
- schemas: [predecessor, dbSchema]
92
+ schemas: [dbSchema]
117
93
  });
118
94
  var DB_SCHEMA_VERSION = dbSchema.version;
119
- var FOLDER_PATH_MAX_LENGTH = 1024;
95
+ var FOLDER_PATH_MAX_BYTES = 1024;
120
96
  var FOLDER_NAME_MAX_LENGTH = 255;
121
97
  var FOLDER_MAX_DEPTH = 32;
122
98
  var INVALID_CHARACTER = /[\p{Cc}\p{Cs}]/u;
99
+ var utf8 = new TextEncoder();
123
100
  function characterCount(value) {
124
101
  return Array.from(value).length;
125
102
  }
126
- function isValidName(name) {
103
+ function isFolderName(name) {
127
104
  const length = characterCount(name);
128
- return length >= 1 && length <= FOLDER_NAME_MAX_LENGTH && name !== "." && name !== ".." && !INVALID_CHARACTER.test(name);
105
+ return length >= 1 && length <= FOLDER_NAME_MAX_LENGTH && name !== "." && name !== ".." && !name.includes("/") && !INVALID_CHARACTER.test(name);
129
106
  }
130
107
  function normalizeFolderPath(path) {
131
108
  if (!path.isWellFormed()) return null;
132
109
  const normalized = path.normalize("NFC");
133
- if (characterCount(normalized) > FOLDER_PATH_MAX_LENGTH) return null;
110
+ if (utf8.encode(normalized).byteLength > FOLDER_PATH_MAX_BYTES) return null;
134
111
  const names = normalized.split("/");
135
112
  if (names.length > FOLDER_MAX_DEPTH) return null;
136
- return names.every(isValidName) ? normalized : null;
137
- }
138
- function parseFolder(value) {
139
- if (value === "") return null;
140
- const path = normalizeFolderPath(value);
141
- if (path === null) throw s3Error("FOLDER_INVALID");
142
- return path;
113
+ return names.every(isFolderName) ? normalized : null;
143
114
  }
144
- function parentFolderPath(path) {
145
- const index = path.lastIndexOf("/");
146
- return index === -1 ? null : path.slice(0, index);
115
+ function childFolderPath(parent, name) {
116
+ if (!isFolderName(name)) return null;
117
+ return normalizeFolderPath(joinFolderPath(parent, name));
147
118
  }
148
- function folderName(path) {
149
- return path.slice(path.lastIndexOf("/") + 1);
119
+ function joinFolderPath(parent, name) {
120
+ return parent === null ? name : `${parent}/${name}`;
150
121
  }
151
122
  function folderAncestors(path) {
152
123
  const segments = path.split("/");
@@ -159,8 +130,9 @@ var DEFAULT_LIST_SORT = {
159
130
  var decoder = new TextDecoder();
160
131
  function fingerprint(filters) {
161
132
  const text = JSON.stringify([
162
- filters.folder === void 0,
163
- filters.folder ?? null,
133
+ filters.folderId === void 0,
134
+ filters.folderId ?? null,
135
+ filters.recursive,
164
136
  filters.search ?? null,
165
137
  filters.status,
166
138
  filters.route ?? null,
@@ -223,7 +195,7 @@ function mapStorageObjectRow(row) {
223
195
  bucket: row.bucket,
224
196
  key: row.key,
225
197
  route: row.route,
226
- folder: row.folder,
198
+ folderId: row.folderId,
227
199
  filename: row.filename,
228
200
  contentType: row.contentType,
229
201
  size: toNumber(row.size),
@@ -242,6 +214,19 @@ function mapStorageObjectRow(row) {
242
214
  deletedAt: row.deletedAt
243
215
  };
244
216
  }
217
+ var LIKE_LITERALS = {
218
+ "%": "\uE000",
219
+ _: "\uE001",
220
+ "\\": "\uE002"
221
+ };
222
+ function toSearchName(value) {
223
+ const folded = normalizeSearchText(value).replaceAll(
224
+ /[%_\\]/g,
225
+ (char) => LIKE_LITERALS[char] ?? char
226
+ );
227
+ const characters = Array.from(folded);
228
+ return characters.length > SEARCH_NAME_MAX_LENGTH ? characters.slice(0, SEARCH_NAME_MAX_LENGTH).join("") : folded;
229
+ }
245
230
 
246
231
  // src/store/object-store.ts
247
232
  var DEFAULT_LIST_LIMIT = 50;
@@ -298,15 +283,17 @@ function claimDeadline() {
298
283
  );
299
284
  return new Date(lastClaimDeadline);
300
285
  }
301
- function filterConditions(b, filter, now) {
286
+ function filterConditions(b, filter, folders, now) {
302
287
  const status = filter.status ?? "active";
303
288
  const parts = [
304
289
  b("scope", "=", filter.scope),
305
290
  status === "pending" ? b.and(b("status", "=", "pending"), b("expiresAt", ">=", now)) : b("status", "=", status)
306
291
  ];
307
- if (filter.folder === null) parts.push(b.isNull("folder"));
308
- else if (filter.folder !== void 0) {
309
- parts.push(b("folder", "=", filter.folder));
292
+ if (folders === null) parts.push(b.isNull("folderId"));
293
+ else if (folders !== void 0) {
294
+ parts.push(
295
+ folders.length === 1 ? b("folderId", "=", folders[0] ?? "") : b("folderId", "in", [...folders])
296
+ );
310
297
  }
311
298
  if (filter.route) parts.push(b("route", "=", filter.route));
312
299
  if (filter.contentType?.endsWith("/*")) {
@@ -315,11 +302,24 @@ function filterConditions(b, filter, now) {
315
302
  } else if (filter.contentType) {
316
303
  parts.push(b("contentType", "=", filter.contentType));
317
304
  }
318
- if (filter.search) parts.push(b("filename", "contains", filter.search));
305
+ const needle = filter.search ? toSearchName(filter.search) : "";
306
+ if (needle) parts.push(b("searchName", "contains", needle));
319
307
  return parts;
320
308
  }
321
- function createObjectStore(getOrm) {
309
+ function toByteCount(value) {
310
+ return value == null ? null : BigInt(value);
311
+ }
312
+ function toColumnValue(value) {
313
+ return typeof value === "number" ? BigInt(value) : value;
314
+ }
315
+ function createObjectStore(getOrm, subtreeIds) {
322
316
  const map = mapStorageObjectRow;
317
+ const folderSet = async (filter) => {
318
+ const { folderId } = filter;
319
+ if (folderId == null) return filter.recursive ? void 0 : folderId;
320
+ if (!filter.recursive) return [folderId];
321
+ return [folderId, ...await subtreeIds(filter.scope, folderId)];
322
+ };
323
323
  const find = async (ref) => {
324
324
  const orm = await getOrm();
325
325
  const row = await orm.findFirst("storageObject", {
@@ -345,7 +345,8 @@ function createObjectStore(getOrm) {
345
345
  const after = direction === "desc" ? "<" : ">";
346
346
  const nullable = field === "size";
347
347
  const filters = {
348
- folder: input.folder,
348
+ folderId: input.folderId,
349
+ recursive: input.recursive === true && input.folderId !== void 0,
349
350
  search: input.search || void 0,
350
351
  status: input.status ?? "active",
351
352
  route: input.route || void 0,
@@ -353,8 +354,9 @@ function createObjectStore(getOrm) {
353
354
  sort
354
355
  };
355
356
  const cursor = input.cursor ? decodeListCursor(input.cursor, filters) : null;
357
+ const folders = await folderSet(input);
356
358
  const where = (segment) => (b) => {
357
- const parts = filterConditions(b, input, now);
359
+ const parts = filterConditions(b, input, folders, now);
358
360
  const position = segment.after;
359
361
  if (segment.nulls) {
360
362
  parts.push(b.isNull(field));
@@ -362,13 +364,11 @@ function createObjectStore(getOrm) {
362
364
  } else {
363
365
  if (nullable) parts.push(b.isNotNull(field));
364
366
  if (position && position.value !== null) {
367
+ const value = toColumnValue(position.value);
365
368
  parts.push(
366
369
  b.or(
367
- b(field, after, position.value),
368
- b.and(
369
- b(field, "=", position.value),
370
- b("id", after, position.id)
371
- )
370
+ b(field, after, value),
371
+ b.and(b(field, "=", value), b("id", after, position.id))
372
372
  )
373
373
  );
374
374
  }
@@ -409,8 +409,9 @@ function createObjectStore(getOrm) {
409
409
  async count(filter) {
410
410
  const orm = await getOrm();
411
411
  const now = /* @__PURE__ */ new Date();
412
+ const folders = await folderSet(filter);
412
413
  return orm.count("storageObject", {
413
- where: (b) => b.and(...filterConditions(b, filter, now))
414
+ where: (b) => b.and(...filterConditions(b, filter, folders, now))
414
415
  });
415
416
  },
416
417
  async getUsage(scope, options = {}) {
@@ -453,7 +454,7 @@ function createObjectStore(getOrm) {
453
454
  const upload = {
454
455
  uploadId: input.uploadId ?? null,
455
456
  uploadToken: input.uploadToken,
456
- declaredSize: input.declaredSize ?? null,
457
+ declaredSize: toByteCount(input.declaredSize),
457
458
  expiresAt: input.expiresAt
458
459
  };
459
460
  const now = /* @__PURE__ */ new Date();
@@ -462,8 +463,9 @@ function createObjectStore(getOrm) {
462
463
  ...ref,
463
464
  scope: input.scope,
464
465
  route: input.route,
465
- folder: input.folder,
466
+ folderId: input.folderId,
466
467
  filename: input.filename,
468
+ searchName: toSearchName(input.filename),
467
469
  contentType: input.contentType ?? null,
468
470
  size: null,
469
471
  eTag: null,
@@ -480,7 +482,7 @@ function createObjectStore(getOrm) {
480
482
  try {
481
483
  await orm.create("storageObject", fresh);
482
484
  } catch (error) {
483
- if (await find(ref)) throw s3Error("CONFLICT");
485
+ if (error instanceof UniqueConstraintError) throw s3Error("CONFLICT");
484
486
  throw error;
485
487
  }
486
488
  };
@@ -515,13 +517,16 @@ function createObjectStore(getOrm) {
515
517
  where: (b) => b.and(byUpload(b, input), uploading(b)),
516
518
  set: {
517
519
  status: "active",
518
- size: input.size,
520
+ size: BigInt(input.size),
519
521
  declaredSize: null,
520
522
  eTag: input.eTag ?? null,
521
523
  ...input.contentType !== void 0 && {
522
524
  contentType: input.contentType
523
525
  },
524
- ...input.filename !== void 0 && { filename: input.filename },
526
+ ...input.filename !== void 0 && {
527
+ filename: input.filename,
528
+ searchName: toSearchName(input.filename)
529
+ },
525
530
  ...input.s3Metadata !== void 0 && {
526
531
  s3Metadata: input.s3Metadata
527
532
  },
@@ -548,8 +553,11 @@ function createObjectStore(getOrm) {
548
553
  ref.scope === void 0 || b("scope", "=", ref.scope)
549
554
  ),
550
555
  set: {
551
- ...input.filename !== void 0 && { filename: input.filename },
552
- ...input.folder !== void 0 && { folder: input.folder },
556
+ ...input.filename !== void 0 && {
557
+ filename: input.filename,
558
+ searchName: toSearchName(input.filename)
559
+ },
560
+ ...input.folderId !== void 0 && { folderId: input.folderId },
553
561
  ...input.attributes !== void 0 && {
554
562
  attributes: input.attributes
555
563
  },
@@ -658,72 +666,154 @@ function createObjectStore(getOrm) {
658
666
 
659
667
  // src/store/folder-store.ts
660
668
  var DEFAULT_FOLDER_CHILDREN_LIMIT = 1e3;
661
- function insertFolder(orm, scope, path) {
662
- return orm.create("storageFolder", {
663
- scope,
664
- path,
665
- parent: parentFolderPath(path),
666
- name: folderName(path),
667
- createdAt: /* @__PURE__ */ new Date()
668
- });
669
+ var DEFAULT_FOLDER_DESCENDANTS_LIMIT = 1e3;
670
+ var FOLDER_SUBTREE_LIMIT = 1e4;
671
+ var IN_BATCH = 500;
672
+ function storedParent(parentId) {
673
+ return parentId ?? "";
674
+ }
675
+ function readParent(parentId) {
676
+ return parentId === "" ? null : parentId;
677
+ }
678
+ function batches(values, size) {
679
+ const runs = [];
680
+ for (let index = 0; index < values.length; index += size) {
681
+ runs.push(values.slice(index, index + size));
682
+ }
683
+ return runs;
684
+ }
685
+ function byNameThenPath(a, b) {
686
+ return a.name.localeCompare(b.name, void 0, {
687
+ numeric: true,
688
+ sensitivity: "base"
689
+ }) || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
690
+ }
691
+ function mapFolder(row) {
692
+ return {
693
+ id: row.id,
694
+ scope: row.scope,
695
+ parentId: readParent(row.parentId),
696
+ name: row.name,
697
+ path: row.path,
698
+ createdAt: row.createdAt,
699
+ updatedAt: row.updatedAt
700
+ };
669
701
  }
670
702
  function createFolderStore(getOrm) {
671
- const find = async (scope, path) => {
703
+ const find = async (scope, id) => {
672
704
  const orm = await getOrm();
673
- return orm.findFirst("storageFolder", {
674
- where: (b) => b.and(b("scope", "=", scope), b("path", "=", path))
705
+ const row = await orm.findFirst("storageFolder", {
706
+ where: (b) => b.and(b("scope", "=", scope), b("id", "=", id))
675
707
  });
708
+ return row ? mapFolder(row) : null;
676
709
  };
677
- const insertMissing = async (scope, path) => {
678
- const existing = await find(scope, path);
679
- if (existing) return existing;
680
- try {
681
- return await insertFolder(await getOrm(), scope, path);
682
- } catch (error) {
683
- const raced = await find(scope, path);
684
- if (raced) return raced;
685
- throw error;
686
- }
710
+ const insertFolder = async (orm, folder) => {
711
+ const now = /* @__PURE__ */ new Date();
712
+ const row = await orm.create("storageFolder", {
713
+ ...folder.id !== void 0 && { id: folder.id },
714
+ scope: folder.scope,
715
+ parentId: storedParent(folder.parentId),
716
+ name: folder.name,
717
+ searchName: toSearchName(folder.name),
718
+ path: folder.path,
719
+ createdAt: folder.createdAt ?? now,
720
+ updatedAt: folder.updatedAt ?? now
721
+ });
722
+ return mapFolder(row);
687
723
  };
688
- const ensure = async (scope, path) => {
689
- if (path === null) return;
690
- const ancestors = folderAncestors(path);
691
- const orm = await getOrm();
692
- const present = new Set(
693
- (await orm.findMany("storageFolder", {
694
- select: ["path"],
695
- where: (b) => b.and(b("scope", "=", scope), b("path", "in", ancestors))
696
- })).map((folder) => folder.path)
697
- );
698
- for (const ancestor of ancestors) {
699
- if (!present.has(ancestor)) await insertMissing(scope, ancestor);
724
+ const destination = async (scope, parentId, folderId) => {
725
+ if (parentId === null) return null;
726
+ if (parentId === folderId) throw s3Error("FOLDER_INVALID");
727
+ const parent = await find(scope, parentId);
728
+ if (!parent) throw s3Error("FOLDER_NOT_FOUND");
729
+ if (folderId !== void 0) {
730
+ let cursor = parent;
731
+ const seen = /* @__PURE__ */ new Set();
732
+ while (cursor && !seen.has(cursor.id)) {
733
+ if (cursor.id === folderId) throw s3Error("FOLDER_INVALID");
734
+ seen.add(cursor.id);
735
+ cursor = cursor.parentId ? await find(scope, cursor.parentId) : null;
736
+ }
700
737
  }
738
+ return parent;
701
739
  };
702
- const countContents = async (scope, path) => {
740
+ const countContents = async (scope, id) => {
703
741
  const orm = await getOrm();
704
742
  const now = /* @__PURE__ */ new Date();
705
743
  const [folders, objects] = await Promise.all([
706
744
  orm.count("storageFolder", {
707
- where: (b) => b.and(b("scope", "=", scope), b("parent", "=", path))
745
+ where: (b) => b.and(b("scope", "=", scope), b("parentId", "=", id))
708
746
  }),
709
747
  orm.count("storageObject", {
710
748
  where: (b) => b.and(
711
749
  b("scope", "=", scope),
712
- b("folder", "=", path),
750
+ b("folderId", "=", id),
713
751
  liveObject(b, now)
714
752
  )
715
753
  })
716
754
  ]);
717
755
  return folders + objects;
718
756
  };
757
+ const subtree = async (scope, id, limit = Infinity) => {
758
+ const orm = await getOrm();
759
+ const found = [];
760
+ const seen = /* @__PURE__ */ new Set([id]);
761
+ let level = [id];
762
+ for (let depth = 0; depth < FOLDER_MAX_DEPTH && level.length > 0; depth++) {
763
+ const next = [];
764
+ for (const parents of batches(level, IN_BATCH)) {
765
+ const rows = await orm.findMany("storageFolder", {
766
+ where: (b) => b.and(b("scope", "=", scope), b("parentId", "in", parents)),
767
+ orderBy: [["id", "asc"]]
768
+ });
769
+ for (const row of rows) {
770
+ if (seen.has(row.id)) continue;
771
+ seen.add(row.id);
772
+ found.push(mapFolder(row));
773
+ next.push(row.id);
774
+ if (found.length >= limit) return found;
775
+ }
776
+ }
777
+ level = next;
778
+ }
779
+ return found;
780
+ };
781
+ const walks = /* @__PURE__ */ new Map();
782
+ const sharedSubtree = (scope, id) => {
783
+ const key = JSON.stringify([scope, id]);
784
+ let walk = walks.get(key);
785
+ if (!walk) {
786
+ walk = subtree(scope, id, FOLDER_SUBTREE_LIMIT).finally(() => {
787
+ walks.delete(key);
788
+ });
789
+ walks.set(key, walk);
790
+ }
791
+ return walk;
792
+ };
793
+ const retain = async (folder) => {
794
+ if (await find(folder.scope, folder.id)) return;
795
+ const orm = await getOrm();
796
+ try {
797
+ await insertFolder(orm, folder);
798
+ } catch (error) {
799
+ if (error instanceof UniqueConstraintError && await find(folder.scope, folder.id)) {
800
+ return;
801
+ }
802
+ throw error;
803
+ }
804
+ };
719
805
  return {
720
806
  find,
721
- async children(scope, parent, options = {}) {
807
+ async subtreeIds(scope, id) {
808
+ const below = await sharedSubtree(scope, id);
809
+ return below.map((folder) => folder.id);
810
+ },
811
+ async children(scope, parentId, options = {}) {
722
812
  const orm = await getOrm();
723
- return orm.findMany("storageFolder", {
813
+ const rows = await orm.findMany("storageFolder", {
724
814
  where: (b) => b.and(
725
815
  b("scope", "=", scope),
726
- parent === null ? b.isNull("parent") : b("parent", "=", parent)
816
+ b("parentId", "=", storedParent(parentId))
727
817
  ),
728
818
  orderBy: [
729
819
  ["name", "asc"],
@@ -731,33 +821,160 @@ function createFolderStore(getOrm) {
731
821
  ],
732
822
  limit: options.limit ?? DEFAULT_FOLDER_CHILDREN_LIMIT
733
823
  });
824
+ return rows.map(mapFolder);
825
+ },
826
+ async trail(scope, id) {
827
+ const chain = [];
828
+ const seen = /* @__PURE__ */ new Set();
829
+ let current = await find(scope, id);
830
+ if (!current) throw s3Error("FOLDER_NOT_FOUND");
831
+ while (current && !seen.has(current.id)) {
832
+ seen.add(current.id);
833
+ chain.push(current);
834
+ if (!current.parentId || chain.length > FOLDER_MAX_DEPTH) break;
835
+ current = await find(scope, current.parentId);
836
+ }
837
+ return chain.reverse();
734
838
  },
735
- ensure,
736
- async create(scope, path) {
737
- if (await find(scope, path)) throw s3Error("FOLDER_EXISTS");
738
- let folder;
839
+ async descendants(scope, parentId, options = {}) {
840
+ const limit = options.limit ?? DEFAULT_FOLDER_DESCENDANTS_LIMIT;
841
+ const needle = options.search ? toSearchName(options.search) : "";
842
+ let folders;
843
+ if (parentId === null) {
844
+ const orm = await getOrm();
845
+ const rows = await orm.findMany("storageFolder", {
846
+ where: (b) => b.and(
847
+ b("scope", "=", scope),
848
+ needle === "" || b("searchName", "contains", needle)
849
+ ),
850
+ orderBy: [["path", "asc"]],
851
+ limit: FOLDER_SUBTREE_LIMIT
852
+ });
853
+ folders = rows.map(mapFolder);
854
+ } else {
855
+ const [parent, below] = await Promise.all([
856
+ find(scope, parentId),
857
+ sharedSubtree(scope, parentId)
858
+ ]);
859
+ if (!parent) throw s3Error("FOLDER_NOT_FOUND");
860
+ folders = below.filter(
861
+ (folder) => needle === "" || toSearchName(folder.name).includes(needle)
862
+ );
863
+ }
864
+ return folders.sort(byNameThenPath).slice(0, limit);
865
+ },
866
+ async ancestors(scope, ids) {
867
+ if (ids.length === 0) return [];
868
+ const orm = await getOrm();
869
+ const byPath = /* @__PURE__ */ new Map();
870
+ for (const run of batches([...new Set(ids)], IN_BATCH)) {
871
+ const rows = await orm.findMany("storageFolder", {
872
+ where: (b) => b.and(b("scope", "=", scope), b("id", "in", run))
873
+ });
874
+ for (const row of rows) byPath.set(row.path, mapFolder(row));
875
+ }
876
+ const missing = /* @__PURE__ */ new Set();
877
+ for (const path of byPath.keys()) {
878
+ for (const above of folderAncestors(path)) {
879
+ if (!byPath.has(above)) missing.add(above);
880
+ }
881
+ }
882
+ for (const run of batches([...missing], IN_BATCH)) {
883
+ const rows = await orm.findMany("storageFolder", {
884
+ where: (b) => b.and(b("scope", "=", scope), b("path", "in", run))
885
+ });
886
+ for (const row of rows) byPath.set(row.path, mapFolder(row));
887
+ }
888
+ return [...byPath.values()].sort(
889
+ (a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0
890
+ );
891
+ },
892
+ async create(scope, input) {
893
+ const parent = await destination(scope, input.parentId);
894
+ const path = childFolderPath(parent?.path ?? null, input.name);
895
+ if (path === null) throw s3Error("FOLDER_INVALID");
896
+ const name = path.slice(path.lastIndexOf("/") + 1);
897
+ const orm = await getOrm();
739
898
  try {
740
- folder = await insertFolder(await getOrm(), scope, path);
899
+ return await insertFolder(orm, {
900
+ scope,
901
+ parentId: input.parentId,
902
+ name,
903
+ path
904
+ });
741
905
  } catch (error) {
742
- if (await find(scope, path)) throw s3Error("FOLDER_EXISTS");
906
+ if (error instanceof UniqueConstraintError) {
907
+ throw s3Error("FOLDER_EXISTS");
908
+ }
743
909
  throw error;
744
910
  }
745
- await ensure(scope, parentFolderPath(path));
746
- return folder;
747
911
  },
748
- async delete(scope, path) {
749
- if (await countContents(scope, path) > 0) {
912
+ async update(scope, id, input) {
913
+ const folder = await find(scope, id);
914
+ if (!folder) throw s3Error("FOLDER_NOT_FOUND");
915
+ const name = input.name ?? folder.name;
916
+ const parentId = input.parentId === void 0 ? folder.parentId : input.parentId;
917
+ if (name === folder.name && parentId === folder.parentId) return folder;
918
+ const parent = await destination(scope, parentId, id);
919
+ const path = childFolderPath(parent?.path ?? null, name);
920
+ if (path === null) throw s3Error("FOLDER_INVALID");
921
+ const storedName = path.slice(path.lastIndexOf("/") + 1);
922
+ const below = await subtree(scope, id);
923
+ const prefix = folder.path;
924
+ const rewritten = below.map((child) => ({
925
+ id: child.id,
926
+ path: `${path}${child.path.slice(prefix.length)}`
927
+ }));
928
+ for (const next of [path, ...rewritten.map((child) => child.path)]) {
929
+ if (normalizeFolderPath(next) !== next) throw s3Error("FOLDER_INVALID");
930
+ }
931
+ const orm = await getOrm();
932
+ const now = /* @__PURE__ */ new Date();
933
+ await orm.transaction(async (tx) => {
934
+ try {
935
+ await tx.updateMany("storageFolder", {
936
+ where: (b) => b.and(b("scope", "=", scope), b("id", "=", id)),
937
+ set: {
938
+ name: storedName,
939
+ searchName: toSearchName(storedName),
940
+ parentId: storedParent(parentId),
941
+ path,
942
+ updatedAt: now
943
+ }
944
+ });
945
+ } catch (error) {
946
+ if (error instanceof UniqueConstraintError) {
947
+ throw s3Error("FOLDER_EXISTS");
948
+ }
949
+ throw error;
950
+ }
951
+ for (const child of rewritten) {
952
+ await tx.updateMany("storageFolder", {
953
+ where: (b) => b.and(b("scope", "=", scope), b("id", "=", child.id)),
954
+ set: { path: child.path, updatedAt: now }
955
+ });
956
+ }
957
+ });
958
+ const updated = await find(scope, id);
959
+ if (!updated) throw s3Error("FOLDER_NOT_FOUND");
960
+ return updated;
961
+ },
962
+ async delete(scope, id) {
963
+ const folder = await find(scope, id);
964
+ if (!folder) return;
965
+ if (await countContents(scope, id) > 0) {
750
966
  throw s3Error("FOLDER_NOT_EMPTY");
751
967
  }
752
968
  const orm = await getOrm();
753
969
  await orm.deleteMany("storageFolder", {
754
- where: (b) => b.and(b("scope", "=", scope), b("path", "=", path))
970
+ where: (b) => b.and(b("scope", "=", scope), b("id", "=", id))
755
971
  });
756
- if (await countContents(scope, path) > 0) {
757
- await insertMissing(scope, path);
972
+ if (await countContents(scope, id) > 0) {
973
+ await retain(folder);
758
974
  throw s3Error("FOLDER_NOT_EMPTY");
759
975
  }
760
- }
976
+ },
977
+ retain
761
978
  };
762
979
  }
763
980
 
@@ -807,9 +1024,10 @@ function createDbStore(client) {
807
1024
  await checkSchema();
808
1025
  return client.orm(DB_SCHEMA_VERSION);
809
1026
  };
1027
+ const folders = createFolderStore(getOrm);
810
1028
  return {
811
- objects: createObjectStore(getOrm),
812
- folders: createFolderStore(getOrm),
1029
+ objects: createObjectStore(getOrm, folders.subtreeIds),
1030
+ folders,
813
1031
  checkSchema
814
1032
  };
815
1033
  }
@@ -839,6 +1057,14 @@ function queryInt(schema2) {
839
1057
  }
840
1058
  );
841
1059
  }
1060
+ var queryBoolean = z.codec(
1061
+ z.union([z.enum(["true", "false"]), z.boolean()]),
1062
+ z.boolean(),
1063
+ {
1064
+ decode: (value) => value === true || value === "true",
1065
+ encode: (value) => value
1066
+ }
1067
+ );
842
1068
  var dbListSortSchema = z.object({
843
1069
  field: z.enum(["createdAt", "updatedAt", "size", "filename"]),
844
1070
  direction: z.enum(["asc", "desc"])
@@ -865,12 +1091,13 @@ var dbListSortQuerySchema = z.codec(
865
1091
  }
866
1092
  );
867
1093
  var dbListQuerySchema = z.strictObject({
868
- folder: z.string().optional(),
1094
+ folderId: z.string().optional(),
1095
+ recursive: queryBoolean.optional(),
869
1096
  route: routeNameSchema.optional(),
870
1097
  // Rows that purge has claimed stay internal, as on `GET /db/object`.
871
1098
  status: z.enum(["pending", "active", "deleted"]).optional(),
872
1099
  contentType: optionalContentTypeSchema,
873
- /** Text the filename contains. */
1100
+ /** Text the filename contains, ignoring case and accents. */
874
1101
  search: optionalTrimmedString.pipe(
875
1102
  z.string().max(MAX_SEARCH_LENGTH).optional()
876
1103
  ),
@@ -890,12 +1117,21 @@ var dbUpdateObjectBodySchema = z.strictObject({
890
1117
  key: objectKeySchema,
891
1118
  bucket: trimmedString.optional(),
892
1119
  filename: fileNameSchema.optional(),
893
- folder: z.string().nullable().optional(),
1120
+ folderId: z.string().nullable().optional(),
894
1121
  /** `null` clears the attributes. */
895
1122
  attributes: z.record(z.string(), z.unknown()).nullable().optional()
896
1123
  });
897
- var dbFolderInputSchema = z.strictObject({
898
- path: z.string()
1124
+ var dbCreateFolderBodySchema = z.strictObject({
1125
+ parentId: z.string().nullable().optional(),
1126
+ name: z.string()
1127
+ });
1128
+ var dbUpdateFolderBodySchema = z.strictObject({
1129
+ id: trimmedString,
1130
+ name: z.string().optional(),
1131
+ parentId: z.string().nullable().optional()
1132
+ });
1133
+ var dbDeleteFolderQuerySchema = z.strictObject({
1134
+ id: trimmedString
899
1135
  });
900
1136
 
901
1137
  // src/plugin/to-db-client-object.ts
@@ -906,7 +1142,7 @@ function toDbClientObject(object2, toClient) {
906
1142
  bucket: object2.bucket,
907
1143
  key: object2.key,
908
1144
  route: object2.route,
909
- folder: object2.folder,
1145
+ folderId: object2.folderId,
910
1146
  filename: object2.filename,
911
1147
  contentType: object2.contentType,
912
1148
  size: object2.size,
@@ -924,16 +1160,18 @@ function toDbClientObject(object2, toClient) {
924
1160
  }
925
1161
  function toDbClientFolder(folder) {
926
1162
  return {
927
- path: folder.path,
1163
+ id: folder.id,
928
1164
  name: folder.name,
929
- parent: folder.parent,
930
- createdAt: folder.createdAt.toISOString()
1165
+ parentId: folder.parentId,
1166
+ path: folder.path,
1167
+ createdAt: folder.createdAt.toISOString(),
1168
+ updatedAt: folder.updatedAt.toISOString()
931
1169
  };
932
1170
  }
933
1171
 
934
1172
  // src/plugin/create-database-endpoints.ts
935
1173
  var DEFAULT_ATTRIBUTES_MAX_BYTES = 16384;
936
- var utf8 = new TextEncoder();
1174
+ var utf82 = new TextEncoder();
937
1175
  function resolveBucket(config, bucket, field) {
938
1176
  const buckets = /* @__PURE__ */ new Set();
939
1177
  for (const route of Object.values(config.routes)) {
@@ -956,16 +1194,18 @@ function resolveBucket(config, bucket, field) {
956
1194
  }
957
1195
  function matchingFolders(children, search) {
958
1196
  if (!search) return children;
959
- const text = search.toLowerCase();
960
- return children.filter((child) => child.name.toLowerCase().includes(text));
1197
+ return children.filter((child) => matchesSearchText(child.name, search));
961
1198
  }
962
- function parseFolderPath(value) {
963
- const path = parseFolder(value);
964
- if (path === null) throw s3Error("FOLDER_INVALID");
965
- return path;
1199
+ function wireFolderId(value) {
1200
+ if (value === void 0) return void 0;
1201
+ return value === "" || value === null ? null : value;
1202
+ }
1203
+ function folderTarget(folder) {
1204
+ if (folder === null) return { folder: null, folderId: null };
1205
+ return { folder: folder.path, folderId: folder.id };
966
1206
  }
967
1207
  function createDatabaseEndpoints(options) {
968
- const { access, quota, toClientObject } = options;
1208
+ const { access, quota, resolveScope, toClientObject } = options;
969
1209
  const { objects, folders } = options.store;
970
1210
  const parseAttributes = async (value) => {
971
1211
  const { attributes } = options;
@@ -981,7 +1221,7 @@ function createDatabaseEndpoints(options) {
981
1221
  });
982
1222
  }
983
1223
  const maxBytes = attributes.maxBytes ?? DEFAULT_ATTRIBUTES_MAX_BYTES;
984
- const size = utf8.encode(JSON.stringify(result.value)).byteLength;
1224
+ const size = utf82.encode(JSON.stringify(result.value)).byteLength;
985
1225
  if (size > maxBytes) {
986
1226
  throw s3Error("VALIDATION_ERROR", {
987
1227
  issue: `[body.attributes] Exceeds ${maxBytes} bytes`
@@ -989,43 +1229,80 @@ function createDatabaseEndpoints(options) {
989
1229
  }
990
1230
  return result.value;
991
1231
  };
1232
+ const openFolder = async (scope, wire) => {
1233
+ const folderId = wireFolderId(wire);
1234
+ if (folderId === void 0) return void 0;
1235
+ if (folderId === null) return null;
1236
+ const folder = await folders.find(scope, folderId);
1237
+ if (!folder) throw s3Error("FOLDER_NOT_FOUND");
1238
+ return folder;
1239
+ };
992
1240
  return {
993
- /** One page of the caller's objects. `folder` omitted lists every folder. */
1241
+ /** One page of the caller's objects. `folderId` omitted lists every folder. */
994
1242
  objects: createS3Endpoint(
995
1243
  pluginPath("db", "objects"),
996
1244
  { method: "GET", query: dbListQuerySchema },
997
1245
  async (ctx) => {
998
- const { folder: wireFolder, ...filters } = ctx.query;
999
- const folder = wireFolder === void 0 ? void 0 : parseFolder(wireFolder);
1246
+ const {
1247
+ folderId: wireFolder,
1248
+ recursive: wantsSubtree,
1249
+ ...filters
1250
+ } = ctx.query;
1251
+ const peeked = await resolveScope(ctx.context, {
1252
+ operation: "list",
1253
+ route: filters.route
1254
+ });
1255
+ const opened = await openFolder(peeked.scope, wireFolder);
1256
+ const recursive = wantsSubtree === true && opened !== void 0;
1000
1257
  const scope = await access.scope(ctx.context, {
1001
1258
  operation: "list",
1002
1259
  route: filters.route,
1003
- ...folder !== void 0 && { folder }
1004
- });
1005
- const page = await objects.list({
1006
- ...filters,
1007
- scope: scope.scope,
1008
- folder
1260
+ ...opened !== void 0 && folderTarget(opened),
1261
+ ...recursive && { recursive }
1009
1262
  });
1263
+ const folderId = opened === void 0 ? void 0 : opened?.id ?? null;
1264
+ const filter = { ...filters, scope: scope.scope, folderId, recursive };
1265
+ const firstPage = () => Promise.all([
1266
+ objects.getUsage(scope.scope),
1267
+ quota.limits(scope),
1268
+ opened === void 0 ? void 0 : recursive ? folders.descendants(scope.scope, folderId ?? null, {
1269
+ search: filters.search
1270
+ }) : folders.children(scope.scope, folderId ?? null).then(
1271
+ (children) => matchingFolders(children, filters.search)
1272
+ ),
1273
+ opened === void 0 ? void 0 : opened === null ? [] : folders.trail(scope.scope, opened.id),
1274
+ filters.search ? objects.count(filter) : void 0
1275
+ ]);
1276
+ const early = filters.cursor ? null : firstPage();
1277
+ early?.catch(() => void 0);
1278
+ const page = await objects.list(filter);
1010
1279
  const response = {
1011
1280
  objects: page.objects.map((object2) => toClientObject(object2)),
1012
1281
  nextCursor: page.nextCursor
1013
1282
  };
1014
- if (!page.firstPage) return response;
1015
- const [usage, limits, children] = await Promise.all([
1016
- objects.getUsage(scope.scope),
1017
- quota.limits(scope),
1018
- folder === void 0 ? void 0 : folders.children(scope.scope, folder)
1019
- ]);
1283
+ const located = page.objects.flatMap(
1284
+ (object2) => object2.folderId === null ? [] : [object2.folderId]
1285
+ );
1286
+ if (!page.firstPage) {
1287
+ if (!recursive) return response;
1288
+ const locations2 = await folders.ancestors(scope.scope, located);
1289
+ return { ...response, locations: locations2.map(toDbClientFolder) };
1290
+ }
1291
+ const [usage, limits, listed, trail, total] = await (early ?? firstPage());
1292
+ const locations = recursive ? await folders.ancestors(scope.scope, [
1293
+ ...located,
1294
+ ...(listed ?? []).flatMap(
1295
+ (folder) => folder.parentId === null ? [] : [folder.parentId]
1296
+ )
1297
+ ]) : void 0;
1020
1298
  return {
1021
1299
  ...response,
1022
1300
  usage,
1023
1301
  limits,
1024
- ...children && {
1025
- folders: matchingFolders(children, filters.search).map(
1026
- toDbClientFolder
1027
- )
1028
- }
1302
+ ...listed && { folders: listed.map(toDbClientFolder) },
1303
+ ...trail && { trail: trail.map(toDbClientFolder) },
1304
+ ...locations && { locations: locations.map(toDbClientFolder) },
1305
+ ...total !== void 0 && { total }
1029
1306
  };
1030
1307
  }
1031
1308
  ),
@@ -1051,8 +1328,7 @@ function createDatabaseEndpoints(options) {
1051
1328
  ),
1052
1329
  /**
1053
1330
  * Renames, moves, or sets the attributes of an active object. A move
1054
- * checks the target folder like an upload: validated, authorized, and
1055
- * created when missing.
1331
+ * requires the target folder to exist and authorizes that folder.
1056
1332
  */
1057
1333
  updateObject: createS3Endpoint(
1058
1334
  pluginPath("db", "object"),
@@ -1064,55 +1340,95 @@ function createDatabaseEndpoints(options) {
1064
1340
  ctx.body.bucket,
1065
1341
  "body.bucket"
1066
1342
  );
1067
- const folder = ctx.body.folder === void 0 ? void 0 : parseFolder(ctx.body.folder ?? "");
1343
+ const folderId = wireFolderId(ctx.body.folderId);
1344
+ const peeked = await resolveScope(ctx.context, {
1345
+ operation: "update"
1346
+ });
1347
+ const opened = folderId === void 0 ? void 0 : await openFolder(peeked.scope, folderId ?? "");
1068
1348
  const { scope, object: object2 } = await access.object(
1069
1349
  ctx.context,
1070
1350
  {
1071
1351
  operation: "update",
1072
1352
  key,
1073
- ...folder !== void 0 && { folder }
1353
+ ...opened !== void 0 && folderTarget(opened)
1074
1354
  },
1075
1355
  { bucket, key }
1076
1356
  );
1077
1357
  if (object2.status !== "active") throw s3Error("OBJECT_NOT_FOUND");
1078
1358
  const attributes = ctx.body.attributes === void 0 || ctx.body.attributes === null ? ctx.body.attributes : await parseAttributes(ctx.body.attributes);
1079
- if (filename === void 0 && folder === void 0 && attributes === void 0) {
1359
+ if (filename === void 0 && folderId === void 0 && attributes === void 0) {
1080
1360
  return { object: toClientObject(object2) };
1081
1361
  }
1082
1362
  const updated = await options.objects.update(
1083
1363
  { bucket, key, id: object2.id, scope: scope.scope },
1084
- { filename, folder, attributes }
1364
+ { filename, folderId, attributes }
1085
1365
  );
1086
1366
  if (!updated) throw s3Error("OBJECT_NOT_FOUND");
1087
1367
  return { object: toClientObject(updated) };
1088
1368
  }
1089
1369
  ),
1090
- /** Creates a folder and its missing ancestors. */
1370
+ /** Creates one folder inside a parent that already exists. */
1091
1371
  createFolder: createS3Endpoint(
1092
1372
  pluginPath("db", "folder"),
1093
- { method: "POST", body: dbFolderInputSchema },
1373
+ { method: "POST", body: dbCreateFolderBodySchema },
1094
1374
  async (ctx) => {
1095
- const path = parseFolderPath(ctx.body.path);
1375
+ const parentId = wireFolderId(ctx.body.parentId) ?? null;
1376
+ const peeked = await resolveScope(ctx.context, { operation: "update" });
1377
+ const parent = parentId === null ? null : await openFolder(peeked.scope, parentId);
1378
+ const path = childFolderPath(parent?.path ?? null, ctx.body.name);
1379
+ if (path === null) throw s3Error("FOLDER_INVALID");
1096
1380
  const scope = await access.scope(ctx.context, {
1097
1381
  operation: "update",
1098
1382
  folder: path
1099
1383
  });
1100
- const folder = await folders.create(scope.scope, path);
1384
+ const folder = await folders.create(scope.scope, {
1385
+ parentId,
1386
+ name: ctx.body.name
1387
+ });
1388
+ return { folder: toDbClientFolder(folder) };
1389
+ }
1390
+ ),
1391
+ /** Renames a folder, moves it, or both. */
1392
+ updateFolder: createS3Endpoint(
1393
+ pluginPath("db", "folder"),
1394
+ { method: "PATCH", body: dbUpdateFolderBodySchema },
1395
+ async (ctx) => {
1396
+ const peeked = await resolveScope(ctx.context, { operation: "update" });
1397
+ const current = await folders.find(peeked.scope, ctx.body.id);
1398
+ if (!current) throw s3Error("FOLDER_NOT_FOUND");
1399
+ const parentId = ctx.body.parentId === void 0 ? current.parentId : wireFolderId(ctx.body.parentId) ?? null;
1400
+ const parent = parentId === null ? null : await openFolder(peeked.scope, parentId);
1401
+ const path = childFolderPath(
1402
+ parent?.path ?? null,
1403
+ ctx.body.name ?? current.name
1404
+ );
1405
+ if (path === null) throw s3Error("FOLDER_INVALID");
1406
+ await access.scope(ctx.context, {
1407
+ operation: "update",
1408
+ folder: path,
1409
+ folderId: current.id
1410
+ });
1411
+ const folder = await folders.update(peeked.scope, current.id, {
1412
+ ...ctx.body.name !== void 0 && { name: ctx.body.name },
1413
+ ...ctx.body.parentId !== void 0 && { parentId }
1414
+ });
1101
1415
  return { folder: toDbClientFolder(folder) };
1102
1416
  }
1103
1417
  ),
1104
1418
  /** Removes an empty folder. A missing folder is not an error. */
1105
1419
  deleteFolder: createS3Endpoint(
1106
1420
  pluginPath("db", "folder"),
1107
- { method: "DELETE", query: dbFolderInputSchema },
1421
+ { method: "DELETE", query: dbDeleteFolderQuerySchema },
1108
1422
  async (ctx) => {
1109
- const path = parseFolderPath(ctx.query.path);
1110
- const scope = await access.scope(ctx.context, {
1423
+ const peeked = await resolveScope(ctx.context, { operation: "update" });
1424
+ const current = await folders.find(peeked.scope, ctx.query.id);
1425
+ if (!current) return { id: ctx.query.id };
1426
+ await access.scope(ctx.context, {
1111
1427
  operation: "update",
1112
- folder: path
1428
+ ...folderTarget(current)
1113
1429
  });
1114
- await folders.delete(scope.scope, path);
1115
- return { path };
1430
+ await folders.delete(peeked.scope, current.id);
1431
+ return { id: current.id };
1116
1432
  }
1117
1433
  )
1118
1434
  };
@@ -1132,12 +1448,9 @@ function refOf(context) {
1132
1448
  function objectTarget(context, operation) {
1133
1449
  return { operation, route: context.route, key: context.key };
1134
1450
  }
1135
- function uploadTarget(context) {
1136
- return {
1137
- ...objectTarget(context, "upload"),
1138
- folder: parseFolder(context.clientMetadata?.folder ?? ""),
1139
- clientMetadata: context.clientMetadata
1140
- };
1451
+ function requestedFolderId(metadata) {
1452
+ const value = metadata?.folderId ?? "";
1453
+ return value === "" ? null : value;
1141
1454
  }
1142
1455
  function writtenBy(object2, uploadToken) {
1143
1456
  return object2 !== null && object2.uploadToken === uploadToken;
@@ -1163,16 +1476,22 @@ function createDatabaseLifecycleHooks(options) {
1163
1476
  if (!live) throw s3Error("OBJECT_NOT_FOUND");
1164
1477
  };
1165
1478
  const uploadWrite = async (context) => {
1166
- const target = uploadTarget(context);
1167
1479
  const existing = await objects.find(refOf(context));
1168
- if (existing?.status !== "active" || routes.replace(context.route) !== "overwrite") {
1169
- return { target, existing, replaced: null };
1480
+ const replaced = existing?.status === "active" && routes.replace(context.route) === "overwrite" ? existing : null;
1481
+ const folderId = replaced ? replaced.folderId : requestedFolderId(context.clientMetadata);
1482
+ const scope = await resolveScope(context, objectTarget(context, "upload"));
1483
+ let folder = null;
1484
+ if (folderId !== null) {
1485
+ folder = await folders.find(scope.scope, folderId);
1486
+ if (!folder && !replaced) throw s3Error("FOLDER_NOT_FOUND");
1170
1487
  }
1171
- return {
1172
- target: { ...target, folder: existing.folder },
1173
- existing,
1174
- replaced: existing
1488
+ const target = {
1489
+ ...objectTarget(context, "upload"),
1490
+ folderId,
1491
+ clientMetadata: context.clientMetadata,
1492
+ ...folder ? { folder: folder.path } : folderId === null ? { folder: null } : {}
1175
1493
  };
1494
+ return { target, existing, replaced, folder };
1176
1495
  };
1177
1496
  const abortPendingMultipart = async (context, row) => {
1178
1497
  const client = routes.client(context.route);
@@ -1220,13 +1539,13 @@ function createDatabaseLifecycleHooks(options) {
1220
1539
  });
1221
1540
  },
1222
1541
  async onStart(context) {
1223
- const { target } = await uploadWrite(context);
1224
- const { scope } = await resolveScope(context, target);
1225
- const row = await objects.upsertPending({
1542
+ const written = await uploadWrite(context);
1543
+ const { scope } = await resolveScope(context, written.target);
1544
+ await objects.upsertPending({
1226
1545
  ...refOf(context),
1227
1546
  scope,
1228
1547
  route: context.route,
1229
- folder: target.folder ?? null,
1548
+ folderId: written.target.folderId ?? null,
1230
1549
  filename: context.file.name,
1231
1550
  contentType: context.file.type ?? null,
1232
1551
  declaredSize: context.file.size,
@@ -1236,7 +1555,7 @@ function createDatabaseLifecycleHooks(options) {
1236
1555
  expiresAt: context.expiresAt,
1237
1556
  overwrite: routes.replace(context.route) === "overwrite"
1238
1557
  });
1239
- await folders.ensure(scope, row.folder);
1558
+ if (written.folder) await folders.retain(written.folder);
1240
1559
  },
1241
1560
  async confirmGuard(context) {
1242
1561
  await assertUploadRow(context, "confirm", {
@@ -1341,6 +1660,8 @@ function createObjectAccess(options) {
1341
1660
  ...scope,
1342
1661
  ...target?.key !== void 0 && { key: target.key },
1343
1662
  ...target?.folder !== void 0 && { folder: target.folder },
1663
+ ...target?.folderId !== void 0 && { folderId: target.folderId },
1664
+ ...target?.recursive === true && { recursive: true },
1344
1665
  ...target?.clientMetadata !== void 0 && {
1345
1666
  clientMetadata: target.clientMetadata
1346
1667
  },
@@ -1370,13 +1691,20 @@ function createObjectAccess(options) {
1370
1691
  assertOwner
1371
1692
  };
1372
1693
  }
1373
- function folderPath(path) {
1374
- const normalized = normalizeFolderPath(path);
1375
- if (normalized === null) throw s3Error("FOLDER_INVALID");
1376
- return normalized;
1694
+ function rootId(folderId) {
1695
+ return folderId === "" ? null : folderId;
1696
+ }
1697
+ async function targetFolder(folders, scope, folderId) {
1698
+ if (folderId === void 0) return void 0;
1699
+ const id = rootId(folderId);
1700
+ if (id === null) return null;
1701
+ const folder = await folders.find(scope, id);
1702
+ if (!folder) throw s3Error("FOLDER_NOT_FOUND");
1703
+ return folder;
1377
1704
  }
1378
1705
  function createPublicStores(store) {
1379
- const { objects, folders } = store;
1706
+ const { objects } = store;
1707
+ const { subtreeIds: _subtreeIds, ...folders } = store.folders;
1380
1708
  return {
1381
1709
  objects: {
1382
1710
  find: objects.find,
@@ -1384,26 +1712,19 @@ function createPublicStores(store) {
1384
1712
  count: objects.count,
1385
1713
  getUsage: objects.getUsage,
1386
1714
  async update(ref, input) {
1387
- const folder = input.folder === void 0 || input.folder === null ? input.folder : folderPath(input.folder);
1388
- const row = await objects.update(ref, { ...input, folder });
1389
- if (row && folder !== void 0) {
1390
- await folders.ensure(row.scope, row.folder);
1715
+ const folderId = input.folderId === void 0 ? void 0 : rootId(input.folderId);
1716
+ let folder;
1717
+ if (typeof folderId === "string") {
1718
+ const scope = ref.scope ?? (await objects.find(ref))?.scope;
1719
+ if (!scope) return null;
1720
+ folder = await targetFolder(folders, scope, folderId);
1391
1721
  }
1722
+ const row = await objects.update(ref, { ...input, folderId });
1723
+ if (row && folder) await folders.retain(folder);
1392
1724
  return row;
1393
1725
  }
1394
1726
  },
1395
- // Async, so an invalid path is a rejection like any other failure.
1396
- folders: {
1397
- find: async (scope, path) => folders.find(scope, folderPath(path)),
1398
- children: async (scope, parent, options) => folders.children(
1399
- scope,
1400
- parent === null ? null : folderPath(parent),
1401
- options
1402
- ),
1403
- ensure: async (scope, path) => folders.ensure(scope, path === null ? null : folderPath(path)),
1404
- create: async (scope, path) => folders.create(scope, folderPath(path)),
1405
- delete: async (scope, path) => folders.delete(scope, folderPath(path))
1406
- }
1727
+ folders
1407
1728
  };
1408
1729
  }
1409
1730
  async function abortUpload(client, row, uploadId) {
@@ -1552,6 +1873,12 @@ function createScopeResolver(options) {
1552
1873
  }
1553
1874
  const resolved = await scope;
1554
1875
  if (resolved === null) throw s3Error("UNAUTHORIZED");
1876
+ const length = characterCount(resolved);
1877
+ if (length > SCOPE_MAX_LENGTH) {
1878
+ throw new Error(
1879
+ `[dimah-s3/db] resolveScope returned a scope of ${length} characters. A scope holds at most ${SCOPE_MAX_LENGTH}.`
1880
+ );
1881
+ }
1555
1882
  return { ...context, scope: resolved };
1556
1883
  };
1557
1884
  }
@@ -1600,6 +1927,7 @@ function db(options) {
1600
1927
  store,
1601
1928
  objects: stores.objects,
1602
1929
  access,
1930
+ resolveScope,
1603
1931
  quota,
1604
1932
  attributes: options.attributes,
1605
1933
  toClientObject