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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
declare const __turbopack_external_require__: {
  resolve: (name: string, opt: { paths: string[] }) => string
} & ((id: string, thunk: () => any, esm?: boolean) => any)

import type { Ipc } from '../ipc/evaluate'
import { dirname, resolve as pathResolve } from 'path'
import {
  StackFrame,
  parse as parseStackTrace,
} from '../compiled/stacktrace-parser'
import { structuredError, type StructuredError } from '../ipc'
import {
  fromPath,
  getReadEnvVariables,
  toPath,
  type TransformIpc,
} from './transforms'

export type IpcInfoMessage =
  | {
      type: 'dependencies'
      envVariables?: string[]
      directories?: Array<[string, string]>
      filePaths?: string[]
      buildFilePaths?: string[]
    }
  | {
      type: 'emittedError'
      severity: 'warning' | 'error'
      error: StructuredError
    }
  | {
      type: 'log'
      logs: Array<{
        time: number
        logType: string
        args: any[]
        trace?: StackFrame[]
      }>
    }

export type IpcRequestMessage = {
  type: 'resolve'
  options: any
  lookupPath: string
  request: string
}

type LoaderConfig =
  | string
  | {
      loader: string
      options: { [k: string]: unknown }
    }

const {
  runLoaders,
}: typeof import('loader-runner') = require('@vercel/turbopack/loader-runner')

const contextDir = process.cwd()

const LogType = Object.freeze({
  error: 'error',
  warn: 'warn',
  info: 'info',
  log: 'log',
  debug: 'debug',

  trace: 'trace',

  group: 'group',
  groupCollapsed: 'groupCollapsed',
  groupEnd: 'groupEnd',

  profile: 'profile',
  profileEnd: 'profileEnd',

  time: 'time',

  clear: 'clear',
  status: 'status',
})

const loaderFlag = 'LOADER_EXECUTION'

const cutOffByFlag = (stack: string, flag: string): string => {
  const errorStack = stack.split('\n')
  for (let i = 0; i < errorStack.length; i++) {
    if (errorStack[i].includes(flag)) {
      errorStack.length = i
    }
  }
  return errorStack.join('\n')
}

/**
 * @param stack stack trace
 * @returns stack trace without the loader execution flag included
 */
const cutOffLoaderExecution = (stack: string): string =>
  cutOffByFlag(stack, loaderFlag)

class DummySpan {
  traceChild() {
    return new DummySpan()
  }

  traceFn<T>(fn: (span: DummySpan) => T): T {
    return fn(this)
  }

  async traceAsyncFn<T>(fn: (span: DummySpan) => T | Promise<T>): Promise<T> {
    return await fn(this)
  }

  stop() {
    return
  }
}

type ResolveOptions = {
  dependencyType?: string
  alias?: Record<string, string[]> | unknown[]
  aliasFields?: string[]
  cacheWithContext?: boolean
  conditionNames?: string[]
  descriptionFiles?: string[]
  enforceExtension?: boolean
  extensionAlias: Record<string, string[]>
  extensions?: string[]
  fallback?: Record<string, string[]>
  mainFields?: string[]
  mainFiles?: string[]
  exportsFields?: string[]
  modules?: string[]
  plugins?: unknown[]
  symlinks?: boolean
  unsafeCache?: boolean
  useSyncFileSystemCalls?: boolean
  preferRelative?: boolean
  preferAbsolute?: boolean
  restrictions?: unknown[]
  roots?: string[]
  importFields?: string[]
}

const transform = (
  ipc: TransformIpc,
  content: string | { binary: string },
  name: string,
  query: string,
  loaders: LoaderConfig[],
  sourceMap: boolean
) => {
  return new Promise((resolve, reject) => {
    const resource = pathResolve(contextDir, name)
    const resourceDir = dirname(resource)

    const loadersWithOptions = loaders.map((loader) =>
      typeof loader === 'string' ? { loader, options: {} } : loader
    )

    const logs: Array<{
      time: number
      logType: string
      args: unknown[]
      trace: StackFrame[] | undefined
    }> = []

    runLoaders(
      {
        resource: resource + query,
        context: {
          _module: {
            // For debugging purpose, if someone find context is not full compatible to
            // webpack they can guess this comes from turbopack
            __reserved: 'TurbopackContext',
          },
          currentTraceSpan: new DummySpan(),
          rootContext: contextDir,
          sourceMap,
          getOptions() {
            const entry = this.loaders[this.loaderIndex]
            return entry.options && typeof entry.options === 'object'
              ? entry.options
              : {}
          },
          getResolve: (options: ResolveOptions) => {
            const rustOptions = {
              aliasFields: undefined as undefined | string[],
              conditionNames: undefined as undefined | string[],
              noPackageJson: false,
              extensions: undefined as undefined | string[],
              mainFields: undefined as undefined | string[],
              noExportsField: false,
              mainFiles: undefined as undefined | string[],
              noModules: false,
              preferRelative: false,
            }
            if (options.alias) {
              if (!Array.isArray(options.alias) || options.alias.length > 0) {
                throw new Error('alias resolve option is not supported')
              }
            }
            if (options.aliasFields) {
              if (!Array.isArray(options.aliasFields)) {
                throw new Error('aliasFields resolve option must be an array')
              }
              rustOptions.aliasFields = options.aliasFields
            }
            if (options.conditionNames) {
              if (!Array.isArray(options.conditionNames)) {
                throw new Error(
                  'conditionNames resolve option must be an array'
                )
              }
              rustOptions.conditionNames = options.conditionNames
            }
            if (options.descriptionFiles) {
              if (
                !Array.isArray(options.descriptionFiles) ||
                options.descriptionFiles.length > 0
              ) {
                throw new Error(
                  'descriptionFiles resolve option is not supported'
                )
              }
              rustOptions.noPackageJson = true
            }
            if (options.extensions) {
              if (!Array.isArray(options.extensions)) {
                throw new Error('extensions resolve option must be an array')
              }
              rustOptions.extensions = options.extensions
            }
            if (options.mainFields) {
              if (!Array.isArray(options.mainFields)) {
                throw new Error('mainFields resolve option must be an array')
              }
              rustOptions.mainFields = options.mainFields
            }
            if (options.exportsFields) {
              if (
                !Array.isArray(options.exportsFields) ||
                options.exportsFields.length > 0
              ) {
                throw new Error('exportsFields resolve option is not supported')
              }
              rustOptions.noExportsField = true
            }
            if (options.mainFiles) {
              if (!Array.isArray(options.mainFiles)) {
                throw new Error('mainFiles resolve option must be an array')
              }
              rustOptions.mainFiles = options.mainFiles
            }
            if (options.modules) {
              if (
                !Array.isArray(options.modules) ||
                options.modules.length > 0
              ) {
                throw new Error('modules resolve option is not supported')
              }
              rustOptions.noModules = true
            }
            if (options.restrictions) {
              // TODO This is ignored for now
            }
            if (options.dependencyType) {
              // TODO This is ignored for now
            }
            if (options.preferRelative) {
              if (typeof options.preferRelative !== 'boolean') {
                throw new Error(
                  'preferRelative resolve option must be a boolean'
                )
              }
              rustOptions.preferRelative = options.preferRelative
            }
            return (
              lookupPath: string,
              request: string,
              callback?: (err?: Error, result?: string) => void
            ) => {
              const promise = ipc
                .sendRequest({
                  type: 'resolve',
                  options: rustOptions,
                  lookupPath: toPath(lookupPath),
                  request,
                })
                .then((unknownResult) => {
                  let result = unknownResult as { path: string }
                  if (result && typeof result.path === 'string') {
                    return fromPath(result.path)
                  } else {
                    throw Error(
                      'Expected { path: string } from resolve request'
                    )
                  }
                })
              if (callback) {
                promise
                  .then(
                    (result) => callback(undefined, result),
                    (err) => callback(err)
                  )
                  .catch((err) => {
                    ipc.sendError(err)
                  })
              } else {
                return promise
              }
            }
          },
          emitWarning: makeErrorEmitter('warning', ipc),
          emitError: makeErrorEmitter('error', ipc),
          getLogger(name: unknown) {
            const logFn = (logType: string, ...args: unknown[]) => {
              let trace: StackFrame[] | undefined
              switch (logType) {
                case LogType.warn:
                case LogType.error:
                case LogType.trace:
                case LogType.debug:
                  trace = parseStackTrace(
                    cutOffLoaderExecution(new Error('Trace').stack!)
                      .split('\n')
                      .slice(3)
                      .join('\n')
                  )
                  break
                default:
                  // TODO: do we need to handle this?
                  break
              }
              // Batch logs messages to be sent at the end
              logs.push({
                time: Date.now(),
                logType,
                args,
                trace,
              })
            }
            let timers: Map<string, [number, number]> | undefined
            let timersAggregates: Map<string, [number, number]> | undefined

            // See https://github.com/webpack/webpack/blob/a48c34b34d2d6c44f9b2b221d7baf278d34ac0be/lib/logging/Logger.js#L8
            return {
              error: logFn.bind(this, LogType.error),
              warn: logFn.bind(this, LogType.warn),
              info: logFn.bind(this, LogType.info),
              log: logFn.bind(this, LogType.log),
              debug: logFn.bind(this, LogType.debug),
              assert: (assertion: boolean, ...args: any[]) => {
                if (!assertion) {
                  logFn(LogType.error, ...args)
                }
              },
              trace: logFn.bind(this, LogType.trace),
              clear: logFn.bind(this, LogType.clear),
              status: logFn.bind(this, LogType.status),
              group: logFn.bind(this, LogType.group),
              groupCollapsed: logFn.bind(this, LogType.groupCollapsed),
              groupEnd: logFn.bind(this, LogType.groupEnd),
              profile: logFn.bind(this, LogType.profile),
              profileEnd: logFn.bind(this, LogType.profileEnd),
              time: (label: string) => {
                timers = timers || new Map()
                timers.set(label, process.hrtime())
              },
              timeLog: (label: string) => {
                const prev = timers && timers.get(label)
                if (!prev) {
                  throw new Error(
                    `No such label '${label}' for WebpackLogger.timeLog()`
                  )
                }
                const time = process.hrtime(prev)
                logFn(LogType.time, [label, ...time])
              },
              timeEnd: (label: string) => {
                const prev = timers && timers.get(label)
                if (!prev) {
                  throw new Error(
                    `No such label '${label}' for WebpackLogger.timeEnd()`
                  )
                }
                const time = process.hrtime(prev)
                /** @type {Map<string | undefined, [number, number]>} */
                timers!.delete(label)
                logFn(LogType.time, [label, ...time])
              },
              timeAggregate: (label: string) => {
                const prev = timers && timers.get(label)
                if (!prev) {
                  throw new Error(
                    `No such label '${label}' for WebpackLogger.timeAggregate()`
                  )
                }
                const time = process.hrtime(prev)
                /** @type {Map<string | undefined, [number, number]>} */
                timers!.delete(label)
                /** @type {Map<string | undefined, [number, number]>} */
                timersAggregates = timersAggregates || new Map()
                const current = timersAggregates.get(label)
                if (current !== undefined) {
                  if (time[1] + current[1] > 1e9) {
                    time[0] += current[0] + 1
                    time[1] = time[1] - 1e9 + current[1]
                  } else {
                    time[0] += current[0]
                    time[1] += current[1]
                  }
                }
                timersAggregates.set(label, time)
              },
              timeAggregateEnd: (label: string) => {
                if (timersAggregates === undefined) return
                const time = timersAggregates.get(label)
                if (time === undefined) return
                timersAggregates.delete(label)
                logFn(LogType.time, [label, ...time])
              },
            }
          },
        },

        loaders: loadersWithOptions.map((loader) => ({
          loader: __turbopack_external_require__.resolve(loader.loader, {
            paths: [resourceDir],
          }),
          options: loader.options,
        })),
        readResource: (_filename, callback) => {
          // TODO assuming that filename === resource, but loaders might change that
          let data =
            typeof content === 'string'
              ? Buffer.from(content, 'utf-8')
              : Buffer.from(content.binary, 'base64')
          callback(null, data)
        },
      },
      (err, result) => {
        if (logs.length) {
          ipc.sendInfo({ type: 'log', logs: logs })
          logs.length = 0
        }
        ipc.sendInfo({
          type: 'dependencies',
          envVariables: getReadEnvVariables(),
          filePaths: result.fileDependencies.map(toPath),
          directories: result.contextDependencies.map((dep) => [
            toPath(dep),
            '**',
          ]),
        })
        if (err) return reject(err)
        if (!result.result) return reject(new Error('No result from loaders'))
        const [source, map] = result.result
        resolve({
          source: Buffer.isBuffer(source)
            ? { binary: source.toString('base64') }
            : source,
          map:
            typeof map === 'string'
              ? map
              : typeof map === 'object'
                ? JSON.stringify(map)
                : undefined,
        })
      }
    )
  })
}

export { transform as default }

function makeErrorEmitter(
  severity: 'warning' | 'error',
  ipc: Ipc<IpcInfoMessage, IpcRequestMessage>
) {
  return function (error: Error | string) {
    ipc.sendInfo({
      type: 'emittedError',
      severity: severity,
      error: structuredError(error),
    })
  }
}