vite 2.6.0-beta.0 → 2.6.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of vite might be problematic. Click here for more details.

Files changed (110) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/LICENSE.md +161 -3011
  3. package/bin/vite.js +2 -1
  4. package/dist/node/chunks/{dep-91aa74e8.js → dep-1e0a75a8.js} +58 -32
  5. package/dist/node/chunks/dep-1e0a75a8.js.map +1 -0
  6. package/dist/node/chunks/{dep-e36486f6.js → dep-ac1b4bf9.js} +1 -1
  7. package/dist/node/chunks/dep-ac1b4bf9.js.map +1 -0
  8. package/dist/node/chunks/{dep-c7e510f9.js → dep-ba6b30a0.js} +27538 -4953
  9. package/dist/node/chunks/dep-ba6b30a0.js.map +1 -0
  10. package/dist/node/chunks/{dep-11213a75.js → dep-c4cf6e92.js} +19 -6
  11. package/dist/node/chunks/dep-c4cf6e92.js.map +1 -0
  12. package/dist/node/chunks/{dep-eb6ef720.js → dep-d574094c.js} +18 -5
  13. package/dist/node/chunks/dep-d574094c.js.map +1 -0
  14. package/dist/node/chunks/{dep-0d2f9464.js → dep-e39b05d6.js} +18 -5
  15. package/dist/node/chunks/dep-e39b05d6.js.map +1 -0
  16. package/dist/node/cli.js +60 -23992
  17. package/dist/node/cli.js.map +1 -1
  18. package/dist/node/index.d.ts +26 -8
  19. package/dist/node/index.js +18 -15
  20. package/dist/node/index.js.map +1 -1
  21. package/dist/node/terser.js +102 -55
  22. package/package.json +28 -13
  23. package/types/package.json +3 -0
  24. package/api-extractor.json +0 -54
  25. package/dist/node/chunks/dep-0d2f9464.js.map +0 -1
  26. package/dist/node/chunks/dep-11213a75.js.map +0 -1
  27. package/dist/node/chunks/dep-91aa74e8.js.map +0 -1
  28. package/dist/node/chunks/dep-c7e510f9.js.map +0 -1
  29. package/dist/node/chunks/dep-e36486f6.js.map +0 -1
  30. package/dist/node/chunks/dep-eb6ef720.js.map +0 -1
  31. package/dist/node/terser.js.map +0 -1
  32. package/rollup.config.js +0 -389
  33. package/scripts/patchTypes.js +0 -70
  34. package/src/node/__tests__/asset.spec.ts +0 -156
  35. package/src/node/__tests__/build.spec.ts +0 -67
  36. package/src/node/__tests__/config.spec.ts +0 -166
  37. package/src/node/__tests__/packages/name/package.json +0 -3
  38. package/src/node/__tests__/packages/noname/package.json +0 -1
  39. package/src/node/__tests__/plugins/css.spec.ts +0 -116
  40. package/src/node/__tests__/scan.spec.ts +0 -118
  41. package/src/node/__tests__/utils.spec.ts +0 -40
  42. package/src/node/build.ts +0 -783
  43. package/src/node/cli.ts +0 -239
  44. package/src/node/config.ts +0 -1033
  45. package/src/node/constants.ts +0 -87
  46. package/src/node/importGlob.ts +0 -173
  47. package/src/node/index.ts +0 -88
  48. package/src/node/logger.ts +0 -167
  49. package/src/node/optimizer/esbuildDepPlugin.ts +0 -216
  50. package/src/node/optimizer/index.ts +0 -410
  51. package/src/node/optimizer/registerMissing.ts +0 -102
  52. package/src/node/optimizer/scan.ts +0 -457
  53. package/src/node/plugin.ts +0 -138
  54. package/src/node/plugins/asset.ts +0 -365
  55. package/src/node/plugins/assetImportMetaUrl.ts +0 -99
  56. package/src/node/plugins/clientInjections.ts +0 -72
  57. package/src/node/plugins/css.ts +0 -1279
  58. package/src/node/plugins/dataUri.ts +0 -64
  59. package/src/node/plugins/define.ts +0 -107
  60. package/src/node/plugins/esbuild.ts +0 -280
  61. package/src/node/plugins/html.ts +0 -673
  62. package/src/node/plugins/importAnalysis.ts +0 -614
  63. package/src/node/plugins/importAnalysisBuild.ts +0 -334
  64. package/src/node/plugins/index.ts +0 -69
  65. package/src/node/plugins/json.ts +0 -75
  66. package/src/node/plugins/loadFallback.ts +0 -19
  67. package/src/node/plugins/manifest.ts +0 -123
  68. package/src/node/plugins/modulePreloadPolyfill.ts +0 -100
  69. package/src/node/plugins/preAlias.ts +0 -22
  70. package/src/node/plugins/reporter.ts +0 -244
  71. package/src/node/plugins/resolve.ts +0 -925
  72. package/src/node/plugins/terser.ts +0 -40
  73. package/src/node/plugins/wasm.ts +0 -72
  74. package/src/node/plugins/worker.ts +0 -117
  75. package/src/node/preview.ts +0 -82
  76. package/src/node/server/__tests__/fixtures/none/nested/package.json +0 -3
  77. package/src/node/server/__tests__/fixtures/pnpm/nested/package.json +0 -3
  78. package/src/node/server/__tests__/fixtures/pnpm/package.json +0 -3
  79. package/src/node/server/__tests__/fixtures/pnpm/pnpm-workspace.yaml +0 -0
  80. package/src/node/server/__tests__/fixtures/yarn/nested/package.json +0 -3
  81. package/src/node/server/__tests__/fixtures/yarn/package.json +0 -6
  82. package/src/node/server/__tests__/search-root.spec.ts +0 -31
  83. package/src/node/server/hmr.ts +0 -489
  84. package/src/node/server/http.ts +0 -198
  85. package/src/node/server/index.ts +0 -705
  86. package/src/node/server/middlewares/base.ts +0 -52
  87. package/src/node/server/middlewares/error.ts +0 -98
  88. package/src/node/server/middlewares/indexHtml.ts +0 -170
  89. package/src/node/server/middlewares/proxy.ts +0 -124
  90. package/src/node/server/middlewares/spaFallback.ts +0 -32
  91. package/src/node/server/middlewares/static.ts +0 -153
  92. package/src/node/server/middlewares/time.ts +0 -18
  93. package/src/node/server/middlewares/transform.ts +0 -196
  94. package/src/node/server/moduleGraph.ts +0 -200
  95. package/src/node/server/openBrowser.ts +0 -101
  96. package/src/node/server/pluginContainer.ts +0 -546
  97. package/src/node/server/searchRoot.ts +0 -70
  98. package/src/node/server/send.ts +0 -54
  99. package/src/node/server/sourcemap.ts +0 -54
  100. package/src/node/server/transformRequest.ts +0 -168
  101. package/src/node/server/ws.ts +0 -131
  102. package/src/node/ssr/__tests__/ssrTransform.spec.ts +0 -309
  103. package/src/node/ssr/ssrExternal.ts +0 -161
  104. package/src/node/ssr/ssrManifestPlugin.ts +0 -53
  105. package/src/node/ssr/ssrModuleLoader.ts +0 -214
  106. package/src/node/ssr/ssrStacktrace.ts +0 -75
  107. package/src/node/ssr/ssrTransform.ts +0 -452
  108. package/src/node/tsconfig.json +0 -14
  109. package/src/node/utils.ts +0 -565
  110. package/tsconfig.base.json +0 -11
@@ -1,546 +0,0 @@
1
- /**
2
- * This file is refactored into TypeScript based on
3
- * https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
4
- */
5
-
6
- /**
7
- https://github.com/preactjs/wmr/blob/master/LICENSE
8
-
9
- MIT License
10
-
11
- Copyright (c) 2020 The Preact Authors
12
-
13
- Permission is hereby granted, free of charge, to any person obtaining a copy
14
- of this software and associated documentation files (the "Software"), to deal
15
- in the Software without restriction, including without limitation the rights
16
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
- copies of the Software, and to permit persons to whom the Software is
18
- furnished to do so, subject to the following conditions:
19
-
20
- The above copyright notice and this permission notice shall be included in all
21
- copies or substantial portions of the Software.
22
-
23
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
- SOFTWARE.
30
- */
31
-
32
- import fs from 'fs'
33
- import { resolve, join } from 'path'
34
- import { Plugin } from '../plugin'
35
- import {
36
- InputOptions,
37
- MinimalPluginContext,
38
- OutputOptions,
39
- ModuleInfo,
40
- NormalizedInputOptions,
41
- PartialResolvedId,
42
- ResolvedId,
43
- PluginContext as RollupPluginContext,
44
- LoadResult,
45
- SourceDescription,
46
- EmittedFile,
47
- SourceMap,
48
- RollupError,
49
- TransformResult
50
- } from 'rollup'
51
- import * as acorn from 'acorn'
52
- import acornClassFields from 'acorn-class-fields'
53
- import acornStaticClassFeatures from 'acorn-static-class-features'
54
- import { RawSourceMap } from '@ampproject/remapping/dist/types/types'
55
- import { combineSourcemaps } from '../utils'
56
- import MagicString from 'magic-string'
57
- import { FSWatcher } from 'chokidar'
58
- import {
59
- createDebugger,
60
- ensureWatchedFile,
61
- generateCodeFrame,
62
- isObject,
63
- isExternalUrl,
64
- normalizePath,
65
- numberToPos,
66
- prettifyUrl,
67
- timeFrom
68
- } from '../utils'
69
- import { FS_PREFIX } from '../constants'
70
- import chalk from 'chalk'
71
- import { ResolvedConfig } from '../config'
72
- import { buildErrorMessage } from './middlewares/error'
73
-
74
- export interface PluginContainerOptions {
75
- cwd?: string
76
- output?: OutputOptions
77
- modules?: Map<string, { info: ModuleInfo }>
78
- writeFile?: (name: string, source: string | Uint8Array) => void
79
- }
80
-
81
- export interface PluginContainer {
82
- options: InputOptions
83
- buildStart(options: InputOptions): Promise<void>
84
- resolveId(
85
- id: string,
86
- importer?: string,
87
- skip?: Set<Plugin>,
88
- ssr?: boolean
89
- ): Promise<PartialResolvedId | null>
90
- transform(
91
- code: string,
92
- id: string,
93
- inMap?: SourceDescription['map'],
94
- ssr?: boolean
95
- ): Promise<SourceDescription | null>
96
- load(id: string, ssr?: boolean): Promise<LoadResult | null>
97
- close(): Promise<void>
98
- }
99
-
100
- type PluginContext = Omit<
101
- RollupPluginContext,
102
- // not documented
103
- | 'cache'
104
- // deprecated
105
- | 'emitAsset'
106
- | 'emitChunk'
107
- | 'getAssetFileName'
108
- | 'getChunkFileName'
109
- | 'isExternal'
110
- | 'moduleIds'
111
- | 'resolveId'
112
- >
113
-
114
- export let parser = acorn.Parser.extend(
115
- acornClassFields,
116
- acornStaticClassFeatures
117
- )
118
-
119
- export async function createPluginContainer(
120
- { plugins, logger, root, build: { rollupOptions } }: ResolvedConfig,
121
- watcher?: FSWatcher
122
- ): Promise<PluginContainer> {
123
- const isDebug = process.env.DEBUG
124
-
125
- const seenResolves: Record<string, true | undefined> = {}
126
- const debugResolve = createDebugger('vite:resolve')
127
- const debugPluginResolve = createDebugger('vite:plugin-resolve', {
128
- onlyWhenFocused: 'vite:plugin'
129
- })
130
- const debugPluginTransform = createDebugger('vite:plugin-transform', {
131
- onlyWhenFocused: 'vite:plugin'
132
- })
133
-
134
- // ---------------------------------------------------------------------------
135
-
136
- const MODULES = new Map()
137
- const watchFiles = new Set<string>()
138
-
139
- // get rollup version
140
- const rollupPkgPath = resolve(require.resolve('rollup'), '../../package.json')
141
- const minimalContext: MinimalPluginContext = {
142
- meta: {
143
- rollupVersion: JSON.parse(fs.readFileSync(rollupPkgPath, 'utf-8'))
144
- .version,
145
- watchMode: true
146
- }
147
- }
148
-
149
- function warnIncompatibleMethod(method: string, plugin: string) {
150
- logger.warn(
151
- chalk.cyan(`[plugin:${plugin}] `) +
152
- chalk.yellow(
153
- `context method ${chalk.bold(
154
- `${method}()`
155
- )} is not supported in serve mode. This plugin is likely not vite-compatible.`
156
- )
157
- )
158
- }
159
-
160
- // we should create a new context for each async hook pipeline so that the
161
- // active plugin in that pipeline can be tracked in a concurrency-safe manner.
162
- // using a class to make creating new contexts more efficient
163
- class Context implements PluginContext {
164
- meta = minimalContext.meta
165
- ssr = false
166
- _activePlugin: Plugin | null
167
- _activeId: string | null = null
168
- _activeCode: string | null = null
169
- _resolveSkips?: Set<Plugin>
170
- _addedImports: Set<string> | null = null
171
-
172
- constructor(initialPlugin?: Plugin) {
173
- this._activePlugin = initialPlugin || null
174
- }
175
-
176
- parse(code: string, opts: any = {}) {
177
- return parser.parse(code, {
178
- sourceType: 'module',
179
- ecmaVersion: 2020,
180
- locations: true,
181
- ...opts
182
- })
183
- }
184
-
185
- async resolve(
186
- id: string,
187
- importer?: string,
188
- options?: { skipSelf?: boolean }
189
- ) {
190
- let skips: Set<Plugin> | undefined
191
- if (options?.skipSelf && this._activePlugin) {
192
- skips = new Set(this._resolveSkips)
193
- skips.add(this._activePlugin)
194
- }
195
- let out = await container.resolveId(id, importer, skips, this.ssr)
196
- if (typeof out === 'string') out = { id: out }
197
- return out as ResolvedId | null
198
- }
199
-
200
- getModuleInfo(id: string) {
201
- let mod = MODULES.get(id)
202
- if (mod) return mod.info
203
- mod = {
204
- /** @type {import('rollup').ModuleInfo} */
205
- // @ts-ignore-next
206
- info: {}
207
- }
208
- MODULES.set(id, mod)
209
- return mod.info
210
- }
211
-
212
- getModuleIds() {
213
- return MODULES.keys()
214
- }
215
-
216
- addWatchFile(id: string) {
217
- watchFiles.add(id)
218
- ;(this._addedImports || (this._addedImports = new Set())).add(id)
219
- if (watcher) ensureWatchedFile(watcher, id, root)
220
- }
221
-
222
- getWatchFiles() {
223
- return [...watchFiles]
224
- }
225
-
226
- emitFile(assetOrFile: EmittedFile) {
227
- warnIncompatibleMethod(`emitFile`, this._activePlugin!.name)
228
- return ''
229
- }
230
-
231
- setAssetSource() {
232
- warnIncompatibleMethod(`setAssetSource`, this._activePlugin!.name)
233
- }
234
-
235
- getFileName() {
236
- warnIncompatibleMethod(`getFileName`, this._activePlugin!.name)
237
- return ''
238
- }
239
-
240
- warn(
241
- e: string | RollupError,
242
- position?: number | { column: number; line: number }
243
- ) {
244
- const err = formatError(e, position, this)
245
- const msg = buildErrorMessage(
246
- err,
247
- [chalk.yellow(`warning: ${err.message}`)],
248
- false
249
- )
250
- logger.warn(msg, {
251
- clear: true,
252
- timestamp: true
253
- })
254
- }
255
-
256
- error(
257
- e: string | RollupError,
258
- position?: number | { column: number; line: number }
259
- ): never {
260
- // error thrown here is caught by the transform middleware and passed on
261
- // the the error middleware.
262
- throw formatError(e, position, this)
263
- }
264
- }
265
-
266
- function formatError(
267
- e: string | RollupError,
268
- position: number | { column: number; line: number } | undefined,
269
- ctx: Context
270
- ) {
271
- const err = (typeof e === 'string' ? new Error(e) : e) as RollupError
272
- if (ctx._activePlugin) err.plugin = ctx._activePlugin.name
273
- if (ctx._activeId && !err.id) err.id = ctx._activeId
274
- if (ctx._activeCode) {
275
- err.pluginCode = ctx._activeCode
276
- const pos =
277
- position != null
278
- ? position
279
- : err.pos != null
280
- ? err.pos
281
- : // some rollup plugins, e.g. json, sets position instead of pos
282
- (err as any).position
283
- if (pos != null) {
284
- let errLocation
285
- try {
286
- errLocation = numberToPos(ctx._activeCode, pos)
287
- } catch (err2) {
288
- logger.error(
289
- chalk.red(
290
- `Error in error handler:\n${err2.stack || err2.message}\n`
291
- ),
292
- // print extra newline to separate the two errors
293
- { error: err2 }
294
- )
295
- throw err
296
- }
297
- err.loc = err.loc || {
298
- file: err.id,
299
- ...errLocation
300
- }
301
- err.frame = err.frame || generateCodeFrame(ctx._activeCode, pos)
302
- } else if (err.loc) {
303
- // css preprocessors may report errors in an included file
304
- if (!err.frame) {
305
- let code = ctx._activeCode
306
- if (err.loc.file) {
307
- err.id = normalizePath(err.loc.file)
308
- try {
309
- code = fs.readFileSync(err.loc.file, 'utf-8')
310
- } catch {}
311
- }
312
- err.frame = generateCodeFrame(code, err.loc)
313
- }
314
- } else if ((err as any).line && (err as any).column) {
315
- err.loc = {
316
- file: err.id,
317
- line: (err as any).line,
318
- column: (err as any).column
319
- }
320
- err.frame = err.frame || generateCodeFrame(ctx._activeCode, err.loc)
321
- }
322
- }
323
- return err
324
- }
325
-
326
- class TransformContext extends Context {
327
- filename: string
328
- originalCode: string
329
- originalSourcemap: SourceMap | null = null
330
- sourcemapChain: NonNullable<SourceDescription['map']>[] = []
331
- combinedMap: SourceMap | null = null
332
-
333
- constructor(filename: string, code: string, inMap?: SourceMap | string) {
334
- super()
335
- this.filename = filename
336
- this.originalCode = code
337
- if (inMap) {
338
- this.sourcemapChain.push(inMap)
339
- }
340
- }
341
-
342
- _getCombinedSourcemap(createIfNull = false) {
343
- let combinedMap = this.combinedMap
344
- for (let m of this.sourcemapChain) {
345
- if (typeof m === 'string') m = JSON.parse(m)
346
- if (!('version' in (m as SourceMap))) {
347
- // empty, nullified source map
348
- combinedMap = this.combinedMap = null
349
- this.sourcemapChain.length = 0
350
- break
351
- }
352
- if (!combinedMap) {
353
- combinedMap = m as SourceMap
354
- } else {
355
- combinedMap = combineSourcemaps(this.filename, [
356
- {
357
- ...(m as RawSourceMap),
358
- sourcesContent: combinedMap.sourcesContent
359
- },
360
- combinedMap as RawSourceMap
361
- ]) as SourceMap
362
- }
363
- }
364
- if (!combinedMap) {
365
- return createIfNull
366
- ? new MagicString(this.originalCode).generateMap({
367
- includeContent: true,
368
- hires: true,
369
- source: this.filename
370
- })
371
- : null
372
- }
373
- if (combinedMap !== this.combinedMap) {
374
- this.combinedMap = combinedMap
375
- this.sourcemapChain.length = 0
376
- }
377
- return this.combinedMap
378
- }
379
-
380
- getCombinedSourcemap() {
381
- return this._getCombinedSourcemap(true) as SourceMap
382
- }
383
- }
384
-
385
- let closed = false
386
-
387
- const container: PluginContainer = {
388
- options: await (async () => {
389
- let options = rollupOptions
390
- for (const plugin of plugins) {
391
- if (!plugin.options) continue
392
- options =
393
- (await plugin.options.call(minimalContext, options)) || options
394
- }
395
- if (options.acornInjectPlugins) {
396
- parser = acorn.Parser.extend(
397
- ...[acornClassFields, acornStaticClassFeatures].concat(
398
- options.acornInjectPlugins
399
- )
400
- )
401
- }
402
- return {
403
- acorn,
404
- acornInjectPlugins: [],
405
- ...options
406
- }
407
- })(),
408
-
409
- async buildStart() {
410
- await Promise.all(
411
- plugins.map((plugin) => {
412
- if (plugin.buildStart) {
413
- return plugin.buildStart.call(
414
- new Context(plugin) as any,
415
- container.options as NormalizedInputOptions
416
- )
417
- }
418
- })
419
- )
420
- },
421
-
422
- async resolveId(rawId, importer = join(root, 'index.html'), skips, ssr) {
423
- const ctx = new Context()
424
- ctx.ssr = !!ssr
425
- ctx._resolveSkips = skips
426
- const resolveStart = isDebug ? Date.now() : 0
427
-
428
- let id: string | null = null
429
- const partial: Partial<PartialResolvedId> = {}
430
- for (const plugin of plugins) {
431
- if (!plugin.resolveId) continue
432
- if (skips?.has(plugin)) continue
433
-
434
- ctx._activePlugin = plugin
435
-
436
- const pluginResolveStart = isDebug ? Date.now() : 0
437
- const result = await plugin.resolveId.call(
438
- ctx as any,
439
- rawId,
440
- importer,
441
- {},
442
- ssr
443
- )
444
- if (!result) continue
445
-
446
- if (typeof result === 'string') {
447
- id = result
448
- } else {
449
- id = result.id
450
- Object.assign(partial, result)
451
- }
452
-
453
- isDebug &&
454
- debugPluginResolve(
455
- timeFrom(pluginResolveStart),
456
- plugin.name,
457
- prettifyUrl(id, root)
458
- )
459
-
460
- // resolveId() is hookFirst - first non-null result is returned.
461
- break
462
- }
463
-
464
- if (isDebug && rawId !== id && !rawId.startsWith(FS_PREFIX)) {
465
- const key = rawId + id
466
- // avoid spamming
467
- if (!seenResolves[key]) {
468
- seenResolves[key] = true
469
- debugResolve(
470
- `${timeFrom(resolveStart)} ${chalk.cyan(rawId)} -> ${chalk.dim(id)}`
471
- )
472
- }
473
- }
474
-
475
- if (id) {
476
- partial.id = isExternalUrl(id) ? id : normalizePath(id)
477
- return partial as PartialResolvedId
478
- } else {
479
- return null
480
- }
481
- },
482
-
483
- async load(id, ssr) {
484
- const ctx = new Context()
485
- ctx.ssr = !!ssr
486
- for (const plugin of plugins) {
487
- if (!plugin.load) continue
488
- ctx._activePlugin = plugin
489
- const result = await plugin.load.call(ctx as any, id, ssr)
490
- if (result != null) {
491
- return result
492
- }
493
- }
494
- return null
495
- },
496
-
497
- async transform(code, id, inMap, ssr) {
498
- const ctx = new TransformContext(id, code, inMap as SourceMap)
499
- ctx.ssr = !!ssr
500
- for (const plugin of plugins) {
501
- if (!plugin.transform) continue
502
- ctx._activePlugin = plugin
503
- ctx._activeId = id
504
- ctx._activeCode = code
505
- const start = isDebug ? Date.now() : 0
506
- let result: TransformResult | string | undefined
507
- try {
508
- result = await plugin.transform.call(ctx as any, code, id, ssr)
509
- } catch (e) {
510
- ctx.error(e)
511
- }
512
- if (!result) continue
513
- isDebug &&
514
- debugPluginTransform(
515
- timeFrom(start),
516
- plugin.name,
517
- prettifyUrl(id, root)
518
- )
519
- if (isObject(result)) {
520
- code = result.code || ''
521
- if (result.map) ctx.sourcemapChain.push(result.map)
522
- } else {
523
- code = result
524
- }
525
- }
526
- return {
527
- code,
528
- map: ctx._getCombinedSourcemap()
529
- }
530
- },
531
-
532
- async close() {
533
- if (closed) return
534
- const ctx = new Context()
535
- await Promise.all(
536
- plugins.map((p) => p.buildEnd && p.buildEnd.call(ctx as any))
537
- )
538
- await Promise.all(
539
- plugins.map((p) => p.closeBundle && p.closeBundle.call(ctx as any))
540
- )
541
- closed = true
542
- }
543
- }
544
-
545
- return container
546
- }
@@ -1,70 +0,0 @@
1
- import fs from 'fs'
2
- import { dirname } from 'path'
3
- import { join } from 'path'
4
-
5
- // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
6
- const ROOT_FILES = [
7
- // '.git',
8
-
9
- // https://pnpm.js.org/workspaces/
10
- 'pnpm-workspace.yaml'
11
-
12
- // https://rushjs.io/pages/advanced/config_files/
13
- // 'rush.json',
14
-
15
- // https://nx.dev/latest/react/getting-started/nx-setup
16
- // 'workspace.json',
17
- // 'nx.json'
18
- ]
19
-
20
- // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces
21
- // yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it
22
- function hasWorkspacePackageJSON(root: string): boolean {
23
- const path = join(root, 'package.json')
24
- try {
25
- fs.accessSync(path, fs.constants.R_OK)
26
- } catch {
27
- return false
28
- }
29
- const content = JSON.parse(fs.readFileSync(path, 'utf-8')) || {}
30
- return !!content.workspaces
31
- }
32
-
33
- function hasRootFile(root: string): boolean {
34
- return ROOT_FILES.some((file) => fs.existsSync(join(root, file)))
35
- }
36
-
37
- function hasPackageJSON(root: string) {
38
- const path = join(root, 'package.json')
39
- return fs.existsSync(path)
40
- }
41
-
42
- /**
43
- * Search up for the nearest `package.json`
44
- */
45
- export function searchForPackageRoot(current: string, root = current): string {
46
- if (hasPackageJSON(current)) return current
47
-
48
- const dir = dirname(current)
49
- // reach the fs root
50
- if (!dir || dir === current) return root
51
-
52
- return searchForPackageRoot(dir, root)
53
- }
54
-
55
- /**
56
- * Search up for the nearest workspace root
57
- */
58
- export function searchForWorkspaceRoot(
59
- current: string,
60
- root = searchForPackageRoot(current)
61
- ): string {
62
- if (hasRootFile(current)) return current
63
- if (hasWorkspacePackageJSON(current)) return current
64
-
65
- const dir = dirname(current)
66
- // reach the fs root
67
- if (!dir || dir === current) return root
68
-
69
- return searchForWorkspaceRoot(dir, root)
70
- }
@@ -1,54 +0,0 @@
1
- import { IncomingMessage, ServerResponse } from 'http'
2
- import getEtag from 'etag'
3
- import { SourceMap } from 'rollup'
4
-
5
- const isDebug = process.env.DEBUG
6
-
7
- const alias: Record<string, string | undefined> = {
8
- js: 'application/javascript',
9
- css: 'text/css',
10
- html: 'text/html',
11
- json: 'application/json'
12
- }
13
-
14
- export function send(
15
- req: IncomingMessage,
16
- res: ServerResponse,
17
- content: string | Buffer,
18
- type: string,
19
- etag = getEtag(content, { weak: true }),
20
- cacheControl = 'no-cache',
21
- map?: SourceMap | null
22
- ): void {
23
- if (req.headers['if-none-match'] === etag) {
24
- res.statusCode = 304
25
- return res.end()
26
- }
27
-
28
- res.setHeader('Content-Type', alias[type] || type)
29
- res.setHeader('Cache-Control', cacheControl)
30
- res.setHeader('Etag', etag)
31
-
32
- // inject source map reference
33
- if (map && map.mappings) {
34
- if (isDebug) {
35
- content += `\n/*${JSON.stringify(map, null, 2).replace(
36
- /\*\//g,
37
- '*\\/'
38
- )}*/\n`
39
- }
40
- content += genSourceMapString(map)
41
- }
42
-
43
- res.statusCode = 200
44
- return res.end(content)
45
- }
46
-
47
- function genSourceMapString(map: SourceMap | string | undefined) {
48
- if (typeof map !== 'string') {
49
- map = JSON.stringify(map)
50
- }
51
- return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(
52
- map
53
- ).toString('base64')}`
54
- }