cloudrop 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,86 @@ Every notable change to the `cloudrop` package. The format follows
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.2.0 - 2026-11-20
10
+
11
+ ### Added
12
+
13
+ - **`client.close()`** stops a client: every running and queued upload of every route stops, and `start()`,
14
+ `upload()` and `resume()` answer the new error code `CLIENT_CLOSED` afterwards. Without options it acts like closing
15
+ the tab: a multipart upload keeps its record and its parts, so the same user can resume it. `close({ abort: true })`
16
+ cancels on the server too, for sign-out: `await close({ abort: true })`, then `forget()`, then your auth library's
17
+ sign-out. A file whose `/complete` may have finished is always kept. `createUploadHooks()` returns the same `close()`
18
+ (`M8-L1` to `M8-L4`, `M8-L7`).
19
+ - **`headers` client option** for requests to the upload server only (`/upload`, `/sign`, `/complete`, `/abort`),
20
+ never for bucket `PUT`s: an object, or a function (possibly async) called before each request, so a bearer token is
21
+ fresh on each. A function that fails or hangs fails that request unsent with `NETWORK_ERROR` (`M8-L5`, `M8-L6`).
22
+ - **`useResumable().discarding`**: the ids being discarded, to disable a second press of Discard (`M8-L8`).
23
+ - **`api.files({ owner, route?, limit?, cursor? })`**: an owner's completed files, newest first, a page at a time
24
+ (`M8-A1`).
25
+ - **`api.eraseOwner(owner, { graceMs?, signal? })`** removes everything an owner uploaded without needing your key
26
+ layout: it revokes unfinished uploads, deletes completed files and reports `done` once nothing can still land. Run it
27
+ until it reports `done` (`M8-A5`).
28
+ - **Route option `replace: true`** (needs a store and `owner`): one file per owner on the route, such as an avatar. The
29
+ previous file is deleted in the same write that records the next one's completion, and of two completions at once
30
+ exactly one file survives. Read the kept file with `api.files({ owner, route, limit: 1 })` (`M8-A6`).
31
+ - **`api.sweep({ all: true, signal? })`** runs every page in one call and sums the reports; the store guide has cron
32
+ recipes for Node and Cloudflare Workers (`M8-A7`).
33
+ - Exported types `FilesOptions`, `FilesPage`, `EraseOptions`, `EraseReport` and `Completion`.
34
+
35
+ ### Changed
36
+
37
+ - **Type-level breaks:** `CloudropErrorCode` and `ClientErrorCode` gain `CLIENT_CLOSED`, which breaks an exhaustive
38
+ `switch` over them. New members break a hand-written mock: `CloudropClient.close()`, `UploadHooks.close()`,
39
+ `UseResumable.discarding`, and `FileApi`/`StoreFileApi`'s `files()` and `eraseOwner()`.
40
+ - **A store written by hand** must implement the new `CloudropStore.list()`, and `complete()` takes `{ replace }` and
41
+ answers `Completion` with `replaced`. Every shipped adapter does (`M8-A3`).
42
+ - `api.deleteFile` deletes the object at once and marks the row cleaned only once a late `PUT` can no longer land
43
+ (about 1 h 15 min after completion); until then the sweep checks the key again. The sweep follows the same rule: it
44
+ marks an ended row cleaned, and counts it in `cleaned`, only once no upload URL of the row can still put an object
45
+ back, and stamps `cleaned_at` with the time its check started (`M8-A4`).
46
+ - The React "Signed-in users" recipe, the guides and the Vite example use `close()` instead of each route's `abort`.
47
+ "Send a bearer token" uses `headers`.
48
+
49
+ ### Fixed
50
+
51
+ - A bearer token no longer needs a custom `fetch`, which moved bucket `PUT`s off `XMLHttpRequest` and its byte-by-byte
52
+ progress.
53
+ - A file still waiting for its ticket can no longer ask `/upload` after sign-out.
54
+ - The sweep could mark a row cleaned up to 15 minutes before its last upload URL ran out when the row ended soon after
55
+ it left `pending` (an `/abort` or a revoke right after `/upload`), so a slow `PUT` landing then stayed in the bucket
56
+ (`M8-A4`).
57
+ - Without a store, `/complete` sends `data: null` when `onComplete` returns a value JSON cannot carry (a function, a
58
+ Symbol); the answer used to have no `data`, which the client refused (`M8-Q34`).
59
+
60
+ ### Migration
61
+
62
+ - **Database store:** the owner index becomes `(owner, status, created_at)`, which `api.files` and `eraseOwner` read:
63
+ `CREATE INDEX "cloudrop_files_owner_status_created_at_idx" ON "cloudrop_files" (owner, status, created_at); DROP
64
+ INDEX "cloudrop_files_owner_status_idx";` (`CONCURRENTLY` on a large Postgres table). Drizzle and Prisma users
65
+ generate a migration; when drizzle-kit asks whether the new index renames the old one, answer that it is created.
66
+ With `tables.schema` or your own table names, use those names. Without the migration the store works, only slower
67
+ for owners with many files (`M8-A2`).
68
+
69
+ ## 0.1.1 - 2026-11-20
70
+
71
+ ### Fixed
72
+
73
+ - **R2: a text, JSON, HTML or SVG file of 50 bytes or more failed at `/complete` with `502 STORAGE_ERROR`** ("The
74
+ storage service's response had no content length"), after its bytes had reached the bucket. R2 compresses its answer
75
+ to the `HEAD` request that reads the stored size when the request offers gzip, as Node's and Bun's `fetch` do, and
76
+ then sends no `Content-Length`. The driver now asks for an uncompressed answer on every `HEAD`, which also fixes
77
+ `/abort`, the store's sweep and `api.head` on such files, for `r2()` and for `s3()` pointed at R2. Applications that
78
+ set `accept-encoding: identity` in a `fetch` of their own can drop it.
79
+
80
+ ### Documentation
81
+
82
+ - **Signed-in users in React:** the React guide shows a client per user, in a context keyed by the user, and a sign-out
83
+ that cancels every route's uploads before `forget()`: `forget()` stops nothing, and a file that gets its ticket
84
+ afterwards saves a new record and, once the session changed, asks `/upload` with the next user's session. The Vite
85
+ example's sign-out now does the same.
86
+ - **What "`onComplete` once" means:** at least once without a store; with one, once under a lease, and exactly once only
87
+ for writes through `tx` on Postgres with `transaction: true`. Keep an email or a webhook idempotent.
88
+
9
89
  ## 0.1.0 - 2026-11-19
10
90
 
11
91
  The first release. Version `0.0.0` on npm only reserved the name.
package/README.md CHANGED
@@ -70,9 +70,17 @@ export function AvatarPicker() {
70
70
 
71
71
  Without React, `createCloudropClient` from `cloudrop/client` gives you `upload()`, which resolves to `{ data, error }`.
72
72
 
73
- To keep a row per upload in your own database, with `onComplete` once per file, a quota per user, revocation and a
74
- sweep for abandoned uploads, pass a store from `cloudrop/adapters/sql`, `cloudrop/adapters/drizzle` or
75
- `cloudrop/adapters/prisma`: [Database store](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/store.md).
73
+ When users sign in, give each user a client of their own, and at sign-out `await close({ abort: true })` before
74
+ `forget()`: [Signed-in users](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/react.md#signed-in-users). A
75
+ bearer token for your API goes in the client's `headers` option, which never reaches the bucket.
76
+
77
+ `onComplete` runs at least once per file: a client that lost the answer to `/complete` asks again, so make it
78
+ idempotent before it sends an email or calls a webhook. To keep a row per upload in your own database, with a quota per
79
+ user, revocation, a listing of each user's files, one file per user on routes such as avatars (`replace: true`),
80
+ erasure of a user's files (`api.eraseOwner`) and a sweep for abandoned uploads, pass a store from `cloudrop/adapters/sql`,
81
+ `cloudrop/adapters/drizzle` or `cloudrop/adapters/prisma`. With a store, `onComplete` runs once per file, except after a
82
+ crash, a throw or a run longer than its lease; only its writes through `tx` on Postgres with `transaction: true` commit
83
+ exactly once: [Database store](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/store.md#what-it-guarantees).
76
84
 
77
85
  ## Bucket setup
78
86
 
@@ -1,4 +1,4 @@
1
- import { a as FileStatus, c as TransactionalStore, n as CloudropStore } from "../store-BfCJejGh.js";
1
+ import { l as TransactionalStore, n as CloudropStore, o as FileStatus } from "../store-B539nY3J.js";
2
2
  import { t as StoreTables } from "../tables-DZnw2sPK.js";
3
3
  import { r as SqlRow } from "../executor-CEA7WV2W.js";
4
4
  import { SQL } from "drizzle-orm";
@@ -1,5 +1,5 @@
1
1
  import { n as configError } from "../errors-CUxMmFAe.js";
2
- import { i as sequential, n as sqlStore, r as tableNames, t as withRoute } from "../transactional-DnvnGsVH.js";
2
+ import { i as sequential, n as sqlStore, r as tableNames, t as withRoute } from "../transactional-CiNwMiDb.js";
3
3
  import { t as d1Executor } from "../d1-BY2c5bcL.js";
4
4
  import { sql } from "drizzle-orm";
5
5
  import { PgSchema, bigint, check, index, integer, pgTable, text, timestamp } from "drizzle-orm/pg-core";
@@ -135,7 +135,7 @@ function cloudropPgTables(options = {}) {
135
135
  index(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),
136
136
  index(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),
137
137
  index(`${names.files}_status_cleaned_at_ended_at_idx`).on(t.status, t.cleanedAt, t.endedAt),
138
- index(`${names.files}_owner_status_idx`).on(t.owner, t.status),
138
+ index(`${names.files}_owner_status_created_at_idx`).on(t.owner, t.status, t.createdAt),
139
139
  index(`${names.files}_key_idx`).on(t.key),
140
140
  index(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey)
141
141
  ]),
@@ -184,7 +184,7 @@ function cloudropSqliteTables(options = {}) {
184
184
  index$1(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),
185
185
  index$1(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),
186
186
  index$1(`${names.files}_status_cleaned_at_ended_at_idx`).on(t.status, t.cleanedAt, t.endedAt),
187
- index$1(`${names.files}_owner_status_idx`).on(t.owner, t.status),
187
+ index$1(`${names.files}_owner_status_created_at_idx`).on(t.owner, t.status, t.createdAt),
188
188
  index$1(`${names.files}_key_idx`).on(t.key),
189
189
  index$1(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey)
190
190
  ]),
@@ -1 +1 @@
1
- {"version":3,"file":"drizzle.js","names":["time","count","text","integer","index"],"sources":["../../src/adapters/drizzle/statement.ts","../../src/adapters/drizzle/postgres.ts","../../src/adapters/drizzle/sqlite.ts","../../src/adapters/drizzle/postgres-tables.ts","../../src/adapters/drizzle/sqlite-tables.ts","../../src/adapters/drizzle.ts"],"sourcesContent":["// A core statement as Drizzle SQL. Drizzle's `sql.raw` takes no parameters, so the text is cut at each placeholder the\n// core's binder wrote (store/sql/bind.ts) and every placeholder becomes a Drizzle parameter; Drizzle numbers them\n// again as it renders, `$1`, `$2`… on Postgres and `?` on SQLite, and the `::type` casts after them stay in the text.\n\nimport { type SQL, type SQLChunk, sql } from \"drizzle-orm\";\nimport type { SqlDialect, SqlStatement } from \"../../store/sql/executor.ts\";\n\nconst PLACEHOLDER: Record<SqlDialect, RegExp> = { postgres: /\\$(\\d+)/g, sqlite: /\\?/g };\n\nexport function drizzleSql(dialect: SqlDialect, { sql: text, params }: SqlStatement): SQL {\n const chunks: SQLChunk[] = [];\n let end = 0;\n for (const [position, match] of [...text.matchAll(PLACEHOLDER[dialect])].entries()) {\n // `$n` names its parameter; SQLite's `?` takes the next one.\n const value = params[match[1] === undefined ? position : Number(match[1]) - 1];\n chunks.push(sql.raw(text.slice(end, match.index)), sql.param(value));\n end = match.index + match[0].length;\n }\n chunks.push(sql.raw(text.slice(end)));\n return sql.join(chunks);\n}\n","// Drizzle on Postgres: statements through `execute`, batches and transactions through `db.transaction`. The database is\n// described by the two members used here, so any Drizzle Postgres driver fits and the library needs no Drizzle types\n// beyond `SQL`; drizzle.db.integration.test.ts runs it on node-postgres and postgres.js.\n\nimport type { SQL } from \"drizzle-orm\";\nimport { configError } from \"../../errors.ts\";\nimport { type SqlRow, type SqlStatement, sequential, type TransactionalSqlExecutor } from \"../../store/sql/executor.ts\";\nimport { drizzleSql } from \"./statement.ts\";\n\n/** What the store calls on a Drizzle Postgres database or transaction. */\nexport interface DrizzlePostgresQueryable {\n execute(query: SQL): PromiseLike<unknown>;\n}\n\n/** A Drizzle Postgres database: `drizzle(pool)` from `drizzle-orm/node-postgres`, `drizzle-orm/postgres-js`, … */\nexport interface DrizzlePostgres extends DrizzlePostgresQueryable {\n transaction<T>(run: (tx: DrizzlePostgresQueryable) => Promise<T>): Promise<T>;\n}\n\n/** The `tx` Drizzle hands to `db.transaction`'s callback, for this database's driver and schema. */\nexport type DrizzleTransaction<TDb extends DrizzlePostgres> = Parameters<Parameters<TDb[\"transaction\"]>[0]>[0];\n\n/** How a result looked, for the message: its keys, never its values. */\nconst shapeOf = (result: unknown): string =>\n typeof result === \"object\" && result !== null ? `{ ${Object.keys(result).join(\", \")} }` : typeof result;\n\n/** node-postgres answers `{ rows }`, postgres.js the rows themselves. */\nasync function rowsOf(target: DrizzlePostgresQueryable, statement: SqlStatement): Promise<SqlRow[]> {\n const result = await target.execute(drizzleSql(\"postgres\", statement));\n if (Array.isArray(result)) return result;\n const { rows } = (result ?? {}) as { rows?: unknown };\n if (Array.isArray(rows)) return rows;\n throw configError(\n `This Drizzle driver's execute() answered ${shapeOf(result)}, not rows or { rows }. Use drizzleStore with node-postgres or postgres.js, or build an executor for cloudrop/adapters/sql.`,\n );\n}\n\n/** The executor's statements on the database or a transaction, in order when batched. */\nconst on = (target: DrizzlePostgresQueryable) =>\n sequential(\"postgres\", (sql, params) => rowsOf(target, { sql, params }));\n\n/**\n * True for a node-postgres client that is not a pool: Drizzle's node-postgres driver checks out a connection for a\n * transaction only from a pool (its own test: the constructor's name contains \"Pool\"), and otherwise runs BEGIN on the\n * client's one connection, which every other request is using too.\n */\nfunction isSingleConnection(db: DrizzlePostgres): boolean {\n const client: unknown = (db as { $client?: unknown }).$client;\n if (typeof client !== \"object\" || client === null) return false;\n const { query, connect } = client as { query?: unknown; connect?: unknown };\n return typeof query === \"function\" && typeof connect === \"function\" && !client.constructor.name.includes(\"Pool\");\n}\n\n/** The executor; its `transaction` runs `onComplete` in a Drizzle transaction whose `tx` the route gets. */\nexport function postgresExecutor(db: DrizzlePostgres): TransactionalSqlExecutor<DrizzlePostgresQueryable> {\n if (isSingleConnection(db)) {\n throw configError(\n \"drizzleStore needs a pg Pool, not a single pg Client: a transaction on the one shared connection would take every other request's statements with it. Pass drizzle(new Pool({ connectionString })), or use postgres.js.\",\n );\n }\n return {\n ...on(db),\n batch: (statements) => db.transaction((tx) => on(tx).batch(statements)),\n transaction: (run) => db.transaction((tx) => run(on(tx), tx)),\n };\n}\n","// Drizzle on SQLite, through `all` and `run`. A synchronous driver (better-sqlite3) runs a batch in\n// `db.transaction(…, { behavior: \"immediate\" })`, which ends before any other call can start. An asynchronous one with\n// an atomic batch (libsql/Turso) runs it through `db.batch`, ordered and all-or-nothing. D1 runs through the binding\n// Drizzle keeps as `db.$client`, as `d1Executor` does: drizzle-orm 0.45's D1 `batch` cannot take a raw statement with\n// parameters (it reads a `stmt` that `db.run(sql)` never prepares; measured in the Wrangler lane). None has transaction\n// mode: an interactive transaction would hold the only writer across `onComplete`'s awaits.\n\nimport type { SQL } from \"drizzle-orm\";\nimport type { BatchItem } from \"drizzle-orm/batch\";\nimport type { SqlExecutor, SqlRow, SqlStatement } from \"../../store/sql/executor.ts\";\nimport { type D1Database, d1Executor } from \"../sql/d1.ts\";\nimport { drizzleSql } from \"./statement.ts\";\n\n/** What the store calls on a synchronous Drizzle SQLite database or transaction. */\nexport interface DrizzleSqliteQueryable {\n all<T = unknown>(query: SQL): T[];\n run(query: SQL): unknown;\n}\n\n/**\n * A Drizzle SQLite database over a synchronous driver: `drizzle(new Database(path))` from `drizzle-orm/better-sqlite3`.\n * `transaction` is not generic here: drizzle-orm 0.45 types its answer as the callback's, 1.0 through a conditional type\n * that refuses async callbacks, and both fit this shape.\n */\nexport interface DrizzleSqlite extends DrizzleSqliteQueryable {\n transaction(run: (tx: DrizzleSqliteQueryable) => SqlRow[][], config?: { behavior?: \"immediate\" }): unknown;\n}\n\n/**\n * A Drizzle SQLite database over an asynchronous driver with an atomic batch: `drizzle-orm/libsql` (Turso) or\n * `drizzle-orm/d1`. `all` and `run` build a statement that runs when awaited, or as part of `batch`.\n */\nexport interface DrizzleAsyncSqlite {\n all<T = unknown>(query: SQL): BatchItem<\"sqlite\"> & PromiseLike<T[]>;\n run(query: SQL): BatchItem<\"sqlite\"> & PromiseLike<unknown>;\n batch(statements: readonly [BatchItem<\"sqlite\">, ...BatchItem<\"sqlite\">[]]): PromiseLike<readonly unknown[]>;\n}\n\n/**\n * Whether the statement answers rows: better-sqlite3 refuses `all` for one that does not. Every statement the core\n * writes either starts with SELECT or ends its write with a RETURNING clause when it needs rows back. A table named\n * `returning` is quoted, so the word is followed by `\"`, never by whitespace.\n */\nconst ANSWERS_ROWS = /^\\s*SELECT\\b|\\bRETURNING\\s/i;\nconst answersRows = ({ sql }: SqlStatement) => ANSWERS_ROWS.test(sql);\n\nfunction synchronousExecutor(db: DrizzleSqlite): SqlExecutor {\n const rowsOf = (target: DrizzleSqliteQueryable, statement: SqlStatement): SqlRow[] => {\n const query = drizzleSql(\"sqlite\", statement);\n if (answersRows(statement)) return target.all<SqlRow>(query);\n target.run(query);\n return [];\n };\n return {\n dialect: \"sqlite\",\n query: async (sql, params) => rowsOf(db, { sql, params }),\n // The transaction answers what its callback returned.\n batch: async (statements) =>\n db.transaction((tx) => statements.map((statement) => rowsOf(tx, statement)), {\n behavior: \"immediate\",\n }) as SqlRow[][],\n };\n}\n\nfunction batchingExecutor(db: DrizzleAsyncSqlite): SqlExecutor {\n const built = (statement: SqlStatement) => {\n const query = drizzleSql(\"sqlite\", statement);\n return answersRows(statement) ? db.all<SqlRow>(query) : db.run(query);\n };\n // A write's answer (libsql's ResultSet, D1's meta) is not rows.\n const rowsFrom = (statement: SqlStatement, answer: unknown) => (answersRows(statement) ? (answer as SqlRow[]) : []);\n return {\n dialect: \"sqlite\",\n query: async (sql, params) => rowsFrom({ sql, params }, await built({ sql, params })),\n async batch(statements) {\n const [first, ...rest] = statements;\n if (!first) return [];\n const answers = await db.batch([built(first), ...rest.map(built)]);\n return statements.map((statement, index) => rowsFrom(statement, answers[index]));\n },\n };\n}\n\n/** The D1 binding of a `drizzle-orm/d1` database, which Drizzle keeps as `$client`; null for any other driver. */\nfunction d1Binding(db: object): D1Database | null {\n const client: unknown = \"$client\" in db ? db.$client : null;\n const isD1 =\n typeof client === \"object\" &&\n client !== null &&\n \"prepare\" in client &&\n typeof client.prepare === \"function\" &&\n \"batch\" in client &&\n typeof client.batch === \"function\";\n return isD1 ? (client as D1Database) : null;\n}\n\nexport function sqliteExecutor(db: DrizzleSqlite | DrizzleAsyncSqlite): SqlExecutor {\n const d1 = d1Binding(db);\n if (d1) return d1Executor(d1);\n return \"batch\" in db && typeof db.batch === \"function\"\n ? batchingExecutor(db as DrizzleAsyncSqlite)\n : synchronousExecutor(db as DrizzleSqlite);\n}\n","// The store's tables as Drizzle `pg-core` tables (spec M5 §3). The package emits declarations without inference\n// (isolatedDeclarations), so the table types are spelled out, but only through what drizzle-orm 0.45 and 1.0 both\n// export: the builder functions' return types, their `this`-typed methods and the table function type `PgTableFn`, the\n// one type name both lines share. The names of the builder types differ between the two lines and are never written\n// here. The compiler checks the builders below against these types, and drizzle.test.ts pins the row types they give\n// on both lines. With `tables.schema` the tables come from that schema's `table`, so drizzle-kit creates them in it and\n// queries name it.\n\nimport { sql } from \"drizzle-orm\";\nimport { bigint, check, index, integer, PgSchema, type PgTableFn, pgTable, text, timestamp } from \"drizzle-orm/pg-core\";\nimport type { FileStatus } from \"../../server/store.ts\";\nimport { type StoreTables, tableNames } from \"../../store/sql/tables.ts\";\n\n// Each builder function's last overload names the column; `timestamp`'s mode defaults to Dates, and `bigint`'s answer\n// is a union by mode, of which the number one is taken.\ntype Text = ReturnType<typeof text>;\ntype Time = ReturnType<typeof timestamp>;\ntype NotNull<TColumn extends { notNull(): unknown }> = ReturnType<TColumn[\"notNull\"]>;\ntype PrimaryKey<TColumn extends { primaryKey(): unknown }> = ReturnType<TColumn[\"primaryKey\"]>;\ntype Count = NotNull<Extract<ReturnType<typeof bigint>, { _: { data: number } }>>;\n// A type-only stand-in for a text column, so `$type`, a generic method, can be instantiated with the status type.\ndeclare const textStandIn: Text;\ntype Status = NotNull<ReturnType<typeof textStandIn.$type<FileStatus>>>;\n// A type-only table function whose tables may or may not carry a schema: `pgTable` and a schema's `table` both fit it.\ndeclare const tableStandIn: PgTableFn<string | undefined>;\n\ntype FileColumns = {\n id: PrimaryKey<Text>;\n route: NotNull<Text>;\n key: NotNull<Text>;\n owner: Text;\n status: Status;\n name: NotNull<Text>;\n type: NotNull<Text>;\n size: Count;\n uploadId: Text;\n metadata: Text;\n result: Text;\n claim: Text;\n claimedAt: Time;\n expiresAt: NotNull<Time>;\n createdAt: NotNull<Time>;\n updatedAt: NotNull<Time>;\n completedAt: Time;\n endedAt: Time;\n cleanedAt: Time;\n requestKey: Text;\n};\n\ntype UsageColumns = {\n owner: PrimaryKey<Text>;\n reservedBytes: Count;\n activeBytes: Count;\n files: NotNull<ReturnType<typeof integer>>;\n updatedAt: NotNull<Time>;\n};\n\n/** `cloudropPgTables()`: the files and usage tables as Drizzle `pg-core` tables, in a schema with `tables.schema`. */\nexport interface CloudropPgTables {\n files: ReturnType<typeof tableStandIn<string, FileColumns>>;\n usage: ReturnType<typeof tableStandIn<string, UsageColumns>>;\n}\n\n/** The tables' names and, on Postgres, their schema: pass the same `tables` as to `drizzleStore`. */\nexport interface CloudropTablesOptions {\n tables?: StoreTables;\n}\n\n// The constructor, not `pgSchema()`, which refuses \"public\" although the store accepts it: the constructor is what\n// `pgSchema()` calls for every other name. 1.0 declares a required `casing` (undefined is what `pgSchema()` passes);\n// 0.45 takes the name alone.\nconst Schema: new (name: string, casing: undefined) => { table: PgTableFn<string> } = PgSchema;\n\nconst time = (name: string) => timestamp(name, { withTimezone: true, precision: 3, mode: \"date\" });\nconst count = (name: string) => bigint(name, { mode: \"number\" }).notNull();\n\n/**\n * The store's tables as Drizzle `pg-core` tables, for an app's schema and migrations (drizzle-kit picks them up from\n * the schema file that exports them) and for typed reads: `db.select().from(files)`. Write to them only through the\n * store, which keeps `usage` in step with `files`.\n *\n * ```ts\n * export const { files: cloudropFiles, usage: cloudropUsage } = cloudropPgTables();\n * const inApp = cloudropPgTables({ tables: { schema: \"app\" } });\n * ```\n */\nexport function cloudropPgTables(options: CloudropTablesOptions = {}): CloudropPgTables {\n const names = tableNames(options.tables, \"postgres\");\n const table: PgTableFn<string | undefined> =\n names.schema === undefined ? pgTable : new Schema(names.schema, undefined).table;\n const files = table(\n names.files,\n {\n id: text(\"id\").primaryKey(),\n route: text(\"route\").notNull(),\n key: text(\"key\").notNull(),\n /** From the route's `owner` callback; not the token's `owner` (what `authorize` returned). */\n owner: text(\"owner\"),\n status: text(\"status\").$type<FileStatus>().notNull(),\n name: text(\"name\").notNull(),\n type: text(\"type\").notNull(),\n size: count(\"size\"),\n uploadId: text(\"upload_id\"),\n metadata: text(\"metadata\"),\n result: text(\"result\"),\n claim: text(\"claim\"),\n claimedAt: time(\"claimed_at\"),\n expiresAt: time(\"expires_at\").notNull(),\n createdAt: time(\"created_at\").notNull(),\n updatedAt: time(\"updated_at\").notNull(),\n completedAt: time(\"completed_at\"),\n endedAt: time(\"ended_at\"),\n cleanedAt: time(\"cleaned_at\"),\n /** The idempotency key of the `/upload` that wrote the row: a retry with it supersedes the row while pending. */\n requestKey: text(\"request_key\"),\n },\n (t) => [\n index(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),\n index(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),\n index(`${names.files}_status_cleaned_at_ended_at_idx`).on(t.status, t.cleanedAt, t.endedAt),\n index(`${names.files}_owner_status_idx`).on(t.owner, t.status),\n index(`${names.files}_key_idx`).on(t.key),\n index(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey),\n ],\n );\n const usage = table(\n names.usage,\n {\n owner: text(\"owner\").primaryKey(),\n reservedBytes: count(\"reserved_bytes\"),\n activeBytes: count(\"active_bytes\"),\n files: integer(\"files\").notNull(),\n updatedAt: time(\"updated_at\").notNull(),\n },\n // Named as Postgres names an unnamed column CHECK, so the plain DDL and these tables agree.\n (t) => [\n check(`${names.usage}_reserved_bytes_check`, sql`${t.reservedBytes} >= 0`),\n check(`${names.usage}_active_bytes_check`, sql`${t.activeBytes} >= 0`),\n check(`${names.usage}_files_check`, sql`${t.files} >= 0`),\n ],\n );\n return { files, usage };\n}\n","// The store's tables as Drizzle `sqlite-core` tables (spec M5 §3): sizes and counters as integers read as numbers,\n// times as integer milliseconds read as Dates. The types are spelled out from what drizzle-orm 0.45 and 1.0 both export,\n// as on Postgres (postgres-tables.ts).\n\nimport { index, integer, sqliteTable, text } from \"drizzle-orm/sqlite-core\";\nimport type { FileStatus } from \"../../server/store.ts\";\nimport { type StoreTables, tableNames } from \"../../store/sql/tables.ts\";\n\n// drizzle-orm 0.45 and 1.0 share no builder type names, and `text`'s overload that takes a name erases to `any` on both,\n// so each builder type comes from an overload both lines have. `text`'s third type argument is the length in 0.45 and\n// the mode in 1.0; `never` satisfies both and selects the plain text builder. An integer's mode defaults to a number.\ntype Text = ReturnType<typeof text<string, [string, ...string[]], never>>;\ntype Time = ReturnType<typeof integer<\"timestamp_ms\">>;\ntype Count = NotNull<ReturnType<typeof integer>>;\ntype NotNull<TColumn extends { notNull(): unknown }> = ReturnType<TColumn[\"notNull\"]>;\ntype PrimaryKey<TColumn extends { primaryKey(): unknown }> = ReturnType<TColumn[\"primaryKey\"]>;\n// A type-only stand-in for a text column, so `$type`, a generic method, can be instantiated with the status type.\ndeclare const textStandIn: Text;\ntype Status = NotNull<ReturnType<typeof textStandIn.$type<FileStatus>>>;\n\ntype FileColumns = {\n id: PrimaryKey<Text>;\n route: NotNull<Text>;\n key: NotNull<Text>;\n owner: Text;\n status: Status;\n name: NotNull<Text>;\n type: NotNull<Text>;\n size: Count;\n uploadId: Text;\n metadata: Text;\n result: Text;\n claim: Text;\n claimedAt: Time;\n expiresAt: NotNull<Time>;\n createdAt: NotNull<Time>;\n updatedAt: NotNull<Time>;\n completedAt: Time;\n endedAt: Time;\n cleanedAt: Time;\n requestKey: Text;\n};\n\ntype UsageColumns = {\n owner: PrimaryKey<Text>;\n reservedBytes: Count;\n activeBytes: Count;\n files: Count;\n updatedAt: NotNull<Time>;\n};\n\n/** `cloudropSqliteTables()`: the files and usage tables as Drizzle `sqlite-core` tables. */\nexport interface CloudropSqliteTables {\n files: ReturnType<typeof sqliteTable<string, FileColumns>>;\n usage: ReturnType<typeof sqliteTable<string, UsageColumns>>;\n}\n\n// The overloads above are the ones without a column name, which 0.45 types as `\"\"` (and then names after the property)\n// and 1.0 does not type at all. The builders below take the real SQL name, so on 0.45 their types differ from those\n// overloads in the name and the text length only: cast here, and pinned by the row-type tests and the catalogue test.\nconst textColumn = (name: string) => text(name) as unknown as Text;\nconst time = (name: string) => integer(name, { mode: \"timestamp_ms\" }) as unknown as Time;\nconst count = (name: string) => integer(name, { mode: \"number\" }).notNull();\n\n/**\n * The store's tables as Drizzle `sqlite-core` tables, for an app's schema and migrations (drizzle-kit picks them up from\n * the schema file that exports them) and for typed reads: `db.select().from(files)`. Write to them only through the\n * store, which keeps `usage` in step with `files`.\n *\n * ```ts\n * export const { files: cloudropFiles, usage: cloudropUsage } = cloudropSqliteTables();\n * ```\n */\nexport function cloudropSqliteTables(options: { tables?: Omit<StoreTables, \"schema\"> } = {}): CloudropSqliteTables {\n const names = tableNames(options.tables, \"sqlite\");\n const files = sqliteTable(\n names.files,\n {\n id: textColumn(\"id\").primaryKey(),\n route: textColumn(\"route\").notNull(),\n key: textColumn(\"key\").notNull(),\n /** From the route's `owner` callback; not the token's `owner` (what `authorize` returned). */\n owner: textColumn(\"owner\"),\n status: textColumn(\"status\").$type<FileStatus>().notNull(),\n name: textColumn(\"name\").notNull(),\n type: textColumn(\"type\").notNull(),\n size: count(\"size\"),\n uploadId: textColumn(\"upload_id\"),\n metadata: textColumn(\"metadata\"),\n result: textColumn(\"result\"),\n claim: textColumn(\"claim\"),\n claimedAt: time(\"claimed_at\"),\n expiresAt: time(\"expires_at\").notNull(),\n createdAt: time(\"created_at\").notNull(),\n updatedAt: time(\"updated_at\").notNull(),\n completedAt: time(\"completed_at\"),\n endedAt: time(\"ended_at\"),\n cleanedAt: time(\"cleaned_at\"),\n /** The idempotency key of the `/upload` that wrote the row: a retry with it supersedes the row while pending. */\n requestKey: textColumn(\"request_key\"),\n },\n (t) => [\n index(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),\n index(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),\n index(`${names.files}_status_cleaned_at_ended_at_idx`).on(t.status, t.cleanedAt, t.endedAt),\n index(`${names.files}_owner_status_idx`).on(t.owner, t.status),\n index(`${names.files}_key_idx`).on(t.key),\n index(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey),\n ],\n );\n const usage = sqliteTable(names.usage, {\n owner: textColumn(\"owner\").primaryKey(),\n reservedBytes: count(\"reserved_bytes\"),\n activeBytes: count(\"active_bytes\"),\n files: count(\"files\"),\n updatedAt: time(\"updated_at\").notNull(),\n });\n return { files, usage };\n}\n","// cloudrop/adapters/drizzle: the database store over an app's Drizzle database (spec M5 §7). The SQL core writes every\n// statement; this entry runs them through Drizzle and exports the tables for the app's own schema. `drizzle-orm` is an\n// optional peer: only this entry imports it.\n\nimport { configError } from \"../errors.ts\";\nimport type { CloudropStore, TransactionalStore } from \"../server/store.ts\";\nimport { sqlStore } from \"../store/sql/store.ts\";\nimport type { StoreTables } from \"../store/sql/tables.ts\";\nimport { type DrizzlePostgres, type DrizzleTransaction, postgresExecutor } from \"./drizzle/postgres.ts\";\nimport { type DrizzleAsyncSqlite, type DrizzleSqlite, sqliteExecutor } from \"./drizzle/sqlite.ts\";\nimport { withRoute } from \"./transactional.ts\";\n\nexport type { StoreTables } from \"../store/sql/tables.ts\";\nexport type { DrizzlePostgres, DrizzlePostgresQueryable, DrizzleTransaction } from \"./drizzle/postgres.ts\";\nexport type { CloudropPgTables, CloudropTablesOptions } from \"./drizzle/postgres-tables.ts\";\nexport { cloudropPgTables } from \"./drizzle/postgres-tables.ts\";\nexport type { DrizzleAsyncSqlite, DrizzleSqlite, DrizzleSqliteQueryable } from \"./drizzle/sqlite.ts\";\nexport type { CloudropSqliteTables } from \"./drizzle/sqlite-tables.ts\";\nexport { cloudropSqliteTables } from \"./drizzle/sqlite-tables.ts\";\n\n/** What the overloads below take; each one names its dialect as a literal. */\ninterface DrizzleStoreOptions {\n dialect: \"postgres\" | \"sqlite\";\n tables?: StoreTables;\n transaction?: boolean;\n}\n\n/**\n * A cloudrop store over a Drizzle database: Postgres (node-postgres over a `Pool`, postgres.js) or SQLite\n * (better-sqlite3, libsql/Turso, D1). Create the tables first, from `cloudropPgTables` or `cloudropSqliteTables` in\n * your Drizzle schema or from the documented DDL; the store checks them on its first call. `tables` names them,\n * defaults `cloudrop_files` and `cloudrop_usage`, and on Postgres `tables.schema` names their schema (pass the same\n * `tables` to `cloudropPgTables`). A single node-postgres `Client` is refused: every request would share its one\n * connection, and a transaction on it would take the others' statements with it.\n *\n * With `transaction: true` (Postgres only), `onComplete` runs inside the completion's transaction with Drizzle's `tx`:\n * an app row written through `tx` commits with the upload or not at all, and routes must come from `store.route`.\n * Postgres waits at most 2 s for the row lock, so a second `/complete` of the same file answers busy. Keep storage and\n * other network calls out of that `onComplete`; they belong in `afterComplete`.\n *\n * Usage:\n * ```ts\n * const db = drizzle(new Pool({ connectionString }));\n * const store = drizzleStore(db, { dialect: \"postgres\", transaction: true });\n * const avatars = store.route({ accept: \"image/*\", maxSize: \"5MB\", authorize }, {\n * owner: ({ userId }) => userId,\n * onComplete: async ({ tx, userId, file }) => {\n * await tx.update(users).set({ avatar: file.key }).where(eq(users.id, userId));\n * },\n * });\n * export const cloudrop = createCloudrop({ storage, secret, store, routes: { avatars } });\n * ```\n */\nexport function drizzleStore<TDb extends DrizzlePostgres>(\n db: TDb,\n options: { dialect: \"postgres\"; tables?: StoreTables; transaction: true },\n): TransactionalStore<DrizzleTransaction<TDb>>;\nexport function drizzleStore(\n db: DrizzlePostgres,\n options: { dialect: \"postgres\"; tables?: StoreTables; transaction?: false },\n): CloudropStore;\nexport function drizzleStore(\n db: DrizzleSqlite | DrizzleAsyncSqlite,\n options: { dialect: \"sqlite\"; tables?: Omit<StoreTables, \"schema\"> },\n): CloudropStore;\nexport function drizzleStore(\n db: DrizzlePostgres | DrizzleSqlite | DrizzleAsyncSqlite,\n options: DrizzleStoreOptions,\n): CloudropStore<unknown> {\n const { dialect, tables, transaction = false } = options;\n if (dialect === \"sqlite\") {\n // The core refuses transaction: true on SQLite, with the same message for every adapter.\n return sqlStore(sqliteExecutor(db as DrizzleSqlite | DrizzleAsyncSqlite), { tables, transaction });\n }\n if (dialect !== \"postgres\") {\n throw configError(\n `drizzleStore's dialect ${JSON.stringify(dialect)} is not supported. Use \"postgres\" or \"sqlite\".`,\n );\n }\n const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apters/drizzle/statement.ts","../../src/adapters/drizzle/postgres.ts","../../src/adapters/drizzle/sqlite.ts","../../src/adapters/drizzle/postgres-tables.ts","../../src/adapters/drizzle/sqlite-tables.ts","../../src/adapters/drizzle.ts"],"sourcesContent":["// A core statement as Drizzle SQL. Drizzle's `sql.raw` takes no parameters, so the text is cut at each placeholder the\n// core's binder wrote (store/sql/bind.ts) and every placeholder becomes a Drizzle parameter; Drizzle numbers them\n// again as it renders, `$1`, `$2`… on Postgres and `?` on SQLite, and the `::type` casts after them stay in the text.\n\nimport { type SQL, type SQLChunk, sql } from \"drizzle-orm\";\nimport type { SqlDialect, SqlStatement } from \"../../store/sql/executor.ts\";\n\nconst PLACEHOLDER: Record<SqlDialect, RegExp> = { postgres: /\\$(\\d+)/g, sqlite: /\\?/g };\n\nexport function drizzleSql(dialect: SqlDialect, { sql: text, params }: SqlStatement): SQL {\n const chunks: SQLChunk[] = [];\n let end = 0;\n for (const [position, match] of [...text.matchAll(PLACEHOLDER[dialect])].entries()) {\n // `$n` names its parameter; SQLite's `?` takes the next one.\n const value = params[match[1] === undefined ? position : Number(match[1]) - 1];\n chunks.push(sql.raw(text.slice(end, match.index)), sql.param(value));\n end = match.index + match[0].length;\n }\n chunks.push(sql.raw(text.slice(end)));\n return sql.join(chunks);\n}\n","// Drizzle on Postgres: statements through `execute`, batches and transactions through `db.transaction`. The database is\n// described by the two members used here, so any Drizzle Postgres driver fits and the library needs no Drizzle types\n// beyond `SQL`; drizzle.db.integration.test.ts runs it on node-postgres and postgres.js.\n\nimport type { SQL } from \"drizzle-orm\";\nimport { configError } from \"../../errors.ts\";\nimport { type SqlRow, type SqlStatement, sequential, type TransactionalSqlExecutor } from \"../../store/sql/executor.ts\";\nimport { drizzleSql } from \"./statement.ts\";\n\n/** What the store calls on a Drizzle Postgres database or transaction. */\nexport interface DrizzlePostgresQueryable {\n execute(query: SQL): PromiseLike<unknown>;\n}\n\n/** A Drizzle Postgres database: `drizzle(pool)` from `drizzle-orm/node-postgres`, `drizzle-orm/postgres-js`, … */\nexport interface DrizzlePostgres extends DrizzlePostgresQueryable {\n transaction<T>(run: (tx: DrizzlePostgresQueryable) => Promise<T>): Promise<T>;\n}\n\n/** The `tx` Drizzle hands to `db.transaction`'s callback, for this database's driver and schema. */\nexport type DrizzleTransaction<TDb extends DrizzlePostgres> = Parameters<Parameters<TDb[\"transaction\"]>[0]>[0];\n\n/** How a result looked, for the message: its keys, never its values. */\nconst shapeOf = (result: unknown): string =>\n typeof result === \"object\" && result !== null ? `{ ${Object.keys(result).join(\", \")} }` : typeof result;\n\n/** node-postgres answers `{ rows }`, postgres.js the rows themselves. */\nasync function rowsOf(target: DrizzlePostgresQueryable, statement: SqlStatement): Promise<SqlRow[]> {\n const result = await target.execute(drizzleSql(\"postgres\", statement));\n if (Array.isArray(result)) return result;\n const { rows } = (result ?? {}) as { rows?: unknown };\n if (Array.isArray(rows)) return rows;\n throw configError(\n `This Drizzle driver's execute() answered ${shapeOf(result)}, not rows or { rows }. Use drizzleStore with node-postgres or postgres.js, or build an executor for cloudrop/adapters/sql.`,\n );\n}\n\n/** The executor's statements on the database or a transaction, in order when batched. */\nconst on = (target: DrizzlePostgresQueryable) =>\n sequential(\"postgres\", (sql, params) => rowsOf(target, { sql, params }));\n\n/**\n * True for a node-postgres client that is not a pool: Drizzle's node-postgres driver checks out a connection for a\n * transaction only from a pool (its own test: the constructor's name contains \"Pool\"), and otherwise runs BEGIN on the\n * client's one connection, which every other request is using too.\n */\nfunction isSingleConnection(db: DrizzlePostgres): boolean {\n const client: unknown = (db as { $client?: unknown }).$client;\n if (typeof client !== \"object\" || client === null) return false;\n const { query, connect } = client as { query?: unknown; connect?: unknown };\n return typeof query === \"function\" && typeof connect === \"function\" && !client.constructor.name.includes(\"Pool\");\n}\n\n/** The executor; its `transaction` runs `onComplete` in a Drizzle transaction whose `tx` the route gets. */\nexport function postgresExecutor(db: DrizzlePostgres): TransactionalSqlExecutor<DrizzlePostgresQueryable> {\n if (isSingleConnection(db)) {\n throw configError(\n \"drizzleStore needs a pg Pool, not a single pg Client: a transaction on the one shared connection would take every other request's statements with it. Pass drizzle(new Pool({ connectionString })), or use postgres.js.\",\n );\n }\n return {\n ...on(db),\n batch: (statements) => db.transaction((tx) => on(tx).batch(statements)),\n transaction: (run) => db.transaction((tx) => run(on(tx), tx)),\n };\n}\n","// Drizzle on SQLite, through `all` and `run`. A synchronous driver (better-sqlite3) runs a batch in\n// `db.transaction(…, { behavior: \"immediate\" })`, which ends before any other call can start. An asynchronous one with\n// an atomic batch (libsql/Turso) runs it through `db.batch`, ordered and all-or-nothing. D1 runs through the binding\n// Drizzle keeps as `db.$client`, as `d1Executor` does: drizzle-orm 0.45's D1 `batch` cannot take a raw statement with\n// parameters (it reads a `stmt` that `db.run(sql)` never prepares; measured in the Wrangler lane). None has transaction\n// mode: an interactive transaction would hold the only writer across `onComplete`'s awaits.\n\nimport type { SQL } from \"drizzle-orm\";\nimport type { BatchItem } from \"drizzle-orm/batch\";\nimport type { SqlExecutor, SqlRow, SqlStatement } from \"../../store/sql/executor.ts\";\nimport { type D1Database, d1Executor } from \"../sql/d1.ts\";\nimport { drizzleSql } from \"./statement.ts\";\n\n/** What the store calls on a synchronous Drizzle SQLite database or transaction. */\nexport interface DrizzleSqliteQueryable {\n all<T = unknown>(query: SQL): T[];\n run(query: SQL): unknown;\n}\n\n/**\n * A Drizzle SQLite database over a synchronous driver: `drizzle(new Database(path))` from `drizzle-orm/better-sqlite3`.\n * `transaction` is not generic here: drizzle-orm 0.45 types its answer as the callback's, 1.0 through a conditional type\n * that refuses async callbacks, and both fit this shape.\n */\nexport interface DrizzleSqlite extends DrizzleSqliteQueryable {\n transaction(run: (tx: DrizzleSqliteQueryable) => SqlRow[][], config?: { behavior?: \"immediate\" }): unknown;\n}\n\n/**\n * A Drizzle SQLite database over an asynchronous driver with an atomic batch: `drizzle-orm/libsql` (Turso) or\n * `drizzle-orm/d1`. `all` and `run` build a statement that runs when awaited, or as part of `batch`.\n */\nexport interface DrizzleAsyncSqlite {\n all<T = unknown>(query: SQL): BatchItem<\"sqlite\"> & PromiseLike<T[]>;\n run(query: SQL): BatchItem<\"sqlite\"> & PromiseLike<unknown>;\n batch(statements: readonly [BatchItem<\"sqlite\">, ...BatchItem<\"sqlite\">[]]): PromiseLike<readonly unknown[]>;\n}\n\n/**\n * Whether the statement answers rows: better-sqlite3 refuses `all` for one that does not. Every statement the core\n * writes either starts with SELECT or ends its write with a RETURNING clause when it needs rows back. A table named\n * `returning` is quoted, so the word is followed by `\"`, never by whitespace.\n */\nconst ANSWERS_ROWS = /^\\s*SELECT\\b|\\bRETURNING\\s/i;\nconst answersRows = ({ sql }: SqlStatement) => ANSWERS_ROWS.test(sql);\n\nfunction synchronousExecutor(db: DrizzleSqlite): SqlExecutor {\n const rowsOf = (target: DrizzleSqliteQueryable, statement: SqlStatement): SqlRow[] => {\n const query = drizzleSql(\"sqlite\", statement);\n if (answersRows(statement)) return target.all<SqlRow>(query);\n target.run(query);\n return [];\n };\n return {\n dialect: \"sqlite\",\n query: async (sql, params) => rowsOf(db, { sql, params }),\n // The transaction answers what its callback returned.\n batch: async (statements) =>\n db.transaction((tx) => statements.map((statement) => rowsOf(tx, statement)), {\n behavior: \"immediate\",\n }) as SqlRow[][],\n };\n}\n\nfunction batchingExecutor(db: DrizzleAsyncSqlite): SqlExecutor {\n const built = (statement: SqlStatement) => {\n const query = drizzleSql(\"sqlite\", statement);\n return answersRows(statement) ? db.all<SqlRow>(query) : db.run(query);\n };\n // A write's answer (libsql's ResultSet, D1's meta) is not rows.\n const rowsFrom = (statement: SqlStatement, answer: unknown) => (answersRows(statement) ? (answer as SqlRow[]) : []);\n return {\n dialect: \"sqlite\",\n query: async (sql, params) => rowsFrom({ sql, params }, await built({ sql, params })),\n async batch(statements) {\n const [first, ...rest] = statements;\n if (!first) return [];\n const answers = await db.batch([built(first), ...rest.map(built)]);\n return statements.map((statement, index) => rowsFrom(statement, answers[index]));\n },\n };\n}\n\n/** The D1 binding of a `drizzle-orm/d1` database, which Drizzle keeps as `$client`; null for any other driver. */\nfunction d1Binding(db: object): D1Database | null {\n const client: unknown = \"$client\" in db ? db.$client : null;\n const isD1 =\n typeof client === \"object\" &&\n client !== null &&\n \"prepare\" in client &&\n typeof client.prepare === \"function\" &&\n \"batch\" in client &&\n typeof client.batch === \"function\";\n return isD1 ? (client as D1Database) : null;\n}\n\nexport function sqliteExecutor(db: DrizzleSqlite | DrizzleAsyncSqlite): SqlExecutor {\n const d1 = d1Binding(db);\n if (d1) return d1Executor(d1);\n return \"batch\" in db && typeof db.batch === \"function\"\n ? batchingExecutor(db as DrizzleAsyncSqlite)\n : synchronousExecutor(db as DrizzleSqlite);\n}\n","// The store's tables as Drizzle `pg-core` tables (spec M5 §3). The package emits declarations without inference\n// (isolatedDeclarations), so the table types are spelled out, but only through what drizzle-orm 0.45 and 1.0 both\n// export: the builder functions' return types, their `this`-typed methods and the table function type `PgTableFn`, the\n// one type name both lines share. The names of the builder types differ between the two lines and are never written\n// here. The compiler checks the builders below against these types, and drizzle.test.ts pins the row types they give\n// on both lines. With `tables.schema` the tables come from that schema's `table`, so drizzle-kit creates them in it and\n// queries name it.\n\nimport { sql } from \"drizzle-orm\";\nimport { bigint, check, index, integer, PgSchema, type PgTableFn, pgTable, text, timestamp } from \"drizzle-orm/pg-core\";\nimport type { FileStatus } from \"../../server/store.ts\";\nimport { type StoreTables, tableNames } from \"../../store/sql/tables.ts\";\n\n// Each builder function's last overload names the column; `timestamp`'s mode defaults to Dates, and `bigint`'s answer\n// is a union by mode, of which the number one is taken.\ntype Text = ReturnType<typeof text>;\ntype Time = ReturnType<typeof timestamp>;\ntype NotNull<TColumn extends { notNull(): unknown }> = ReturnType<TColumn[\"notNull\"]>;\ntype PrimaryKey<TColumn extends { primaryKey(): unknown }> = ReturnType<TColumn[\"primaryKey\"]>;\ntype Count = NotNull<Extract<ReturnType<typeof bigint>, { _: { data: number } }>>;\n// A type-only stand-in for a text column, so `$type`, a generic method, can be instantiated with the status type.\ndeclare const textStandIn: Text;\ntype Status = NotNull<ReturnType<typeof textStandIn.$type<FileStatus>>>;\n// A type-only table function whose tables may or may not carry a schema: `pgTable` and a schema's `table` both fit it.\ndeclare const tableStandIn: PgTableFn<string | undefined>;\n\ntype FileColumns = {\n id: PrimaryKey<Text>;\n route: NotNull<Text>;\n key: NotNull<Text>;\n owner: Text;\n status: Status;\n name: NotNull<Text>;\n type: NotNull<Text>;\n size: Count;\n uploadId: Text;\n metadata: Text;\n result: Text;\n claim: Text;\n claimedAt: Time;\n expiresAt: NotNull<Time>;\n createdAt: NotNull<Time>;\n updatedAt: NotNull<Time>;\n completedAt: Time;\n endedAt: Time;\n cleanedAt: Time;\n requestKey: Text;\n};\n\ntype UsageColumns = {\n owner: PrimaryKey<Text>;\n reservedBytes: Count;\n activeBytes: Count;\n files: NotNull<ReturnType<typeof integer>>;\n updatedAt: NotNull<Time>;\n};\n\n/** `cloudropPgTables()`: the files and usage tables as Drizzle `pg-core` tables, in a schema with `tables.schema`. */\nexport interface CloudropPgTables {\n files: ReturnType<typeof tableStandIn<string, FileColumns>>;\n usage: ReturnType<typeof tableStandIn<string, UsageColumns>>;\n}\n\n/** The tables' names and, on Postgres, their schema: pass the same `tables` as to `drizzleStore`. */\nexport interface CloudropTablesOptions {\n tables?: StoreTables;\n}\n\n// The constructor, not `pgSchema()`, which refuses \"public\" although the store accepts it: the constructor is what\n// `pgSchema()` calls for every other name. 1.0 declares a required `casing` (undefined is what `pgSchema()` passes);\n// 0.45 takes the name alone.\nconst Schema: new (name: string, casing: undefined) => { table: PgTableFn<string> } = PgSchema;\n\nconst time = (name: string) => timestamp(name, { withTimezone: true, precision: 3, mode: \"date\" });\nconst count = (name: string) => bigint(name, { mode: \"number\" }).notNull();\n\n/**\n * The store's tables as Drizzle `pg-core` tables, for an app's schema and migrations (drizzle-kit picks them up from\n * the schema file that exports them) and for typed reads: `db.select().from(files)`. Write to them only through the\n * store, which keeps `usage` in step with `files`.\n *\n * ```ts\n * export const { files: cloudropFiles, usage: cloudropUsage } = cloudropPgTables();\n * const inApp = cloudropPgTables({ tables: { schema: \"app\" } });\n * ```\n */\nexport function cloudropPgTables(options: CloudropTablesOptions = {}): CloudropPgTables {\n const names = tableNames(options.tables, \"postgres\");\n const table: PgTableFn<string | undefined> =\n names.schema === undefined ? pgTable : new Schema(names.schema, undefined).table;\n const files = table(\n names.files,\n {\n id: text(\"id\").primaryKey(),\n route: text(\"route\").notNull(),\n key: text(\"key\").notNull(),\n /** From the route's `owner` callback; not the token's `owner` (what `authorize` returned). */\n owner: text(\"owner\"),\n status: text(\"status\").$type<FileStatus>().notNull(),\n name: text(\"name\").notNull(),\n type: text(\"type\").notNull(),\n size: count(\"size\"),\n uploadId: text(\"upload_id\"),\n metadata: text(\"metadata\"),\n result: text(\"result\"),\n claim: text(\"claim\"),\n claimedAt: time(\"claimed_at\"),\n expiresAt: time(\"expires_at\").notNull(),\n createdAt: time(\"created_at\").notNull(),\n updatedAt: time(\"updated_at\").notNull(),\n completedAt: time(\"completed_at\"),\n endedAt: time(\"ended_at\"),\n cleanedAt: time(\"cleaned_at\"),\n /** The idempotency key of the `/upload` that wrote the row: a retry with it supersedes the row while pending. */\n requestKey: text(\"request_key\"),\n },\n (t) => [\n index(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),\n index(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),\n index(`${names.files}_status_cleaned_at_ended_at_idx`).on(t.status, t.cleanedAt, t.endedAt),\n index(`${names.files}_owner_status_created_at_idx`).on(t.owner, t.status, t.createdAt),\n index(`${names.files}_key_idx`).on(t.key),\n index(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey),\n ],\n );\n const usage = table(\n names.usage,\n {\n owner: text(\"owner\").primaryKey(),\n reservedBytes: count(\"reserved_bytes\"),\n activeBytes: count(\"active_bytes\"),\n files: integer(\"files\").notNull(),\n updatedAt: time(\"updated_at\").notNull(),\n },\n // Named as Postgres names an unnamed column CHECK, so the plain DDL and these tables agree.\n (t) => [\n check(`${names.usage}_reserved_bytes_check`, sql`${t.reservedBytes} >= 0`),\n check(`${names.usage}_active_bytes_check`, sql`${t.activeBytes} >= 0`),\n check(`${names.usage}_files_check`, sql`${t.files} >= 0`),\n ],\n );\n return { files, usage };\n}\n","// The store's tables as Drizzle `sqlite-core` tables (spec M5 §3): sizes and counters as integers read as numbers,\n// times as integer milliseconds read as Dates. The types are spelled out from what drizzle-orm 0.45 and 1.0 both export,\n// as on Postgres (postgres-tables.ts).\n\nimport { index, integer, sqliteTable, text } from \"drizzle-orm/sqlite-core\";\nimport type { FileStatus } from \"../../server/store.ts\";\nimport { type StoreTables, tableNames } from \"../../store/sql/tables.ts\";\n\n// drizzle-orm 0.45 and 1.0 share no builder type names, and `text`'s overload that takes a name erases to `any` on both,\n// so each builder type comes from an overload both lines have. `text`'s third type argument is the length in 0.45 and\n// the mode in 1.0; `never` satisfies both and selects the plain text builder. An integer's mode defaults to a number.\ntype Text = ReturnType<typeof text<string, [string, ...string[]], never>>;\ntype Time = ReturnType<typeof integer<\"timestamp_ms\">>;\ntype Count = NotNull<ReturnType<typeof integer>>;\ntype NotNull<TColumn extends { notNull(): unknown }> = ReturnType<TColumn[\"notNull\"]>;\ntype PrimaryKey<TColumn extends { primaryKey(): unknown }> = ReturnType<TColumn[\"primaryKey\"]>;\n// A type-only stand-in for a text column, so `$type`, a generic method, can be instantiated with the status type.\ndeclare const textStandIn: Text;\ntype Status = NotNull<ReturnType<typeof textStandIn.$type<FileStatus>>>;\n\ntype FileColumns = {\n id: PrimaryKey<Text>;\n route: NotNull<Text>;\n key: NotNull<Text>;\n owner: Text;\n status: Status;\n name: NotNull<Text>;\n type: NotNull<Text>;\n size: Count;\n uploadId: Text;\n metadata: Text;\n result: Text;\n claim: Text;\n claimedAt: Time;\n expiresAt: NotNull<Time>;\n createdAt: NotNull<Time>;\n updatedAt: NotNull<Time>;\n completedAt: Time;\n endedAt: Time;\n cleanedAt: Time;\n requestKey: Text;\n};\n\ntype UsageColumns = {\n owner: PrimaryKey<Text>;\n reservedBytes: Count;\n activeBytes: Count;\n files: Count;\n updatedAt: NotNull<Time>;\n};\n\n/** `cloudropSqliteTables()`: the files and usage tables as Drizzle `sqlite-core` tables. */\nexport interface CloudropSqliteTables {\n files: ReturnType<typeof sqliteTable<string, FileColumns>>;\n usage: ReturnType<typeof sqliteTable<string, UsageColumns>>;\n}\n\n// The overloads above are the ones without a column name, which 0.45 types as `\"\"` (and then names after the property)\n// and 1.0 does not type at all. The builders below take the real SQL name, so on 0.45 their types differ from those\n// overloads in the name and the text length only: cast here, and pinned by the row-type tests and the catalogue test.\nconst textColumn = (name: string) => text(name) as unknown as Text;\nconst time = (name: string) => integer(name, { mode: \"timestamp_ms\" }) as unknown as Time;\nconst count = (name: string) => integer(name, { mode: \"number\" }).notNull();\n\n/**\n * The store's tables as Drizzle `sqlite-core` tables, for an app's schema and migrations (drizzle-kit picks them up from\n * the schema file that exports them) and for typed reads: `db.select().from(files)`. Write to them only through the\n * store, which keeps `usage` in step with `files`.\n *\n * ```ts\n * export const { files: cloudropFiles, usage: cloudropUsage } = cloudropSqliteTables();\n * ```\n */\nexport function cloudropSqliteTables(options: { tables?: Omit<StoreTables, \"schema\"> } = {}): CloudropSqliteTables {\n const names = tableNames(options.tables, \"sqlite\");\n const files = sqliteTable(\n names.files,\n {\n id: textColumn(\"id\").primaryKey(),\n route: textColumn(\"route\").notNull(),\n key: textColumn(\"key\").notNull(),\n /** From the route's `owner` callback; not the token's `owner` (what `authorize` returned). */\n owner: textColumn(\"owner\"),\n status: textColumn(\"status\").$type<FileStatus>().notNull(),\n name: textColumn(\"name\").notNull(),\n type: textColumn(\"type\").notNull(),\n size: count(\"size\"),\n uploadId: textColumn(\"upload_id\"),\n metadata: textColumn(\"metadata\"),\n result: textColumn(\"result\"),\n claim: textColumn(\"claim\"),\n claimedAt: time(\"claimed_at\"),\n expiresAt: time(\"expires_at\").notNull(),\n createdAt: time(\"created_at\").notNull(),\n updatedAt: time(\"updated_at\").notNull(),\n completedAt: time(\"completed_at\"),\n endedAt: time(\"ended_at\"),\n cleanedAt: time(\"cleaned_at\"),\n /** The idempotency key of the `/upload` that wrote the row: a retry with it supersedes the row while pending. */\n requestKey: textColumn(\"request_key\"),\n },\n (t) => [\n index(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),\n index(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),\n index(`${names.files}_status_cleaned_at_ended_at_idx`).on(t.status, t.cleanedAt, t.endedAt),\n index(`${names.files}_owner_status_created_at_idx`).on(t.owner, t.status, t.createdAt),\n index(`${names.files}_key_idx`).on(t.key),\n index(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey),\n ],\n );\n const usage = sqliteTable(names.usage, {\n owner: textColumn(\"owner\").primaryKey(),\n reservedBytes: count(\"reserved_bytes\"),\n activeBytes: count(\"active_bytes\"),\n files: count(\"files\"),\n updatedAt: time(\"updated_at\").notNull(),\n });\n return { files, usage };\n}\n","// cloudrop/adapters/drizzle: the database store over an app's Drizzle database (spec M5 §7). The SQL core writes every\n// statement; this entry runs them through Drizzle and exports the tables for the app's own schema. `drizzle-orm` is an\n// optional peer: only this entry imports it.\n\nimport { configError } from \"../errors.ts\";\nimport type { CloudropStore, TransactionalStore } from \"../server/store.ts\";\nimport { sqlStore } from \"../store/sql/store.ts\";\nimport type { StoreTables } from \"../store/sql/tables.ts\";\nimport { type DrizzlePostgres, type DrizzleTransaction, postgresExecutor } from \"./drizzle/postgres.ts\";\nimport { type DrizzleAsyncSqlite, type DrizzleSqlite, sqliteExecutor } from \"./drizzle/sqlite.ts\";\nimport { withRoute } from \"./transactional.ts\";\n\nexport type { StoreTables } from \"../store/sql/tables.ts\";\nexport type { DrizzlePostgres, DrizzlePostgresQueryable, DrizzleTransaction } from \"./drizzle/postgres.ts\";\nexport type { CloudropPgTables, CloudropTablesOptions } from \"./drizzle/postgres-tables.ts\";\nexport { cloudropPgTables } from \"./drizzle/postgres-tables.ts\";\nexport type { DrizzleAsyncSqlite, DrizzleSqlite, DrizzleSqliteQueryable } from \"./drizzle/sqlite.ts\";\nexport type { CloudropSqliteTables } from \"./drizzle/sqlite-tables.ts\";\nexport { cloudropSqliteTables } from \"./drizzle/sqlite-tables.ts\";\n\n/** What the overloads below take; each one names its dialect as a literal. */\ninterface DrizzleStoreOptions {\n dialect: \"postgres\" | \"sqlite\";\n tables?: StoreTables;\n transaction?: boolean;\n}\n\n/**\n * A cloudrop store over a Drizzle database: Postgres (node-postgres over a `Pool`, postgres.js) or SQLite\n * (better-sqlite3, libsql/Turso, D1). Create the tables first, from `cloudropPgTables` or `cloudropSqliteTables` in\n * your Drizzle schema or from the documented DDL; the store checks them on its first call. `tables` names them,\n * defaults `cloudrop_files` and `cloudrop_usage`, and on Postgres `tables.schema` names their schema (pass the same\n * `tables` to `cloudropPgTables`). A single node-postgres `Client` is refused: every request would share its one\n * connection, and a transaction on it would take the others' statements with it.\n *\n * With `transaction: true` (Postgres only), `onComplete` runs inside the completion's transaction with Drizzle's `tx`:\n * an app row written through `tx` commits with the upload or not at all, and routes must come from `store.route`.\n * Postgres waits at most 2 s for the row lock, so a second `/complete` of the same file answers busy. Keep storage and\n * other network calls out of that `onComplete`; they belong in `afterComplete`.\n *\n * Usage:\n * ```ts\n * const db = drizzle(new Pool({ connectionString }));\n * const store = drizzleStore(db, { dialect: \"postgres\", transaction: true });\n * const avatars = store.route({ accept: \"image/*\", maxSize: \"5MB\", authorize }, {\n * owner: ({ userId }) => userId,\n * onComplete: async ({ tx, userId, file }) => {\n * await tx.update(users).set({ avatar: file.key }).where(eq(users.id, userId));\n * },\n * });\n * export const cloudrop = createCloudrop({ storage, secret, store, routes: { avatars } });\n * ```\n */\nexport function drizzleStore<TDb extends DrizzlePostgres>(\n db: TDb,\n options: { dialect: \"postgres\"; tables?: StoreTables; transaction: true },\n): TransactionalStore<DrizzleTransaction<TDb>>;\nexport function drizzleStore(\n db: DrizzlePostgres,\n options: { dialect: \"postgres\"; tables?: StoreTables; transaction?: false },\n): CloudropStore;\nexport function drizzleStore(\n db: DrizzleSqlite | DrizzleAsyncSqlite,\n options: { dialect: \"sqlite\"; tables?: Omit<StoreTables, \"schema\"> },\n): CloudropStore;\nexport function drizzleStore(\n db: DrizzlePostgres | DrizzleSqlite | DrizzleAsyncSqlite,\n options: DrizzleStoreOptions,\n): CloudropStore<unknown> {\n const { dialect, tables, transaction = false } = options;\n if (dialect === \"sqlite\") {\n // The core refuses transaction: true on SQLite, with the same message for every adapter.\n return sqlStore(sqliteExecutor(db as DrizzleSqlite | DrizzleAsyncSqlite), { tables, transaction });\n }\n if (dialect !== \"postgres\") {\n throw configError(\n `drizzleStore's dialect ${JSON.stringify(dialect)} is not supported. Use \"postgres\" or \"sqlite\".`,\n );\n }\n const store = sqlStore(postgresExecutor(db as DrizzlePostgres), { tables, transaction });\n return transaction ? withRoute(store) : store;\n}\n"],"mappings":";;;;;;;AAOA,MAAM,cAA0C;CAAE,UAAU;CAAY,QAAQ;AAAM;AAEtF,SAAgB,WAAW,SAAqB,EAAE,KAAK,MAAM,UAA6B;CACxF,MAAM,SAAqB,CAAC;CAC5B,IAAI,MAAM;CACV,KAAK,MAAM,CAAC,UAAU,UAAU,CAAC,GAAG,KAAK,SAAS,YAAY,QAAQ,CAAC,CAAC,CAAC,QAAQ,GAAG;EAElF,MAAM,QAAQ,OAAO,MAAM,OAAO,KAAA,IAAY,WAAW,OAAO,MAAM,EAAE,IAAI;EAC5E,OAAO,KAAK,IAAI,IAAI,KAAK,MAAM,KAAK,MAAM,KAAK,CAAC,GAAG,IAAI,MAAM,KAAK,CAAC;EACnE,MAAM,MAAM,QAAQ,MAAM,EAAE,CAAC;CAC/B;CACA,OAAO,KAAK,IAAI,IAAI,KAAK,MAAM,GAAG,CAAC,CAAC;CACpC,OAAO,IAAI,KAAK,MAAM;AACxB;;ACGA,MAAM,WAAW,WACf,OAAO,WAAW,YAAY,WAAW,OAAO,KAAK,O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AAM,gBAAgB;GACrC,aAAa,MAAM,cAAc;GACjC,OAAO,MAAM,OAAO;GACpB,WAAW,KAAK,YAAY,CAAC,CAAC,QAAQ;EACxC,CACoB;CAAE;AACxB;;ACrDA,SAAgB,aACd,IACA,SACwB;CACxB,MAAM,EAAE,SAAS,QAAQ,cAAc,UAAU;CACjD,IAAI,YAAY,UAEd,OAAO,SAAS,eAAe,EAAwC,GAAG;EAAE;EAAQ;CAAY,CAAC;CAEnG,IAAI,YAAY,YACd,MAAM,YACJ,0BAA0B,KAAK,UAAU,OAAO,EAAE,+CACpD;CAEF,MAAM,QAAQ,SAAS,iBAAiB,EAAqB,GAAG;EAAE;EAAQ;CAAY,CAAC;CACvF,OAAO,cAAc,UAAU,KAAK,IAAI;AAC1C"}
@@ -1,4 +1,4 @@
1
- import { c as TransactionalStore, n as CloudropStore } from "../store-BfCJejGh.js";
1
+ import { l as TransactionalStore, n as CloudropStore } from "../store-B539nY3J.js";
2
2
  import { t as StoreTables } from "../tables-DZnw2sPK.js";
3
3
  /** What the store calls on a Prisma client, or on the client of an interactive transaction. */
4
4
  export interface PrismaQueryable {
@@ -1,5 +1,5 @@
1
1
  import { n as configError } from "../errors-CUxMmFAe.js";
2
- import { i as sequential, n as sqlStore, t as withRoute } from "../transactional-DnvnGsVH.js";
2
+ import { i as sequential, n as sqlStore, t as withRoute } from "../transactional-CiNwMiDb.js";
3
3
  // src/adapters/prisma.ts
4
4
  const on = (client, dialect) => sequential(dialect, async (sql, params) => await client.$queryRawUnsafe(sql, ...params));
5
5
  function checkOptions(options) {
@@ -1,4 +1,4 @@
1
- import { c as TransactionalStore, n as CloudropStore } from "../store-BfCJejGh.js";
1
+ import { l as TransactionalStore, n as CloudropStore } from "../store-B539nY3J.js";
2
2
  import { a as TransactionalSqlExecutor, i as SqlStatement, n as SqlExecutor, r as SqlRow, t as SqlDialect } from "../executor-CEA7WV2W.js";
3
3
  import { t as StoreTables } from "../tables-DZnw2sPK.js";
4
4
  interface SqlStoreOptions {
@@ -1,4 +1,4 @@
1
- import { i as sequential, n as sqlStore$1, t as withRoute } from "../transactional-DnvnGsVH.js";
1
+ import { i as sequential, n as sqlStore$1, t as withRoute } from "../transactional-CiNwMiDb.js";
2
2
  import { t as d1Executor } from "../d1-BY2c5bcL.js";
3
3
  // src/adapters/sql/pg.ts
4
4
  const on$1 = (client) => sequential("postgres", async (sql, params) => (await client.query(sql, [...params])).rows);
@@ -1,6 +1,36 @@
1
- import { E as CloudropError, _ as RouteResult, g as RouteName, h as RouteMetadata, i as CompleteResponse, k as Result, u as InferableCloudrop } from "./types-BrAx3dA4.js";
1
+ import { E as CloudropError, _ as RouteResult, g as RouteName, h as RouteMetadata, i as CompleteResponse, k as Result, u as InferableCloudrop } from "./types-CFfMw-n_.js";
2
2
  /** How the client sends every request: the endpoints' POSTs and the bucket's PUTs. */
3
3
  type ClientFetch = (url: string, init: RequestInit) => Promise<Response>;
4
+ /** Headers for the upload server only, or a function, possibly async, that gives them before each request (M8-L5). */
5
+ type ServerHeaders = HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
6
+ interface ClientOptions {
7
+ /** Where the server's handler is mounted: a path on this page's origin or an absolute URL. Default "/api/cloudrop". */
8
+ basePath?: string;
9
+ /**
10
+ * Headers for the requests to the upload server (/upload, /sign, /complete and /abort), never for bucket PUTs: an
11
+ * object, or a function, possibly async, called before each request, such as one that returns a fresh bearer token.
12
+ */
13
+ headers?: ServerHeaders;
14
+ /** Replaces the global fetch, for tests and runtimes that bring their own. Bucket PUTs then go through it too. */
15
+ fetch?: ClientFetch;
16
+ /**
17
+ * How many bucket PUTs this client sends at once, across all its uploads: 1 to 16, or "auto" (the default), which
18
+ * starts at 4, adds one while the bytes sent keep rising, up to 8, and halves on a network error or a busy bucket.
19
+ */
20
+ concurrency?: number | "auto";
21
+ /** Which PUTs go first when they wait for a connection: "added" (the default) or "smallest-first" by file size. */
22
+ order?: "added" | "smallest-first";
23
+ /**
24
+ * Keeps each unfinished multipart upload in the browser's IndexedDB, with its upload token, until the file ends, so
25
+ * that it can resume after a reload. Default true; false keeps nothing on disk.
26
+ */
27
+ persist?: boolean;
28
+ /**
29
+ * Keeps one signed-in user's unfinished uploads apart from another's in the same browser: pass the user's id. At most
30
+ * 256 characters; default "".
31
+ */
32
+ namespace?: string;
33
+ }
4
34
  /** Where one file of a job stands. `done`, `failed` and `aborted` are final. */
5
35
  type FileStatus = "queued" | "uploading" | "paused" | "completing" | "done" | "failed" | "aborted";
6
36
  /** One file as a page renders it (spec §2.1). */
@@ -146,29 +176,6 @@ interface ResumableUpload<TName extends string = string> {
146
176
  /** ISO 8601: when its token expires. A minute before that it is no longer listed. */
147
177
  expiresAt: string;
148
178
  }
149
- interface ClientOptions {
150
- /** Where the server's handler is mounted: a path on this page's origin or an absolute URL. Default "/api/cloudrop". */
151
- basePath?: string;
152
- /** Replaces the global fetch, for tests and runtimes that bring their own. */
153
- fetch?: ClientFetch;
154
- /**
155
- * How many bucket PUTs this client sends at once, across all its uploads: 1 to 16, or "auto" (the default), which
156
- * starts at 4, adds one while the bytes sent keep rising, up to 8, and halves on a network error or a busy bucket.
157
- */
158
- concurrency?: number | "auto";
159
- /** Which PUTs go first when they wait for a connection: "added" (the default) or "smallest-first" by file size. */
160
- order?: "added" | "smallest-first";
161
- /**
162
- * Keeps each unfinished multipart upload in the browser's IndexedDB, with its upload token, until the file ends, so
163
- * that it can resume after a reload. Default true; false keeps nothing on disk.
164
- */
165
- persist?: boolean;
166
- /**
167
- * Keeps one signed-in user's unfinished uploads apart from another's in the same browser: pass the user's id. At most
168
- * 256 characters; default "".
169
- */
170
- namespace?: string;
171
- }
172
179
  interface UploadOptions<TMetadata = unknown> {
173
180
  /** Validated by the route's schema on the server. */
174
181
  metadata?: TMetadata;
@@ -209,6 +216,17 @@ interface CloudropClient<TCloudrop extends InferableCloudrop = InferableCloudrop
209
216
  }): Promise<Result<{
210
217
  forgotten: number;
211
218
  }>>;
219
+ /**
220
+ * Stops the client for good, in any phase and as often as called: start(), upload() and resume() are refused with
221
+ * CLIENT_CLOSED, and every file of every route stops. A file that may have completed is kept. Without options, as
222
+ * when another user signed in in another tab, each multipart upload keeps its record and gets no /abort, so its user
223
+ * can resume it on a new client; `{ abort: true }`, at sign-out, cancels every file as job.abort() does, telling the
224
+ * server. The first call decides; resumable(), discard() and forget() keep working. Resolves once every file it
225
+ * stopped has ended and each /abort it sent was answered, also for every later call; never rejects.
226
+ */
227
+ close(options?: {
228
+ abort: true;
229
+ }): Promise<void>;
212
230
  }
213
231
  declare function createCloudropClient<TCloudrop extends InferableCloudrop = InferableCloudrop>(options?: ClientOptions): CloudropClient<TCloudrop>;
214
- export { createCloudropClient as a, FileSnapshot as c, ResumableUpload as d, UploadJob as f, UploadOptions as i, FileStatus as l, CloudropClient as n, FileHandle as o, UploadResult as p, UploadArguments as r, FileOutcome as s, ClientOptions as t, JobSnapshot as u };
232
+ export { FileHandle as a, FileStatus as c, UploadJob as d, UploadResult as f, createCloudropClient as i, JobSnapshot as l, UploadArguments as n, FileOutcome as o, ClientOptions as p, UploadOptions as r, FileSnapshot as s, CloudropClient as t, ResumableUpload as u };