-
Notifications
You must be signed in to change notification settings - Fork 27.2k
/
index.ts
1398 lines (1264 loc) · 42.2 KB
/
index.ts
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-use-before-define */
import path from 'path'
import { pathToFileURL } from 'url'
import { arch, platform } from 'os'
import { platformArchTriples } from 'next/dist/compiled/@napi-rs/triples'
import * as Log from '../output/log'
import { getParserOptions } from './options'
import { eventSwcLoadFailure } from '../../telemetry/events/swc-load-failure'
import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile'
import { downloadNativeNextSwc, downloadWasmSwc } from '../../lib/download-swc'
import type {
NextConfigComplete,
TurboLoaderItem,
TurboRuleConfigItem,
TurboRuleConfigItemOptions,
TurboRuleConfigItemOrShortcut,
} from '../../server/config-shared'
import { isDeepStrictEqual } from 'util'
import {
type DefineEnvPluginOptions,
getDefineEnv,
} from '../webpack/plugins/define-env-plugin'
import { getReactCompilerLoader } from '../get-babel-loader-config'
import { TurbopackInternalError } from '../../server/dev/turbopack-utils'
import type {
NapiPartialProjectOptions,
NapiProjectOptions,
} from './generated-native'
import type {
Binding,
DefineEnv,
Endpoint,
HmrIdentifiers,
Project,
ProjectOptions,
Route,
TurboEngineOptions,
TurbopackResult,
TurbopackStackFrame,
Update,
UpdateMessage,
WrittenEndpoint,
} from './types'
type RawBindings = typeof import('./generated-native')
type RawWasmBindings = typeof import('./generated-wasm') & {
default?(): Promise<typeof import('./generated-wasm')>
}
const nextVersion = process.env.__NEXT_VERSION as string
const ArchName = arch()
const PlatformName = platform()
function infoLog(...args: any[]) {
if (process.env.NEXT_PRIVATE_BUILD_WORKER) {
return
}
if (process.env.DEBUG) {
Log.info(...args)
}
}
/**
* Based on napi-rs's target triples, returns triples that have corresponding next-swc binaries.
*/
export function getSupportedArchTriples(): Record<string, any> {
const { darwin, win32, linux, freebsd, android } = platformArchTriples
return {
darwin,
win32: {
arm64: win32.arm64,
ia32: win32.ia32.filter((triple) => triple.abi === 'msvc'),
x64: win32.x64.filter((triple) => triple.abi === 'msvc'),
},
linux: {
// linux[x64] includes `gnux32` abi, with x64 arch.
x64: linux.x64.filter((triple) => triple.abi !== 'gnux32'),
arm64: linux.arm64,
// This target is being deprecated, however we keep it in `knownDefaultWasmFallbackTriples` for now
arm: linux.arm,
},
// Below targets are being deprecated, however we keep it in `knownDefaultWasmFallbackTriples` for now
freebsd: {
x64: freebsd.x64,
},
android: {
arm64: android.arm64,
arm: android.arm,
},
}
}
const triples = (() => {
const supportedArchTriples = getSupportedArchTriples()
const targetTriple = supportedArchTriples[PlatformName]?.[ArchName]
// If we have supported triple, return it right away
if (targetTriple) {
return targetTriple
}
// If there isn't corresponding target triple in `supportedArchTriples`, check if it's excluded from original raw triples
// Otherwise, it is completely unsupported platforms.
let rawTargetTriple = platformArchTriples[PlatformName]?.[ArchName]
if (rawTargetTriple) {
Log.warn(
`Trying to load next-swc for target triple ${rawTargetTriple}, but there next-swc does not have native bindings support`
)
} else {
Log.warn(
`Trying to load next-swc for unsupported platforms ${PlatformName}/${ArchName}`
)
}
return []
})()
// Allow to specify an absolute path to the custom turbopack binary to load.
// If one of env variables is set, `loadNative` will try to use specified
// binary instead. This is thin, naive interface
// - `loadBindings` will not validate neither path nor the binary.
//
// Note these are internal flag: there's no stability, feature guarantee.
const __INTERNAL_CUSTOM_TURBOPACK_BINDINGS =
process.env.__INTERNAL_CUSTOM_TURBOPACK_BINDINGS
function checkVersionMismatch(pkgData: any) {
const version = pkgData.version
if (version && version !== nextVersion) {
Log.warn(
`Mismatching @next/swc version, detected: ${version} while Next.js is on ${nextVersion}. Please ensure these match`
)
}
}
// These are the platforms we'll try to load wasm bindings first,
// only try to load native bindings if loading wasm binding somehow fails.
// Fallback to native binding is for migration period only,
// once we can verify loading-wasm-first won't cause visible regressions,
// we'll not include native bindings for these platform at all.
const knownDefaultWasmFallbackTriples = [
'x86_64-unknown-freebsd',
'aarch64-linux-android',
'arm-linux-androideabi',
'armv7-unknown-linux-gnueabihf',
'i686-pc-windows-msvc',
// WOA targets are TBD, while current userbase is small we may support it in the future
//'aarch64-pc-windows-msvc',
]
// The last attempt's error code returned when cjs require to native bindings fails.
// If node.js throws an error without error code, this should be `unknown` instead of undefined.
// For the wasm-first targets (`knownDefaultWasmFallbackTriples`) this will be `unsupported_target`.
let lastNativeBindingsLoadErrorCode:
| 'unknown'
| 'unsupported_target'
| string
| undefined = undefined
let nativeBindings: Binding
let wasmBindings: Binding
let downloadWasmPromise: any
let pendingBindings: any
let swcTraceFlushGuard: any
let swcHeapProfilerFlushGuard: any
let downloadNativeBindingsPromise: Promise<void> | undefined = undefined
export const lockfilePatchPromise: { cur?: Promise<void> } = {}
export async function loadBindings(
useWasmBinary: boolean = false
): Promise<Binding> {
// Increase Rust stack size as some npm packages being compiled need more than the default.
if (!process.env.RUST_MIN_STACK) {
process.env.RUST_MIN_STACK = '8388608'
}
if (pendingBindings) {
return pendingBindings
}
// rust needs stdout to be blocking, otherwise it will throw an error (on macOS at least) when writing a lot of data (logs) to it
// see https://github.com/napi-rs/napi-rs/issues/1630
// and https://github.com/nodejs/node/blob/main/doc/api/process.md#a-note-on-process-io
if (process.stdout._handle != null) {
// @ts-ignore
process.stdout._handle.setBlocking?.(true)
}
if (process.stderr._handle != null) {
// @ts-ignore
process.stderr._handle.setBlocking?.(true)
}
pendingBindings = new Promise(async (resolve, _reject) => {
if (!lockfilePatchPromise.cur) {
// always run lockfile check once so that it gets patched
// even if it doesn't fail to load locally
lockfilePatchPromise.cur = patchIncorrectLockfile(process.cwd()).catch(
console.error
)
}
let attempts: any[] = []
const disableWasmFallback = process.env.NEXT_DISABLE_SWC_WASM
const unsupportedPlatform = triples.some(
(triple: any) =>
!!triple?.raw && knownDefaultWasmFallbackTriples.includes(triple.raw)
)
const isWebContainer = process.versions.webcontainer
// Normal execution relies on the param `useWasmBinary` flag to load, but
// in certain cases where there isn't a native binary we always load wasm fallback first.
const shouldLoadWasmFallbackFirst =
(!disableWasmFallback && useWasmBinary) ||
unsupportedPlatform ||
isWebContainer
if (!unsupportedPlatform && useWasmBinary) {
Log.warn(
`experimental.useWasmBinary is not an option for supported platform ${PlatformName}/${ArchName} and will be ignored.`
)
}
if (shouldLoadWasmFallbackFirst) {
lastNativeBindingsLoadErrorCode = 'unsupported_target'
const fallbackBindings = await tryLoadWasmWithFallback(attempts)
if (fallbackBindings) {
return resolve(fallbackBindings)
}
}
// Trickle down loading `fallback` bindings:
//
// - First, try to load native bindings installed in node_modules.
// - If that fails with `ERR_MODULE_NOT_FOUND`, treat it as case of https://github.com/npm/cli/issues/4828
// that host system where generated package lock is not matching to the guest system running on, try to manually
// download corresponding target triple and load it. This won't be triggered if native bindings are failed to load
// with other reasons than `ERR_MODULE_NOT_FOUND`.
// - Lastly, falls back to wasm binding where possible.
try {
return resolve(loadNative())
} catch (a) {
if (
Array.isArray(a) &&
a.every((m) => m.includes('it was not installed'))
) {
let fallbackBindings = await tryLoadNativeWithFallback(attempts)
if (fallbackBindings) {
return resolve(fallbackBindings)
}
}
attempts = attempts.concat(a)
}
// For these platforms we already tried to load wasm and failed, skip reattempt
if (!shouldLoadWasmFallbackFirst && !disableWasmFallback) {
const fallbackBindings = await tryLoadWasmWithFallback(attempts)
if (fallbackBindings) {
return resolve(fallbackBindings)
}
}
logLoadFailure(attempts, true)
})
return pendingBindings
}
async function tryLoadNativeWithFallback(attempts: Array<string>) {
const nativeBindingsDirectory = path.join(
path.dirname(require.resolve('next/package.json')),
'next-swc-fallback'
)
if (!downloadNativeBindingsPromise) {
downloadNativeBindingsPromise = downloadNativeNextSwc(
nextVersion,
nativeBindingsDirectory,
triples.map((triple: any) => triple.platformArchABI)
)
}
await downloadNativeBindingsPromise
try {
return loadNative(nativeBindingsDirectory)
} catch (a: any) {
attempts.push(...[].concat(a))
}
return undefined
}
async function tryLoadWasmWithFallback(attempts: any[]) {
try {
let bindings = await loadWasm('')
// @ts-expect-error TODO: this event has a wrong type.
eventSwcLoadFailure({
wasm: 'enabled',
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode,
})
return bindings
} catch (a: any) {
attempts.push(...[].concat(a))
}
try {
// if not installed already download wasm package on-demand
// we download to a custom directory instead of to node_modules
// as node_module import attempts are cached and can't be re-attempted
// x-ref: https://github.com/nodejs/modules/issues/307
const wasmDirectory = path.join(
path.dirname(require.resolve('next/package.json')),
'wasm'
)
if (!downloadWasmPromise) {
downloadWasmPromise = downloadWasmSwc(nextVersion, wasmDirectory)
}
await downloadWasmPromise
let bindings = await loadWasm(wasmDirectory)
// @ts-expect-error TODO: this event has a wrong type.
eventSwcLoadFailure({
wasm: 'fallback',
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode,
})
// still log native load attempts so user is
// aware it failed and should be fixed
for (const attempt of attempts) {
Log.warn(attempt)
}
return bindings
} catch (a: any) {
attempts.push(...[].concat(a))
}
}
function loadBindingsSync() {
let attempts: any[] = []
try {
return loadNative()
} catch (a) {
attempts = attempts.concat(a)
}
// we can leverage the wasm bindings if they are already
// loaded
if (wasmBindings) {
return wasmBindings
}
logLoadFailure(attempts)
throw new Error('Failed to load bindings', { cause: attempts })
}
let loggingLoadFailure = false
function logLoadFailure(attempts: any, triedWasm = false) {
// make sure we only emit the event and log the failure once
if (loggingLoadFailure) return
loggingLoadFailure = true
for (let attempt of attempts) {
Log.warn(attempt)
}
// @ts-expect-error TODO: this event has a wrong type.
eventSwcLoadFailure({
wasm: triedWasm ? 'failed' : undefined,
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode,
})
.then(() => lockfilePatchPromise.cur || Promise.resolve())
.finally(() => {
Log.error(
`Failed to load SWC binary for ${PlatformName}/${ArchName}, see more info here: https://nextjs.org/docs/messages/failed-loading-swc`
)
process.exit(1)
})
}
type RustifiedEnv = { name: string; value: string }[]
export function createDefineEnv({
isTurbopack,
clientRouterFilters,
config,
dev,
distDir,
fetchCacheKeyPrefix,
hasRewrites,
middlewareMatchers,
}: Omit<
DefineEnvPluginOptions,
'isClient' | 'isNodeOrEdgeCompilation' | 'isEdgeServer' | 'isNodeServer'
>): DefineEnv {
let defineEnv: DefineEnv = {
client: [],
edge: [],
nodejs: [],
}
for (const variant of Object.keys(defineEnv) as (keyof typeof defineEnv)[]) {
defineEnv[variant] = rustifyEnv(
getDefineEnv({
isTurbopack,
clientRouterFilters,
config,
dev,
distDir,
fetchCacheKeyPrefix,
hasRewrites,
isClient: variant === 'client',
isEdgeServer: variant === 'edge',
isNodeOrEdgeCompilation: variant === 'nodejs' || variant === 'edge',
isNodeServer: variant === 'nodejs',
middlewareMatchers,
})
)
}
return defineEnv
}
function rustifyEnv(env: Record<string, string>): RustifiedEnv {
return Object.entries(env)
.filter(([_, value]) => value != null)
.map(([name, value]) => ({
name,
value,
}))
}
// TODO(sokra) Support wasm option.
function bindingToApi(
binding: RawBindings,
_wasm: boolean
): Binding['turbo']['createProject'] {
type NativeFunction<T> = (
callback: (err: Error, value: T) => void
) => Promise<{ __napiType: 'RootTask' }>
const cancel = new (class Cancel extends Error {})()
/**
* Utility function to ensure all variants of an enum are handled.
*/
function invariant(
never: never,
computeMessage: (arg: any) => string
): never {
throw new Error(`Invariant: ${computeMessage(never)}`)
}
async function withErrorCause<T>(fn: () => Promise<T>): Promise<T> {
try {
return await fn()
} catch (nativeError: any) {
throw new TurbopackInternalError(nativeError)
}
}
/**
* Calls a native function and streams the result.
* If useBuffer is true, all values will be preserved, potentially buffered
* if consumed slower than produced. Else, only the latest value will be
* preserved.
*/
function subscribe<T>(
useBuffer: boolean,
nativeFunction:
| NativeFunction<T>
| ((callback: (err: Error, value: T) => void) => Promise<void>)
): AsyncIterableIterator<T> {
type BufferItem =
| { err: Error; value: undefined }
| { err: undefined; value: T }
// A buffer of produced items. This will only contain values if the
// consumer is slower than the producer.
let buffer: BufferItem[] = []
// A deferred value waiting for the next produced item. This will only
// exist if the consumer is faster than the producer.
let waiting:
| {
resolve: (value: T) => void
reject: (error: Error) => void
}
| undefined
let canceled = false
// The native function will call this every time it emits a new result. We
// either need to notify a waiting consumer, or buffer the new result until
// the consumer catches up.
function emitResult(err: Error | undefined, value: T | undefined) {
if (waiting) {
let { resolve, reject } = waiting
waiting = undefined
if (err) reject(err)
else resolve(value!)
} else {
const item = { err, value } as BufferItem
if (useBuffer) buffer.push(item)
else buffer[0] = item
}
}
async function* createIterator() {
const task = await withErrorCause<{ __napiType: 'RootTask' } | void>(() =>
nativeFunction(emitResult)
)
try {
while (!canceled) {
if (buffer.length > 0) {
const item = buffer.shift()!
if (item.err) throw item.err
yield item.value
} else {
// eslint-disable-next-line no-loop-func
yield new Promise<T>((resolve, reject) => {
waiting = { resolve, reject }
})
}
}
} catch (e) {
if (e === cancel) return
if (e instanceof Error) {
throw new TurbopackInternalError(e)
}
throw e
} finally {
if (task) {
binding.rootTaskDispose(task)
}
}
}
const iterator = createIterator()
iterator.return = async () => {
canceled = true
if (waiting) waiting.reject(cancel)
return { value: undefined, done: true } as IteratorReturnResult<never>
}
return iterator
}
async function rustifyProjectOptions(
options: ProjectOptions
): Promise<NapiProjectOptions> {
return {
...options,
nextConfig: await serializeNextConfig(
options.nextConfig,
options.projectPath!
),
jsConfig: JSON.stringify(options.jsConfig),
env: rustifyEnv(options.env),
}
}
async function rustifyPartialProjectOptions(
options: Partial<ProjectOptions>
): Promise<NapiPartialProjectOptions> {
return {
...options,
nextConfig:
options.nextConfig &&
(await serializeNextConfig(options.nextConfig, options.projectPath!)),
jsConfig: options.jsConfig && JSON.stringify(options.jsConfig),
env: options.env && rustifyEnv(options.env),
}
}
class ProjectImpl implements Project {
private readonly _nativeProject: { __napiType: 'Project' }
constructor(nativeProject: { __napiType: 'Project' }) {
this._nativeProject = nativeProject
}
async update(options: Partial<ProjectOptions>) {
await withErrorCause(async () =>
binding.projectUpdate(
this._nativeProject,
await rustifyPartialProjectOptions(options)
)
)
}
entrypointsSubscribe() {
type NapiEndpoint = { __napiType: 'Endpoint' }
type NapiEntrypoints = {
routes: NapiRoute[]
middleware?: NapiMiddleware
instrumentation?: NapiInstrumentation
pagesDocumentEndpoint: NapiEndpoint
pagesAppEndpoint: NapiEndpoint
pagesErrorEndpoint: NapiEndpoint
}
type NapiMiddleware = {
endpoint: NapiEndpoint
runtime: 'nodejs' | 'edge'
matcher?: string[]
}
type NapiInstrumentation = {
nodeJs: NapiEndpoint
edge: NapiEndpoint
}
type NapiRoute = {
pathname: string
} & (
| {
type: 'page'
htmlEndpoint: NapiEndpoint
dataEndpoint: NapiEndpoint
}
| {
type: 'page-api'
endpoint: NapiEndpoint
}
| {
type: 'app-page'
pages: {
originalName: string
htmlEndpoint: NapiEndpoint
rscEndpoint: NapiEndpoint
}[]
}
| {
type: 'app-route'
originalName: string
endpoint: NapiEndpoint
}
| {
type: 'conflict'
}
)
const subscription = subscribe<TurbopackResult<NapiEntrypoints>>(
false,
async (callback) =>
binding.projectEntrypointsSubscribe(this._nativeProject, callback)
)
return (async function* () {
for await (const entrypoints of subscription) {
const routes = new Map()
for (const { pathname, ...nativeRoute } of entrypoints.routes) {
let route: Route
const routeType = nativeRoute.type
switch (routeType) {
case 'page':
route = {
type: 'page',
htmlEndpoint: new EndpointImpl(nativeRoute.htmlEndpoint),
dataEndpoint: new EndpointImpl(nativeRoute.dataEndpoint),
}
break
case 'page-api':
route = {
type: 'page-api',
endpoint: new EndpointImpl(nativeRoute.endpoint),
}
break
case 'app-page':
route = {
type: 'app-page',
pages: nativeRoute.pages.map((page) => ({
originalName: page.originalName,
htmlEndpoint: new EndpointImpl(page.htmlEndpoint),
rscEndpoint: new EndpointImpl(page.rscEndpoint),
})),
}
break
case 'app-route':
route = {
type: 'app-route',
originalName: nativeRoute.originalName,
endpoint: new EndpointImpl(nativeRoute.endpoint),
}
break
case 'conflict':
route = {
type: 'conflict',
}
break
default:
const _exhaustiveCheck: never = routeType
invariant(
nativeRoute,
() => `Unknown route type: ${_exhaustiveCheck}`
)
}
routes.set(pathname, route)
}
const napiMiddlewareToMiddleware = (middleware: NapiMiddleware) => ({
endpoint: new EndpointImpl(middleware.endpoint),
runtime: middleware.runtime,
matcher: middleware.matcher,
})
const middleware = entrypoints.middleware
? napiMiddlewareToMiddleware(entrypoints.middleware)
: undefined
const napiInstrumentationToInstrumentation = (
instrumentation: NapiInstrumentation
) => ({
nodeJs: new EndpointImpl(instrumentation.nodeJs),
edge: new EndpointImpl(instrumentation.edge),
})
const instrumentation = entrypoints.instrumentation
? napiInstrumentationToInstrumentation(entrypoints.instrumentation)
: undefined
yield {
routes,
middleware,
instrumentation,
pagesDocumentEndpoint: new EndpointImpl(
entrypoints.pagesDocumentEndpoint
),
pagesAppEndpoint: new EndpointImpl(entrypoints.pagesAppEndpoint),
pagesErrorEndpoint: new EndpointImpl(
entrypoints.pagesErrorEndpoint
),
issues: entrypoints.issues,
diagnostics: entrypoints.diagnostics,
}
}
})()
}
hmrEvents(identifier: string) {
return subscribe<TurbopackResult<Update>>(true, async (callback) =>
binding.projectHmrEvents(this._nativeProject, identifier, callback)
)
}
hmrIdentifiersSubscribe() {
return subscribe<TurbopackResult<HmrIdentifiers>>(
false,
async (callback) =>
binding.projectHmrIdentifiersSubscribe(this._nativeProject, callback)
)
}
traceSource(
stackFrame: TurbopackStackFrame,
currentDirectoryFileUrl: string
): Promise<TurbopackStackFrame | null> {
return binding.projectTraceSource(
this._nativeProject,
stackFrame,
currentDirectoryFileUrl
)
}
getSourceForAsset(filePath: string): Promise<string | null> {
return binding.projectGetSourceForAsset(this._nativeProject, filePath)
}
getSourceMap(filePath: string): Promise<string | null> {
return binding.projectGetSourceMap(this._nativeProject, filePath)
}
getSourceMapSync(filePath: string): string | null {
return binding.projectGetSourceMapSync(this._nativeProject, filePath)
}
updateInfoSubscribe(aggregationMs: number) {
return subscribe<TurbopackResult<UpdateMessage>>(true, async (callback) =>
binding.projectUpdateInfoSubscribe(
this._nativeProject,
aggregationMs,
callback
)
)
}
shutdown(): Promise<void> {
return binding.projectShutdown(this._nativeProject)
}
onExit(): Promise<void> {
return binding.projectOnExit(this._nativeProject)
}
}
class EndpointImpl implements Endpoint {
private readonly _nativeEndpoint: { __napiType: 'Endpoint' }
constructor(nativeEndpoint: { __napiType: 'Endpoint' }) {
this._nativeEndpoint = nativeEndpoint
}
async writeToDisk(): Promise<TurbopackResult<WrittenEndpoint>> {
return await withErrorCause(
() =>
binding.endpointWriteToDisk(this._nativeEndpoint) as Promise<
TurbopackResult<WrittenEndpoint>
>
)
}
async clientChanged(): Promise<AsyncIterableIterator<TurbopackResult<{}>>> {
const clientSubscription = subscribe<TurbopackResult>(
false,
async (callback) =>
binding.endpointClientChangedSubscribe(
await this._nativeEndpoint,
callback
)
)
await clientSubscription.next()
return clientSubscription
}
async serverChanged(
includeIssues: boolean
): Promise<AsyncIterableIterator<TurbopackResult<{}>>> {
const serverSubscription = subscribe<TurbopackResult>(
false,
async (callback) =>
binding.endpointServerChangedSubscribe(
await this._nativeEndpoint,
includeIssues,
callback
)
)
await serverSubscription.next()
return serverSubscription
}
}
/**
* Returns a new copy of next.js config object to avoid mutating the original.
*
* Also it does some augmentation to the configuration as well, for example set the
* turbopack's rules if `experimental.reactCompilerOptions` is set.
*/
function augmentNextConfig(
originalNextConfig: NextConfigComplete,
projectPath: string
): Record<string, any> {
let nextConfig = { ...(originalNextConfig as any) }
const reactCompilerOptions = nextConfig.experimental?.reactCompiler
// It is not easy to set the rules inside of rust as resolving, and passing the context identical to the webpack
// config is bit hard, also we can reuse same codes between webpack config in here.
if (reactCompilerOptions) {
const ruleKeys = ['*.ts', '*.js', '*.jsx', '*.tsx']
if (
Object.keys(nextConfig?.experimental?.turbo?.rules ?? []).some((key) =>
ruleKeys.includes(key)
)
) {
Log.warn(
`The React Compiler cannot be enabled automatically because 'experimental.turbo' contains a rule for '*.ts', '*.js', '*.jsx', and '*.tsx'. Remove this rule, or add 'babel-loader' and 'babel-plugin-react-compiler' to the Turbopack configuration manually.`
)
} else {
if (!nextConfig.experimental.turbo) {
nextConfig.experimental.turbo = {}
}
if (!nextConfig.experimental.turbo.rules) {
nextConfig.experimental.turbo.rules = {}
}
for (const key of ['*.ts', '*.js', '*.jsx', '*.tsx']) {
nextConfig.experimental.turbo.rules[key] = {
browser: {
foreign: false,
loaders: [
getReactCompilerLoader(
originalNextConfig.experimental.reactCompiler,
projectPath,
nextConfig.dev,
false,
undefined
),
],
},
}
}
}
}
return nextConfig
}
async function serializeNextConfig(
nextConfig: NextConfigComplete,
projectPath: string
): Promise<string> {
// Avoid mutating the existing `nextConfig` object.
let nextConfigSerializable = augmentNextConfig(nextConfig, projectPath)
nextConfigSerializable.generateBuildId =
await nextConfig.generateBuildId?.()
// TODO: these functions takes arguments, have to be supported in a different way
nextConfigSerializable.exportPathMap = {}
nextConfigSerializable.webpack = nextConfig.webpack && {}
if (nextConfigSerializable.experimental?.turbo?.rules) {
ensureLoadersHaveSerializableOptions(
nextConfigSerializable.experimental.turbo?.rules
)
}
nextConfigSerializable.modularizeImports =
nextConfigSerializable.modularizeImports
? Object.fromEntries(
Object.entries<any>(nextConfigSerializable.modularizeImports).map(
([mod, config]) => [
mod,
{
...config,
transform:
typeof config.transform === 'string'
? config.transform
: Object.entries(config.transform).map(([key, value]) => [
key,
value,
]),
},
]
)
)
: undefined
// loaderFile is an absolute path, we need it to be relative for turbopack.
if (nextConfigSerializable.images.loaderFile) {
nextConfigSerializable.images = {
...nextConfig.images,
loaderFile:
'./' + path.relative(projectPath, nextConfig.images.loaderFile),
}
}
return JSON.stringify(nextConfigSerializable, null, 2)
}
function ensureLoadersHaveSerializableOptions(
turbopackRules: Record<string, TurboRuleConfigItemOrShortcut>
) {
for (const [glob, rule] of Object.entries(turbopackRules)) {
if (Array.isArray(rule)) {
checkLoaderItems(rule, glob)
} else {
checkConfigItem(rule, glob)
}
}
function checkConfigItem(rule: TurboRuleConfigItem, glob: string) {
if (!rule) return
if ('loaders' in rule) {
checkLoaderItems((rule as TurboRuleConfigItemOptions).loaders, glob)
} else {
for (const key in rule) {
const inner = rule[key]
if (typeof inner === 'object' && inner) {
checkConfigItem(inner, glob)
}
}
}
}
function checkLoaderItems(loaderItems: TurboLoaderItem[], glob: string) {
for (const loaderItem of loaderItems) {
if (
typeof loaderItem !== 'string' &&
!isDeepStrictEqual(loaderItem, JSON.parse(JSON.stringify(loaderItem)))
) {
throw new Error(
`loader ${loaderItem.loader} for match "${glob}" does not have serializable options. Ensure that options passed are plain JavaScript objects and values.`
)
}
}
}
}
return async function createProject(
options: ProjectOptions,
turboEngineOptions
) {
return new ProjectImpl(
await binding.projectNew(
await rustifyProjectOptions(options),
turboEngineOptions || {}
)
)
}
}
async function loadWasm(importPath = '') {
if (wasmBindings) {
return wasmBindings