@fragno-dev/blobs 0.0.0-stage → 0.0.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/LICENSE.md +16 -0
- package/README.md +67 -2
- package/dist/definition.d.ts +30 -0
- package/dist/definition.d.ts.map +1 -0
- package/dist/definition.js +25 -0
- package/dist/definition.js.map +1 -0
- package/dist/index.d.ts +104 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/node_modules/.pnpm/@standard-schema_spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts +79 -0
- package/dist/node_modules/.pnpm/@standard-schema_spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts.map +1 -0
- package/dist/routes.d.ts +91 -0
- package/dist/routes.d.ts.map +1 -0
- package/dist/routes.js +368 -0
- package/dist/routes.js.map +1 -0
- package/dist/schema.js +13 -0
- package/dist/schema.js.map +1 -0
- package/dist/storage.d.ts +85 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +81 -0
- package/dist/storage.js.map +1 -0
- package/package.json +55 -3
package/LICENSE.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
Copyright 2025 - present "ReJot Nederland B.V.", and individual contributors.
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
|
4
|
+
associated documentation files (the “Software”), to deal in the Software without restriction,
|
|
5
|
+
including without limitation the rights to use, copy, modify, merge, publish, distribute,
|
|
6
|
+
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
|
7
|
+
furnished to do so, subject to the following conditions:
|
|
8
|
+
|
|
9
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial
|
|
10
|
+
portions of the Software.
|
|
11
|
+
|
|
12
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
|
|
13
|
+
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
14
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
|
|
15
|
+
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
16
|
+
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,68 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Blobs Fragment
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Large files for Fragno, kept in an S3-compatible bucket such as Cloudflare R2. Callers move bytes
|
|
4
|
+
straight to and from storage through presigned URLs; the fragment records each blob's key, size,
|
|
5
|
+
content type, and ETag, and deletes objects nobody needs anymore.
|
|
6
|
+
|
|
7
|
+
For files that fit in database rows, with search, edits, and atomic batches, use
|
|
8
|
+
`@fragno-dev/upload`.
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { createBlobsFragment, createS3BlobStorage } from "@fragno-dev/blobs";
|
|
12
|
+
|
|
13
|
+
const blobs = createBlobsFragment(
|
|
14
|
+
{
|
|
15
|
+
storage: createS3BlobStorage({
|
|
16
|
+
endpoint: "https://<account>.r2.cloudflarestorage.com",
|
|
17
|
+
bucket: "blobs",
|
|
18
|
+
pathStyle: true,
|
|
19
|
+
// Signs requests with AWS Signature Version 4, e.g. with aws4fetch.
|
|
20
|
+
signer,
|
|
21
|
+
fetch,
|
|
22
|
+
}),
|
|
23
|
+
// Prefixes every object key, so several fragments can share one bucket.
|
|
24
|
+
storageKeyPrefix: "tenant-1",
|
|
25
|
+
// Durable: each runs after its change commits, and may run more than once.
|
|
26
|
+
onBlobStored: async (blob, idempotencyKey) => {
|
|
27
|
+
await startTranscription(blob.key, { idempotencyKey });
|
|
28
|
+
},
|
|
29
|
+
onBlobDeleted: async (blob, idempotencyKey) => {},
|
|
30
|
+
},
|
|
31
|
+
{ databaseAdapter, mountRoute: "/api/blobs" },
|
|
32
|
+
);
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Routes
|
|
36
|
+
|
|
37
|
+
| Route | Behavior |
|
|
38
|
+
| ---------------------------------------------- | ------------------------------------------------------------------------- |
|
|
39
|
+
| `POST /uploads` | `{ key, contentType }` → a presigned PUT `url`, its `headers`, `uploadId` |
|
|
40
|
+
| `POST /uploads/:uploadId/complete` | Records what storage holds as the key's blob, replacing any earlier one |
|
|
41
|
+
| `GET /blobs?prefix=&cursor=&pageSize=` | Blobs by key, a page at a time |
|
|
42
|
+
| `GET /blobs/by-key?key=` | One blob's key, size, content type, and ETag |
|
|
43
|
+
| `GET /blobs/by-key/download-url?key=` | A presigned GET URL |
|
|
44
|
+
| `GET /blobs/by-key/range?key=&offset=&length=` | Up to 8 MiB of the blob's bytes from `offset` |
|
|
45
|
+
| `DELETE /blobs/by-key?key=` | Deletes the blob and its object |
|
|
46
|
+
|
|
47
|
+
An upload's URL accepts one PUT for an hour, and completion stays open for another hour, so a PUT
|
|
48
|
+
that started in time may finish late. The uploader need not know the size in advance: completion
|
|
49
|
+
reads it and the ETag from storage, and fails with `UPLOAD_CONTENT_MISSING` until the bytes arrive.
|
|
50
|
+
Creating another upload for the same key replaces an unfinished one. Every upload writes its own
|
|
51
|
+
object, so neither an unfinished upload nor a replacement touches the object a download URL reads.
|
|
52
|
+
|
|
53
|
+
A download URL ends in the last segment of the blob's key, so browsers save the file under its name.
|
|
54
|
+
Storage serves the bytes with the content type they were uploaded with, so browsers show some types,
|
|
55
|
+
such as videos, in place.
|
|
56
|
+
|
|
57
|
+
A range read returns the bytes with status 206, a `Content-Range` giving the blob's size, and the
|
|
58
|
+
blob's `ETag`, so readers combining several ranges can tell whether the blob was replaced between
|
|
59
|
+
them. It ends early at the blob's end, and fails with `RANGE_NOT_SATISFIABLE` from there on. It
|
|
60
|
+
reads only bytes that still carry the blob's ETag, and fails with `BLOB_CHANGED` when storage holds
|
|
61
|
+
others, as when the upload's URL overwrote the object after completion. Readers can look inside
|
|
62
|
+
large files without downloading them, such as a zip archive's directory at its end.
|
|
63
|
+
|
|
64
|
+
`onBlobStored` runs for a new blob and for a replacement; `onBlobDeleted` runs only for
|
|
65
|
+
`DELETE /blobs/by-key`. Both receive the blob as `GET /blobs/by-key` returns it.
|
|
66
|
+
|
|
67
|
+
Durable hooks delete objects nobody references: a replaced or deleted blob's object once the change
|
|
68
|
+
commits, and an unfinished upload's object once its URL can no longer write it.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { BlobStorage } from "./storage.js";
|
|
2
|
+
//#region src/definition.d.ts
|
|
3
|
+
/** A blob as callers and hooks see it. */
|
|
4
|
+
type StoredBlob = {
|
|
5
|
+
key: string;
|
|
6
|
+
sizeBytes: number;
|
|
7
|
+
contentType: string;
|
|
8
|
+
/** Storage's tag for the blob's bytes; it changes whenever the bytes do. */
|
|
9
|
+
etag: string;
|
|
10
|
+
};
|
|
11
|
+
interface BlobsFragmentConfig {
|
|
12
|
+
storage: BlobStorage;
|
|
13
|
+
/** Prefixes every object key, so several fragments can keep their blobs in one bucket. */
|
|
14
|
+
storageKeyPrefix: string;
|
|
15
|
+
/**
|
|
16
|
+
* Runs, durably and possibly more than once, after an upload stores a blob or replaces the one at
|
|
17
|
+
* its key.
|
|
18
|
+
*/
|
|
19
|
+
onBlobStored?: (blob: StoredBlob, idempotencyKey: string) => Promise<void>;
|
|
20
|
+
/** Runs, durably and possibly more than once, after a blob is deleted. */
|
|
21
|
+
onBlobDeleted?: (blob: StoredBlob, idempotencyKey: string) => Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
type UnfinishedUpload = {
|
|
24
|
+
uploadId: string;
|
|
25
|
+
key: string;
|
|
26
|
+
objectKey: string;
|
|
27
|
+
};
|
|
28
|
+
//#endregion
|
|
29
|
+
export { BlobsFragmentConfig, StoredBlob, UnfinishedUpload };
|
|
30
|
+
//# sourceMappingURL=definition.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"definition.d.ts","names":[],"sources":["../src/definition.ts"],"mappings":";;;KAOY;EACV;EACA;EACA;;EAEA;;UAGe;EACf,SAAS;;EAET;;;;;EAKA,gBAAgB,MAAM,YAAY,2BAA2B;;EAE7D,iBAAiB,MAAM,YAAY,2BAA2B;;KAGpD;EAAqB;EAAkB;EAAa"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { blobsSchema } from "./schema.js";
|
|
2
|
+
import { defineFragment } from "@fragno-dev/core";
|
|
3
|
+
import { withDatabase } from "@fragno-dev/db";
|
|
4
|
+
//#region src/definition.ts
|
|
5
|
+
const blobsFragmentDefinition = defineFragment("blobs").extend(withDatabase(blobsSchema)).provideHooks(({ defineHook, config }) => ({
|
|
6
|
+
onBlobStored: defineHook(async function(blob) {
|
|
7
|
+
await config.onBlobStored?.(blob, this.idempotencyKey);
|
|
8
|
+
}),
|
|
9
|
+
onBlobDeleted: defineHook(async function(blob) {
|
|
10
|
+
await config.onBlobDeleted?.(blob, this.idempotencyKey);
|
|
11
|
+
}),
|
|
12
|
+
deleteObject: defineHook(async function({ objectKey }) {
|
|
13
|
+
await config.storage.deleteObject(objectKey);
|
|
14
|
+
}),
|
|
15
|
+
discardUnfinishedUpload: defineHook(async function({ uploadId, key, objectKey }) {
|
|
16
|
+
if (!await this.handlerTx().retrieve(({ forSchema }) => forSchema(blobsSchema).findFirst("blob_upload", (b) => b.whereIndex("primary", (eb) => eb("id", "=", uploadId))).findFirst("blob", (b) => b.whereIndex("idx_blob_key", (eb) => eb("key", "=", key)))).mutate(({ forSchema, retrieveResult: [upload, blob] }) => {
|
|
17
|
+
if (upload) forSchema(blobsSchema).delete("blob_upload", upload.id, (b) => b.check());
|
|
18
|
+
return blob?.objectKey === objectKey;
|
|
19
|
+
}).execute()) await config.storage.deleteObject(objectKey);
|
|
20
|
+
})
|
|
21
|
+
})).build();
|
|
22
|
+
//#endregion
|
|
23
|
+
export { blobsFragmentDefinition };
|
|
24
|
+
|
|
25
|
+
//# sourceMappingURL=definition.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"definition.js","names":[],"sources":["../src/definition.ts"],"sourcesContent":["import { defineFragment } from \"@fragno-dev/core\";\nimport { withDatabase } from \"@fragno-dev/db\";\n\nimport { blobsSchema } from \"./schema\";\nimport type { BlobStorage } from \"./storage\";\n\n/** A blob as callers and hooks see it. */\nexport type StoredBlob = {\n key: string;\n sizeBytes: number;\n contentType: string;\n /** Storage's tag for the blob's bytes; it changes whenever the bytes do. */\n etag: string;\n};\n\nexport interface BlobsFragmentConfig {\n storage: BlobStorage;\n /** Prefixes every object key, so several fragments can keep their blobs in one bucket. */\n storageKeyPrefix: string;\n /**\n * Runs, durably and possibly more than once, after an upload stores a blob or replaces the one at\n * its key.\n */\n onBlobStored?: (blob: StoredBlob, idempotencyKey: string) => Promise<void>;\n /** Runs, durably and possibly more than once, after a blob is deleted. */\n onBlobDeleted?: (blob: StoredBlob, idempotencyKey: string) => Promise<void>;\n}\n\nexport type UnfinishedUpload = { uploadId: string; key: string; objectKey: string };\n\nexport const blobsFragmentDefinition = defineFragment<BlobsFragmentConfig>(\"blobs\")\n .extend(withDatabase(blobsSchema))\n .provideHooks(({ defineHook, config }) => ({\n onBlobStored: defineHook(async function (blob: StoredBlob) {\n await config.onBlobStored?.(blob, this.idempotencyKey);\n }),\n onBlobDeleted: defineHook(async function (blob: StoredBlob) {\n await config.onBlobDeleted?.(blob, this.idempotencyKey);\n }),\n deleteObject: defineHook(async function ({ objectKey }: { objectKey: string }) {\n await config.storage.deleteObject(objectKey);\n }),\n discardUnfinishedUpload: defineHook(async function ({\n uploadId,\n key,\n objectKey,\n }: UnfinishedUpload) {\n const published = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(blobsSchema)\n .findFirst(\"blob_upload\", (b) =>\n b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", uploadId)),\n )\n .findFirst(\"blob\", (b) => b.whereIndex(\"idx_blob_key\", (eb) => eb(\"key\", \"=\", key))),\n )\n .mutate(({ forSchema, retrieveResult: [upload, blob] }) => {\n if (upload) {\n forSchema(blobsSchema).delete(\"blob_upload\", upload.id, (b) => b.check());\n }\n return blob?.objectKey === objectKey;\n })\n .execute();\n\n // The upload has expired, so it can no longer become its key's blob, and whatever its URL\n // stored is garbage unless the upload already did.\n if (!published) {\n await config.storage.deleteObject(objectKey);\n }\n }),\n }))\n .build();\n"],"mappings":";;;;AA8BA,MAAa,0BAA0B,eAAoC,OAAO,CAAC,CAChF,OAAO,aAAa,WAAW,CAAC,CAAC,CACjC,cAAc,EAAE,YAAY,cAAc;CACzC,cAAc,WAAW,eAAgB,MAAkB;EACzD,MAAM,OAAO,eAAe,MAAM,KAAK,cAAc;CACvD,CAAC;CACD,eAAe,WAAW,eAAgB,MAAkB;EAC1D,MAAM,OAAO,gBAAgB,MAAM,KAAK,cAAc;CACxD,CAAC;CACD,cAAc,WAAW,eAAgB,EAAE,aAAoC;EAC7E,MAAM,OAAO,QAAQ,aAAa,SAAS;CAC7C,CAAC;CACD,yBAAyB,WAAW,eAAgB,EAClD,UACA,KACA,aACmB;EAmBnB,IAAI,CAAC,MAlBmB,KAAK,UAAU,CAAC,CACrC,UAAU,EAAE,gBACX,UAAU,WAAW,CAAC,CACnB,UAAU,gBAAgB,MACzB,EAAE,WAAW,YAAY,OAAO,GAAG,MAAM,KAAK,QAAQ,CAAC,CACzD,CAAC,CACA,UAAU,SAAS,MAAM,EAAE,WAAW,iBAAiB,OAAO,GAAG,OAAO,KAAK,GAAG,CAAC,CAAC,CACvF,CAAC,CACA,QAAQ,EAAE,WAAW,gBAAgB,CAAC,QAAQ,YAAY;GACzD,IAAI,QACF,UAAU,WAAW,CAAC,CAAC,OAAO,eAAe,OAAO,KAAK,MAAM,EAAE,MAAM,CAAC;GAE1E,OAAO,MAAM,cAAc;EAC7B,CAAC,CAAC,CACD,QAAQ,GAKT,MAAM,OAAO,QAAQ,aAAa,SAAS;CAE/C,CAAC;AACH,EAAE,CAAC,CACF,MAAM"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { BlobStorage, ObjectRange, S3BlobStorageOptions, S3Signer, StoredObject, createS3BlobStorage } from "./storage.js";
|
|
2
|
+
import { BlobsFragmentConfig, StoredBlob, UnfinishedUpload } from "./definition.js";
|
|
3
|
+
import { StandardSchemaV1 } from "./node_modules/.pnpm/@standard-schema_spec@1.1.0/node_modules/@standard-schema/spec/dist/index.js";
|
|
4
|
+
import { FragnoPublicConfigWithDatabase } from "@fragno-dev/db";
|
|
5
|
+
//#region src/index.d.ts
|
|
6
|
+
declare function createBlobsFragment(config: BlobsFragmentConfig, options: FragnoPublicConfigWithDatabase): import("@fragno-dev/core").FragnoInstantiatedFragment<readonly [import("@fragno-dev/core").FragnoRouteConfig<"POST", "/uploads", import("zod").ZodObject<{
|
|
7
|
+
key: import("zod").ZodString;
|
|
8
|
+
contentType: import("zod").ZodString;
|
|
9
|
+
}, import("zod/v4/core").$strip>, import("zod").ZodObject<{
|
|
10
|
+
uploadId: import("zod").ZodString;
|
|
11
|
+
key: import("zod").ZodString;
|
|
12
|
+
url: import("zod").ZodString;
|
|
13
|
+
headers: import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodString>;
|
|
14
|
+
expiresAt: import("zod").ZodDate;
|
|
15
|
+
}, import("zod/v4/core").$strip>, "INVALID_KEY" | "INVALID_RANGE" | "RANGE_NOT_SATISFIABLE" | "UPLOAD_NOT_FOUND" | "UPLOAD_EXPIRED" | "UPLOAD_CONTENT_MISSING" | "BLOB_NOT_FOUND" | "BLOB_CHANGED" | "STORAGE_ERROR", string, import("@fragno-dev/db").DatabaseRequestContext<{
|
|
16
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
17
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
18
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
19
|
+
objectKey: string;
|
|
20
|
+
}>;
|
|
21
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
22
|
+
}>>, import("@fragno-dev/core").FragnoRouteConfig<"POST", "/uploads/:uploadId/complete", StandardSchemaV1<unknown, unknown> | undefined, import("zod").ZodObject<{
|
|
23
|
+
key: import("zod").ZodString;
|
|
24
|
+
sizeBytes: import("zod").ZodNumber;
|
|
25
|
+
contentType: import("zod").ZodString;
|
|
26
|
+
etag: import("zod").ZodString;
|
|
27
|
+
}, import("zod/v4/core").$strip>, "INVALID_KEY" | "INVALID_RANGE" | "RANGE_NOT_SATISFIABLE" | "UPLOAD_NOT_FOUND" | "UPLOAD_EXPIRED" | "UPLOAD_CONTENT_MISSING" | "BLOB_NOT_FOUND" | "BLOB_CHANGED" | "STORAGE_ERROR", string, import("@fragno-dev/db").DatabaseRequestContext<{
|
|
28
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
29
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
30
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
31
|
+
objectKey: string;
|
|
32
|
+
}>;
|
|
33
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
34
|
+
}>>, import("@fragno-dev/core").FragnoRouteConfig<"GET", "/blobs", StandardSchemaV1<unknown, unknown> | undefined, import("zod").ZodObject<{
|
|
35
|
+
blobs: import("zod").ZodArray<import("zod").ZodObject<{
|
|
36
|
+
key: import("zod").ZodString;
|
|
37
|
+
sizeBytes: import("zod").ZodNumber;
|
|
38
|
+
contentType: import("zod").ZodString;
|
|
39
|
+
etag: import("zod").ZodString;
|
|
40
|
+
}, import("zod/v4/core").$strip>>;
|
|
41
|
+
cursor: import("zod").ZodNullable<import("zod").ZodString>;
|
|
42
|
+
}, import("zod/v4/core").$strip>, string, "pageSize" | "prefix" | "cursor", import("@fragno-dev/db").DatabaseRequestContext<{
|
|
43
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
44
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
45
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
46
|
+
objectKey: string;
|
|
47
|
+
}>;
|
|
48
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
49
|
+
}>>, import("@fragno-dev/core").FragnoRouteConfig<"GET", "/blobs/by-key", StandardSchemaV1<unknown, unknown> | undefined, import("zod").ZodObject<{
|
|
50
|
+
key: import("zod").ZodString;
|
|
51
|
+
sizeBytes: import("zod").ZodNumber;
|
|
52
|
+
contentType: import("zod").ZodString;
|
|
53
|
+
etag: import("zod").ZodString;
|
|
54
|
+
}, import("zod/v4/core").$strip>, "INVALID_KEY" | "INVALID_RANGE" | "RANGE_NOT_SATISFIABLE" | "UPLOAD_NOT_FOUND" | "UPLOAD_EXPIRED" | "UPLOAD_CONTENT_MISSING" | "BLOB_NOT_FOUND" | "BLOB_CHANGED" | "STORAGE_ERROR", "key", import("@fragno-dev/db").DatabaseRequestContext<{
|
|
55
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
56
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
57
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
58
|
+
objectKey: string;
|
|
59
|
+
}>;
|
|
60
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
61
|
+
}>>, import("@fragno-dev/core").FragnoRouteConfig<"GET", "/blobs/by-key/download-url", StandardSchemaV1<unknown, unknown> | undefined, import("zod").ZodObject<{
|
|
62
|
+
url: import("zod").ZodString;
|
|
63
|
+
expiresAt: import("zod").ZodDate;
|
|
64
|
+
}, import("zod/v4/core").$strip>, "INVALID_KEY" | "INVALID_RANGE" | "RANGE_NOT_SATISFIABLE" | "UPLOAD_NOT_FOUND" | "UPLOAD_EXPIRED" | "UPLOAD_CONTENT_MISSING" | "BLOB_NOT_FOUND" | "BLOB_CHANGED" | "STORAGE_ERROR", "key", import("@fragno-dev/db").DatabaseRequestContext<{
|
|
65
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
66
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
67
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
68
|
+
objectKey: string;
|
|
69
|
+
}>;
|
|
70
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
71
|
+
}>>, import("@fragno-dev/core").FragnoRouteConfig<"GET", "/blobs/by-key/range", StandardSchemaV1<unknown, unknown> | undefined, StandardSchemaV1<unknown, unknown> | undefined, "INVALID_KEY" | "INVALID_RANGE" | "RANGE_NOT_SATISFIABLE" | "UPLOAD_NOT_FOUND" | "UPLOAD_EXPIRED" | "UPLOAD_CONTENT_MISSING" | "BLOB_NOT_FOUND" | "BLOB_CHANGED" | "STORAGE_ERROR", "key" | "length" | "offset", import("@fragno-dev/db").DatabaseRequestContext<{
|
|
72
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
73
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
74
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
75
|
+
objectKey: string;
|
|
76
|
+
}>;
|
|
77
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
78
|
+
}>>, import("@fragno-dev/core").FragnoRouteConfig<"DELETE", "/blobs/by-key", StandardSchemaV1<unknown, unknown> | undefined, import("zod").ZodObject<{
|
|
79
|
+
ok: import("zod").ZodLiteral<true>;
|
|
80
|
+
}, import("zod/v4/core").$strip>, "INVALID_KEY" | "INVALID_RANGE" | "RANGE_NOT_SATISFIABLE" | "UPLOAD_NOT_FOUND" | "UPLOAD_EXPIRED" | "UPLOAD_CONTENT_MISSING" | "BLOB_NOT_FOUND" | "BLOB_CHANGED" | "STORAGE_ERROR", "key", import("@fragno-dev/db").DatabaseRequestContext<{
|
|
81
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
82
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
83
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
84
|
+
objectKey: string;
|
|
85
|
+
}>;
|
|
86
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
87
|
+
}>>], import("@fragno-dev/db").ImplicitDatabaseDependencies<import("@fragno-dev/db/schema").Schema<Record<"blob", import("@fragno-dev/db/schema").Table<Record<"id", import("@fragno-dev/db/schema").IdColumn<"varchar(128)", string | import("@fragno-dev/db/schema").FragnoId | null, import("@fragno-dev/db/schema").FragnoId>> & Record<"key", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"objectKey", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"sizeBytes", import("@fragno-dev/db/schema").Column<"bigint", bigint, bigint>> & Record<"contentType", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"etag", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"createdAt", import("@fragno-dev/db/schema").Column<"timestamp", (Date | import("@fragno-dev/db").DbNow) | null, Date>> & Record<"updatedAt", import("@fragno-dev/db/schema").Column<"timestamp", (Date | import("@fragno-dev/db").DbNow) | null, Date>>, Record<"idx_blob_key", import("@fragno-dev/db/schema").Index<readonly [import("@fragno-dev/db/schema").Column<"string", string, string>] & import("@fragno-dev/db/schema").AnyColumn[], readonly ["key"]>>>> & Record<"blob_upload", import("@fragno-dev/db/schema").Table<Record<"id", import("@fragno-dev/db/schema").IdColumn<"varchar(128)", string | import("@fragno-dev/db/schema").FragnoId | null, import("@fragno-dev/db/schema").FragnoId>> & Record<"key", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"objectKey", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"contentType", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"expiresAt", import("@fragno-dev/db/schema").Column<"timestamp", Date | import("@fragno-dev/db").DbNow, Date>> & Record<"createdAt", import("@fragno-dev/db/schema").Column<"timestamp", (Date | import("@fragno-dev/db").DbNow) | null, Date>>, Record<"idx_blob_upload_key", import("@fragno-dev/db/schema").Index<readonly [import("@fragno-dev/db/schema").Column<"string", string, string>] & import("@fragno-dev/db/schema").AnyColumn[], readonly ["key"]>>>>>>, import("@fragno-dev/core").BoundServices<{}>, import("@fragno-dev/db").DatabaseServiceContext<{
|
|
88
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
89
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
90
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
91
|
+
objectKey: string;
|
|
92
|
+
}>;
|
|
93
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
94
|
+
}>, import("@fragno-dev/db").DatabaseRequestContext<{
|
|
95
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
96
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
97
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
98
|
+
objectKey: string;
|
|
99
|
+
}>;
|
|
100
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
101
|
+
}>, import("@fragno-dev/db/fragment-definition-builder").DatabaseRequestStorage, FragnoPublicConfigWithDatabase, never>;
|
|
102
|
+
//#endregion
|
|
103
|
+
export { type BlobStorage, type BlobsFragmentConfig, type ObjectRange, type S3BlobStorageOptions, type S3Signer, type StoredBlob, type StoredObject, createBlobsFragment, createS3BlobStorage };
|
|
104
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;iBAgBgB,oBACd,QAAQ,qBACR,SAAS,4DAA8B,gEAAA,oDAAA;;;;;;;;;;gDAA9B"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { blobsFragmentDefinition } from "./definition.js";
|
|
2
|
+
import { blobsRoutesFactory } from "./routes.js";
|
|
3
|
+
import { createS3BlobStorage } from "./storage.js";
|
|
4
|
+
import { instantiate } from "@fragno-dev/core";
|
|
5
|
+
//#region src/index.ts
|
|
6
|
+
function createBlobsFragment(config, options) {
|
|
7
|
+
return instantiate(blobsFragmentDefinition).withConfig(config).withRoutes([blobsRoutesFactory]).withOptions(options).build();
|
|
8
|
+
}
|
|
9
|
+
//#endregion
|
|
10
|
+
export { createBlobsFragment, createS3BlobStorage };
|
|
11
|
+
|
|
12
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { instantiate } from \"@fragno-dev/core\";\nimport type { FragnoPublicConfigWithDatabase } from \"@fragno-dev/db\";\n\nimport { blobsFragmentDefinition, type BlobsFragmentConfig } from \"./definition\";\nimport { blobsRoutesFactory } from \"./routes\";\n\nexport type { BlobsFragmentConfig, StoredBlob } from \"./definition\";\nexport {\n createS3BlobStorage,\n type BlobStorage,\n type ObjectRange,\n type S3BlobStorageOptions,\n type S3Signer,\n type StoredObject,\n} from \"./storage\";\n\nexport function createBlobsFragment(\n config: BlobsFragmentConfig,\n options: FragnoPublicConfigWithDatabase,\n) {\n return instantiate(blobsFragmentDefinition)\n .withConfig(config)\n .withRoutes([blobsRoutesFactory])\n .withOptions(options)\n .build();\n}\n"],"mappings":";;;;;AAgBA,SAAgB,oBACd,QACA,SACA;CACA,OAAO,YAAY,uBAAuB,CAAC,CACxC,WAAW,MAAM,CAAC,CAClB,WAAW,CAAC,kBAAkB,CAAC,CAAC,CAChC,YAAY,OAAO,CAAC,CACpB,MAAM;AACX"}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
//#region ../../node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts
|
|
2
|
+
/** The Standard Typed interface. This is a base type extended by other specs. */
|
|
3
|
+
interface StandardTypedV1<Input = unknown, Output = Input> {
|
|
4
|
+
/** The Standard properties. */
|
|
5
|
+
readonly "~standard": StandardTypedV1.Props<Input, Output>;
|
|
6
|
+
}
|
|
7
|
+
declare namespace StandardTypedV1 {
|
|
8
|
+
/** The Standard Typed properties interface. */
|
|
9
|
+
interface Props<Input = unknown, Output = Input> {
|
|
10
|
+
/** The version number of the standard. */
|
|
11
|
+
readonly version: 1;
|
|
12
|
+
/** The vendor name of the schema library. */
|
|
13
|
+
readonly vendor: string;
|
|
14
|
+
/** Inferred types associated with the schema. */
|
|
15
|
+
readonly types?: Types<Input, Output> | undefined;
|
|
16
|
+
}
|
|
17
|
+
/** The Standard Typed types interface. */
|
|
18
|
+
interface Types<Input = unknown, Output = Input> {
|
|
19
|
+
/** The input type of the schema. */
|
|
20
|
+
readonly input: Input;
|
|
21
|
+
/** The output type of the schema. */
|
|
22
|
+
readonly output: Output;
|
|
23
|
+
}
|
|
24
|
+
/** Infers the input type of a Standard Typed. */
|
|
25
|
+
type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["input"];
|
|
26
|
+
/** Infers the output type of a Standard Typed. */
|
|
27
|
+
type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["output"];
|
|
28
|
+
}
|
|
29
|
+
/** The Standard Schema interface. */
|
|
30
|
+
interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
31
|
+
/** The Standard Schema properties. */
|
|
32
|
+
readonly "~standard": StandardSchemaV1.Props<Input, Output>;
|
|
33
|
+
}
|
|
34
|
+
declare namespace StandardSchemaV1 {
|
|
35
|
+
/** The Standard Schema properties interface. */
|
|
36
|
+
interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
|
|
37
|
+
/** Validates unknown input values. */
|
|
38
|
+
readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
|
|
39
|
+
}
|
|
40
|
+
/** The result interface of the validate function. */
|
|
41
|
+
type Result<Output> = SuccessResult<Output> | FailureResult;
|
|
42
|
+
/** The result interface if validation succeeds. */
|
|
43
|
+
interface SuccessResult<Output> {
|
|
44
|
+
/** The typed output value. */
|
|
45
|
+
readonly value: Output;
|
|
46
|
+
/** A falsy value for `issues` indicates success. */
|
|
47
|
+
readonly issues?: undefined;
|
|
48
|
+
}
|
|
49
|
+
interface Options {
|
|
50
|
+
/** Explicit support for additional vendor-specific parameters, if needed. */
|
|
51
|
+
readonly libraryOptions?: Record<string, unknown> | undefined;
|
|
52
|
+
}
|
|
53
|
+
/** The result interface if validation fails. */
|
|
54
|
+
interface FailureResult {
|
|
55
|
+
/** The issues of failed validation. */
|
|
56
|
+
readonly issues: ReadonlyArray<Issue>;
|
|
57
|
+
}
|
|
58
|
+
/** The issue interface of the failure output. */
|
|
59
|
+
interface Issue {
|
|
60
|
+
/** The error message of the issue. */
|
|
61
|
+
readonly message: string;
|
|
62
|
+
/** The path of the issue, if any. */
|
|
63
|
+
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
|
|
64
|
+
}
|
|
65
|
+
/** The path segment interface of the issue. */
|
|
66
|
+
interface PathSegment {
|
|
67
|
+
/** The key representing a path segment. */
|
|
68
|
+
readonly key: PropertyKey;
|
|
69
|
+
}
|
|
70
|
+
/** The Standard types interface. */
|
|
71
|
+
interface Types<Input = unknown, Output = Input> extends StandardTypedV1.Types<Input, Output> {}
|
|
72
|
+
/** Infers the input type of a Standard. */
|
|
73
|
+
type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
|
|
74
|
+
/** Infers the output type of a Standard. */
|
|
75
|
+
type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
|
|
76
|
+
}
|
|
77
|
+
//#endregion
|
|
78
|
+
export { StandardSchemaV1, StandardTypedV1 };
|
|
79
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../../../../../../../../node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts"],"x_google_ignoreList":[0],"mappings":";;UACU,gBAAgB,iBAAiB,SAAS;;WAEvC,aAAa,gBAAgB,MAAM,OAAO;;kBAErC;;YAEJ,MAAM,iBAAiB,SAAS;;aAE7B;;aAEA;;aAEA,QAAQ,MAAM,OAAO;;;YAGxB,MAAM,iBAAiB,SAAS;;aAE7B,OAAO;;aAEP,QAAQ;;;OAGhB,WAAW,eAAe,mBAAmB,YAAY;;OAEzD,YAAY,eAAe,mBAAmB,YAAY;;;UAGzD,iBAAiB,iBAAiB,SAAS;;WAExC,aAAa,iBAAiB,MAAM,OAAO;;kBAEtC;;YAEJ,MAAM,iBAAiB,SAAS,eAAe,gBAAgB,MAAM,OAAO;;aAEzE,WAAW,gBAAgB,UAAU,iBAAiB,wBAAwB,OAAO,UAAU,QAAQ,OAAO;;;OAGtH,OAAO,UAAU,cAAc,UAAU;;YAEpC,cAAc;;aAEX,OAAO;;aAEP;;YAEH;;aAEG,iBAAiB;;;YAGpB;;aAEG,QAAQ,cAAc;;;YAGzB;;aAEG;;aAEA,OAAO,cAAc,cAAc;;;YAGtC;;aAEG,KAAK;;;YAGR,MAAM,iBAAiB,SAAS,eAAe,gBAAgB,MAAM,OAAO;;OAGjF,WAAW,eAAe,mBAAmB,gBAAgB,WAAW;;OAExE,YAAY,eAAe,mBAAmB,gBAAgB,YAAY"}
|
package/dist/routes.d.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { BlobsFragmentConfig, StoredBlob, UnfinishedUpload } from "./definition.js";
|
|
2
|
+
import { StandardSchemaV1 } from "./node_modules/.pnpm/@standard-schema_spec@1.1.0/node_modules/@standard-schema/spec/dist/index.js";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
//#region src/routes.d.ts
|
|
5
|
+
/** The most bytes one range read returns; it bounds what the read holds in memory. */
|
|
6
|
+
declare const BLOBS_MAX_RANGE_BYTES: number;
|
|
7
|
+
declare const blobsRoutesFactory: import("@fragno-dev/core").RouteFactory<BlobsFragmentConfig, import("@fragno-dev/db").ImplicitDatabaseDependencies<import("@fragno-dev/db/schema").Schema<Record<"blob", import("@fragno-dev/db/schema").Table<Record<"id", import("@fragno-dev/db/schema").IdColumn<"varchar(128)", string | import("@fragno-dev/db/schema").FragnoId | null, import("@fragno-dev/db/schema").FragnoId>> & Record<"key", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"objectKey", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"sizeBytes", import("@fragno-dev/db/schema").Column<"bigint", bigint, bigint>> & Record<"contentType", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"etag", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"createdAt", import("@fragno-dev/db/schema").Column<"timestamp", (Date | import("@fragno-dev/db").DbNow) | null, Date>> & Record<"updatedAt", import("@fragno-dev/db/schema").Column<"timestamp", (Date | import("@fragno-dev/db").DbNow) | null, Date>>, Record<"idx_blob_key", import("@fragno-dev/db/schema").Index<readonly [import("@fragno-dev/db/schema").Column<"string", string, string>] & import("@fragno-dev/db/schema").AnyColumn[], readonly ["key"]>>>> & Record<"blob_upload", import("@fragno-dev/db/schema").Table<Record<"id", import("@fragno-dev/db/schema").IdColumn<"varchar(128)", string | import("@fragno-dev/db/schema").FragnoId | null, import("@fragno-dev/db/schema").FragnoId>> & Record<"key", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"objectKey", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"contentType", import("@fragno-dev/db/schema").Column<"string", string, string>> & Record<"expiresAt", import("@fragno-dev/db/schema").Column<"timestamp", Date | import("@fragno-dev/db").DbNow, Date>> & Record<"createdAt", import("@fragno-dev/db/schema").Column<"timestamp", (Date | import("@fragno-dev/db").DbNow) | null, Date>>, Record<"idx_blob_upload_key", import("@fragno-dev/db/schema").Index<readonly [import("@fragno-dev/db/schema").Column<"string", string, string>] & import("@fragno-dev/db/schema").AnyColumn[], readonly ["key"]>>>>>>, import("@fragno-dev/core").BoundServices<{}>, {}, readonly [import("@fragno-dev/core").FragnoRouteConfig<"POST", "/uploads", z.ZodObject<{
|
|
8
|
+
key: z.ZodString;
|
|
9
|
+
contentType: z.ZodString;
|
|
10
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
11
|
+
uploadId: z.ZodString;
|
|
12
|
+
key: z.ZodString;
|
|
13
|
+
url: z.ZodString;
|
|
14
|
+
headers: z.ZodRecord<z.ZodString, z.ZodString>;
|
|
15
|
+
expiresAt: z.ZodDate;
|
|
16
|
+
}, z.core.$strip>, "INVALID_KEY" | "INVALID_RANGE" | "RANGE_NOT_SATISFIABLE" | "UPLOAD_NOT_FOUND" | "UPLOAD_EXPIRED" | "UPLOAD_CONTENT_MISSING" | "BLOB_NOT_FOUND" | "BLOB_CHANGED" | "STORAGE_ERROR", string, import("@fragno-dev/db").DatabaseRequestContext<{
|
|
17
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
18
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
19
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
20
|
+
objectKey: string;
|
|
21
|
+
}>;
|
|
22
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
23
|
+
}>>, import("@fragno-dev/core").FragnoRouteConfig<"POST", "/uploads/:uploadId/complete", StandardSchemaV1<unknown, unknown> | undefined, z.ZodObject<{
|
|
24
|
+
key: z.ZodString;
|
|
25
|
+
sizeBytes: z.ZodNumber;
|
|
26
|
+
contentType: z.ZodString;
|
|
27
|
+
etag: z.ZodString;
|
|
28
|
+
}, z.core.$strip>, "INVALID_KEY" | "INVALID_RANGE" | "RANGE_NOT_SATISFIABLE" | "UPLOAD_NOT_FOUND" | "UPLOAD_EXPIRED" | "UPLOAD_CONTENT_MISSING" | "BLOB_NOT_FOUND" | "BLOB_CHANGED" | "STORAGE_ERROR", string, import("@fragno-dev/db").DatabaseRequestContext<{
|
|
29
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
30
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
31
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
32
|
+
objectKey: string;
|
|
33
|
+
}>;
|
|
34
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
35
|
+
}>>, import("@fragno-dev/core").FragnoRouteConfig<"GET", "/blobs", StandardSchemaV1<unknown, unknown> | undefined, z.ZodObject<{
|
|
36
|
+
blobs: z.ZodArray<z.ZodObject<{
|
|
37
|
+
key: z.ZodString;
|
|
38
|
+
sizeBytes: z.ZodNumber;
|
|
39
|
+
contentType: z.ZodString;
|
|
40
|
+
etag: z.ZodString;
|
|
41
|
+
}, z.core.$strip>>;
|
|
42
|
+
cursor: z.ZodNullable<z.ZodString>;
|
|
43
|
+
}, z.core.$strip>, string, "pageSize" | "prefix" | "cursor", import("@fragno-dev/db").DatabaseRequestContext<{
|
|
44
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
45
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
46
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
47
|
+
objectKey: string;
|
|
48
|
+
}>;
|
|
49
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
50
|
+
}>>, import("@fragno-dev/core").FragnoRouteConfig<"GET", "/blobs/by-key", StandardSchemaV1<unknown, unknown> | undefined, z.ZodObject<{
|
|
51
|
+
key: z.ZodString;
|
|
52
|
+
sizeBytes: z.ZodNumber;
|
|
53
|
+
contentType: z.ZodString;
|
|
54
|
+
etag: z.ZodString;
|
|
55
|
+
}, z.core.$strip>, "INVALID_KEY" | "INVALID_RANGE" | "RANGE_NOT_SATISFIABLE" | "UPLOAD_NOT_FOUND" | "UPLOAD_EXPIRED" | "UPLOAD_CONTENT_MISSING" | "BLOB_NOT_FOUND" | "BLOB_CHANGED" | "STORAGE_ERROR", "key", import("@fragno-dev/db").DatabaseRequestContext<{
|
|
56
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
57
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
58
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
59
|
+
objectKey: string;
|
|
60
|
+
}>;
|
|
61
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
62
|
+
}>>, import("@fragno-dev/core").FragnoRouteConfig<"GET", "/blobs/by-key/download-url", StandardSchemaV1<unknown, unknown> | undefined, z.ZodObject<{
|
|
63
|
+
url: z.ZodString;
|
|
64
|
+
expiresAt: z.ZodDate;
|
|
65
|
+
}, z.core.$strip>, "INVALID_KEY" | "INVALID_RANGE" | "RANGE_NOT_SATISFIABLE" | "UPLOAD_NOT_FOUND" | "UPLOAD_EXPIRED" | "UPLOAD_CONTENT_MISSING" | "BLOB_NOT_FOUND" | "BLOB_CHANGED" | "STORAGE_ERROR", "key", import("@fragno-dev/db").DatabaseRequestContext<{
|
|
66
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
67
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
68
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
69
|
+
objectKey: string;
|
|
70
|
+
}>;
|
|
71
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
72
|
+
}>>, import("@fragno-dev/core").FragnoRouteConfig<"GET", "/blobs/by-key/range", StandardSchemaV1<unknown, unknown> | undefined, StandardSchemaV1<unknown, unknown> | undefined, "INVALID_KEY" | "INVALID_RANGE" | "RANGE_NOT_SATISFIABLE" | "UPLOAD_NOT_FOUND" | "UPLOAD_EXPIRED" | "UPLOAD_CONTENT_MISSING" | "BLOB_NOT_FOUND" | "BLOB_CHANGED" | "STORAGE_ERROR", "key" | "length" | "offset", import("@fragno-dev/db").DatabaseRequestContext<{
|
|
73
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
74
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
75
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
76
|
+
objectKey: string;
|
|
77
|
+
}>;
|
|
78
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
79
|
+
}>>, import("@fragno-dev/core").FragnoRouteConfig<"DELETE", "/blobs/by-key", StandardSchemaV1<unknown, unknown> | undefined, z.ZodObject<{
|
|
80
|
+
ok: z.ZodLiteral<true>;
|
|
81
|
+
}, z.core.$strip>, "INVALID_KEY" | "INVALID_RANGE" | "RANGE_NOT_SATISFIABLE" | "UPLOAD_NOT_FOUND" | "UPLOAD_EXPIRED" | "UPLOAD_CONTENT_MISSING" | "BLOB_NOT_FOUND" | "BLOB_CHANGED" | "STORAGE_ERROR", "key", import("@fragno-dev/db").DatabaseRequestContext<{
|
|
82
|
+
onBlobStored: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
83
|
+
onBlobDeleted: import("@fragno-dev/db").HookFn<StoredBlob>;
|
|
84
|
+
deleteObject: import("@fragno-dev/db").HookFn<{
|
|
85
|
+
objectKey: string;
|
|
86
|
+
}>;
|
|
87
|
+
discardUnfinishedUpload: import("@fragno-dev/db").HookFn<UnfinishedUpload>;
|
|
88
|
+
}>>]>;
|
|
89
|
+
//#endregion
|
|
90
|
+
export { BLOBS_MAX_RANGE_BYTES, blobsRoutesFactory };
|
|
91
|
+
//# sourceMappingURL=routes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.d.ts","names":[],"sources":["../src/routes.ts"],"mappings":";;;;;cAgBa;cAiFA,+CAAkB,aAAlB,8CAAkB,6DAAA,OAAA,+CAAA,MAAA,6CAAA,kEAAA,iDAAA,aAAA,8CAAA,oCAAA,oDAAA,oCAAA,oDAAA,oCAAA,sDAAA,oCAAA,+CAAA,oCAAA,oDAAA,qBAAA,gCAAA,eAAA,SAAA,oDAAA,qBAAA,gCAAA,eAAA,QAAA,uDAAA,gDAAA,oEAAA,oCAAA,sDAAA,MAAA,6CAAA,kEAAA,iDAAA,aAAA,8CAAA,oCAAA,oDAAA,oCAAA,sDAAA,oCAAA,oDAAA,oBAAA,gCAAA,OAAA,SAAA,oDAAA,qBAAA,gCAAA,eAAA,QAAA,8DAAA,gDAAA,oEAAA,gEAAA,4DAAA,sCAAA,EAAA"}
|
package/dist/routes.js
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
import { blobsSchema } from "./schema.js";
|
|
2
|
+
import { blobsFragmentDefinition } from "./definition.js";
|
|
3
|
+
import { defineRoutes } from "@fragno-dev/core";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
//#region src/routes.ts
|
|
6
|
+
const UPLOAD_EXPIRES_IN_SECONDS = 3600;
|
|
7
|
+
const DOWNLOAD_URL_EXPIRES_IN_SECONDS = 3600;
|
|
8
|
+
const UNFINISHED_UPLOAD_DISCARD_GRACE_MS = 3600 * 1e3;
|
|
9
|
+
const MAX_OBJECT_KEY_BYTES = 1024;
|
|
10
|
+
/** The most bytes one range read returns; it bounds what the read holds in memory. */
|
|
11
|
+
const BLOBS_MAX_RANGE_BYTES = 8 * 1024 * 1024;
|
|
12
|
+
const DEFAULT_PAGE_SIZE = 100;
|
|
13
|
+
const MAX_PAGE_SIZE = 1e3;
|
|
14
|
+
const errorCodes = [
|
|
15
|
+
"INVALID_KEY",
|
|
16
|
+
"INVALID_RANGE",
|
|
17
|
+
"RANGE_NOT_SATISFIABLE",
|
|
18
|
+
"UPLOAD_NOT_FOUND",
|
|
19
|
+
"UPLOAD_EXPIRED",
|
|
20
|
+
"UPLOAD_CONTENT_MISSING",
|
|
21
|
+
"BLOB_NOT_FOUND",
|
|
22
|
+
"BLOB_CHANGED",
|
|
23
|
+
"STORAGE_ERROR"
|
|
24
|
+
];
|
|
25
|
+
const ERROR_STATUS = {
|
|
26
|
+
INVALID_KEY: 400,
|
|
27
|
+
INVALID_RANGE: 400,
|
|
28
|
+
RANGE_NOT_SATISFIABLE: 416,
|
|
29
|
+
UPLOAD_NOT_FOUND: 404,
|
|
30
|
+
UPLOAD_EXPIRED: 410,
|
|
31
|
+
UPLOAD_CONTENT_MISSING: 409,
|
|
32
|
+
BLOB_NOT_FOUND: 404,
|
|
33
|
+
BLOB_CHANGED: 409,
|
|
34
|
+
STORAGE_ERROR: 502
|
|
35
|
+
};
|
|
36
|
+
var BlobsError = class extends Error {
|
|
37
|
+
code;
|
|
38
|
+
constructor(code, message) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.code = code;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
const blobSchema = z.object({
|
|
44
|
+
key: z.string(),
|
|
45
|
+
sizeBytes: z.number(),
|
|
46
|
+
contentType: z.string(),
|
|
47
|
+
etag: z.string()
|
|
48
|
+
});
|
|
49
|
+
function toBlob(blob) {
|
|
50
|
+
return {
|
|
51
|
+
key: blob.key,
|
|
52
|
+
sizeBytes: Number(blob.sizeBytes),
|
|
53
|
+
contentType: blob.contentType,
|
|
54
|
+
etag: blob.etag
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** Slash-separated segments, none empty, `.`, or `..`, without control characters. */
|
|
58
|
+
function isBlobKey(value) {
|
|
59
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
60
|
+
const code = value.charCodeAt(index);
|
|
61
|
+
if (code <= 31 || code === 127) return false;
|
|
62
|
+
}
|
|
63
|
+
return value.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
|
|
64
|
+
}
|
|
65
|
+
function blobKeyQuery(query) {
|
|
66
|
+
const key = query.get("key");
|
|
67
|
+
return key !== null && isBlobKey(key) ? key : null;
|
|
68
|
+
}
|
|
69
|
+
function integerQuery(query, name) {
|
|
70
|
+
const value = query.get(name);
|
|
71
|
+
return value !== null && /^\d+$/.test(value) ? Number(value) : null;
|
|
72
|
+
}
|
|
73
|
+
const blobsRoutesFactory = defineRoutes(blobsFragmentDefinition).create(({ defineRoute, config }) => {
|
|
74
|
+
const storagePrefix = config.storageKeyPrefix.replace(/^\/+|\/+$/g, "");
|
|
75
|
+
return [
|
|
76
|
+
defineRoute({
|
|
77
|
+
method: "POST",
|
|
78
|
+
path: "/uploads",
|
|
79
|
+
inputSchema: z.object({
|
|
80
|
+
key: z.string(),
|
|
81
|
+
contentType: z.string().min(1)
|
|
82
|
+
}),
|
|
83
|
+
outputSchema: z.object({
|
|
84
|
+
uploadId: z.string(),
|
|
85
|
+
key: z.string(),
|
|
86
|
+
url: z.string(),
|
|
87
|
+
headers: z.record(z.string(), z.string()),
|
|
88
|
+
expiresAt: z.date()
|
|
89
|
+
}),
|
|
90
|
+
errorCodes,
|
|
91
|
+
handler: async function({ input }, { json, error }) {
|
|
92
|
+
const { key, contentType } = await input.valid();
|
|
93
|
+
const segments = key.split("/");
|
|
94
|
+
const objectKey = [
|
|
95
|
+
storagePrefix,
|
|
96
|
+
...segments.slice(0, -1),
|
|
97
|
+
crypto.randomUUID(),
|
|
98
|
+
segments.at(-1)
|
|
99
|
+
].filter(Boolean).join("/");
|
|
100
|
+
if (!isBlobKey(key) || new TextEncoder().encode(objectKey).length > MAX_OBJECT_KEY_BYTES) return error({
|
|
101
|
+
message: "The blob key is invalid.",
|
|
102
|
+
code: "INVALID_KEY"
|
|
103
|
+
}, 400);
|
|
104
|
+
const expiresAt = new Date(Date.now() + UPLOAD_EXPIRES_IN_SECONDS * 1e3);
|
|
105
|
+
let presigned;
|
|
106
|
+
try {
|
|
107
|
+
presigned = await config.storage.createUploadUrl({
|
|
108
|
+
objectKey,
|
|
109
|
+
contentType,
|
|
110
|
+
expiresInSeconds: UPLOAD_EXPIRES_IN_SECONDS
|
|
111
|
+
});
|
|
112
|
+
} catch {
|
|
113
|
+
return error({
|
|
114
|
+
message: "Storage error",
|
|
115
|
+
code: "STORAGE_ERROR"
|
|
116
|
+
}, 502);
|
|
117
|
+
}
|
|
118
|
+
return json({
|
|
119
|
+
uploadId: await this.handlerTx().retrieve(({ forSchema }) => forSchema(blobsSchema).find("blob_upload", (b) => b.whereIndex("idx_blob_upload_key", (eb) => eb("key", "=", key)))).mutate(({ forSchema, retrieveResult: [replaced] }) => {
|
|
120
|
+
const uow = forSchema(blobsSchema);
|
|
121
|
+
for (const upload of replaced) uow.delete("blob_upload", upload.id, (b) => b.check());
|
|
122
|
+
const id = uow.create("blob_upload", {
|
|
123
|
+
key,
|
|
124
|
+
objectKey,
|
|
125
|
+
contentType,
|
|
126
|
+
expiresAt
|
|
127
|
+
});
|
|
128
|
+
uow.triggerHook("discardUnfinishedUpload", {
|
|
129
|
+
uploadId: id.toString(),
|
|
130
|
+
key,
|
|
131
|
+
objectKey
|
|
132
|
+
}, { processAt: new Date(expiresAt.getTime() + UNFINISHED_UPLOAD_DISCARD_GRACE_MS) });
|
|
133
|
+
return id.toString();
|
|
134
|
+
}).execute(),
|
|
135
|
+
key,
|
|
136
|
+
url: presigned.url,
|
|
137
|
+
headers: presigned.headers,
|
|
138
|
+
expiresAt
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}),
|
|
142
|
+
defineRoute({
|
|
143
|
+
method: "POST",
|
|
144
|
+
path: "/uploads/:uploadId/complete",
|
|
145
|
+
outputSchema: blobSchema,
|
|
146
|
+
errorCodes,
|
|
147
|
+
handler: async function({ pathParams }, { json, error }) {
|
|
148
|
+
let stored = null;
|
|
149
|
+
try {
|
|
150
|
+
return json(await this.handlerTx().retrieve(({ forSchema }) => forSchema(blobsSchema).findFirst("blob_upload", (b) => b.whereIndex("primary", (eb) => eb("id", "=", pathParams.uploadId)).joinOne("blob", "blob", (blob) => blob.onIndex("idx_blob_key", (eb) => eb("key", "=", eb.parent("key")))))).afterRetrieve(async (_uow, [upload]) => {
|
|
151
|
+
if (!upload) throw new BlobsError("UPLOAD_NOT_FOUND", "The upload does not exist.");
|
|
152
|
+
if (upload.expiresAt.getTime() + UNFINISHED_UPLOAD_DISCARD_GRACE_MS <= Date.now()) throw new BlobsError("UPLOAD_EXPIRED", "The upload has expired.");
|
|
153
|
+
try {
|
|
154
|
+
stored = await config.storage.describeObject(upload.objectKey);
|
|
155
|
+
} catch {
|
|
156
|
+
throw new BlobsError("STORAGE_ERROR", "Storage error");
|
|
157
|
+
}
|
|
158
|
+
if (stored === null) throw new BlobsError("UPLOAD_CONTENT_MISSING", "Storage holds no bytes for the upload yet.");
|
|
159
|
+
}).mutate(({ forSchema, retrieveResult: [upload] }) => {
|
|
160
|
+
const { blob: previous, ...completed } = upload;
|
|
161
|
+
const uow = forSchema(blobsSchema);
|
|
162
|
+
const values = {
|
|
163
|
+
key: completed.key,
|
|
164
|
+
objectKey: completed.objectKey,
|
|
165
|
+
sizeBytes: stored.sizeBytes,
|
|
166
|
+
contentType: completed.contentType,
|
|
167
|
+
etag: stored.etag
|
|
168
|
+
};
|
|
169
|
+
uow.delete("blob_upload", completed.id, (b) => b.check());
|
|
170
|
+
if (previous) {
|
|
171
|
+
uow.update("blob", previous.id, (b) => b.set({
|
|
172
|
+
...values,
|
|
173
|
+
updatedAt: uow.now()
|
|
174
|
+
}).check());
|
|
175
|
+
uow.triggerHook("deleteObject", { objectKey: previous.objectKey });
|
|
176
|
+
} else uow.create("blob", values, { retryOnUniqueConflict: ({ error }) => error.kind === "unique" });
|
|
177
|
+
const blob = toBlob(values);
|
|
178
|
+
uow.triggerHook("onBlobStored", blob);
|
|
179
|
+
return blob;
|
|
180
|
+
}).execute());
|
|
181
|
+
} catch (cause) {
|
|
182
|
+
if (cause instanceof BlobsError) return error({
|
|
183
|
+
message: cause.message,
|
|
184
|
+
code: cause.code
|
|
185
|
+
}, ERROR_STATUS[cause.code]);
|
|
186
|
+
throw cause;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}),
|
|
190
|
+
defineRoute({
|
|
191
|
+
method: "GET",
|
|
192
|
+
path: "/blobs",
|
|
193
|
+
queryParameters: [
|
|
194
|
+
"prefix",
|
|
195
|
+
"cursor",
|
|
196
|
+
"pageSize"
|
|
197
|
+
],
|
|
198
|
+
outputSchema: z.object({
|
|
199
|
+
blobs: z.array(blobSchema),
|
|
200
|
+
cursor: z.string().nullable()
|
|
201
|
+
}),
|
|
202
|
+
handler: async function({ query }, { json }) {
|
|
203
|
+
const prefix = query.get("prefix") ?? "";
|
|
204
|
+
const cursor = query.get("cursor");
|
|
205
|
+
const pageSize = Math.min(Number.parseInt(query.get("pageSize") ?? "", 10) || DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE);
|
|
206
|
+
const page = await this.handlerTx().retrieve(({ forSchema }) => forSchema(blobsSchema).findWithCursor("blob", (b) => {
|
|
207
|
+
const ordered = b.whereIndex("idx_blob_key", (eb) => eb("key", "starts with", prefix)).orderByIndex("idx_blob_key", "asc").pageSize(pageSize);
|
|
208
|
+
return cursor ? ordered.after(cursor) : ordered;
|
|
209
|
+
})).transformRetrieve(([result]) => result).execute();
|
|
210
|
+
return json({
|
|
211
|
+
blobs: page.items.map(toBlob),
|
|
212
|
+
cursor: page.hasNextPage && page.cursor ? page.cursor.encode() : null
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
}),
|
|
216
|
+
defineRoute({
|
|
217
|
+
method: "GET",
|
|
218
|
+
path: "/blobs/by-key",
|
|
219
|
+
queryParameters: ["key"],
|
|
220
|
+
outputSchema: blobSchema,
|
|
221
|
+
errorCodes,
|
|
222
|
+
handler: async function({ query }, { json, error }) {
|
|
223
|
+
const key = blobKeyQuery(query);
|
|
224
|
+
if (key === null) return error({
|
|
225
|
+
message: "The blob key is invalid.",
|
|
226
|
+
code: "INVALID_KEY"
|
|
227
|
+
}, 400);
|
|
228
|
+
const blob = await this.handlerTx().retrieve(({ forSchema }) => forSchema(blobsSchema).findFirst("blob", (b) => b.whereIndex("idx_blob_key", (eb) => eb("key", "=", key)))).transformRetrieve(([result]) => result).execute();
|
|
229
|
+
if (!blob) return error({
|
|
230
|
+
message: "The blob does not exist.",
|
|
231
|
+
code: "BLOB_NOT_FOUND"
|
|
232
|
+
}, 404);
|
|
233
|
+
return json(toBlob(blob));
|
|
234
|
+
}
|
|
235
|
+
}),
|
|
236
|
+
defineRoute({
|
|
237
|
+
method: "GET",
|
|
238
|
+
path: "/blobs/by-key/download-url",
|
|
239
|
+
queryParameters: ["key"],
|
|
240
|
+
outputSchema: z.object({
|
|
241
|
+
url: z.string(),
|
|
242
|
+
expiresAt: z.date()
|
|
243
|
+
}),
|
|
244
|
+
errorCodes,
|
|
245
|
+
handler: async function({ query }, { json, error }) {
|
|
246
|
+
const key = blobKeyQuery(query);
|
|
247
|
+
if (key === null) return error({
|
|
248
|
+
message: "The blob key is invalid.",
|
|
249
|
+
code: "INVALID_KEY"
|
|
250
|
+
}, 400);
|
|
251
|
+
const blob = await this.handlerTx().retrieve(({ forSchema }) => forSchema(blobsSchema).findFirst("blob", (b) => b.whereIndex("idx_blob_key", (eb) => eb("key", "=", key)))).transformRetrieve(([result]) => result).execute();
|
|
252
|
+
if (!blob) return error({
|
|
253
|
+
message: "The blob does not exist.",
|
|
254
|
+
code: "BLOB_NOT_FOUND"
|
|
255
|
+
}, 404);
|
|
256
|
+
const expiresAt = new Date(Date.now() + DOWNLOAD_URL_EXPIRES_IN_SECONDS * 1e3);
|
|
257
|
+
try {
|
|
258
|
+
return json({
|
|
259
|
+
url: await config.storage.createDownloadUrl({
|
|
260
|
+
objectKey: blob.objectKey,
|
|
261
|
+
expiresInSeconds: DOWNLOAD_URL_EXPIRES_IN_SECONDS
|
|
262
|
+
}),
|
|
263
|
+
expiresAt
|
|
264
|
+
});
|
|
265
|
+
} catch {
|
|
266
|
+
return error({
|
|
267
|
+
message: "Storage error",
|
|
268
|
+
code: "STORAGE_ERROR"
|
|
269
|
+
}, 502);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}),
|
|
273
|
+
defineRoute({
|
|
274
|
+
method: "GET",
|
|
275
|
+
path: "/blobs/by-key/range",
|
|
276
|
+
queryParameters: [
|
|
277
|
+
"key",
|
|
278
|
+
"offset",
|
|
279
|
+
"length"
|
|
280
|
+
],
|
|
281
|
+
errorCodes,
|
|
282
|
+
handler: async function({ query }, { error }) {
|
|
283
|
+
const key = blobKeyQuery(query);
|
|
284
|
+
if (key === null) return error({
|
|
285
|
+
message: "The blob key is invalid.",
|
|
286
|
+
code: "INVALID_KEY"
|
|
287
|
+
}, 400);
|
|
288
|
+
const offset = integerQuery(query, "offset");
|
|
289
|
+
const length = integerQuery(query, "length");
|
|
290
|
+
if (offset === null || length === null || length < 1 || length > 8388608) return error({
|
|
291
|
+
message: `Ranges start at a byte offset and span 1 to ${BLOBS_MAX_RANGE_BYTES} bytes.`,
|
|
292
|
+
code: "INVALID_RANGE"
|
|
293
|
+
}, 400);
|
|
294
|
+
const blob = await this.handlerTx().retrieve(({ forSchema }) => forSchema(blobsSchema).findFirst("blob", (b) => b.whereIndex("idx_blob_key", (eb) => eb("key", "=", key)))).transformRetrieve(([result]) => result).execute();
|
|
295
|
+
if (!blob) return error({
|
|
296
|
+
message: "The blob does not exist.",
|
|
297
|
+
code: "BLOB_NOT_FOUND"
|
|
298
|
+
}, 404);
|
|
299
|
+
const sizeBytes = Number(blob.sizeBytes);
|
|
300
|
+
if (offset >= sizeBytes) return error({
|
|
301
|
+
message: `The blob ends before byte ${offset}; it holds ${sizeBytes} bytes.`,
|
|
302
|
+
code: "RANGE_NOT_SATISFIABLE"
|
|
303
|
+
}, 416);
|
|
304
|
+
const end = Math.min(offset + length, sizeBytes);
|
|
305
|
+
let range;
|
|
306
|
+
try {
|
|
307
|
+
range = await config.storage.readObjectRange({
|
|
308
|
+
objectKey: blob.objectKey,
|
|
309
|
+
etag: blob.etag,
|
|
310
|
+
offset,
|
|
311
|
+
length: end - offset
|
|
312
|
+
});
|
|
313
|
+
} catch {
|
|
314
|
+
return error({
|
|
315
|
+
message: "Storage error",
|
|
316
|
+
code: "STORAGE_ERROR"
|
|
317
|
+
}, 502);
|
|
318
|
+
}
|
|
319
|
+
if (range.status === "missing") return error({
|
|
320
|
+
message: "The blob does not exist.",
|
|
321
|
+
code: "BLOB_NOT_FOUND"
|
|
322
|
+
}, 404);
|
|
323
|
+
if (range.status === "changed") return error({
|
|
324
|
+
message: "Storage holds other bytes than the blob recorded.",
|
|
325
|
+
code: "BLOB_CHANGED"
|
|
326
|
+
}, 409);
|
|
327
|
+
return new Response(range.bytes, {
|
|
328
|
+
status: 206,
|
|
329
|
+
headers: {
|
|
330
|
+
"Content-Type": "application/octet-stream",
|
|
331
|
+
"Content-Range": `bytes ${offset}-${end - 1}/${sizeBytes}`,
|
|
332
|
+
ETag: `"${blob.etag}"`
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
}),
|
|
337
|
+
defineRoute({
|
|
338
|
+
method: "DELETE",
|
|
339
|
+
path: "/blobs/by-key",
|
|
340
|
+
queryParameters: ["key"],
|
|
341
|
+
outputSchema: z.object({ ok: z.literal(true) }),
|
|
342
|
+
errorCodes,
|
|
343
|
+
handler: async function({ query }, { json, error }) {
|
|
344
|
+
const key = blobKeyQuery(query);
|
|
345
|
+
if (key === null) return error({
|
|
346
|
+
message: "The blob key is invalid.",
|
|
347
|
+
code: "INVALID_KEY"
|
|
348
|
+
}, 400);
|
|
349
|
+
if (!await this.handlerTx().retrieve(({ forSchema }) => forSchema(blobsSchema).findFirst("blob", (b) => b.whereIndex("idx_blob_key", (eb) => eb("key", "=", key)))).mutate(({ forSchema, retrieveResult: [blob] }) => {
|
|
350
|
+
if (!blob) return false;
|
|
351
|
+
const uow = forSchema(blobsSchema);
|
|
352
|
+
uow.delete("blob", blob.id, (b) => b.check());
|
|
353
|
+
uow.triggerHook("deleteObject", { objectKey: blob.objectKey });
|
|
354
|
+
uow.triggerHook("onBlobDeleted", toBlob(blob));
|
|
355
|
+
return true;
|
|
356
|
+
}).execute()) return error({
|
|
357
|
+
message: "The blob does not exist.",
|
|
358
|
+
code: "BLOB_NOT_FOUND"
|
|
359
|
+
}, 404);
|
|
360
|
+
return json({ ok: true });
|
|
361
|
+
}
|
|
362
|
+
})
|
|
363
|
+
];
|
|
364
|
+
});
|
|
365
|
+
//#endregion
|
|
366
|
+
export { BLOBS_MAX_RANGE_BYTES, blobsRoutesFactory };
|
|
367
|
+
|
|
368
|
+
//# sourceMappingURL=routes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.js","names":[],"sources":["../src/routes.ts"],"sourcesContent":["import { z } from \"zod\";\n\nimport { defineRoutes } from \"@fragno-dev/core\";\n\nimport { blobsFragmentDefinition, type StoredBlob, type UnfinishedUpload } from \"./definition\";\nimport { blobsSchema } from \"./schema\";\nimport type { StoredObject } from \"./storage\";\n\nconst UPLOAD_EXPIRES_IN_SECONDS = 60 * 60;\nconst DOWNLOAD_URL_EXPIRES_IN_SECONDS = 60 * 60;\n// Storage checks a presigned URL's expiry when a request starts, so a PUT that began just before its\n// URL expired may still be landing afterwards.\nconst UNFINISHED_UPLOAD_DISCARD_GRACE_MS = 60 * 60 * 1000;\n// S3's limit on object key length.\nconst MAX_OBJECT_KEY_BYTES = 1024;\n/** The most bytes one range read returns; it bounds what the read holds in memory. */\nexport const BLOBS_MAX_RANGE_BYTES = 8 * 1024 * 1024;\nconst DEFAULT_PAGE_SIZE = 100;\nconst MAX_PAGE_SIZE = 1000;\n\nconst errorCodes = [\n \"INVALID_KEY\",\n \"INVALID_RANGE\",\n \"RANGE_NOT_SATISFIABLE\",\n \"UPLOAD_NOT_FOUND\",\n \"UPLOAD_EXPIRED\",\n \"UPLOAD_CONTENT_MISSING\",\n \"BLOB_NOT_FOUND\",\n \"BLOB_CHANGED\",\n \"STORAGE_ERROR\",\n] as const;\n\ntype BlobsErrorCode = (typeof errorCodes)[number];\n\nconst ERROR_STATUS = {\n INVALID_KEY: 400,\n INVALID_RANGE: 400,\n RANGE_NOT_SATISFIABLE: 416,\n UPLOAD_NOT_FOUND: 404,\n UPLOAD_EXPIRED: 410,\n UPLOAD_CONTENT_MISSING: 409,\n BLOB_NOT_FOUND: 404,\n BLOB_CHANGED: 409,\n STORAGE_ERROR: 502,\n} as const satisfies Record<BlobsErrorCode, number>;\n\nclass BlobsError extends Error {\n constructor(\n readonly code: BlobsErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\nconst blobSchema = z.object({\n key: z.string(),\n sizeBytes: z.number(),\n contentType: z.string(),\n etag: z.string(),\n});\n\nfunction toBlob(blob: {\n key: string;\n sizeBytes: bigint;\n contentType: string;\n etag: string;\n}): StoredBlob {\n return {\n key: blob.key,\n sizeBytes: Number(blob.sizeBytes),\n contentType: blob.contentType,\n etag: blob.etag,\n };\n}\n\n/** Slash-separated segments, none empty, `.`, or `..`, without control characters. */\nfunction isBlobKey(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code <= 0x1f || code === 0x7f) {\n return false;\n }\n }\n return value.split(\"/\").every((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\");\n}\n\nfunction blobKeyQuery(query: URLSearchParams): string | null {\n const key = query.get(\"key\");\n return key !== null && isBlobKey(key) ? key : null;\n}\n\nfunction integerQuery(query: URLSearchParams, name: string): number | null {\n const value = query.get(name);\n return value !== null && /^\\d+$/.test(value) ? Number(value) : null;\n}\n\nexport const blobsRoutesFactory = defineRoutes(blobsFragmentDefinition).create(\n ({ defineRoute, config }) => {\n const storagePrefix = config.storageKeyPrefix.replace(/^\\/+|\\/+$/g, \"\");\n\n return [\n defineRoute({\n method: \"POST\",\n path: \"/uploads\",\n inputSchema: z.object({ key: z.string(), contentType: z.string().min(1) }),\n outputSchema: z.object({\n uploadId: z.string(),\n key: z.string(),\n url: z.string(),\n headers: z.record(z.string(), z.string()),\n expiresAt: z.date(),\n }),\n errorCodes,\n handler: async function ({ input }, { json, error }) {\n const { key, contentType } = await input.valid();\n // Every upload gets its own object, so an unfinished upload never touches the blob. The\n // object's key ends in the blob's name, so browsers save downloads under that name.\n const segments = key.split(\"/\");\n const objectKey = [\n storagePrefix,\n ...segments.slice(0, -1),\n crypto.randomUUID(),\n segments.at(-1),\n ]\n .filter(Boolean)\n .join(\"/\");\n if (\n !isBlobKey(key) ||\n new TextEncoder().encode(objectKey).length > MAX_OBJECT_KEY_BYTES\n ) {\n return error({ message: \"The blob key is invalid.\", code: \"INVALID_KEY\" }, 400);\n }\n\n const expiresAt = new Date(Date.now() + UPLOAD_EXPIRES_IN_SECONDS * 1000);\n let presigned;\n try {\n presigned = await config.storage.createUploadUrl({\n objectKey,\n contentType,\n expiresInSeconds: UPLOAD_EXPIRES_IN_SECONDS,\n });\n } catch {\n return error({ message: \"Storage error\", code: \"STORAGE_ERROR\" }, 502);\n }\n\n const uploadId = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(blobsSchema).find(\"blob_upload\", (b) =>\n b.whereIndex(\"idx_blob_upload_key\", (eb) => eb(\"key\", \"=\", key)),\n ),\n )\n .mutate(({ forSchema, retrieveResult: [replaced] }) => {\n const uow = forSchema(blobsSchema);\n // Replaced uploads can no longer complete; their own discards clean up what their\n // URLs store.\n for (const upload of replaced) {\n uow.delete(\"blob_upload\", upload.id, (b) => b.check());\n }\n const id = uow.create(\"blob_upload\", { key, objectKey, contentType, expiresAt });\n uow.triggerHook(\n \"discardUnfinishedUpload\",\n { uploadId: id.toString(), key, objectKey } satisfies UnfinishedUpload,\n { processAt: new Date(expiresAt.getTime() + UNFINISHED_UPLOAD_DISCARD_GRACE_MS) },\n );\n return id.toString();\n })\n .execute();\n\n return json({ uploadId, key, url: presigned.url, headers: presigned.headers, expiresAt });\n },\n }),\n\n defineRoute({\n method: \"POST\",\n path: \"/uploads/:uploadId/complete\",\n outputSchema: blobSchema,\n errorCodes,\n handler: async function ({ pathParams }, { json, error }) {\n let stored: StoredObject | null = null;\n try {\n const blob = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(blobsSchema).findFirst(\"blob_upload\", (b) =>\n b\n .whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", pathParams.uploadId))\n .joinOne(\"blob\", \"blob\", (blob) =>\n blob.onIndex(\"idx_blob_key\", (eb) => eb(\"key\", \"=\", eb.parent(\"key\"))),\n ),\n ),\n )\n .afterRetrieve(async (_uow, [upload]) => {\n if (!upload) {\n throw new BlobsError(\"UPLOAD_NOT_FOUND\", \"The upload does not exist.\");\n }\n // A PUT that started before the URL expired may finish after it, so completion\n // stays open until the upload is discarded.\n if (upload.expiresAt.getTime() + UNFINISHED_UPLOAD_DISCARD_GRACE_MS <= Date.now()) {\n throw new BlobsError(\"UPLOAD_EXPIRED\", \"The upload has expired.\");\n }\n try {\n stored = await config.storage.describeObject(upload.objectKey);\n } catch {\n throw new BlobsError(\"STORAGE_ERROR\", \"Storage error\");\n }\n if (stored === null) {\n throw new BlobsError(\n \"UPLOAD_CONTENT_MISSING\",\n \"Storage holds no bytes for the upload yet.\",\n );\n }\n })\n .mutate(({ forSchema, retrieveResult: [upload] }) => {\n // afterRetrieve rejected a missing upload and a missing object.\n const { blob: previous, ...completed } = upload!;\n const uow = forSchema(blobsSchema);\n const values = {\n key: completed.key,\n objectKey: completed.objectKey,\n sizeBytes: stored!.sizeBytes,\n contentType: completed.contentType,\n etag: stored!.etag,\n };\n uow.delete(\"blob_upload\", completed.id, (b) => b.check());\n if (previous) {\n uow.update(\"blob\", previous.id, (b) =>\n b.set({ ...values, updatedAt: uow.now() }).check(),\n );\n uow.triggerHook(\"deleteObject\", { objectKey: previous.objectKey });\n } else {\n uow.create(\"blob\", values, {\n // Another upload of the same key may complete concurrently; the retry replaces\n // the blob it created.\n retryOnUniqueConflict: ({ error }) => error.kind === \"unique\",\n });\n }\n const blob = toBlob(values);\n uow.triggerHook(\"onBlobStored\", blob);\n return blob;\n })\n .execute();\n\n return json(blob);\n } catch (cause) {\n if (cause instanceof BlobsError) {\n return error({ message: cause.message, code: cause.code }, ERROR_STATUS[cause.code]);\n }\n throw cause;\n }\n },\n }),\n\n defineRoute({\n method: \"GET\",\n path: \"/blobs\",\n queryParameters: [\"prefix\", \"cursor\", \"pageSize\"],\n outputSchema: z.object({ blobs: z.array(blobSchema), cursor: z.string().nullable() }),\n handler: async function ({ query }, { json }) {\n const prefix = query.get(\"prefix\") ?? \"\";\n const cursor = query.get(\"cursor\");\n const pageSize = Math.min(\n Number.parseInt(query.get(\"pageSize\") ?? \"\", 10) || DEFAULT_PAGE_SIZE,\n MAX_PAGE_SIZE,\n );\n\n const page = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(blobsSchema).findWithCursor(\"blob\", (b) => {\n const ordered = b\n .whereIndex(\"idx_blob_key\", (eb) => eb(\"key\", \"starts with\", prefix))\n .orderByIndex(\"idx_blob_key\", \"asc\")\n .pageSize(pageSize);\n return cursor ? ordered.after(cursor) : ordered;\n }),\n )\n .transformRetrieve(([result]) => result)\n .execute();\n\n return json({\n blobs: page.items.map(toBlob),\n cursor: page.hasNextPage && page.cursor ? page.cursor.encode() : null,\n });\n },\n }),\n\n defineRoute({\n method: \"GET\",\n path: \"/blobs/by-key\",\n queryParameters: [\"key\"],\n outputSchema: blobSchema,\n errorCodes,\n handler: async function ({ query }, { json, error }) {\n const key = blobKeyQuery(query);\n if (key === null) {\n return error({ message: \"The blob key is invalid.\", code: \"INVALID_KEY\" }, 400);\n }\n const blob = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(blobsSchema).findFirst(\"blob\", (b) =>\n b.whereIndex(\"idx_blob_key\", (eb) => eb(\"key\", \"=\", key)),\n ),\n )\n .transformRetrieve(([result]) => result)\n .execute();\n if (!blob) {\n return error({ message: \"The blob does not exist.\", code: \"BLOB_NOT_FOUND\" }, 404);\n }\n return json(toBlob(blob));\n },\n }),\n\n defineRoute({\n method: \"GET\",\n path: \"/blobs/by-key/download-url\",\n queryParameters: [\"key\"],\n outputSchema: z.object({ url: z.string(), expiresAt: z.date() }),\n errorCodes,\n handler: async function ({ query }, { json, error }) {\n const key = blobKeyQuery(query);\n if (key === null) {\n return error({ message: \"The blob key is invalid.\", code: \"INVALID_KEY\" }, 400);\n }\n const blob = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(blobsSchema).findFirst(\"blob\", (b) =>\n b.whereIndex(\"idx_blob_key\", (eb) => eb(\"key\", \"=\", key)),\n ),\n )\n .transformRetrieve(([result]) => result)\n .execute();\n if (!blob) {\n return error({ message: \"The blob does not exist.\", code: \"BLOB_NOT_FOUND\" }, 404);\n }\n\n const expiresAt = new Date(Date.now() + DOWNLOAD_URL_EXPIRES_IN_SECONDS * 1000);\n try {\n const url = await config.storage.createDownloadUrl({\n objectKey: blob.objectKey,\n expiresInSeconds: DOWNLOAD_URL_EXPIRES_IN_SECONDS,\n });\n return json({ url, expiresAt });\n } catch {\n return error({ message: \"Storage error\", code: \"STORAGE_ERROR\" }, 502);\n }\n },\n }),\n\n defineRoute({\n method: \"GET\",\n path: \"/blobs/by-key/range\",\n queryParameters: [\"key\", \"offset\", \"length\"],\n errorCodes,\n handler: async function ({ query }, { error }) {\n const key = blobKeyQuery(query);\n if (key === null) {\n return error({ message: \"The blob key is invalid.\", code: \"INVALID_KEY\" }, 400);\n }\n const offset = integerQuery(query, \"offset\");\n const length = integerQuery(query, \"length\");\n if (offset === null || length === null || length < 1 || length > BLOBS_MAX_RANGE_BYTES) {\n return error(\n {\n message: `Ranges start at a byte offset and span 1 to ${BLOBS_MAX_RANGE_BYTES} bytes.`,\n code: \"INVALID_RANGE\",\n },\n 400,\n );\n }\n const blob = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(blobsSchema).findFirst(\"blob\", (b) =>\n b.whereIndex(\"idx_blob_key\", (eb) => eb(\"key\", \"=\", key)),\n ),\n )\n .transformRetrieve(([result]) => result)\n .execute();\n if (!blob) {\n return error({ message: \"The blob does not exist.\", code: \"BLOB_NOT_FOUND\" }, 404);\n }\n const sizeBytes = Number(blob.sizeBytes);\n if (offset >= sizeBytes) {\n return error(\n {\n message: `The blob ends before byte ${offset}; it holds ${sizeBytes} bytes.`,\n code: \"RANGE_NOT_SATISFIABLE\",\n },\n 416,\n );\n }\n\n const end = Math.min(offset + length, sizeBytes);\n let range;\n try {\n // The upload's URL can still overwrite the object after the upload completed, so only\n // bytes that still carry the recorded tag match the blob's size and tag.\n range = await config.storage.readObjectRange({\n objectKey: blob.objectKey,\n etag: blob.etag,\n offset,\n length: end - offset,\n });\n } catch {\n return error({ message: \"Storage error\", code: \"STORAGE_ERROR\" }, 502);\n }\n // Replacing or deleting the blob since it was read removes its object.\n if (range.status === \"missing\") {\n return error({ message: \"The blob does not exist.\", code: \"BLOB_NOT_FOUND\" }, 404);\n }\n if (range.status === \"changed\") {\n return error(\n {\n message: \"Storage holds other bytes than the blob recorded.\",\n code: \"BLOB_CHANGED\",\n },\n 409,\n );\n }\n return new Response(range.bytes, {\n status: 206,\n headers: {\n \"Content-Type\": \"application/octet-stream\",\n \"Content-Range\": `bytes ${offset}-${end - 1}/${sizeBytes}`,\n // Tells readers combining several ranges whether they all came from the same bytes.\n ETag: `\"${blob.etag}\"`,\n },\n });\n },\n }),\n\n defineRoute({\n method: \"DELETE\",\n path: \"/blobs/by-key\",\n queryParameters: [\"key\"],\n outputSchema: z.object({ ok: z.literal(true) }),\n errorCodes,\n handler: async function ({ query }, { json, error }) {\n const key = blobKeyQuery(query);\n if (key === null) {\n return error({ message: \"The blob key is invalid.\", code: \"INVALID_KEY\" }, 400);\n }\n const deleted = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(blobsSchema).findFirst(\"blob\", (b) =>\n b.whereIndex(\"idx_blob_key\", (eb) => eb(\"key\", \"=\", key)),\n ),\n )\n .mutate(({ forSchema, retrieveResult: [blob] }) => {\n if (!blob) {\n return false;\n }\n const uow = forSchema(blobsSchema);\n uow.delete(\"blob\", blob.id, (b) => b.check());\n uow.triggerHook(\"deleteObject\", { objectKey: blob.objectKey });\n uow.triggerHook(\"onBlobDeleted\", toBlob(blob));\n return true;\n })\n .execute();\n if (!deleted) {\n return error({ message: \"The blob does not exist.\", code: \"BLOB_NOT_FOUND\" }, 404);\n }\n return json({ ok: true });\n },\n }),\n ];\n },\n);\n"],"mappings":";;;;;AAQA,MAAM,4BAA4B;AAClC,MAAM,kCAAkC;AAGxC,MAAM,qCAAqC,OAAU;AAErD,MAAM,uBAAuB;;AAE7B,MAAa,wBAAwB,IAAI,OAAO;AAChD,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AAEtB,MAAM,aAAa;CACjB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAIA,MAAM,eAAe;CACnB,aAAa;CACb,eAAe;CACf,uBAAuB;CACvB,kBAAkB;CAClB,gBAAgB;CAChB,wBAAwB;CACxB,gBAAgB;CAChB,cAAc;CACd,eAAe;AACjB;AAEA,IAAM,aAAN,cAAyB,MAAM;CAElB;CADX,YACE,MACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,OAAA;CAIX;AACF;AAEA,MAAM,aAAa,EAAE,OAAO;CAC1B,KAAK,EAAE,OAAO;CACd,WAAW,EAAE,OAAO;CACpB,aAAa,EAAE,OAAO;CACtB,MAAM,EAAE,OAAO;AACjB,CAAC;AAED,SAAS,OAAO,MAKD;CACb,OAAO;EACL,KAAK,KAAK;EACV,WAAW,O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AAM,MAAM,UAAU,WAAW;KACjC,IAAI,OAAO,QAAQ,KAAK,KAAK,MAAM,EAAE,MAAM,CAAC;KAC5C,IAAI,YAAY,gBAAgB,EAAE,WAAW,KAAK,UAAU,CAAC;KAC7D,IAAI,YAAY,iBAAiB,OAAO,IAAI,CAAC;KAC7C,OAAO;IACT,CAAC,CAAC,CACD,QAAQ,GAET,OAAO,MAAM;KAAE,SAAS;KAA4B,MAAM;IAAiB,GAAG,GAAG;IAEnF,OAAO,KAAK,EAAE,IAAI,KAAK,CAAC;GAC1B;EACF,CAAC;CACH;AACF,CACF"}
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { column, idColumn, schema } from "@fragno-dev/db/schema";
|
|
2
|
+
//#region src/schema.ts
|
|
3
|
+
const blobsSchema = schema("blobs", (s) => {
|
|
4
|
+
return s.addTable("blob", (t) => {
|
|
5
|
+
return t.addColumn("id", idColumn()).addColumn("key", column("string")).addColumn("objectKey", column("string")).addColumn("sizeBytes", column("bigint")).addColumn("contentType", column("string")).addColumn("etag", column("string")).addColumn("createdAt", column("timestamp").defaultTo((b) => b.now())).addColumn("updatedAt", column("timestamp").defaultTo((b) => b.now())).createIndex("idx_blob_key", ["key"], { unique: true });
|
|
6
|
+
}).addTable("blob_upload", (t) => {
|
|
7
|
+
return t.addColumn("id", idColumn()).addColumn("key", column("string")).addColumn("objectKey", column("string")).addColumn("contentType", column("string")).addColumn("expiresAt", column("timestamp")).addColumn("createdAt", column("timestamp").defaultTo((b) => b.now())).createIndex("idx_blob_upload_key", ["key"]);
|
|
8
|
+
});
|
|
9
|
+
});
|
|
10
|
+
//#endregion
|
|
11
|
+
export { blobsSchema };
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","names":[],"sources":["../src/schema.ts"],"sourcesContent":["import { column, idColumn, schema } from \"@fragno-dev/db/schema\";\n\nexport const blobsSchema = schema(\"blobs\", (s) => {\n return s\n .addTable(\"blob\", (t) => {\n return (\n t\n .addColumn(\"id\", idColumn())\n .addColumn(\"key\", column(\"string\"))\n // Every upload stores its bytes under a fresh object key, so replacing a blob never\n // overwrites the object an earlier download URL still reads.\n .addColumn(\"objectKey\", column(\"string\"))\n .addColumn(\"sizeBytes\", column(\"bigint\"))\n .addColumn(\"contentType\", column(\"string\"))\n .addColumn(\"etag\", column(\"string\"))\n .addColumn(\n \"createdAt\",\n column(\"timestamp\").defaultTo((b) => b.now()),\n )\n .addColumn(\n \"updatedAt\",\n column(\"timestamp\").defaultTo((b) => b.now()),\n )\n .createIndex(\"idx_blob_key\", [\"key\"], { unique: true })\n );\n })\n .addTable(\"blob_upload\", (t) => {\n return t\n .addColumn(\"id\", idColumn())\n .addColumn(\"key\", column(\"string\"))\n .addColumn(\"objectKey\", column(\"string\"))\n .addColumn(\"contentType\", column(\"string\"))\n .addColumn(\"expiresAt\", column(\"timestamp\"))\n .addColumn(\n \"createdAt\",\n column(\"timestamp\").defaultTo((b) => b.now()),\n )\n .createIndex(\"idx_blob_upload_key\", [\"key\"]);\n });\n});\n"],"mappings":";;AAEA,MAAa,cAAc,OAAO,UAAU,MAAM;CAChD,OAAO,EACJ,SAAS,SAAS,MAAM;EACvB,OACE,EACG,UAAU,MAAM,SAAS,CAAC,CAAC,CAC3B,UAAU,OAAO,OAAO,QAAQ,CAAC,CAAC,CAGlC,UAAU,aAAa,OAAO,QAAQ,CAAC,CAAC,CACxC,UAAU,aAAa,OAAO,QAAQ,CAAC,CAAC,CACxC,UAAU,eAAe,OAAO,QAAQ,CAAC,CAAC,CAC1C,UAAU,QAAQ,OAAO,QAAQ,CAAC,CAAC,CACnC,UACC,aACA,OAAO,WAAW,CAAC,CAAC,WAAW,MAAM,EAAE,IAAI,CAAC,CAC9C,CAAC,CACA,UACC,aACA,OAAO,WAAW,CAAC,CAAC,WAAW,MAAM,EAAE,IAAI,CAAC,CAC9C,CAAC,CACA,YAAY,gBAAgB,CAAC,KAAK,GAAG,EAAE,QAAQ,KAAK,CAAC;CAE5D,CAAC,CAAC,CACD,SAAS,gBAAgB,MAAM;EAC9B,OAAO,EACJ,UAAU,MAAM,SAAS,CAAC,CAAC,CAC3B,UAAU,OAAO,OAAO,QAAQ,CAAC,CAAC,CAClC,UAAU,aAAa,OAAO,QAAQ,CAAC,CAAC,CACxC,UAAU,eAAe,OAAO,QAAQ,CAAC,CAAC,CAC1C,UAAU,aAAa,OAAO,WAAW,CAAC,CAAC,CAC3C,UACC,aACA,OAAO,WAAW,CAAC,CAAC,WAAW,MAAM,EAAE,IAAI,CAAC,CAC9C,CAAC,CACA,YAAY,uBAAuB,CAAC,KAAK,CAAC;CAC/C,CAAC;AACL,CAAC"}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
//#region src/storage.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Object storage that hands out presigned URLs, so blob bytes travel between callers and storage
|
|
4
|
+
* without passing through the server.
|
|
5
|
+
*/
|
|
6
|
+
interface BlobStorage {
|
|
7
|
+
/** A URL that accepts one PUT of the object's bytes, sent with `headers` unchanged. */
|
|
8
|
+
createUploadUrl(input: {
|
|
9
|
+
objectKey: string;
|
|
10
|
+
contentType: string;
|
|
11
|
+
expiresInSeconds: number;
|
|
12
|
+
}): Promise<{
|
|
13
|
+
url: string;
|
|
14
|
+
headers: Record<string, string>;
|
|
15
|
+
}>;
|
|
16
|
+
/** A URL whose GET returns the object's bytes. */
|
|
17
|
+
createDownloadUrl(input: {
|
|
18
|
+
objectKey: string;
|
|
19
|
+
expiresInSeconds: number;
|
|
20
|
+
}): Promise<string>;
|
|
21
|
+
/**
|
|
22
|
+
* `length` bytes of the object from byte `offset`, which must lie within it, provided the object
|
|
23
|
+
* still carries `etag`.
|
|
24
|
+
*/
|
|
25
|
+
readObjectRange(input: {
|
|
26
|
+
objectKey: string;
|
|
27
|
+
etag: string;
|
|
28
|
+
offset: number;
|
|
29
|
+
length: number;
|
|
30
|
+
}): Promise<ObjectRange>;
|
|
31
|
+
/** What storage holds at the key, or null when it holds no object there. */
|
|
32
|
+
describeObject(objectKey: string): Promise<StoredObject | null>;
|
|
33
|
+
/** Deletes the object; deleting a missing object succeeds. */
|
|
34
|
+
deleteObject(objectKey: string): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
type StoredObject = {
|
|
37
|
+
sizeBytes: bigint;
|
|
38
|
+
/** Storage's tag for the object's bytes, without quotes; it changes whenever the bytes do. */
|
|
39
|
+
etag: string;
|
|
40
|
+
};
|
|
41
|
+
type ObjectRange = {
|
|
42
|
+
status: "read";
|
|
43
|
+
bytes: Uint8Array<ArrayBuffer>;
|
|
44
|
+
} | {
|
|
45
|
+
status: "missing";
|
|
46
|
+
} | {
|
|
47
|
+
status: "changed";
|
|
48
|
+
};
|
|
49
|
+
/** Signs S3 API requests with AWS Signature Version 4. */
|
|
50
|
+
type S3Signer = {
|
|
51
|
+
/** Signs a request the server sends itself, with the signature in its headers. */
|
|
52
|
+
sign(request: {
|
|
53
|
+
method: "GET" | "HEAD" | "DELETE";
|
|
54
|
+
url: string;
|
|
55
|
+
headers: Record<string, string>;
|
|
56
|
+
}): Promise<{
|
|
57
|
+
url: string;
|
|
58
|
+
headers: Record<string, string>;
|
|
59
|
+
}>;
|
|
60
|
+
/** Signs a request someone else sends, with the signature in the URL. */
|
|
61
|
+
presign(request: {
|
|
62
|
+
method: "GET" | "PUT";
|
|
63
|
+
url: string;
|
|
64
|
+
headers: Record<string, string>;
|
|
65
|
+
expiresInSeconds: number;
|
|
66
|
+
}): Promise<{
|
|
67
|
+
url: string;
|
|
68
|
+
headers: Record<string, string>;
|
|
69
|
+
}>;
|
|
70
|
+
};
|
|
71
|
+
type S3BlobStorageOptions = {
|
|
72
|
+
/** The S3 API endpoint, e.g. `https://<account>.r2.cloudflarestorage.com` for R2. */
|
|
73
|
+
endpoint: string;
|
|
74
|
+
bucket: string;
|
|
75
|
+
/** Addresses the bucket in the URL's path instead of its hostname, as R2 and MinIO need. */
|
|
76
|
+
pathStyle: boolean;
|
|
77
|
+
signer: S3Signer;
|
|
78
|
+
/** Sends the signed storage requests. */
|
|
79
|
+
fetch: typeof fetch;
|
|
80
|
+
};
|
|
81
|
+
/** Blob storage in an S3-compatible bucket, such as R2. */
|
|
82
|
+
declare function createS3BlobStorage(options: S3BlobStorageOptions): BlobStorage;
|
|
83
|
+
//#endregion
|
|
84
|
+
export { BlobStorage, ObjectRange, S3BlobStorageOptions, S3Signer, StoredObject, createS3BlobStorage };
|
|
85
|
+
//# sourceMappingURL=storage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.d.ts","names":[],"sources":["../src/storage.ts"],"mappings":";;;;;UAIiB;;EAEf,gBAAgB;IACd;IACA;IACA;MACE;IAAU;IAAa,SAAS;;;EAEpC,kBAAkB;IAAS;IAAmB;MAA6B;;;;;EAK3E,gBAAgB;IACd;IACA;IACA;IACA;MACE,QAAQ;;EAEZ,eAAe,oBAAoB,QAAQ;;EAE3C,aAAa,oBAAoB;;KAGvB;EACV;;EAEA;;KAGU;EACN;EAAgB,OAAO,WAAW;;EAClC;;EAEA;;;KAGM;;EAEV,KAAK;IACH;IACA;IACA,SAAS;MACP;IAAU;IAAa,SAAS;;;EAEpC,QAAQ;IACN;IACA;IACA,SAAS;IACT;MACE;IAAU;IAAa,SAAS;;;KAG1B;;EAEV;EACA;;EAEA;EACA,QAAQ;;EAER,cAAc;;;iBAIA,oBAAoB,SAAS,uBAAuB"}
|
package/dist/storage.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
//#region src/storage.ts
|
|
2
|
+
/** Blob storage in an S3-compatible bucket, such as R2. */
|
|
3
|
+
function createS3BlobStorage(options) {
|
|
4
|
+
const objectUrl = (objectKey) => {
|
|
5
|
+
const url = new URL(options.endpoint);
|
|
6
|
+
const basePath = url.pathname.replace(/^\/+|\/+$/g, "");
|
|
7
|
+
const encodedKey = objectKey.split("/").map(encodeURIComponent).join("/");
|
|
8
|
+
if (options.pathStyle) url.pathname = `/${[
|
|
9
|
+
basePath,
|
|
10
|
+
options.bucket,
|
|
11
|
+
encodedKey
|
|
12
|
+
].filter(Boolean).join("/")}`;
|
|
13
|
+
else {
|
|
14
|
+
url.hostname = `${options.bucket}.${url.hostname}`;
|
|
15
|
+
url.pathname = `/${[basePath, encodedKey].filter(Boolean).join("/")}`;
|
|
16
|
+
}
|
|
17
|
+
return url.toString();
|
|
18
|
+
};
|
|
19
|
+
const send = async (method, objectKey, headers) => {
|
|
20
|
+
const signed = await options.signer.sign({
|
|
21
|
+
method,
|
|
22
|
+
url: objectUrl(objectKey),
|
|
23
|
+
headers
|
|
24
|
+
});
|
|
25
|
+
const sendRequest = options.fetch;
|
|
26
|
+
return await sendRequest(signed.url, {
|
|
27
|
+
method,
|
|
28
|
+
headers: signed.headers
|
|
29
|
+
});
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
async createUploadUrl({ objectKey, contentType, expiresInSeconds }) {
|
|
33
|
+
return await options.signer.presign({
|
|
34
|
+
method: "PUT",
|
|
35
|
+
url: objectUrl(objectKey),
|
|
36
|
+
headers: { "Content-Type": contentType },
|
|
37
|
+
expiresInSeconds
|
|
38
|
+
});
|
|
39
|
+
},
|
|
40
|
+
async createDownloadUrl({ objectKey, expiresInSeconds }) {
|
|
41
|
+
return (await options.signer.presign({
|
|
42
|
+
method: "GET",
|
|
43
|
+
url: objectUrl(objectKey),
|
|
44
|
+
headers: {},
|
|
45
|
+
expiresInSeconds
|
|
46
|
+
})).url;
|
|
47
|
+
},
|
|
48
|
+
async readObjectRange({ objectKey, etag, offset, length }) {
|
|
49
|
+
const response = await send("GET", objectKey, {
|
|
50
|
+
"If-Match": `"${etag}"`,
|
|
51
|
+
Range: `bytes=${offset}-${offset + length - 1}`
|
|
52
|
+
});
|
|
53
|
+
if (response.status === 404) return { status: "missing" };
|
|
54
|
+
if (response.status === 412) return { status: "changed" };
|
|
55
|
+
if (response.status !== 206) throw new Error(`Storage could not read object ${objectKey} (${response.status}).`);
|
|
56
|
+
return {
|
|
57
|
+
status: "read",
|
|
58
|
+
bytes: new Uint8Array(await response.arrayBuffer())
|
|
59
|
+
};
|
|
60
|
+
},
|
|
61
|
+
async describeObject(objectKey) {
|
|
62
|
+
const response = await send("HEAD", objectKey, {});
|
|
63
|
+
if (response.status === 404) return null;
|
|
64
|
+
const contentLength = response.headers.get("content-length");
|
|
65
|
+
const etag = response.headers.get("etag")?.replace(/^"|"$/g, "");
|
|
66
|
+
if (!response.ok || contentLength === null || !/^\d+$/.test(contentLength) || !etag) throw new Error(`Storage could not describe object ${objectKey} (${response.status}).`);
|
|
67
|
+
return {
|
|
68
|
+
sizeBytes: BigInt(contentLength),
|
|
69
|
+
etag
|
|
70
|
+
};
|
|
71
|
+
},
|
|
72
|
+
async deleteObject(objectKey) {
|
|
73
|
+
const response = await send("DELETE", objectKey, {});
|
|
74
|
+
if (!response.ok && response.status !== 404) throw new Error(`Storage could not delete object ${objectKey} (${response.status}).`);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
//#endregion
|
|
79
|
+
export { createS3BlobStorage };
|
|
80
|
+
|
|
81
|
+
//# sourceMappingURL=storage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.js","names":[],"sources":["../src/storage.ts"],"sourcesContent":["/**\n * Object storage that hands out presigned URLs, so blob bytes travel between callers and storage\n * without passing through the server.\n */\nexport interface BlobStorage {\n /** A URL that accepts one PUT of the object's bytes, sent with `headers` unchanged. */\n createUploadUrl(input: {\n objectKey: string;\n contentType: string;\n expiresInSeconds: number;\n }): Promise<{ url: string; headers: Record<string, string> }>;\n /** A URL whose GET returns the object's bytes. */\n createDownloadUrl(input: { objectKey: string; expiresInSeconds: number }): Promise<string>;\n /**\n * `length` bytes of the object from byte `offset`, which must lie within it, provided the object\n * still carries `etag`.\n */\n readObjectRange(input: {\n objectKey: string;\n etag: string;\n offset: number;\n length: number;\n }): Promise<ObjectRange>;\n /** What storage holds at the key, or null when it holds no object there. */\n describeObject(objectKey: string): Promise<StoredObject | null>;\n /** Deletes the object; deleting a missing object succeeds. */\n deleteObject(objectKey: string): Promise<void>;\n}\n\nexport type StoredObject = {\n sizeBytes: bigint;\n /** Storage's tag for the object's bytes, without quotes; it changes whenever the bytes do. */\n etag: string;\n};\n\nexport type ObjectRange =\n | { status: \"read\"; bytes: Uint8Array<ArrayBuffer> }\n | { status: \"missing\" }\n // Storage holds other bytes than those tagged `etag`.\n | { status: \"changed\" };\n\n/** Signs S3 API requests with AWS Signature Version 4. */\nexport type S3Signer = {\n /** Signs a request the server sends itself, with the signature in its headers. */\n sign(request: {\n method: \"GET\" | \"HEAD\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n }): Promise<{ url: string; headers: Record<string, string> }>;\n /** Signs a request someone else sends, with the signature in the URL. */\n presign(request: {\n method: \"GET\" | \"PUT\";\n url: string;\n headers: Record<string, string>;\n expiresInSeconds: number;\n }): Promise<{ url: string; headers: Record<string, string> }>;\n};\n\nexport type S3BlobStorageOptions = {\n /** The S3 API endpoint, e.g. `https://<account>.r2.cloudflarestorage.com` for R2. */\n endpoint: string;\n bucket: string;\n /** Addresses the bucket in the URL's path instead of its hostname, as R2 and MinIO need. */\n pathStyle: boolean;\n signer: S3Signer;\n /** Sends the signed storage requests. */\n fetch: typeof fetch;\n};\n\n/** Blob storage in an S3-compatible bucket, such as R2. */\nexport function createS3BlobStorage(options: S3BlobStorageOptions): BlobStorage {\n const objectUrl = (objectKey: string) => {\n const url = new URL(options.endpoint);\n const basePath = url.pathname.replace(/^\\/+|\\/+$/g, \"\");\n const encodedKey = objectKey.split(\"/\").map(encodeURIComponent).join(\"/\");\n if (options.pathStyle) {\n url.pathname = `/${[basePath, options.bucket, encodedKey].filter(Boolean).join(\"/\")}`;\n } else {\n url.hostname = `${options.bucket}.${url.hostname}`;\n url.pathname = `/${[basePath, encodedKey].filter(Boolean).join(\"/\")}`;\n }\n return url.toString();\n };\n\n const send = async (\n method: \"GET\" | \"HEAD\" | \"DELETE\",\n objectKey: string,\n headers: Record<string, string>,\n ) => {\n const signed = await options.signer.sign({ method, url: objectUrl(objectKey), headers });\n // Called unbound: Workers' global `fetch` throws when called as a method of another object.\n const sendRequest = options.fetch;\n return await sendRequest(signed.url, { method, headers: signed.headers });\n };\n\n return {\n async createUploadUrl({ objectKey, contentType, expiresInSeconds }) {\n return await options.signer.presign({\n method: \"PUT\",\n url: objectUrl(objectKey),\n headers: { \"Content-Type\": contentType },\n expiresInSeconds,\n });\n },\n async createDownloadUrl({ objectKey, expiresInSeconds }) {\n const signed = await options.signer.presign({\n method: \"GET\",\n url: objectUrl(objectKey),\n headers: {},\n expiresInSeconds,\n });\n return signed.url;\n },\n async readObjectRange({ objectKey, etag, offset, length }) {\n const response = await send(\"GET\", objectKey, {\n \"If-Match\": `\"${etag}\"`,\n Range: `bytes=${offset}-${offset + length - 1}`,\n });\n if (response.status === 404) {\n return { status: \"missing\" };\n }\n if (response.status === 412) {\n return { status: \"changed\" };\n }\n if (response.status !== 206) {\n throw new Error(`Storage could not read object ${objectKey} (${response.status}).`);\n }\n return { status: \"read\", bytes: new Uint8Array(await response.arrayBuffer()) };\n },\n async describeObject(objectKey) {\n const response = await send(\"HEAD\", objectKey, {});\n if (response.status === 404) {\n return null;\n }\n const contentLength = response.headers.get(\"content-length\");\n const etag = response.headers.get(\"etag\")?.replace(/^\"|\"$/g, \"\");\n if (!response.ok || contentLength === null || !/^\\d+$/.test(contentLength) || !etag) {\n throw new Error(`Storage could not describe object ${objectKey} (${response.status}).`);\n }\n return { sizeBytes: BigInt(contentLength), etag };\n },\n async deleteObject(objectKey) {\n const response = await send(\"DELETE\", objectKey, {});\n if (!response.ok && response.status !== 404) {\n throw new Error(`Storage could not delete object ${objectKey} (${response.status}).`);\n }\n },\n };\n}\n"],"mappings":";;AAsEA,SAAgB,oBAAoB,SAA4C;CAC9E,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AAO,GAAG,SAAS,SAAS;GAC9C,CAAC;GACD,IAAI,SAAS,WAAW,KACtB,OAAO,EAAE,QAAQ,UAAU;GAE7B,IAAI,SAAS,WAAW,KACtB,OAAO,EAAE,QAAQ,UAAU;GAE7B,IAAI,SAAS,WAAW,KACtB,MAAM,IAAI,MAAM,iCAAiC,UAAU,IAAI,SAAS,OAAO,GAAG;GAEpF,OAAO;IAAE,QAAQ;IAAQ,OAAO,IAAI,WAAW,MAAM,SAAS,YAAY,CAAC;GAAE;EAC/E;EACA,MAAM,eAAe,WAAW;GAC9B,MAAM,WAAW,MAAM,KAAK,QAAQ,WAAW,CAAC,CAAC;GACjD,IAAI,SAAS,WAAW,KACtB,OAAO;GAET,MAAM,gBAAgB,SAAS,QAAQ,IAAI,gBAAgB;GAC3D,MAAM,OAAO,SAAS,QAAQ,IAAI,MAAM,CAAC,EAAE,QAAQ,UAAU,EAAE;GAC/D,IAAI,CAAC,SAAS,MAAM,kBAAkB,QAAQ,CAAC,QAAQ,KAAK,aAAa,KAAK,CAAC,MAC7E,MAAM,IAAI,MAAM,qCAAqC,UAAU,IAAI,SAAS,OAAO,GAAG;GAExF,OAAO;IAAE,WAAW,OAAO,aAAa;IAAG;GAAK;EAClD;EACA,MAAM,aAAa,WAAW;GAC5B,MAAM,WAAW,MAAM,KAAK,UAAU,WAAW,CAAC,CAAC;GACnD,IAAI,CAAC,SAAS,MAAM,SAAS,WAAW,KACtC,MAAM,IAAI,MAAM,mCAAmC,UAAU,IAAI,SAAS,OAAO,GAAG;EAExF;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fragno-dev/blobs",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "Fragno fragment for large files kept in S3-compatible object storage",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"fragno",
|
|
7
|
+
"typescript"
|
|
8
|
+
],
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "https://github.com/rejot-dev/fragno.git",
|
|
12
|
+
"directory": "packages/fragment-blobs"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist"
|
|
16
|
+
],
|
|
17
|
+
"type": "module",
|
|
18
|
+
"main": "./dist/index.js",
|
|
19
|
+
"module": "./dist/index.js",
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"default": "./dist/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./routes": {
|
|
27
|
+
"types": "./dist/routes.d.ts",
|
|
28
|
+
"default": "./dist/routes.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"zod": "^4.5.4",
|
|
33
|
+
"@fragno-dev/db": "0.4.1",
|
|
34
|
+
"@fragno-dev/core": "0.2.2"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@types/node": "^24",
|
|
38
|
+
"@vitest/coverage-istanbul": "^5.0.5",
|
|
39
|
+
"tsdown": "^0.22.4",
|
|
40
|
+
"vitest": "^5.0.5",
|
|
41
|
+
"@fragno-dev/unplugin-fragno": "0.0.9",
|
|
42
|
+
"@fragno-dev/test": "2.0.2",
|
|
43
|
+
"@fragno-private/vitest-config": "0.0.0"
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"typescript": "npm:@typescript/typescript6@^6.0.2"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"types:check": "tsc --noEmit",
|
|
50
|
+
"build": "tsdown",
|
|
51
|
+
"test": "vitest run",
|
|
52
|
+
"test:watch": "vitest --watch",
|
|
53
|
+
"format:package": "node ../../scripts/run-package-quality.mjs format",
|
|
54
|
+
"format:check:package": "node ../../scripts/run-package-quality.mjs format:check",
|
|
55
|
+
"lint:package": "node ../../scripts/run-package-quality.mjs lint",
|
|
56
|
+
"lint:fix:package": "node ../../scripts/run-package-quality.mjs lint:fix"
|
|
57
|
+
}
|
|
6
58
|
}
|