@dimah-s3/db 2.0.0-beta.6 → 2.0.0-beta.8

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.
package/dist/cli.js CHANGED
@@ -6,13 +6,14 @@ import { table, column, idColumn, schema } from 'fumadb/schema';
6
6
  var BINARY = { mysql: "utf8mb4_bin" };
7
7
  var TEXT = { mysql: "utf8mb4_unicode_ci" };
8
8
  var LONG_PREFIX = 512;
9
+ var SCOPE_MAX_LENGTH = 255;
9
10
  function string(name, length = 255) {
10
11
  return column(name, `varchar(${length})`).collate(BINARY);
11
12
  }
12
13
  var storageObject = table("storage_object", {
13
14
  id: idColumn("id", "varchar(255)").collate(BINARY).defaultTo$("auto"),
14
15
  /** Owner, for example `user:123` or `org:acme`. */
15
- scope: string("scope"),
16
+ scope: string("scope", SCOPE_MAX_LENGTH),
16
17
  bucket: string("bucket"),
17
18
  key: string("key", 1024),
18
19
  /** Named dimah-s3 route that created the object. */
@@ -52,7 +53,7 @@ var storageObject = table("storage_object", {
52
53
  ]).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"]);
53
54
  var storageFolder = table("storage_folder", {
54
55
  id: idColumn("id", "varchar(255)").collate(BINARY).defaultTo$("auto"),
55
- scope: string("scope"),
56
+ scope: string("scope", SCOPE_MAX_LENGTH),
56
57
  /** Id of the containing folder. `""` is the root. */
57
58
  parentId: string("parent_id").defaultTo(""),
58
59
  /** Last segment of `path`. */
@@ -85,7 +86,7 @@ function runCli(client) {
85
86
  db: client,
86
87
  command: "dimah-s3-db",
87
88
  description: "FumaDB CLI for @dimah-s3/db",
88
- version: "2.0.0-beta.6"
89
+ version: "2.0.0-beta.8"
89
90
  });
90
91
  return main();
91
92
  }
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources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M,EAAE,IAAA,EAAK,GAAI,SAAA,CAAU;AAAA,IACzB,EAAA,EAAI,MAAA;AAAA,IACJ,OAAA,EAAS,aAAA;AAAA,IACT,WAAA,EAAa,6BAAA;AAAA,IACb,OAAA,EAAS;AAAA,GACV,CAAA;AAED,EAAA,OAAO,IAAA,EAAK;AACd;AAiBA,eAAsB,QAAQ,MAAA,EAAwC;AACpE,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACF,IAAA,OAAA,GAAU,MAAM,OAAO,OAAA,EAAQ;AAAA,EACjC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAA,GAAU,MAAA;AAAA,EACZ;AACA,EAAA,IAAI,YAAY,iBAAA,EAAmB;AACnC,EAAA,IAAI,YAAY,MAAA,EAAW;AACzB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,wCAAA,EAA2C,OAAO,CAAA,qDAAA,EAAwD,iBAAiB,CAAA,mBAAA;AAAA,KAC7H;AAAA,EACF;AACA,EAAA,MAAA,CAAO,MAAM,MAAA,CAAO,cAAA,EAAe,CAAE,eAAA,IAAmB,OAAA,EAAQ;AAClE","file":"cli.js","sourcesContent":["import { column, idColumn, schema, table } from \"fumadb/schema\";\n\n/**\n * MySQL collation of every text column but `filename`: keys, scopes, ids, and\n * upload tokens compare byte for byte.\n */\nconst BINARY = { mysql: \"utf8mb4_bin\" };\n\n/** MySQL collation of `filename`: case-insensitive, for search. */\nconst TEXT = { mysql: \"utf8mb4_unicode_ci\" };\n\n/**\n * InnoDB indexes at most 3072 bytes, so S3 keys and folder paths are indexed\n * on their first 512 characters on MySQL. Two values that share those\n * characters share an index entry, and the unique keys treat them as equal.\n */\nconst LONG_PREFIX = 512;\n\nfunction string(name: string, length = 255) {\n return column(name, `varchar(${length})`).collate(BINARY);\n}\n\n/**\n * One row per tracked object:\n * `pending` (presigned) → `active` (confirmed) → `deleted` (soft delete).\n * `purging` marks a stale pending row that purge has claimed.\n */\nconst storageObject = table(\"storage_object\", {\n id: idColumn(\"id\", \"varchar(255)\").collate(BINARY).defaultTo$(\"auto\"),\n /** Owner, for example `user:123` or `org:acme`. */\n scope: string(\"scope\"),\n bucket: string(\"bucket\"),\n key: string(\"key\", 1024),\n /** Named dimah-s3 route that created the object. */\n route: string(\"route\"),\n /** Folder that holds the object. `null` is the root. */\n folderId: string(\"folder_id\").nullable(),\n filename: column(\"filename\", \"varchar(255)\").collate(TEXT),\n contentType: string(\"content_type\").nullable(),\n /** Verified size from HeadObject, set on confirm. */\n size: column(\"size\", \"bigint\").nullable(),\n /** Size the client declared before confirm. Quota counts it while pending. */\n declaredSize: column(\"declared_size\", \"bigint\").nullable(),\n eTag: string(\"e_tag\").nullable(),\n status: string(\"status\", 16),\n /** S3 user metadata of the verified object. */\n s3Metadata: column(\"s3_metadata\", \"json\").nullable(),\n /** App attributes, validated by the plugin's `attributes.schema`. */\n attributes: column(\"attributes\", \"json\").nullable(),\n acl: string(\"acl\").nullable(),\n /** Multipart upload ID while the row is pending. */\n uploadId: column(\"upload_id\", \"string\").collate(BINARY).nullable(),\n /** Token of the upload ticket that wrote the row. Confirm and purge match it. */\n uploadToken: string(\"upload_token\", 64).nullable(),\n /** Confirm deadline of a pending row (the upload ticket's expiry). */\n expiresAt: column(\"expires_at\", \"timestamp\").nullable(),\n confirmedAt: column(\"confirmed_at\", \"timestamp\").nullable(),\n createdAt: column(\"created_at\", \"timestamp\").defaultTo$(\"now\"),\n updatedAt: column(\"updated_at\", \"timestamp\").defaultTo$(\"now\"),\n deletedAt: column(\"deleted_at\", \"timestamp\").nullable(),\n})\n .unique(\"storage_object_bucket_key_uk\", [\"bucket\", \"key\"], {\n length: { key: LONG_PREFIX },\n })\n .index(\"storage_object_scope_folder_idx\", [\n \"scope\",\n \"status\",\n \"folderId\",\n \"createdAt\",\n ])\n .index(\"storage_object_scope_updated_idx\", [\"scope\", \"status\", \"updatedAt\"])\n .index(\"storage_object_scope_filename_idx\", [\"scope\", \"status\", \"filename\"])\n .index(\"storage_object_scope_size_idx\", [\"scope\", \"status\", \"size\"])\n .index(\"storage_object_status_expires_idx\", [\"status\", \"expiresAt\"]);\n\n/**\n * One row per folder, so an empty folder still lists. `parentId` is `\"\"` at\n * the root: a nullable parent cannot be unique on PostgreSQL, MySQL, and\n * SQLite, and the root is not a row. `path` is a cache of `name` joined\n * through the parents, rewritten when a folder is renamed or moved.\n */\nconst storageFolder = table(\"storage_folder\", {\n id: idColumn(\"id\", \"varchar(255)\").collate(BINARY).defaultTo$(\"auto\"),\n scope: string(\"scope\"),\n /** Id of the containing folder. `\"\"` is the root. */\n parentId: string(\"parent_id\").defaultTo(\"\"),\n /** Last segment of `path`. */\n name: string(\"name\"),\n /** Full folder path. */\n path: string(\"path\", 1024),\n createdAt: column(\"created_at\", \"timestamp\").defaultTo$(\"now\"),\n updatedAt: column(\"updated_at\", \"timestamp\").defaultTo$(\"now\"),\n})\n .unique(\"storage_folder_scope_path_uk\", [\"scope\", \"path\"], {\n length: { path: LONG_PREFIX },\n })\n .unique(\"storage_folder_scope_parent_name_uk\", [\"scope\", \"parentId\", \"name\"]);\n\n/**\n * The @dimah-s3/db schema, version `2.1.0`. The tables, their indexes, and\n * the MySQL collations and prefix lengths are all declared here, so FumaDB\n * creates them (`migrate`) and generates them for Drizzle and Prisma.\n */\nexport const dbSchema = schema({\n version: \"2.1.0\",\n tables: {\n storageObject,\n storageFolder,\n },\n});\n","import { fumadb, type InferFumaDB } from \"fumadb\";\nimport { dbSchema } from \"./schema/schema\";\n\n/**\n * The @dimah-s3/db FumaDB library. Call `DimahS3DB.client(adapter)` with an\n * adapter from `@dimah-s3/db/adapters/*` to get a {@link DimahS3DbClient}.\n */\nexport const DimahS3DB = fumadb({\n namespace: \"dimah_s3\",\n schemas: [dbSchema],\n});\n\n/** FumaDB client for the @dimah-s3/db schema. */\nexport type DimahS3DbClient = InferFumaDB<typeof DimahS3DB>;\n\n/** The schema version the stores read and write. */\nexport const DB_SCHEMA_VERSION = dbSchema.version;\n","import { createCli } from \"fumadb/cli\";\nimport { DB_SCHEMA_VERSION, type DimahS3DbClient } from \"./fuma-db\";\n\ndeclare const __DIMAH_S3_DB_VERSION__: string;\n\n/**\n * Runs the FumaDB CLI for the @dimah-s3/db schema. `generate` writes the\n * Drizzle or Prisma schema for the client's adapter, and with Kysely, the SQL\n * that creates the tables. `migrate` creates them with Kysely.\n *\n * Generating does not query the database, so the client can wrap an adapter\n * that has no connection yet.\n *\n * ```ts\n * // scripts/dimah-s3.mts\n * import { DimahS3DB } from \"@dimah-s3/db\";\n * import { drizzleAdapter } from \"@dimah-s3/db/adapters/drizzle\";\n * import { runCli } from \"@dimah-s3/db/cli\";\n *\n * await runCli(DimahS3DB.client(drizzleAdapter({ db: undefined, provider: \"postgresql\" })));\n * ```\n *\n * `node scripts/dimah-s3.mts generate latest -o db/dimah-s3.ts`\n */\nexport function runCli(client: DimahS3DbClient): Promise<void> {\n const { main } = createCli({\n db: client,\n command: \"dimah-s3-db\",\n description: \"FumaDB CLI for @dimah-s3/db\",\n version: __DIMAH_S3_DB_VERSION__,\n });\n\n return main();\n}\n\n/**\n * Creates the schema this package reads, with its indexes, on an empty\n * database. It needs the Kysely adapter; with Drizzle or Prisma, generate the\n * schema with {@link runCli} and apply it with your ORM. It does nothing on a\n * database already at {@link DB_SCHEMA_VERSION}, and throws on a database at\n * another version: this package does not upgrade one.\n *\n * ```ts\n * import { DimahS3DB } from \"@dimah-s3/db\";\n * import { kyselyAdapter } from \"@dimah-s3/db/adapters/kysely\";\n * import { migrate } from \"@dimah-s3/db/cli\";\n *\n * await migrate(DimahS3DB.client(kyselyAdapter({ db: kysely, provider: \"postgresql\" })));\n * ```\n */\nexport async function migrate(client: DimahS3DbClient): Promise<void> {\n let version: string | undefined;\n try {\n version = await client.version();\n } catch {\n version = undefined;\n }\n if (version === DB_SCHEMA_VERSION) return;\n if (version !== undefined) {\n throw new Error(\n `[dimah-s3/db] The database is at schema ${version}, which this package does not upgrade. Create schema ${DB_SCHEMA_VERSION} on a new database.`,\n );\n }\n await (await client.createMigrator().migrateToLatest()).execute();\n}\n"]}
1
+ {"version":3,"sources":["../src/schema/schema.ts","../src/fuma-db.ts","../src/cli.ts"],"names":[],"mappings":";;;;;AAMA,IAAM,MAAA,GAAS,EAAE,KAAA,EAAO,aAAA,EAAc;AAGtC,IAAM,IAAA,GAAO,EAAE,KAAA,EAAO,oBAAA,EAAqB;AAO3C,IAAM,WAAA,GAAc,GAAA;AAMb,IAAM,gBAAA,GAAmB,GAAA;AAEhC,SAAS,MAAA,CAAO,IAAA,EAAc,MAAA,GAAS,GAAA,EAAK;AAC1C,EAAA,OAAO,OAAO,IAAA,EAAM,CAAA,QAAA,EAAW,MAAM,CAAA,CAAA,CAAG,CAAA,CAAE,QAAQ,MAAM,CAAA;AAC1D;AAOA,IAAM,aAAA,GAAgB,MAAM,gBAAA,EAAkB;AAAA,EAC5C,EAAA,EAAI,SAAS,IAAA,EAAM,cAAc,EAAE,OAAA,CAAQ,MAAM,CAAA,CAAE,UAAA,CAAW,MAAM,CAAA;AAAA;AAAA,EAEpE,KAAA,EAAO,MAAA,CAAO,OAAA,EAAS,gBAAgB,CAAA;AAAA,EACvC,MAAA,EAAQ,OAAO,QAAQ,CAAA;AAAA,EACvB,GAAA,EAAK,MAAA,CAAO,KAAA,EAAO,IAAI,CAAA;AAAA;AAAA,EAEvB,KAAA,EAAO,OAAO,OAAO,CAAA;AAAA;AAAA,EAErB,QAAA,EAAU,MAAA,CAAO,WAAW,CAAA,CAAE,QAAA,EAAS;AAAA,EACvC,UAAU,MAAA,CAAO,UAAA,EAAY,cAAc,CAAA,CAAE,QAAQ,IAAI,CAAA;AAAA,EACzD,WAAA,EAAa,MAAA,CAAO,cAAc,CAAA,CAAE,QAAA,EAAS;AAAA;AAAA,EAE7C,IAAA,EAAM,MAAA,CAAO,MAAA,EAAQ,QAAQ,EAAE,QAAA,EAAS;AAAA;AAAA,EAExC,YAAA,EAAc,MAAA,CAAO,eAAA,EAAiB,QAAQ,EAAE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AAA;AAAA,EACX,OAAA,EAAS,CAAC,QAAQ;AACpB,CAAC;AAMM,IAAM,oBAAoB,QAAA,CAAS,OAAA;;;ACQnC,SAAS,OAAO,MAAA,EAAwC;AAC7D,EAAA,MAAM,EAAE,IAAA,EAAK,GAAI,SAAA,CAAU;AAAA,IACzB,EAAA,EAAI,MAAA;AAAA,IACJ,OAAA,EAAS,aAAA;AAAA,IACT,WAAA,EAAa,6BAAA;AAAA,IACb,OAAA,EAAS;AAAA,GACV,CAAA;AAED,EAAA,OAAO,IAAA,EAAK;AACd;AAiBA,eAAsB,QAAQ,MAAA,EAAwC;AACpE,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACF,IAAA,OAAA,GAAU,MAAM,OAAO,OAAA,EAAQ;AAAA,EACjC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAA,GAAU,MAAA;AAAA,EACZ;AACA,EAAA,IAAI,YAAY,iBAAA,EAAmB;AACnC,EAAA,IAAI,YAAY,MAAA,EAAW;AACzB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,wCAAA,EAA2C,OAAO,CAAA,qDAAA,EAAwD,iBAAiB,CAAA,mBAAA;AAAA,KAC7H;AAAA,EACF;AACA,EAAA,MAAA,CAAO,MAAM,MAAA,CAAO,cAAA,EAAe,CAAE,eAAA,IAAmB,OAAA,EAAQ;AAClE","file":"cli.js","sourcesContent":["import { column, idColumn, schema, table } from \"fumadb/schema\";\n\n/**\n * MySQL collation of every text column but `filename`: keys, scopes, ids, and\n * upload tokens compare byte for byte.\n */\nconst BINARY = { mysql: \"utf8mb4_bin\" };\n\n/** MySQL collation of `filename`: case-insensitive, for search. */\nconst TEXT = { mysql: \"utf8mb4_unicode_ci\" };\n\n/**\n * InnoDB indexes at most 3072 bytes, so S3 keys and folder paths are indexed\n * on their first 512 characters on MySQL. Two values that share those\n * characters share an index entry, and the unique keys treat them as equal.\n */\nconst LONG_PREFIX = 512;\n\n/**\n * Longest scope `resolveScope` may return, in characters. The `scope`\n * columns are `varchar(255)`.\n */\nexport const SCOPE_MAX_LENGTH = 255;\n\nfunction string(name: string, length = 255) {\n return column(name, `varchar(${length})`).collate(BINARY);\n}\n\n/**\n * One row per tracked object:\n * `pending` (presigned) → `active` (confirmed) → `deleted` (soft delete).\n * `purging` marks a stale pending row that purge has claimed.\n */\nconst storageObject = table(\"storage_object\", {\n id: idColumn(\"id\", \"varchar(255)\").collate(BINARY).defaultTo$(\"auto\"),\n /** Owner, for example `user:123` or `org:acme`. */\n scope: string(\"scope\", SCOPE_MAX_LENGTH),\n bucket: string(\"bucket\"),\n key: string(\"key\", 1024),\n /** Named dimah-s3 route that created the object. */\n route: string(\"route\"),\n /** Folder that holds the object. `null` is the root. */\n folderId: string(\"folder_id\").nullable(),\n filename: column(\"filename\", \"varchar(255)\").collate(TEXT),\n contentType: string(\"content_type\").nullable(),\n /** Verified size from HeadObject, set on confirm. */\n size: column(\"size\", \"bigint\").nullable(),\n /** Size the client declared before confirm. Quota counts it while pending. */\n declaredSize: column(\"declared_size\", \"bigint\").nullable(),\n eTag: string(\"e_tag\").nullable(),\n status: string(\"status\", 16),\n /** S3 user metadata of the verified object. */\n s3Metadata: column(\"s3_metadata\", \"json\").nullable(),\n /** App attributes, validated by the plugin's `attributes.schema`. */\n attributes: column(\"attributes\", \"json\").nullable(),\n acl: string(\"acl\").nullable(),\n /** Multipart upload ID while the row is pending. */\n uploadId: column(\"upload_id\", \"string\").collate(BINARY).nullable(),\n /** Token of the upload ticket that wrote the row. Confirm and purge match it. */\n uploadToken: string(\"upload_token\", 64).nullable(),\n /** Confirm deadline of a pending row (the upload ticket's expiry). */\n expiresAt: column(\"expires_at\", \"timestamp\").nullable(),\n confirmedAt: column(\"confirmed_at\", \"timestamp\").nullable(),\n createdAt: column(\"created_at\", \"timestamp\").defaultTo$(\"now\"),\n updatedAt: column(\"updated_at\", \"timestamp\").defaultTo$(\"now\"),\n deletedAt: column(\"deleted_at\", \"timestamp\").nullable(),\n})\n .unique(\"storage_object_bucket_key_uk\", [\"bucket\", \"key\"], {\n length: { key: LONG_PREFIX },\n })\n .index(\"storage_object_scope_folder_idx\", [\n \"scope\",\n \"status\",\n \"folderId\",\n \"createdAt\",\n ])\n .index(\"storage_object_scope_updated_idx\", [\"scope\", \"status\", \"updatedAt\"])\n .index(\"storage_object_scope_filename_idx\", [\"scope\", \"status\", \"filename\"])\n .index(\"storage_object_scope_size_idx\", [\"scope\", \"status\", \"size\"])\n .index(\"storage_object_status_expires_idx\", [\"status\", \"expiresAt\"]);\n\n/**\n * One row per folder, so an empty folder still lists. `parentId` is `\"\"` at\n * the root: a nullable parent cannot be unique on PostgreSQL, MySQL, and\n * SQLite, and the root is not a row. `path` is a cache of `name` joined\n * through the parents, rewritten when a folder is renamed or moved.\n */\nconst storageFolder = table(\"storage_folder\", {\n id: idColumn(\"id\", \"varchar(255)\").collate(BINARY).defaultTo$(\"auto\"),\n scope: string(\"scope\", SCOPE_MAX_LENGTH),\n /** Id of the containing folder. `\"\"` is the root. */\n parentId: string(\"parent_id\").defaultTo(\"\"),\n /** Last segment of `path`. */\n name: string(\"name\"),\n /** Full folder path. */\n path: string(\"path\", 1024),\n createdAt: column(\"created_at\", \"timestamp\").defaultTo$(\"now\"),\n updatedAt: column(\"updated_at\", \"timestamp\").defaultTo$(\"now\"),\n})\n .unique(\"storage_folder_scope_path_uk\", [\"scope\", \"path\"], {\n length: { path: LONG_PREFIX },\n })\n .unique(\"storage_folder_scope_parent_name_uk\", [\"scope\", \"parentId\", \"name\"]);\n\n/**\n * The @dimah-s3/db schema, version `2.1.0`. The tables, their indexes, and\n * the MySQL collations and prefix lengths are all declared here, so FumaDB\n * creates them (`migrate`) and generates them for Drizzle and Prisma.\n */\nexport const dbSchema = schema({\n version: \"2.1.0\",\n tables: {\n storageObject,\n storageFolder,\n },\n});\n","import { fumadb, type InferFumaDB } from \"fumadb\";\nimport { dbSchema } from \"./schema/schema\";\n\n/**\n * The @dimah-s3/db FumaDB library. Call `DimahS3DB.client(adapter)` with an\n * adapter from `@dimah-s3/db/adapters/*` to get a {@link DimahS3DbClient}.\n */\nexport const DimahS3DB = fumadb({\n namespace: \"dimah_s3\",\n schemas: [dbSchema],\n});\n\n/** FumaDB client for the @dimah-s3/db schema. */\nexport type DimahS3DbClient = InferFumaDB<typeof DimahS3DB>;\n\n/** The schema version the stores read and write. */\nexport const DB_SCHEMA_VERSION = dbSchema.version;\n","import { createCli } from \"fumadb/cli\";\nimport { DB_SCHEMA_VERSION, type DimahS3DbClient } from \"./fuma-db\";\n\ndeclare const __DIMAH_S3_DB_VERSION__: string;\n\n/**\n * Runs the FumaDB CLI for the @dimah-s3/db schema. `generate` writes the\n * Drizzle or Prisma schema for the client's adapter, and with Kysely, the SQL\n * that creates the tables. `migrate` creates them with Kysely.\n *\n * Generating does not query the database, so the client can wrap an adapter\n * that has no connection yet.\n *\n * ```ts\n * // scripts/dimah-s3.mts\n * import { DimahS3DB } from \"@dimah-s3/db\";\n * import { drizzleAdapter } from \"@dimah-s3/db/adapters/drizzle\";\n * import { runCli } from \"@dimah-s3/db/cli\";\n *\n * await runCli(DimahS3DB.client(drizzleAdapter({ db: undefined, provider: \"postgresql\" })));\n * ```\n *\n * `node scripts/dimah-s3.mts generate latest -o db/dimah-s3.ts`\n */\nexport function runCli(client: DimahS3DbClient): Promise<void> {\n const { main } = createCli({\n db: client,\n command: \"dimah-s3-db\",\n description: \"FumaDB CLI for @dimah-s3/db\",\n version: __DIMAH_S3_DB_VERSION__,\n });\n\n return main();\n}\n\n/**\n * Creates the schema this package reads, with its indexes, on an empty\n * database. It needs the Kysely adapter; with Drizzle or Prisma, generate the\n * schema with {@link runCli} and apply it with your ORM. It does nothing on a\n * database already at {@link DB_SCHEMA_VERSION}, and throws on a database at\n * another version: this package does not upgrade one.\n *\n * ```ts\n * import { DimahS3DB } from \"@dimah-s3/db\";\n * import { kyselyAdapter } from \"@dimah-s3/db/adapters/kysely\";\n * import { migrate } from \"@dimah-s3/db/cli\";\n *\n * await migrate(DimahS3DB.client(kyselyAdapter({ db: kysely, provider: \"postgresql\" })));\n * ```\n */\nexport async function migrate(client: DimahS3DbClient): Promise<void> {\n let version: string | undefined;\n try {\n version = await client.version();\n } catch {\n version = undefined;\n }\n if (version === DB_SCHEMA_VERSION) return;\n if (version !== undefined) {\n throw new Error(\n `[dimah-s3/db] The database is at schema ${version}, which this package does not upgrade. Create schema ${DB_SCHEMA_VERSION} on a new database.`,\n );\n }\n await (await client.createMigrator().migrateToLatest()).execute();\n}\n"]}
@@ -45,6 +45,7 @@ function dbClient() {
45
45
  }
46
46
  var FOLDER_NAME_MAX_LENGTH = 255;
47
47
  var INVALID_CHARACTER = /[\p{Cc}\p{Cs}]/u;
48
+ new TextEncoder();
48
49
  function characterCount(value) {
49
50
  return Array.from(value).length;
50
51
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/client/db-client.ts","../../src/folder-path.ts","../../src/client/db-object-source.ts"],"names":["s3Error"],"mappings":";;;AAeA,SAAS,KAAK,OAAA,EAAuC;AACnD,EAAA,OAAO,EAAE,MAAA,EAAQ,OAAA,EAAS,MAAA,EAAQ,OAAA,EAAS,SAAS,OAAA,EAAQ;AAC9D;AAGA,SAAS,UAAU,KAAA,EAAsC;AACvD,EAAA,IAAI,KAAA,EAAO,QAAA,KAAa,IAAA,EAAM,OAAO,KAAA;AACrC,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,QAAA,EAAU,EAAA,EAAG;AAClC;AAqBO,SAAS,QAAA,GAAsC;AACpD,EAAA,OAAO,kBAAA,CAAmB;AAAA,IACxB,EAAA,EAAI,IAAA;AAAA,IACJ,oBAAoB,EAAC;AAAA,IACrB,UAAA,EAAY,CAAC,MAAA,MAAgD;AAAA,MAC3D,WAAA,EAAa,CAAC,KAAA,EAAO,OAAA,KACnB,MAAA;AAAA,QACE,UAAA,CAAW,MAAM,SAAS,CAAA;AAAA,QAC1B,EAAE,MAAA,EAAQ,KAAA,EAAO,KAAA,EAAO,SAAA,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O,EAAA,EAAI,IAAA,EAAM,OAAO,IAAA,EAAK;AAAA,IAC5C,CAAA;AAAA,EACF;AACA,EAAA,MAAM,YAAA,GAAe,EAAA,CAAG,YAAA,EAAc,IAAA,CAAK,EAAE,CAAA;AAC7C,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,MAAA,CAAO,YAAA,GAAe,OAAO,EAAE,MAAA,EAAQ,MAAK,KAAM;AAEhD,MAAA,IAAI,CAAC,YAAA,CAAa,IAAI,CAAA,EAAG,MAAMA,QAAQ,gBAAgB,CAAA;AACvD,MAAA,MAAM,EAAE,MAAA,EAAQ,OAAA,EAAQ,GAAI,MAAM,YAAA,CAAa;AAAA,QAC7C,IAAI,MAAA,CAAO,EAAA;AAAA,QACX;AAAA,OACD,CAAA;AACD,MAAA,OAAO,EAAE,EAAA,EAAI,OAAA,CAAQ,EAAA,EAAI,IAAA,EAAM,QAAQ,IAAA,EAAK;AAAA,IAC9C,CAAA;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["import {\n defineClientPlugin,\n pluginPath,\n type S3RequestOptions,\n} from \"@dimah-s3/core\";\nimport type { db } from \"@/plugin/db\";\nimport type {\n DbClientActions,\n DbClientFolder,\n DbClientListInput,\n DbClientListResponse,\n DbClientObject,\n} from \"@/types/client\";\n\n/** The per-call options better-fetch reads: the abort signal and headers. */\nfunction call(options: S3RequestOptions | undefined) {\n return { signal: options?.signal, headers: options?.headers };\n}\n\n/** The list query on the wire, where the root folder is `\"\"`. */\nfunction listQuery(input: DbClientListInput | undefined) {\n if (input?.folderId !== null) return input;\n return { ...input, folderId: \"\" };\n}\n\n/**\n * Client plugin for the server `db()` endpoints. Its actions are\n * {@link DbClientActions} on `api.db`. Pass `TClientAttributes` to type the\n * `attributes` the plugin's `attributes.toClient` returns.\n *\n * ```ts\n * import { createS3Client } from \"@dimah-s3/react\";\n * import { dbClient } from \"@dimah-s3/db/client\";\n *\n * export const s3Client = createS3Client({\n * plugins: [dbClient()],\n * });\n *\n * const page = await s3Client.db.listObjects({ folderId: \"\" });\n * ```\n *\n * The server resolves the scope from the request, so no action takes one.\n * Server code skips HTTP and uses `s3.db.objects` and `s3.db.folders`.\n */\nexport function dbClient<TClientAttributes = never>() {\n return defineClientPlugin({\n id: \"db\",\n $InferServerPlugin: {} as ReturnType<typeof db>,\n getActions: ($fetch): DbClientActions<TClientAttributes> => ({\n listObjects: (input, options) =>\n $fetch<DbClientListResponse<TClientAttributes>>(\n pluginPath(\"db\", \"objects\"),\n { method: \"GET\", query: listQuery(input), ...call(options) },\n ),\n getObject: (input, options) =>\n $fetch<{ object: DbClientObject<TClientAttributes> }>(\n pluginPath(\"db\", \"object\"),\n { method: \"GET\", query: input, ...call(options) },\n ),\n updateObject: (input, options) =>\n $fetch<{ object: DbClientObject<TClientAttributes> }>(\n pluginPath(\"db\", \"object\"),\n { method: \"PATCH\", body: input, ...call(options) },\n ),\n createFolder: (input, options) =>\n $fetch<{ folder: DbClientFolder }>(pluginPath(\"db\", \"folder\"), {\n method: \"POST\",\n body: input,\n ...call(options),\n }),\n updateFolder: (input, options) =>\n $fetch<{ folder: DbClientFolder }>(pluginPath(\"db\", \"folder\"), {\n method: \"PATCH\",\n body: input,\n ...call(options),\n }),\n deleteFolder: (input, options) =>\n $fetch<{ id: string }>(pluginPath(\"db\", \"folder\"), {\n method: \"DELETE\",\n query: input,\n ...call(options),\n }),\n }),\n });\n}\n","import { s3Error } from \"@dimah-s3/core\";\n\n/**\n * Logical folder paths. A path is NFC-normalized and `/`-separated, with no\n * leading or trailing `/`. `null` is the root. The wire addresses a folder\n * by id; the path is the cached label of that id.\n */\n\n/** Longest folder path, in characters. */\nexport const FOLDER_PATH_MAX_LENGTH = 1024;\n\n/** Longest folder name (one path segment), in characters. */\nexport const FOLDER_NAME_MAX_LENGTH = 255;\n\n/** Most segments in a folder path. Each one is a row the server keeps. */\nexport const FOLDER_MAX_DEPTH = 32;\n\n/** Control characters and lone surrogates. */\nconst INVALID_CHARACTER = /[\\p{Cc}\\p{Cs}]/u;\n\n/** Counts code points, so a character outside the BMP counts once. */\nfunction characterCount(value: string): number {\n return Array.from(value).length;\n}\n\n/** True when `name` can be one segment of a folder path. */\nexport function isFolderName(name: string): boolean {\n const length = characterCount(name);\n return (\n length >= 1 &&\n length <= FOLDER_NAME_MAX_LENGTH &&\n name !== \".\" &&\n name !== \"..\" &&\n !name.includes(\"/\") &&\n !INVALID_CHARACTER.test(name)\n );\n}\n\n/**\n * Returns the NFC form of `path`, or `null` when it is not a valid folder\n * path. The root (`\"\"`) is not a folder path.\n */\nexport function normalizeFolderPath(path: string): string | null {\n if (!path.isWellFormed()) return null;\n const normalized = path.normalize(\"NFC\");\n if (characterCount(normalized) > FOLDER_PATH_MAX_LENGTH) return null;\n const names = normalized.split(\"/\");\n if (names.length > FOLDER_MAX_DEPTH) return null;\n return names.every(isFolderName) ? normalized : null;\n}\n\n/**\n * Reads a wire folder value. `\"\"` is the root and returns `null`.\n * @throws `FOLDER_INVALID` when the value is not a valid folder path.\n */\nexport function parseFolder(value: string): string | null {\n if (value === \"\") return null;\n const path = normalizeFolderPath(value);\n if (path === null) throw s3Error(\"FOLDER_INVALID\");\n return path;\n}\n\n/** Writes a folder for the wire. The root becomes `\"\"`. */\nexport function formatFolder(folder: string | null): string {\n return folder ?? \"\";\n}\n\n/**\n * The path of `name` inside `parent`. `null` when `name` is not a folder\n * name or the joined path is too long or too deep.\n */\nexport function childFolderPath(\n parent: string | null,\n name: string,\n): string | null {\n if (!isFolderName(name)) return null;\n return normalizeFolderPath(joinFolderPath(parent, name));\n}\n\n/** Appends `name` to `parent`. The result is not validated. */\nexport function joinFolderPath(parent: string | null, name: string): string {\n return parent === null ? name : `${parent}/${name}`;\n}\n\n/** The folder that contains `path`. `null` for a top-level folder. */\nexport function parentFolderPath(path: string): string | null {\n const index = path.lastIndexOf(\"/\");\n return index === -1 ? null : path.slice(0, index);\n}\n\n/** The last segment of `path`. */\nexport function folderName(path: string): string {\n return path.slice(path.lastIndexOf(\"/\") + 1);\n}\n\n/** Every folder from the top level down to `path` itself. */\nexport function folderAncestors(path: string): string[] {\n const segments = path.split(\"/\");\n return segments.map((_, index) => segments.slice(0, index + 1).join(\"/\"));\n}\n","import { s3Error } from \"@dimah-s3/core\";\nimport { isFolderName } from \"@/folder-path\";\nimport type {\n DbClientActions,\n DbClientListInput,\n DbClientObject,\n DbListSort,\n DbListSortField,\n DbObjectSource,\n DbObjectSourceFile,\n DbObjectSourceOptions,\n DbObjectSourceQueryInput,\n} from \"@/types/client\";\n\n/** The `api.db` actions {@link dbObjectSource} calls. */\nexport type DbObjectSourceActions<TClientAttributes = never> = Pick<\n DbClientActions<TClientAttributes>,\n \"listObjects\"\n> &\n Partial<\n Pick<\n DbClientActions<TClientAttributes>,\n \"createFolder\" | \"updateObject\" | \"updateFolder\"\n >\n >;\n\n/** List sort fields and the `listObjects` columns they order by. */\nconst SORT_FIELDS = new Map<string, DbListSortField>([\n [\"name\", \"filename\"],\n [\"size\", \"size\"],\n [\"updatedAt\", \"updatedAt\"],\n]);\n\nfunction toListSort(\n sort: DbObjectSourceQueryInput[\"sort\"],\n): DbListSort | undefined {\n const field = sort ? SORT_FIELDS.get(sort.field) : undefined;\n return sort && field ? { field, direction: sort.direction } : undefined;\n}\n\nfunction toFile(object: DbClientObject<unknown>): DbObjectSourceFile {\n return {\n name: object.filename,\n objectKey: object.key,\n size: object.size,\n contentType: object.contentType,\n updatedAt: object.updatedAt,\n };\n}\n\n/**\n * A `useObjectList` source over `api.db`.\n *\n * With `folders` on (the default), `parent` is a folder id: each page lists\n * one folder, the first page carries its child folders and the breadcrumb\n * trail, uploads go to the open folder, and \"New folder\" calls\n * `api.db.createFolder`. Rename calls `api.db.updateObject` (`filename`) or\n * `api.db.updateFolder` (`name`) and leaves the object key as it is. With\n * `folders: false`, the list is flat: file rename stays, and folder actions\n * do not.\n *\n * `search` matches the filename on the server. `sort` maps `name` to\n * `filename`; `size` and `updatedAt` keep their names, and other fields keep\n * the server's order (newest first). `usage` is the scope total with its\n * caps, not the open folder's.\n *\n * ```ts\n * const list = useObjectList({\n * ...dbObjectSource(api.db, { route: \"docs\" }),\n * queryKey: [\"docs\"],\n * });\n * ```\n */\nexport function dbObjectSource<TClientAttributes = never>(\n db: DbObjectSourceActions<TClientAttributes>,\n options: DbObjectSourceOptions = {},\n): DbObjectSource<TClientAttributes> {\n const folders = options.folders !== false;\n\n const source: DbObjectSource<TClientAttributes> = {\n getKey: (item) => item.id,\n getFile: toFile,\n async query({ parent, cursor, sort, search, signal }) {\n const input: DbClientListInput = {};\n if (folders) input.folderId = parent ?? \"\";\n if (cursor) input.cursor = cursor;\n if (search) input.search = search;\n const listSort = toListSort(sort);\n if (listSort) input.sort = listSort;\n if (options.route) input.route = options.route;\n if (options.status) input.status = options.status;\n if (options.contentType) input.contentType = options.contentType;\n if (options.limit !== undefined) input.limit = options.limit;\n\n const page = await db.listObjects(input, { signal });\n return {\n items: page.objects,\n nextCursor: page.nextCursor,\n ...(page.folders && {\n folders: page.folders.map((folder) => ({\n id: folder.id,\n name: folder.name,\n })),\n }),\n ...(page.trail && {\n trail: page.trail.map((folder) => ({\n id: folder.id,\n name: folder.name,\n })),\n }),\n ...(page.usage && { usage: { ...page.usage, ...page.limits } }),\n };\n },\n };\n\n const updateObject = db.updateObject?.bind(db);\n if (updateObject) {\n source.renameFile = async ({ item, name }) => {\n const { object } = await updateObject({\n key: item.key,\n bucket: item.bucket,\n filename: name,\n });\n return object;\n };\n }\n if (!folders) return source;\n\n source.uploadOptions = (parent) => ({\n metadata: { folderId: parent ?? \"\" },\n });\n const createFolder = db.createFolder?.bind(db);\n if (createFolder) {\n source.createFolder = async ({ parent, name }) => {\n // A `/` would be a nested path. The server creates one folder.\n if (!isFolderName(name)) throw s3Error(\"FOLDER_INVALID\");\n const { folder } = await createFolder({\n parentId: parent,\n name,\n });\n return { id: folder.id, name: folder.name };\n };\n }\n const updateFolder = db.updateFolder?.bind(db);\n if (updateFolder) {\n source.renameFolder = async ({ folder, name }) => {\n // A `/` would be a nested path. The server renames one folder.\n if (!isFolderName(name)) throw s3Error(\"FOLDER_INVALID\");\n const { folder: updated } = await updateFolder({\n id: folder.id,\n name,\n });\n return { id: updated.id, name: updated.name };\n };\n }\n return source;\n}\n"]}
1
+ {"version":3,"sources":["../../src/client/db-client.ts","../../src/folder-path.ts","../../src/client/db-object-source.ts"],"names":["s3Error"],"mappings":";;;AAeA,SAAS,KAAK,OAAA,EAAuC;AACnD,EAAA,OAAO,EAAE,MAAA,EAAQ,OAAA,EAAS,MAAA,EAAQ,OAAA,EAAS,SAAS,OAAA,EAAQ;AAC9D;AAGA,SAAS,UAAU,KAAA,EAAsC;AACvD,EAAA,IAAI,KAAA,EAAO,QAAA,KAAa,IAAA,EAAM,OAAO,KAAA;AACrC,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,QAAA,EAAU,EAAA,EAAG;AAClC;AAqBO,SAAS,QAAA,GAAsC;AACpD,EAAA,OAAO,kBAAA,CAAmB;AAAA,IACxB,EAAA,EAAI,IAAA;AAAA,IACJ,oBAAoB,EAAC;AAAA,IACrB,UAAA,EAAY,CAAC,MAAA,MAAgD;AAAA,MAC3D,WAAA,EAAa,CAAC,KAAA,EAAO,OAAA,KACnB,MAAA;AAAA,QACE,UAAA,CAAW,MAAM,SAAS,CAAA;AAAA,QAC1B,EAAE,MAAA,EAAQ,KAAA,EAAO,KAAA,EAAO,SAAA,CAAU,KAAK,CAAA,EAAG,GAAG,IAAA,CAAK,OAAO,CAAA;AAAE,OAC7D;AAAA,MACF,SAAA,EAAW,CAAC,KAAA,EAAO,OAAA,KACjB,MAAA;AAAA,QACE,UAAA,CAAW,MAAM,QAAQ,CAAA;AAAA,QACzB,EAAE,QAAQ,KAAA,EAAO,KAAA,EAAO,OAAO,GAAG,IAAA,CAAK,OAAO,CAAA;AAAE,OAClD;AAAA,MACF,YAAA,EAAc,CAAC,KAAA,EAAO,OAAA,KACpB,MAAA;AAAA,Q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A,QAAQ,gBAAgB,CAAA;AACvD,MAAA,MAAM,EAAE,MAAA,EAAQ,OAAA,EAAQ,GAAI,MAAM,YAAA,CAAa;AAAA,QAC7C,IAAI,MAAA,CAAO,EAAA;AAAA,QACX;AAAA,OACD,CAAA;AACD,MAAA,OAAO,EAAE,EAAA,EAAI,OAAA,CAAQ,EAAA,EAAI,IAAA,EAAM,QAAQ,IAAA,EAAK;AAAA,IAC9C,CAAA;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["import {\n defineClientPlugin,\n pluginPath,\n type S3RequestOptions,\n} from \"@dimah-s3/core\";\nimport type { db } from \"@/plugin/db\";\nimport type {\n DbClientActions,\n DbClientFolder,\n DbClientListInput,\n DbClientListResponse,\n DbClientObject,\n} from \"@/types/client\";\n\n/** The per-call options better-fetch reads: the abort signal and headers. */\nfunction call(options: S3RequestOptions | undefined) {\n return { signal: options?.signal, headers: options?.headers };\n}\n\n/** The list query on the wire, where the root folder is `\"\"`. */\nfunction listQuery(input: DbClientListInput | undefined) {\n if (input?.folderId !== null) return input;\n return { ...input, folderId: \"\" };\n}\n\n/**\n * Client plugin for the server `db()` endpoints. Its actions are\n * {@link DbClientActions} on `api.db`. Pass `TClientAttributes` to type the\n * `attributes` the plugin's `attributes.toClient` returns.\n *\n * ```ts\n * import { createS3Client } from \"@dimah-s3/react\";\n * import { dbClient } from \"@dimah-s3/db/client\";\n *\n * export const s3Client = createS3Client({\n * plugins: [dbClient()],\n * });\n *\n * const page = await s3Client.db.listObjects({ folderId: \"\" });\n * ```\n *\n * The server resolves the scope from the request, so no action takes one.\n * Server code skips HTTP and uses `s3.db.objects` and `s3.db.folders`.\n */\nexport function dbClient<TClientAttributes = never>() {\n return defineClientPlugin({\n id: \"db\",\n $InferServerPlugin: {} as ReturnType<typeof db>,\n getActions: ($fetch): DbClientActions<TClientAttributes> => ({\n listObjects: (input, options) =>\n $fetch<DbClientListResponse<TClientAttributes>>(\n pluginPath(\"db\", \"objects\"),\n { method: \"GET\", query: listQuery(input), ...call(options) },\n ),\n getObject: (input, options) =>\n $fetch<{ object: DbClientObject<TClientAttributes> }>(\n pluginPath(\"db\", \"object\"),\n { method: \"GET\", query: input, ...call(options) },\n ),\n updateObject: (input, options) =>\n $fetch<{ object: DbClientObject<TClientAttributes> }>(\n pluginPath(\"db\", \"object\"),\n { method: \"PATCH\", body: input, ...call(options) },\n ),\n createFolder: (input, options) =>\n $fetch<{ folder: DbClientFolder }>(pluginPath(\"db\", \"folder\"), {\n method: \"POST\",\n body: input,\n ...call(options),\n }),\n updateFolder: (input, options) =>\n $fetch<{ folder: DbClientFolder }>(pluginPath(\"db\", \"folder\"), {\n method: \"PATCH\",\n body: input,\n ...call(options),\n }),\n deleteFolder: (input, options) =>\n $fetch<{ id: string }>(pluginPath(\"db\", \"folder\"), {\n method: \"DELETE\",\n query: input,\n ...call(options),\n }),\n }),\n });\n}\n","import { s3Error } from \"@dimah-s3/core\";\n\n/**\n * Logical folder paths. A path is NFC-normalized and `/`-separated, with no\n * leading or trailing `/`. `null` is the root. The wire addresses a folder\n * by id; the path is the cached label of that id.\n */\n\n/**\n * Longest folder path, in UTF-8 bytes, like an S3 key. With the longest scope,\n * the `(scope, path)` unique key stays under PostgreSQL's 2704-byte limit\n * for a btree entry.\n */\nexport const FOLDER_PATH_MAX_BYTES = 1024;\n\n/** Longest folder name (one path segment), in characters. */\nexport const FOLDER_NAME_MAX_LENGTH = 255;\n\n/** Most segments in a folder path. Each one is a row the server keeps. */\nexport const FOLDER_MAX_DEPTH = 32;\n\n/** Control characters and lone surrogates. */\nconst INVALID_CHARACTER = /[\\p{Cc}\\p{Cs}]/u;\n\nconst utf8 = new TextEncoder();\n\n/** Counts code points, so a character outside the BMP counts once. */\nexport function characterCount(value: string): number {\n return Array.from(value).length;\n}\n\n/** True when `name` can be one segment of a folder path. */\nexport function isFolderName(name: string): boolean {\n const length = characterCount(name);\n return (\n length >= 1 &&\n length <= FOLDER_NAME_MAX_LENGTH &&\n name !== \".\" &&\n name !== \"..\" &&\n !name.includes(\"/\") &&\n !INVALID_CHARACTER.test(name)\n );\n}\n\n/**\n * Returns the NFC form of `path`, or `null` when it is not a valid folder\n * path. The root (`\"\"`) is not a folder path.\n */\nexport function normalizeFolderPath(path: string): string | null {\n if (!path.isWellFormed()) return null;\n const normalized = path.normalize(\"NFC\");\n if (utf8.encode(normalized).byteLength > FOLDER_PATH_MAX_BYTES) return null;\n const names = normalized.split(\"/\");\n if (names.length > FOLDER_MAX_DEPTH) return null;\n return names.every(isFolderName) ? normalized : null;\n}\n\n/**\n * Reads a wire folder value. `\"\"` is the root and returns `null`.\n * @throws `FOLDER_INVALID` when the value is not a valid folder path.\n */\nexport function parseFolder(value: string): string | null {\n if (value === \"\") return null;\n const path = normalizeFolderPath(value);\n if (path === null) throw s3Error(\"FOLDER_INVALID\");\n return path;\n}\n\n/** Writes a folder for the wire. The root becomes `\"\"`. */\nexport function formatFolder(folder: string | null): string {\n return folder ?? \"\";\n}\n\n/**\n * The path of `name` inside `parent`. `null` when `name` is not a folder\n * name or the joined path is too long or too deep.\n */\nexport function childFolderPath(\n parent: string | null,\n name: string,\n): string | null {\n if (!isFolderName(name)) return null;\n return normalizeFolderPath(joinFolderPath(parent, name));\n}\n\n/** Appends `name` to `parent`. The result is not validated. */\nexport function joinFolderPath(parent: string | null, name: string): string {\n return parent === null ? name : `${parent}/${name}`;\n}\n\n/** The folder that contains `path`. `null` for a top-level folder. */\nexport function parentFolderPath(path: string): string | null {\n const index = path.lastIndexOf(\"/\");\n return index === -1 ? null : path.slice(0, index);\n}\n\n/** The last segment of `path`. */\nexport function folderName(path: string): string {\n return path.slice(path.lastIndexOf(\"/\") + 1);\n}\n\n/** Every folder from the top level down to `path` itself. */\nexport function folderAncestors(path: string): string[] {\n const segments = path.split(\"/\");\n return segments.map((_, index) => segments.slice(0, index + 1).join(\"/\"));\n}\n","import { s3Error } from \"@dimah-s3/core\";\nimport { isFolderName } from \"@/folder-path\";\nimport type {\n DbClientActions,\n DbClientListInput,\n DbClientObject,\n DbListSort,\n DbListSortField,\n DbObjectSource,\n DbObjectSourceFile,\n DbObjectSourceOptions,\n DbObjectSourceQueryInput,\n} from \"@/types/client\";\n\n/** The `api.db` actions {@link dbObjectSource} calls. */\nexport type DbObjectSourceActions<TClientAttributes = never> = Pick<\n DbClientActions<TClientAttributes>,\n \"listObjects\"\n> &\n Partial<\n Pick<\n DbClientActions<TClientAttributes>,\n \"createFolder\" | \"updateObject\" | \"updateFolder\"\n >\n >;\n\n/** List sort fields and the `listObjects` columns they order by. */\nconst SORT_FIELDS = new Map<string, DbListSortField>([\n [\"name\", \"filename\"],\n [\"size\", \"size\"],\n [\"updatedAt\", \"updatedAt\"],\n]);\n\nfunction toListSort(\n sort: DbObjectSourceQueryInput[\"sort\"],\n): DbListSort | undefined {\n const field = sort ? SORT_FIELDS.get(sort.field) : undefined;\n return sort && field ? { field, direction: sort.direction } : undefined;\n}\n\nfunction toFile(object: DbClientObject<unknown>): DbObjectSourceFile {\n return {\n name: object.filename,\n objectKey: object.key,\n size: object.size,\n contentType: object.contentType,\n updatedAt: object.updatedAt,\n };\n}\n\n/**\n * A `useObjectList` source over `api.db`.\n *\n * With `folders` on (the default), `parent` is a folder id: each page lists\n * one folder, the first page carries its child folders and the breadcrumb\n * trail, uploads go to the open folder, and \"New folder\" calls\n * `api.db.createFolder`. Rename calls `api.db.updateObject` (`filename`) or\n * `api.db.updateFolder` (`name`) and leaves the object key as it is. With\n * `folders: false`, the list is flat: file rename stays, and folder actions\n * do not.\n *\n * `search` matches the filename on the server. `sort` maps `name` to\n * `filename`; `size` and `updatedAt` keep their names, and other fields keep\n * the server's order (newest first). `usage` is the scope total with its\n * caps, not the open folder's.\n *\n * ```ts\n * const list = useObjectList({\n * ...dbObjectSource(api.db, { route: \"docs\" }),\n * queryKey: [\"docs\"],\n * });\n * ```\n */\nexport function dbObjectSource<TClientAttributes = never>(\n db: DbObjectSourceActions<TClientAttributes>,\n options: DbObjectSourceOptions = {},\n): DbObjectSource<TClientAttributes> {\n const folders = options.folders !== false;\n\n const source: DbObjectSource<TClientAttributes> = {\n getKey: (item) => item.id,\n getFile: toFile,\n async query({ parent, cursor, sort, search, signal }) {\n const input: DbClientListInput = {};\n if (folders) input.folderId = parent ?? \"\";\n if (cursor) input.cursor = cursor;\n if (search) input.search = search;\n const listSort = toListSort(sort);\n if (listSort) input.sort = listSort;\n if (options.route) input.route = options.route;\n if (options.status) input.status = options.status;\n if (options.contentType) input.contentType = options.contentType;\n if (options.limit !== undefined) input.limit = options.limit;\n\n const page = await db.listObjects(input, { signal });\n return {\n items: page.objects,\n nextCursor: page.nextCursor,\n ...(page.folders && {\n folders: page.folders.map((folder) => ({\n id: folder.id,\n name: folder.name,\n })),\n }),\n ...(page.trail && {\n trail: page.trail.map((folder) => ({\n id: folder.id,\n name: folder.name,\n })),\n }),\n ...(page.usage && { usage: { ...page.usage, ...page.limits } }),\n };\n },\n };\n\n const updateObject = db.updateObject?.bind(db);\n if (updateObject) {\n source.renameFile = async ({ item, name }) => {\n const { object } = await updateObject({\n key: item.key,\n bucket: item.bucket,\n filename: name,\n });\n return object;\n };\n }\n if (!folders) return source;\n\n source.uploadOptions = (parent) => ({\n metadata: { folderId: parent ?? \"\" },\n });\n const createFolder = db.createFolder?.bind(db);\n if (createFolder) {\n source.createFolder = async ({ parent, name }) => {\n // A `/` would be a nested path. The server creates one folder.\n if (!isFolderName(name)) throw s3Error(\"FOLDER_INVALID\");\n const { folder } = await createFolder({\n parentId: parent,\n name,\n });\n return { id: folder.id, name: folder.name };\n };\n }\n const updateFolder = db.updateFolder?.bind(db);\n if (updateFolder) {\n source.renameFolder = async ({ folder, name }) => {\n // A `/` would be a nested path. The server renames one folder.\n if (!isFolderName(name)) throw s3Error(\"FOLDER_INVALID\");\n const { folder: updated } = await updateFolder({\n id: folder.id,\n name,\n });\n return { id: updated.id, name: updated.name };\n };\n }\n return source;\n}\n"]}
@@ -3,12 +3,18 @@
3
3
  * leading or trailing `/`. `null` is the root. The wire addresses a folder
4
4
  * by id; the path is the cached label of that id.
5
5
  */
6
- /** Longest folder path, in characters. */
7
- export declare const FOLDER_PATH_MAX_LENGTH = 1024;
6
+ /**
7
+ * Longest folder path, in UTF-8 bytes, like an S3 key. With the longest scope,
8
+ * the `(scope, path)` unique key stays under PostgreSQL's 2704-byte limit
9
+ * for a btree entry.
10
+ */
11
+ export declare const FOLDER_PATH_MAX_BYTES = 1024;
8
12
  /** Longest folder name (one path segment), in characters. */
9
13
  export declare const FOLDER_NAME_MAX_LENGTH = 255;
10
14
  /** Most segments in a folder path. Each one is a row the server keeps. */
11
15
  export declare const FOLDER_MAX_DEPTH = 32;
16
+ /** Counts code points, so a character outside the BMP counts once. */
17
+ export declare function characterCount(value: string): number;
12
18
  /** True when `name` can be one segment of a folder path. */
13
19
  export declare function isFolderName(name: string): boolean;
14
20
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"folder-path.d.ts","sourceRoot":"","sources":["../src/folder-path.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH,0CAA0C;AAC1C,eAAO,MAAM,sBAAsB,OAAO,CAAC;AAE3C,6DAA6D;AAC7D,eAAO,MAAM,sBAAsB,MAAM,CAAC;AAE1C,0EAA0E;AAC1E,eAAO,MAAM,gBAAgB,KAAK,CAAC;AAUnC,4DAA4D;AAC5D,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAUlD;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAO/D;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAKxD;AAED,2DAA2D;AAC3D,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAE1D;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,MAAM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Gf;AAED,+DAA+D;AAC/D,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAE1E;AAED,sEAAsE;AACtE,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAG5D;AAED,kCAAkC;AAClC,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C;AAED,6DAA6D;AAC7D,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAGtD"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
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
4
  import { s3Error, pluginPath, base64UrlDecode, base64UrlEncode } from '@dimah-s3/core';
@@ -10,13 +10,14 @@ import { AbortMultipartUploadCommand, HeadObjectCommand } from '@aws-sdk/client-
10
10
  var BINARY = { mysql: "utf8mb4_bin" };
11
11
  var TEXT = { mysql: "utf8mb4_unicode_ci" };
12
12
  var LONG_PREFIX = 512;
13
+ var SCOPE_MAX_LENGTH = 255;
13
14
  function string(name, length = 255) {
14
15
  return column(name, `varchar(${length})`).collate(BINARY);
15
16
  }
16
17
  var storageObject = table("storage_object", {
17
18
  id: idColumn("id", "varchar(255)").collate(BINARY).defaultTo$("auto"),
18
19
  /** Owner, for example `user:123` or `org:acme`. */
19
- scope: string("scope"),
20
+ scope: string("scope", SCOPE_MAX_LENGTH),
20
21
  bucket: string("bucket"),
21
22
  key: string("key", 1024),
22
23
  /** Named dimah-s3 route that created the object. */
@@ -56,7 +57,7 @@ var storageObject = table("storage_object", {
56
57
  ]).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"]);
57
58
  var storageFolder = table("storage_folder", {
58
59
  id: idColumn("id", "varchar(255)").collate(BINARY).defaultTo$("auto"),
59
- scope: string("scope"),
60
+ scope: string("scope", SCOPE_MAX_LENGTH),
60
61
  /** Id of the containing folder. `""` is the root. */
61
62
  parentId: string("parent_id").defaultTo(""),
62
63
  /** Last segment of `path`. */
@@ -82,10 +83,11 @@ var DimahS3DB = fumadb({
82
83
  schemas: [dbSchema]
83
84
  });
84
85
  var DB_SCHEMA_VERSION = dbSchema.version;
85
- var FOLDER_PATH_MAX_LENGTH = 1024;
86
+ var FOLDER_PATH_MAX_BYTES = 1024;
86
87
  var FOLDER_NAME_MAX_LENGTH = 255;
87
88
  var FOLDER_MAX_DEPTH = 32;
88
89
  var INVALID_CHARACTER = /[\p{Cc}\p{Cs}]/u;
90
+ var utf8 = new TextEncoder();
89
91
  function characterCount(value) {
90
92
  return Array.from(value).length;
91
93
  }
@@ -96,7 +98,7 @@ function isFolderName(name) {
96
98
  function normalizeFolderPath(path) {
97
99
  if (!path.isWellFormed()) return null;
98
100
  const normalized = path.normalize("NFC");
99
- if (characterCount(normalized) > FOLDER_PATH_MAX_LENGTH) return null;
101
+ if (utf8.encode(normalized).byteLength > FOLDER_PATH_MAX_BYTES) return null;
100
102
  const names = normalized.split("/");
101
103
  if (names.length > FOLDER_MAX_DEPTH) return null;
102
104
  return names.every(isFolderName) ? normalized : null;
@@ -440,7 +442,7 @@ function createObjectStore(getOrm) {
440
442
  try {
441
443
  await orm.create("storageObject", fresh);
442
444
  } catch (error) {
443
- if (await find(ref)) throw s3Error("CONFLICT");
445
+ if (error instanceof UniqueConstraintError) throw s3Error("CONFLICT");
444
446
  throw error;
445
447
  }
446
448
  };
@@ -618,19 +620,6 @@ function createObjectStore(getOrm) {
618
620
 
619
621
  // src/store/folder-store.ts
620
622
  var DEFAULT_FOLDER_CHILDREN_LIMIT = 1e3;
621
- function isUniqueViolation(error) {
622
- for (let current = error; typeof current === "object" && current !== null; ) {
623
- const code = "code" in current ? String(current.code) : "";
624
- if (code === "23505" || code === "ER_DUP_ENTRY" || code === "P2002") {
625
- return true;
626
- }
627
- if (current instanceof Error && /unique/i.test(current.message)) {
628
- return true;
629
- }
630
- current = "cause" in current ? current.cause : void 0;
631
- }
632
- return false;
633
- }
634
623
  function storedParent(parentId) {
635
624
  return parentId ?? "";
636
625
  }
@@ -656,17 +645,6 @@ function createFolderStore(getOrm) {
656
645
  });
657
646
  return row ? mapFolder(row) : null;
658
647
  };
659
- const findNamed = async (scope, parentId, name) => {
660
- const orm = await getOrm();
661
- const row = await orm.findFirst("storageFolder", {
662
- where: (b) => b.and(
663
- b("scope", "=", scope),
664
- b("parentId", "=", storedParent(parentId)),
665
- b("name", "=", name)
666
- )
667
- });
668
- return row ? mapFolder(row) : null;
669
- };
670
648
  const insertFolder = async (orm, folder) => {
671
649
  const now = /* @__PURE__ */ new Date();
672
650
  const row = await orm.create("storageFolder", {
@@ -727,7 +705,9 @@ function createFolderStore(getOrm) {
727
705
  try {
728
706
  await insertFolder(orm, folder);
729
707
  } catch (error) {
730
- if (await find(folder.scope, folder.id)) return;
708
+ if (error instanceof UniqueConstraintError && await find(folder.scope, folder.id)) {
709
+ return;
710
+ }
731
711
  throw error;
732
712
  }
733
713
  };
@@ -775,7 +755,7 @@ function createFolderStore(getOrm) {
775
755
  path
776
756
  });
777
757
  } catch (error) {
778
- if (await findNamed(scope, input.parentId, name)) {
758
+ if (error instanceof UniqueConstraintError) {
779
759
  throw s3Error("FOLDER_EXISTS");
780
760
  }
781
761
  throw error;
@@ -814,7 +794,9 @@ function createFolderStore(getOrm) {
814
794
  }
815
795
  });
816
796
  } catch (error) {
817
- if (isUniqueViolation(error)) throw s3Error("FOLDER_EXISTS");
797
+ if (error instanceof UniqueConstraintError) {
798
+ throw s3Error("FOLDER_EXISTS");
799
+ }
818
800
  throw error;
819
801
  }
820
802
  for (const child of rewritten) {
@@ -1030,7 +1012,7 @@ function toDbClientFolder(folder) {
1030
1012
 
1031
1013
  // src/plugin/create-database-endpoints.ts
1032
1014
  var DEFAULT_ATTRIBUTES_MAX_BYTES = 16384;
1033
- var utf8 = new TextEncoder();
1015
+ var utf82 = new TextEncoder();
1034
1016
  function resolveBucket(config, bucket, field) {
1035
1017
  const buckets = /* @__PURE__ */ new Set();
1036
1018
  for (const route of Object.values(config.routes)) {
@@ -1081,7 +1063,7 @@ function createDatabaseEndpoints(options) {
1081
1063
  });
1082
1064
  }
1083
1065
  const maxBytes = attributes.maxBytes ?? DEFAULT_ATTRIBUTES_MAX_BYTES;
1084
- const size = utf8.encode(JSON.stringify(result.value)).byteLength;
1066
+ const size = utf82.encode(JSON.stringify(result.value)).byteLength;
1085
1067
  if (size > maxBytes) {
1086
1068
  throw s3Error("VALIDATION_ERROR", {
1087
1069
  issue: `[body.attributes] Exceeds ${maxBytes} bytes`
@@ -1708,6 +1690,12 @@ function createScopeResolver(options) {
1708
1690
  }
1709
1691
  const resolved = await scope;
1710
1692
  if (resolved === null) throw s3Error("UNAUTHORIZED");
1693
+ const length = characterCount(resolved);
1694
+ if (length > SCOPE_MAX_LENGTH) {
1695
+ throw new Error(
1696
+ `[dimah-s3/db] resolveScope returned a scope of ${length} characters. A scope holds at most ${SCOPE_MAX_LENGTH}.`
1697
+ );
1698
+ }
1711
1699
  return { ...context, scope: resolved };
1712
1700
  };
1713
1701
  }