@fonderie/media 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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/routes.ts","../src/config.ts","../src/models/asset.model.ts","../src/dtos/media.ts","../src/services/image.ts","../src/module.ts","../src/providers/db-blob.ts","../src/providers/local-fs.ts"],"sourcesContent":["import type { Middleware } from '@fonderie/core';\nimport { HTTP, setApiResponse } from '@fonderie/core';\nimport { requireAuth } from '@fonderie/core/middlewares';\nimport type { IStoreAdapter } from '@fonderie/store';\n\nimport { DEFAULT_ALLOWED_TYPES, DEFAULT_MAX_BYTES, type IMediaConfig } from './config';\nimport { MediaAssetModel } from './models/asset.model';\nimport { toMediaAssetDTO } from './dtos/media';\nimport { decodeBase64, sniffImageType } from './services/image';\n\ntype Route = [string, string, ...Middleware[]];\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport function buildMediaRoutes(store: IStoreAdapter, config: IMediaConfig): Route[] {\n\tconst assets = new MediaAssetModel(store);\n\tconst maxBytes = config.maxBytes ?? DEFAULT_MAX_BYTES;\n\tconst allowed = config.allowedTypes ?? DEFAULT_ALLOWED_TYPES;\n\n\treturn [\n\t\t// POST /media { dataBase64, ownerType?, ownerId?, purpose? } -> { asset }\n\t\t// Accepts base64 (bare or a data URI), verifies it's a real image by its\n\t\t// magic bytes (never the client's claim), caps the decoded size, stores\n\t\t// the bytes via the provider, and records metadata. Returns a URL.\n\t\t[\n\t\t\t'POST',\n\t\t\t'/media',\n\t\t\trequireAuth,\n\t\t\tasync (ctx) => {\n\t\t\t\tconst userId = ctx.user!.id;\n\t\t\t\tconst body = (ctx.meta['body'] ?? {}) as {\n\t\t\t\t\tdataBase64?: unknown;\n\t\t\t\t\townerType?: unknown;\n\t\t\t\t\townerId?: unknown;\n\t\t\t\t\tpurpose?: unknown;\n\t\t\t\t};\n\n\t\t\t\tif (typeof body.dataBase64 !== 'string' || body.dataBase64.length === 0) {\n\t\t\t\t\treturn setApiResponse(HTTP.UNPROCESSABLE, 'INVALID_PARAMETER', 'dataBase64 (a base64 string) is required.');\n\t\t\t\t}\n\n\t\t\t\tlet bytes: Uint8Array;\n\t\t\t\ttry {\n\t\t\t\t\tbytes = decodeBase64(body.dataBase64);\n\t\t\t\t} catch {\n\t\t\t\t\treturn setApiResponse(HTTP.UNPROCESSABLE, 'INVALID_PARAMETER', 'dataBase64 is not valid base64.');\n\t\t\t\t}\n\t\t\t\tif (bytes.byteLength === 0) {\n\t\t\t\t\treturn setApiResponse(HTTP.UNPROCESSABLE, 'INVALID_PARAMETER', 'The image is empty.');\n\t\t\t\t}\n\t\t\t\tif (bytes.byteLength > maxBytes) {\n\t\t\t\t\treturn setApiResponse(HTTP.UNPROCESSABLE, 'ASSET_TOO_LARGE', `Image exceeds the ${maxBytes}-byte limit.`);\n\t\t\t\t}\n\n\t\t\t\tconst contentType = sniffImageType(bytes);\n\t\t\t\tif (!contentType || !allowed.includes(contentType)) {\n\t\t\t\t\treturn setApiResponse(\n\t\t\t\t\t\tHTTP.UNPROCESSABLE,\n\t\t\t\t\t\t'ASSET_UNSUPPORTED',\n\t\t\t\t\t\t`Unsupported image type. Allowed: ${allowed.join(', ')}.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst ownerType = typeof body.ownerType === 'string' ? body.ownerType : 'user';\n\t\t\t\tconst ownerId = typeof body.ownerId === 'string' ? body.ownerId : userId;\n\t\t\t\tconst purpose = typeof body.purpose === 'string' ? body.purpose : 'avatar';\n\n\t\t\t\tconst { ref } = await config.provider.put({ bytes, contentType });\n\t\t\t\tconst asset = await assets.create({\n\t\t\t\t\townerType,\n\t\t\t\t\townerId,\n\t\t\t\t\tpurpose,\n\t\t\t\t\tcontentType,\n\t\t\t\t\tbyteSize: bytes.byteLength,\n\t\t\t\t\tstorageRef: ref,\n\t\t\t\t\tcreatedBy: userId,\n\t\t\t\t});\n\n\t\t\t\t// Build the URL at whatever prefix this route is mounted under\n\t\t\t\t// (e.g. '/v1/media/:id'), derived from the request path.\n\t\t\t\tconst basePath = new URL(ctx.request.url).pathname.replace(/\\/media$/, '');\n\t\t\t\treturn setApiResponse(HTTP.OK, 'ASSET_CREATED', 'Asset uploaded.', {\n\t\t\t\t\tasset: toMediaAssetDTO(asset, basePath),\n\t\t\t\t});\n\t\t\t},\n\t\t],\n\n\t\t// GET /media/:id (PUBLIC — an <img src> can't send an Authorization\n\t\t// header) -> the image bytes with cache headers, or a 302 to a\n\t\t// provider-served URL. Assets are immutable, so the id is a stable ETag.\n\t\t[\n\t\t\t'GET',\n\t\t\t'/media/:id',\n\t\t\tasync (ctx) => {\n\t\t\t\tconst id = ctx.meta.params?.['id'];\n\t\t\t\tif (!id || !UUID_RE.test(id)) return new Response('Not found', { status: 404 });\n\n\t\t\t\tconst asset = await assets.get(id);\n\t\t\t\tif (!asset) return new Response('Not found', { status: 404 });\n\n\t\t\t\tconst etag = `\"${asset.id}\"`;\n\t\t\t\tif (ctx.request.headers.get('if-none-match') === etag) {\n\t\t\t\t\treturn new Response(null, { status: 304, headers: { ETag: etag } });\n\t\t\t\t}\n\n\t\t\t\tconst fetched = await config.provider.get(asset.storageRef);\n\t\t\t\tif (!fetched) return new Response('Not found', { status: 404 });\n\t\t\t\tif (fetched.kind === 'redirect') {\n\t\t\t\t\treturn new Response(null, { status: 302, headers: { Location: fetched.url } });\n\t\t\t\t}\n\t\t\t\t// Fresh Uint8Array (ArrayBuffer-backed) so it satisfies BodyInit; a\n\t\t\t\t// pg Buffer is typed Uint8Array<ArrayBufferLike>, which the lib rejects.\n\t\t\t\treturn new Response(new Uint8Array(fetched.bytes), {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': asset.contentType,\n\t\t\t\t\t\t'Content-Length': String(asset.byteSize),\n\t\t\t\t\t\t'Cache-Control': 'public, max-age=300',\n\t\t\t\t\t\tETag: etag,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t},\n\t\t],\n\n\t\t// DELETE /media/:id -> removes the asset; only the uploader may delete it.\n\t\t[\n\t\t\t'DELETE',\n\t\t\t'/media/:id',\n\t\t\trequireAuth,\n\t\t\tasync (ctx) => {\n\t\t\t\tconst id = ctx.meta.params?.['id'];\n\t\t\t\tif (!id || !UUID_RE.test(id)) {\n\t\t\t\t\treturn setApiResponse(HTTP.NOT_FOUND, 'ASSET_NOT_FOUND', 'No such asset.');\n\t\t\t\t}\n\t\t\t\tconst asset = await assets.get(id);\n\t\t\t\tif (!asset) return setApiResponse(HTTP.NOT_FOUND, 'ASSET_NOT_FOUND', 'No such asset.');\n\t\t\t\tif (asset.createdBy !== ctx.user!.id) {\n\t\t\t\t\treturn setApiResponse(HTTP.FORBIDDEN, 'FORBIDDEN', 'You can only delete assets you uploaded.');\n\t\t\t\t}\n\t\t\t\tawait config.provider.delete(asset.storageRef);\n\t\t\t\tawait assets.delete(id);\n\t\t\t\treturn setApiResponse(HTTP.OK, 'ASSET_DELETED', 'Asset deleted.', { id });\n\t\t\t},\n\t\t],\n\t];\n}\n","import type { IStorageProvider } from './providers/types';\n\nexport interface IMediaConfig {\n\t/** Where bytes are stored. `DbBlobProvider` (zero infra) by default; swap for S3 at scale. */\n\tprovider: IStorageProvider;\n\t/** Max decoded size per asset, in bytes. Default 1 MB. */\n\tmaxBytes?: number;\n\t/**\n\t * Content types accepted on upload (matched against magic bytes, not the\n\t * client's claim). Default: PNG / JPEG / WebP / GIF. SVG is never accepted —\n\t * it's a stored-XSS vector.\n\t */\n\tallowedTypes?: string[];\n}\n\nexport const DEFAULT_MAX_BYTES = 1_000_000;\nexport const DEFAULT_ALLOWED_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif'];\n","import type { IStoreAdapter } from '@fonderie/store';\n\nimport type { ICreateAssetInput, IMediaAsset } from '../types';\n\ninterface AssetRow {\n\tid: string;\n\towner_type: string;\n\towner_id: string;\n\tpurpose: string;\n\tcontent_type: string;\n\tbyte_size: number;\n\tstorage_ref: string;\n\tcreated_by: string | null;\n\tcreated_at: Date;\n}\n\nconst toAsset = (r: AssetRow): IMediaAsset => ({\n\tid: r.id,\n\townerType: r.owner_type,\n\townerId: r.owner_id,\n\tpurpose: r.purpose,\n\tcontentType: r.content_type,\n\tbyteSize: r.byte_size,\n\tstorageRef: r.storage_ref,\n\tcreatedBy: r.created_by,\n\tcreatedAt: r.created_at,\n});\n\n/** Data access for `fonderie_media_assets` — the metadata around each stored blob. */\nexport class MediaAssetModel {\n\tconstructor(private readonly store: IStoreAdapter) {}\n\n\tasync create(input: ICreateAssetInput): Promise<IMediaAsset> {\n\t\tconst rows = await this.store.query<AssetRow>(\n\t\t\t`INSERT INTO fonderie_media_assets\n\t\t\t (owner_type, owner_id, purpose, content_type, byte_size, storage_ref, created_by)\n\t\t\t VALUES ($1, $2, $3, $4, $5, $6, $7)\n\t\t\t RETURNING *`,\n\t\t\t[input.ownerType, input.ownerId, input.purpose, input.contentType, input.byteSize, input.storageRef, input.createdBy],\n\t\t);\n\t\treturn toAsset(rows[0]!);\n\t}\n\n\tasync get(id: string): Promise<IMediaAsset | null> {\n\t\tconst rows = await this.store.query<AssetRow>('SELECT * FROM fonderie_media_assets WHERE id = $1', [id]);\n\t\treturn rows[0] ? toAsset(rows[0]) : null;\n\t}\n\n\t/** The most recent asset for an owner + purpose (e.g. a user's current avatar). */\n\tasync latestFor(ownerType: string, ownerId: string, purpose: string): Promise<IMediaAsset | null> {\n\t\tconst rows = await this.store.query<AssetRow>(\n\t\t\t`SELECT * FROM fonderie_media_assets\n\t\t\t WHERE owner_type = $1 AND owner_id = $2 AND purpose = $3\n\t\t\t ORDER BY created_at DESC LIMIT 1`,\n\t\t\t[ownerType, ownerId, purpose],\n\t\t);\n\t\treturn rows[0] ? toAsset(rows[0]) : null;\n\t}\n\n\tasync delete(id: string): Promise<void> {\n\t\tawait this.store.query('DELETE FROM fonderie_media_assets WHERE id = $1', [id]);\n\t}\n}\n","import type { IMediaAsset } from '../types';\n\n/**\n * The wire shape for a stored asset. `url` is the monomorphic read contract:\n * always a `/media/:id` path, whatever the backend — clients render it in an\n * `<img>` and never care whether the bytes came from Postgres, disk, or S3.\n */\nexport interface IMediaAssetDTO {\n\tid: string;\n\turl: string;\n\tcontentType: string;\n\tbyteSize: number;\n\townerType: string;\n\townerId: string;\n\tpurpose: string;\n\tcreatedAt: string;\n}\n\n/** basePath is the router mount (e.g. '/v1'); '' yields a root-relative '/media/:id'. */\nexport function toMediaAssetDTO(asset: IMediaAsset, basePath = ''): IMediaAssetDTO {\n\treturn {\n\t\tid: asset.id,\n\t\turl: `${basePath}/media/${asset.id}`,\n\t\tcontentType: asset.contentType,\n\t\tbyteSize: asset.byteSize,\n\t\townerType: asset.ownerType,\n\t\townerId: asset.ownerId,\n\t\tpurpose: asset.purpose,\n\t\tcreatedAt: asset.createdAt instanceof Date ? asset.createdAt.toISOString() : String(asset.createdAt),\n\t};\n}\n","/**\n * Decode a base64 payload to bytes. Accepts both a bare base64 string and a\n * data URI (`data:image/png;base64,<...>`) — the frontend `FileReader` produces\n * the latter, so callers don't have to strip it.\n */\nexport function decodeBase64(input: string): Uint8Array {\n\tconst comma = input.startsWith('data:') ? input.indexOf(',') : -1;\n\tconst b64 = comma >= 0 ? input.slice(comma + 1) : input;\n\treturn new Uint8Array(Buffer.from(b64, 'base64'));\n}\n\n/**\n * Identify an image from its magic bytes — NOT from a client-claimed MIME type,\n * which is trivially spoofed. Returns the canonical content type or `null` for\n * anything unrecognised. SVG is deliberately not detected (it's XML, can carry\n * scripts, and is a stored-XSS vector), so it falls through to `null` and is\n * rejected upstream.\n */\nexport function sniffImageType(bytes: Uint8Array): string | null {\n\tconst b = bytes;\n\t// PNG: 89 50 4E 47 0D 0A 1A 0A\n\tif (b.length >= 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47 && b[4] === 0x0d && b[5] === 0x0a && b[6] === 0x1a && b[7] === 0x0a) {\n\t\treturn 'image/png';\n\t}\n\t// JPEG: FF D8 FF\n\tif (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) {\n\t\treturn 'image/jpeg';\n\t}\n\t// GIF: \"GIF87a\" / \"GIF89a\"\n\tif (b.length >= 6 && b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38 && (b[4] === 0x37 || b[4] === 0x39) && b[5] === 0x61) {\n\t\treturn 'image/gif';\n\t}\n\t// WEBP: \"RIFF\" .... \"WEBP\" (bytes 0-3 and 8-11)\n\tif (b.length >= 12 && b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50) {\n\t\treturn 'image/webp';\n\t}\n\treturn null;\n}\n","import type { IFonderieApp, IFonderieModule } from '@fonderie/core';\nimport type { IStoreAdapter } from '@fonderie/store';\n\nimport type { IMediaConfig } from './config';\nimport { buildMediaRoutes } from './routes';\n\n/**\n * Provider-abstracted asset storage. Register it like any other brick; it adds\n * `POST /media`, `GET /media/:id` (public), and `DELETE /media/:id`, and stores\n * bytes through the configured `IStorageProvider` (`DbBlobProvider` for zero\n * infra, swappable for object storage). Depends on `@fonderie/auth` for the\n * authenticated caller on upload/delete.\n */\nexport class MediaModule implements IFonderieModule {\n\treadonly name = '@fonderie/media';\n\treadonly deps = ['@fonderie/auth'];\n\n\tconstructor(\n\t\tprivate readonly store: IStoreAdapter,\n\t\tprivate readonly config: IMediaConfig,\n\t) {}\n\n\tinstall(app: IFonderieApp): void {\n\t\tfor (const [method, path, ...handlers] of buildMediaRoutes(this.store, this.config)) {\n\t\t\tapp.addRoute(method, path, ...handlers);\n\t\t}\n\t}\n}\n","import type { IStoreAdapter } from '@fonderie/store';\n\nimport type { IFetched, IStorageProvider, IStoredRef } from './types';\n\n/**\n * Zero-infra provider: bytes live in Postgres (`fonderie_media_blobs`, created by\n * this package's migration). Great for getting started and self-hosting — the\n * whole app is one Node process + one database, and a `pg_dump` captures the\n * images atomically with their metadata. Swap to `S3Provider` when bandwidth or\n * table size make object storage worth the extra moving part; no app code\n * changes, only the `MediaModule` config line.\n */\nexport class DbBlobProvider implements IStorageProvider {\n\treadonly name = 'db-blob';\n\n\tconstructor(private readonly store: IStoreAdapter) {}\n\n\tasync put({ bytes }: { bytes: Uint8Array; contentType: string }): Promise<IStoredRef> {\n\t\tconst rows = await this.store.query<{ id: string }>(\n\t\t\t'INSERT INTO fonderie_media_blobs (bytes) VALUES ($1) RETURNING id',\n\t\t\t[Buffer.from(bytes)],\n\t\t);\n\t\treturn { ref: rows[0]!.id };\n\t}\n\n\tasync get(ref: string): Promise<IFetched | null> {\n\t\tconst rows = await this.store.query<{ bytes: Buffer }>(\n\t\t\t'SELECT bytes FROM fonderie_media_blobs WHERE id = $1',\n\t\t\t[ref],\n\t\t);\n\t\tconst row = rows[0];\n\t\treturn row ? { kind: 'bytes', bytes: row.bytes } : null;\n\t}\n\n\tasync delete(ref: string): Promise<void> {\n\t\tawait this.store.query('DELETE FROM fonderie_media_blobs WHERE id = $1', [ref]);\n\t}\n}\n","import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { randomUUID } from 'node:crypto';\nimport { join, resolve } from 'node:path';\n\nimport type { IFetched, IStorageProvider, IStoredRef } from './types';\n\n/**\n * Zero-infra provider: bytes live on the server's filesystem under `dir`. Useful\n * for a single-box deployment that wants images off the database without\n * standing up object storage. The `ref` is an opaque filename; the asset's\n * content type is tracked in `fonderie_media_assets`, so nothing about the\n * bytes-on-disk needs to encode it.\n *\n * (Serves inline through the app like `DbBlobProvider`. It has no CDN in front,\n * so at real scale prefer `S3Provider` — same interface, one config line.)\n */\nexport class LocalFsProvider implements IStorageProvider {\n\treadonly name = 'local-fs';\n\tprivate readonly dir: string;\n\tprivate ready: Promise<void> | null = null;\n\n\tconstructor(dir: string) {\n\t\tthis.dir = resolve(dir);\n\t}\n\n\tprivate ensureDir(): Promise<void> {\n\t\tif (!this.ready) this.ready = mkdir(this.dir, { recursive: true }).then(() => undefined);\n\t\treturn this.ready;\n\t}\n\n\t// Reject any ref that isn't a bare id, so a ref can never escape `dir`\n\t// (path traversal). Ids we mint are UUIDs.\n\tprivate pathFor(ref: string): string {\n\t\tif (!/^[A-Za-z0-9_-]+$/.test(ref)) throw new Error('invalid media ref');\n\t\treturn join(this.dir, ref);\n\t}\n\n\tasync put({ bytes }: { bytes: Uint8Array; contentType: string }): Promise<IStoredRef> {\n\t\tawait this.ensureDir();\n\t\tconst ref = randomUUID();\n\t\tawait writeFile(this.pathFor(ref), bytes);\n\t\treturn { ref };\n\t}\n\n\tasync get(ref: string): Promise<IFetched | null> {\n\t\ttry {\n\t\t\tconst bytes = await readFile(this.pathFor(ref));\n\t\t\treturn { kind: 'bytes', bytes };\n\t\t} catch {\n\t\t\treturn null; // ENOENT (or an invalid ref) → treated as not found\n\t\t}\n\t}\n\n\tasync delete(ref: string): Promise<void> {\n\t\tawait rm(this.pathFor(ref), { force: true }); // force → no throw when already gone\n\t}\n}\n"],"mappings":";AACA,SAAS,MAAM,sBAAsB;AACrC,SAAS,mBAAmB;;;ACarB,IAAM,oBAAoB;AAC1B,IAAM,wBAAwB,CAAC,aAAa,cAAc,cAAc,WAAW;;;ACA1F,IAAM,UAAU,CAAC,OAA8B;AAAA,EAC9C,IAAI,EAAE;AAAA,EACN,WAAW,EAAE;AAAA,EACb,SAAS,EAAE;AAAA,EACX,SAAS,EAAE;AAAA,EACX,aAAa,EAAE;AAAA,EACf,UAAU,EAAE;AAAA,EACZ,YAAY,EAAE;AAAA,EACd,WAAW,EAAE;AAAA,EACb,WAAW,EAAE;AACd;AAGO,IAAM,kBAAN,MAAsB;AAAA,EAC5B,YAA6B,OAAsB;AAAtB;AAAA,EAAuB;AAAA,EAAvB;AAAA,EAE7B,MAAM,OAAO,OAAgD;AAC5D,UAAM,OA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;AACxC,UAAM,GAAG,KAAK,QAAQ,GAAG,GAAG,EAAE,OAAO,KAAK,CAAC;AAAA,EAC5C;AACD;","names":[]}
@@ -0,0 +1,3 @@
1
+ declare const getMigrationsPath: () => string;
2
+
3
+ export { getMigrationsPath };
@@ -0,0 +1,7 @@
1
+ // src/migrations/index.ts
2
+ import { createMigrationsPath } from "@fonderie/store";
3
+ var getMigrationsPath = () => createMigrationsPath(import.meta.url);
4
+ export {
5
+ getMigrationsPath
6
+ };
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/migrations/index.ts"],"sourcesContent":["import { createMigrationsPath } from '@fonderie/store';\n\nexport const getMigrationsPath = (): string => createMigrationsPath(import.meta.url);\n"],"mappings":";AAAA,SAAS,4BAA4B;AAE9B,IAAM,oBAAoB,MAAc,qBAAqB,YAAY,GAAG;","names":[]}
@@ -0,0 +1,37 @@
1
+ -- ----------------------------------------------------------------------------
2
+ -- 001_media
3
+ -- ----------------------------------------------------------------------------
4
+ -- Asset storage for @fonderie/media. Two tables:
5
+ --
6
+ -- fonderie_media_assets — metadata for every stored asset. `storage_ref` is the
7
+ -- opaque handle the configured IStorageProvider returned from put(); the
8
+ -- provider alone knows how to resolve it back to bytes. Addressed publicly by
9
+ -- id via GET /media/:id. Not FK'd to any owner table because owner_type varies
10
+ -- (user / workspace / customer / …).
11
+ --
12
+ -- fonderie_media_blobs — bytes for the built-in DbBlobProvider (zero-infra
13
+ -- storage in Postgres). Untouched when an external provider (local-fs, S3) is
14
+ -- wired; storage_ref then points into that backend instead.
15
+ -- ----------------------------------------------------------------------------
16
+
17
+ CREATE TABLE IF NOT EXISTS fonderie_media_assets (
18
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
19
+ owner_type TEXT NOT NULL,
20
+ owner_id UUID NOT NULL,
21
+ purpose TEXT NOT NULL,
22
+ content_type TEXT NOT NULL,
23
+ byte_size INTEGER NOT NULL,
24
+ storage_ref TEXT NOT NULL,
25
+ created_by UUID,
26
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
27
+ );
28
+
29
+ -- Supports "the current avatar/logo for this owner" lookups (latestFor).
30
+ CREATE INDEX IF NOT EXISTS idx_media_assets_owner
31
+ ON fonderie_media_assets (owner_type, owner_id, purpose, created_at DESC);
32
+
33
+ CREATE TABLE IF NOT EXISTS fonderie_media_blobs (
34
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
35
+ bytes BYTEA NOT NULL,
36
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
37
+ );
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@fonderie/media",
3
+ "version": "0.1.0",
4
+ "description": "Provider-abstracted asset storage — upload, store, and serve user-owned images (avatars, logos) with a DB-blob backend by default and object storage as a one-line swap.",
5
+ "keywords": [
6
+ "fonderiejs",
7
+ "media",
8
+ "storage",
9
+ "avatar",
10
+ "upload",
11
+ "saas",
12
+ "typescript"
13
+ ],
14
+ "license": "MIT",
15
+ "type": "module",
16
+ "engines": {
17
+ "node": ">=20"
18
+ },
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js",
23
+ "require": "./dist/index.cjs"
24
+ },
25
+ "./migrations": {
26
+ "types": "./dist/migrations/index.d.ts",
27
+ "import": "./dist/migrations/index.js"
28
+ }
29
+ },
30
+ "main": "./dist/index.cjs",
31
+ "module": "./dist/index.js",
32
+ "types": "./dist/index.d.ts",
33
+ "scripts": {
34
+ "build": "tsup && tsup --config tsup.migrations.ts",
35
+ "dev": "tsup --watch",
36
+ "typecheck": "tsc --noEmit",
37
+ "test": "tsx --test src/__tests__/*.test.ts",
38
+ "lint": "biome lint src",
39
+ "format": "biome format --write src",
40
+ "check": "biome check --write src"
41
+ },
42
+ "peerDependencies": {
43
+ "@fonderie/core": "^0.8.0",
44
+ "@fonderie/store": "^0.2.0"
45
+ },
46
+ "devDependencies": {
47
+ "@fonderie/core": "../core",
48
+ "@fonderie/store": "../store",
49
+ "@types/node": "^26.4.1",
50
+ "tsup": "^8.5.1",
51
+ "tsx": "^4.23.13",
52
+ "typescript": "^6.0.3"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
57
+ "files": [
58
+ "dist",
59
+ "brain",
60
+ "LICENSE",
61
+ "README.md"
62
+ ],
63
+ "repository": {
64
+ "type": "git",
65
+ "url": "git+https://github.com/fonderiejs/fonderie.git",
66
+ "directory": "packages/media"
67
+ },
68
+ "homepage": "https://github.com/fonderiejs/fonderie/tree/main/packages/media#readme",
69
+ "bugs": {
70
+ "url": "https://github.com/fonderiejs/fonderie/issues"
71
+ }
72
+ }