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.
Files changed (48) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +21 -0
  3. package/README.md +101 -2
  4. package/dist/adapters/drizzle.d.ts +204 -0
  5. package/dist/adapters/drizzle.js +216 -0
  6. package/dist/adapters/drizzle.js.map +1 -0
  7. package/dist/adapters/prisma.d.ts +81 -0
  8. package/dist/adapters/prisma.js +32 -0
  9. package/dist/adapters/prisma.js.map +1 -0
  10. package/dist/adapters/sql.d.ts +98 -0
  11. package/dist/adapters/sql.js +70 -0
  12. package/dist/adapters/sql.js.map +1 -0
  13. package/dist/client-Dj6ON4MN.d.ts +214 -0
  14. package/dist/client-Y1zUEbCj.js +1561 -0
  15. package/dist/client-Y1zUEbCj.js.map +1 -0
  16. package/dist/client.d.ts +3 -0
  17. package/dist/client.js +3 -0
  18. package/dist/d1-BY2c5bcL.js +16 -0
  19. package/dist/d1-BY2c5bcL.js.map +1 -0
  20. package/dist/errors-CUxMmFAe.js +40 -0
  21. package/dist/errors-CUxMmFAe.js.map +1 -0
  22. package/dist/executor-CEA7WV2W.d.ts +27 -0
  23. package/dist/index.d.ts +421 -0
  24. package/dist/index.js +3007 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/input-DTC476_I.js +13 -0
  27. package/dist/input-DTC476_I.js.map +1 -0
  28. package/dist/next.d.ts +9 -0
  29. package/dist/next.js +14 -0
  30. package/dist/next.js.map +1 -0
  31. package/dist/node.d.ts +32 -0
  32. package/dist/node.js +100 -0
  33. package/dist/node.js.map +1 -0
  34. package/dist/part-size-CvMoobfC.js +9 -0
  35. package/dist/part-size-CvMoobfC.js.map +1 -0
  36. package/dist/react.d.ts +123 -0
  37. package/dist/react.js +355 -0
  38. package/dist/react.js.map +1 -0
  39. package/dist/route-CspI1Ypt.js +72 -0
  40. package/dist/route-CspI1Ypt.js.map +1 -0
  41. package/dist/store-BfCJejGh.d.ts +382 -0
  42. package/dist/tables-DZnw2sPK.d.ts +11 -0
  43. package/dist/transactional-DnvnGsVH.js +672 -0
  44. package/dist/transactional-DnvnGsVH.js.map +1 -0
  45. package/dist/types-BZUOaz_B.js +5 -0
  46. package/dist/types-BZUOaz_B.js.map +1 -0
  47. package/dist/types-BrAx3dA4.d.ts +185 -0
  48. package/package.json +110 -4
@@ -0,0 +1,13 @@
1
+ import { t as CloudropError } from "./errors-CUxMmFAe.js";
2
+ // src/input.ts
3
+ function invalidInput(message) {
4
+ return new CloudropError("INVALID_INPUT", message);
5
+ }
6
+ function isPlainObject(value) {
7
+ if (typeof value !== "object" || value === null) return false;
8
+ const prototype = Object.getPrototypeOf(value);
9
+ return prototype === Object.prototype || prototype === null;
10
+ }
11
+ export { isPlainObject as n, invalidInput as t };
12
+
13
+ //# sourceMappingURL=input-DTC476_I.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"input-DTC476_I.js","names":[],"sources":["../src/input.ts"],"sourcesContent":["// Untrusted input: the error for it, and the plain-object check every JSON reader uses. Shared by storage, server and\n// client.\n\nimport { CloudropError } from \"./errors.ts\";\n\nexport function invalidInput(message: string): CloudropError {\n return new CloudropError(\"INVALID_INPUT\", message);\n}\n\n/** An object literal or Object.create(null): never an array, a Map, a Response, an Error or another class instance. */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"],"mappings":";;AAKA,SAAgB,aAAa,SAAgC;CAC3D,OAAO,IAAI,cAAc,iBAAiB,OAAO;AACnD;AAGA,SAAgB,cAAc,OAAkD;CAC9E,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD"}
package/dist/next.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { m as RequestHandler } from "./types-BrAx3dA4.js";
2
+ export interface NextRouteHandlers {
3
+ GET(request: Request): Promise<Response>;
4
+ POST(request: Request): Promise<Response>;
5
+ /** CORS preflights from trustedOrigins. */
6
+ OPTIONS(request: Request): Promise<Response>;
7
+ }
8
+ export declare function toNextHandler(cloudrop: RequestHandler): NextRouteHandlers;
9
+ export type { RequestHandler };
package/dist/next.js ADDED
@@ -0,0 +1,14 @@
1
+ import { n as configError } from "./errors-CUxMmFAe.js";
2
+ // src/next.ts
3
+ function toNextHandler(cloudrop) {
4
+ if (typeof cloudrop?.handler !== "function") throw configError("toNextHandler needs the cloudrop server, an object with a handler function: pass what createCloudrop returned.");
5
+ const handle = (request) => cloudrop.handler(request);
6
+ return {
7
+ GET: handle,
8
+ POST: handle,
9
+ OPTIONS: handle
10
+ };
11
+ }
12
+ export { toNextHandler };
13
+
14
+ //# sourceMappingURL=next.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next.js","names":[],"sources":["../src/next.ts"],"sourcesContent":["// cloudrop/next: `export const { GET, POST, OPTIONS } = toNextHandler(cloudrop)` in app/api/cloudrop/[...all]/route.ts.\n\nimport { configError } from \"./errors.ts\";\nimport type { RequestHandler } from \"./protocol/types.ts\";\n\nexport type { RequestHandler } from \"./protocol/types.ts\";\n\nexport interface NextRouteHandlers {\n GET(request: Request): Promise<Response>;\n POST(request: Request): Promise<Response>;\n /** CORS preflights from trustedOrigins. */\n OPTIONS(request: Request): Promise<Response>;\n}\n\nexport function toNextHandler(cloudrop: RequestHandler): NextRouteHandlers {\n // Plain JavaScript can pass anything here.\n if (typeof (cloudrop as Partial<RequestHandler> | null)?.handler !== \"function\") {\n throw configError(\n \"toNextHandler needs the cloudrop server, an object with a handler function: pass what createCloudrop returned.\",\n );\n }\n // Called on cloudrop, not detached from it, so a handler that reads `this` keeps working.\n const handle = (request: Request) => cloudrop.handler(request);\n return { GET: handle, POST: handle, OPTIONS: handle };\n}\n"],"mappings":";;AAcA,SAAgB,cAAc,UAA6C;CAEzE,IAAI,OAAQ,UAA6C,YAAY,YACnE,MAAM,YACJ,gHACF;CAGF,MAAM,UAAU,YAAqB,SAAS,QAAQ,OAAO;CAC7D,OAAO;EAAE,KAAK;EAAQ,MAAM;EAAQ,SAAS;CAAO;AACtD"}
package/dist/node.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ import { m as RequestHandler } from "./types-BrAx3dA4.js";
2
+ /** The parts of Node's IncomingMessage this adapter reads. */
3
+ export interface NodeRequest extends AsyncIterable<Uint8Array> {
4
+ method?: string;
5
+ url?: string;
6
+ /** Express and Connect move the mount path out of `url` into this. */
7
+ originalUrl?: string;
8
+ headers: Record<string, string | string[] | undefined>;
9
+ /**
10
+ * Names and values in the order they arrived; the only place a second Host header still shows. Node always sets it;
11
+ * a hand-built request without it is read from `headers` alone.
12
+ */
13
+ rawHeaders?: string[];
14
+ socket: object;
15
+ }
16
+ /** The parts of Node's ServerResponse this adapter writes. */
17
+ export interface NodeResponse {
18
+ /** True once the status line and headers have gone out: no other answer can be sent then. */
19
+ readonly headersSent: boolean;
20
+ /** An object of headers is the form every `writeHead` wrapper understands; set-cookie carries a list of values. */
21
+ writeHead(status: number, headers: Record<string, string | string[]>): unknown;
22
+ end(body: Uint8Array): unknown;
23
+ }
24
+ /**
25
+ * Never rejects: Node ignores the listener's promise, so a rejection would be an unhandled rejection that stops the
26
+ * process. Node accepts requests a fetch Request cannot hold (TRACE, an absolute URL with port 99999), requests that
27
+ * name no single valid host, and clients that hang up mid-body; those get a 400, or nothing once the socket is gone. A
28
+ * handler that throws, or answers with something that cannot be sent, gets the client a 500 and is logged to the
29
+ * console.
30
+ */
31
+ export declare function toNodeHandler(cloudrop: RequestHandler): (request: NodeRequest, response: NodeResponse) => Promise<void>;
32
+ export type { RequestHandler };
package/dist/node.js ADDED
@@ -0,0 +1,100 @@
1
+ import { n as configError } from "./errors-CUxMmFAe.js";
2
+ import { t as MAX_BODY_BYTES } from "./types-BZUOaz_B.js";
3
+ // src/node.ts
4
+ async function discardRest(iterator) {
5
+ let chunk = await iterator.next();
6
+ while (!chunk.done) chunk = await iterator.next();
7
+ }
8
+ async function readBody(request) {
9
+ const iterator = request[Symbol.asyncIterator]();
10
+ const chunks = [];
11
+ let length = 0;
12
+ while (length <= MAX_BODY_BYTES) {
13
+ const chunk = await iterator.next();
14
+ if (chunk.done) break;
15
+ chunks.push(chunk.value);
16
+ length += chunk.value.length;
17
+ }
18
+ if (length > 65536) discardRest(iterator).catch(() => void 0);
19
+ const body = new Uint8Array(length);
20
+ let offset = 0;
21
+ for (const chunk of chunks) {
22
+ body.set(chunk, offset);
23
+ offset += chunk.length;
24
+ }
25
+ return body;
26
+ }
27
+ function hostOrigin(scheme, value) {
28
+ if (typeof value !== "string" || /[@/\\?#]/.test(value)) return null;
29
+ return URL.parse(`${scheme}://${value}`)?.origin ?? null;
30
+ }
31
+ function requestOrigin(request, scheme) {
32
+ if ((request.rawHeaders ?? []).filter((name, index) => index % 2 === 0 && name.toLowerCase() === "host").length > 1) return null;
33
+ const { host, ":authority": authority } = request.headers;
34
+ const named = [host, authority].filter((value) => value !== void 0);
35
+ const origins = new Set(named.map((value) => hostOrigin(scheme, value)));
36
+ return origins.size === 1 ? [...origins][0] ?? null : null;
37
+ }
38
+ function toUrl(request) {
39
+ const base = requestOrigin(request, "encrypted" in request.socket && request.socket.encrypted === true ? "https" : "http");
40
+ if (base === null) throw new TypeError("The request names no single valid host.");
41
+ const target = request.originalUrl ?? request.url ?? "/";
42
+ if (!target.startsWith("/")) throw new TypeError("The request target is not a path.");
43
+ return new URL(`${base}${target}`);
44
+ }
45
+ async function toRequest(request) {
46
+ const headers = new Headers();
47
+ for (const [name, value] of Object.entries(request.headers)) {
48
+ if (name.startsWith(":") || value === void 0) continue;
49
+ for (const item of [value].flat()) headers.append(name, item);
50
+ }
51
+ const method = request.method ?? "GET";
52
+ const body = method === "GET" || method === "HEAD" ? void 0 : await readBody(request);
53
+ return new Request(toUrl(request), {
54
+ method,
55
+ headers,
56
+ body
57
+ });
58
+ }
59
+ const UNREADABLE = { error: {
60
+ code: "INVALID_INPUT",
61
+ message: "The request could not be read. Check its method and URL, then send it again.",
62
+ retryable: false
63
+ } };
64
+ const FAILED = { error: {
65
+ code: "SERVER_ERROR",
66
+ message: "The server could not handle the upload. Contact the site owner if this keeps happening.",
67
+ retryable: false
68
+ } };
69
+ function json(body, status) {
70
+ return new Response(JSON.stringify(body), {
71
+ status,
72
+ headers: {
73
+ "content-type": "application/json",
74
+ "cache-control": "no-store"
75
+ }
76
+ });
77
+ }
78
+ async function send(response, answer) {
79
+ const body = new Uint8Array(await answer.arrayBuffer());
80
+ const headers = Object.fromEntries(answer.headers);
81
+ const cookies = answer.headers.getSetCookie();
82
+ if (cookies.length > 0) headers["set-cookie"] = cookies;
83
+ response.writeHead(answer.status, headers);
84
+ response.end(body);
85
+ }
86
+ function toNodeHandler(cloudrop) {
87
+ if (typeof cloudrop?.handler !== "function") throw configError("toNodeHandler needs the cloudrop server, an object with a handler function: pass what createCloudrop returned.");
88
+ return async (request, response) => {
89
+ try {
90
+ const incoming = await toRequest(request).catch(() => null);
91
+ await send(response, incoming ? await cloudrop.handler(incoming) : json(UNREADABLE, 400));
92
+ } catch (error) {
93
+ console.error("cloudrop/node: the handler threw or gave an answer that could not be sent; answering 500 instead.", error);
94
+ if (!response.headersSent) await send(response, json(FAILED, 500)).catch(() => void 0);
95
+ }
96
+ };
97
+ }
98
+ export { toNodeHandler };
99
+
100
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","names":[],"sources":["../src/node.ts"],"sourcesContent":["// cloudrop/node: `http.createServer(toNodeHandler(cloudrop))`, or mount it in Express with\n// `app.use(\"/api/cloudrop\", toNodeHandler(cloudrop))` before any body parser: a parser that reads the body first leaves\n// nothing to read.\n// The library compiles without Node's types (tsconfig `types: []`), so the two Node objects are described by the\n// members used here; node.test.ts proves real IncomingMessage and ServerResponse values fit them.\n\nimport { configError } from \"./errors.ts\";\nimport { type ErrorResponse, MAX_BODY_BYTES, type RequestHandler } from \"./protocol/types.ts\";\n\nexport type { RequestHandler } from \"./protocol/types.ts\";\n\n/** The parts of Node's IncomingMessage this adapter reads. */\nexport interface NodeRequest extends AsyncIterable<Uint8Array> {\n method?: string;\n url?: string;\n /** Express and Connect move the mount path out of `url` into this. */\n originalUrl?: string;\n headers: Record<string, string | string[] | undefined>;\n /**\n * Names and values in the order they arrived; the only place a second Host header still shows. Node always sets it;\n * a hand-built request without it is read from `headers` alone.\n */\n rawHeaders?: string[];\n socket: object;\n}\n\n/** The parts of Node's ServerResponse this adapter writes. */\nexport interface NodeResponse {\n /** True once the status line and headers have gone out: no other answer can be sent then. */\n readonly headersSent: boolean;\n /** An object of headers is the form every `writeHead` wrapper understands; set-cookie carries a list of values. */\n writeHead(status: number, headers: Record<string, string | string[]>): unknown;\n end(body: Uint8Array): unknown;\n}\n\n/** Reads and drops whatever is left, so the connection is free for the next request. */\nasync function discardRest(iterator: AsyncIterator<Uint8Array>): Promise<void> {\n let chunk = await iterator.next();\n while (!chunk.done) chunk = await iterator.next();\n}\n\n/**\n * Reads at most one chunk past the cap, so the handler sees an oversized body and answers 413. The iterator is not\n * closed, since that would destroy the socket before the answer is sent. Node does not drop a body that has an\n * iterator, so the rest is read and dropped here; without that the socket waits paused until Node times it out. A\n * client that never stops sending is cut off by the server's own `requestTimeout` (300 seconds by default in Node).\n */\nasync function readBody(request: NodeRequest): Promise<Uint8Array<ArrayBuffer>> {\n const iterator = request[Symbol.asyncIterator]();\n const chunks: Uint8Array[] = [];\n let length = 0;\n while (length <= MAX_BODY_BYTES) {\n const chunk = await iterator.next();\n if (chunk.done) break;\n chunks.push(chunk.value);\n length += chunk.value.length;\n }\n // A client that hangs up mid-way rejects the iterator: nothing is left to drop then.\n if (length > MAX_BODY_BYTES) discardRest(iterator).catch(() => undefined);\n const body = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n body.set(chunk, offset);\n offset += chunk.length;\n }\n return body;\n}\n\n// The origin a Host or \":authority\" value names, or null unless the value is just a host and an optional port.\nfunction hostOrigin(scheme: string, value: string | string[] | undefined): string | null {\n // The URL parser would read userinfo as credentials and \"/\", \"\\\", \"?\" or \"#\" as the start of a path.\n if (typeof value !== \"string\" || /[@/\\\\?#]/.test(value)) return null;\n return URL.parse(`${scheme}://${value}`)?.origin ?? null;\n}\n\n// The origin of the host the request names: Host, or HTTP/2's \":authority\" pseudo-header. Null, so the request is\n// refused, when there is none, when Host is sent twice (RFC 9112 §3.2), when the two name different hosts (RFC 9113\n// §8.3.1), or when either is more than a host and port. No origin is invented for a request that names none.\n// (Line comments: the build keeps doc blocks in the published file, and these functions are private.)\nfunction requestOrigin(request: NodeRequest, scheme: string): string | null {\n // rawHeaders alternates names and values.\n const hosts = (request.rawHeaders ?? []).filter((name, index) => index % 2 === 0 && name.toLowerCase() === \"host\");\n if (hosts.length > 1) return null;\n const { host, \":authority\": authority } = request.headers;\n const named = [host, authority].filter((value) => value !== undefined);\n const origins = new Set(named.map((value) => hostOrigin(scheme, value)));\n return origins.size === 1 ? ([...origins][0] ?? null) : null;\n}\n\nfunction toUrl(request: NodeRequest): URL {\n // No X-Forwarded-* header is trusted: behind a proxy, list the public origin in trustedOrigins instead.\n const scheme = \"encrypted\" in request.socket && request.socket.encrypted === true ? \"https\" : \"http\";\n const base = requestOrigin(request, scheme);\n if (base === null) throw new TypeError(\"The request names no single valid host.\");\n const target = request.originalUrl ?? request.url ?? \"/\";\n // Only a path may follow the Host header's origin: \"//other.host/…\" or an absolute URL would replace that origin,\n // and a caller could then make any Origin look same-origin.\n if (!target.startsWith(\"/\")) throw new TypeError(\"The request target is not a path.\");\n return new URL(`${base}${target}`);\n}\n\nasync function toRequest(request: NodeRequest): Promise<Request> {\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n // HTTP/2 pseudo-headers (\":authority\") are not header names a Request accepts.\n if (name.startsWith(\":\") || value === undefined) continue;\n for (const item of [value].flat()) headers.append(name, item);\n }\n const method = request.method ?? \"GET\";\n const body = method === \"GET\" || method === \"HEAD\" ? undefined : await readBody(request);\n return new Request(toUrl(request), { method, headers, body });\n}\n\nconst UNREADABLE: ErrorResponse = {\n error: {\n code: \"INVALID_INPUT\",\n message: \"The request could not be read. Check its method and URL, then send it again.\",\n retryable: false,\n },\n};\n\n// The same words cloudrop's own handler uses for SERVER_ERROR, so a client sees one message for it.\nconst FAILED: ErrorResponse = {\n error: {\n code: \"SERVER_ERROR\",\n message: \"The server could not handle the upload. Contact the site owner if this keeps happening.\",\n retryable: false,\n },\n};\n\nfunction json(body: ErrorResponse, status: number): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\", \"cache-control\": \"no-store\" },\n });\n}\n\n/** The body is read in full before anything is written, so an answer that fails mid-read can still become a 500. */\nasync function send(response: NodeResponse, answer: Response): Promise<void> {\n const body = new Uint8Array(await answer.arrayBuffer());\n const headers: Record<string, string | string[]> = Object.fromEntries(answer.headers);\n // Headers joins repeated values with a comma, which breaks cookies: they are sent one by one.\n const cookies = answer.headers.getSetCookie();\n if (cookies.length > 0) headers[\"set-cookie\"] = cookies;\n response.writeHead(answer.status, headers);\n response.end(body);\n}\n\n/**\n * Never rejects: Node ignores the listener's promise, so a rejection would be an unhandled rejection that stops the\n * process. Node accepts requests a fetch Request cannot hold (TRACE, an absolute URL with port 99999), requests that\n * name no single valid host, and clients that hang up mid-body; those get a 400, or nothing once the socket is gone. A\n * handler that throws, or answers with something that cannot be sent, gets the client a 500 and is logged to the\n * console.\n */\nexport function toNodeHandler(\n cloudrop: RequestHandler,\n): (request: NodeRequest, response: NodeResponse) => Promise<void> {\n // Plain JavaScript can pass anything here.\n if (typeof (cloudrop as Partial<RequestHandler> | null)?.handler !== \"function\") {\n throw configError(\n \"toNodeHandler needs the cloudrop server, an object with a handler function: pass what createCloudrop returned.\",\n );\n }\n return async (request, response) => {\n try {\n const incoming = await toRequest(request).catch(() => null);\n await send(response, incoming ? await cloudrop.handler(incoming) : json(UNREADABLE, 400));\n } catch (error) {\n console.error(\n \"cloudrop/node: the handler threw or gave an answer that could not be sent; answering 500 instead.\",\n error,\n );\n // When even this fails, the socket is gone and nobody is left to answer.\n if (!response.headersSent) await send(response, json(FAILED, 500)).catch(() => undefined);\n }\n };\n}\n"],"mappings":"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"}
@@ -0,0 +1,9 @@
1
+ // src/part-size.ts
2
+ const countParts = (size, partSize) => Math.ceil(size / partSize);
3
+ function sizeOfPart(size, partSize, partNumber) {
4
+ const count = countParts(size, partSize);
5
+ return partNumber < count ? partSize : size - (count - 1) * partSize;
6
+ }
7
+ export { sizeOfPart as n, countParts as t };
8
+
9
+ //# sourceMappingURL=part-size-CvMoobfC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"part-size-CvMoobfC.js","names":[],"sources":["../src/part-size.ts"],"sourcesContent":["// How a file is cut into parts, apart from the planner's storage rules (plan.ts): the browser client needs only these\n// two, and importing them from plan.ts would ship the rules and size constants it never uses.\n\n/** How many parts of `partSize` bytes a file of `size` bytes needs. */\nexport const countParts = (size: number, partSize: number): number => Math.ceil(size / partSize);\n\n/**\n * The size of part `partNumber` (from 1): `partSize` for every part but the last, which holds the rest. Equal parts\n * satisfy R2's equal-part rule by construction (spec §5.1).\n */\nexport function sizeOfPart(size: number, partSize: number, partNumber: number): number {\n const count = countParts(size, partSize);\n return partNumber < count ? partSize : size - (count - 1) * partSize;\n}\n"],"mappings":";AAIA,MAAa,cAAc,MAAc,aAA6B,KAAK,KAAK,OAAO,QAAQ;AAM/F,SAAgB,WAAW,MAAc,UAAkB,YAA4B;CACrF,MAAM,QAAQ,WAAW,MAAM,QAAQ;CACvC,OAAO,aAAa,QAAQ,WAAW,QAAQ,QAAQ,KAAK;AAC9D"}
@@ -0,0 +1,123 @@
1
+ import { _ as RouteResult, g as RouteName, h as RouteMetadata, k as Result, u as InferableCloudrop } from "./types-BrAx3dA4.js";
2
+ import { c as FileSnapshot, d as ResumableUpload, n as CloudropClient, p as UploadResult, s as FileOutcome, t as ClientOptions, u as JobSnapshot } from "./client-Dj6ON4MN.js";
3
+ import { ChangeEvent, DragEvent } from "react";
4
+ /** The client's options, to create the client on first use in the browser; or `{ client }` to share one. */
5
+ type UploadHooksOptions<TCloudrop extends InferableCloudrop> = ClientOptions | {
6
+ client: CloudropClient<TCloudrop> & {
7
+ resumable: (route?: RouteName<TCloudrop>) => unknown;
8
+ };
9
+ };
10
+ interface UseUploadOptions<TMetadata> {
11
+ /** Sent with every upload of the hook, validated by the route's schema; the latest render's value is used. */
12
+ metadata?: TMetadata;
13
+ /** The input's `multiple`; without it a drop uploads only its first file. Default false. */
14
+ multiple?: boolean;
15
+ /** The input's `accept`, such as "image/*": it filters the file picker only, the route's `accept` decides. */
16
+ accept?: string;
17
+ }
18
+ /** The options argument is required when the route's metadata is. */
19
+ type UseUploadArguments<TMetadata> = undefined extends TMetadata ? [options?: UseUploadOptions<TMetadata>] : [options: UseUploadOptions<TMetadata> & {
20
+ metadata: TMetadata;
21
+ }];
22
+ /** One file of useUpload's `files`: the client's snapshot of it, with that file's controls (FileHandle). */
23
+ interface UploadItem<R> extends FileSnapshot<R> {
24
+ pause(): void;
25
+ resume(): void;
26
+ abort(): void;
27
+ retry(): Promise<FileOutcome<R>>;
28
+ }
29
+ /** Spread onto an `<input>`: picking files uploads them. */
30
+ interface InputProps {
31
+ type: "file";
32
+ multiple: boolean;
33
+ accept: string | undefined;
34
+ /** Uploads the picked files and clears the input, so that picking the same file again uploads it again. */
35
+ onChange(event: ChangeEvent<HTMLInputElement>): void;
36
+ }
37
+ /** Spread onto any element: dropping files on it uploads them. */
38
+ interface DropProps {
39
+ onDragEnter(event: DragEvent<HTMLElement>): void;
40
+ onDragOver(event: DragEvent<HTMLElement>): void;
41
+ onDragLeave(event: DragEvent<HTMLElement>): void;
42
+ onDrop(event: DragEvent<HTMLElement>): void;
43
+ }
44
+ interface UseUploadResult<R, TName extends string, TMetadata> {
45
+ /**
46
+ * Every file of the uploads started on this route through any hook of the factory, in start order, kept across
47
+ * unmounts. A file's object changes only when that file does.
48
+ */
49
+ files: readonly UploadItem<R>[];
50
+ /** As JobSnapshot's totals, across the uploads in `files`: failed and aborted files are left out of the bytes. */
51
+ totals: JobSnapshot<R>["totals"];
52
+ /** True while a file is queued, uploading or completing; a paused file is not uploading. */
53
+ isUploading: boolean;
54
+ /** True while files are dragged over the element that has getDropProps(). */
55
+ isDragOver: boolean;
56
+ /**
57
+ * Starts one upload of the files and resolves with its result once every file has first settled. A FileList, an
58
+ * array or one File; null or an empty list resolves null and starts nothing. The call's metadata replaces the hook's.
59
+ */
60
+ upload(files: File | ArrayLike<File> | null, options?: {
61
+ metadata?: TMetadata;
62
+ }): Promise<UploadResult<R> | null>;
63
+ getInputProps(): InputProps;
64
+ getDropProps(): DropProps;
65
+ /** Pauses every queued or uploading file in `files`. */
66
+ pause(): void;
67
+ /** Resumes every paused file in `files`. */
68
+ resume(): void;
69
+ /** Continues an upload useResumable listed, with the file the user picked again, as one more upload in `files`. */
70
+ resume(upload: ResumableUpload<TName>, file: File): Promise<UploadResult<R>>;
71
+ /** Cancels every file in `files` that has not ended done. */
72
+ abort(): void;
73
+ /** Sends every failed file in `files` again; resolves once they have settled. */
74
+ retry(): Promise<void>;
75
+ /**
76
+ * Removes from `files`, for every component on the route, the uploads whose every file ended done or aborted. One
77
+ * with a failed file stays: retry() can still send it.
78
+ */
79
+ clear(): void;
80
+ }
81
+ /** One route's records as a union per route, so that `record.route === "files"` narrows the record. */
82
+ type ResumableOf<TName extends string> = TName extends string ? ResumableUpload<TName> : never;
83
+ interface UseResumableResult<TName extends string> {
84
+ /** The client's resumable() list, newest first; `[]` on the server, before the first read and when it failed. */
85
+ uploads: readonly ResumableOf<TName>[];
86
+ /** Reads the list again; resolves with the client's answer, whose error says why the list is empty. */
87
+ refresh(): Promise<Result<ResumableOf<TName>[]>>;
88
+ /**
89
+ * The client's discard(): drops one listed upload without its file, then reads the list again. `aborted` is true once
90
+ * the server accepted the /abort, which keeps a file whose /complete finished; false when the token could no longer
91
+ * abort anything (the bucket's lifecycle rule cleans up).
92
+ */
93
+ discard(upload: ResumableOf<TName>): Promise<Result<{
94
+ aborted: boolean;
95
+ }>>;
96
+ /**
97
+ * The client's forget(): deletes the unfinished uploads of the client's namespace, of every route, not only this
98
+ * hook's, then reads the list again.
99
+ */
100
+ forget(): Promise<Result<{
101
+ forgotten: number;
102
+ }>>;
103
+ }
104
+ interface UploadHooks<TCloudrop extends InferableCloudrop> {
105
+ /**
106
+ * Uploads to `route`, with the files, progress and controls a page renders. Every component on one route shares its
107
+ * list, and unmounting cancels nothing: a component that mounts again shows its running and failed files.
108
+ */
109
+ useUpload<TName extends RouteName<TCloudrop>>(route: TName, ...options: UseUploadArguments<RouteMetadata<TCloudrop, TName>>): UseUploadResult<RouteResult<TCloudrop, TName>, TName, RouteMetadata<TCloudrop, TName>>;
110
+ /**
111
+ * The unfinished uploads this browser keeps, of `route` or of every route, without the ones this page holds; read
112
+ * after mount and whenever an upload of these hooks may have changed them.
113
+ */
114
+ useResumable<TName extends RouteName<TCloudrop> = RouteName<TCloudrop>>(route?: TName): UseResumableResult<TName>;
115
+ }
116
+ /**
117
+ * Creates `useUpload` and `useResumable` for one server's routes: `createUploadHooks<typeof cloudrop>()`, with a type
118
+ * import of the server's `cloudrop`. Takes the client's options, or `{ client }` to share a client. The client is
119
+ * created at the first upload or resumable read in the browser, never during a server render; a wrong option makes
120
+ * upload(), resume() and refresh() resolve with its INVALID_CONFIG error.
121
+ */
122
+ export declare function createUploadHooks<TCloudrop extends InferableCloudrop = InferableCloudrop>(options?: UploadHooksOptions<TCloudrop>): UploadHooks<TCloudrop>;
123
+ export type { DropProps, InputProps, UploadHooks, UploadHooksOptions, UploadItem, UseResumableResult, UseUploadOptions, UseUploadResult };