File size: 12,967 Bytes
4514571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
diff --git a/packages/next/errors.json b/packages/next/errors.json
index 6cf757d5c2..bc70516553 100644
--- a/packages/next/errors.json
+++ b/packages/next/errors.json
@@ -1440,5 +1440,6 @@
   "1439": "Route \"%s\": Next.js encountered URL data during prerendering or a navigation.\\n\\n\\`params\\` or \\`searchParams\\` accessed outside of \\`<Suspense>\\` may prevent the navigation from being instant, leading to a slower user experience.\\n\\nWays to fix this:\\n  - [stream] Provide a placeholder with \\`<Suspense fallback={...}>\\` around the data access\\n  - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\nLearn more: https://nextjs.org/docs/messages/instant-shell-url-data",
   "1440": "Route \"%s\": Next.js encountered uncached data during prerendering.\\n\\n\\`fetch(...)\\` or \\`connection()\\` accessed outside of \\`<Suspense>\\` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.\\n\\nWays to fix this:\\n  - [stream] Provide a placeholder with \\`<Suspense fallback={...}>\\` around the data access\\n  - [cache] Cache the data access with \\`\"use cache\"\\` (does not apply to \\`connection()\\`)\\n  - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\nLearn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic",
   "1441": "DevValidationScheduler requires at least one active validation",
-  "1442": "The Server Reference ID did not match the expected format. Received %s.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action"
+  "1442": "The Server Reference ID did not match the expected format. Received %s.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
+  "1443": "Unsupported body type: %s"
 }
diff --git a/packages/next/src/server/lib/incremental-cache/index.ts b/packages/next/src/server/lib/incremental-cache/index.ts
index 918f5583fb..31f100be25 100644
--- a/packages/next/src/server/lib/incremental-cache/index.ts
+++ b/packages/next/src/server/lib/incremental-cache/index.ts
@@ -55,6 +55,50 @@ export interface CacheHandlerValue {
   value: IncrementalCacheValue | null
 }
 
+function toHex(buffer: ArrayBufferView | ArrayBuffer): string {
+  // Hex-encode body bytes losslessly: decoding as UTF-8 would collapse
+  // distinct bytes (0xff/0xfe to U+FFFD) and collide; Buffer isn't on edge.
+  const bytes = isArrayBuffer(buffer)
+    ? new Uint8Array(buffer)
+    : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
+  let hex = ''
+  for (const byte of bytes) {
+    hex += byte.toString(16).padStart(2, '0')
+  }
+  return hex
+}
+
+type Body = NonNullable<RequestInit['body'] | Request['body']>
+
+// Duck typing to support Edge runtime
+// TODO: Switch to instanceof checks once Edge runtime is removed.
+
+function isArrayBuffer(
+  buffer: ArrayBuffer | ArrayBufferView
+): buffer is ArrayBuffer {
+  return !('buffer' in buffer)
+}
+
+function isBodyByteSequence(
+  body: Body
+): body is ArrayBufferView<ArrayBuffer> | ArrayBuffer {
+  return typeof body === 'object' && 'byteLength' in body
+}
+
+function isBodyReadableStream(body: Body): body is ReadableStream {
+  return typeof (body as any).getReader === 'function'
+}
+
+function isBodyFormDataOrURLSearchParams(
+  body: Body
+): body is FormData | URLSearchParams {
+  return typeof (body as any).keys === 'function'
+}
+
+function isBodyBlob(body: Body): body is Blob {
+  return typeof (body as any).arrayBuffer === 'function'
+}
+
 export class CacheHandler {
   // eslint-disable-next-line
   constructor(_ctx: CacheHandlerContext) {}
@@ -80,6 +124,21 @@ export class CacheHandler {
   public resetRequestCache(): void {}
 }
 
+async function hashString(cacheString: string): Promise<string> {
+  if (process.env.NEXT_RUNTIME === 'edge') {
+    const encoder = new TextEncoder()
+    const buffer = encoder.encode(cacheString)
+    return toHex(await crypto.subtle.digest('SHA-256', buffer))
+  } else {
+    const crypto = require('crypto') as typeof import('crypto')
+    return crypto.createHash('sha256').update(cacheString).digest('hex')
+  }
+}
+
+// this should be bumped anytime a fix is made to cache entries
+// that should bust the cache
+const MAIN_KEY_PREFIX = 'v4'
+
 export class IncrementalCache implements IncrementalCacheType {
   readonly dev?: boolean
   readonly disableForTestmode?: boolean
@@ -288,28 +347,34 @@ export class IncrementalCache implements IncrementalCacheType {
     return this.cacheHandler?.revalidateTag(tags, durations)
   }
 
+  async generateSimpleCacheKey(input: string): Promise<string> {
+    const cacheString = JSON.stringify([
+      MAIN_KEY_PREFIX,
+      this.fetchCacheKeyPrefix || '',
+      input,
+    ])
+
+    return hashString(cacheString)
+  }
+
   // x-ref: https://github.com/facebook/react/blob/2655c9354d8e1c54ba888444220f63e836925caa/packages/react/src/ReactFetch.js#L23
   async generateCacheKey(
     url: string,
     init: RequestInit | Request = {}
   ): Promise<string> {
-    // this should be bumped anytime a fix is made to cache entries
-    // that should bust the cache
-    const MAIN_KEY_PREFIX = 'v3'
-
     const bodyChunks: string[] = []
 
     const encoder = new TextEncoder()
-    const decoder = new TextDecoder()
 
-    if (init.body) {
-      // handle Uint8Array body
-      if (init.body instanceof Uint8Array) {
-        bodyChunks.push(decoder.decode(init.body))
-        ;(init as any)._ogBody = init.body
-      } // handle ReadableStream body
-      else if (typeof (init.body as any).getReader === 'function') {
-        const readableBody = init.body as ReadableStream<Uint8Array | string>
+    // Will be set implementing https://fetch.spec.whatwg.org/#concept-bodyinit-extract
+    let bodyType: string | null = null
+    const body = init.body
+    if (body) {
+      if (isBodyByteSequence(body)) {
+        bodyChunks.push(`bytes:${toHex(body)}`)
+        ;(init as any)._ogBody = body
+      } else if (isBodyReadableStream(body)) {
+        const readableBody = body
 
         const chunks: Uint8Array[] = []
 
@@ -317,20 +382,13 @@ export class IncrementalCache implements IncrementalCacheType {
           await readableBody.pipeTo(
             new WritableStream({
               write(chunk) {
-                if (typeof chunk === 'string') {
-                  chunks.push(encoder.encode(chunk))
-                  bodyChunks.push(chunk)
-                } else {
-                  chunks.push(chunk)
-                  bodyChunks.push(decoder.decode(chunk, { stream: true }))
-                }
+                chunks.push(
+                  typeof chunk === 'string' ? encoder.encode(chunk) : chunk
+                )
               },
             })
           )
 
-          // Flush the decoder.
-          bodyChunks.push(decoder.decode())
-
           // Create a new buffer with all the chunks.
           const length = chunks.reduce((total, arr) => total + arr.length, 0)
           const arrayBuffer = new Uint8Array(length)
@@ -342,46 +400,54 @@ export class IncrementalCache implements IncrementalCacheType {
             offset += chunk.length
           }
 
+          bodyChunks.push(`bytes:${toHex(arrayBuffer)}`)
           ;(init as any)._ogBody = arrayBuffer
         } catch (err) {
           console.error('Problem reading body', err)
         }
-      } // handle FormData or URLSearchParams bodies
-      else if (typeof (init.body as any).keys === 'function') {
-        const formData = init.body as FormData
-        ;(init as any)._ogBody = init.body
-        for (const key of new Set([...formData.keys()])) {
-          const values = formData.getAll(key)
-          bodyChunks.push(
-            `${key}=${(
-              await Promise.all(
-                values.map(async (val) => {
-                  if (typeof val === 'string') {
-                    return val
-                  } else {
-                    return await val.text()
-                  }
-                })
-              )
-            ).join(',')}`
-          )
+      } else if (isBodyFormDataOrURLSearchParams(body)) {
+        bodyType =
+          String(body) === '[object FormData]'
+            ? // We don't need a boundary because we're not actually using this for a Content-Type header
+              'multipart/form-data; boundary='
+            : 'application/x-www-form-urlencoded;charset=UTF-8'
+        const iterable = body
+        ;(init as any)._ogBody = body
+        // Separate, tagged chunks so `["a","b"]` can't collide with `["a,b"]`.
+        for (const [key, val] of iterable.entries()) {
+          bodyChunks.push(`key:${key}`)
+          if (typeof val === 'string') {
+            bodyChunks.push(`str:${val}`)
+          } else {
+            bodyChunks.push(
+              'file',
+              val.name,
+              val.type,
+              `bytes:${toHex(await val.arrayBuffer())}`
+            )
+          }
         }
         // handle blob body
-      } else if (typeof (init.body as any).arrayBuffer === 'function') {
-        const blob = init.body as Blob
+      } else if (isBodyBlob(body)) {
+        const blob = body
         const arrayBuffer = await blob.arrayBuffer()
-        bodyChunks.push(await blob.text())
+        bodyChunks.push('blob', blob.type, `bytes:${toHex(arrayBuffer)}`)
         ;(init as any)._ogBody = new Blob([arrayBuffer], { type: blob.type })
-      } else if (typeof init.body === 'string') {
-        bodyChunks.push(init.body)
-        ;(init as any)._ogBody = init.body
+        bodyType = blob.type
+      } else if (typeof body === 'string') {
+        bodyChunks.push(`str:${body}`)
+        ;(init as any)._ogBody = body
+        bodyType = 'text/plain;charset=UTF-8'
+      } else {
+        body satisfies never
+        throw new Error(`Unsupported body type: ${typeof body}`)
       }
     }
 
     const headers =
       typeof (init.headers || {}).keys === 'function'
         ? Object.fromEntries(init.headers as Headers)
-        : Object.assign({}, init.headers)
+        : Object.assign({} as Record<string, string>, init.headers)
 
     // w3c trace context headers can break request caching and deduplication
     // so we remove them from the cache key
@@ -393,6 +459,9 @@ export class IncrementalCache implements IncrementalCacheType {
       this.fetchCacheKeyPrefix || '',
       url,
       init.method,
+      // Ensures default Content-Type is part of the cache key
+      // TODO: Only necessary when headers are not used from the Request instance
+      bodyType,
       headers,
       init.mode,
       init.redirect,
@@ -404,18 +473,7 @@ export class IncrementalCache implements IncrementalCacheType {
       bodyChunks,
     ])
 
-    if (process.env.NEXT_RUNTIME === 'edge') {
-      function bufferToHex(buffer: ArrayBuffer): string {
-        return Array.prototype.map
-          .call(new Uint8Array(buffer), (b) => b.toString(16).padStart(2, '0'))
-          .join('')
-      }
-      const buffer = encoder.encode(cacheString)
-      return bufferToHex(await crypto.subtle.digest('SHA-256', buffer))
-    } else {
-      const crypto = require('crypto') as typeof import('crypto')
-      return crypto.createHash('sha256').update(cacheString).digest('hex')
-    }
+    return hashString(cacheString)
   }
 
   async get(
diff --git a/packages/next/src/server/lib/patch-fetch.ts b/packages/next/src/server/lib/patch-fetch.ts
index 4be72496f1..b7e8b124c4 100644
--- a/packages/next/src/server/lib/patch-fetch.ts
+++ b/packages/next/src/server/lib/patch-fetch.ts
@@ -820,8 +820,8 @@ export function createPatchedFetcher(
               fetchUrl,
               isRequestInput ? (input as RequestInit) : init
             )
-          } catch (err) {
-            console.error(`Failed to generate cache key for`, input)
+          } catch (cause) {
+            console.error(`Failed to generate cache key for`, input, cause)
           }
         }
 
diff --git a/packages/next/src/server/web/spec-extension/unstable-cache.ts b/packages/next/src/server/web/spec-extension/unstable-cache.ts
index 9027330881..5c3aac47c7 100644
--- a/packages/next/src/server/web/spec-extension/unstable-cache.ts
+++ b/packages/next/src/server/web/spec-extension/unstable-cache.ts
@@ -134,7 +134,8 @@ export function unstable_cache<T extends Callback>(
       // @TODO stringify is likely not safe here. We will coerce undefined to null which will make
       // the keyspace smaller than the execution space
       const invocationKey = `${fixedKey}-${JSON.stringify(args)}`
-      const cacheKey = await incrementalCache.generateCacheKey(invocationKey)
+      const cacheKey =
+        await incrementalCache.generateSimpleCacheKey(invocationKey)
       // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse
       const fetchUrl = `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`
       const fetchIdx =