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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import {
  type ReadonlyRequestCookies,
  type ResponseCookies,
  areCookiesMutableInCurrentPhase,
  RequestCookiesAdapter,
} from '../web/spec-extension/adapters/request-cookies'
import { RequestCookies } from '../web/spec-extension/cookies'
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import {
  throwForMissingRequestStore,
  workUnitAsyncStorage,
  type PrerenderStoreModern,
} from '../app-render/work-unit-async-storage.external'
import {
  postponeWithTracking,
  throwToInterruptStaticGeneration,
  trackDynamicDataInDynamicRender,
  trackSynchronousRequestDataAccessInDev,
} from '../app-render/dynamic-rendering'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { scheduleImmediate } from '../../lib/scheduler'
import { isRequestAPICallableInsideAfter } from './utils'
import { InvariantError } from '../../shared/lib/invariant-error'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'

/**
 * In this version of Next.js `cookies()` returns a Promise however you can still reference the properties of the underlying cookies object
 * synchronously to facilitate migration. The `UnsafeUnwrappedCookies` type is added to your code by a codemod that attempts to automatically
 * updates callsites to reflect the new Promise return type. There are some cases where `cookies()` cannot be automatically converted, namely
 * when it is used inside a synchronous function and we can't be sure the function can be made async automatically. In these cases we add an
 * explicit type case to `UnsafeUnwrappedCookies` to enable typescript to allow for the synchronous usage only where it is actually necessary.
 *
 * You should should update these callsites to either be async functions where the `cookies()` value can be awaited or you should call `cookies()`
 * from outside and await the return value before passing it into this function.
 *
 * You can find instances that require manual migration by searching for `UnsafeUnwrappedCookies` in your codebase or by search for a comment that
 * starts with `@next-codemod-error`.
 *
 * In a future version of Next.js `cookies()` will only return a Promise and you will not be able to access the underlying cookies object directly
 * without awaiting the return value first. When this change happens the type `UnsafeUnwrappedCookies` will be updated to reflect that is it no longer
 * usable.
 *
 * This type is marked deprecated to help identify it as target for refactoring away.
 *
 * @deprecated
 */
export type UnsafeUnwrappedCookies = ReadonlyRequestCookies

export function cookies(): Promise<ReadonlyRequestCookies> {
  const callingExpression = 'cookies'
  const workStore = workAsyncStorage.getStore()
  const workUnitStore = workUnitAsyncStorage.getStore()

  if (workStore) {
    if (
      workUnitStore &&
      workUnitStore.phase === 'after' &&
      !isRequestAPICallableInsideAfter()
    ) {
      throw new Error(
        // TODO(after): clarify that this only applies to pages?
        `Route ${workStore.route} used "cookies" inside "after(...)". This is not supported. If you need this data inside an "after" callback, use "cookies" outside of the callback. See more info here: https://nextjs.org/docs/canary/app/api-reference/functions/after`
      )
    }

    if (workStore.forceStatic) {
      // When using forceStatic we override all other logic and always just return an empty
      // cookies object without tracking
      const underlyingCookies = createEmptyCookies()
      return makeUntrackedExoticCookies(underlyingCookies)
    }

    if (workStore.dynamicShouldError) {
      throw new StaticGenBailoutError(
        `Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
      )
    }

    if (workUnitStore) {
      switch (workUnitStore.type) {
        case 'cache':
          const error = new Error(
            `Route ${workStore.route} used "cookies" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
          )
          Error.captureStackTrace(error, cookies)
          workStore.invalidDynamicUsageError ??= error
          throw error
        case 'unstable-cache':
          throw new Error(
            `Route ${workStore.route} used "cookies" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
          )
        case 'prerender':
          return makeHangingCookies(workUnitStore)
        case 'prerender-client':
          const exportName = '`cookies`'
          throw new InvariantError(
            `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`
          )
        case 'prerender-ppr':
          // We need track dynamic access here eagerly to keep continuity with
          // how cookies has worked in PPR without cacheComponents.
          return postponeWithTracking(
            workStore.route,
            callingExpression,
            workUnitStore.dynamicTracking
          )
        case 'prerender-legacy':
          // We track dynamic access here so we don't need to wrap the cookies
          // in individual property access tracking.
          return throwToInterruptStaticGeneration(
            callingExpression,
            workStore,
            workUnitStore
          )
        case 'private-cache':
          return makeUntrackedExoticCookies(workUnitStore.cookies)
        case 'request':
          trackDynamicDataInDynamicRender(workUnitStore)

          let underlyingCookies: ReadonlyRequestCookies

          if (areCookiesMutableInCurrentPhase(workUnitStore)) {
            // We can't conditionally return different types here based on the context.
            // To avoid confusion, we always return the readonly type here.
            underlyingCookies =
              workUnitStore.userspaceMutableCookies as unknown as ReadonlyRequestCookies
          } else {
            underlyingCookies = workUnitStore.cookies
          }

          if (
            process.env.NODE_ENV === 'development' &&
            !workStore?.isPrefetchRequest
          ) {
            if (process.env.__NEXT_CACHE_COMPONENTS) {
              return makeUntrackedCookiesWithDevWarnings(
                underlyingCookies,
                workStore?.route
              )
            }

            return makeUntrackedExoticCookiesWithDevWarnings(
              underlyingCookies,
              workStore?.route
            )
          } else {
            return makeUntrackedExoticCookies(underlyingCookies)
          }
        default:
          workUnitStore satisfies never
      }
    }
  }

  // If we end up here, there was no work store or work unit store present.
  throwForMissingRequestStore(callingExpression)
}

function createEmptyCookies(): ReadonlyRequestCookies {
  return RequestCookiesAdapter.seal(new RequestCookies(new Headers({})))
}

interface CacheLifetime {}
const CachedCookies = new WeakMap<
  CacheLifetime,
  Promise<ReadonlyRequestCookies>
>()

function makeHangingCookies(
  prerenderStore: PrerenderStoreModern
): Promise<ReadonlyRequestCookies> {
  const cachedPromise = CachedCookies.get(prerenderStore)
  if (cachedPromise) {
    return cachedPromise
  }

  const promise = makeHangingPromise<ReadonlyRequestCookies>(
    prerenderStore.renderSignal,
    '`cookies()`'
  )
  CachedCookies.set(prerenderStore, promise)

  return promise
}

function makeUntrackedExoticCookies(
  underlyingCookies: ReadonlyRequestCookies
): Promise<ReadonlyRequestCookies> {
  const cachedCookies = CachedCookies.get(underlyingCookies)
  if (cachedCookies) {
    return cachedCookies
  }

  const promise = Promise.resolve(underlyingCookies)
  CachedCookies.set(underlyingCookies, promise)

  Object.defineProperties(promise, {
    [Symbol.iterator]: {
      value: underlyingCookies[Symbol.iterator]
        ? underlyingCookies[Symbol.iterator].bind(underlyingCookies)
        : // TODO this is a polyfill for when the underlying type is ResponseCookies
          // We should remove this and unify our cookies types. We could just let this continue to throw lazily
          // but that's already a hard thing to debug so we may as well implement it consistently. The biggest problem with
          // implementing this in this way is the underlying cookie type is a ResponseCookie and not a RequestCookie and so it
          // has extra properties not available on RequestCookie instances.
          polyfilledResponseCookiesIterator.bind(underlyingCookies),
    },
    size: {
      get(): number {
        return underlyingCookies.size
      },
    },
    get: {
      value: underlyingCookies.get.bind(underlyingCookies),
    },
    getAll: {
      value: underlyingCookies.getAll.bind(underlyingCookies),
    },
    has: {
      value: underlyingCookies.has.bind(underlyingCookies),
    },
    set: {
      value: underlyingCookies.set.bind(underlyingCookies),
    },
    delete: {
      value: underlyingCookies.delete.bind(underlyingCookies),
    },
    clear: {
      value:
        // @ts-expect-error clear is defined in RequestCookies implementation but not in the type
        typeof underlyingCookies.clear === 'function'
          ? // @ts-expect-error clear is defined in RequestCookies implementation but not in the type
            underlyingCookies.clear.bind(underlyingCookies)
          : // TODO this is a polyfill for when the underlying type is ResponseCookies
            // We should remove this and unify our cookies types. We could just let this continue to throw lazily
            // but that's already a hard thing to debug so we may as well implement it consistently. The biggest problem with
            // implementing this in this way is the underlying cookie type is a ResponseCookie and not a RequestCookie and so it
            // has extra properties not available on RequestCookie instances.
            polyfilledResponseCookiesClear.bind(underlyingCookies, promise),
    },
    toString: {
      value: underlyingCookies.toString.bind(underlyingCookies),
    },
  } satisfies CookieExtensions)

  return promise
}

function makeUntrackedExoticCookiesWithDevWarnings(
  underlyingCookies: ReadonlyRequestCookies,
  route?: string
): Promise<ReadonlyRequestCookies> {
  const cachedCookies = CachedCookies.get(underlyingCookies)
  if (cachedCookies) {
    return cachedCookies
  }

  const promise = new Promise<ReadonlyRequestCookies>((resolve) =>
    scheduleImmediate(() => resolve(underlyingCookies))
  )
  CachedCookies.set(underlyingCookies, promise)

  Object.defineProperties(promise, {
    [Symbol.iterator]: {
      value: function () {
        const expression = '`...cookies()` or similar iteration'
        syncIODev(route, expression)
        return underlyingCookies[Symbol.iterator]
          ? underlyingCookies[Symbol.iterator].apply(
              underlyingCookies,
              arguments as any
            )
          : // TODO this is a polyfill for when the underlying type is ResponseCookies
            // We should remove this and unify our cookies types. We could just let this continue to throw lazily
            // but that's already a hard thing to debug so we may as well implement it consistently. The biggest problem with
            // implementing this in this way is the underlying cookie type is a ResponseCookie and not a RequestCookie and so it
            // has extra properties not available on RequestCookie instances.
            polyfilledResponseCookiesIterator.call(underlyingCookies)
      },
      writable: false,
    },
    size: {
      get(): number {
        const expression = '`cookies().size`'
        syncIODev(route, expression)
        return underlyingCookies.size
      },
    },
    get: {
      value: function get() {
        let expression: string
        if (arguments.length === 0) {
          expression = '`cookies().get()`'
        } else {
          expression = `\`cookies().get(${describeNameArg(arguments[0])})\``
        }
        syncIODev(route, expression)
        return underlyingCookies.get.apply(underlyingCookies, arguments as any)
      },
      writable: false,
    },
    getAll: {
      value: function getAll() {
        let expression: string
        if (arguments.length === 0) {
          expression = '`cookies().getAll()`'
        } else {
          expression = `\`cookies().getAll(${describeNameArg(arguments[0])})\``
        }
        syncIODev(route, expression)
        return underlyingCookies.getAll.apply(
          underlyingCookies,
          arguments as any
        )
      },
      writable: false,
    },
    has: {
      value: function get() {
        let expression: string
        if (arguments.length === 0) {
          expression = '`cookies().has()`'
        } else {
          expression = `\`cookies().has(${describeNameArg(arguments[0])})\``
        }
        syncIODev(route, expression)
        return underlyingCookies.has.apply(underlyingCookies, arguments as any)
      },
      writable: false,
    },
    set: {
      value: function set() {
        let expression: string
        if (arguments.length === 0) {
          expression = '`cookies().set()`'
        } else {
          const arg = arguments[0]
          if (arg) {
            expression = `\`cookies().set(${describeNameArg(arg)}, ...)\``
          } else {
            expression = '`cookies().set(...)`'
          }
        }
        syncIODev(route, expression)
        return underlyingCookies.set.apply(underlyingCookies, arguments as any)
      },
      writable: false,
    },
    delete: {
      value: function () {
        let expression: string
        if (arguments.length === 0) {
          expression = '`cookies().delete()`'
        } else if (arguments.length === 1) {
          expression = `\`cookies().delete(${describeNameArg(arguments[0])})\``
        } else {
          expression = `\`cookies().delete(${describeNameArg(arguments[0])}, ...)\``
        }
        syncIODev(route, expression)
        return underlyingCookies.delete.apply(
          underlyingCookies,
          arguments as any
        )
      },
      writable: false,
    },
    clear: {
      value: function clear() {
        const expression = '`cookies().clear()`'
        syncIODev(route, expression)
        // @ts-ignore clear is defined in RequestCookies implementation but not in the type
        return typeof underlyingCookies.clear === 'function'
          ? // @ts-ignore clear is defined in RequestCookies implementation but not in the type
            underlyingCookies.clear.apply(underlyingCookies, arguments)
          : // TODO this is a polyfill for when the underlying type is ResponseCookies
            // We should remove this and unify our cookies types. We could just let this continue to throw lazily
            // but that's already a hard thing to debug so we may as well implement it consistently. The biggest problem with
            // implementing this in this way is the underlying cookie type is a ResponseCookie and not a RequestCookie and so it
            // has extra properties not available on RequestCookie instances.
            polyfilledResponseCookiesClear.call(underlyingCookies, promise)
      },
      writable: false,
    },
    toString: {
      value: function toString() {
        const expression = '`cookies().toString()` or implicit casting'
        syncIODev(route, expression)
        return underlyingCookies.toString.apply(
          underlyingCookies,
          arguments as any
        )
      },
      writable: false,
    },
  } satisfies CookieExtensions)

  return promise
}

// Similar to `makeUntrackedExoticCookiesWithDevWarnings`, but just logging the
// sync access without actually defining the cookies properties on the promise.
function makeUntrackedCookiesWithDevWarnings(
  underlyingCookies: ReadonlyRequestCookies,
  route?: string
): Promise<ReadonlyRequestCookies> {
  const cachedCookies = CachedCookies.get(underlyingCookies)
  if (cachedCookies) {
    return cachedCookies
  }

  const promise = new Promise<ReadonlyRequestCookies>((resolve) =>
    scheduleImmediate(() => resolve(underlyingCookies))
  )

  const proxiedPromise = new Proxy(promise, {
    get(target, prop, receiver) {
      switch (prop) {
        case Symbol.iterator: {
          warnForSyncAccess(route, '`...cookies()` or similar iteration')
          break
        }
        case 'size':
        case 'get':
        case 'getAll':
        case 'has':
        case 'set':
        case 'delete':
        case 'clear':
        case 'toString': {
          warnForSyncAccess(route, `\`cookies().${prop}\``)
          break
        }
        default: {
          // We only warn for well-defined properties of the cookies object.
        }
      }

      return ReflectAdapter.get(target, prop, receiver)
    },
  })

  CachedCookies.set(underlyingCookies, proxiedPromise)

  return proxiedPromise
}

function describeNameArg(arg: unknown) {
  return typeof arg === 'object' &&
    arg !== null &&
    typeof (arg as any).name === 'string'
    ? `'${(arg as any).name}'`
    : typeof arg === 'string'
      ? `'${arg}'`
      : '...'
}

function syncIODev(route: string | undefined, expression: string) {
  const workUnitStore = workUnitAsyncStorage.getStore()

  if (workUnitStore) {
    switch (workUnitStore.type) {
      case 'request':
        if (workUnitStore.prerenderPhase === true) {
          // When we're rendering dynamically in dev, we need to advance out of
          // the Prerender environment when we read Request data synchronously.
          trackSynchronousRequestDataAccessInDev(workUnitStore)
        }
        break
      case 'prerender':
      case 'prerender-client':
      case 'prerender-ppr':
      case 'prerender-legacy':
      case 'cache':
      case 'private-cache':
      case 'unstable-cache':
        break
      default:
        workUnitStore satisfies never
    }
  }

  // In all cases we warn normally
  warnForSyncAccess(route, expression)
}

const warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(
  createCookiesAccessError
)

function createCookiesAccessError(
  route: string | undefined,
  expression: string
) {
  const prefix = route ? `Route "${route}" ` : 'This route '
  return new Error(
    `${prefix}used ${expression}. ` +
      `\`cookies()\` should be awaited before using its value. ` +
      `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`
  )
}

function polyfilledResponseCookiesIterator(
  this: ResponseCookies
): ReturnType<ReadonlyRequestCookies[typeof Symbol.iterator]> {
  return this.getAll()
    .map((c) => [c.name, c] as [string, any])
    .values()
}

function polyfilledResponseCookiesClear(
  this: ResponseCookies,
  returnable: Promise<ReadonlyRequestCookies>
): typeof returnable {
  for (const cookie of this.getAll()) {
    this.delete(cookie.name)
  }
  return returnable
}

type CookieExtensions = {
  [K in keyof ReadonlyRequestCookies | 'clear']: unknown
}