@prunellejs/files 0.0.0-stage → 0.7.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/src/stores.ts ADDED
@@ -0,0 +1,513 @@
1
+ // Storage backends for `@prunellejs/files`: `memoryFiles`, `diskFiles`, and `s3Files` (built on Bun's native S3Client).
2
+
3
+ import type { S3Options } from 'bun'
4
+ import type { FileMetadata, FilePutRecord, FileStore, S3ClientLike, S3FilesOptions, StoredFile } from './types'
5
+ import { randomBytes } from 'node:crypto'
6
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs'
7
+ import { dirname, join, resolve } from 'node:path'
8
+ import { S3Client } from 'bun'
9
+ import { isInside } from 'prunelle/config'
10
+ import { keyMatchesPrefix, normalizeFileKey, normalizeFilePrefix } from './keys'
11
+ import { FilesError } from './types'
12
+
13
+ interface SerializedMeta {
14
+ key: string
15
+ contentType: string
16
+ size: number
17
+ etag: string
18
+ public: boolean
19
+ updatedAt: number
20
+ }
21
+
22
+ function toMeta(record: FileMetadata): FileMetadata {
23
+ return {
24
+ key: record.key,
25
+ contentType: record.contentType,
26
+ size: record.size,
27
+ etag: record.etag,
28
+ public: record.public,
29
+ updatedAt: record.updatedAt,
30
+ }
31
+ }
32
+
33
+ function parseMetaJson(raw: string): FileMetadata | undefined {
34
+ let parsed: unknown
35
+ try {
36
+ parsed = JSON.parse(raw)
37
+ }
38
+ catch {
39
+ return undefined
40
+ }
41
+ if (parsed === null || typeof parsed !== 'object')
42
+ return undefined
43
+ const obj = parsed as Record<string, unknown>
44
+ if (
45
+ typeof obj.key !== 'string'
46
+ || typeof obj.contentType !== 'string'
47
+ || typeof obj.size !== 'number'
48
+ || typeof obj.etag !== 'string'
49
+ || typeof obj.public !== 'boolean'
50
+ || typeof obj.updatedAt !== 'number'
51
+ ) {
52
+ return undefined
53
+ }
54
+ return {
55
+ key: obj.key,
56
+ contentType: obj.contentType,
57
+ size: obj.size,
58
+ etag: obj.etag,
59
+ public: obj.public,
60
+ updatedAt: obj.updatedAt,
61
+ }
62
+ }
63
+
64
+ function isEnoent(error: unknown): boolean {
65
+ if (error === null || typeof error !== 'object')
66
+ return false
67
+ const code = (error as { code?: unknown }).code
68
+ return code === 'ENOENT' || code === 'ENOTDIR'
69
+ }
70
+
71
+ function isS3NotFound(error: unknown): boolean {
72
+ if (error === null || typeof error !== 'object')
73
+ return false
74
+ const rec = error as { code?: unknown, status?: unknown, statusCode?: unknown, name?: unknown }
75
+ return rec.code === 'NoSuchKey'
76
+ || rec.code === 'ERR_S3_NOT_FOUND'
77
+ || rec.name === 'NoSuchKey'
78
+ || rec.status === 404
79
+ || rec.statusCode === 404
80
+ }
81
+
82
+ /** In-memory store for development and tests. Warned/refused in production unless `allowMemoryInProd: true`. */
83
+ export function memoryFiles(): FileStore {
84
+ const entries = new Map<string, StoredFile>()
85
+
86
+ return {
87
+ kind: 'memory',
88
+ put(record: FilePutRecord): void {
89
+ const key = normalizeFileKey(record.key)
90
+ const bytes = new Uint8Array(record.bytes)
91
+ entries.set(key, {
92
+ key,
93
+ bytes,
94
+ contentType: record.contentType,
95
+ size: bytes.byteLength,
96
+ etag: record.etag,
97
+ public: record.public,
98
+ updatedAt: record.updatedAt,
99
+ })
100
+ },
101
+ get(key: string): StoredFile | undefined {
102
+ const norm = normalizeFileKey(key)
103
+ const found = entries.get(norm)
104
+ if (found === undefined)
105
+ return undefined
106
+ return { ...found, bytes: new Uint8Array(found.bytes) }
107
+ },
108
+ stat(key: string): FileMetadata | undefined {
109
+ const norm = normalizeFileKey(key)
110
+ const found = entries.get(norm)
111
+ return found === undefined ? undefined : toMeta(found)
112
+ },
113
+ delete(key: string): boolean {
114
+ return entries.delete(normalizeFileKey(key))
115
+ },
116
+ list(prefix = ''): readonly FileMetadata[] {
117
+ const norm = normalizeFilePrefix(prefix, { allowEmpty: true })
118
+ const out: FileMetadata[] = []
119
+ for (const item of entries.values()) {
120
+ if (keyMatchesPrefix(item.key, norm))
121
+ out.push(toMeta(item))
122
+ }
123
+ out.sort((a, b) => a.key.localeCompare(b.key))
124
+ return out
125
+ },
126
+ deleteWhere(prefix: string): number {
127
+ const norm = normalizeFilePrefix(prefix, { allowEmpty: false })
128
+ let removed = 0
129
+ for (const key of [...entries.keys()]) {
130
+ if (keyMatchesPrefix(key, norm)) {
131
+ entries.delete(key)
132
+ removed++
133
+ }
134
+ }
135
+ return removed
136
+ },
137
+ }
138
+ }
139
+
140
+ function assertNoSymlinkChain(baseDir: string, targetPath: string): void {
141
+ if (!isInside(baseDir, targetPath))
142
+ throw new FilesError('INVALID_KEY', '@prunellejs/files: resolved path escapes storage directory.', 400)
143
+
144
+ if (!existsSync(baseDir))
145
+ return
146
+
147
+ const realBase = realpathSync(baseDir)
148
+ const relParts = targetPath.slice(baseDir.length).replace(/^[/\\]+/, '').split(/[/\\]+/).filter(Boolean)
149
+ let current = baseDir
150
+ for (let i = 0; i < relParts.length; i++) {
151
+ current = join(current, relParts[i]!)
152
+ if (!existsSync(current))
153
+ break
154
+ const stat = lstatSync(current)
155
+ if (stat.isSymbolicLink())
156
+ throw new FilesError('INVALID_KEY', '@prunellejs/files: symlinks are not permitted inside diskFiles storage.', 400)
157
+ const realCurrent = realpathSync(current)
158
+ if (!isInside(realBase, realCurrent, { orSame: true }))
159
+ throw new FilesError('INVALID_KEY', '@prunellejs/files: canonical path escapes storage directory.', 400)
160
+ }
161
+ }
162
+
163
+ function resolveDiskPath(baseDir: string, relKey: string): string {
164
+ const target = resolve(baseDir, relKey)
165
+ assertNoSymlinkChain(baseDir, target)
166
+ return target
167
+ }
168
+
169
+ function writeFileAtomic(targetPath: string, data: Uint8Array | string): void {
170
+ const parent = dirname(targetPath)
171
+ mkdirSync(parent, { recursive: true })
172
+ const tmpPath = join(parent, `.tmp-${randomBytes(8).toString('hex')}`)
173
+ writeFileSync(tmpPath, data)
174
+ try {
175
+ renameSync(tmpPath, targetPath)
176
+ }
177
+ catch (error) {
178
+ try {
179
+ unlinkSync(tmpPath)
180
+ }
181
+ catch (cleanupError) {
182
+ if (!isEnoent(cleanupError))
183
+ throw cleanupError
184
+ }
185
+ throw error
186
+ }
187
+ }
188
+
189
+ function removeFileIfExists(path: string): boolean {
190
+ try {
191
+ unlinkSync(path)
192
+ return true
193
+ }
194
+ catch (error) {
195
+ if (isEnoent(error))
196
+ return false
197
+ throw error
198
+ }
199
+ }
200
+
201
+ function pruneEmptyDirs(startDir: string, stopAt: string): void {
202
+ let current = startDir
203
+ while (isInside(stopAt, current)) {
204
+ try {
205
+ const entries = readdirSync(current)
206
+ if (entries.length > 0)
207
+ break
208
+ rmdirSync(current)
209
+ }
210
+ catch (error) {
211
+ if (isEnoent(error))
212
+ break
213
+ return
214
+ }
215
+ current = dirname(current)
216
+ }
217
+ }
218
+
219
+ function collectDiskMeta(dir: string, realMetaRoot: string, normalizedPrefix: string, out: FileMetadata[]): void {
220
+ let entries
221
+ try {
222
+ entries = readdirSync(dir, { withFileTypes: true })
223
+ }
224
+ catch (error) {
225
+ if (isEnoent(error))
226
+ return
227
+ throw error
228
+ }
229
+
230
+ for (let i = 0; i < entries.length; i++) {
231
+ const entry = entries[i]!
232
+ if (entry.isSymbolicLink() || entry.name.startsWith('.tmp-'))
233
+ continue
234
+ const full = join(dir, entry.name)
235
+ const realFull = realpathSync(full)
236
+ if (!isInside(realMetaRoot, realFull))
237
+ continue
238
+
239
+ if (entry.isDirectory()) {
240
+ collectDiskMeta(full, realMetaRoot, normalizedPrefix, out)
241
+ }
242
+ else if (entry.isFile() && entry.name.endsWith('.json')) {
243
+ const meta = parseMetaJson(readFileSync(full, 'utf8'))
244
+ if (meta !== undefined && keyMatchesPrefix(meta.key, normalizedPrefix))
245
+ out.push(meta)
246
+ }
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Local disk storage under `dir`.
252
+ * Stores objects under `<dir>/objects/<key>` and metadata under `<dir>/meta/<key>.json` so metadata
253
+ * can never collide with or be directly served as an object, and enforces `isInside` + symlink checks on every operation.
254
+ */
255
+ export function diskFiles(dir: string): FileStore {
256
+ if (typeof dir !== 'string' || dir.trim().length === 0)
257
+ throw new FilesError('INVALID_CONFIG', '@prunellejs/files: diskFiles(dir) requires a non-empty directory path.', 500)
258
+
259
+ const rootDir = resolve(dir)
260
+ const objectsDir = join(rootDir, 'objects')
261
+ const metaDir = join(rootDir, 'meta')
262
+
263
+ const readDiskMeta = (normKey: string): FileMetadata | undefined => {
264
+ const metaPath = resolveDiskPath(metaDir, `${normKey}.json`)
265
+ try {
266
+ return parseMetaJson(readFileSync(metaPath, 'utf8'))
267
+ }
268
+ catch (error) {
269
+ if (isEnoent(error))
270
+ return undefined
271
+ throw error
272
+ }
273
+ }
274
+
275
+ const removeOne = (normKey: string): boolean => {
276
+ const objectPath = resolveDiskPath(objectsDir, normKey)
277
+ const metaPath = resolveDiskPath(metaDir, `${normKey}.json`)
278
+ const removedObj = removeFileIfExists(objectPath)
279
+ const removedMeta = removeFileIfExists(metaPath)
280
+ if (removedObj)
281
+ pruneEmptyDirs(dirname(objectPath), objectsDir)
282
+ if (removedMeta)
283
+ pruneEmptyDirs(dirname(metaPath), metaDir)
284
+ return removedObj || removedMeta
285
+ }
286
+
287
+ return {
288
+ kind: 'disk',
289
+ put(record: FilePutRecord): void {
290
+ const key = normalizeFileKey(record.key)
291
+ mkdirSync(objectsDir, { recursive: true })
292
+ mkdirSync(metaDir, { recursive: true })
293
+ const objectPath = resolveDiskPath(objectsDir, key)
294
+ const metaPath = resolveDiskPath(metaDir, `${key}.json`)
295
+
296
+ writeFileAtomic(objectPath, record.bytes)
297
+ const serialized: SerializedMeta = {
298
+ key,
299
+ contentType: record.contentType,
300
+ size: record.bytes.byteLength,
301
+ etag: record.etag,
302
+ public: record.public,
303
+ updatedAt: record.updatedAt,
304
+ }
305
+ writeFileAtomic(metaPath, JSON.stringify(serialized))
306
+ },
307
+ get(key: string): StoredFile | undefined {
308
+ const norm = normalizeFileKey(key)
309
+ const meta = readDiskMeta(norm)
310
+ if (meta === undefined)
311
+ return undefined
312
+ const objectPath = resolveDiskPath(objectsDir, norm)
313
+ try {
314
+ const bytes = new Uint8Array(readFileSync(objectPath))
315
+ return { ...meta, bytes, size: bytes.byteLength }
316
+ }
317
+ catch (error) {
318
+ if (isEnoent(error))
319
+ return undefined
320
+ throw error
321
+ }
322
+ },
323
+ stat(key: string): FileMetadata | undefined {
324
+ const norm = normalizeFileKey(key)
325
+ const meta = readDiskMeta(norm)
326
+ if (meta === undefined)
327
+ return undefined
328
+ const objectPath = resolveDiskPath(objectsDir, norm)
329
+ return existsSync(objectPath) ? meta : undefined
330
+ },
331
+ delete(key: string): boolean {
332
+ return removeOne(normalizeFileKey(key))
333
+ },
334
+ list(prefix = ''): readonly FileMetadata[] {
335
+ const norm = normalizeFilePrefix(prefix, { allowEmpty: true })
336
+ if (!existsSync(metaDir))
337
+ return []
338
+ const realMetaRoot = realpathSync(metaDir)
339
+ const out: FileMetadata[] = []
340
+ collectDiskMeta(metaDir, realMetaRoot, norm, out)
341
+ out.sort((a, b) => a.key.localeCompare(b.key))
342
+ return out
343
+ },
344
+ deleteWhere(prefix: string): number {
345
+ const norm = normalizeFilePrefix(prefix, { allowEmpty: false })
346
+ if (!existsSync(metaDir))
347
+ return 0
348
+ const realMetaRoot = realpathSync(metaDir)
349
+ const matching: FileMetadata[] = []
350
+ collectDiskMeta(metaDir, realMetaRoot, norm, matching)
351
+ let removed = 0
352
+ for (let i = 0; i < matching.length; i++) {
353
+ if (removeOne(matching[i]!.key))
354
+ removed++
355
+ }
356
+ return removed
357
+ },
358
+ }
359
+ }
360
+
361
+ function buildBunS3Options(options: S3FilesOptions): S3Options {
362
+ const s3Opts: S3Options = {}
363
+ if (options.bucket !== undefined)
364
+ s3Opts.bucket = options.bucket
365
+ if (options.region !== undefined)
366
+ s3Opts.region = options.region
367
+ if (options.endpoint !== undefined)
368
+ s3Opts.endpoint = options.endpoint
369
+ if (options.accessKeyId !== undefined)
370
+ s3Opts.accessKeyId = options.accessKeyId
371
+ if (options.secretAccessKey !== undefined)
372
+ s3Opts.secretAccessKey = options.secretAccessKey
373
+ if (options.sessionToken !== undefined)
374
+ s3Opts.sessionToken = options.sessionToken
375
+ return s3Opts
376
+ }
377
+
378
+ /**
379
+ * S3-compatible object storage built directly on Bun's native `S3Client` (zero npm dependencies).
380
+ * Works with AWS S3, Cloudflare R2, MinIO, Scaleway Object Storage, or an injected `client` in tests.
381
+ */
382
+ export function s3Files(options: S3FilesOptions = {}): FileStore {
383
+ const basePrefix = options.prefix !== undefined && options.prefix.length > 0
384
+ ? `${normalizeFilePrefix(options.prefix, { allowEmpty: false })}/`
385
+ : ''
386
+ const client: S3ClientLike = options.client ?? new S3Client(buildBunS3Options(options))
387
+
388
+ const objectKey = (normKey: string): string => `${basePrefix}objects/${normKey}`
389
+ const metaKey = (normKey: string): string => `${basePrefix}meta/${normKey}.json`
390
+
391
+ const readS3Meta = async (normKey: string): Promise<FileMetadata | undefined> => {
392
+ const file = client.file(metaKey(normKey))
393
+ if (!(await file.exists()))
394
+ return undefined
395
+ try {
396
+ return parseMetaJson(await file.text())
397
+ }
398
+ catch (error) {
399
+ if (isS3NotFound(error))
400
+ return undefined
401
+ throw error
402
+ }
403
+ }
404
+
405
+ const listS3Meta = async (normPrefix: string): Promise<FileMetadata[]> => {
406
+ const metaBase = `${basePrefix}meta/`
407
+ const searchPrefix = normPrefix.length > 0 ? `${metaBase}${normPrefix}` : metaBase
408
+ const metaPaths: string[] = []
409
+ let continuationToken: string | undefined
410
+
411
+ for (;;) {
412
+ const input: { prefix?: string, continuationToken?: string } = { prefix: searchPrefix }
413
+ if (continuationToken !== undefined)
414
+ input.continuationToken = continuationToken
415
+ const page = await client.list(input)
416
+ for (const item of page.contents ?? []) {
417
+ if (item.key.endsWith('.json'))
418
+ metaPaths.push(item.key)
419
+ }
420
+ if (page.isTruncated !== true || page.nextContinuationToken === undefined)
421
+ break
422
+ continuationToken = page.nextContinuationToken
423
+ }
424
+
425
+ const out: FileMetadata[] = []
426
+ for (let i = 0; i < metaPaths.length; i++) {
427
+ try {
428
+ const meta = parseMetaJson(await client.file(metaPaths[i]!).text())
429
+ if (meta !== undefined && keyMatchesPrefix(meta.key, normPrefix))
430
+ out.push(meta)
431
+ }
432
+ catch (error) {
433
+ if (!isS3NotFound(error))
434
+ throw error
435
+ }
436
+ }
437
+ out.sort((a, b) => a.key.localeCompare(b.key))
438
+ return out
439
+ }
440
+
441
+ const deleteS3Pair = async (normKey: string): Promise<boolean> => {
442
+ const objPath = objectKey(normKey)
443
+ const mPath = metaKey(normKey)
444
+ const existed = (await client.file(mPath).exists()) || (await client.file(objPath).exists())
445
+ for (const path of [objPath, mPath]) {
446
+ try {
447
+ await client.delete(path)
448
+ }
449
+ catch (error) {
450
+ if (!isS3NotFound(error))
451
+ throw error
452
+ }
453
+ }
454
+ return existed
455
+ }
456
+
457
+ return {
458
+ kind: 's3',
459
+ async put(record: FilePutRecord): Promise<void> {
460
+ const key = normalizeFileKey(record.key)
461
+ await client.file(objectKey(key), { type: record.contentType }).write(record.bytes, { type: record.contentType })
462
+ const serialized: SerializedMeta = {
463
+ key,
464
+ contentType: record.contentType,
465
+ size: record.bytes.byteLength,
466
+ etag: record.etag,
467
+ public: record.public,
468
+ updatedAt: record.updatedAt,
469
+ }
470
+ await client.file(metaKey(key), { type: 'application/json' }).write(JSON.stringify(serialized), { type: 'application/json' })
471
+ },
472
+ async get(key: string): Promise<StoredFile | undefined> {
473
+ const norm = normalizeFileKey(key)
474
+ const meta = await readS3Meta(norm)
475
+ if (meta === undefined)
476
+ return undefined
477
+ const objFile = client.file(objectKey(norm))
478
+ if (!(await objFile.exists()))
479
+ return undefined
480
+ try {
481
+ const bytes = new Uint8Array(await objFile.arrayBuffer())
482
+ return { ...meta, bytes, size: bytes.byteLength }
483
+ }
484
+ catch (error) {
485
+ if (isS3NotFound(error))
486
+ return undefined
487
+ throw error
488
+ }
489
+ },
490
+ async stat(key: string): Promise<FileMetadata | undefined> {
491
+ const norm = normalizeFileKey(key)
492
+ const meta = await readS3Meta(norm)
493
+ if (meta === undefined)
494
+ return undefined
495
+ return (await client.file(objectKey(norm)).exists()) ? meta : undefined
496
+ },
497
+ async delete(key: string): Promise<boolean> {
498
+ return await deleteS3Pair(normalizeFileKey(key))
499
+ },
500
+ async list(prefix = ''): Promise<readonly FileMetadata[]> {
501
+ return await listS3Meta(normalizeFilePrefix(prefix, { allowEmpty: true }))
502
+ },
503
+ async deleteWhere(prefix: string): Promise<number> {
504
+ const items = await listS3Meta(normalizeFilePrefix(prefix, { allowEmpty: false }))
505
+ let removed = 0
506
+ for (let i = 0; i < items.length; i++) {
507
+ if (await deleteS3Pair(items[i]!.key))
508
+ removed++
509
+ }
510
+ return removed
511
+ },
512
+ }
513
+ }
package/src/types.ts ADDED
@@ -0,0 +1,176 @@
1
+ // Public types and error class for `@prunellejs/files`.
2
+
3
+ import type { PrunellePlugin } from 'prunelle/config'
4
+
5
+ export type FilesErrorCode =
6
+ | 'INVALID_KEY'
7
+ | 'EMPTY_FILE'
8
+ | 'FILE_TOO_LARGE'
9
+ | 'DISALLOWED_MIME'
10
+ | 'UNKNOWN_MIME'
11
+ | 'INVALID_TTL'
12
+ | 'INVALID_CONFIG'
13
+ | 'STORE_ERROR'
14
+
15
+ /** Structured error thrown by `@prunellejs/files` with an HTTP-aligned `status` and machine-readable `code`. */
16
+ export class FilesError extends Error {
17
+ readonly code: FilesErrorCode
18
+ readonly status: number
19
+
20
+ constructor(code: FilesErrorCode, message: string, status: number) {
21
+ super(message)
22
+ this.name = 'FilesError'
23
+ this.code = code
24
+ this.status = status
25
+ }
26
+ }
27
+
28
+ export type FileInput = File | Blob | Uint8Array | ArrayBuffer
29
+
30
+ export type TtlInput = number | string
31
+
32
+ export interface FileMetadata {
33
+ readonly key: string
34
+ readonly contentType: string
35
+ readonly size: number
36
+ readonly etag: string
37
+ readonly public: boolean
38
+ readonly updatedAt: number
39
+ }
40
+
41
+ export interface StoredFile extends FileMetadata {
42
+ readonly bytes: Uint8Array
43
+ }
44
+
45
+ export interface FilePutRecord {
46
+ readonly key: string
47
+ readonly bytes: Uint8Array
48
+ readonly contentType: string
49
+ readonly etag: string
50
+ readonly public: boolean
51
+ readonly updatedAt: number
52
+ }
53
+
54
+ export interface FileStore {
55
+ readonly kind?: 'memory' | 'disk' | 's3' | string | undefined
56
+ put(record: FilePutRecord): Promise<void> | void
57
+ get(key: string): Promise<StoredFile | undefined> | StoredFile | undefined
58
+ stat(key: string): Promise<FileMetadata | undefined> | FileMetadata | undefined
59
+ delete(key: string): Promise<boolean> | boolean
60
+ list(prefix?: string): Promise<readonly FileMetadata[]> | readonly FileMetadata[]
61
+ deleteWhere?(prefix: string): Promise<number> | number
62
+ }
63
+
64
+ /** Structural subset of `Bun.S3File` used by `s3Files()` so tests can supply an in-memory mock without network I/O. */
65
+ export interface S3FileLike {
66
+ exists(): Promise<boolean>
67
+ arrayBuffer(): Promise<ArrayBuffer>
68
+ text(): Promise<string>
69
+ write(data: Uint8Array | string, options?: { type?: string }): Promise<number>
70
+ delete(): Promise<void>
71
+ }
72
+
73
+ /** Structural subset of `Bun.S3ListObjectsResponse` used by `s3Files()`. */
74
+ export interface S3ListResultLike {
75
+ contents?: ReadonlyArray<{
76
+ key: string
77
+ size?: number
78
+ eTag?: string
79
+ lastModified?: string
80
+ }> | undefined
81
+ isTruncated?: boolean | undefined
82
+ nextContinuationToken?: string | undefined
83
+ }
84
+
85
+ /** Structural subset of `Bun.S3Client` used by `s3Files()`. */
86
+ export interface S3ClientLike {
87
+ file(path: string, options?: { type?: string }): S3FileLike
88
+ list(input?: {
89
+ prefix?: string
90
+ continuationToken?: string
91
+ maxKeys?: number
92
+ } | null): Promise<S3ListResultLike>
93
+ delete(path: string): Promise<void>
94
+ }
95
+
96
+ export interface S3FilesOptions {
97
+ /** S3 bucket name (falls back to `S3_BUCKET` / `AWS_BUCKET`). */
98
+ bucket?: string | undefined
99
+ /** AWS/S3 region (falls back to `S3_REGION` / `AWS_REGION`). */
100
+ region?: string | undefined
101
+ /** S3-compatible endpoint URL (e.g. Cloudflare R2, MinIO, Scaleway). */
102
+ endpoint?: string | undefined
103
+ /** Access key ID (falls back to `S3_ACCESS_KEY_ID` / `AWS_ACCESS_KEY_ID`). */
104
+ accessKeyId?: string | undefined
105
+ /** Secret access key (falls back to `S3_SECRET_ACCESS_KEY` / `AWS_SECRET_ACCESS_KEY`). */
106
+ secretAccessKey?: string | undefined
107
+ /** Optional temporary session token. */
108
+ sessionToken?: string | undefined
109
+ /** Optional prefix prepended to every object inside the bucket. */
110
+ prefix?: string | undefined
111
+ /** Optional `S3Client` override (defaults to `new Bun.S3Client(...)`). */
112
+ client?: S3ClientLike | undefined
113
+ }
114
+
115
+ export interface PutFileOptions {
116
+ /** Key prefix (e.g. `'avatars/user-42'`). Ignored when `key` is set explicitly. */
117
+ prefix?: string | undefined
118
+ /** Explicit normalized storage key. Generated with a random ID when omitted. */
119
+ key?: string | undefined
120
+ /** Original filename used only to derive a sanitized stem for generated keys; never trusted for MIME detection. */
121
+ filename?: string | undefined
122
+ /** Serve publicly at `files.url(key)` without a signature (defaults to `createFiles({ defaultPublic })`, which is `false`). */
123
+ public?: boolean | undefined
124
+ /** Maximum file size in bytes for this upload. */
125
+ maxSize?: number | undefined
126
+ /** Allowed detected MIME types or wildcards (e.g. `['image/*', 'application/pdf']`). */
127
+ allow?: readonly string[] | undefined
128
+ /** Allow 0-byte uploads (default: `false`). */
129
+ allowEmpty?: boolean | undefined
130
+ }
131
+
132
+ export interface FilesOptions {
133
+ /** Storage backend (`diskFiles(dir)`, `s3Files(opts)`, or `memoryFiles()`). Defaults to `memoryFiles()`. */
134
+ store?: FileStore | undefined
135
+ /** Route prefix where files are served (default: `'/files'`). */
136
+ basePath?: string | undefined
137
+ /** HMAC-SHA256 signing secret for private URLs (defaults to `FILES_SECRET`, then `AUTH_SECRET`, or an ephemeral dev secret). Must be >= 32 UTF-8 bytes in production. */
138
+ secret?: string | undefined
139
+ /** Default maximum file size in bytes (falls back to `PrunelleConfig.maxRequestBodySize`, then 10 MiB). */
140
+ maxSize?: number | undefined
141
+ /** Default allowed detected MIME types or wildcards (default: PNG, JPEG, WebP, GIF, AVIF, PDF). */
142
+ allow?: readonly string[] | undefined
143
+ /** Default visibility when `put()` omits `public` (default: `false`, private by default). */
144
+ defaultPublic?: boolean | undefined
145
+ /** `Cache-Control` header for public files (default: `'public, max-age=31536000, immutable'`). */
146
+ publicCacheControl?: string | undefined
147
+ /** `Cache-Control` header for private / signed URL responses (default: `'private, no-store'`). */
148
+ privateCacheControl?: string | undefined
149
+ /** Allow `memoryFiles()` in `NODE_ENV=production` without failing `requires()` (default: `false`). */
150
+ allowMemoryInProd?: boolean | undefined
151
+ /** Clock function returning milliseconds since epoch (primarily for deterministic tests). */
152
+ now?: (() => number) | undefined
153
+ }
154
+
155
+ export interface Files extends PrunellePlugin {
156
+ readonly store: FileStore
157
+ readonly basePath: string
158
+ /** Validate, sniff real MIME type, and store an uploaded file. Returns its normalized key. */
159
+ put(input: FileInput, options?: PutFileOptions): Promise<string>
160
+ /** Retrieve a stored file and its metadata by key, or `undefined` when missing. */
161
+ get(key: string): Promise<StoredFile | undefined>
162
+ /** Retrieve file metadata without reading bytes, or `undefined` when missing. */
163
+ stat(key: string): Promise<FileMetadata | undefined>
164
+ /** List metadata for all stored files, optionally filtered to a normalized key prefix. */
165
+ list(prefix?: string): Promise<readonly FileMetadata[]>
166
+ /** Delete one file by key (idempotent). Returns `true` if a file was removed. */
167
+ delete(key: string): Promise<boolean>
168
+ /** Delete all files under a non-empty normalized prefix (e.g. `'users/42'` for RGPD erasure). Returns the count deleted. */
169
+ deleteWhere(prefix: string): Promise<number>
170
+ /** Public serving path for `key` (`${basePath}/${encodeKeySegments(key)}`). */
171
+ url(key: string): string
172
+ /** Time-limited HMAC-SHA256 signed URL for a private file (`ttl` in seconds or `'30s'` / `'10m'` / `'1h'` / `'7d'`). */
173
+ signedUrl(key: string, ttl: TtlInput): string
174
+ /** Verify a signed URL's expiry and HMAC signature in constant time. */
175
+ verifySignedUrl(key: string, exp: string | number | null | undefined, sig: string | null | undefined): boolean
176
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.