graphql-upload-nextjs 2.0.11 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,369 +1,53 @@
1
- import { fileTypeFromBuffer } from 'file-type';
2
- import { GraphQLError, GraphQLScalarType } from 'graphql';
3
- import { isText } from 'istextorbinary';
4
- import { NextResponse } from 'next/server.js';
5
- import { Readable } from 'stream';
6
- const DEFAULT_MIME_TYPE = 'application/octet-stream';
7
- /**
8
- * Represents an instance of a file upload.
9
- * Holds a promise that resolves with the file details once processed.
10
- */
11
- export class Upload {
12
- file;
13
- promise;
14
- reject = () => { };
15
- resolve = () => { };
16
- constructor() {
17
- this.promise = new Promise((resolve, reject) => {
18
- this.resolve = (file) => {
19
- this.file = file;
20
- resolve(file);
21
- };
22
- this.reject = reject;
23
- });
24
- this.promise.catch(() => { });
25
- }
26
- }
27
- /** Custom GraphQL scalar type for handling file uploads. */
28
- export const GraphQLUpload = new GraphQLScalarType({
29
- description: 'The Upload scalar type represents a file upload.',
30
- name: 'Upload',
31
- parseLiteral(node) {
32
- throw new GraphQLError('Upload literal unsupported.', { nodes: node });
33
- },
34
- parseValue(value) {
35
- if (value instanceof Upload)
36
- return value.promise;
37
- throw new GraphQLError('Upload value invalid.');
38
- },
39
- serialize() {
40
- throw new GraphQLError('Upload serialization unsupported.');
41
- },
42
- });
43
- /** Converts a Buffer into a Node.js readable stream. */
44
- export function bufferToStream(buffer) {
45
- const stream = new Readable();
46
- stream.push(buffer);
47
- stream.push(null);
48
- return stream;
49
- }
50
- /** Collects a GraphQL response into a serializable result object. */
51
- async function collectResponse(response) {
52
- if (response.body.kind === 'single') {
53
- return response.body.singleResult;
54
- }
55
- if (response.body.kind === 'incremental') {
56
- const { initialResult, subsequentResults } = response.body;
57
- const collected = [];
58
- for await (const result of subsequentResults) {
59
- collected.push(result);
60
- }
61
- return { initialResult, subsequentResults: collected };
62
- }
63
- return { errors: [{ message: 'Unexpected server response format' }] };
64
- }
65
- /** Extracts File entries from multipart FormData. */
66
- async function extractFiles(formData) {
67
- const files = {};
68
- for (const [key, value] of formData.entries()) {
69
- if (value instanceof globalThis.File) {
70
- files[key] = value;
71
- }
72
- }
73
- return files;
74
- }
75
- /** Parses JSON for the operations field. Accepts objects or arrays (for batching per spec). */
76
- export function parseOperationsJSON(input) {
77
- let result;
78
- try {
79
- result = JSON.parse(input);
80
- }
81
- catch {
82
- throw new Error('Invalid JSON in the operations multipart field.');
83
- }
84
- if (typeof result !== 'object' || result === null) {
85
- throw new Error('Invalid type for the operations multipart field.');
86
- }
87
- return result;
88
- }
89
- /**
90
- * Processes a file from FormData, detects its MIME type via magic bytes,
91
- * and returns a resolved Upload instance with streaming file access.
92
- */
93
- async function processUpload(file, allowedTypes) {
94
- if (!file.name || typeof file.size !== 'number' || !Number.isFinite(file.size) || file.size < 0) {
95
- throw new Error('Invalid file properties: name or size is missing or invalid.');
96
- }
97
- const blob = file;
98
- // Only read the first 4100 bytes for MIME type detection via magic bytes.
99
- // This avoids buffering the entire file into memory.
100
- const DETECTION_BYTES = 4100;
101
- const headerBuffer = Buffer.from(await blob.slice(0, DETECTION_BYTES).arrayBuffer());
102
- const fileTypeInfo = await fileTypeFromBuffer(new Uint8Array(headerBuffer.buffer, headerBuffer.byteOffset, headerBuffer.byteLength));
103
- let mimetype = DEFAULT_MIME_TYPE;
104
- if (fileTypeInfo) {
105
- mimetype = fileTypeInfo.mime;
106
- }
107
- else {
108
- try {
109
- if (await isText(file.name, headerBuffer)) {
110
- mimetype = 'text/plain';
111
- }
112
- }
113
- catch {
114
- // Fallback: isText detection failed, keeping the unknown binary default.
115
- }
116
- }
117
- if (allowedTypes && !allowedTypes.includes(mimetype)) {
118
- throw new Error(`File type ${mimetype} is not allowed. Allowed types: ${allowedTypes.join(', ')}`);
119
- }
120
- const upload = new Upload();
121
- upload.resolve({
122
- createReadStream: () => Readable.fromWeb(blob.stream()),
123
- encoding: 'binary',
124
- fileSize: file.size,
125
- filename: file.name,
126
- mimetype,
127
- });
128
- return upload;
129
- }
130
- /** Parses and validates a JSON string, ensuring it resolves to a non-null object (rejects arrays). */
131
- export function sanitizeAndValidateJSON(input) {
132
- let result;
133
- try {
134
- result = JSON.parse(input);
135
- }
136
- catch (error) {
137
- throw new Error(`Invalid JSON input: ${error.message}`);
138
- }
139
- if (typeof result !== 'object' || result === null || Array.isArray(result)) {
140
- throw new Error('Invalid JSON structure: expected a non-null object.');
141
- }
142
- return result;
143
- }
144
- /** Dangerous property names that could lead to prototype pollution. */
145
- const BLOCKED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
146
- /** Checks whether a value is a plain object record suitable for GraphQL variables. */
147
- function isObjectRecord(value) {
148
- return typeof value === 'object' && value !== null && !Array.isArray(value);
149
- }
150
- /** Validates the minimal GraphQL operation shape required for execution. */
151
- function validateOperation(operation, label) {
152
- if (!isObjectRecord(operation)) {
153
- return `Invalid ${label}: expected an operation object.`;
154
- }
155
- if (typeof operation.query !== 'string') {
156
- return `Invalid ${label}: expected query to be a string.`;
157
- }
158
- if (operation.variables !== undefined && !isObjectRecord(operation.variables)) {
159
- return `Invalid ${label}: expected variables to be an object when provided.`;
160
- }
161
- return null;
162
- }
163
- /** Validates upload process settings before request body processing starts. */
164
- function validateSettings(settings) {
165
- if (settings?.maxFileSize !== undefined && (typeof settings.maxFileSize !== 'number' ||
166
- !Number.isFinite(settings.maxFileSize) ||
167
- settings.maxFileSize < 0)) {
168
- return 'Invalid maxFileSize setting: expected a finite non-negative number.';
169
- }
170
- if (settings?.maxFiles !== undefined && (typeof settings.maxFiles !== 'number' ||
171
- !Number.isFinite(settings.maxFiles) ||
172
- settings.maxFiles < 0)) {
173
- return 'Invalid maxFiles setting: expected a finite non-negative number.';
174
- }
175
- return null;
176
- }
177
- /** Sets a value at a dot-notation path in a nested object, creating intermediate containers as needed. */
178
- export function setValueAtPath(obj, path, value) {
179
- const keys = path.split('.');
180
- let current = obj;
181
- for (let i = 0; i < keys.length - 1; i++) {
182
- const key = keys[i];
183
- if (BLOCKED_KEYS.has(key)) {
184
- throw new Error(`Invalid path segment: '${key}' is not allowed.`);
185
- }
186
- const nextKeyIsArrayIndex = /^\d+$/.test(keys[i + 1]);
187
- if (!current[key] ||
188
- typeof current[key] !== 'object' ||
189
- (nextKeyIsArrayIndex && !Array.isArray(current[key])) ||
190
- (!nextKeyIsArrayIndex && Array.isArray(current[key]))) {
191
- current[key] = nextKeyIsArrayIndex ? [] : {};
192
- }
193
- current = current[key];
194
- }
195
- const finalKey = keys[keys.length - 1];
196
- if (BLOCKED_KEYS.has(finalKey)) {
197
- throw new Error(`Invalid path segment: '${finalKey}' is not allowed.`);
198
- }
199
- current[finalKey] = value;
200
- }
201
- /** Converts a Node.js readable stream into a Buffer by collecting all chunks. */
202
- export async function streamToBuffer(stream) {
203
- const chunks = [];
204
- for await (const chunk of stream) {
205
- if (Buffer.isBuffer(chunk)) {
206
- chunks.push(chunk);
207
- }
208
- else if (typeof chunk === 'string') {
209
- chunks.push(Buffer.from(chunk));
210
- }
211
- else {
212
- chunks.push(Buffer.from(chunk));
213
- }
214
- }
215
- return Buffer.concat(chunks);
216
- }
217
- /** Validates that each map entry is an array of string paths. */
218
- export function validateMap(map) {
219
- for (const [key, paths] of Object.entries(map)) {
220
- if (!Array.isArray(paths)) {
221
- return `Invalid type for map entry '${key}': expected an array of paths.`;
222
- }
223
- for (const p of paths) {
224
- if (typeof p !== 'string') {
225
- return `Invalid path in map entry '${key}': expected string.`;
226
- }
227
- if (!p) {
228
- return `Invalid path in map entry '${key}': path cannot be empty.`;
229
- }
230
- const segments = p.split('.');
231
- for (const segment of segments) {
232
- if (!segment) {
233
- return `Invalid path in map entry '${key}': path cannot contain empty segments.`;
234
- }
235
- if (BLOCKED_KEYS.has(segment)) {
236
- return `Invalid path segment in map entry '${key}': '${segment}' is not allowed.`;
237
- }
238
- }
239
- }
240
- }
241
- return null;
242
- }
243
- /** Processes a GraphQL multipart request with file uploads. Supports batching per the spec. */
1
+ import { UploadRequestError, checkUploadRequest, executeOperations, prepareOperations, processUpload, uploadErrorResponse, } from './core.js';
2
+ export { GraphQLUpload, Upload, bufferToStream, parseOperationsJSON, sanitizeAndValidateJSON, setValueAtPath, streamToBuffer, validateMap, } from './core.js';
3
+ export { uploadProcessStreaming } from './streaming.js';
4
+ /** Fully receives files before executing GraphQL; existing callers retain numeric file sizes. */
244
5
  export async function uploadProcess(request, contextValueInput, server, settings) {
245
6
  try {
246
- const settingsError = validateSettings(settings);
247
- if (settingsError) {
248
- return NextResponse.json({ errors: [{ message: settingsError }] }, { status: 400 });
249
- }
250
- const formData = await request.formData();
251
- const files = await extractFiles(formData);
252
- const mapRaw = formData.get('map');
253
- const operationsRaw = formData.get('operations');
254
- if (!mapRaw || !operationsRaw || typeof mapRaw !== 'string' || typeof operationsRaw !== 'string') {
255
- return NextResponse.json({ errors: [{ message: 'Missing or invalid map/operations in form data.' }] }, { status: 400 });
256
- }
257
- const mapString = mapRaw;
258
- const operationsString = operationsRaw;
259
- // Parse and validate the map field (must be an object, not array).
260
- let map;
261
- try {
262
- map = sanitizeAndValidateJSON(mapString);
263
- }
264
- catch {
265
- return NextResponse.json({ errors: [{ message: 'Invalid JSON in the map multipart field.' }] }, { status: 400 });
266
- }
267
- const mapError = validateMap(map);
268
- if (mapError) {
269
- return NextResponse.json({ errors: [{ message: mapError }] }, { status: 400 });
270
- }
271
- // Parse the operations field (object or array for batching).
272
- let parsedOperations;
7
+ checkUploadRequest(request.headers, settings);
8
+ let formData;
273
9
  try {
274
- parsedOperations = parseOperationsJSON(operationsString);
10
+ formData = await request.formData();
275
11
  }
276
12
  catch {
277
- return NextResponse.json({ errors: [{ message: 'Invalid JSON in the operations multipart field.' }] }, { status: 400 });
13
+ throw new UploadRequestError('Invalid multipart request body.');
278
14
  }
279
- if (Array.isArray(parsedOperations)) {
280
- for (let i = 0; i < parsedOperations.length; i++) {
281
- const operationError = validateOperation(parsedOperations[i], `operation at index ${i}`);
282
- if (operationError) {
283
- return NextResponse.json({ errors: [{ message: operationError }] }, { status: 400 });
284
- }
285
- }
15
+ const entries = [...formData.entries()].filter((entry) => entry[1] instanceof globalThis.File);
16
+ if (settings?.maxFiles !== undefined && entries.length > settings.maxFiles) {
17
+ throw new UploadRequestError(`${settings.maxFiles} max file uploads exceeded.`, 413);
286
18
  }
287
- else {
288
- const operationError = validateOperation(parsedOperations, 'operation');
289
- if (operationError) {
290
- return NextResponse.json({ errors: [{ message: operationError }] }, { status: 400 });
291
- }
292
- }
293
- // Check maxFiles limit.
294
- if (settings?.maxFiles !== undefined && Object.keys(map).length > settings.maxFiles) {
295
- return NextResponse.json({ errors: [{ message: `${settings.maxFiles} max file uploads exceeded.` }] }, { status: 413 });
296
- }
297
- // Normalize operations into a keyed object for path resolution.
298
- // Single: paths are "variables.file" → use the operation object directly.
299
- // Batch: paths are "0.variables.file" → use indices as keys in a wrapper object.
300
- const isBatch = Array.isArray(parsedOperations);
301
- let operationsRoot;
302
- if (isBatch) {
303
- const batchOperations = parsedOperations;
304
- operationsRoot = {};
305
- for (let i = 0; i < batchOperations.length; i++) {
306
- const op = batchOperations[i];
307
- if (!op.variables)
308
- op.variables = {};
309
- operationsRoot[String(i)] = op;
19
+ const operationsRaw = formData.get('operations');
20
+ const mapRaw = formData.get('map');
21
+ if (typeof operationsRaw !== 'string' || typeof mapRaw !== 'string' ||
22
+ formData.getAll('operations').length !== 1 || formData.getAll('map').length !== 1) {
23
+ throw new UploadRequestError('Missing, duplicate, or invalid map/operations in form data.');
24
+ }
25
+ const files = new Map();
26
+ for (const [field, file] of entries) {
27
+ if (files.has(field))
28
+ throw new UploadRequestError('Duplicate multipart file field.');
29
+ if (settings?.maxFileSize !== undefined && file.size > settings.maxFileSize) {
30
+ throw new UploadRequestError(`File ${file.name} size is too large.`, 413);
310
31
  }
32
+ files.set(field, file);
311
33
  }
312
- else {
313
- const singleOp = parsedOperations;
314
- if (!singleOp.variables)
315
- singleOp.variables = {};
316
- operationsRoot = singleOp;
317
- }
318
- // Process files and resolve Upload instances at mapped paths.
319
- const fileProcessingPromises = [];
320
- for (const fileKeyInMap of Object.keys(map)) {
321
- const file = files[fileKeyInMap];
34
+ const { operations, uploads } = prepareOperations(operationsRaw, mapRaw, settings?.maxFiles);
35
+ await Promise.all([...uploads].map(async ([field, upload]) => {
36
+ const file = files.get(field);
322
37
  if (!file) {
323
- // Per spec: reject Upload promise when file is missing from the request.
324
- for (const filePath of map[fileKeyInMap]) {
325
- const missingUpload = new Upload();
326
- missingUpload.reject(new Error('File missing in the request.'));
327
- setValueAtPath(operationsRoot, filePath, missingUpload);
328
- }
329
- continue;
38
+ upload.reject(new Error('File missing in the request.'));
39
+ return;
330
40
  }
331
- if (settings?.maxFileSize !== undefined && file.size > settings.maxFileSize) {
332
- return NextResponse.json({ errors: [{ message: `File ${file.name} size is too large. Maximum allowed size is ${(settings.maxFileSize / (1024 * 1024)).toFixed(2)}MB.` }] }, { status: 413 });
41
+ try {
42
+ upload.resolve(await processUpload(file, settings?.allowedTypes));
333
43
  }
334
- const variablePaths = map[fileKeyInMap];
335
- const filePromise = processUpload(file, settings?.allowedTypes)
336
- .then(uploadInstance => {
337
- for (const filePath of variablePaths) {
338
- setValueAtPath(operationsRoot, filePath, uploadInstance);
339
- }
340
- })
341
- .catch((error) => {
342
- for (const filePath of variablePaths) {
343
- const uploadError = new Upload();
344
- uploadError.reject(new Error(`Failed to process file ${file.name}: ${error.message}`));
345
- setValueAtPath(operationsRoot, filePath, uploadError);
346
- }
347
- });
348
- fileProcessingPromises.push(filePromise);
349
- }
350
- await Promise.all(fileProcessingPromises);
351
- // Execute operations and collect results.
352
- if (isBatch) {
353
- const results = [];
354
- const sortedKeys = Object.keys(operationsRoot).sort((a, b) => Number(a) - Number(b));
355
- for (const key of sortedKeys) {
356
- const op = operationsRoot[key];
357
- const response = await server.executeOperation({ query: op.query, variables: op.variables || {} }, { contextValue: contextValueInput });
358
- results.push(await collectResponse(response));
44
+ catch (error) {
45
+ upload.reject(new Error(`Failed to process file ${file.name}: ${error.message}`));
359
46
  }
360
- return NextResponse.json(results);
361
- }
362
- const response = await server.executeOperation({ query: operationsRoot.query, variables: operationsRoot.variables }, { contextValue: contextValueInput });
363
- return NextResponse.json(await collectResponse(response));
47
+ }));
48
+ return await executeOperations(operations, contextValueInput, server);
364
49
  }
365
50
  catch (error) {
366
- const errorMessage = error instanceof Error ? error.message : 'Unknown error during upload processing.';
367
- return NextResponse.json({ errors: [{ message: `Error processing upload: ${errorMessage}` }] }, { status: 500 });
51
+ return uploadErrorResponse(error);
368
52
  }
369
53
  }
package/package.json CHANGED
@@ -7,21 +7,21 @@
7
7
  "url": "https://github.com/lafittemehdy/graphql-upload-nextjs/issues"
8
8
  },
9
9
  "dependencies": {
10
- "file-type": "^22.0.1",
10
+ "busboy": "^1.6.0",
11
+ "file-type": "^22.3.0",
12
+ "fs-capacitor": "^8.0.0",
11
13
  "istextorbinary": "^9.5.0"
12
14
  },
13
15
  "description": "The middleware and Upload scalar in this package enable GraphQL multipart requests (file uploads via queries and mutations) in your Apollo Server Next.js integration.",
14
16
  "devDependencies": {
15
- "@types/jest": "^30.0.0",
16
- "@types/node": "^25.9.3",
17
- "graphql": "^16.14.2",
17
+ "@types/busboy": "^1.5.5",
18
+ "@types/node": "^26.6.6",
19
+ "graphql": "^16.15.0",
18
20
  "husky": "^9.1.7",
19
- "jest": "^30.4.2",
20
- "next": "^16.2.10",
21
- "nodemon": "^3.1.14",
22
- "ts-jest": "^29.4.11",
23
- "typescript": "^6.0.3",
24
- "undici": "^8.7.0"
21
+ "next": "^16.4.5",
22
+ "typescript": "^7.0.2",
23
+ "undici": "^8.12.4",
24
+ "vitest": "^5.1.0"
25
25
  },
26
26
  "files": [
27
27
  "CODE_OF_CONDUCT.md",
@@ -29,8 +29,12 @@
29
29
  "LICENSE",
30
30
  "README.md",
31
31
  "SECURITY.md",
32
+ "core.d.ts",
33
+ "core.js",
32
34
  "index.d.ts",
33
- "index.js"
35
+ "index.js",
36
+ "streaming.d.ts",
37
+ "streaming.js"
34
38
  ],
35
39
  "engines": {
36
40
  "node": ">=22.13.0"
@@ -52,9 +56,14 @@
52
56
  "main": "index.js",
53
57
  "name": "graphql-upload-nextjs",
54
58
  "overrides": {
55
- "postcss": "8.5.14"
59
+ "postcss": "8.5.32",
60
+ "@graphql-tools/utils": "13.2.1",
61
+ "@fastify/busboy": "3.2.5",
62
+ "qs": "6.17.1",
63
+ "source-map-js": "1.2.2",
64
+ "body-parser": "2.4.0"
56
65
  },
57
- "packageManager": "npm@10.9.3",
66
+ "packageManager": "npm@12.2.2",
58
67
  "peerDependencies": {
59
68
  "@apollo/server": "^5.0.0",
60
69
  "graphql": "^16.0.0",
@@ -70,13 +79,15 @@
70
79
  },
71
80
  "scripts": {
72
81
  "build": "tsc",
73
- "dev": "tsc -w | nodemon index.js",
74
- "prepublishOnly": "npm run build && npm test",
82
+ "dev": "tsc --watch",
83
+ "prepublishOnly": "npm run build && npm test && npm run test:types",
75
84
  "start": "tsc && node index.js",
76
- "test": "jest",
85
+ "test": "vitest run",
86
+ "test:types": "tsc --ignoreConfig --noEmit --strict --skipLibCheck --module NodeNext --moduleResolution NodeNext --target ES2022 tests/public-api.ts",
87
+ "test:integration": "node --test tests/next-http.test.mjs",
77
88
  "prepare": "husky || exit 0"
78
89
  },
79
90
  "type": "module",
80
91
  "types": "index.d.ts",
81
- "version": "2.0.11"
92
+ "version": "3.1.0"
82
93
  }
package/streaming.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { NextResponse } from 'next/server.js';
2
+ import { Readable } from 'node:stream';
3
+ import { type File, type MinimalRequest, type UploadProcessSettings, type UploadServer } from './core.js';
4
+ /** Streaming metadata deliberately has a different size contract from the buffered File. */
5
+ export interface StreamingFile extends Omit<File, 'fileSize' | 'createReadStream'> {
6
+ /** Resolves after this file has been completely received and written to temporary storage. */
7
+ fileSize: Promise<number>;
8
+ createReadStream: () => Readable;
9
+ /** Cancels the entire multipart request, including any aliases and other pending uploads. */
10
+ abort: () => void;
11
+ }
12
+ export interface StreamingRequest {
13
+ body: ReadableStream<Uint8Array> | null;
14
+ headers: MinimalRequest['headers'];
15
+ signal?: AbortSignal;
16
+ }
17
+ export interface StreamingUploadSettings extends UploadProcessSettings {
18
+ maxFieldSize?: number;
19
+ maxRequestSize?: number;
20
+ }
21
+ /** Opt-in Node.js API; success waits for reception, and all readers must finish within execution. */
22
+ export declare function uploadProcessStreaming<TContext extends Record<string, unknown>>(request: StreamingRequest, contextValueInput: TContext, server: UploadServer<TContext>, settings?: StreamingUploadSettings): Promise<NextResponse>;