cloudrop 0.0.0-stage → 0.1.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 +56 -0
- package/LICENSE +21 -0
- package/README.md +101 -2
- package/dist/adapters/drizzle.d.ts +204 -0
- package/dist/adapters/drizzle.js +216 -0
- package/dist/adapters/drizzle.js.map +1 -0
- package/dist/adapters/prisma.d.ts +81 -0
- package/dist/adapters/prisma.js +32 -0
- package/dist/adapters/prisma.js.map +1 -0
- package/dist/adapters/sql.d.ts +98 -0
- package/dist/adapters/sql.js +70 -0
- package/dist/adapters/sql.js.map +1 -0
- package/dist/client-Dj6ON4MN.d.ts +214 -0
- package/dist/client-Y1zUEbCj.js +1561 -0
- package/dist/client-Y1zUEbCj.js.map +1 -0
- package/dist/client.d.ts +3 -0
- package/dist/client.js +3 -0
- package/dist/d1-BY2c5bcL.js +16 -0
- package/dist/d1-BY2c5bcL.js.map +1 -0
- package/dist/errors-CUxMmFAe.js +40 -0
- package/dist/errors-CUxMmFAe.js.map +1 -0
- package/dist/executor-CEA7WV2W.d.ts +27 -0
- package/dist/index.d.ts +421 -0
- package/dist/index.js +3007 -0
- package/dist/index.js.map +1 -0
- package/dist/input-DTC476_I.js +13 -0
- package/dist/input-DTC476_I.js.map +1 -0
- package/dist/next.d.ts +9 -0
- package/dist/next.js +14 -0
- package/dist/next.js.map +1 -0
- package/dist/node.d.ts +32 -0
- package/dist/node.js +100 -0
- package/dist/node.js.map +1 -0
- package/dist/part-size-CvMoobfC.js +9 -0
- package/dist/part-size-CvMoobfC.js.map +1 -0
- package/dist/react.d.ts +123 -0
- package/dist/react.js +355 -0
- package/dist/react.js.map +1 -0
- package/dist/route-CspI1Ypt.js +72 -0
- package/dist/route-CspI1Ypt.js.map +1 -0
- package/dist/store-BfCJejGh.d.ts +382 -0
- package/dist/tables-DZnw2sPK.d.ts +11 -0
- package/dist/transactional-DnvnGsVH.js +672 -0
- package/dist/transactional-DnvnGsVH.js.map +1 -0
- package/dist/types-BZUOaz_B.js +5 -0
- package/dist/types-BZUOaz_B.js.map +1 -0
- package/dist/types-BrAx3dA4.d.ts +185 -0
- package/package.json +110 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
Every notable change to the `cloudrop` package. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
|
|
5
|
+
[Semantic Versioning](https://semver.org/spec/v2.0.0.html): before 1.0, a minor version may change the API.
|
|
6
|
+
|
|
7
|
+
## Unreleased
|
|
8
|
+
|
|
9
|
+
## 0.1.0 - 2026-11-19
|
|
10
|
+
|
|
11
|
+
The first release. Version `0.0.0` on npm only reserved the name.
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
|
|
15
|
+
- **The server** (`cloudrop`): `createCloudrop` with routes declared by `route(policy, callbacks)`. Every route requires
|
|
16
|
+
an `authorize` function, which refuses a request with `unauthorized()` or `forbidden()`; size and type are checked
|
|
17
|
+
before an upload link is signed and again on the stored object. The handler serves four endpoints (`/upload`,
|
|
18
|
+
`/sign`, `/complete`, `/abort`), answers every request, with an error whose `code` and `message` say what to do when
|
|
19
|
+
it refuses one, and after `/upload` trusts only the signed upload token. `/upload` takes an optional idempotency key,
|
|
20
|
+
which the client sends with every request; with a store, a retry ends the pending rows of the attempt whose answer
|
|
21
|
+
was lost, so they hold no quota. `/abort` takes `keep: true`, which the client's `discard()` sends: without a store,
|
|
22
|
+
it aborts an unfinished upload but never deletes an object that already landed, since `onComplete` may have recorded
|
|
23
|
+
it. `cloudrop.api` gives server code the same operations without HTTP.
|
|
24
|
+
- **Storage drivers** for Cloudflare R2 (`r2()`) and any S3-compatible service (`s3()`), with SigV4 signing over
|
|
25
|
+
`fetch` and settings read from `CLOUDROP_*` environment variables on the first request, so a build needs no secrets.
|
|
26
|
+
`cloudrop.api.checkBucket` reports a missing CORS or lifecycle rule.
|
|
27
|
+
- **Adapters to mount the handler:** `cloudrop/next` for the Next.js App Router and `cloudrop/node` for Node's
|
|
28
|
+
`http`, Express and similar servers. Runtimes with `Request` and `Response` (Bun, Deno, Hono, Cloudflare Workers) use
|
|
29
|
+
the handler directly.
|
|
30
|
+
- **The browser client** (`cloudrop/client`): `createCloudropClient`, typed from the server's routes. Small files go in
|
|
31
|
+
one `PUT`, large files in parts sent in parallel; every request is retried with growing waits and honours
|
|
32
|
+
`Retry-After`; expired links are renewed and missing parts are sent again. Progress, speed and time left per file and
|
|
33
|
+
per job, pause, resume, cancel and retry per file or job, connections that adapt to the network, pausing while
|
|
34
|
+
offline, and resuming a large upload after a reload or a closed tab. `discard(upload)` drops one unfinished upload
|
|
35
|
+
without its file: the server aborts it and the browser deletes its record. `forget()` deletes every record and
|
|
36
|
+
aborts nothing, for sign-out.
|
|
37
|
+
- **React hooks** (`cloudrop/react`): `createUploadHooks` gives `useUpload` for inputs, drop zones and progress lists
|
|
38
|
+
and `useResumable` for uploads that continue after a reload, with `discard(upload)` and `forget()`, each followed by
|
|
39
|
+
a fresh read of every `useResumable`'s list. `react` 18 or 19 is an optional peer dependency.
|
|
40
|
+
- **An optional database store:** one row per upload before anything is signed, `onComplete` once per file (exactly
|
|
41
|
+
once for writes through its transaction on Postgres), a quota per owner that concurrent uploads cannot overshoot
|
|
42
|
+
(refused with `QUOTA_EXCEEDED`), revocation of an owner's uploads, and a sweep that cleans up abandoned uploads.
|
|
43
|
+
`tables.schema` puts the store's tables in a Postgres schema. Postgres time columns are `timestamptz(3)`, the
|
|
44
|
+
millisecond precision of a JavaScript `Date`. cloudrop 0.x ships no migrations: Postgres tables created from the
|
|
45
|
+
repository before this release keep working as they are; recreate them, or apply the change drizzle-kit and Prisma
|
|
46
|
+
propose, to match.
|
|
47
|
+
Adapters: `cloudrop/adapters/sql` (node-postgres, postgres.js, `node:sqlite`, Cloudflare D1),
|
|
48
|
+
`cloudrop/adapters/drizzle` (`drizzle-orm` 0.45 or later, including 1.x from 1.0.0-rc.5) and
|
|
49
|
+
`cloudrop/adapters/prisma` (Prisma 7).
|
|
50
|
+
- **Zero runtime dependencies.** Only web-platform APIs, so the server runs on Node.js 24+, Bun, Deno and Cloudflare
|
|
51
|
+
Workers. ESM only, with type declarations for every entry.
|
|
52
|
+
- **Examples** in the repository: `examples/next`, a Next.js app that uploads to a local RustFS container, Wrangler's
|
|
53
|
+
local R2 or real R2, with an upload UI on the hooks as its home page, a lab page and an opt-in SQLite store;
|
|
54
|
+
`examples/hono`, a Bun and Hono API with better-auth sign-in and a Drizzle store on Postgres; and
|
|
55
|
+
`examples/vite-react`, a Vite React app on another origin that uploads through it. Both web apps list unfinished
|
|
56
|
+
uploads after a reload, to resume by picking the file again or to discard.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vibe Code (vcode.sh)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,102 @@
|
|
|
1
|
-
#
|
|
1
|
+
# cloudrop
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Direct-to-bucket file uploads for Cloudflare R2 and S3-compatible storage. Your server decides who may upload and signs
|
|
4
|
+
short-lived links; the browser sends the bytes straight to the bucket, with progress, retries, pause and resume after a
|
|
5
|
+
reload.
|
|
6
|
+
|
|
7
|
+
Before 1.0, a minor version may change the API; every change is in the
|
|
8
|
+
[changelog](https://github.com/vcode-sh/cloudrop/blob/main/packages/cloudrop/CHANGELOG.md).
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm i cloudrop # or: bun add cloudrop, pnpm add cloudrop
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Quickstart
|
|
15
|
+
|
|
16
|
+
The server, in `lib/cloudrop.ts`. It reads `CLOUDROP_SECRET` and the `CLOUDROP_R2_*` credentials on the first request:
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { createCloudrop, r2, route, unauthorized } from "cloudrop";
|
|
20
|
+
|
|
21
|
+
export const cloudrop = createCloudrop({
|
|
22
|
+
storage: r2({ bucket: "media" }),
|
|
23
|
+
routes: {
|
|
24
|
+
avatar: route(
|
|
25
|
+
{
|
|
26
|
+
accept: "image/*",
|
|
27
|
+
maxSize: "5MB",
|
|
28
|
+
authorize: async ({ request }) => {
|
|
29
|
+
const user = await getUser(request); // your app's session lookup
|
|
30
|
+
return user ? { userId: user.id } : unauthorized();
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
{ prefix: ({ userId }) => `users/${userId}/avatars` },
|
|
34
|
+
),
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Mount it. In Next.js, `app/api/cloudrop/[...all]/route.ts`:
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { toNextHandler } from "cloudrop/next";
|
|
43
|
+
import { cloudrop } from "../../../../lib/cloudrop";
|
|
44
|
+
|
|
45
|
+
export const { GET, POST, OPTIONS } = toNextHandler(cloudrop);
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Upload from React. `createUploadHooks` needs only the server's type (a type import), so no server code reaches the
|
|
49
|
+
browser. Create the hooks once, in their own module when several components upload:
|
|
50
|
+
|
|
51
|
+
```tsx
|
|
52
|
+
"use client";
|
|
53
|
+
import { createUploadHooks } from "cloudrop/react";
|
|
54
|
+
import type { cloudrop } from "../lib/cloudrop";
|
|
55
|
+
|
|
56
|
+
const { useUpload } = createUploadHooks<typeof cloudrop>();
|
|
57
|
+
|
|
58
|
+
export function AvatarPicker() {
|
|
59
|
+
const { files, getInputProps } = useUpload("avatar", { accept: "image/*" });
|
|
60
|
+
const avatar = files.at(-1);
|
|
61
|
+
return (
|
|
62
|
+
<label>
|
|
63
|
+
Avatar <input {...getInputProps()} />
|
|
64
|
+
{avatar && `${avatar.status} ${Math.round(avatar.progress * 100)}%`}
|
|
65
|
+
{avatar?.error && <p role="alert">{avatar.error.message}</p>}
|
|
66
|
+
</label>
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Without React, `createCloudropClient` from `cloudrop/client` gives you `upload()`, which resolves to `{ data, error }`.
|
|
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).
|
|
76
|
+
|
|
77
|
+
## Bucket setup
|
|
78
|
+
|
|
79
|
+
The browser uploads to the bucket directly, so the bucket needs a CORS rule that allows `PUT` from your page's origin
|
|
80
|
+
with the headers cloudrop signs (`content-type`, `content-disposition`, `if-none-match`, `x-amz-meta-cloudrop-id`) and
|
|
81
|
+
exposes `ETag` and `Retry-After`, plus a lifecycle rule that aborts incomplete multipart uploads. Both rules, with the
|
|
82
|
+
Wrangler and AWS CLI commands: [Bucket setup](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/bucket-setup.md).
|
|
83
|
+
|
|
84
|
+
## Documentation
|
|
85
|
+
|
|
86
|
+
[All docs](https://github.com/vcode-sh/cloudrop/blob/main/docs/README.md) ·
|
|
87
|
+
[Server](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/server.md) ·
|
|
88
|
+
[Client](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/client.md) ·
|
|
89
|
+
[React](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/react.md) ·
|
|
90
|
+
[Database store](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/store.md) ·
|
|
91
|
+
[Deployment](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/deployment.md) ·
|
|
92
|
+
[Resume after reload](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/resume.md) ·
|
|
93
|
+
[Hono guide](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/hono.md) ·
|
|
94
|
+
[Errors](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/errors.md) ·
|
|
95
|
+
[Troubleshooting](https://github.com/vcode-sh/cloudrop/blob/main/docs/guide/troubleshooting.md)
|
|
96
|
+
|
|
97
|
+
Runs on Node.js 24+, Bun, Deno and Cloudflare Workers, with zero runtime dependencies. `cloudrop/react` needs React 18
|
|
98
|
+
or 19, an optional peer dependency.
|
|
99
|
+
|
|
100
|
+
## License
|
|
101
|
+
|
|
102
|
+
[MIT](https://github.com/vcode-sh/cloudrop/blob/main/LICENSE). Not affiliated with Cloudflare.
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { a as FileStatus, c as TransactionalStore, n as CloudropStore } from "../store-BfCJejGh.js";
|
|
2
|
+
import { t as StoreTables } from "../tables-DZnw2sPK.js";
|
|
3
|
+
import { r as SqlRow } from "../executor-CEA7WV2W.js";
|
|
4
|
+
import { SQL } from "drizzle-orm";
|
|
5
|
+
import { PgTableFn, bigint, integer, text, timestamp } from "drizzle-orm/pg-core";
|
|
6
|
+
import { integer as integer$1, sqliteTable, text as text$1 } from "drizzle-orm/sqlite-core";
|
|
7
|
+
import { BatchItem } from "drizzle-orm/batch";
|
|
8
|
+
/** What the store calls on a Drizzle Postgres database or transaction. */
|
|
9
|
+
interface DrizzlePostgresQueryable {
|
|
10
|
+
execute(query: SQL): PromiseLike<unknown>;
|
|
11
|
+
}
|
|
12
|
+
/** A Drizzle Postgres database: `drizzle(pool)` from `drizzle-orm/node-postgres`, `drizzle-orm/postgres-js`, … */
|
|
13
|
+
interface DrizzlePostgres extends DrizzlePostgresQueryable {
|
|
14
|
+
transaction<T>(run: (tx: DrizzlePostgresQueryable) => Promise<T>): Promise<T>;
|
|
15
|
+
}
|
|
16
|
+
/** The `tx` Drizzle hands to `db.transaction`'s callback, for this database's driver and schema. */
|
|
17
|
+
type DrizzleTransaction<TDb extends DrizzlePostgres> = Parameters<Parameters<TDb["transaction"]>[0]>[0];
|
|
18
|
+
/** What the store calls on a synchronous Drizzle SQLite database or transaction. */
|
|
19
|
+
interface DrizzleSqliteQueryable {
|
|
20
|
+
all<T = unknown>(query: SQL): T[];
|
|
21
|
+
run(query: SQL): unknown;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A Drizzle SQLite database over a synchronous driver: `drizzle(new Database(path))` from `drizzle-orm/better-sqlite3`.
|
|
25
|
+
* `transaction` is not generic here: drizzle-orm 0.45 types its answer as the callback's, 1.0 through a conditional type
|
|
26
|
+
* that refuses async callbacks, and both fit this shape.
|
|
27
|
+
*/
|
|
28
|
+
interface DrizzleSqlite extends DrizzleSqliteQueryable {
|
|
29
|
+
transaction(run: (tx: DrizzleSqliteQueryable) => SqlRow[][], config?: {
|
|
30
|
+
behavior?: "immediate";
|
|
31
|
+
}): unknown;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* A Drizzle SQLite database over an asynchronous driver with an atomic batch: `drizzle-orm/libsql` (Turso) or
|
|
35
|
+
* `drizzle-orm/d1`. `all` and `run` build a statement that runs when awaited, or as part of `batch`.
|
|
36
|
+
*/
|
|
37
|
+
interface DrizzleAsyncSqlite {
|
|
38
|
+
all<T = unknown>(query: SQL): BatchItem<"sqlite"> & PromiseLike<T[]>;
|
|
39
|
+
run(query: SQL): BatchItem<"sqlite"> & PromiseLike<unknown>;
|
|
40
|
+
batch(statements: readonly [BatchItem<"sqlite">, ...BatchItem<"sqlite">[]]): PromiseLike<readonly unknown[]>;
|
|
41
|
+
}
|
|
42
|
+
type Text$1 = ReturnType<typeof text>;
|
|
43
|
+
type Time$1 = ReturnType<typeof timestamp>;
|
|
44
|
+
type NotNull$1<TColumn extends {
|
|
45
|
+
notNull(): unknown;
|
|
46
|
+
}> = ReturnType<TColumn["notNull"]>;
|
|
47
|
+
type PrimaryKey$1<TColumn extends {
|
|
48
|
+
primaryKey(): unknown;
|
|
49
|
+
}> = ReturnType<TColumn["primaryKey"]>;
|
|
50
|
+
type Count$1 = NotNull$1<Extract<ReturnType<typeof bigint>, {
|
|
51
|
+
_: {
|
|
52
|
+
data: number;
|
|
53
|
+
};
|
|
54
|
+
}>>;
|
|
55
|
+
declare const textStandIn$1: Text$1;
|
|
56
|
+
type Status$1 = NotNull$1<ReturnType<typeof textStandIn$1.$type<FileStatus>>>;
|
|
57
|
+
declare const tableStandIn: PgTableFn<string | undefined>;
|
|
58
|
+
type FileColumns$1 = {
|
|
59
|
+
id: PrimaryKey$1<Text$1>;
|
|
60
|
+
route: NotNull$1<Text$1>;
|
|
61
|
+
key: NotNull$1<Text$1>;
|
|
62
|
+
owner: Text$1;
|
|
63
|
+
status: Status$1;
|
|
64
|
+
name: NotNull$1<Text$1>;
|
|
65
|
+
type: NotNull$1<Text$1>;
|
|
66
|
+
size: Count$1;
|
|
67
|
+
uploadId: Text$1;
|
|
68
|
+
metadata: Text$1;
|
|
69
|
+
result: Text$1;
|
|
70
|
+
claim: Text$1;
|
|
71
|
+
claimedAt: Time$1;
|
|
72
|
+
expiresAt: NotNull$1<Time$1>;
|
|
73
|
+
createdAt: NotNull$1<Time$1>;
|
|
74
|
+
updatedAt: NotNull$1<Time$1>;
|
|
75
|
+
completedAt: Time$1;
|
|
76
|
+
endedAt: Time$1;
|
|
77
|
+
cleanedAt: Time$1;
|
|
78
|
+
requestKey: Text$1;
|
|
79
|
+
};
|
|
80
|
+
type UsageColumns$1 = {
|
|
81
|
+
owner: PrimaryKey$1<Text$1>;
|
|
82
|
+
reservedBytes: Count$1;
|
|
83
|
+
activeBytes: Count$1;
|
|
84
|
+
files: NotNull$1<ReturnType<typeof integer>>;
|
|
85
|
+
updatedAt: NotNull$1<Time$1>;
|
|
86
|
+
};
|
|
87
|
+
/** `cloudropPgTables()`: the files and usage tables as Drizzle `pg-core` tables, in a schema with `tables.schema`. */
|
|
88
|
+
interface CloudropPgTables {
|
|
89
|
+
files: ReturnType<typeof tableStandIn<string, FileColumns$1>>;
|
|
90
|
+
usage: ReturnType<typeof tableStandIn<string, UsageColumns$1>>;
|
|
91
|
+
}
|
|
92
|
+
/** The tables' names and, on Postgres, their schema: pass the same `tables` as to `drizzleStore`. */
|
|
93
|
+
interface CloudropTablesOptions {
|
|
94
|
+
tables?: StoreTables;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The store's tables as Drizzle `pg-core` tables, for an app's schema and migrations (drizzle-kit picks them up from
|
|
98
|
+
* the schema file that exports them) and for typed reads: `db.select().from(files)`. Write to them only through the
|
|
99
|
+
* store, which keeps `usage` in step with `files`.
|
|
100
|
+
*
|
|
101
|
+
* ```ts
|
|
102
|
+
* export const { files: cloudropFiles, usage: cloudropUsage } = cloudropPgTables();
|
|
103
|
+
* const inApp = cloudropPgTables({ tables: { schema: "app" } });
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
export declare function cloudropPgTables(options?: CloudropTablesOptions): CloudropPgTables;
|
|
107
|
+
type Text = ReturnType<typeof text$1<string, [string, ...string[]], never>>;
|
|
108
|
+
type Time = ReturnType<typeof integer$1<"timestamp_ms">>;
|
|
109
|
+
type Count = NotNull<ReturnType<typeof integer$1>>;
|
|
110
|
+
type NotNull<TColumn extends {
|
|
111
|
+
notNull(): unknown;
|
|
112
|
+
}> = ReturnType<TColumn["notNull"]>;
|
|
113
|
+
type PrimaryKey<TColumn extends {
|
|
114
|
+
primaryKey(): unknown;
|
|
115
|
+
}> = ReturnType<TColumn["primaryKey"]>;
|
|
116
|
+
declare const textStandIn: Text;
|
|
117
|
+
type Status = NotNull<ReturnType<typeof textStandIn.$type<FileStatus>>>;
|
|
118
|
+
type FileColumns = {
|
|
119
|
+
id: PrimaryKey<Text>;
|
|
120
|
+
route: NotNull<Text>;
|
|
121
|
+
key: NotNull<Text>;
|
|
122
|
+
owner: Text;
|
|
123
|
+
status: Status;
|
|
124
|
+
name: NotNull<Text>;
|
|
125
|
+
type: NotNull<Text>;
|
|
126
|
+
size: Count;
|
|
127
|
+
uploadId: Text;
|
|
128
|
+
metadata: Text;
|
|
129
|
+
result: Text;
|
|
130
|
+
claim: Text;
|
|
131
|
+
claimedAt: Time;
|
|
132
|
+
expiresAt: NotNull<Time>;
|
|
133
|
+
createdAt: NotNull<Time>;
|
|
134
|
+
updatedAt: NotNull<Time>;
|
|
135
|
+
completedAt: Time;
|
|
136
|
+
endedAt: Time;
|
|
137
|
+
cleanedAt: Time;
|
|
138
|
+
requestKey: Text;
|
|
139
|
+
};
|
|
140
|
+
type UsageColumns = {
|
|
141
|
+
owner: PrimaryKey<Text>;
|
|
142
|
+
reservedBytes: Count;
|
|
143
|
+
activeBytes: Count;
|
|
144
|
+
files: Count;
|
|
145
|
+
updatedAt: NotNull<Time>;
|
|
146
|
+
};
|
|
147
|
+
/** `cloudropSqliteTables()`: the files and usage tables as Drizzle `sqlite-core` tables. */
|
|
148
|
+
interface CloudropSqliteTables {
|
|
149
|
+
files: ReturnType<typeof sqliteTable<string, FileColumns>>;
|
|
150
|
+
usage: ReturnType<typeof sqliteTable<string, UsageColumns>>;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The store's tables as Drizzle `sqlite-core` tables, for an app's schema and migrations (drizzle-kit picks them up from
|
|
154
|
+
* the schema file that exports them) and for typed reads: `db.select().from(files)`. Write to them only through the
|
|
155
|
+
* store, which keeps `usage` in step with `files`.
|
|
156
|
+
*
|
|
157
|
+
* ```ts
|
|
158
|
+
* export const { files: cloudropFiles, usage: cloudropUsage } = cloudropSqliteTables();
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
export declare function cloudropSqliteTables(options?: {
|
|
162
|
+
tables?: Omit<StoreTables, "schema">;
|
|
163
|
+
}): CloudropSqliteTables;
|
|
164
|
+
/**
|
|
165
|
+
* A cloudrop store over a Drizzle database: Postgres (node-postgres over a `Pool`, postgres.js) or SQLite
|
|
166
|
+
* (better-sqlite3, libsql/Turso, D1). Create the tables first, from `cloudropPgTables` or `cloudropSqliteTables` in
|
|
167
|
+
* your Drizzle schema or from the documented DDL; the store checks them on its first call. `tables` names them,
|
|
168
|
+
* defaults `cloudrop_files` and `cloudrop_usage`, and on Postgres `tables.schema` names their schema (pass the same
|
|
169
|
+
* `tables` to `cloudropPgTables`). A single node-postgres `Client` is refused: every request would share its one
|
|
170
|
+
* connection, and a transaction on it would take the others' statements with it.
|
|
171
|
+
*
|
|
172
|
+
* With `transaction: true` (Postgres only), `onComplete` runs inside the completion's transaction with Drizzle's `tx`:
|
|
173
|
+
* an app row written through `tx` commits with the upload or not at all, and routes must come from `store.route`.
|
|
174
|
+
* Postgres waits at most 2 s for the row lock, so a second `/complete` of the same file answers busy. Keep storage and
|
|
175
|
+
* other network calls out of that `onComplete`; they belong in `afterComplete`.
|
|
176
|
+
*
|
|
177
|
+
* Usage:
|
|
178
|
+
* ```ts
|
|
179
|
+
* const db = drizzle(new Pool({ connectionString }));
|
|
180
|
+
* const store = drizzleStore(db, { dialect: "postgres", transaction: true });
|
|
181
|
+
* const avatars = store.route({ accept: "image/*", maxSize: "5MB", authorize }, {
|
|
182
|
+
* owner: ({ userId }) => userId,
|
|
183
|
+
* onComplete: async ({ tx, userId, file }) => {
|
|
184
|
+
* await tx.update(users).set({ avatar: file.key }).where(eq(users.id, userId));
|
|
185
|
+
* },
|
|
186
|
+
* });
|
|
187
|
+
* export const cloudrop = createCloudrop({ storage, secret, store, routes: { avatars } });
|
|
188
|
+
* ```
|
|
189
|
+
*/
|
|
190
|
+
export declare function drizzleStore<TDb extends DrizzlePostgres>(db: TDb, options: {
|
|
191
|
+
dialect: "postgres";
|
|
192
|
+
tables?: StoreTables;
|
|
193
|
+
transaction: true;
|
|
194
|
+
}): TransactionalStore<DrizzleTransaction<TDb>>;
|
|
195
|
+
export declare function drizzleStore(db: DrizzlePostgres, options: {
|
|
196
|
+
dialect: "postgres";
|
|
197
|
+
tables?: StoreTables;
|
|
198
|
+
transaction?: false;
|
|
199
|
+
}): CloudropStore;
|
|
200
|
+
export declare function drizzleStore(db: DrizzleSqlite | DrizzleAsyncSqlite, options: {
|
|
201
|
+
dialect: "sqlite";
|
|
202
|
+
tables?: Omit<StoreTables, "schema">;
|
|
203
|
+
}): CloudropStore;
|
|
204
|
+
export type { CloudropPgTables, CloudropSqliteTables, CloudropTablesOptions, DrizzleAsyncSqlite, DrizzlePostgres, DrizzlePostgresQueryable, DrizzleSqlite, DrizzleSqliteQueryable, DrizzleTransaction, StoreTables };
|
|
@@ -0,0 +1,216 @@
|
|
|
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";
|
|
3
|
+
import { t as d1Executor } from "../d1-BY2c5bcL.js";
|
|
4
|
+
import { sql } from "drizzle-orm";
|
|
5
|
+
import { PgSchema, bigint, check, index, integer, pgTable, text, timestamp } from "drizzle-orm/pg-core";
|
|
6
|
+
import { index as index$1, integer as integer$1, sqliteTable, text as text$1 } from "drizzle-orm/sqlite-core";
|
|
7
|
+
// src/adapters/drizzle/statement.ts
|
|
8
|
+
const PLACEHOLDER = {
|
|
9
|
+
postgres: /\$(\d+)/g,
|
|
10
|
+
sqlite: /\?/g
|
|
11
|
+
};
|
|
12
|
+
function drizzleSql(dialect, { sql: text, params }) {
|
|
13
|
+
const chunks = [];
|
|
14
|
+
let end = 0;
|
|
15
|
+
for (const [position, match] of [...text.matchAll(PLACEHOLDER[dialect])].entries()) {
|
|
16
|
+
const value = params[match[1] === void 0 ? position : Number(match[1]) - 1];
|
|
17
|
+
chunks.push(sql.raw(text.slice(end, match.index)), sql.param(value));
|
|
18
|
+
end = match.index + match[0].length;
|
|
19
|
+
}
|
|
20
|
+
chunks.push(sql.raw(text.slice(end)));
|
|
21
|
+
return sql.join(chunks);
|
|
22
|
+
}
|
|
23
|
+
// src/adapters/drizzle/postgres.ts
|
|
24
|
+
const shapeOf = (result) => typeof result === "object" && result !== null ? `{ ${Object.keys(result).join(", ")} }` : typeof result;
|
|
25
|
+
async function rowsOf(target, statement) {
|
|
26
|
+
const result = await target.execute(drizzleSql("postgres", statement));
|
|
27
|
+
if (Array.isArray(result)) return result;
|
|
28
|
+
const { rows } = result ?? {};
|
|
29
|
+
if (Array.isArray(rows)) return rows;
|
|
30
|
+
throw configError(`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.`);
|
|
31
|
+
}
|
|
32
|
+
const on = (target) => sequential("postgres", (sql, params) => rowsOf(target, {
|
|
33
|
+
sql,
|
|
34
|
+
params
|
|
35
|
+
}));
|
|
36
|
+
function isSingleConnection(db) {
|
|
37
|
+
const client = db.$client;
|
|
38
|
+
if (typeof client !== "object" || client === null) return false;
|
|
39
|
+
const { query, connect } = client;
|
|
40
|
+
return typeof query === "function" && typeof connect === "function" && !client.constructor.name.includes("Pool");
|
|
41
|
+
}
|
|
42
|
+
function postgresExecutor(db) {
|
|
43
|
+
if (isSingleConnection(db)) throw configError("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.");
|
|
44
|
+
return {
|
|
45
|
+
...on(db),
|
|
46
|
+
batch: (statements) => db.transaction((tx) => on(tx).batch(statements)),
|
|
47
|
+
transaction: (run) => db.transaction((tx) => run(on(tx), tx))
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
// src/adapters/drizzle/sqlite.ts
|
|
51
|
+
const ANSWERS_ROWS = /^\s*SELECT\b|\bRETURNING\s/i;
|
|
52
|
+
const answersRows = ({ sql }) => ANSWERS_ROWS.test(sql);
|
|
53
|
+
function synchronousExecutor(db) {
|
|
54
|
+
const rowsOf = (target, statement) => {
|
|
55
|
+
const query = drizzleSql("sqlite", statement);
|
|
56
|
+
if (answersRows(statement)) return target.all(query);
|
|
57
|
+
target.run(query);
|
|
58
|
+
return [];
|
|
59
|
+
};
|
|
60
|
+
return {
|
|
61
|
+
dialect: "sqlite",
|
|
62
|
+
query: async (sql, params) => rowsOf(db, {
|
|
63
|
+
sql,
|
|
64
|
+
params
|
|
65
|
+
}),
|
|
66
|
+
batch: async (statements) => db.transaction((tx) => statements.map((statement) => rowsOf(tx, statement)), { behavior: "immediate" })
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function batchingExecutor(db) {
|
|
70
|
+
const built = (statement) => {
|
|
71
|
+
const query = drizzleSql("sqlite", statement);
|
|
72
|
+
return answersRows(statement) ? db.all(query) : db.run(query);
|
|
73
|
+
};
|
|
74
|
+
const rowsFrom = (statement, answer) => answersRows(statement) ? answer : [];
|
|
75
|
+
return {
|
|
76
|
+
dialect: "sqlite",
|
|
77
|
+
query: async (sql, params) => rowsFrom({
|
|
78
|
+
sql,
|
|
79
|
+
params
|
|
80
|
+
}, await built({
|
|
81
|
+
sql,
|
|
82
|
+
params
|
|
83
|
+
})),
|
|
84
|
+
async batch(statements) {
|
|
85
|
+
const [first, ...rest] = statements;
|
|
86
|
+
if (!first) return [];
|
|
87
|
+
const answers = await db.batch([built(first), ...rest.map(built)]);
|
|
88
|
+
return statements.map((statement, index) => rowsFrom(statement, answers[index]));
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function d1Binding(db) {
|
|
93
|
+
const client = "$client" in db ? db.$client : null;
|
|
94
|
+
return typeof client === "object" && client !== null && "prepare" in client && typeof client.prepare === "function" && "batch" in client && typeof client.batch === "function" ? client : null;
|
|
95
|
+
}
|
|
96
|
+
function sqliteExecutor(db) {
|
|
97
|
+
const d1 = d1Binding(db);
|
|
98
|
+
if (d1) return d1Executor(d1);
|
|
99
|
+
return "batch" in db && typeof db.batch === "function" ? batchingExecutor(db) : synchronousExecutor(db);
|
|
100
|
+
}
|
|
101
|
+
// src/adapters/drizzle/postgres-tables.ts
|
|
102
|
+
const Schema = PgSchema;
|
|
103
|
+
const time$1 = (name) => timestamp(name, {
|
|
104
|
+
withTimezone: true,
|
|
105
|
+
precision: 3,
|
|
106
|
+
mode: "date"
|
|
107
|
+
});
|
|
108
|
+
const count$1 = (name) => bigint(name, { mode: "number" }).notNull();
|
|
109
|
+
function cloudropPgTables(options = {}) {
|
|
110
|
+
const names = tableNames(options.tables, "postgres");
|
|
111
|
+
const table = names.schema === void 0 ? pgTable : new Schema(names.schema, void 0).table;
|
|
112
|
+
return {
|
|
113
|
+
files: table(names.files, {
|
|
114
|
+
id: text("id").primaryKey(),
|
|
115
|
+
route: text("route").notNull(),
|
|
116
|
+
key: text("key").notNull(),
|
|
117
|
+
owner: text("owner"),
|
|
118
|
+
status: text("status").$type().notNull(),
|
|
119
|
+
name: text("name").notNull(),
|
|
120
|
+
type: text("type").notNull(),
|
|
121
|
+
size: count$1("size"),
|
|
122
|
+
uploadId: text("upload_id"),
|
|
123
|
+
metadata: text("metadata"),
|
|
124
|
+
result: text("result"),
|
|
125
|
+
claim: text("claim"),
|
|
126
|
+
claimedAt: time$1("claimed_at"),
|
|
127
|
+
expiresAt: time$1("expires_at").notNull(),
|
|
128
|
+
createdAt: time$1("created_at").notNull(),
|
|
129
|
+
updatedAt: time$1("updated_at").notNull(),
|
|
130
|
+
completedAt: time$1("completed_at"),
|
|
131
|
+
endedAt: time$1("ended_at"),
|
|
132
|
+
cleanedAt: time$1("cleaned_at"),
|
|
133
|
+
requestKey: text("request_key")
|
|
134
|
+
}, (t) => [
|
|
135
|
+
index(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),
|
|
136
|
+
index(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),
|
|
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),
|
|
139
|
+
index(`${names.files}_key_idx`).on(t.key),
|
|
140
|
+
index(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey)
|
|
141
|
+
]),
|
|
142
|
+
usage: table(names.usage, {
|
|
143
|
+
owner: text("owner").primaryKey(),
|
|
144
|
+
reservedBytes: count$1("reserved_bytes"),
|
|
145
|
+
activeBytes: count$1("active_bytes"),
|
|
146
|
+
files: integer("files").notNull(),
|
|
147
|
+
updatedAt: time$1("updated_at").notNull()
|
|
148
|
+
}, (t) => [
|
|
149
|
+
check(`${names.usage}_reserved_bytes_check`, sql`${t.reservedBytes} >= 0`),
|
|
150
|
+
check(`${names.usage}_active_bytes_check`, sql`${t.activeBytes} >= 0`),
|
|
151
|
+
check(`${names.usage}_files_check`, sql`${t.files} >= 0`)
|
|
152
|
+
])
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
// src/adapters/drizzle/sqlite-tables.ts
|
|
156
|
+
const textColumn = (name) => text$1(name);
|
|
157
|
+
const time = (name) => integer$1(name, { mode: "timestamp_ms" });
|
|
158
|
+
const count = (name) => integer$1(name, { mode: "number" }).notNull();
|
|
159
|
+
function cloudropSqliteTables(options = {}) {
|
|
160
|
+
const names = tableNames(options.tables, "sqlite");
|
|
161
|
+
return {
|
|
162
|
+
files: sqliteTable(names.files, {
|
|
163
|
+
id: textColumn("id").primaryKey(),
|
|
164
|
+
route: textColumn("route").notNull(),
|
|
165
|
+
key: textColumn("key").notNull(),
|
|
166
|
+
owner: textColumn("owner"),
|
|
167
|
+
status: textColumn("status").$type().notNull(),
|
|
168
|
+
name: textColumn("name").notNull(),
|
|
169
|
+
type: textColumn("type").notNull(),
|
|
170
|
+
size: count("size"),
|
|
171
|
+
uploadId: textColumn("upload_id"),
|
|
172
|
+
metadata: textColumn("metadata"),
|
|
173
|
+
result: textColumn("result"),
|
|
174
|
+
claim: textColumn("claim"),
|
|
175
|
+
claimedAt: time("claimed_at"),
|
|
176
|
+
expiresAt: time("expires_at").notNull(),
|
|
177
|
+
createdAt: time("created_at").notNull(),
|
|
178
|
+
updatedAt: time("updated_at").notNull(),
|
|
179
|
+
completedAt: time("completed_at"),
|
|
180
|
+
endedAt: time("ended_at"),
|
|
181
|
+
cleanedAt: time("cleaned_at"),
|
|
182
|
+
requestKey: textColumn("request_key")
|
|
183
|
+
}, (t) => [
|
|
184
|
+
index$1(`${names.files}_status_expires_at_idx`).on(t.status, t.expiresAt),
|
|
185
|
+
index$1(`${names.files}_status_claimed_at_idx`).on(t.status, t.claimedAt),
|
|
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),
|
|
188
|
+
index$1(`${names.files}_key_idx`).on(t.key),
|
|
189
|
+
index$1(`${names.files}_route_request_key_idx`).on(t.route, t.requestKey)
|
|
190
|
+
]),
|
|
191
|
+
usage: sqliteTable(names.usage, {
|
|
192
|
+
owner: textColumn("owner").primaryKey(),
|
|
193
|
+
reservedBytes: count("reserved_bytes"),
|
|
194
|
+
activeBytes: count("active_bytes"),
|
|
195
|
+
files: count("files"),
|
|
196
|
+
updatedAt: time("updated_at").notNull()
|
|
197
|
+
})
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
// src/adapters/drizzle.ts
|
|
201
|
+
function drizzleStore(db, options) {
|
|
202
|
+
const { dialect, tables, transaction = false } = options;
|
|
203
|
+
if (dialect === "sqlite") return sqlStore(sqliteExecutor(db), {
|
|
204
|
+
tables,
|
|
205
|
+
transaction
|
|
206
|
+
});
|
|
207
|
+
if (dialect !== "postgres") throw configError(`drizzleStore's dialect ${JSON.stringify(dialect)} is not supported. Use "postgres" or "sqlite".`);
|
|
208
|
+
const store = sqlStore(postgresExecutor(db), {
|
|
209
|
+
tables,
|
|
210
|
+
transaction
|
|
211
|
+
});
|
|
212
|
+
return transaction ? withRoute(store) : store;
|
|
213
|
+
}
|
|
214
|
+
export { cloudropPgTables, cloudropSqliteTables, drizzleStore };
|
|
215
|
+
|
|
216
|
+
//# sourceMappingURL=drizzle.js.map
|