File size: 24,777 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
import type {
  EdgeFunctionDefinition,
  MiddlewareManifest,
} from '../../../build/webpack/plugins/middleware-plugin'
import type {
  StatsAsset,
  StatsChunk,
  StatsChunkGroup,
  StatsModule,
  StatsCompilation as WebpackStats,
} from 'webpack'
import type { BuildManifest } from '../../../server/get-page-files'
import type { AppBuildManifest } from '../../../build/webpack/plugins/app-build-manifest-plugin'
import type { PagesManifest } from '../../../build/webpack/plugins/pages-manifest-plugin'
import type { ActionManifest } from '../../../build/webpack/plugins/flight-client-entry-plugin'
import type { NextFontManifest } from '../../../build/webpack/plugins/next-font-manifest-plugin'
import type { REACT_LOADABLE_MANIFEST } from '../constants'
import {
  APP_BUILD_MANIFEST,
  APP_PATHS_MANIFEST,
  BUILD_MANIFEST,
  INTERCEPTION_ROUTE_REWRITE_MANIFEST,
  MIDDLEWARE_BUILD_MANIFEST,
  MIDDLEWARE_MANIFEST,
  NEXT_FONT_MANIFEST,
  PAGES_MANIFEST,
  SERVER_REFERENCE_MANIFEST,
  TURBOPACK_CLIENT_BUILD_MANIFEST,
  TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST,
  WEBPACK_STATS,
} from '../constants'
import { join, posix } from 'path'
import { readFile } from 'fs/promises'
import type { SetupOpts } from '../../../server/lib/router-utils/setup-dev-bundler'
import { deleteCache } from '../../../server/dev/require-cache'
import { writeFileAtomic } from '../../../lib/fs/write-atomic'
import { isInterceptionRouteRewrite } from '../../../lib/generate-interception-routes-rewrites'
import {
  type ClientBuildManifest,
  normalizeRewritesForBuildManifest,
  srcEmptySsgManifest,
  processRoute,
  createEdgeRuntimeManifest,
} from '../../../build/webpack/plugins/build-manifest-plugin'
import getAssetPathFromRoute from '../router/utils/get-asset-path-from-route'
import { getEntryKey, type EntryKey } from './entry-key'
import type { CustomRoutes } from '../../../lib/load-custom-routes'
import { getSortedRoutes } from '../router/utils'
import { existsSync } from 'fs'
import {
  addMetadataIdToRoute,
  addRouteSuffix,
  removeRouteSuffix,
} from '../../../server/dev/turbopack-utils'
import { tryToParsePath } from '../../../lib/try-to-parse-path'
import { safePathToRegexp } from '../router/utils/route-match-utils'
import type { Entrypoints } from '../../../build/swc/types'

interface InstrumentationDefinition {
  files: string[]
  name: 'instrumentation'
}

type TurbopackMiddlewareManifest = MiddlewareManifest & {
  instrumentation?: InstrumentationDefinition
}

type ManifestName =
  | typeof MIDDLEWARE_MANIFEST
  | typeof BUILD_MANIFEST
  | typeof APP_BUILD_MANIFEST
  | typeof PAGES_MANIFEST
  | typeof WEBPACK_STATS
  | typeof APP_PATHS_MANIFEST
  | `${typeof SERVER_REFERENCE_MANIFEST}.json`
  | `${typeof NEXT_FONT_MANIFEST}.json`
  | typeof REACT_LOADABLE_MANIFEST
  | typeof TURBOPACK_CLIENT_BUILD_MANIFEST

const getManifestPath = (
  page: string,
  distDir: string,
  name: ManifestName,
  type: string,
  firstCall: boolean
) => {
  let manifestPath = posix.join(
    distDir,
    `server`,
    type,
    type === 'middleware' || type === 'instrumentation'
      ? ''
      : type === 'app'
        ? page
        : getAssetPathFromRoute(page),
    name
  )

  if (firstCall) {
    const isSitemapRoute = /[\\/]sitemap(.xml)?\/route$/.test(page)
    // Check the ambiguity of /sitemap and /sitemap.xml
    if (isSitemapRoute && !existsSync(manifestPath)) {
      manifestPath = getManifestPath(
        page.replace(/\/sitemap\/route$/, '/sitemap.xml/route'),
        distDir,
        name,
        type,
        false
      )
    }
    // existsSync is faster than using the async version
    if (!existsSync(manifestPath) && page.endsWith('/route')) {
      // TODO: Improve implementation of metadata routes, currently it requires this extra check for the variants of the files that can be written.
      let metadataPage = addRouteSuffix(
        addMetadataIdToRoute(removeRouteSuffix(page))
      )
      manifestPath = getManifestPath(metadataPage, distDir, name, type, false)
    }
  }

  return manifestPath
}

async function readPartialManifest<T>(
  distDir: string,
  name: ManifestName,
  pageName: string,
  type: 'pages' | 'app' | 'middleware' | 'instrumentation' = 'pages'
): Promise<T> {
  const page = pageName
  const manifestPath = getManifestPath(page, distDir, name, type, true)
  return JSON.parse(await readFile(posix.join(manifestPath), 'utf-8')) as T
}

export class TurbopackManifestLoader {
  private actionManifests: Map<EntryKey, ActionManifest> = new Map()
  private appBuildManifests: Map<EntryKey, AppBuildManifest> = new Map()
  private appPathsManifests: Map<EntryKey, PagesManifest> = new Map()
  private buildManifests: Map<EntryKey, BuildManifest> = new Map()
  private clientBuildManifests: Map<EntryKey, ClientBuildManifest> = new Map()
  private fontManifests: Map<EntryKey, NextFontManifest> = new Map()
  private middlewareManifests: Map<EntryKey, TurbopackMiddlewareManifest> =
    new Map()
  private pagesManifests: Map<string, PagesManifest> = new Map()
  private webpackStats: Map<EntryKey, WebpackStats> = new Map()
  private encryptionKey: string

  private readonly distDir: string
  private readonly buildId: string

  constructor({
    distDir,
    buildId,
    encryptionKey,
  }: {
    buildId: string
    distDir: string
    encryptionKey: string
  }) {
    this.distDir = distDir
    this.buildId = buildId
    this.encryptionKey = encryptionKey
  }

  delete(key: EntryKey) {
    this.actionManifests.delete(key)
    this.appBuildManifests.delete(key)
    this.appPathsManifests.delete(key)
    this.buildManifests.delete(key)
    this.clientBuildManifests.delete(key)
    this.fontManifests.delete(key)
    this.middlewareManifests.delete(key)
    this.pagesManifests.delete(key)
    this.webpackStats.delete(key)
  }

  async loadActionManifest(pageName: string): Promise<void> {
    this.actionManifests.set(
      getEntryKey('app', 'server', pageName),
      await readPartialManifest(
        this.distDir,
        `${SERVER_REFERENCE_MANIFEST}.json`,
        pageName,
        'app'
      )
    )
  }

  private async mergeActionManifests(manifests: Iterable<ActionManifest>) {
    type ActionEntries = ActionManifest['edge' | 'node']
    const manifest: ActionManifest = {
      node: {},
      edge: {},
      encryptionKey: this.encryptionKey,
    }

    function mergeActionIds(
      actionEntries: ActionEntries,
      other: ActionEntries
    ): void {
      for (const key in other) {
        const action = (actionEntries[key] ??= {
          workers: {},
          layer: {},
        })
        Object.assign(action.workers, other[key].workers)
        Object.assign(action.layer, other[key].layer)
      }
    }

    for (const m of manifests) {
      mergeActionIds(manifest.node, m.node)
      mergeActionIds(manifest.edge, m.edge)
    }
    for (const key in manifest.node) {
      const entry = manifest.node[key]
      entry.workers = sortObjectByKey(entry.workers)
      entry.layer = sortObjectByKey(entry.layer)
    }
    for (const key in manifest.edge) {
      const entry = manifest.edge[key]
      entry.workers = sortObjectByKey(entry.workers)
      entry.layer = sortObjectByKey(entry.layer)
    }

    return manifest
  }

  private async writeActionManifest(): Promise<void> {
    const actionManifest = await this.mergeActionManifests(
      this.actionManifests.values()
    )
    const actionManifestJsonPath = join(
      this.distDir,
      'server',
      `${SERVER_REFERENCE_MANIFEST}.json`
    )
    const actionManifestJsPath = join(
      this.distDir,
      'server',
      `${SERVER_REFERENCE_MANIFEST}.js`
    )
    const json = JSON.stringify(actionManifest, null, 2)
    deleteCache(actionManifestJsonPath)
    deleteCache(actionManifestJsPath)
    await writeFileAtomic(actionManifestJsonPath, json)
    await writeFileAtomic(
      actionManifestJsPath,
      `self.__RSC_SERVER_MANIFEST=${JSON.stringify(json)}`
    )
  }

  async loadAppBuildManifest(pageName: string): Promise<void> {
    this.appBuildManifests.set(
      getEntryKey('app', 'server', pageName),
      await readPartialManifest(
        this.distDir,
        APP_BUILD_MANIFEST,
        pageName,
        'app'
      )
    )
  }

  private mergeAppBuildManifests(manifests: Iterable<AppBuildManifest>) {
    const manifest: AppBuildManifest = {
      pages: {},
    }
    for (const m of manifests) {
      Object.assign(manifest.pages, m.pages)
    }
    manifest.pages = sortObjectByKey(manifest.pages)
    return manifest
  }

  private async writeAppBuildManifest(): Promise<void> {
    const appBuildManifest = this.mergeAppBuildManifests(
      this.appBuildManifests.values()
    )
    const appBuildManifestPath = join(this.distDir, APP_BUILD_MANIFEST)
    deleteCache(appBuildManifestPath)
    await writeFileAtomic(
      appBuildManifestPath,
      JSON.stringify(appBuildManifest, null, 2)
    )
  }

  async loadAppPathsManifest(pageName: string): Promise<void> {
    this.appPathsManifests.set(
      getEntryKey('app', 'server', pageName),
      await readPartialManifest(
        this.distDir,
        APP_PATHS_MANIFEST,
        pageName,
        'app'
      )
    )
  }

  private async writeAppPathsManifest(): Promise<void> {
    const appPathsManifest = this.mergePagesManifests(
      this.appPathsManifests.values()
    )
    const appPathsManifestPath = join(
      this.distDir,
      'server',
      APP_PATHS_MANIFEST
    )
    deleteCache(appPathsManifestPath)
    await writeFileAtomic(
      appPathsManifestPath,
      JSON.stringify(appPathsManifest, null, 2)
    )
  }

  private async writeWebpackStats(): Promise<void> {
    const webpackStats = this.mergeWebpackStats(this.webpackStats.values())
    const path = join(this.distDir, 'server', WEBPACK_STATS)
    deleteCache(path)
    await writeFileAtomic(path, JSON.stringify(webpackStats, null, 2))
  }

  async loadBuildManifest(
    pageName: string,
    type: 'app' | 'pages' = 'pages'
  ): Promise<void> {
    this.buildManifests.set(
      getEntryKey(type, 'server', pageName),
      await readPartialManifest(this.distDir, BUILD_MANIFEST, pageName, type)
    )
  }

  async loadClientBuildManifest(
    pageName: string,
    type: 'app' | 'pages' = 'pages'
  ): Promise<void> {
    this.clientBuildManifests.set(
      getEntryKey(type, 'server', pageName),
      await readPartialManifest(
        this.distDir,
        TURBOPACK_CLIENT_BUILD_MANIFEST,
        pageName,
        type
      )
    )
  }

  async loadWebpackStats(
    pageName: string,
    type: 'app' | 'pages' = 'pages'
  ): Promise<void> {
    this.webpackStats.set(
      getEntryKey(type, 'client', pageName),
      await readPartialManifest(this.distDir, WEBPACK_STATS, pageName, type)
    )
  }

  private mergeWebpackStats(statsFiles: Iterable<WebpackStats>): WebpackStats {
    const entrypoints: Record<string, StatsChunkGroup> = {}
    const assets: Map<string, StatsAsset> = new Map()
    const chunks: Map<string | number, StatsChunk> = new Map()
    const modules: Map<string | number, StatsModule> = new Map()

    for (const statsFile of statsFiles) {
      if (statsFile.entrypoints) {
        for (const [k, v] of Object.entries(statsFile.entrypoints)) {
          if (!entrypoints[k]) {
            entrypoints[k] = v
          }
        }
      }

      if (statsFile.assets) {
        for (const asset of statsFile.assets) {
          if (!assets.has(asset.name)) {
            assets.set(asset.name, asset)
          }
        }
      }

      if (statsFile.chunks) {
        for (const chunk of statsFile.chunks) {
          if (!chunks.has(chunk.id!)) {
            chunks.set(chunk.id!, chunk)
          }
        }
      }

      if (statsFile.modules) {
        for (const module of statsFile.modules) {
          const id = module.id
          if (id != null) {
            // Merge the chunk list for the module. This can vary across endpoints.
            const existing = modules.get(id)
            if (existing == null) {
              modules.set(id, module)
            } else if (module.chunks != null && existing.chunks != null) {
              for (const chunk of module.chunks) {
                if (!existing.chunks.includes(chunk)) {
                  existing.chunks.push(chunk)
                }
              }
            }
          }
        }
      }
    }

    return {
      version: 'Turbopack',
      entrypoints,
      assets: [...assets.values()],
      chunks: [...chunks.values()],
      modules: [...modules.values()],
    }
  }

  private mergeBuildManifests(manifests: Iterable<BuildManifest>) {
    const manifest: Partial<BuildManifest> & Pick<BuildManifest, 'pages'> = {
      pages: {
        '/_app': [],
      },
      // Something in next.js depends on these to exist even for app dir rendering
      devFiles: [],
      ampDevFiles: [],
      polyfillFiles: [],
      lowPriorityFiles: [
        `static/${this.buildId}/_ssgManifest.js`,
        `static/${this.buildId}/_buildManifest.js`,
      ],
      rootMainFiles: [],
      ampFirstPages: [],
    }
    for (const m of manifests) {
      Object.assign(manifest.pages, m.pages)
      if (m.rootMainFiles.length) manifest.rootMainFiles = m.rootMainFiles
      // polyfillFiles should always be the same, so we can overwrite instead of actually merging
      if (m.polyfillFiles.length) manifest.polyfillFiles = m.polyfillFiles
    }
    manifest.pages = sortObjectByKey(manifest.pages) as BuildManifest['pages']
    return manifest
  }

  private mergeClientBuildManifests(
    rewrites: CustomRoutes['rewrites'],
    manifests: Iterable<ClientBuildManifest>,
    sortedPageKeys: string[]
  ): ClientBuildManifest {
    const manifest = {
      __rewrites: normalizeRewritesForBuildManifest(rewrites) as any,
      sortedPages: sortedPageKeys,
    }
    for (const m of manifests) {
      Object.assign(manifest, m)
    }
    return sortObjectByKey(manifest)
  }

  private async writeBuildManifest(
    entrypoints: Entrypoints,
    devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined,
    productionRewrites: CustomRoutes['rewrites'] | undefined
  ): Promise<void> {
    const rewrites = productionRewrites ?? {
      ...devRewrites,
      beforeFiles: (devRewrites?.beforeFiles ?? []).map(processRoute),
      afterFiles: (devRewrites?.afterFiles ?? []).map(processRoute),
      fallback: (devRewrites?.fallback ?? []).map(processRoute),
    }
    const buildManifest = this.mergeBuildManifests(this.buildManifests.values())
    const buildManifestPath = join(this.distDir, BUILD_MANIFEST)
    const middlewareBuildManifestPath = join(
      this.distDir,
      'server',
      `${MIDDLEWARE_BUILD_MANIFEST}.js`
    )
    const interceptionRewriteManifestPath = join(
      this.distDir,
      'server',
      `${INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js`
    )
    deleteCache(buildManifestPath)
    deleteCache(middlewareBuildManifestPath)
    deleteCache(interceptionRewriteManifestPath)
    await writeFileAtomic(
      buildManifestPath,
      JSON.stringify(buildManifest, null, 2)
    )
    await writeFileAtomic(
      middlewareBuildManifestPath,
      // we use globalThis here because middleware can be node
      // which doesn't have "self"
      createEdgeRuntimeManifest(buildManifest)
    )

    const interceptionRewrites = JSON.stringify(
      rewrites.beforeFiles.filter(isInterceptionRouteRewrite)
    )

    await writeFileAtomic(
      interceptionRewriteManifestPath,
      `self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST=${JSON.stringify(
        interceptionRewrites
      )};`
    )

    const pagesKeys = [...entrypoints.page.keys()]
    if (entrypoints.global.app) {
      pagesKeys.push('/_app')
    }
    if (entrypoints.global.error) {
      pagesKeys.push('/_error')
    }

    const sortedPageKeys = getSortedRoutes(pagesKeys)
    const clientBuildManifest = this.mergeClientBuildManifests(
      rewrites,
      this.clientBuildManifests.values(),
      sortedPageKeys
    )
    const clientBuildManifestJs = `self.__BUILD_MANIFEST = ${JSON.stringify(
      clientBuildManifest,
      null,
      2
    )};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`
    await writeFileAtomic(
      join(this.distDir, 'static', this.buildId, '_buildManifest.js'),
      clientBuildManifestJs
    )
    await writeFileAtomic(
      join(this.distDir, 'static', this.buildId, '_ssgManifest.js'),
      srcEmptySsgManifest
    )
  }

  private async writeClientMiddlewareManifest(): Promise<void> {
    const middlewareManifest = this.mergeMiddlewareManifests(
      this.middlewareManifests.values()
    )

    const matchers = middlewareManifest?.middleware['/']?.matchers || []

    const clientMiddlewareManifestPath = join(
      this.distDir,
      'static',
      this.buildId,
      `${TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST}`
    )
    deleteCache(clientMiddlewareManifestPath)
    await writeFileAtomic(
      clientMiddlewareManifestPath,
      JSON.stringify(matchers, null, 2)
    )
  }

  private async writeFallbackBuildManifest(): Promise<void> {
    const fallbackBuildManifest = this.mergeBuildManifests(
      [
        this.buildManifests.get(getEntryKey('pages', 'server', '_app')),
        this.buildManifests.get(getEntryKey('pages', 'server', '_error')),
      ].filter(Boolean) as BuildManifest[]
    )
    const fallbackBuildManifestPath = join(
      this.distDir,
      `fallback-${BUILD_MANIFEST}`
    )
    deleteCache(fallbackBuildManifestPath)
    await writeFileAtomic(
      fallbackBuildManifestPath,
      JSON.stringify(fallbackBuildManifest, null, 2)
    )
  }

  async loadFontManifest(
    pageName: string,
    type: 'app' | 'pages' = 'pages'
  ): Promise<void> {
    this.fontManifests.set(
      getEntryKey(type, 'server', pageName),
      await readPartialManifest(
        this.distDir,
        `${NEXT_FONT_MANIFEST}.json`,
        pageName,
        type
      )
    )
  }

  private mergeFontManifests(manifests: Iterable<NextFontManifest>) {
    const manifest: NextFontManifest = {
      app: {},
      appUsingSizeAdjust: false,
      pages: {},
      pagesUsingSizeAdjust: false,
    }
    for (const m of manifests) {
      Object.assign(manifest.app, m.app)
      Object.assign(manifest.pages, m.pages)

      manifest.appUsingSizeAdjust =
        manifest.appUsingSizeAdjust || m.appUsingSizeAdjust
      manifest.pagesUsingSizeAdjust =
        manifest.pagesUsingSizeAdjust || m.pagesUsingSizeAdjust
    }
    manifest.app = sortObjectByKey(manifest.app)
    manifest.pages = sortObjectByKey(manifest.pages)
    return manifest
  }

  private async writeNextFontManifest(): Promise<void> {
    const fontManifest = this.mergeFontManifests(this.fontManifests.values())
    const json = JSON.stringify(fontManifest, null, 2)

    const fontManifestJsonPath = join(
      this.distDir,
      'server',
      `${NEXT_FONT_MANIFEST}.json`
    )
    const fontManifestJsPath = join(
      this.distDir,
      'server',
      `${NEXT_FONT_MANIFEST}.js`
    )
    deleteCache(fontManifestJsonPath)
    deleteCache(fontManifestJsPath)
    await writeFileAtomic(fontManifestJsonPath, json)
    await writeFileAtomic(
      fontManifestJsPath,
      `self.__NEXT_FONT_MANIFEST=${JSON.stringify(json)}`
    )
  }

  /**
   * @returns If the manifest was written or not
   */
  async loadMiddlewareManifest(
    pageName: string,
    type: 'pages' | 'app' | 'middleware' | 'instrumentation'
  ): Promise<boolean> {
    const middlewareManifestPath = getManifestPath(
      pageName,
      this.distDir,
      MIDDLEWARE_MANIFEST,
      type,
      true
    )

    // middlewareManifest is actually "edge manifest" and not all routes are edge runtime. If it is not written we skip it.
    if (!existsSync(middlewareManifestPath)) {
      return false
    }

    this.middlewareManifests.set(
      getEntryKey(
        type === 'middleware' || type === 'instrumentation' ? 'root' : type,
        'server',
        pageName
      ),
      await readPartialManifest(
        this.distDir,
        MIDDLEWARE_MANIFEST,
        pageName,
        type
      )
    )

    return true
  }

  getMiddlewareManifest(key: EntryKey) {
    return this.middlewareManifests.get(key)
  }

  deleteMiddlewareManifest(key: EntryKey) {
    return this.middlewareManifests.delete(key)
  }

  private mergeMiddlewareManifests(
    manifests: Iterable<TurbopackMiddlewareManifest>
  ): MiddlewareManifest {
    const manifest: MiddlewareManifest = {
      version: 3,
      middleware: {},
      sortedMiddleware: [],
      functions: {},
    }
    let instrumentation: InstrumentationDefinition | undefined = undefined
    for (const m of manifests) {
      Object.assign(manifest.functions, m.functions)
      Object.assign(manifest.middleware, m.middleware)
      if (m.instrumentation) {
        instrumentation = m.instrumentation
      }
    }
    manifest.functions = sortObjectByKey(manifest.functions)
    manifest.middleware = sortObjectByKey(manifest.middleware)
    const updateFunctionDefinition = (
      fun: EdgeFunctionDefinition
    ): EdgeFunctionDefinition => {
      return {
        ...fun,
        files: [...(instrumentation?.files ?? []), ...fun.files],
      }
    }
    for (const key of Object.keys(manifest.middleware)) {
      const value = manifest.middleware[key]
      manifest.middleware[key] = updateFunctionDefinition(value)
    }
    for (const key of Object.keys(manifest.functions)) {
      const value = manifest.functions[key]
      manifest.functions[key] = updateFunctionDefinition(value)
    }
    for (const fun of Object.values(manifest.functions).concat(
      Object.values(manifest.middleware)
    )) {
      for (const matcher of fun.matchers) {
        if (!matcher.regexp) {
          matcher.regexp = safePathToRegexp(matcher.originalSource, [], {
            delimiter: '/',
            sensitive: false,
            strict: true,
          }).source.replaceAll('\\/', '/')
        }
      }
    }
    manifest.sortedMiddleware = Object.keys(manifest.middleware)

    return manifest
  }

  private async writeMiddlewareManifest(): Promise<void> {
    const middlewareManifest = this.mergeMiddlewareManifests(
      this.middlewareManifests.values()
    )

    // Normalize regexes as it uses path-to-regexp
    for (const key in middlewareManifest.middleware) {
      middlewareManifest.middleware[key].matchers.forEach((matcher) => {
        if (!matcher.regexp.startsWith('^')) {
          const parsedPage = tryToParsePath(matcher.regexp)
          if (parsedPage.error || !parsedPage.regexStr) {
            throw new Error(`Invalid source: ${matcher.regexp}`)
          }
          matcher.regexp = parsedPage.regexStr
        }
      })
    }

    const middlewareManifestPath = join(
      this.distDir,
      'server',
      MIDDLEWARE_MANIFEST
    )
    deleteCache(middlewareManifestPath)
    await writeFileAtomic(
      middlewareManifestPath,
      JSON.stringify(middlewareManifest, null, 2)
    )
  }

  async loadPagesManifest(pageName: string): Promise<void> {
    this.pagesManifests.set(
      getEntryKey('pages', 'server', pageName),
      await readPartialManifest(this.distDir, PAGES_MANIFEST, pageName)
    )
  }

  private mergePagesManifests(manifests: Iterable<PagesManifest>) {
    const manifest: PagesManifest = {}
    for (const m of manifests) {
      Object.assign(manifest, m)
    }
    return sortObjectByKey(manifest)
  }

  private async writePagesManifest(): Promise<void> {
    const pagesManifest = this.mergePagesManifests(this.pagesManifests.values())
    const pagesManifestPath = join(this.distDir, 'server', PAGES_MANIFEST)
    deleteCache(pagesManifestPath)
    await writeFileAtomic(
      pagesManifestPath,
      JSON.stringify(pagesManifest, null, 2)
    )
  }

  async writeManifests({
    devRewrites,
    productionRewrites,
    entrypoints,
  }: {
    devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined
    productionRewrites: CustomRoutes['rewrites'] | undefined
    entrypoints: Entrypoints
  }) {
    await this.writeActionManifest()
    await this.writeAppBuildManifest()
    await this.writeAppPathsManifest()
    await this.writeBuildManifest(entrypoints, devRewrites, productionRewrites)
    await this.writeFallbackBuildManifest()
    await this.writeMiddlewareManifest()
    await this.writeClientMiddlewareManifest()
    await this.writeNextFontManifest()
    await this.writePagesManifest()

    if (process.env.TURBOPACK_STATS != null) {
      await this.writeWebpackStats()
    }
  }
}

function sortObjectByKey(obj: Record<string, any>) {
  return Object.keys(obj)
    .sort()
    .reduce(
      (acc, key) => {
        acc[key] = obj[key]
        return acc
      },
      {} as Record<string, any>
    )
}