@opensaas/stack-storage 0.43.0 → 0.44.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +445 -0
- package/README.md +62 -30
- package/dist/.build-hash +1 -0
- package/dist/fields/index.d.ts +9 -8
- package/dist/fields/index.d.ts.map +1 -1
- package/dist/fields/index.js +376 -153
- package/dist/fields/index.js.map +1 -1
- package/dist/providers/local.d.ts +8 -0
- package/dist/providers/local.d.ts.map +1 -1
- package/dist/providers/local.js +56 -5
- package/dist/providers/local.js.map +1 -1
- package/dist/runtime/index.d.ts +29 -0
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/index.js +244 -29
- package/dist/runtime/index.js.map +1 -1
- package/dist/utils/asset-references.d.ts +13 -0
- package/dist/utils/asset-references.d.ts.map +1 -0
- package/dist/utils/asset-references.js +40 -0
- package/dist/utils/asset-references.js.map +1 -0
- package/dist/utils/image.d.ts +17 -0
- package/dist/utils/image.d.ts.map +1 -1
- package/dist/utils/image.js +69 -22
- package/dist/utils/image.js.map +1 -1
- package/dist/utils/metadata-trust.d.ts +30 -0
- package/dist/utils/metadata-trust.d.ts.map +1 -0
- package/dist/utils/metadata-trust.js +57 -0
- package/dist/utils/metadata-trust.js.map +1 -0
- package/dist/utils/multi-column.d.ts +7 -7
- package/dist/utils/multi-column.d.ts.map +1 -1
- package/dist/utils/multi-column.js +17 -34
- package/dist/utils/multi-column.js.map +1 -1
- package/dist/utils/upload.d.ts +58 -0
- package/dist/utils/upload.d.ts.map +1 -1
- package/dist/utils/upload.js +135 -11
- package/dist/utils/upload.js.map +1 -1
- package/package.json +20 -9
- package/.turbo/turbo-build.log +0 -4
- package/CLAUDE.md +0 -528
- package/src/config/index.ts +0 -30
- package/src/config/types.ts +0 -92
- package/src/fields/index.ts +0 -531
- package/src/index.ts +0 -14
- package/src/providers/index.ts +0 -1
- package/src/providers/local.ts +0 -79
- package/src/runtime/index.ts +0 -244
- package/src/runtime/registry.ts +0 -106
- package/src/utils/image.ts +0 -95
- package/src/utils/index.ts +0 -3
- package/src/utils/multi-column.ts +0 -425
- package/src/utils/upload.ts +0 -95
- package/tests/field-zod-schema.test.ts +0 -133
- package/tests/image-utils.test.ts +0 -498
- package/tests/local-provider.test.ts +0 -364
- package/tests/multi-column-fields.test.ts +0 -393
- package/tests/multi-column.test.ts +0 -453
- package/tests/opensaas-image-file-write-validation.test.ts +0 -294
- package/tests/provider-registry.test.ts +0 -201
- package/tests/upload-utils.test.ts +0 -313
- package/tsconfig.json +0 -9
- package/vitest.config.ts +0 -14
package/CLAUDE.md
DELETED
|
@@ -1,528 +0,0 @@
|
|
|
1
|
-
# @opensaas/stack-storage
|
|
2
|
-
|
|
3
|
-
File and image upload field types with pluggable storage providers.
|
|
4
|
-
|
|
5
|
-
## Purpose
|
|
6
|
-
|
|
7
|
-
Provides file and image upload capabilities for OpenSaas Stack with:
|
|
8
|
-
|
|
9
|
-
- Self-contained field types (`file()` and `image()`)
|
|
10
|
-
- Pluggable storage providers (local, S3, Vercel Blob)
|
|
11
|
-
- Automatic image transformations with sharp
|
|
12
|
-
- JSON-backed metadata storage
|
|
13
|
-
- Developer-controlled upload routes
|
|
14
|
-
|
|
15
|
-
## Package Structure
|
|
16
|
-
|
|
17
|
-
```
|
|
18
|
-
packages/storage/
|
|
19
|
-
├── src/
|
|
20
|
-
│ ├── config/ # Storage config types and builders
|
|
21
|
-
│ ├── fields/ # file() and image() field builders
|
|
22
|
-
│ ├── providers/ # LocalStorageProvider
|
|
23
|
-
│ ├── runtime/ # Upload/delete utilities for developers
|
|
24
|
-
│ └── utils/ # Image processing, validation utilities
|
|
25
|
-
└── package.json
|
|
26
|
-
|
|
27
|
-
packages/storage-s3/ # Separate S3 provider package
|
|
28
|
-
packages/storage-vercel/ # Separate Vercel Blob provider package
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
## Key Exports
|
|
32
|
-
|
|
33
|
-
### Config (`src/config/`)
|
|
34
|
-
|
|
35
|
-
- `localStorage(config)` - Creates local filesystem storage config
|
|
36
|
-
- Types: `StorageProvider`, `StorageConfig`, `FileMetadata`, `ImageMetadata`
|
|
37
|
-
|
|
38
|
-
### Fields (`src/fields/`)
|
|
39
|
-
|
|
40
|
-
- `file(options)` - File upload field builder
|
|
41
|
-
- `image(options)` - Image upload field builder with transformations
|
|
42
|
-
|
|
43
|
-
### Providers (`src/providers/`)
|
|
44
|
-
|
|
45
|
-
- `LocalStorageProvider` - Built-in filesystem storage
|
|
46
|
-
|
|
47
|
-
### Runtime (`src/runtime/`)
|
|
48
|
-
|
|
49
|
-
- `uploadFile(config, provider, data, options)` - Upload file and return metadata
|
|
50
|
-
- `uploadImage(config, provider, data, options)` - Upload image with transformations
|
|
51
|
-
- `deleteFile(config, provider, filename)` - Delete file
|
|
52
|
-
- `deleteImage(config, metadata)` - Delete image and all transformations
|
|
53
|
-
- `createStorageProvider(config, providerName)` - Create provider instance (resolves the provider `type` through the registry)
|
|
54
|
-
- `registerStorageProvider(type, factory)` - Register a provider `type` → constructor (host opts in to optional/custom providers)
|
|
55
|
-
- `getStorageProviderFactory(type)` / `hasStorageProvider(type)` - Inspect the registry
|
|
56
|
-
- `resetStorageProviderRegistry()` - Reset to built-in defaults (mainly for tests)
|
|
57
|
-
|
|
58
|
-
### Utils (`src/utils/`)
|
|
59
|
-
|
|
60
|
-
- `validateFile(file, options)` - Validate file size, MIME type, extensions
|
|
61
|
-
- `formatFileSize(bytes)` - Human-readable file sizes
|
|
62
|
-
- `getMimeType(filename)` - Get MIME type from filename
|
|
63
|
-
- `parseFileFromFormData(formData, fieldName)` - Extract file from FormData
|
|
64
|
-
- `getImageDimensions(buffer)` - Get image width/height
|
|
65
|
-
- `transformImage(buffer, config)` - Apply single transformation
|
|
66
|
-
- `processImageTransformations(buffer, filename, transformations, provider, contentType)` - Process all transformations
|
|
67
|
-
|
|
68
|
-
## Architecture Patterns
|
|
69
|
-
|
|
70
|
-
### Field Self-Containment
|
|
71
|
-
|
|
72
|
-
File and image fields follow the self-contained field pattern:
|
|
73
|
-
|
|
74
|
-
```typescript
|
|
75
|
-
export function file(options): FileFieldConfig {
|
|
76
|
-
return {
|
|
77
|
-
type: 'file',
|
|
78
|
-
...options,
|
|
79
|
-
getZodSchema: () => z.object({ filename: z.string(), url: z.string().url(), ... }).nullable(),
|
|
80
|
-
getPrismaType: () => ({ type: 'Json', modifiers: '?' }),
|
|
81
|
-
getTypeScriptType: () => ({ type: 'import("@opensaas/stack-storage").FileMetadata | null', optional: true }),
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
No changes to core generators - fields define their own Prisma/TS types.
|
|
87
|
-
|
|
88
|
-
### Storage Provider Interface
|
|
89
|
-
|
|
90
|
-
All storage backends implement `StorageProvider`:
|
|
91
|
-
|
|
92
|
-
```typescript
|
|
93
|
-
interface StorageProvider {
|
|
94
|
-
upload(
|
|
95
|
-
file: Buffer | Uint8Array,
|
|
96
|
-
filename: string,
|
|
97
|
-
options?: UploadOptions,
|
|
98
|
-
): Promise<UploadResult>
|
|
99
|
-
download(filename: string): Promise<Buffer>
|
|
100
|
-
delete(filename: string): Promise<void>
|
|
101
|
-
getUrl(filename: string): string
|
|
102
|
-
getSignedUrl?(filename: string, expiresIn?: number): Promise<string> // Optional
|
|
103
|
-
}
|
|
104
|
-
```
|
|
105
|
-
|
|
106
|
-
### Config-Level Storage
|
|
107
|
-
|
|
108
|
-
Storage config is added to `OpenSaasConfig` (similar to auth pattern):
|
|
109
|
-
|
|
110
|
-
```typescript
|
|
111
|
-
export type OpenSaasConfig = {
|
|
112
|
-
db: DatabaseConfig
|
|
113
|
-
lists: Record<string, ListConfig>
|
|
114
|
-
storage?: StorageConfig // Maps names to provider configs
|
|
115
|
-
// ...
|
|
116
|
-
}
|
|
117
|
-
```
|
|
118
|
-
|
|
119
|
-
### Named Storage Providers
|
|
120
|
-
|
|
121
|
-
Multiple storage providers can be configured:
|
|
122
|
-
|
|
123
|
-
```typescript
|
|
124
|
-
storage: {
|
|
125
|
-
avatars: s3Storage({ bucket: 'avatars', region: 'us-east-1' }),
|
|
126
|
-
documents: localStorage({ uploadDir: './uploads', serveUrl: '/api/files' }),
|
|
127
|
-
videos: vercelBlobStorage({ token: process.env.BLOB_TOKEN }),
|
|
128
|
-
}
|
|
129
|
-
```
|
|
130
|
-
|
|
131
|
-
Fields reference providers by name:
|
|
132
|
-
|
|
133
|
-
```typescript
|
|
134
|
-
avatar: image({ storage: 'avatars' }),
|
|
135
|
-
resume: file({ storage: 'documents' }),
|
|
136
|
-
```
|
|
137
|
-
|
|
138
|
-
### JSON Metadata Storage
|
|
139
|
-
|
|
140
|
-
Files and images store metadata as JSON (leveraging existing `json` field type):
|
|
141
|
-
|
|
142
|
-
**Prisma schema:**
|
|
143
|
-
|
|
144
|
-
```prisma
|
|
145
|
-
model User {
|
|
146
|
-
avatar Json? // ImageMetadata
|
|
147
|
-
resume Json? // FileMetadata
|
|
148
|
-
}
|
|
149
|
-
```
|
|
150
|
-
|
|
151
|
-
**Runtime types:**
|
|
152
|
-
|
|
153
|
-
```typescript
|
|
154
|
-
user.avatar // ImageMetadata | null
|
|
155
|
-
user.resume // FileMetadata | null
|
|
156
|
-
```
|
|
157
|
-
|
|
158
|
-
### Automatic Upload via Field Hooks
|
|
159
|
-
|
|
160
|
-
Files are uploaded automatically during form submission via `resolveInput` hooks. **No custom upload API routes are needed.**
|
|
161
|
-
|
|
162
|
-
**How it works:**
|
|
163
|
-
|
|
164
|
-
1. User selects file in UI component
|
|
165
|
-
2. File object stored in form state
|
|
166
|
-
3. Form submitted with File object
|
|
167
|
-
4. Field's `resolveInput` hook uploads file server-side
|
|
168
|
-
5. Returns FileMetadata for database storage
|
|
169
|
-
|
|
170
|
-
**This provides:**
|
|
171
|
-
|
|
172
|
-
1. **Atomic uploads** - files only saved if form submission succeeds
|
|
173
|
-
2. **No orphaned files** - failed submissions don't leave files in storage
|
|
174
|
-
3. **Automatic security** - uploads happen server-side with access control
|
|
175
|
-
4. **Simpler code** - no custom upload routes needed
|
|
176
|
-
|
|
177
|
-
### Image Transformation Pipeline
|
|
178
|
-
|
|
179
|
-
1. Validate file (size, MIME type)
|
|
180
|
-
2. Upload original image to storage
|
|
181
|
-
3. For each transformation:
|
|
182
|
-
- Apply transformation with sharp
|
|
183
|
-
- Upload transformed image
|
|
184
|
-
- Return transformation metadata
|
|
185
|
-
4. Return ImageMetadata with all URLs
|
|
186
|
-
|
|
187
|
-
**Transformations stored with original:**
|
|
188
|
-
|
|
189
|
-
```typescript
|
|
190
|
-
{
|
|
191
|
-
url: "https://bucket.s3.amazonaws.com/original.jpg",
|
|
192
|
-
transformations: {
|
|
193
|
-
thumbnail: { url: "https://bucket.s3.amazonaws.com/original-thumbnail.jpg", width: 100, height: 100 },
|
|
194
|
-
large: { url: "https://bucket.s3.amazonaws.com/original-large.jpg", width: 1200, height: 1200 }
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
```
|
|
198
|
-
|
|
199
|
-
### UI Component Integration
|
|
200
|
-
|
|
201
|
-
File/image fields work in admin UI via component registry:
|
|
202
|
-
|
|
203
|
-
```typescript
|
|
204
|
-
// packages/ui/src/components/fields/registry.ts
|
|
205
|
-
export const fieldComponentRegistry = {
|
|
206
|
-
file: FileField,
|
|
207
|
-
image: ImageField,
|
|
208
|
-
// ...
|
|
209
|
-
}
|
|
210
|
-
```
|
|
211
|
-
|
|
212
|
-
Components accept `File | FileMetadata | null` as values:
|
|
213
|
-
|
|
214
|
-
- New uploads: File object stored in form state
|
|
215
|
-
- Existing files: FileMetadata from database
|
|
216
|
-
- Deleted files: null
|
|
217
|
-
|
|
218
|
-
## Integration Points
|
|
219
|
-
|
|
220
|
-
### With @opensaas/stack-core
|
|
221
|
-
|
|
222
|
-
- `StorageConfig` added to `OpenSaasConfig` type
|
|
223
|
-
- Field builders use `BaseFieldConfig` interface
|
|
224
|
-
- Generators delegate to field methods (no core changes)
|
|
225
|
-
|
|
226
|
-
### With @opensaas/stack-ui
|
|
227
|
-
|
|
228
|
-
- `FileField` component with drag-and-drop
|
|
229
|
-
- `ImageField` component with preview
|
|
230
|
-
- Registered in field component registry
|
|
231
|
-
- Components require `onUpload` prop (developer implements)
|
|
232
|
-
|
|
233
|
-
### With @opensaas/stack-storage-s3
|
|
234
|
-
|
|
235
|
-
- S3StorageProvider implements `StorageProvider`
|
|
236
|
-
- Supports AWS S3 and S3-compatible services (MinIO, Backblaze, etc.)
|
|
237
|
-
- Optional signed URLs for private files
|
|
238
|
-
|
|
239
|
-
### With @opensaas/stack-storage-vercel
|
|
240
|
-
|
|
241
|
-
- VercelBlobStorageProvider implements `StorageProvider`
|
|
242
|
-
- Uses `@vercel/blob` package
|
|
243
|
-
- Optimized for Vercel deployments
|
|
244
|
-
|
|
245
|
-
## Common Patterns
|
|
246
|
-
|
|
247
|
-
### Basic Config
|
|
248
|
-
|
|
249
|
-
```typescript
|
|
250
|
-
import { config, list } from '@opensaas/stack-core'
|
|
251
|
-
import { localStorage } from '@opensaas/stack-storage'
|
|
252
|
-
import { file, image } from '@opensaas/stack-storage/fields'
|
|
253
|
-
|
|
254
|
-
export default config({
|
|
255
|
-
storage: {
|
|
256
|
-
files: localStorage({
|
|
257
|
-
uploadDir: './public/uploads',
|
|
258
|
-
serveUrl: '/uploads',
|
|
259
|
-
}),
|
|
260
|
-
},
|
|
261
|
-
lists: {
|
|
262
|
-
Post: list({
|
|
263
|
-
fields: {
|
|
264
|
-
coverImage: image({
|
|
265
|
-
storage: 'files',
|
|
266
|
-
transformations: {
|
|
267
|
-
thumbnail: { width: 300, height: 200, fit: 'cover' },
|
|
268
|
-
},
|
|
269
|
-
}),
|
|
270
|
-
},
|
|
271
|
-
}),
|
|
272
|
-
},
|
|
273
|
-
})
|
|
274
|
-
```
|
|
275
|
-
|
|
276
|
-
### Multiple Storage Providers
|
|
277
|
-
|
|
278
|
-
```typescript
|
|
279
|
-
storage: {
|
|
280
|
-
avatars: s3Storage({
|
|
281
|
-
bucket: 'user-avatars',
|
|
282
|
-
region: 'us-east-1',
|
|
283
|
-
acl: 'public-read',
|
|
284
|
-
}),
|
|
285
|
-
documents: localStorage({
|
|
286
|
-
uploadDir: './private/documents',
|
|
287
|
-
serveUrl: '/api/files', // Served through auth-protected route
|
|
288
|
-
}),
|
|
289
|
-
}
|
|
290
|
-
```
|
|
291
|
-
|
|
292
|
-
### Automatic File Cleanup
|
|
293
|
-
|
|
294
|
-
Enable automatic cleanup of files when records are deleted or files are replaced:
|
|
295
|
-
|
|
296
|
-
```typescript
|
|
297
|
-
User: list({
|
|
298
|
-
fields: {
|
|
299
|
-
avatar: image({
|
|
300
|
-
storage: 'avatars',
|
|
301
|
-
cleanupOnDelete: true, // Delete avatar when user deleted
|
|
302
|
-
cleanupOnReplace: true, // Delete old avatar when new one uploaded
|
|
303
|
-
transformations: {
|
|
304
|
-
thumbnail: { width: 100, height: 100 },
|
|
305
|
-
},
|
|
306
|
-
}),
|
|
307
|
-
},
|
|
308
|
-
}),
|
|
309
|
-
```
|
|
310
|
-
|
|
311
|
-
### Serving Private Files
|
|
312
|
-
|
|
313
|
-
```typescript
|
|
314
|
-
// app/api/files/[filename]/route.ts
|
|
315
|
-
import { createStorageProvider } from '@opensaas/stack-storage/runtime'
|
|
316
|
-
import config from '@/opensaas.config'
|
|
317
|
-
|
|
318
|
-
export async function GET(request: NextRequest, { params }: { params: { filename: string } }) {
|
|
319
|
-
const session = await getSession()
|
|
320
|
-
if (!session) {
|
|
321
|
-
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
// Get storage provider
|
|
325
|
-
const provider = createStorageProvider(config, 'documents')
|
|
326
|
-
|
|
327
|
-
// Download file
|
|
328
|
-
const buffer = await provider.download(params.filename)
|
|
329
|
-
|
|
330
|
-
// Return file
|
|
331
|
-
return new NextResponse(buffer, {
|
|
332
|
-
headers: {
|
|
333
|
-
'Content-Type': 'application/octet-stream',
|
|
334
|
-
'Content-Disposition': `attachment; filename="${params.filename}"`,
|
|
335
|
-
},
|
|
336
|
-
})
|
|
337
|
-
}
|
|
338
|
-
```
|
|
339
|
-
|
|
340
|
-
### Image Transformations
|
|
341
|
-
|
|
342
|
-
```typescript
|
|
343
|
-
avatar: image({
|
|
344
|
-
storage: 'avatars',
|
|
345
|
-
transformations: {
|
|
346
|
-
thumbnail: { width: 100, height: 100, fit: 'cover', format: 'webp', quality: 80 },
|
|
347
|
-
small: { width: 200, height: 200, fit: 'cover', format: 'webp' },
|
|
348
|
-
medium: { width: 400, height: 400, fit: 'cover', format: 'webp' },
|
|
349
|
-
large: { width: 800, height: 800, fit: 'inside', format: 'jpeg', quality: 90 },
|
|
350
|
-
},
|
|
351
|
-
validation: {
|
|
352
|
-
maxFileSize: 10 * 1024 * 1024,
|
|
353
|
-
acceptedMimeTypes: ['image/jpeg', 'image/png', 'image/webp'],
|
|
354
|
-
},
|
|
355
|
-
})
|
|
356
|
-
```
|
|
357
|
-
|
|
358
|
-
### Storage Provider Registry
|
|
359
|
-
|
|
360
|
-
`createStorageProvider` resolves a provider `type` through a **registry** rather
|
|
361
|
-
than a hardcoded `switch`. `'local'` is registered as a built-in default, so it
|
|
362
|
-
works with no setup. Every other provider — the optional packages
|
|
363
|
-
(`@opensaas/stack-storage-s3`, `@opensaas/stack-storage-vercel`) and your own
|
|
364
|
-
custom providers — must be **registered by the host** before
|
|
365
|
-
`createStorageProvider` can build them.
|
|
366
|
-
|
|
367
|
-
`@opensaas/stack-storage` deliberately does **not** depend on `-s3`/`-vercel`:
|
|
368
|
-
wiring them into the factory directly would force the AWS/Vercel SDKs onto every
|
|
369
|
-
storage user. The host opts in by registering only the provider(s) it uses.
|
|
370
|
-
|
|
371
|
-
#### Registering an optional provider package
|
|
372
|
-
|
|
373
|
-
Register once at app startup (e.g. in a server-only module imported by your app
|
|
374
|
-
entry, the upload route, or `instrumentation.ts`):
|
|
375
|
-
|
|
376
|
-
```typescript
|
|
377
|
-
// lib/register-storage.ts (server-only)
|
|
378
|
-
import { registerStorageProvider } from '@opensaas/stack-storage/runtime'
|
|
379
|
-
import { S3StorageProvider, type S3StorageConfig } from '@opensaas/stack-storage-s3'
|
|
380
|
-
|
|
381
|
-
registerStorageProvider<S3StorageConfig>('s3', (config) => new S3StorageProvider(config))
|
|
382
|
-
```
|
|
383
|
-
|
|
384
|
-
Then reference the provider by `type` in config (via the package's config
|
|
385
|
-
builder, which sets `type: 's3'`):
|
|
386
|
-
|
|
387
|
-
```typescript
|
|
388
|
-
import { s3Storage } from '@opensaas/stack-storage-s3'
|
|
389
|
-
|
|
390
|
-
export default config({
|
|
391
|
-
storage: {
|
|
392
|
-
avatars: s3Storage({ bucket: 'user-avatars', region: 'us-east-1' }),
|
|
393
|
-
},
|
|
394
|
-
// ...
|
|
395
|
-
})
|
|
396
|
-
```
|
|
397
|
-
|
|
398
|
-
The Vercel Blob provider follows the same shape:
|
|
399
|
-
|
|
400
|
-
```typescript
|
|
401
|
-
import { registerStorageProvider } from '@opensaas/stack-storage/runtime'
|
|
402
|
-
import {
|
|
403
|
-
VercelBlobStorageProvider,
|
|
404
|
-
type VercelBlobStorageConfig,
|
|
405
|
-
} from '@opensaas/stack-storage-vercel'
|
|
406
|
-
|
|
407
|
-
registerStorageProvider<VercelBlobStorageConfig>(
|
|
408
|
-
'vercel-blob',
|
|
409
|
-
(config) => new VercelBlobStorageProvider(config),
|
|
410
|
-
)
|
|
411
|
-
```
|
|
412
|
-
|
|
413
|
-
#### Registering a custom provider
|
|
414
|
-
|
|
415
|
-
Implement `StorageProvider`, give it a `type` discriminator, then register it:
|
|
416
|
-
|
|
417
|
-
```typescript
|
|
418
|
-
// lib/cloudflare-r2-storage.ts
|
|
419
|
-
import type {
|
|
420
|
-
StorageProvider,
|
|
421
|
-
UploadOptions,
|
|
422
|
-
UploadResult,
|
|
423
|
-
BaseStorageConfig,
|
|
424
|
-
} from '@opensaas/stack-storage'
|
|
425
|
-
|
|
426
|
-
export interface CloudflareR2Config extends BaseStorageConfig {
|
|
427
|
-
type: 'cloudflare-r2'
|
|
428
|
-
bucket: string
|
|
429
|
-
accountId: string
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
export class CloudflareR2StorageProvider implements StorageProvider {
|
|
433
|
-
constructor(private config: CloudflareR2Config) {}
|
|
434
|
-
|
|
435
|
-
async upload(
|
|
436
|
-
file: Buffer | Uint8Array,
|
|
437
|
-
filename: string,
|
|
438
|
-
options?: UploadOptions,
|
|
439
|
-
): Promise<UploadResult> {
|
|
440
|
-
// Upload to Cloudflare R2 ...
|
|
441
|
-
return {
|
|
442
|
-
filename,
|
|
443
|
-
url: this.getUrl(filename),
|
|
444
|
-
size: file.length,
|
|
445
|
-
contentType: options?.contentType ?? 'application/octet-stream',
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
async download(filename: string): Promise<Buffer> {
|
|
450
|
-
// Download from R2 ...
|
|
451
|
-
return Buffer.from('')
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
async delete(filename: string): Promise<void> {
|
|
455
|
-
// Delete from R2 ...
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
getUrl(filename: string): string {
|
|
459
|
-
return `https://r2.example.com/${this.config.bucket}/${filename}`
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
```
|
|
463
|
-
|
|
464
|
-
```typescript
|
|
465
|
-
// lib/register-storage.ts (server-only)
|
|
466
|
-
import { registerStorageProvider } from '@opensaas/stack-storage/runtime'
|
|
467
|
-
import { CloudflareR2StorageProvider, type CloudflareR2Config } from './cloudflare-r2-storage'
|
|
468
|
-
|
|
469
|
-
registerStorageProvider<CloudflareR2Config>(
|
|
470
|
-
'cloudflare-r2',
|
|
471
|
-
(config) => new CloudflareR2StorageProvider(config),
|
|
472
|
-
)
|
|
473
|
-
```
|
|
474
|
-
|
|
475
|
-
```typescript
|
|
476
|
-
// opensaas.config.ts
|
|
477
|
-
export default config({
|
|
478
|
-
storage: {
|
|
479
|
-
media: { type: 'cloudflare-r2', bucket: 'media', accountId: process.env.CF_ACCOUNT_ID! },
|
|
480
|
-
},
|
|
481
|
-
// ...
|
|
482
|
-
})
|
|
483
|
-
```
|
|
484
|
-
|
|
485
|
-
If a field references a provider whose `type` has not been registered,
|
|
486
|
-
`createStorageProvider` throws a clear error
|
|
487
|
-
(`Unknown storage provider type: <type>. Register it with registerStorageProvider(...)`).
|
|
488
|
-
Reads are unaffected — assembling existing asset metadata only stamps the
|
|
489
|
-
provider **name** and never constructs a provider.
|
|
490
|
-
|
|
491
|
-
## Type Safety
|
|
492
|
-
|
|
493
|
-
All types are strongly typed:
|
|
494
|
-
|
|
495
|
-
- `FileMetadata` and `ImageMetadata` for database storage
|
|
496
|
-
- `StorageProvider` interface for custom providers
|
|
497
|
-
- Field configs fully typed with TypeScript
|
|
498
|
-
- Validation options typed with Zod
|
|
499
|
-
|
|
500
|
-
Avoid `any` - all internal utilities use proper types.
|
|
501
|
-
|
|
502
|
-
## Performance Considerations
|
|
503
|
-
|
|
504
|
-
- **Image transformations** happen during upload (one-time cost)
|
|
505
|
-
- **Sharp** is fast but CPU-intensive (consider background jobs for large images)
|
|
506
|
-
- **Separate provider packages** reduce bundle size (only install what you use)
|
|
507
|
-
- **JSON storage** is efficient for metadata (no additional tables)
|
|
508
|
-
- **CDN integration** via custom domains or CloudFront
|
|
509
|
-
|
|
510
|
-
## Security
|
|
511
|
-
|
|
512
|
-
- **Developer-controlled routes** allow custom auth/validation
|
|
513
|
-
- **MIME type validation** prevents file type spoofing
|
|
514
|
-
- **File size limits** prevent DoS attacks
|
|
515
|
-
- **Access control** enforced in upload routes
|
|
516
|
-
- **Signed URLs** for private S3 files (optional)
|
|
517
|
-
- **No direct file access** unless served through developer routes
|
|
518
|
-
|
|
519
|
-
## Future Enhancements
|
|
520
|
-
|
|
521
|
-
Potential additions:
|
|
522
|
-
|
|
523
|
-
- Background job support for large image processing
|
|
524
|
-
- Video/audio field types
|
|
525
|
-
- CDN invalidation hooks
|
|
526
|
-
- Image optimization (compression, format conversion)
|
|
527
|
-
- Cloud provider integrations (Azure Blob, Google Cloud Storage)
|
|
528
|
-
- File virus scanning integration
|
package/src/config/index.ts
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import type { LocalStorageConfig } from './types.js'
|
|
2
|
-
|
|
3
|
-
export * from './types.js'
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Creates a local filesystem storage configuration
|
|
7
|
-
*
|
|
8
|
-
* @example
|
|
9
|
-
* ```typescript
|
|
10
|
-
* const config = config({
|
|
11
|
-
* storage: {
|
|
12
|
-
* documents: localStorage({
|
|
13
|
-
* uploadDir: './uploads/documents',
|
|
14
|
-
* serveUrl: '/api/files',
|
|
15
|
-
* }),
|
|
16
|
-
* },
|
|
17
|
-
* })
|
|
18
|
-
* ```
|
|
19
|
-
*/
|
|
20
|
-
export function localStorage(
|
|
21
|
-
config: Pick<LocalStorageConfig, 'uploadDir' | 'serveUrl'> &
|
|
22
|
-
Partial<Pick<LocalStorageConfig, 'generateUniqueFilenames'>>,
|
|
23
|
-
): LocalStorageConfig {
|
|
24
|
-
return {
|
|
25
|
-
type: 'local',
|
|
26
|
-
uploadDir: config.uploadDir,
|
|
27
|
-
serveUrl: config.serveUrl,
|
|
28
|
-
generateUniqueFilenames: config.generateUniqueFilenames ?? true,
|
|
29
|
-
}
|
|
30
|
-
}
|
package/src/config/types.ts
DELETED
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Storage provider interface that all storage backends must implement.
|
|
3
|
-
* This allows pluggable storage solutions (local, S3, Vercel Blob, etc.)
|
|
4
|
-
*/
|
|
5
|
-
export interface StorageProvider {
|
|
6
|
-
/** Uploads a file. `filename` may be transformed by the provider (e.g. to guarantee uniqueness). */
|
|
7
|
-
upload(
|
|
8
|
-
file: Buffer | Uint8Array,
|
|
9
|
-
filename: string,
|
|
10
|
-
options?: UploadOptions,
|
|
11
|
-
): Promise<UploadResult>
|
|
12
|
-
|
|
13
|
-
download(filename: string): Promise<Buffer>
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Deletes a file from the storage provider.
|
|
17
|
-
*
|
|
18
|
-
* Idempotent: deleting a filename that doesn't exist in the backing store
|
|
19
|
-
* resolves without error. Only non-not-found errors (permissions, network,
|
|
20
|
-
* etc.) should reject.
|
|
21
|
-
*/
|
|
22
|
-
delete(filename: string): Promise<void>
|
|
23
|
-
|
|
24
|
-
getUrl(filename: string): string
|
|
25
|
-
|
|
26
|
-
/** Gets a signed URL for private files. */
|
|
27
|
-
getSignedUrl?(filename: string, expiresIn?: number): Promise<string>
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export interface UploadOptions {
|
|
31
|
-
/** MIME type of the file */
|
|
32
|
-
contentType?: string
|
|
33
|
-
/** Custom metadata to store with the file */
|
|
34
|
-
metadata?: Record<string, string>
|
|
35
|
-
/** Whether the file should be publicly accessible */
|
|
36
|
-
public?: boolean
|
|
37
|
-
/** Cache control header */
|
|
38
|
-
cacheControl?: string
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export interface UploadResult {
|
|
42
|
-
/** Generated filename (may differ from input) */
|
|
43
|
-
filename: string
|
|
44
|
-
/** Public URL to access the file */
|
|
45
|
-
url: string
|
|
46
|
-
/** File size in bytes */
|
|
47
|
-
size: number
|
|
48
|
-
/** MIME type */
|
|
49
|
-
contentType: string
|
|
50
|
-
/** Additional provider-specific metadata */
|
|
51
|
-
metadata?: Record<string, unknown>
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export interface LocalStorageConfig {
|
|
55
|
-
type: 'local'
|
|
56
|
-
/** Directory to store uploaded files */
|
|
57
|
-
uploadDir: string
|
|
58
|
-
/** Base URL for serving files (e.g., '/api/files' or 'https://cdn.example.com') */
|
|
59
|
-
serveUrl: string
|
|
60
|
-
/** Whether to generate unique filenames (default: true) */
|
|
61
|
-
generateUniqueFilenames?: boolean
|
|
62
|
-
/** Allow additional properties */
|
|
63
|
-
[key: string]: unknown
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export interface BaseStorageConfig {
|
|
67
|
-
type: string
|
|
68
|
-
[key: string]: unknown
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** Maps names to storage provider configs, e.g. `{ avatars: s3Config, documents: localConfig }`. */
|
|
72
|
-
export type StorageConfig = Record<string, BaseStorageConfig | LocalStorageConfig>
|
|
73
|
-
|
|
74
|
-
// Defined in @opensaas/stack-core, not here, to avoid circular dependencies.
|
|
75
|
-
export type {
|
|
76
|
-
FileMetadata,
|
|
77
|
-
ImageMetadata,
|
|
78
|
-
ImageTransformationResult,
|
|
79
|
-
} from '@opensaas/stack-core/internal'
|
|
80
|
-
|
|
81
|
-
export interface ImageTransformationConfig {
|
|
82
|
-
/** Target width in pixels */
|
|
83
|
-
width?: number
|
|
84
|
-
/** Target height in pixels */
|
|
85
|
-
height?: number
|
|
86
|
-
/** Fit mode: cover (crop), contain (letterbox), fill (stretch) */
|
|
87
|
-
fit?: 'cover' | 'contain' | 'fill' | 'inside' | 'outside'
|
|
88
|
-
/** Output format (default: original format) */
|
|
89
|
-
format?: 'jpeg' | 'png' | 'webp' | 'avif'
|
|
90
|
-
/** Quality 1-100 (default: 80) */
|
|
91
|
-
quality?: number
|
|
92
|
-
}
|