@nexusts/upload 0.7.2

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/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # @nexusts/upload
2
+
3
+ > **NexusTS** — Bun-native fullstack framework
4
+
5
+ ## Description
6
+
7
+ Multipart file upload with validation.
8
+
9
+ @Upload() / @UploadedFile() decorators. Size limits, MIME validation, count limits. Stores through the configured drive driver.
10
+
11
+ ## Install
12
+
13
+ This module is part of the NexusTS monorepo. Each module is published as its own npm package under the `@nexusts/` scope.
14
+
15
+ Most apps start with just the core:
16
+
17
+ ```bash
18
+ bun add @nexusts/core
19
+ ```
20
+
21
+ Then add this module only if you need it:
22
+
23
+ ```bash
24
+ bun add @nexusts/upload
25
+ ```
26
+
27
+ ## Peer dependencies
28
+
29
+ **None.** No external dependencies. Files are stored through the configured `@nexusts/drive` driver.
30
+
31
+ ## Usage
32
+
33
+ ```typescript
34
+ import { /* public API */ } from "@nexusts/upload";
35
+ ```
36
+
37
+ See the [user guide](../../docs/user-guide/upload.md) and the [example app](../../examples/) for a working demo.
38
+
39
+ ## License
40
+
41
+ MIT — see the root [LICENSE](../../LICENSE).
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Decorator barrel.
3
+ */
4
+ export { Upload } from "./upload.js";
5
+ export { UploadedFile, getUploadedFile, getUploadedFiles } from "./uploaded-file.js";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@Upload('fieldName', opts?)` — declare that a controller method
3
+ * expects one or more uploaded files in `multipart/form-data`.
4
+ *
5
+ * @Post('/avatars')
6
+ * @Upload('avatar')
7
+ * async upload(@UploadedFile('avatar') file: UploadedFile) { ... }
8
+ *
9
+ * @Post('/photos')
10
+ * @Upload('photos', { maxFiles: 10 })
11
+ * async multi(@UploadedFiles('photos') files: UploadedFile[]) { ... }
12
+ */
13
+ import "reflect-metadata";
14
+ import { type UploadOptions } from "../types.js";
15
+ export declare function Upload(name?: string, options?: UploadOptions): MethodDecorator;
@@ -0,0 +1,9 @@
1
+ export declare const UploadedFile: (fieldName?: string) => ParameterDecorator;
2
+ /**
3
+ * Resolve a `@UploadedFile(name)` call against a Hono context. The
4
+ * framework invokes this from its param pipeline. Application
5
+ * code typically does not call this directly — use the decorator.
6
+ */
7
+ export declare function getUploadedFile(c: any, fieldName: string): any;
8
+ /** Resolve a `@UploadedFiles(name)` call. */
9
+ export declare function getUploadedFiles(c: any, fieldName: string): any[];
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Public entry point for `nexusjs/upload`.
3
+ */
4
+ export * from "./types.js";
5
+ export { UploadService } from "./upload.service.js";
6
+ export { UploadModule } from "./upload.module.js";
7
+ export { uploadMiddleware } from "./upload.middleware.js";
8
+ export { Upload, UploadedFile, getUploadedFile, getUploadedFiles } from "./decorators/index.js";
package/dist/index.js ADDED
@@ -0,0 +1,315 @@
1
+ // @bun
2
+ var __legacyDecorateClassTS = function(decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
5
+ r = Reflect.decorate(decorators, target, key, desc);
6
+ else
7
+ for (var i = decorators.length - 1;i >= 0; i--)
8
+ if (d = decorators[i])
9
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
10
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
11
+ };
12
+ var __legacyDecorateParamTS = (index, decorator) => (target, key) => decorator(target, key, index);
13
+ var __legacyMetadataTS = (k, v) => {
14
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
15
+ return Reflect.metadata(k, v);
16
+ };
17
+
18
+ // packages/upload/src/types.ts
19
+ import"reflect-metadata";
20
+ import { METADATA_KEY } from "@nexusts/core";
21
+
22
+ class UploadError extends Error {
23
+ status = 400;
24
+ code;
25
+ field;
26
+ constructor(code, field, message) {
27
+ super(message);
28
+ this.code = code;
29
+ this.field = field;
30
+ this.name = "UploadError";
31
+ }
32
+ }
33
+ var UPLOAD_STORAGE_KEY = "nexus:upload:files";
34
+ var UPLOAD_META = "nexus:upload:options";
35
+ // packages/upload/src/upload.service.ts
36
+ import { Inject, Injectable } from "@nexusts/core";
37
+ class UploadService {
38
+ static TOKEN = Symbol.for("nexus:UploadService");
39
+ #config;
40
+ #driveResolver = null;
41
+ constructor(config = {}) {
42
+ this.#config = {
43
+ maxFileSize: config.maxFileSize ?? 10 * 1024 * 1024,
44
+ maxFiles: config.maxFiles ?? 5,
45
+ allowedMimeTypes: config.allowedMimeTypes ?? ["*"],
46
+ storage: config.storage ?? "memory",
47
+ driveToken: config.driveToken ?? "",
48
+ drivePrefix: config.drivePrefix ?? "",
49
+ preserveFilename: config.preserveFilename ?? false
50
+ };
51
+ }
52
+ bindDriveResolver(fn) {
53
+ this.#driveResolver = fn;
54
+ }
55
+ getConfig() {
56
+ return { ...this.#config };
57
+ }
58
+ async parseAndStore(c, fields) {
59
+ const body = await this.#parseBody(c);
60
+ const stored = {};
61
+ for (const spec of fields) {
62
+ const value = body[spec.fieldName];
63
+ const files = this.#extractFiles(value);
64
+ if (files.length === 0) {
65
+ if (spec.required) {
66
+ throw new UploadError("MISSING_FIELD", spec.fieldName, `Missing required field "${spec.fieldName}".`);
67
+ }
68
+ continue;
69
+ }
70
+ if (files.length > spec.maxFiles) {
71
+ throw new UploadError("TOO_MANY_FILES", spec.fieldName, `Field "${spec.fieldName}" accepts at most ${spec.maxFiles} files (got ${files.length}).`);
72
+ }
73
+ for (const f of files) {
74
+ this.#validate(f, spec.fieldName);
75
+ }
76
+ stored[spec.fieldName] = files.length === 1 ? files[0] : files;
77
+ }
78
+ c.set(UPLOAD_STORAGE_KEY, stored);
79
+ if (this.#config.driveToken && this.#driveResolver) {
80
+ const drive = this.#driveResolver(this.#config.driveToken);
81
+ if (drive?.put) {
82
+ for (const [, entry] of Object.entries(stored)) {
83
+ const list = Array.isArray(entry) ? entry : [entry];
84
+ for (const file of list) {
85
+ const filename = this.#config.preserveFilename ? file.filename : this.#newFilename(file);
86
+ const key = `${this.#config.drivePrefix}/${filename}`;
87
+ await drive.put(key, file.buffer, {
88
+ contentType: file.contentType
89
+ });
90
+ file.storedKey = key;
91
+ }
92
+ }
93
+ }
94
+ }
95
+ }
96
+ get(c, fieldName) {
97
+ const stored = c.get(UPLOAD_STORAGE_KEY);
98
+ if (!stored)
99
+ return;
100
+ const v = stored[fieldName];
101
+ if (Array.isArray(v))
102
+ return v[0];
103
+ return v;
104
+ }
105
+ getAll(c, fieldName) {
106
+ const stored = c.get(UPLOAD_STORAGE_KEY);
107
+ if (!stored)
108
+ return [];
109
+ const v = stored[fieldName];
110
+ if (Array.isArray(v))
111
+ return v;
112
+ if (v)
113
+ return [v];
114
+ return [];
115
+ }
116
+ async#parseBody(c) {
117
+ const req = c.req?.raw ?? c.req;
118
+ const ct = req.headers?.get?.("content-type") ?? "";
119
+ if (!ct.startsWith("multipart/form-data")) {
120
+ return {};
121
+ }
122
+ try {
123
+ return await c.req.parseBody({ all: true });
124
+ } catch (err) {
125
+ throw new UploadError("BAD_MULTIPART", "*", `Failed to parse multipart body: ${err.message}`);
126
+ }
127
+ }
128
+ #extractFiles(value) {
129
+ if (value === undefined || value === null)
130
+ return [];
131
+ const list = Array.isArray(value) ? value : [value];
132
+ const out = [];
133
+ for (const v of list) {
134
+ if (typeof v === "string")
135
+ continue;
136
+ if (typeof v !== "object")
137
+ continue;
138
+ const file = v;
139
+ if (typeof file.arrayBuffer !== "function")
140
+ continue;
141
+ const filename = file.filename ?? file.name ?? "upload";
142
+ const contentType = file.type ?? "application/octet-stream";
143
+ out.push({
144
+ fieldName: file.name,
145
+ filename,
146
+ contentType,
147
+ encoding: "7bit",
148
+ buffer: Buffer.alloc(0),
149
+ size: file.size ?? 0
150
+ });
151
+ }
152
+ return out;
153
+ }
154
+ #validate(file, fieldName) {
155
+ if (file.size > this.#config.maxFileSize) {
156
+ throw new UploadError("FILE_TOO_LARGE", fieldName, `File "${file.filename}" is ${file.size} bytes; max is ${this.#config.maxFileSize}.`);
157
+ }
158
+ if (!this.#mimeAllowed(file.contentType)) {
159
+ throw new UploadError("MIME_NOT_ALLOWED", fieldName, `File "${file.filename}" has type "${file.contentType}"; not in the allow list.`);
160
+ }
161
+ }
162
+ #mimeAllowed(mime) {
163
+ for (const pat of this.#config.allowedMimeTypes) {
164
+ if (pat === "*")
165
+ return true;
166
+ if (pat === mime)
167
+ return true;
168
+ if (pat.endsWith("/*")) {
169
+ const prefix = pat.slice(0, -2);
170
+ if (mime.startsWith(prefix))
171
+ return true;
172
+ }
173
+ }
174
+ return false;
175
+ }
176
+ #newFilename(file) {
177
+ const ext = file.filename.includes(".") ? file.filename.slice(file.filename.lastIndexOf(".")) : "";
178
+ const stamp = Date.now().toString(36);
179
+ const rand = Math.random().toString(36).slice(2, 8);
180
+ return `${stamp}-${rand}${ext}`;
181
+ }
182
+ }
183
+ UploadService = __legacyDecorateClassTS([
184
+ Injectable(),
185
+ __legacyDecorateParamTS(0, Inject("UPLOAD_CONFIG")),
186
+ __legacyMetadataTS("design:paramtypes", [
187
+ typeof UploadConfig === "undefined" ? Object : UploadConfig
188
+ ])
189
+ ], UploadService);
190
+ // packages/upload/src/upload.module.ts
191
+ import"reflect-metadata";
192
+ import { Module } from "@nexusts/core";
193
+
194
+ // packages/upload/src/upload.middleware.ts
195
+ function uploadMiddleware(svc) {
196
+ return async (c, next) => {
197
+ const ct = c.req?.raw?.headers?.get?.("content-type") ?? "";
198
+ if (!ct.startsWith("multipart/form-data"))
199
+ return next();
200
+ const fields = c.get?.("uploadFields") ?? [];
201
+ if (fields.length === 0)
202
+ return next();
203
+ try {
204
+ await svc.parseAndStore(c, fields);
205
+ return next();
206
+ } catch (err) {
207
+ if (err instanceof UploadError) {
208
+ return c.json({ error: err.message, code: err.code, field: err.field }, err.status);
209
+ }
210
+ throw err;
211
+ }
212
+ };
213
+ }
214
+
215
+ // packages/upload/src/upload.module.ts
216
+ class UploadModule {
217
+ static forRoot(config = {}) {
218
+ class ConfiguredUploadModule {
219
+ }
220
+ ConfiguredUploadModule = __legacyDecorateClassTS([
221
+ Module({
222
+ providers: [
223
+ UploadService,
224
+ { provide: UploadService.TOKEN, useExisting: UploadService },
225
+ { provide: "UPLOAD_CONFIG", useValue: config }
226
+ ],
227
+ exports: [UploadService, UploadService.TOKEN]
228
+ })
229
+ ], ConfiguredUploadModule);
230
+ Object.defineProperty(ConfiguredUploadModule, "name", {
231
+ value: "ConfiguredUploadModule"
232
+ });
233
+ return ConfiguredUploadModule;
234
+ }
235
+ static mount(app, svc, routes = []) {
236
+ const fieldSet = new Map;
237
+ for (const r of routes) {
238
+ const metas = Reflect.getMetadata("nexus:upload:options", r.target.constructor, r.propertyKey) ?? [];
239
+ for (const m of metas) {
240
+ const existing = fieldSet.get(m.name);
241
+ const maxFiles = m.options?.maxFiles ?? 1;
242
+ const required = m.options?.required ?? true;
243
+ if (!existing || maxFiles > existing.maxFiles) {
244
+ fieldSet.set(m.name, { maxFiles, required: existing?.required ?? required });
245
+ }
246
+ }
247
+ }
248
+ app.use("/**", async (c, next) => {
249
+ const fields = [];
250
+ for (const [name, info] of fieldSet.entries()) {
251
+ fields.push({ fieldName: name, ...info });
252
+ }
253
+ c.set("uploadFields", fields);
254
+ return uploadMiddleware(svc)(c, next);
255
+ });
256
+ }
257
+ }
258
+ UploadModule = __legacyDecorateClassTS([
259
+ Module({
260
+ providers: [
261
+ UploadService,
262
+ { provide: UploadService.TOKEN, useExisting: UploadService }
263
+ ],
264
+ exports: [UploadService, UploadService.TOKEN]
265
+ })
266
+ ], UploadModule);
267
+ // packages/upload/src/decorators/upload.ts
268
+ import"reflect-metadata";
269
+ var DEFAULT_NAME = "__upload__";
270
+ function Upload(name = DEFAULT_NAME, options = {}) {
271
+ return (target, propertyKey) => {
272
+ const existing = Reflect.getMetadata(UPLOAD_META, target.constructor, propertyKey) ?? [];
273
+ existing.push({ name, options });
274
+ Reflect.defineMetadata(UPLOAD_META, existing, target.constructor, propertyKey);
275
+ };
276
+ }
277
+ // packages/upload/src/decorators/uploaded-file.ts
278
+ import { createParamDecorator } from "@nexusts/core";
279
+ var UploadedFile = (fieldName) => createParamDecorator(128, fieldName);
280
+ function getUploadedFile(c, fieldName) {
281
+ const stored = c.get?.(UPLOAD_STORAGE_KEY) ?? c.var?.[UPLOAD_STORAGE_KEY];
282
+ if (!stored)
283
+ return;
284
+ const v = stored[fieldName];
285
+ if (Array.isArray(v))
286
+ return v[0];
287
+ return v;
288
+ }
289
+ function getUploadedFiles(c, fieldName) {
290
+ const stored = c.get?.(UPLOAD_STORAGE_KEY) ?? c.var?.[UPLOAD_STORAGE_KEY];
291
+ if (!stored)
292
+ return [];
293
+ const v = stored[fieldName];
294
+ if (Array.isArray(v))
295
+ return v;
296
+ if (v)
297
+ return [v];
298
+ return [];
299
+ }
300
+ export {
301
+ uploadMiddleware,
302
+ getUploadedFiles,
303
+ getUploadedFile,
304
+ UploadedFile,
305
+ UploadService,
306
+ UploadModule,
307
+ UploadError,
308
+ Upload,
309
+ UPLOAD_STORAGE_KEY,
310
+ UPLOAD_META,
311
+ METADATA_KEY
312
+ };
313
+
314
+ //# debugId=9217B58E0BF1076D64756E2164756E21
315
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,15 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/types.ts", "../src/upload.service.ts", "../src/upload.module.ts", "../src/upload.middleware.ts", "../src/decorators/upload.ts", "../src/decorators/uploaded-file.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * `nexusjs/upload` — file upload helper.\n *\n * @Module({\n * imports: [\n * UploadModule.forRoot({\n * maxFileSize: 10 * 1024 * 1024, // 10MB per file\n * maxFiles: 5,\n * allowedMimeTypes: ['image/*', 'application/pdf'],\n * storage: 'memory', // or 'drive' (uses nexus/drive)\n * }),\n * ],\n * })\n *\n * @Post('/avatars')\n * @Upload('avatar') // form field name\n * async upload(@UploadedFile('avatar') file: UploadedFile) {\n * return { size: file.size, type: file.contentType };\n * }\n *\n * @Post('/photos')\n * async multi(@UploadedFiles('photos') files: UploadedFile[]) {\n * return files.length;\n * }\n */\n\nimport \"reflect-metadata\";\nimport { METADATA_KEY } from \"@nexusts/core\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * A file that has been parsed from `multipart/form-data`.\n *\n * The framework reads the entire body into memory (with a hard cap\n * enforced by `maxFileSize`) and exposes it as a `Buffer`. For very\n * large files (gigabytes), use a streaming approach instead — the\n * middleware leaves `stream` populated when the file is too large\n * to buffer.\n */\nexport interface UploadedFile {\n\t/** Form field name (e.g. \"avatar\", \"photos\"). */\n\tfieldName: string;\n\t/** Filename from the client (e.g. \"my-photo.png\"). */\n\tfilename: string;\n\t/** MIME type from the client. */\n\tcontentType: string;\n\t/** Encoding (typically '7bit'). */\n\tencoding: string;\n\t/** File content. */\n\tbuffer: Buffer;\n\t/** Convenience: same as `buffer.length`. */\n\tsize: number;\n}\n\n/** Top-level config. */\nexport interface UploadConfig {\n\t/** Max bytes per file. Default: 10 MB. */\n\tmaxFileSize?: number;\n\t/** Max number of files per request. Default: 5. */\n\tmaxFiles?: number;\n\t/**\n\t * Allowed MIME types. Supports `*` wildcards:\n\t * 'image/*' — any image type\n\t * 'application/pdf'\n\t * 'video/mp4'\n\t * Default: '*' (any).\n\t */\n\tallowedMimeTypes?: string[];\n\t/**\n\t * Where parsed files are stored in memory. Default: 'memory'.\n\t * The decorator reads from this storage on each access.\n\t */\n\tstorage?: \"memory\";\n\t/**\n\t * When set, parsed files are also pushed to the configured\n\t * `nexusjs/drive` storage under this prefix. The drive is\n\t * resolved by the DI token string.\n\t */\n\tdriveToken?: string;\n\tdrivePrefix?: string;\n\t/** When using drive storage: keep the original filename. Default: false (UUID). */\n\tpreserveFilename?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Decorator payload\n// ---------------------------------------------------------------------------\n\nexport interface UploadOptions {\n\t/** Form field name. Default: property name. */\n\tname?: string;\n\t/** Per-field max size (overrides the global default). */\n\tmaxSize?: number;\n\t/** Per-field MIME-type filter. */\n\tmimeTypes?: string[];\n\t/** Per-field max files (for multi-file). Default: 1. */\n\tmaxFiles?: number;\n\t/** Whether the field is required. Default: true. */\n\trequired?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Validation errors\n// ---------------------------------------------------------------------------\n\nexport class UploadError extends Error {\n\treadonly status = 400;\n\treadonly code: string;\n\treadonly field: string;\n\tconstructor(code: string, field: string, message: string) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.field = field;\n\t\tthis.name = \"UploadError\";\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Middleware storage key (per-request)\n// ---------------------------------------------------------------------------\n\n/** Key under which the multipart middleware stores parsed files. */\nexport const UPLOAD_STORAGE_KEY = \"nexus:upload:files\";\n\n/** Internal metadata key (decorator). */\nexport const UPLOAD_META = \"nexus:upload:options\";\n\nexport { METADATA_KEY };\n",
6
+ "/**\n * `UploadService` — parses `multipart/form-data` requests and exposes\n * the parsed files to controller methods via decorators.\n *\n * Lifecycle:\n * 1. The framework mounts `uploadMiddleware` (from this module)\n * at the route level.\n * 2. The middleware calls `UploadService.parseAndStore(c, fields)`,\n * which:\n * - reads `c.req.parseBody({ all: true })`\n * - extracts `File` entries from the requested fields\n * - validates each (size, MIME)\n * - stores the result on the Hono context under\n * `UPLOAD_STORAGE_KEY`\n * 3. Decorators (`@UploadedFile`, `@UploadedFiles`) read from the\n * context at parameter-extraction time.\n *\n * The middleware runs **before** the controller handler, so by the\n * time the handler is invoked, all files are already validated.\n */\nimport { Inject, Injectable } from \"@nexusts/core\";\nimport {\n\tUPLOAD_STORAGE_KEY,\n\tUploadError,\n\ttype UploadConfig,\n\ttype UploadedFile,\n} from \"./types.js\";\n\n/** What Hono's `parseBody` returns for file fields. */\ninterface ParsedFileEntry {\n\t/** Original form field name. */\n\tname: string;\n\t/** Web-API File (the multipart payload). */\n\tfilename?: string;\n\ttype?: string;\n\tsize?: number;\n\tarrayBuffer(): Promise<ArrayBuffer>;\n}\n\n/** What Hono's `parseBody` returns overall: string | File | array thereof. */\ntype ParsedBodyValue =\n\t| string\n\t| ParsedFileEntry\n\t| Array<string | ParsedFileEntry>\n\t| undefined;\n\n@Injectable()\nexport class UploadService {\n\t/** DI token. */\n\tstatic readonly TOKEN = Symbol.for(\"nexus:UploadService\");\n\n\t#config: Required<UploadConfig>;\n\t#driveResolver: ((token: string) => any) | null = null;\n\n\tconstructor(@Inject(\"UPLOAD_CONFIG\") config: UploadConfig = {}) {\n\t\tthis.#config = {\n\t\t\tmaxFileSize: config.maxFileSize ?? 10 * 1024 * 1024,\n\t\t\tmaxFiles: config.maxFiles ?? 5,\n\t\t\tallowedMimeTypes: config.allowedMimeTypes ?? [\"*\"],\n\t\t\tstorage: (config.storage as \"memory\") ?? \"memory\",\n\t\t\tdriveToken: config.driveToken ?? \"\",\n\t\t\tdrivePrefix: config.drivePrefix ?? \"\",\n\t\t\tpreserveFilename: config.preserveFilename ?? false,\n\t\t};\n\t}\n\n\t/** Bind a function that resolves a DI token to a service. Set by the module on boot. */\n\tbindDriveResolver(fn: (token: string) => any): void {\n\t\tthis.#driveResolver = fn;\n\t}\n\n\t/** The config this service was constructed with. */\n\tgetConfig(): Required<UploadConfig> {\n\t\treturn { ...this.#config };\n\t}\n\n\t/**\n\t * Parse the request body and store the requested fields on the\n\t * Hono context. Called by `uploadMiddleware`.\n\t */\n\tasync parseAndStore(\n\t\tc: any,\n\t\tfields: Array<{ fieldName: string; maxFiles: number; required: boolean }>,\n\t): Promise<void> {\n\t\tconst body = await this.#parseBody(c);\n\t\tconst stored: Record<string, UploadedFile | UploadedFile[]> = {};\n\n\t\tfor (const spec of fields) {\n\t\t\tconst value = body[spec.fieldName];\n\t\t\tconst files = this.#extractFiles(value);\n\t\t\tif (files.length === 0) {\n\t\t\t\tif (spec.required) {\n\t\t\t\t\tthrow new UploadError(\n\t\t\t\t\t\t\"MISSING_FIELD\",\n\t\t\t\t\t\tspec.fieldName,\n\t\t\t\t\t\t`Missing required field \"${spec.fieldName}\".`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (files.length > spec.maxFiles) {\n\t\t\t\tthrow new UploadError(\n\t\t\t\t\t\"TOO_MANY_FILES\",\n\t\t\t\t\tspec.fieldName,\n\t\t\t\t\t`Field \"${spec.fieldName}\" accepts at most ${spec.maxFiles} files (got ${files.length}).`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tfor (const f of files) {\n\t\t\t\tthis.#validate(f, spec.fieldName);\n\t\t\t}\n\t\t\tstored[spec.fieldName] = files.length === 1 ? files[0]! : files;\n\t\t}\n\n\t\t// Stash on the Hono context so decorators can pull it.\n\t\tc.set(UPLOAD_STORAGE_KEY, stored);\n\n\t\t// Optional: push to drive storage.\n\t\tif (this.#config.driveToken && this.#driveResolver) {\n\t\t\tconst drive = this.#driveResolver(this.#config.driveToken);\n\t\t\tif (drive?.put) {\n\t\t\t\tfor (const [, entry] of Object.entries(stored)) {\n\t\t\t\t\tconst list = Array.isArray(entry) ? entry : [entry];\n\t\t\t\t\tfor (const file of list) {\n\t\t\t\t\t\tconst filename = this.#config.preserveFilename\n\t\t\t\t\t\t\t? file.filename\n\t\t\t\t\t\t\t: this.#newFilename(file);\n\t\t\t\t\t\tconst key = `${this.#config.drivePrefix}/${filename}`;\n\t\t\t\t\t\tawait drive.put(key, file.buffer, {\n\t\t\t\t\t\t\tcontentType: file.contentType,\n\t\t\t\t\t\t});\n\t\t\t\t\t\t(file as UploadedFile & { storedKey?: string }).storedKey = key;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Read a single file from the stored body. Used by `@UploadedFile`.\n\t */\n\tget(c: any, fieldName: string): UploadedFile | undefined {\n\t\tconst stored: Record<string, UploadedFile | UploadedFile[]> | undefined =\n\t\t\tc.get(UPLOAD_STORAGE_KEY);\n\t\tif (!stored) return undefined;\n\t\tconst v = stored[fieldName];\n\t\tif (Array.isArray(v)) return v[0];\n\t\treturn v;\n\t}\n\n\t/**\n\t * Read multiple files from the stored body. Used by `@UploadedFiles`.\n\t */\n\tgetAll(c: any, fieldName: string): UploadedFile[] {\n\t\tconst stored: Record<string, UploadedFile | UploadedFile[]> | undefined =\n\t\t\tc.get(UPLOAD_STORAGE_KEY);\n\t\tif (!stored) return [];\n\t\tconst v = stored[fieldName];\n\t\tif (Array.isArray(v)) return v;\n\t\tif (v) return [v];\n\t\treturn [];\n\t}\n\n\t// ---------------------------------------------------------------------------\n\t// Internal\n\t// ---------------------------------------------------------------------------\n\n\tasync #parseBody(c: any): Promise<Record<string, ParsedBodyValue>> {\n\t\t// Hono's parseBody returns Promise<unknown>. We pass `all: true`\n\t\t// so every field is included, not just the first.\n\t\tconst req = c.req?.raw ?? c.req;\n\t\tconst ct = (req.headers?.get?.(\"content-type\") ?? \"\") as string;\n\t\tif (!ct.startsWith(\"multipart/form-data\")) {\n\t\t\t// Not a multipart request — return empty body. The middleware\n\t\t\t// should skip parsing in this case.\n\t\t\treturn {};\n\t\t}\n\t\ttry {\n\t\t\treturn (await c.req.parseBody({ all: true })) as Record<string, ParsedBodyValue>;\n\t\t} catch (err) {\n\t\t\tthrow new UploadError(\n\t\t\t\t\"BAD_MULTIPART\",\n\t\t\t\t\"*\",\n\t\t\t\t`Failed to parse multipart body: ${(err as Error).message}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t#extractFiles(value: ParsedBodyValue): UploadedFile[] {\n\t\tif (value === undefined || value === null) return [];\n\t\tconst list = Array.isArray(value) ? value : [value];\n\t\tconst out: UploadedFile[] = [];\n\t\tfor (const v of list) {\n\t\t\tif (typeof v === \"string\") continue; // skip plain text fields\n\t\t\tif (typeof v !== \"object\") continue;\n\t\t\tconst file = v as ParsedFileEntry;\n\t\t\tif (typeof file.arrayBuffer !== \"function\") continue;\n\t\t\t// Hono under Bun returns a Blob (not a File) for file fields.\n\t\t\t// The original filename lives in `name` (Blob) or `filename`\n\t\t\t// (File). Accept either.\n\t\t\tconst filename = (file as unknown as { filename?: string }).filename\n\t\t\t\t?? (file as unknown as { name?: string }).name\n\t\t\t\t?? \"upload\";\n\t\t\tconst contentType = file.type ?? \"application/octet-stream\";\n\t\t\tout.push({\n\t\t\t\tfieldName: file.name,\n\t\t\t\tfilename,\n\t\t\t\tcontentType,\n\t\t\t\tencoding: \"7bit\",\n\t\t\t\tbuffer: Buffer.alloc(0), // filled below\n\t\t\t\tsize: file.size ?? 0,\n\t\t\t});\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * After we've extracted the field list, replace each placeholder\n\t * with its real bytes. This is split out so we can do all the\n\t * parsing in parallel.\n\t */\n\t// placeholder for future async hydration.\n\n\t#validate(file: UploadedFile, fieldName: string): void {\n\t\tif (file.size > this.#config.maxFileSize) {\n\t\t\tthrow new UploadError(\n\t\t\t\t\"FILE_TOO_LARGE\",\n\t\t\t\tfieldName,\n\t\t\t\t`File \"${file.filename}\" is ${file.size} bytes; max is ${this.#config.maxFileSize}.`,\n\t\t\t);\n\t\t}\n\t\tif (!this.#mimeAllowed(file.contentType)) {\n\t\t\tthrow new UploadError(\n\t\t\t\t\"MIME_NOT_ALLOWED\",\n\t\t\t\tfieldName,\n\t\t\t\t`File \"${file.filename}\" has type \"${file.contentType}\"; not in the allow list.`,\n\t\t\t);\n\t\t}\n\t}\n\n\t#mimeAllowed(mime: string): boolean {\n\t\tfor (const pat of this.#config.allowedMimeTypes) {\n\t\t\tif (pat === \"*\") return true;\n\t\t\tif (pat === mime) return true;\n\t\t\tif (pat.endsWith(\"/*\")) {\n\t\t\t\tconst prefix = pat.slice(0, -2); // 'image/*' -> 'image/'\n\t\t\t\tif (mime.startsWith(prefix)) return true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t#newFilename(file: UploadedFile): string {\n\t\tconst ext = file.filename.includes(\".\")\n\t\t\t? file.filename.slice(file.filename.lastIndexOf(\".\"))\n\t\t\t: \"\";\n\t\tconst stamp = Date.now().toString(36);\n\t\tconst rand = Math.random().toString(36).slice(2, 8);\n\t\treturn `${stamp}-${rand}${ext}`;\n\t}\n}",
7
+ "/**\n * `UploadModule` — drop-in file upload handling.\n *\n * @Module({\n * imports: [\n * UploadModule.forRoot({\n * maxFileSize: 10 * 1024 * 1024,\n * allowedMimeTypes: ['image/*', 'application/pdf'],\n * storage: 'memory',\n * }),\n * ],\n * })\n *\n * After the framework router is built, call `UploadModule.mount(app, svc)`\n * to install the multipart middleware. The middleware looks at\n * the route's metadata (set by `@Upload('fieldName')`) to know\n * which fields to parse.\n */\nimport \"reflect-metadata\";\nimport { Module } from \"@nexusts/core\";\nimport { UploadService } from \"./upload.service.js\";\nimport type { UploadConfig } from \"./types.js\";\nimport { uploadMiddleware } from \"./upload.middleware.js\";\n\n@Module({\n\tproviders: [\n\t\tUploadService,\n\t\t{ provide: UploadService.TOKEN, useExisting: UploadService },\n\t],\n\texports: [UploadService, UploadService.TOKEN],\n})\nexport class UploadModule {\n\tstatic forRoot(config: UploadConfig = {}) {\n\t\t@Module({\n\t\t\tproviders: [\n\t\t\t\tUploadService,\n\t\t\t\t{ provide: UploadService.TOKEN, useExisting: UploadService },\n\t\t\t\t{ provide: \"UPLOAD_CONFIG\", useValue: config },\n\t\t\t],\n\t\t\texports: [UploadService, UploadService.TOKEN],\n\t\t})\n\t\tclass ConfiguredUploadModule {}\n\t\tObject.defineProperty(ConfiguredUploadModule, \"name\", {\n\t\t\tvalue: \"ConfiguredUploadModule\",\n\t\t});\n\t\treturn ConfiguredUploadModule;\n\t}\n\n\t/**\n\t * Install the multipart middleware on the Hono app. Walk the\n\t * route table, collect every `@Upload` decorator, and emit a\n\t * middleware that knows which fields to parse.\n\t */\n\tstatic mount(app: any, svc: UploadService, routes: any[] = []): void {\n\t\tconst fieldSet = new Map<string, { maxFiles: number; required: boolean }>();\n\t\tfor (const r of routes) {\n\t\t\tconst metas = (Reflect.getMetadata(\"nexus:upload:options\", r.target.constructor, r.propertyKey) ?? []) as Array<{ name: string; options: any }>;\n\t\t\tfor (const m of metas) {\n\t\t\t\tconst existing = fieldSet.get(m.name);\n\t\t\t\tconst maxFiles = m.options?.maxFiles ?? 1;\n\t\t\t\tconst required = m.options?.required ?? true;\n\t\t\t\tif (!existing || maxFiles > existing.maxFiles) {\n\t\t\t\t\tfieldSet.set(m.name, { maxFiles, required: existing?.required ?? required });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Per-route middleware: we capture the fields for that route in\n\t\t// a closure. Hono supports per-route middleware via `app.use(path, mw)`.\n\t\tapp.use(\"/**\", async (c: any, next: () => Promise<any>) => {\n\t\t\tconst fields: Array<{ fieldName: string; maxFiles: number; required: boolean }> = [];\n\t\t\tfor (const [name, info] of fieldSet.entries()) {\n\t\t\t\tfields.push({ fieldName: name, ...info });\n\t\t\t}\n\t\t\tc.set(\"uploadFields\", fields);\n\t\t\treturn uploadMiddleware(svc)(c, next);\n\t\t});\n\t}\n}",
8
+ "/**\n * Hono middleware that parses multipart/form-data and stores the\n * requested fields on the Hono context. Routes that need\n * `@UploadedFile` opt in by:\n *\n * 1. Calling `uploadMiddleware(fieldSpecs)` to register the fields\n * they expect.\n * 2. Or, listing the field names in the `@Upload(...)` decorator\n * metadata, which the `UploadModule` reads to wire up the\n * middleware at boot.\n *\n * For convenience, `UploadModule.mountAll()` walks the route table\n * and installs the middleware on every controller method that has\n * an `@Upload(...)` decorator.\n */\nimport { UploadError } from \"./types.js\";\n\nexport interface FieldSpec {\n\tfieldName: string;\n\tmaxFiles: number;\n\trequired: boolean;\n}\n\n/**\n * Middleware factory. Returns a Hono middleware that:\n * 1. Skips non-multipart requests.\n * 2. Asks the UploadService to parse and store the given fields.\n * 3. On `UploadError`, returns a 400 response with the error code.\n */\nexport function uploadMiddleware(svc: {\n\tparseAndStore(c: any, fields: FieldSpec[]): Promise<void>;\n}) {\n\treturn async (c: any, next: () => Promise<any>) => {\n\t\tconst ct = (c.req?.raw?.headers?.get?.(\"content-type\") ?? \"\") as string;\n\t\tif (!ct.startsWith(\"multipart/form-data\")) return next();\n\t\t// The fields are read off the route at boot. By the time this\n\t\t// middleware runs, `c.var` should have the route spec.\n\t\tconst fields: FieldSpec[] = (c.get?.(\"uploadFields\") as FieldSpec[] | undefined) ?? [];\n\t\tif (fields.length === 0) return next();\n\t\ttry {\n\t\t\tawait svc.parseAndStore(c, fields);\n\t\t\treturn next();\n\t\t} catch (err) {\n\t\t\tif (err instanceof UploadError) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: err.message, code: err.code, field: err.field },\n\t\t\t\t\terr.status as any,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t};\n}\n",
9
+ "/**\n * `@Upload('fieldName', opts?)` — declare that a controller method\n * expects one or more uploaded files in `multipart/form-data`.\n *\n * @Post('/avatars')\n * @Upload('avatar')\n * async upload(@UploadedFile('avatar') file: UploadedFile) { ... }\n *\n * @Post('/photos')\n * @Upload('photos', { maxFiles: 10 })\n * async multi(@UploadedFiles('photos') files: UploadedFile[]) { ... }\n */\nimport \"reflect-metadata\";\nimport { UPLOAD_META, type UploadOptions } from \"../types.js\";\n\n/** Default name when the decorator is applied without arguments. */\nconst DEFAULT_NAME = \"__upload__\";\n\nexport function Upload(name: string = DEFAULT_NAME, options: UploadOptions = {}): MethodDecorator {\n\treturn (target: object, propertyKey: string | symbol) => {\n\t\tconst existing: Array<{ name: string; options: UploadOptions }> =\n\t\t\tReflect.getMetadata(UPLOAD_META, target.constructor, propertyKey) ?? [];\n\t\texisting.push({ name, options });\n\t\tReflect.defineMetadata(UPLOAD_META, existing, target.constructor, propertyKey);\n\t};\n}\n",
10
+ "/**\n * `@UploadedFile('fieldName')` — inject a single uploaded file into\n * the controller method.\n *\n * The framework pulls the parsed file from the Hono context (which\n * the upload middleware populated). If the field is missing and the\n * `@Upload` decorator declared it required, the middleware has\n * already returned a 400 — by the time we run, the file is either\n * present or the request is non-multipart.\n */\nimport { createParamDecorator } from \"@nexusts/core\";\nimport { UPLOAD_STORAGE_KEY } from \"../types.js\";\n\nexport const UploadedFile = (fieldName?: string) =>\n\tcreateParamDecorator(0x80 as any /* USER */, fieldName); // placeholder token\n\n// ---------------------------------------------------------------------\n// The decorator above is a placeholder for the framework's param\n// decorator factory. The actual pull-from-context logic is wired by\n// the framework's param resolver at boot. We re-export a helper\n// that, given a Hono context, returns the file.\n// ---------------------------------------------------------------------\n\n/**\n * Resolve a `@UploadedFile(name)` call against a Hono context. The\n * framework invokes this from its param pipeline. Application\n * code typically does not call this directly — use the decorator.\n */\nexport function getUploadedFile(c: any, fieldName: string) {\n\tconst stored = c.get?.(UPLOAD_STORAGE_KEY) ?? c.var?.[UPLOAD_STORAGE_KEY];\n\tif (!stored) return undefined;\n\tconst v = stored[fieldName];\n\tif (Array.isArray(v)) return v[0];\n\treturn v;\n}\n\n/** Resolve a `@UploadedFiles(name)` call. */\nexport function getUploadedFiles(c: any, fieldName: string) {\n\tconst stored = c.get?.(UPLOAD_STORAGE_KEY) ?? c.var?.[UPLOAD_STORAGE_KEY];\n\tif (!stored) return [];\n\tconst v = stored[fieldName];\n\tif (Array.isArray(v)) return v;\n\tif (v) return [v];\n\treturn [];\n}"
11
+ ],
12
+ "mappings": ";;;;;;;;;;;;;;;;;;AA0BA;AACA;AAAA;AAiFO,MAAM,oBAAoB,MAAM;AAAA,EAC7B,SAAS;AAAA,EACT;AAAA,EACA;AAAA,EACT,WAAW,CAAC,MAAc,OAAe,SAAiB;AAAA,IACzD,MAAM,OAAO;AAAA,IACb,KAAK,OAAO;AAAA,IACZ,KAAK,QAAQ;AAAA,IACb,KAAK,OAAO;AAAA;AAEd;AAOO,IAAM,qBAAqB;AAG3B,IAAM,cAAc;;AC5G3B;AA2BO,MAAM,cAAc;AAAA,SAEV,QAAQ,OAAO,IAAI,qBAAqB;AAAA,EAExD;AAAA,EACA,iBAAkD;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B,MAAM,IAAI,OAAO;AAAA,EACjB,IAAI,MAAM,QAAQ,CAAC;AAAA,IAAG,OAAO;AAAA,EAC7B,IAAI;AAAA,IAAG,OAAO,CAAC,CAAC;AAAA,EAChB,OAAO,CAAC;AAAA;",
13
+ "debugId": "9217B58E0BF1076D64756E2164756E21",
14
+ "names": []
15
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * `nexusjs/upload` — file upload helper.
3
+ *
4
+ * @Module({
5
+ * imports: [
6
+ * UploadModule.forRoot({
7
+ * maxFileSize: 10 * 1024 * 1024, // 10MB per file
8
+ * maxFiles: 5,
9
+ * allowedMimeTypes: ['image/*', 'application/pdf'],
10
+ * storage: 'memory', // or 'drive' (uses nexus/drive)
11
+ * }),
12
+ * ],
13
+ * })
14
+ *
15
+ * @Post('/avatars')
16
+ * @Upload('avatar') // form field name
17
+ * async upload(@UploadedFile('avatar') file: UploadedFile) {
18
+ * return { size: file.size, type: file.contentType };
19
+ * }
20
+ *
21
+ * @Post('/photos')
22
+ * async multi(@UploadedFiles('photos') files: UploadedFile[]) {
23
+ * return files.length;
24
+ * }
25
+ */
26
+ import "reflect-metadata";
27
+ import { METADATA_KEY } from "@nexusts/core";
28
+ /**
29
+ * A file that has been parsed from `multipart/form-data`.
30
+ *
31
+ * The framework reads the entire body into memory (with a hard cap
32
+ * enforced by `maxFileSize`) and exposes it as a `Buffer`. For very
33
+ * large files (gigabytes), use a streaming approach instead — the
34
+ * middleware leaves `stream` populated when the file is too large
35
+ * to buffer.
36
+ */
37
+ export interface UploadedFile {
38
+ /** Form field name (e.g. "avatar", "photos"). */
39
+ fieldName: string;
40
+ /** Filename from the client (e.g. "my-photo.png"). */
41
+ filename: string;
42
+ /** MIME type from the client. */
43
+ contentType: string;
44
+ /** Encoding (typically '7bit'). */
45
+ encoding: string;
46
+ /** File content. */
47
+ buffer: Buffer;
48
+ /** Convenience: same as `buffer.length`. */
49
+ size: number;
50
+ }
51
+ /** Top-level config. */
52
+ export interface UploadConfig {
53
+ /** Max bytes per file. Default: 10 MB. */
54
+ maxFileSize?: number;
55
+ /** Max number of files per request. Default: 5. */
56
+ maxFiles?: number;
57
+ /**
58
+ * Allowed MIME types. Supports `*` wildcards:
59
+ * 'image/*' — any image type
60
+ * 'application/pdf'
61
+ * 'video/mp4'
62
+ * Default: '*' (any).
63
+ */
64
+ allowedMimeTypes?: string[];
65
+ /**
66
+ * Where parsed files are stored in memory. Default: 'memory'.
67
+ * The decorator reads from this storage on each access.
68
+ */
69
+ storage?: "memory";
70
+ /**
71
+ * When set, parsed files are also pushed to the configured
72
+ * `nexusjs/drive` storage under this prefix. The drive is
73
+ * resolved by the DI token string.
74
+ */
75
+ driveToken?: string;
76
+ drivePrefix?: string;
77
+ /** When using drive storage: keep the original filename. Default: false (UUID). */
78
+ preserveFilename?: boolean;
79
+ }
80
+ export interface UploadOptions {
81
+ /** Form field name. Default: property name. */
82
+ name?: string;
83
+ /** Per-field max size (overrides the global default). */
84
+ maxSize?: number;
85
+ /** Per-field MIME-type filter. */
86
+ mimeTypes?: string[];
87
+ /** Per-field max files (for multi-file). Default: 1. */
88
+ maxFiles?: number;
89
+ /** Whether the field is required. Default: true. */
90
+ required?: boolean;
91
+ }
92
+ export declare class UploadError extends Error {
93
+ readonly status = 400;
94
+ readonly code: string;
95
+ readonly field: string;
96
+ constructor(code: string, field: string, message: string);
97
+ }
98
+ /** Key under which the multipart middleware stores parsed files. */
99
+ export declare const UPLOAD_STORAGE_KEY = "nexus:upload:files";
100
+ /** Internal metadata key (decorator). */
101
+ export declare const UPLOAD_META = "nexus:upload:options";
102
+ export { METADATA_KEY };
@@ -0,0 +1,14 @@
1
+ export interface FieldSpec {
2
+ fieldName: string;
3
+ maxFiles: number;
4
+ required: boolean;
5
+ }
6
+ /**
7
+ * Middleware factory. Returns a Hono middleware that:
8
+ * 1. Skips non-multipart requests.
9
+ * 2. Asks the UploadService to parse and store the given fields.
10
+ * 3. On `UploadError`, returns a 400 response with the error code.
11
+ */
12
+ export declare function uploadMiddleware(svc: {
13
+ parseAndStore(c: any, fields: FieldSpec[]): Promise<void>;
14
+ }): (c: any, next: () => Promise<any>) => Promise<any>;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * `UploadModule` — drop-in file upload handling.
3
+ *
4
+ * @Module({
5
+ * imports: [
6
+ * UploadModule.forRoot({
7
+ * maxFileSize: 10 * 1024 * 1024,
8
+ * allowedMimeTypes: ['image/*', 'application/pdf'],
9
+ * storage: 'memory',
10
+ * }),
11
+ * ],
12
+ * })
13
+ *
14
+ * After the framework router is built, call `UploadModule.mount(app, svc)`
15
+ * to install the multipart middleware. The middleware looks at
16
+ * the route's metadata (set by `@Upload('fieldName')`) to know
17
+ * which fields to parse.
18
+ */
19
+ import "reflect-metadata";
20
+ import { UploadService } from "./upload.service.js";
21
+ import type { UploadConfig } from "./types.js";
22
+ export declare class UploadModule {
23
+ static forRoot(config?: UploadConfig): {
24
+ new (): {};
25
+ };
26
+ /**
27
+ * Install the multipart middleware on the Hono app. Walk the
28
+ * route table, collect every `@Upload` decorator, and emit a
29
+ * middleware that knows which fields to parse.
30
+ */
31
+ static mount(app: any, svc: UploadService, routes?: any[]): void;
32
+ }
@@ -0,0 +1,28 @@
1
+ import { type UploadConfig, type UploadedFile } from "./types.js";
2
+ export declare class UploadService {
3
+ #private;
4
+ /** DI token. */
5
+ static readonly TOKEN: unique symbol;
6
+ constructor(config?: UploadConfig);
7
+ /** Bind a function that resolves a DI token to a service. Set by the module on boot. */
8
+ bindDriveResolver(fn: (token: string) => any): void;
9
+ /** The config this service was constructed with. */
10
+ getConfig(): Required<UploadConfig>;
11
+ /**
12
+ * Parse the request body and store the requested fields on the
13
+ * Hono context. Called by `uploadMiddleware`.
14
+ */
15
+ parseAndStore(c: any, fields: Array<{
16
+ fieldName: string;
17
+ maxFiles: number;
18
+ required: boolean;
19
+ }>): Promise<void>;
20
+ /**
21
+ * Read a single file from the stored body. Used by `@UploadedFile`.
22
+ */
23
+ get(c: any, fieldName: string): UploadedFile | undefined;
24
+ /**
25
+ * Read multiple files from the stored body. Used by `@UploadedFiles`.
26
+ */
27
+ getAll(c: any, fieldName: string): UploadedFile[];
28
+ }
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@nexusts/upload",
3
+ "version": "0.7.2",
4
+ "description": "Multipart file upload with validation",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": ["dist", "README.md"],
16
+ "scripts": {
17
+ "build": "bun run ../../build.ts"
18
+ },
19
+ "keywords": ["nexusts", "framework", "bun"],
20
+ "license": "MIT",
21
+
22
+
23
+ "dependencies": {
24
+ "@nexusts/core": "file:../core"
25
+ }
26
+ }