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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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
/* 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,
  TurbopackLoaderItem,
  TurbopackRuleConfigItem,
  TurbopackRuleConfigItemOptions,
  TurbopackRuleConfigItemOrShortcut,
} from '../../server/config-shared'
import { isDeepStrictEqual } from 'util'
import { type DefineEnvOptions, getDefineEnv } from '../define-env'
import { getReactCompilerLoader } from '../get-babel-loader-config'
import type {
  NapiModuleGraphSnapshot,
  NapiModuleGraphSnapshots,
  NapiPartialProjectOptions,
  NapiProjectOptions,
  NapiSourceDiagnostic,
} from './generated-native'
import type {
  Binding,
  CompilationEvent,
  DefineEnv,
  Endpoint,
  HmrIdentifiers,
  Project,
  ProjectOptions,
  RawEntrypoints,
  Route,
  TurboEngineOptions,
  TurbopackResult,
  TurbopackStackFrame,
  Update,
  UpdateMessage,
  WrittenEndpoint,
} from './types'
import { throwTurbopackInternalError } from '../../shared/lib/turbopack/internal-error'

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
// Used to cache calls to `loadBindings`
let pendingBindings: Promise<Binding>
// some things call `loadNative` directly instead of `loadBindings`... Cache calls to that
// separately.
let nativeBindings: Binding
// can allow hacky sync access to bindings for loadBindingsSync
let wasmBindings: Binding
let downloadWasmPromise: any
let swcTraceFlushGuard: any
let downloadNativeBindingsPromise: Promise<void> | undefined = undefined

export const lockfilePatchPromise: { cur?: Promise<void> } = {}

/**
 * Attempts to load a native or wasm binding.
 *
 * By default, this first tries to use a native binding, falling back to a wasm binding if that
 * fails.
 *
 * This function is `async` as wasm requires an asynchronous import in browsers.
 */
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
  }

  if (process.env.NEXT_TEST_WASM) {
    useWasmBinary = true
  }

  // 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
}

// helper for loadBindings
async function tryLoadWasmWithFallback(
  attempts: any[]
): Promise<Binding | undefined> {
  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)
  }

  // HACK: we can leverage the wasm bindings if they are already loaded
  // this may introduce race conditions
  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 }[]
type RustifiedOptionEnv = { name: string; value: string | undefined }[]

export function createDefineEnv({
  isTurbopack,
  clientRouterFilters,
  config,
  dev,
  distDir,
  projectPath,
  fetchCacheKeyPrefix,
  hasRewrites,
  middlewareMatchers,
  rewrites,
}: Omit<
  DefineEnvOptions,
  'isClient' | 'isNodeOrEdgeCompilation' | 'isEdgeServer' | 'isNodeServer'
>): DefineEnv {
  let defineEnv: DefineEnv = {
    client: [],
    edge: [],
    nodejs: [],
  }

  for (const variant of Object.keys(defineEnv) as (keyof typeof defineEnv)[]) {
    defineEnv[variant] = rustifyOptionEnv(
      getDefineEnv({
        isTurbopack,
        clientRouterFilters,
        config,
        dev,
        distDir,
        projectPath,
        fetchCacheKeyPrefix,
        hasRewrites,
        isClient: variant === 'client',
        isEdgeServer: variant === 'edge',
        isNodeServer: variant === 'nodejs',
        middlewareMatchers,
        rewrites,
      })
    )
  }

  return defineEnv
}

function rustifyEnv(env: Record<string, string>): RustifiedEnv {
  return Object.entries(env)
    .filter(([_, value]) => value != null)
    .map(([name, value]) => ({
      name,
      value,
    }))
}

function rustifyOptionEnv(
  env: Record<string, string | undefined>
): RustifiedOptionEnv {
  return Object.entries(env).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' }>

  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 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)}`)
  }

  /**
   * 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 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
        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,
        path.join(options.rootPath, 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,
          path.join(options.rootPath!, 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 binding.projectUpdate(
        this._nativeProject,
        await rustifyPartialProjectOptions(options)
      )
    }

    async writeAllEntrypointsToDisk(
      appDirOnly: boolean
    ): Promise<TurbopackResult<RawEntrypoints>> {
      const napiEndpoints = (await binding.projectWriteAllEntrypointsToDisk(
        this._nativeProject,
        appDirOnly
      )) as TurbopackResult<NapiEntrypoints>

      return napiEntrypointsToRawEntrypoints(napiEndpoints)
    }

    async getEntrypoints() {
      const napiEndpoints = (await binding.projectEntrypoints(
        this._nativeProject
      )) as TurbopackResult<NapiEntrypoints>

      return napiEntrypointsToRawEntrypoints(napiEndpoints)
    }

    entrypointsSubscribe() {
      const subscription = subscribe<TurbopackResult<NapiEntrypoints>>(
        false,
        async (callback) =>
          binding.projectEntrypointsSubscribe(this._nativeProject, callback)
      )
      return (async function* () {
        for await (const entrypoints of subscription) {
          yield napiEntrypointsToRawEntrypoints(entrypoints)
        }
      })()
    }

    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
        )
      )
    }

    compilationEventsSubscribe(eventTypes?: string[]) {
      return subscribe<TurbopackResult<CompilationEvent>>(
        true,
        async (callback) => {
          binding.projectCompilationEventsSubscribe(
            this._nativeProject,
            callback,
            eventTypes
          )
        }
      )
    }

    moduleGraph(): Promise<TurbopackResult<NapiModuleGraphSnapshot>> {
      return binding.projectModuleGraph(this._nativeProject) as Promise<
        TurbopackResult<NapiModuleGraphSnapshot>
      >
    }

    invalidatePersistentCache(): Promise<void> {
      return binding.projectInvalidatePersistentCache(this._nativeProject)
    }

    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 binding.endpointWriteToDisk(
        this._nativeEndpoint
      )) as TurbopackResult<WrittenEndpoint>
    }

    async clientChanged(): Promise<AsyncIterableIterator<TurbopackResult<{}>>> {
      const clientSubscription = subscribe<TurbopackResult>(
        false,
        async (callback) =>
          binding.endpointClientChangedSubscribe(this._nativeEndpoint, callback)
      )
      await clientSubscription.next()
      return clientSubscription
    }

    async serverChanged(
      includeIssues: boolean
    ): Promise<AsyncIterableIterator<TurbopackResult<{}>>> {
      const serverSubscription = subscribe<TurbopackResult>(
        false,
        async (callback) =>
          binding.endpointServerChangedSubscribe(
            this._nativeEndpoint,
            includeIssues,
            callback
          )
      )
      await serverSubscription.next()
      return serverSubscription
    }

    async moduleGraphs(): Promise<TurbopackResult<NapiModuleGraphSnapshots>> {
      return binding.endpointModuleGraphs(this._nativeEndpoint) as Promise<
        TurbopackResult<NapiModuleGraphSnapshots>
      >
    }
  }

  /**
   * 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?.turbopack?.rules ?? []).some((key) =>
          ruleKeys.includes(key)
        )
      ) {
        Log.warn(
          `The React Compiler cannot be enabled automatically because 'turbopack.rules' 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.turbopack) {
          nextConfig.turbopack = {}
        }

        if (!nextConfig.turbopack.rules) {
          nextConfig.turbopack.rules = {}
        }

        for (const key of ['*.ts', '*.js', '*.jsx', '*.tsx']) {
          nextConfig.turbopack.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.turbopack?.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),
      }
    }

    const conditions: (typeof nextConfig)['turbopack']['conditions'] =
      nextConfigSerializable.turbopack?.conditions
    if (conditions) {
      type SerializedConditions = {
        [key: string]: {
          path:
            | { type: 'regex'; value: { source: string; flags: string } }
            | { type: 'glob'; value: string }
        }
      }

      const serializedConditions: SerializedConditions = {}
      for (const [key, value] of Object.entries(conditions)) {
        serializedConditions[key] = {
          ...value,
          path:
            value.path instanceof RegExp
              ? {
                  type: 'regex',
                  value: { source: value.path.source, flags: value.path.flags },
                }
              : { type: 'glob', value: value.path },
        }
      }
      nextConfigSerializable.turbopack.conditions = serializedConditions
    }

    return JSON.stringify(nextConfigSerializable, null, 2)
  }

  function ensureLoadersHaveSerializableOptions(
    turbopackRules: Record<string, TurbopackRuleConfigItemOrShortcut>
  ) {
    for (const [glob, rule] of Object.entries(turbopackRules)) {
      if (Array.isArray(rule)) {
        checkLoaderItems(rule, glob)
      } else {
        checkConfigItem(rule, glob)
      }
    }

    function checkConfigItem(rule: TurbopackRuleConfigItem, glob: string) {
      if (!rule) return
      if ('loaders' in rule) {
        checkLoaderItems((rule as TurbopackRuleConfigItemOptions).loaders, glob)
      } else {
        for (const key in rule) {
          const inner = rule[key]
          if (typeof inner === 'object' && inner) {
            checkConfigItem(inner, glob)
          }
        }
      }
    }

    function checkLoaderItems(
      loaderItems: TurbopackLoaderItem[],
      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.`
          )
        }
      }
    }
  }

  function napiEntrypointsToRawEntrypoints(
    entrypoints: TurbopackResult<NapiEntrypoints>
  ): TurbopackResult<RawEntrypoints> {
    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

    return {
      routes,
      middleware,
      instrumentation,
      pagesDocumentEndpoint: new EndpointImpl(
        entrypoints.pagesDocumentEndpoint
      ),
      pagesAppEndpoint: new EndpointImpl(entrypoints.pagesAppEndpoint),
      pagesErrorEndpoint: new EndpointImpl(entrypoints.pagesErrorEndpoint),
      issues: entrypoints.issues,
      diagnostics: entrypoints.diagnostics,
    }
  }

  return async function createProject(
    options: ProjectOptions,
    turboEngineOptions
  ) {
    return new ProjectImpl(
      await binding.projectNew(
        await rustifyProjectOptions(options),
        turboEngineOptions || {},
        {
          throwTurbopackInternalError,
        }
      )
    )
  }
}

// helper for loadWasm
async function loadWasmRawBindings(importPath = ''): Promise<RawWasmBindings> {
  let attempts = []

  // Used by `run-tests` to force use of a locally-built wasm binary. This environment variable is
  // unstable and subject to change.
  const testWasmDir = process.env.NEXT_TEST_WASM_DIR

  if (testWasmDir) {
    // assume these are node.js bindings and don't need a call to `.default()`
    const rawBindings = await import(
      pathToFileURL(path.join(testWasmDir, 'wasm.js')).toString()
    )
    infoLog(`next-swc build: wasm build ${testWasmDir}`)
    return rawBindings
  } else {
    for (let pkg of ['@next/swc-wasm-nodejs', '@next/swc-wasm-web']) {
      try {
        let pkgPath = pkg

        if (importPath) {
          // the import path must be exact when not in node_modules
          pkgPath = path.join(importPath, pkg, 'wasm.js')
        }
        const importedRawBindings = await import(
          pathToFileURL(pkgPath).toString()
        )
        let rawBindings
        if (pkg === '@next/swc-wasm-web') {
          // https://rustwasm.github.io/docs/wasm-bindgen/examples/without-a-bundler.html
          // `default` must be called to initialize the module
          rawBindings = await importedRawBindings.default!()
        } else {
          rawBindings = importedRawBindings
        }
        infoLog(`next-swc build: wasm build ${pkg}`)
        return rawBindings
      } catch (e: any) {
        // Only log attempts for loading wasm when loading as fallback
        if (importPath) {
          if (e?.code === 'ERR_MODULE_NOT_FOUND') {
            attempts.push(`Attempted to load ${pkg}, but it was not installed`)
          } else {
            attempts.push(
              `Attempted to load ${pkg}, but an error occurred: ${e.message ?? e}`
            )
          }
        }
      }
    }
  }

  throw attempts
}

// helper for tryLoadWasmWithFallback / loadBindings.
async function loadWasm(importPath = '') {
  const rawBindings = await loadWasmRawBindings(importPath)

  function removeUndefined(obj: any): any {
    // serde-wasm-bindgen expect that `undefined` values map to `()` in rust, but we want to treat
    // those fields as non-existent, so remove them before passing them to rust.
    //
    // The native (non-wasm) bindings use `JSON.stringify`, which strips undefined values.
    if (typeof obj !== 'object' || obj === null) {
      return obj
    }
    if (Array.isArray(obj)) {
      return obj.map(removeUndefined)
    }
    const newObj: { [key: string]: any } = {}
    for (const [k, v] of Object.entries(obj)) {
      if (typeof v !== 'undefined') {
        newObj[k] = removeUndefined(v)
      }
    }
    return newObj
  }

  // Note wasm binary does not support async intefaces yet, all async
  // interface coereces to sync interfaces.
  wasmBindings = {
    css: {
      lightning: {
        transform: function (_options: any) {
          throw new Error(
            '`css.lightning.transform` is not supported by the wasm bindings.'
          )
        },
        transformStyleAttr: function (_options: any) {
          throw new Error(
            '`css.lightning.transformStyleAttr` is not supported by the wasm bindings.'
          )
        },
      },
    },
    isWasm: true,
    transform(src: string, options: any): Promise<any> {
      return rawBindings.transform(src.toString(), removeUndefined(options))
    },
    transformSync(src: string, options: any) {
      return rawBindings.transformSync(src.toString(), removeUndefined(options))
    },
    minify(src: string, options: any): Promise<any> {
      return rawBindings.minify(src.toString(), removeUndefined(options))
    },
    minifySync(src: string, options: any) {
      return rawBindings.minifySync(src.toString(), removeUndefined(options))
    },
    parse(src: string, options: any): Promise<any> {
      return rawBindings.parse(src.toString(), removeUndefined(options))
    },
    getTargetTriple() {
      return undefined
    },
    turbo: {
      createProject(
        _options: ProjectOptions,
        _turboEngineOptions?: TurboEngineOptions | undefined
      ): Promise<Project> {
        throw new Error(
          '`turbo.createProject` is not supported by the wasm bindings.'
        )
      },
      startTurbopackTraceServer(_traceFilePath: string): void {
        throw new Error(
          '`turbo.startTurbopackTraceServer` is not supported by the wasm bindings.'
        )
      },
    },
    mdx: {
      compile(src: string, options: any) {
        return rawBindings.mdxCompile(
          src,
          removeUndefined(getMdxOptions(options))
        )
      },
      compileSync(src: string, options: any) {
        return rawBindings.mdxCompileSync(
          src,
          removeUndefined(getMdxOptions(options))
        )
      },
    },
    reactCompiler: {
      isReactCompilerRequired(_filename: string) {
        return Promise.resolve(true)
      },
    },
    rspack: {
      getModuleNamedExports(_resourcePath: string): Promise<string[]> {
        throw new Error(
          '`rspack.getModuleNamedExports` is not supported by the wasm bindings.'
        )
      },
      warnForEdgeRuntime(
        _source: string,
        _isProduction: boolean
      ): Promise<NapiSourceDiagnostic[]> {
        throw new Error(
          '`rspack.warnForEdgeRuntime` is not supported by the wasm bindings.'
        )
      },
    },
  }
  return wasmBindings
}

/**
 * Loads the native (non-wasm) bindings. Prefer `loadBindings` over this API, as that includes a
 * wasm fallback.
 */
function loadNative(importPath?: string) {
  if (nativeBindings) {
    return nativeBindings
  }

  if (process.env.NEXT_TEST_WASM) {
    throw new Error('cannot run loadNative when `NEXT_TEST_WASM` is set')
  }

  const customBindings: RawBindings = !!__INTERNAL_CUSTOM_TURBOPACK_BINDINGS
    ? require(__INTERNAL_CUSTOM_TURBOPACK_BINDINGS)
    : null
  let bindings: RawBindings = customBindings
  let attempts: any[] = []

  const NEXT_TEST_NATIVE_DIR = process.env.NEXT_TEST_NATIVE_DIR
  for (const triple of triples) {
    if (NEXT_TEST_NATIVE_DIR) {
      try {
        // Use the binary directly to skip `pnpm pack` for testing as it's slow because of the large native binary.
        bindings = require(
          `${NEXT_TEST_NATIVE_DIR}/next-swc.${triple.platformArchABI}.node`
        )
        infoLog(
          'next-swc build: local built @next/swc from NEXT_TEST_NATIVE_DIR'
        )
        break
      } catch (e) {}
    } else {
      try {
        bindings = require(
          `@next/swc/native/next-swc.${triple.platformArchABI}.node`
        )
        infoLog('next-swc build: local built @next/swc')
        break
      } catch (e) {}
    }
  }

  if (!bindings) {
    for (const triple of triples) {
      let pkg = importPath
        ? path.join(
            importPath,
            `@next/swc-${triple.platformArchABI}`,
            `next-swc.${triple.platformArchABI}.node`
          )
        : `@next/swc-${triple.platformArchABI}`
      try {
        bindings = require(pkg)
        if (!importPath) {
          checkVersionMismatch(require(`${pkg}/package.json`))
        }
        break
      } catch (e: any) {
        if (e?.code === 'MODULE_NOT_FOUND') {
          attempts.push(`Attempted to load ${pkg}, but it was not installed`)
        } else {
          attempts.push(
            `Attempted to load ${pkg}, but an error occurred: ${e.message ?? e}`
          )
        }
        lastNativeBindingsLoadErrorCode = e?.code ?? 'unknown'
      }
    }
  }

  if (bindings) {
    nativeBindings = {
      isWasm: false,
      transform(src: string, options: any) {
        const isModule =
          typeof src !== 'undefined' &&
          typeof src !== 'string' &&
          !Buffer.isBuffer(src)
        options = options || {}

        if (options?.jsc?.parser) {
          options.jsc.parser.syntax = options.jsc.parser.syntax ?? 'ecmascript'
        }

        return bindings.transform(
          isModule ? JSON.stringify(src) : src,
          isModule,
          toBuffer(options)
        )
      },

      transformSync(src: string, options: any) {
        if (typeof src === 'undefined') {
          throw new Error(
            "transformSync doesn't implement reading the file from filesystem"
          )
        } else if (Buffer.isBuffer(src)) {
          throw new Error(
            "transformSync doesn't implement taking the source code as Buffer"
          )
        }
        const isModule = typeof src !== 'string'
        options = options || {}

        if (options?.jsc?.parser) {
          options.jsc.parser.syntax = options.jsc.parser.syntax ?? 'ecmascript'
        }

        return bindings.transformSync(
          isModule ? JSON.stringify(src) : src,
          isModule,
          toBuffer(options)
        )
      },

      minify(src: string, options: any) {
        return bindings.minify(Buffer.from(src), toBuffer(options ?? {}))
      },

      minifySync(src: string, options: any) {
        return bindings.minifySync(Buffer.from(src), toBuffer(options ?? {}))
      },

      parse(src: string, options: any) {
        return bindings.parse(src, toBuffer(options ?? {}))
      },

      getTargetTriple: bindings.getTargetTriple,
      initCustomTraceSubscriber: bindings.initCustomTraceSubscriber,
      teardownTraceSubscriber: bindings.teardownTraceSubscriber,
      turbo: {
        createProject: bindingToApi(customBindings ?? bindings, false),
        startTurbopackTraceServer(traceFilePath) {
          Log.warn(
            'Turbopack trace server started. View trace at https://trace.nextjs.org'
          )
          ;(customBindings ?? bindings).startTurbopackTraceServer(traceFilePath)
        },
      },
      mdx: {
        compile(src: string, options: any) {
          return bindings.mdxCompile(src, toBuffer(getMdxOptions(options)))
        },
        compileSync(src: string, options: any) {
          bindings.mdxCompileSync(src, toBuffer(getMdxOptions(options)))
        },
      },
      css: {
        lightning: {
          transform(transformOptions: any) {
            return bindings.lightningCssTransform(transformOptions)
          },
          transformStyleAttr(transformAttrOptions: any) {
            return bindings.lightningCssTransformStyleAttribute(
              transformAttrOptions
            )
          },
        },
      },
      reactCompiler: {
        isReactCompilerRequired: (filename: string) => {
          return bindings.isReactCompilerRequired(filename)
        },
      },
      rspack: {
        getModuleNamedExports: function (
          resourcePath: string
        ): Promise<string[]> {
          return bindings.getModuleNamedExports(resourcePath)
        },
        warnForEdgeRuntime: function (
          source: string,
          isProduction: boolean
        ): Promise<NapiSourceDiagnostic[]> {
          return bindings.warnForEdgeRuntime(source, isProduction)
        },
      },
    }
    return nativeBindings
  }

  throw attempts
}

/// Build a mdx options object contains default values that
/// can be parsed with serde_wasm_bindgen.
function getMdxOptions(options: any = {}) {
  return {
    ...options,
    development: options.development ?? false,
    jsx: options.jsx ?? false,
    mdxType: options.mdxType ?? 'commonMark',
  }
}

function toBuffer(t: any) {
  return Buffer.from(JSON.stringify(t))
}

export async function isWasm(): Promise<boolean> {
  let bindings = await loadBindings()
  return bindings.isWasm
}

export async function transform(src: string, options?: any): Promise<any> {
  let bindings = await loadBindings()
  return bindings.transform(src, options)
}

export function transformSync(src: string, options?: any): any {
  let bindings = loadBindingsSync()
  return bindings.transformSync(src, options)
}

export async function minify(
  src: string,
  options: any
): Promise<{ code: string; map: any }> {
  let bindings = await loadBindings()
  return bindings.minify(src, options)
}

export async function isReactCompilerRequired(
  filename: string
): Promise<boolean> {
  let bindings = await loadBindings()
  return bindings.reactCompiler.isReactCompilerRequired(filename)
}

export async function parse(src: string, options: any): Promise<any> {
  let bindings = await loadBindings()
  let parserOptions = getParserOptions(options)
  return bindings
    .parse(src, parserOptions)
    .then((astStr: any) => JSON.parse(astStr))
}

export function getBinaryMetadata() {
  let bindings
  try {
    bindings = loadNative()
  } catch (e) {
    // Suppress exceptions, this fn allows to fail to load native bindings
  }

  return {
    target: bindings?.getTargetTriple?.(),
  }
}

/**
 * Initialize trace subscriber to emit traces.
 *
 */
export function initCustomTraceSubscriber(traceFileName?: string) {
  if (swcTraceFlushGuard) {
    // Wasm binary doesn't support trace emission
    let bindings = loadNative()
    swcTraceFlushGuard = bindings.initCustomTraceSubscriber?.(traceFileName)
  }
}

function once(fn: () => void): () => void {
  let executed = false

  return function (): void {
    if (!executed) {
      executed = true

      fn()
    }
  }
}

/**
 * Teardown swc's trace subscriber if there's an initialized flush guard exists.
 *
 * This is workaround to amend behavior with process.exit
 * (https://github.com/vercel/next.js/blob/4db8c49cc31e4fc182391fae6903fb5ef4e8c66e/packages/next/bin/next.ts#L134=)
 * seems preventing napi's cleanup hook execution (https://github.com/swc-project/swc/blob/main/crates/node/src/util.rs#L48-L51=),
 *
 * instead parent process manually drops guard when process gets signal to exit.
 */
export const teardownTraceSubscriber = once(() => {
  try {
    let bindings = loadNative()
    if (swcTraceFlushGuard) {
      bindings.teardownTraceSubscriber?.(swcTraceFlushGuard)
    }
  } catch (e) {
    // Suppress exceptions, this fn allows to fail to load native bindings
  }
})

export async function getModuleNamedExports(
  resourcePath: string
): Promise<string[]> {
  const bindings = await loadBindings()
  return bindings.rspack.getModuleNamedExports(resourcePath)
}

export async function warnForEdgeRuntime(
  source: string,
  isProduction: boolean
): Promise<NapiSourceDiagnostic[]> {
  const bindings = await loadBindings()
  return bindings.rspack.warnForEdgeRuntime(source, isProduction)
}