File size: 21,141 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
import { Span } from '../trace'
import type { NextConfigComplete } from '../server/config-shared'

import {
  TRACE_IGNORES,
  type BuildTraceContext,
  getFilesMapFromReasons,
} from './webpack/plugins/next-trace-entrypoints-plugin'

import path from 'path'
import fs from 'fs/promises'
import { nonNullable } from '../lib/non-nullable'
import * as ciEnvironment from '../server/ci-info'
import debugOriginal from 'next/dist/compiled/debug'
import picomatch from 'next/dist/compiled/picomatch'
import { defaultOverrides } from '../server/require-hook'
import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import isError from '../lib/is-error'
import type { NodeFileTraceReasons } from '@vercel/nft'
import type { RoutesUsingEdgeRuntime } from './utils'

const debug = debugOriginal('next:build:build-traces')

function shouldIgnore(
  file: string,
  serverIgnoreFn: (file: string) => boolean,
  reasons: NodeFileTraceReasons,
  cachedIgnoreFiles: Map<string, boolean>,
  children: Set<string> = new Set()
) {
  if (cachedIgnoreFiles.has(file)) {
    return cachedIgnoreFiles.get(file)
  }

  if (serverIgnoreFn(file)) {
    cachedIgnoreFiles.set(file, true)
    return true
  }
  children.add(file)

  const reason = reasons.get(file)
  if (!reason || reason.parents.size === 0 || reason.type.includes('initial')) {
    cachedIgnoreFiles.set(file, false)
    return false
  }

  // if all parents are ignored the child file
  // should be ignored as well
  let allParentsIgnored = true

  for (const parent of reason.parents.values()) {
    if (!children.has(parent)) {
      children.add(parent)
      if (
        !shouldIgnore(
          parent,
          serverIgnoreFn,
          reasons,
          cachedIgnoreFiles,
          children
        )
      ) {
        allParentsIgnored = false
        break
      }
    }
  }

  cachedIgnoreFiles.set(file, allParentsIgnored)
  return allParentsIgnored
}

export async function collectBuildTraces({
  dir,
  config,
  distDir,
  edgeRuntimeRoutes,
  staticPages,
  nextBuildSpan = new Span({ name: 'build' }),
  hasSsrAmpPages,
  buildTraceContext,
  outputFileTracingRoot,
  isTurbopack,
}: {
  dir: string
  distDir: string
  staticPages: string[]
  hasSsrAmpPages: boolean
  outputFileTracingRoot: string
  // pageInfos is serialized when this function runs in a worker.
  edgeRuntimeRoutes: RoutesUsingEdgeRuntime
  nextBuildSpan?: Span
  config: NextConfigComplete
  buildTraceContext?: BuildTraceContext
  isTurbopack: boolean
}) {
  const startTime = Date.now()
  debug('starting build traces')

  const { outputFileTracingIncludes = {}, outputFileTracingExcludes = {} } =
    config
  const excludeGlobKeys = Object.keys(outputFileTracingExcludes)
  const includeGlobKeys = Object.keys(outputFileTracingIncludes)

  await nextBuildSpan
    .traceChild('node-file-trace-build', {
      isTurbotrace: 'false', // TODO(arlyon): remove this
    })
    .traceAsyncFn(async () => {
      const nextServerTraceOutput = path.join(
        distDir,
        'next-server.js.nft.json'
      )
      const nextMinimalTraceOutput = path.join(
        distDir,
        'next-minimal-server.js.nft.json'
      )
      const root = outputFileTracingRoot

      // Under standalone mode, we need to trace the extra IPC server and
      // worker files.
      const isStandalone = config.output === 'standalone'
      const sharedEntriesSet = Object.keys(defaultOverrides).map((value) =>
        require.resolve(value, {
          paths: [require.resolve('next/dist/server/require-hook')],
        })
      )

      const { cacheHandler } = config
      const { cacheHandlers } = config.experimental

      // ensure we trace any dependencies needed for custom
      // incremental cache handler
      if (cacheHandler) {
        sharedEntriesSet.push(
          require.resolve(
            path.isAbsolute(cacheHandler)
              ? cacheHandler
              : path.join(dir, cacheHandler)
          )
        )
      }

      if (cacheHandlers) {
        for (const handlerPath of Object.values(cacheHandlers)) {
          if (handlerPath) {
            sharedEntriesSet.push(
              require.resolve(
                path.isAbsolute(handlerPath)
                  ? handlerPath
                  : path.join(dir, handlerPath)
              )
            )
          }
        }
      }

      const serverEntries = [
        ...sharedEntriesSet,
        ...(isStandalone
          ? [
              require.resolve('next/dist/server/lib/start-server'),
              require.resolve('next/dist/server/next'),
              require.resolve('next/dist/server/require-hook'),
            ]
          : []),
        require.resolve('next/dist/server/next-server'),
      ].filter(Boolean) as string[]

      const minimalServerEntries = [
        ...sharedEntriesSet,
        require.resolve('next/dist/compiled/next-server/server.runtime.prod'),
      ].filter(Boolean)

      const additionalIgnores = new Set<string>()

      for (const glob of excludeGlobKeys) {
        if (picomatch(glob)('next-server')) {
          outputFileTracingExcludes[glob].forEach((exclude) => {
            additionalIgnores.add(exclude)
          })
        }
      }

      const makeIgnoreFn = (ignores: string[]) => {
        // pre compile the ignore globs
        const isMatch = picomatch(ignores, {
          contains: true,
          dot: true,
        })

        return (pathname: string) => {
          if (path.isAbsolute(pathname) && !pathname.startsWith(root)) {
            return true
          }

          return isMatch(pathname)
        }
      }

      const sharedIgnores = [
        '**/next/dist/compiled/next-server/**/*.dev.js',
        ...(isStandalone ? [] : ['**/next/dist/compiled/jest-worker/**/*']),
        '**/next/dist/compiled/webpack/*',
        '**/node_modules/webpack5/**/*',
        '**/next/dist/server/lib/route-resolver*',
        'next/dist/compiled/semver/semver/**/*.js',

        ...(ciEnvironment.hasNextSupport
          ? [
              // only ignore image-optimizer code when
              // this is being handled outside of next-server
              '**/next/dist/server/image-optimizer.js',
            ]
          : []),

        ...(!hasSsrAmpPages
          ? ['**/next/dist/compiled/@ampproject/toolbox-optimizer/**/*']
          : []),

        ...(isStandalone ? [] : TRACE_IGNORES),
        ...additionalIgnores,
      ]

      const sharedIgnoresFn = makeIgnoreFn(sharedIgnores)

      const serverIgnores = [
        ...sharedIgnores,
        '**/node_modules/react{,-dom,-dom-server-turbopack}/**/*.development.js',
        '**/*.d.ts',
        '**/*.map',
        '**/next/dist/pages/**/*',
        ...(ciEnvironment.hasNextSupport
          ? ['**/node_modules/sharp/**/*', '**/@img/sharp-libvips*/**/*']
          : []),
      ].filter(nonNullable)
      const serverIgnoreFn = makeIgnoreFn(serverIgnores)

      const minimalServerIgnores = [
        ...serverIgnores,
        '**/next/dist/compiled/edge-runtime/**/*',
        '**/next/dist/server/web/sandbox/**/*',
        '**/next/dist/server/post-process.js',
      ]
      const minimalServerIgnoreFn = makeIgnoreFn(minimalServerIgnores)

      const routesIgnores = [
        ...sharedIgnores,
        // server chunks are provided via next-trace-entrypoints-plugin plugin
        // as otherwise all chunks are traced here and included for all pages
        // whether they are needed or not
        '**/.next/server/chunks/**',
        '**/next/dist/server/optimize-amp.js',
        '**/next/dist/server/post-process.js',
      ].filter(nonNullable)

      const routeIgnoreFn = makeIgnoreFn(routesIgnores)

      const serverTracedFiles = new Set<string>()
      const minimalServerTracedFiles = new Set<string>()

      function addToTracedFiles(base: string, file: string, dest: Set<string>) {
        dest.add(
          path.relative(distDir, path.join(base, file)).replace(/\\/g, '/')
        )
      }

      if (isStandalone) {
        addToTracedFiles(
          '',
          require.resolve('next/dist/compiled/jest-worker/processChild'),
          serverTracedFiles
        )
        addToTracedFiles(
          '',
          require.resolve('next/dist/compiled/jest-worker/threadChild'),
          serverTracedFiles
        )
      }

      if (isTurbopack) {
        addToTracedFiles(distDir, './package.json', serverTracedFiles)
        addToTracedFiles(distDir, './package.json', minimalServerTracedFiles)
      }

      {
        const chunksToTrace: string[] = [
          ...(buildTraceContext?.chunksTrace?.action.input || []),
          ...serverEntries,
          ...minimalServerEntries,
        ]
        const result = await nodeFileTrace(chunksToTrace, {
          base: outputFileTracingRoot,
          processCwd: dir,
          mixedModules: true,
          async readFile(p) {
            try {
              return await fs.readFile(p, 'utf8')
            } catch (e) {
              if (isError(e) && (e.code === 'ENOENT' || e.code === 'EISDIR')) {
                // since tracing runs in parallel with static generation server
                // files might be removed from that step so tolerate ENOENT
                // errors gracefully
                return ''
              }
              throw e
            }
          },
          async readlink(p) {
            try {
              return await fs.readlink(p)
            } catch (e) {
              if (
                isError(e) &&
                (e.code === 'EINVAL' ||
                  e.code === 'ENOENT' ||
                  e.code === 'UNKNOWN')
              ) {
                return null
              }
              throw e
            }
          },
          async stat(p) {
            try {
              return await fs.stat(p)
            } catch (e) {
              if (isError(e) && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) {
                return null
              }
              throw e
            }
          },
          // handle shared ignores at top-level as it
          // avoids over-tracing when we don't need to
          // and speeds up total trace time
          ignore(p) {
            if (sharedIgnoresFn(p)) {
              return true
            }

            // if a chunk is attempting to be traced that isn't
            // in our initial list we need to ignore it to prevent
            // over tracing as webpack needs to be the source of
            // truth for which chunks should be included for each entry
            if (
              p.includes('.next/server/chunks') &&
              !chunksToTrace.includes(path.join(outputFileTracingRoot, p))
            ) {
              return true
            }
            return false
          },
        })
        const reasons = result.reasons
        const fileList = result.fileList
        for (const file of result.esmFileList) {
          fileList.add(file)
        }

        const parentFilesMap = getFilesMapFromReasons(fileList, reasons)
        const cachedLookupIgnore = new Map<string, boolean>()
        const cachedLookupIgnoreMinimal = new Map<string, boolean>()

        for (const [entries, tracedFiles] of [
          [serverEntries, serverTracedFiles],
          [minimalServerEntries, minimalServerTracedFiles],
        ] as Array<[string[], Set<string>]>) {
          for (const file of entries) {
            const curFiles = [
              ...(parentFilesMap
                .get(path.relative(outputFileTracingRoot, file))
                ?.keys() || []),
            ]
            tracedFiles.add(path.relative(distDir, file).replace(/\\/g, '/'))

            for (const curFile of curFiles || []) {
              const filePath = path.join(outputFileTracingRoot, curFile)

              if (
                !shouldIgnore(
                  curFile,
                  tracedFiles === minimalServerTracedFiles
                    ? minimalServerIgnoreFn
                    : serverIgnoreFn,
                  reasons,
                  tracedFiles === minimalServerTracedFiles
                    ? cachedLookupIgnoreMinimal
                    : cachedLookupIgnore
                )
              ) {
                tracedFiles.add(
                  path.relative(distDir, filePath).replace(/\\/g, '/')
                )
              }
            }
          }
        }

        const { entryNameFilesMap } = buildTraceContext?.chunksTrace || {}

        const cachedLookupIgnoreRoutes = new Map<string, boolean>()

        await Promise.all(
          [
            ...(entryNameFilesMap
              ? Object.entries(entryNameFilesMap)
              : new Map()),
          ].map(async ([entryName, entryNameFiles]) => {
            const isApp = entryName.startsWith('app/')
            const isPages = entryName.startsWith('pages/')
            let route = entryName
            if (isApp) {
              route = normalizeAppPath(route.substring('app'.length))
            }
            if (isPages) {
              route = normalizePagePath(route.substring('pages'.length))
            }

            // we don't need to trace for automatically statically optimized
            // pages as they don't have server bundles, note there is
            // the caveat with flying shuttle mode as it needs this for
            // detecting changed entries
            if (staticPages.includes(route)) {
              return
            }
            const entryOutputPath = path.join(
              distDir,
              'server',
              `${entryName}.js`
            )
            const traceOutputPath = `${entryOutputPath}.nft.json`
            const existingTrace = JSON.parse(
              await fs.readFile(traceOutputPath, 'utf8')
            ) as {
              version: number
              files: string[]
              fileHashes: Record<string, string>
            }
            const traceOutputDir = path.dirname(traceOutputPath)
            const curTracedFiles = new Set<string>()

            for (const file of [...entryNameFiles, entryOutputPath]) {
              const curFiles = [
                ...(parentFilesMap
                  .get(path.relative(outputFileTracingRoot, file))
                  ?.keys() || []),
              ]
              for (const curFile of curFiles || []) {
                if (
                  !shouldIgnore(
                    curFile,
                    routeIgnoreFn,
                    reasons,
                    cachedLookupIgnoreRoutes
                  )
                ) {
                  const filePath = path.join(outputFileTracingRoot, curFile)
                  const outputFile = path
                    .relative(traceOutputDir, filePath)
                    .replace(/\\/g, '/')
                  curTracedFiles.add(outputFile)
                }
              }
            }

            for (const file of existingTrace.files || []) {
              curTracedFiles.add(file)
            }

            await fs.writeFile(
              traceOutputPath,
              JSON.stringify({
                ...existingTrace,
                files: [...curTracedFiles].sort(),
              })
            )
          })
        )
      }

      const moduleTypes = ['app-page', 'pages']

      for (const type of moduleTypes) {
        const modulePath = require.resolve(
          `next/dist/server/route-modules/${type}/module.compiled`
        )
        const relativeModulePath = path.relative(root, modulePath)

        const contextDir = path.join(
          path.dirname(modulePath),
          'vendored',
          'contexts'
        )

        for (const item of await fs.readdir(contextDir)) {
          const itemPath = path.relative(root, path.join(contextDir, item))
          if (!serverIgnoreFn(itemPath)) {
            addToTracedFiles(root, itemPath, serverTracedFiles)
            addToTracedFiles(root, itemPath, minimalServerTracedFiles)
          }
        }
        addToTracedFiles(root, relativeModulePath, serverTracedFiles)
        addToTracedFiles(root, relativeModulePath, minimalServerTracedFiles)
      }

      const serverTracedFilesSorted = Array.from(serverTracedFiles)
      serverTracedFilesSorted.sort()
      const minimalServerTracedFilesSorted = Array.from(
        minimalServerTracedFiles
      )
      minimalServerTracedFilesSorted.sort()

      await Promise.all([
        fs.writeFile(
          nextServerTraceOutput,
          JSON.stringify({
            version: 1,
            files: serverTracedFilesSorted,
          } as {
            version: number
            files: string[]
          })
        ),
        fs.writeFile(
          nextMinimalTraceOutput,
          JSON.stringify({
            version: 1,
            files: minimalServerTracedFilesSorted,
          } as {
            version: number
            files: string[]
          })
        ),
      ])
    })

  // apply outputFileTracingIncludes/outputFileTracingExcludes after runTurbotrace
  const includeExcludeSpan = nextBuildSpan.traceChild('apply-include-excludes')
  await includeExcludeSpan.traceAsyncFn(async () => {
    const globOrig =
      require('next/dist/compiled/glob') as typeof import('next/dist/compiled/glob')
    const glob = (pattern: string): Promise<string[]> => {
      return new Promise((resolve, reject) => {
        globOrig(
          pattern,
          { cwd: dir, nodir: true, dot: true },
          (err, files) => {
            if (err) {
              return reject(err)
            }
            resolve(files)
          }
        )
      })
    }

    const { entryNameFilesMap } = buildTraceContext?.chunksTrace || {}

    await Promise.all(
      [
        ...(entryNameFilesMap ? Object.entries(entryNameFilesMap) : new Map()),
      ].map(async ([entryName]) => {
        const isApp = entryName.startsWith('app/')
        const isPages = entryName.startsWith('pages/')
        let route = entryName
        if (isApp) {
          route = normalizeAppPath(entryName)
        }
        if (isPages) {
          route = normalizePagePath(entryName)
        }

        if (staticPages.includes(route)) {
          return
        }

        // edge routes have no trace files
        if (edgeRuntimeRoutes.hasOwnProperty(route)) {
          return
        }

        const combinedIncludes = new Set<string>()
        const combinedExcludes = new Set<string>()
        for (const curGlob of includeGlobKeys) {
          const isMatch = picomatch(curGlob, { dot: true, contains: true })
          if (isMatch(route)) {
            for (const include of outputFileTracingIncludes[curGlob]) {
              combinedIncludes.add(include.replace(/\\/g, '/'))
            }
          }
        }

        for (const curGlob of excludeGlobKeys) {
          const isMatch = picomatch(curGlob, { dot: true, contains: true })
          if (isMatch(route)) {
            for (const exclude of outputFileTracingExcludes[curGlob]) {
              combinedExcludes.add(exclude)
            }
          }
        }

        if (!combinedIncludes?.size && !combinedExcludes?.size) {
          return
        }

        const traceFile = path.join(
          distDir,
          `server`,
          `${entryName}.js.nft.json`
        )
        const pageDir = path.dirname(traceFile)
        const traceContent = JSON.parse(await fs.readFile(traceFile, 'utf8'))
        const includes: string[] = []
        const resolvedTraceIncludes = new Map<string, string[]>()

        if (combinedIncludes?.size) {
          await Promise.all(
            [...combinedIncludes].map(async (includeGlob) => {
              const results = await glob(includeGlob)
              const resolvedInclude = resolvedTraceIncludes.get(
                includeGlob
              ) || [
                ...results.map((file) => {
                  return path.relative(pageDir, path.join(dir, file))
                }),
              ]
              includes.push(...resolvedInclude)
              resolvedTraceIncludes.set(includeGlob, resolvedInclude)
            })
          )
        }
        const combined = new Set([...traceContent.files, ...includes])

        if (combinedExcludes?.size) {
          const resolvedGlobs = [...combinedExcludes].map((exclude) =>
            path.join(dir, exclude)
          )

          // pre compile before forEach
          const isMatch = picomatch(resolvedGlobs, {
            dot: true,
            contains: true,
          })

          combined.forEach((file) => {
            if (isMatch(path.join(pageDir, file))) {
              combined.delete(file)
            }
          })
        }

        // overwrite trace file with custom includes/excludes
        await fs.writeFile(
          traceFile,
          JSON.stringify({
            version: traceContent.version,
            files: [...combined],
          })
        )
      })
    )
  })

  debug(`finished build tracing ${Date.now() - startTime}ms`)
}