jiek 2.3.2 → 2.3.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.
Files changed (81) hide show
  1. package/dist/.internal/.chunks/{filterSupport.4rM7f6jB.cjs → getWD.Bdo2NGCR.cjs} +30 -30
  2. package/dist/.internal/.chunks/{filterSupport.BXWpLBpT.js → getWD.DGvwAHMY.js} +29 -29
  3. package/dist/.internal/.chunks/{loadConfig.OOKddvHF.cjs → loadConfig.8xhNFEJe.cjs} +30 -12
  4. package/dist/.internal/.chunks/{loadConfig.CFfzkm_p.js → loadConfig.BjzxLOdC.js} +26 -9
  5. package/dist/.internal/bin/common.cjs +92 -97
  6. package/dist/.internal/bin/common.d.cts +2 -0
  7. package/dist/.internal/bin/common.d.ts +2 -0
  8. package/dist/.internal/bin/common.js +93 -98
  9. package/dist/.internal/bin/parseArgv.cjs +2 -2
  10. package/dist/.internal/bin/parseArgv.js +2 -2
  11. package/dist/.internal/commands/utils/createAreaManagement.cjs +108 -0
  12. package/dist/.internal/commands/utils/createAreaManagement.d.cts +18 -0
  13. package/dist/.internal/commands/utils/createAreaManagement.d.ts +18 -0
  14. package/dist/.internal/commands/utils/createAreaManagement.js +106 -0
  15. package/dist/.internal/polyfill.cjs +13 -0
  16. package/dist/.internal/polyfill.d.cts +1 -0
  17. package/dist/.internal/polyfill.d.ts +1 -0
  18. package/dist/.internal/polyfill.js +11 -0
  19. package/dist/.internal/rollup/base.d.cts +27 -4
  20. package/dist/.internal/rollup/base.d.ts +27 -4
  21. package/dist/.internal/utils/filterSupport.cjs +1 -1
  22. package/dist/.internal/utils/filterSupport.js +2 -2
  23. package/dist/.internal/utils/loadConfig.cjs +3 -3
  24. package/dist/.internal/utils/loadConfig.d.cts +1 -0
  25. package/dist/.internal/utils/loadConfig.d.ts +1 -0
  26. package/dist/.internal/utils/loadConfig.js +4 -4
  27. package/dist/.internal/utils/pascalCase.cjs +5 -0
  28. package/dist/.internal/utils/pascalCase.d.cts +3 -0
  29. package/dist/.internal/utils/pascalCase.d.ts +3 -0
  30. package/dist/.internal/utils/pascalCase.js +3 -0
  31. package/dist/.internal/utils/reveal.cjs +9 -0
  32. package/dist/.internal/utils/reveal.d.cts +3 -0
  33. package/dist/.internal/utils/reveal.d.ts +3 -0
  34. package/dist/.internal/utils/reveal.js +7 -0
  35. package/dist/bin/index.cjs +101 -43
  36. package/dist/index.d.cts +7 -0
  37. package/dist/index.d.ts +7 -0
  38. package/dist/rollup/index.cjs +91 -31
  39. package/dist/rollup/index.js +90 -30
  40. package/package.json +6 -2
  41. package/src/bin/build.cts +0 -5
  42. package/src/bin/common.ts +0 -3
  43. package/src/bin/index.cts +0 -7
  44. package/src/bin/parseArgv.ts +0 -26
  45. package/src/bridge.ts +0 -46
  46. package/src/commands/base.ts +0 -18
  47. package/src/commands/build/analyzer.ts +0 -122
  48. package/src/commands/build/client/analyzer.tsx +0 -121
  49. package/src/commands/build/client/index.ts +0 -26
  50. package/src/commands/build.ts +0 -544
  51. package/src/commands/descriptions.ts +0 -17
  52. package/src/commands/meta.ts +0 -5
  53. package/src/commands/publish.ts +0 -628
  54. package/src/commands/utils/optionParser.ts +0 -4
  55. package/src/index.ts +0 -12
  56. package/src/inner.ts +0 -11
  57. package/src/rollup/base.ts +0 -151
  58. package/src/rollup/bundle-analyzer.ts +0 -62
  59. package/src/rollup/index.ts +0 -892
  60. package/src/rollup/plugins/create-require.ts +0 -23
  61. package/src/rollup/plugins/progress.ts +0 -26
  62. package/src/rollup/plugins/replace.ts +0 -96
  63. package/src/rollup/plugins/skip.ts +0 -21
  64. package/src/rollup/plugins/with-external.ts +0 -23
  65. package/src/rollup/utils/commonOptions.ts +0 -9
  66. package/src/rollup/utils/externalResolver.ts +0 -47
  67. package/src/rollup/utils/globalResolver.ts +0 -13
  68. package/src/rollup/utils/withMinify.ts +0 -18
  69. package/src/rollup-plugin-utils.ts +0 -32
  70. package/src/server.ts +0 -30
  71. package/src/utils/checkDependency.ts +0 -26
  72. package/src/utils/filterSupport.ts +0 -90
  73. package/src/utils/getInternalModuleName.ts +0 -5
  74. package/src/utils/getRoot.ts +0 -14
  75. package/src/utils/getWD.ts +0 -31
  76. package/src/utils/intersection.ts +0 -1
  77. package/src/utils/loadConfig.ts +0 -108
  78. package/src/utils/recursiveListFiles.ts +0 -13
  79. package/src/utils/resolveExports.ts +0 -165
  80. package/src/utils/ts.ts +0 -94
  81. package/src/utils/tsRegister.ts +0 -22
@@ -1,892 +0,0 @@
1
- /* eslint-disable ts/strict-boolean-expressions */
2
- import fs from 'node:fs'
3
- import { dirname, extname, relative, resolve } from 'node:path'
4
- import process from 'node:process'
5
-
6
- import type { RecursiveRecord } from '@jiek/pkger/entrypoints'
7
- import { getAllLeafs } from '@jiek/pkger/entrypoints'
8
- import { dts } from '@jiek/rollup-plugin-dts'
9
- import { getWorkspaceDir } from '@jiek/utils/getWorkspaceDir'
10
- import commonjs from '@rollup/plugin-commonjs'
11
- import inject from '@rollup/plugin-inject'
12
- import json from '@rollup/plugin-json'
13
- import { nodeResolve } from '@rollup/plugin-node-resolve'
14
- import type { InputPluginOption, OutputOptions, OutputPlugin, OutputPluginOption, Plugin, RollupOptions } from 'rollup'
15
- import ts from 'typescript'
16
-
17
- import type { RollupBuildEntryCtx, RollupBuildEventMap } from '#~/bridge'
18
- import { publish } from '#~/bridge'
19
- import { bundleAnalyzer } from '#~/rollup/bundle-analyzer'
20
- import { getInternalModuleName } from '#~/utils/getInternalModuleName'
21
- import { intersection } from '#~/utils/intersection'
22
- import { loadConfig } from '#~/utils/loadConfig'
23
- import { recursiveListFiles } from '#~/utils/recursiveListFiles'
24
- import { getOutDirs, resolveExports } from '#~/utils/resolveExports'
25
- import { getCompilerOptionsByFilePath } from '#~/utils/ts'
26
-
27
- import type { ConfigGenerateContext, TemplateOptions } from './base'
28
- import createRequire, { CREATE_REQUIRE_VIRTUAL_MODULE_NAME } from './plugins/create-require'
29
- import progress from './plugins/progress'
30
- import replace from './plugins/replace'
31
- import skip from './plugins/skip'
32
- import withExternal from './plugins/with-external.ts'
33
- import type { PackageJSON } from './utils/externalResolver'
34
- import externalResolver from './utils/externalResolver'
35
-
36
- const {
37
- JIEK_ROOT,
38
- JIEK_NAME,
39
- JIEK_BUILDER,
40
- JIEK_ENTRIES,
41
- JIEK_EXTERNAL,
42
- JIEK_WITHOUT_JS,
43
- JIEK_WITHOUT_DTS,
44
- JIEK_WITHOUT_MINIFY,
45
- JIEK_MINIFY_TYPE,
46
- JIEK_CLEAN,
47
- JIEK_ONLY_MINIFY,
48
- JIEK_TSCONFIG,
49
- JIEK_DTSCONFIG,
50
- JIEK_SKIP_JS,
51
- JIEK_FEATURES
52
- } = process.env
53
-
54
- const resolveArrayString = (str: string | undefined) => {
55
- const arr = [
56
- ...new Set(
57
- str
58
- ?.split(',')
59
- .map(e => e.trim())
60
- .filter(e => e.length > 0)
61
- ?? []
62
- )
63
- ]
64
- return arr?.length ? arr : undefined
65
- }
66
-
67
- const entries = resolveArrayString(JIEK_ENTRIES)?.map(e => ({ 'index': '.' }[e] ?? e))
68
-
69
- const commandExternal = resolveArrayString(JIEK_EXTERNAL)?.map(e => new RegExp(`^${e}$`))
70
-
71
- const WORKSPACE_ROOT = JIEK_ROOT ?? getWorkspaceDir()
72
- const COMMON_OPTIONS = {} satisfies RollupOptions
73
- const COMMON_PLUGINS = [
74
- json()
75
- ]
76
-
77
- const INTERNAL_MODULE_NAME = getInternalModuleName(JIEK_NAME!)
78
-
79
- const WITHOUT_JS = JIEK_WITHOUT_JS === 'true'
80
- const WITHOUT_DTS = JIEK_WITHOUT_DTS === 'true'
81
- const WITHOUT_MINIFY = JIEK_WITHOUT_MINIFY === 'true'
82
-
83
- const ONLY_MINIFY = JIEK_ONLY_MINIFY === 'true'
84
-
85
- const CLEAN = JIEK_CLEAN === 'true'
86
-
87
- const SKIP_JS = JIEK_SKIP_JS === 'false'
88
- ? false
89
- : JIEK_SKIP_JS === 'true'
90
- ? true
91
- : undefined
92
-
93
- const FEATURES = JSON.parse(JIEK_FEATURES ?? '{}') as Record<string, unknown>
94
-
95
- const MINIFY_DEFAULT_VALUE = WITHOUT_MINIFY
96
- ? false
97
- : ONLY_MINIFY
98
- ? 'only-minify'
99
- : true
100
-
101
- type BuilderOptions = NonNullable<TemplateOptions['builder']>
102
-
103
- const BUILDER_OPTIONS = {
104
- type: JIEK_BUILDER ?? 'esbuild'
105
- } as NonNullable<Exclude<BuilderOptions, string>>
106
-
107
- type MinifyOptions = NonNullable<TemplateOptions['output']>['minifyOptions']
108
-
109
- const MINIFY_OPTIONS = {
110
- type: JIEK_MINIFY_TYPE ?? 'esbuild'
111
- } as NonNullable<Exclude<MinifyOptions, string>>
112
-
113
- const config = loadConfig({
114
- root: WORKSPACE_ROOT
115
- }) ?? {}
116
- const {
117
- experimental,
118
- skipJS,
119
- build = {}
120
- } = config
121
- const { js: jsOutdir, dts: dtsOutdir } = getOutDirs({
122
- config,
123
- pkgName: JIEK_NAME
124
- })
125
-
126
- if (CLEAN) {
127
- fs.existsSync(jsOutdir) && fs.rmdirSync(jsOutdir, { recursive: true })
128
- fs.existsSync(dtsOutdir) && fs.rmdirSync(dtsOutdir, { recursive: true })
129
- }
130
-
131
- const STYLE_REGEXP = /\.(css|s[ac]ss|less|styl)$/
132
-
133
- const CWD_FILES = recursiveListFiles(process.cwd())
134
- .filter(p => /(?<!\.d)\.[cm]?tsx?$/.test(p))
135
- .map(p => `./${relative(process.cwd(), p)}`)
136
-
137
- const resolveBuildPlugins = (context: ConfigGenerateContext, plugins: TemplateOptions['plugins']): {
138
- js: InputPluginOption
139
- dts: InputPluginOption
140
- } => {
141
- if (plugins === false || plugins === undefined || plugins === null) {
142
- return { js: [], dts: [] }
143
- }
144
- let js: InputPluginOption = []
145
- let dts: InputPluginOption = []
146
- // eslint-disable-next-line ts/switch-exhaustiveness-check
147
- switch (typeof plugins) {
148
- case 'function':
149
- js = plugins('js', context)
150
- dts = plugins('dts', context)
151
- break
152
- case 'object':
153
- if ('js' in plugins || 'dts' in plugins) {
154
- js = plugins.js ?? []
155
- dts = plugins.dts ?? []
156
- } else {
157
- js = plugins
158
- dts = plugins
159
- }
160
- break
161
- }
162
- return { js, dts }
163
- }
164
-
165
- const resolveOutputControls = (
166
- context: ConfigGenerateContext,
167
- output: TemplateOptions['output']
168
- ): { js: boolean; dts: boolean } => ({
169
- js: typeof output?.js === 'boolean'
170
- ? output.js
171
- : typeof output?.js === 'function'
172
- ? output.js(context)
173
- : true,
174
- dts: typeof output?.dts === 'boolean'
175
- ? output.dts
176
- : typeof output?.dts === 'function'
177
- ? output.dts(context)
178
- : true
179
- })
180
-
181
- const resolveWorkspacePath = (p: string) => resolve(WORKSPACE_ROOT, p)
182
-
183
- const pascalCase = (str: string) =>
184
- str
185
- // eslint-disable-next-line ts/no-unsafe-member-access,ts/no-unsafe-return,ts/no-unsafe-call
186
- .replace(/[@|/-](\w)/g, (_, $1) => $1.toUpperCase())
187
- // eslint-disable-next-line ts/no-unsafe-member-access,ts/no-unsafe-return,ts/no-unsafe-call
188
- .replace(/(?:^|-)(\w)/g, (_, $1) => $1.toUpperCase())
189
-
190
- const reveal = (obj: string | Record<string, unknown>, keys: string[]) =>
191
- keys.reduce((acc, key) => {
192
- if (typeof acc === 'string') throw new Error('key not found in exports')
193
- if (!(key in acc)) throw new Error(`key ${key} not found in exports`)
194
- return acc[key] as string | Record<string, unknown>
195
- }, obj)
196
-
197
- const resolveMinifyOptions = (minifyOptions: MinifyOptions): typeof MINIFY_OPTIONS =>
198
- typeof minifyOptions === 'string'
199
- ? { type: minifyOptions }
200
- : minifyOptions ?? { type: 'esbuild' }
201
-
202
- const resolveBuilderOptions = (
203
- builder: TemplateOptions['builder']
204
- ): Exclude<TemplateOptions['builder'], string | undefined> =>
205
- typeof builder === 'string'
206
- ? { type: builder }
207
- : builder ?? { type: 'esbuild' }
208
-
209
- const resolvedMinifyOptions = resolveMinifyOptions(build.output?.minifyOptions ?? MINIFY_OPTIONS)
210
- const { type: _resolvedMinifyOptionsType, ...noTypeResolvedMinifyOptions } = resolvedMinifyOptions
211
- const resolvedBuilderOptions = resolveBuilderOptions(build.builder ?? BUILDER_OPTIONS)
212
- const { type: _resolvedBuilderOptionsType, ...noTypeResolvedBuilderOptions } = resolvedBuilderOptions
213
-
214
- const withMinify = (
215
- output: OutputOptions & {
216
- plugins?: OutputPlugin[]
217
- },
218
- disableMinify?: boolean,
219
- onlyOncePlugins: OutputPluginOption[] = []
220
- ): OutputOptions[] => {
221
- const minify = disableMinify !== undefined
222
- ? !disableMinify
223
- : build?.output?.minify ?? MINIFY_DEFAULT_VALUE
224
-
225
- output.plugins = output.plugins ?? []
226
- const notOnlyOncePlugins = [...output.plugins]
227
- output.plugins.push(...onlyOncePlugins)
228
-
229
- if (minify === false) {
230
- return [output]
231
- }
232
-
233
- const minifyPlugin = resolvedMinifyOptions.type === 'esbuild'
234
- // eslint-disable-next-line ts/no-unsafe-argument
235
- ? import('rollup-plugin-esbuild').then(({ minify }) => minify(noTypeResolvedMinifyOptions as any))
236
- : resolvedMinifyOptions.type === 'swc'
237
- // eslint-disable-next-line ts/no-unsafe-argument
238
- ? import('rollup-plugin-swc3').then(({ minify }) => minify(noTypeResolvedMinifyOptions as any))
239
- // eslint-disable-next-line ts/no-unsafe-argument
240
- : import('@rollup/plugin-terser').then(({ default: minify }) => minify(noTypeResolvedMinifyOptions as any))
241
- return minify === 'only-minify'
242
- ? [{
243
- ...output,
244
- // TODO replace suffix when publish to npm and the `build.output.minify` is 'only-minify'
245
- // TODO resolve dts output file name
246
- entryFileNames: chunkInfo =>
247
- typeof output.entryFileNames === 'function'
248
- ? output.entryFileNames(chunkInfo)
249
- : (() => {
250
- throw new TypeError('entryFileNames must be a function')
251
- })(),
252
- plugins: [
253
- ...output.plugins,
254
- ...notOnlyOncePlugins,
255
- minifyPlugin
256
- ]
257
- }]
258
- : [
259
- output,
260
- {
261
- ...output,
262
- entryFileNames: chunkInfo =>
263
- typeof output.entryFileNames === 'function'
264
- ? output.entryFileNames(chunkInfo).replace(/(\.[cm]?js)$/, '.min$1')
265
- : (() => {
266
- throw new Error('entryFileNames must be a function')
267
- })(),
268
- chunkFileNames: chunkInfo =>
269
- typeof output.chunkFileNames === 'function'
270
- ? output.chunkFileNames(chunkInfo).replace(/(\.[cm]?js)$/, '.min$1')
271
- : (() => {
272
- throw new Error('chunkFileNames must be a function')
273
- })(),
274
- file: output.file?.replace(/(\.[cm]?js)$/, '.min$1'),
275
- plugins: [
276
- ...notOnlyOncePlugins,
277
- minifyPlugin
278
- ]
279
- }
280
- ]
281
- }
282
-
283
- interface GenerateConfigsOptions {
284
- internalModuleCollect?: (id: string) => void
285
- commonPlugins?: InputPluginOption[]
286
- disableDTS?: boolean
287
- disableMinify?: boolean
288
- disableCollectInternalModule?: boolean
289
- }
290
-
291
- const generateConfigs = (
292
- context: ConfigGenerateContext,
293
- {
294
- internalModuleCollect,
295
- commonPlugins: inputCommonPlugins = [],
296
- disableDTS = false,
297
- disableMinify,
298
- disableCollectInternalModule
299
- }: GenerateConfigsOptions = {}
300
- ): RollupOptions[] => {
301
- const buildOptions: TemplateOptions = build
302
- const {
303
- path,
304
- name,
305
- input,
306
- output,
307
- external: inputExternal,
308
- pkgIsModule,
309
- conditionals
310
- } = context
311
- const external = [...inputExternal, ...(buildOptions.external ?? []), ...(commandExternal ?? [])]
312
- const isModule = conditionals.includes('import')
313
- const isCommonJS = conditionals.includes('require')
314
- const isBrowser = conditionals.includes('browser')
315
- const format = isModule ? 'esm' : (
316
- isCommonJS ? 'cjs' : (
317
- isBrowser ? 'umd' : (
318
- pkgIsModule ? 'esm' : 'cjs'
319
- )
320
- )
321
- )
322
-
323
- const dtsTSConfigPaths = [
324
- resolveWorkspacePath('tsconfig.json'),
325
- resolveWorkspacePath('tsconfig.dts.json')
326
- ]
327
- JIEK_TSCONFIG && dtsTSConfigPaths.push(resolveWorkspacePath(JIEK_TSCONFIG))
328
- JIEK_DTSCONFIG && dtsTSConfigPaths.push(resolveWorkspacePath(JIEK_DTSCONFIG))
329
- const buildTSConfigPaths = [
330
- ...dtsTSConfigPaths,
331
- resolveWorkspacePath('tsconfig.build.json')
332
- ]
333
- // 这里重复写了俩次 JIEK_TSCONFIG 到 tsconfig 的加载列表中
334
- // 目的是保证在 build 的时候,JIEK_TSCONFIG 的优先级高于 JIEK_DTSCONFIG
335
- JIEK_TSCONFIG && buildTSConfigPaths.push(resolveWorkspacePath(JIEK_TSCONFIG))
336
- let dtsTSConfigPath: string | undefined
337
- dtsTSConfigPaths.forEach(p => {
338
- if (fs.existsSync(p) && fs.statSync(p).isFile()) {
339
- dtsTSConfigPath = p
340
- }
341
- })
342
- let buildTSConfigPath: string | undefined
343
- buildTSConfigPaths.forEach(p => {
344
- if (fs.existsSync(p) && fs.statSync(p).isFile()) {
345
- buildTSConfigPath = p
346
- }
347
- })
348
- let compilerOptions: ts.CompilerOptions = {}
349
- if (dtsTSConfigPath) {
350
- const jsonCompilerOptions = getCompilerOptionsByFilePath(dtsTSConfigPath, resolve(input))
351
- const { options, errors } = ts.convertCompilerOptionsFromJson(
352
- jsonCompilerOptions,
353
- dirname(dtsTSConfigPath)
354
- )
355
- if (errors.length > 0) {
356
- throw new Error(errors.map(e => e.messageText).join('\n'))
357
- }
358
- compilerOptions = options
359
- delete compilerOptions.composite
360
- }
361
- const exportConditions = [...conditionals, ...(compilerOptions.customConditions ?? [])]
362
- const nodeResolvePluginInstance = nodeResolve({
363
- exportConditions,
364
- extensions: [
365
- '.js',
366
- '.cjs',
367
- '.mjs',
368
- '.jsx',
369
- '.cjsx',
370
- '.mjsx',
371
- '.ts',
372
- '.cts',
373
- '.mts',
374
- '.tsx',
375
- '.ctsx',
376
- '.mtsx'
377
- ]
378
- })
379
- const publishInEntry = <K extends keyof RollupBuildEventMap>(
380
- type: K,
381
- data: Omit<RollupBuildEventMap[K], keyof RollupBuildEntryCtx>
382
- ) =>
383
- // eslint-disable-next-line ts/no-unsafe-argument
384
- void publish(type, {
385
- ...{
386
- type: format,
387
- name,
388
- path,
389
- exportConditions,
390
- input
391
- } as RollupBuildEntryCtx,
392
- ...data
393
- } as any)
394
-
395
- const { js: jsPlugins, dts: dtsPlugins } = resolveBuildPlugins(context, build.plugins)
396
- if (input.includes('**')) {
397
- throw new Error(
398
- 'input should not include "**", please read the [documentation](https://nodejs.org/api/packages.html#subpath-patterns).'
399
- )
400
- }
401
- const reg = new RegExp(`^\./${
402
- input
403
- .slice(2)
404
- .replace(/\./g, '\\.')
405
- .replace(/\*/g, '.*')
406
- }$`)
407
- const inputObj = !input.includes('*')
408
- ? input
409
- : CWD_FILES.filter(p => reg.test(p))
410
- const globCommonDir = input.includes('*')
411
- ? input.split('*')[0]
412
- : ''
413
- const outputCommonDir = output.includes('*')
414
- ? output.split('*')[0]
415
- : ''
416
- if (
417
- (globCommonDir.length > 0 && outputCommonDir.length === 0)
418
- || (globCommonDir.length === 0 && outputCommonDir.length > 0)
419
- ) {
420
- throw new Error('input and path should both include "*" or not include "*"')
421
- }
422
- const jsOutputSuffix = extname(output)
423
- const tsOutputSuffix = jsOutputSuffix.replace(/(\.[cm]?)js$/, '.d$1ts')
424
- const { js: jsOutput, dts: dtsOutput } = resolveOutputControls(context, build.output)
425
- const rollupOptions: RollupOptions[] = []
426
-
427
- const commonPlugins = (
428
- { sourcemap }: { sourcemap?: string | boolean }
429
- ): InputPluginOption[] => [
430
- replace({
431
- sourcemap: sourcemap === 'hidden' ? false : !!sourcemap,
432
- values: build.replacements
433
- }),
434
- ...inputCommonPlugins,
435
- withExternal(),
436
- !disableCollectInternalModule && {
437
- name: 'jiek:collect-internal-module',
438
- resolveId: {
439
- order: 'pre',
440
- async handler(source, importer, options) {
441
- if (!source.startsWith('#')) return
442
-
443
- if (!nodeResolvePluginInstance.resolveId || !('handler' in nodeResolvePluginInstance.resolveId)) {
444
- throw new Error('nodeResolvePluginInstance.resolveId is not a plugin instance')
445
- }
446
- let resolved = await nodeResolvePluginInstance
447
- .resolveId
448
- .handler
449
- .call(this, source, importer, options)
450
- if (typeof resolved === 'string') {
451
- resolved = { id: resolved }
452
- }
453
- if (!resolved || !('id' in resolved)) {
454
- throw new Error('nodeResolvePluginInstance.resolveId.handler did not return a resolved object')
455
- }
456
- internalModuleCollect?.(`./${relative(process.cwd(), resolved.id)}`)
457
- return {
458
- id: experimental?.importsDowngrade
459
- ? source
460
- .replaceAll('#', `${INTERNAL_MODULE_NAME}/`)
461
- .replaceAll('~', '+')
462
- : source,
463
- external: true
464
- }
465
- }
466
- }
467
- }
468
- ]
469
- const features = Object.assign(
470
- {
471
- keepImportAttributes: false
472
- },
473
- build.features,
474
- FEATURES
475
- )
476
- const importAttributesKey = (
477
- features.keepImportAttributes === false
478
- || features.keepImportAttributes === undefined
479
- )
480
- ? undefined
481
- : features.keepImportAttributes === true
482
- ? 'with'
483
- : features.keepImportAttributes
484
- if (jsOutput && !WITHOUT_JS) {
485
- const sourcemap = typeof buildOptions?.output?.sourcemap === 'object'
486
- ? buildOptions.output.sourcemap.js
487
- : buildOptions?.output?.sourcemap
488
- const builder = resolvedBuilderOptions.type === 'esbuild'
489
- ? import('rollup-plugin-esbuild').then(({ default: esbuild }) =>
490
- esbuild({
491
- sourceMap: sourcemap === 'hidden' ? false : !!sourcemap,
492
- tsconfig: buildTSConfigPath,
493
- loaders: {
494
- cts: 'ts',
495
- ctsx: 'tsx',
496
- mts: 'ts',
497
- mtsx: 'tsx',
498
- cjs: 'js',
499
- cjsx: 'jsx',
500
- mjs: 'js',
501
- mjsx: 'jsx'
502
- },
503
- ...noTypeResolvedBuilderOptions,
504
- supported: {
505
- ...resolvedBuilderOptions.supported,
506
- 'import-attributes': true
507
- }
508
- })
509
- )
510
- : import('rollup-plugin-swc3').then(({ default: swc }) =>
511
- swc({
512
- sourceMaps: typeof sourcemap === 'boolean'
513
- ? sourcemap
514
- : typeof sourcemap === 'undefined'
515
- ? undefined
516
- : ({
517
- hidden: false,
518
- inline: 'inline'
519
- } as const)[sourcemap] ?? undefined,
520
- tsconfig: buildTSConfigPath,
521
- ...noTypeResolvedBuilderOptions,
522
- jsc: {
523
- ...resolvedBuilderOptions.jsc,
524
- parser: resolvedBuilderOptions.jsc?.parser
525
- ? resolvedBuilderOptions.jsc?.parser
526
- : {
527
- syntax: 'typescript',
528
- tsx: true,
529
- decorators: true,
530
- dynamicImport: true
531
- },
532
- experimental: {
533
- ...resolvedBuilderOptions.jsc?.experimental,
534
- keepImportAttributes: true
535
- }
536
- }
537
- })
538
- )
539
- const [ana, anaOutputPlugin] = bundleAnalyzer(modules => void publishInEntry('modulesAnalyze', { modules }))
540
- const onlyOncePlugins = [
541
- anaOutputPlugin
542
- ]
543
- rollupOptions.push({
544
- input: inputObj,
545
- external,
546
- output: [
547
- ...withMinify(
548
- {
549
- dir: jsOutdir,
550
- name,
551
- interop: 'auto',
552
- entryFileNames: (chunkInfo) => {
553
- return Array.isArray(inputObj)
554
- ? chunkInfo.facadeModuleId!
555
- .replace(`${process.cwd()}/`, './')
556
- .replace(globCommonDir, outputCommonDir)
557
- .replace(/(\.[cm]?)ts$/, jsOutputSuffix)
558
- .replace(`${jsOutdir}/`, '')
559
- : output
560
- .replace(`${jsOutdir}/`, '')
561
- },
562
- chunkFileNames: (chunkInfo) => {
563
- return `.internal/.chunks/${chunkInfo.name}.[hash]${jsOutputSuffix}`
564
- },
565
- sourcemap,
566
- format,
567
- strict: typeof buildOptions?.output?.strict === 'object'
568
- ? buildOptions.output.strict.js
569
- : buildOptions?.output?.strict,
570
- externalImportAttributes: features.keepImportAttributes === true
571
- ? true
572
- : features.keepImportAttributes,
573
- importAttributesKey
574
- },
575
- disableMinify,
576
- onlyOncePlugins
577
- )
578
- ],
579
- plugins: [
580
- ...commonPlugins({ sourcemap }),
581
- nodeResolvePluginInstance,
582
- import('rollup-plugin-postcss')
583
- .then(({ default: postcss }) =>
584
- postcss({
585
- extract: resolve(output.replace(/\.[cm]?js$/, '.css')),
586
- minimize: true
587
- })
588
- )
589
- .catch(() => void 0),
590
- commonjs(),
591
- builder,
592
- // inject plugin can't resolve `import type`, so we should register it after the builder plugin
593
- inject({
594
- sourceMap: sourcemap === 'hidden' ? false : !!sourcemap,
595
- modules: {
596
- ...build.injects ?? {},
597
- require: CREATE_REQUIRE_VIRTUAL_MODULE_NAME
598
- }
599
- }),
600
- createRequire(format === 'esm'),
601
- ana,
602
- progress({
603
- onEvent: (event, message) => void publishInEntry('progress', { event, message, tags: ['js'] })
604
- }),
605
- jsPlugins
606
- ]
607
- })
608
- }
609
-
610
- if (!disableDTS && dtsOutput && !WITHOUT_DTS) {
611
- const sourcemap = typeof buildOptions?.output?.sourcemap === 'object'
612
- ? buildOptions.output.sourcemap.dts
613
- : buildOptions?.output?.sourcemap
614
- rollupOptions.push({
615
- input: inputObj,
616
- external,
617
- output: [
618
- {
619
- dir: dtsOutdir,
620
- sourcemap,
621
- entryFileNames: (chunkInfo) => (
622
- Array.isArray(inputObj)
623
- ? chunkInfo.facadeModuleId!
624
- .replace(`${process.cwd()}/`, './')
625
- .replace(globCommonDir, outputCommonDir)
626
- .replace(/(\.[cm]?)ts$/, tsOutputSuffix)
627
- .replace(`${jsOutdir}/`, '')
628
- : output
629
- .replace(/(\.[cm]?)js$/, tsOutputSuffix)
630
- .replace(`${jsOutdir}/`, '')
631
- ),
632
- strict: typeof buildOptions?.output?.strict === 'object'
633
- ? buildOptions.output.strict.dts
634
- : buildOptions?.output?.strict,
635
- externalImportAttributes: features.keepImportAttributes !== false,
636
- importAttributesKey
637
- }
638
- ],
639
- plugins: [
640
- ...commonPlugins({ sourcemap }),
641
- skip({ patterns: [STYLE_REGEXP] }),
642
- dts({
643
- respectExternal: true,
644
- compilerOptions: {
645
- // temp directory, it not affect the output
646
- // but if the user not set it and `declaration`, inputs can't generate any dts files when the input relative imports of `package.json`
647
- outDir: 'dist',
648
- declaration: true,
649
- // https://github.com/Swatinem/rollup-plugin-dts/issues/143
650
- preserveSymlinks: false,
651
- // Expected '{', got 'type' (Note that you need plugins to import files that are not JavaScript)
652
- // https://github.com/Swatinem/rollup-plugin-dts/issues/96
653
- noEmit: false
654
- },
655
- tsconfig: dtsTSConfigPath
656
- }),
657
- progress({
658
- onEvent: (event, message) => void publishInEntry('progress', { event, message, tags: ['dts'] })
659
- }),
660
- dtsPlugins
661
- ]
662
- })
663
- }
664
- if (rollupOptions.length > 0) {
665
- // only push the first one a watcher plugin
666
- rollupOptions[0].plugins = [
667
- {
668
- name: 'jiek-plugin-watcher',
669
- watchChange: id => void publishInEntry('watchChange', { id })
670
- },
671
- ...(rollupOptions[0].plugins as Plugin[])
672
- ]
673
- }
674
- return rollupOptions
675
- }
676
-
677
- export function template(packageJSON: PackageJSON): RollupOptions[] {
678
- const {
679
- name,
680
- type,
681
- bin,
682
- exports: entrypoints,
683
- imports: internalEntrypoints
684
- } = packageJSON
685
- const pkgIsModule = type === 'module'
686
- const packageName = pascalCase(name)
687
- const leafMap = new Map<string, string[][]>()
688
- const inputTags = new Map<string, string>()
689
- const inputExports = new Map<string, Record<string, unknown>>()
690
- const configs: RollupOptions[] = []
691
- const external = externalResolver(packageJSON)
692
-
693
- let collectConfigTotal = 0
694
- const collected = Promise.withResolvers<void>()
695
- const internalModules = new Set<string>()
696
- const internalModuleCollect = (id?: string) => {
697
- if (!id) return
698
- internalModules.add(id)
699
- }
700
- const collectPlugin: Plugin = {
701
- name: 'jiek:collect',
702
- buildStart() {
703
- collectConfigTotal++
704
- },
705
- buildEnd() {
706
- if (--collectConfigTotal === 0) {
707
- collected.resolve()
708
- }
709
- }
710
- }
711
-
712
- if (entrypoints) {
713
- const [filteredResolvedEntrypoints, exports] = resolveExports({
714
- entrypoints,
715
- pkgIsModule,
716
- entries,
717
- pkgName: JIEK_NAME!,
718
- outdir: jsOutdir,
719
- config,
720
- skipJS: skipJS ?? SKIP_JS
721
- })
722
- getAllLeafs(filteredResolvedEntrypoints as RecursiveRecord<string>, ({ keys, value }) => {
723
- if (typeof value === 'string') {
724
- const keysArr = leafMap.get(value) ?? []
725
- leafMap.set(value, keysArr)
726
- inputExports.set(value, exports)
727
- keysArr.push(keys)
728
- }
729
- return false
730
- })
731
- }
732
- if (bin) {
733
- ;[...new Set(typeof bin === 'string' ? [bin] : Object.values(bin))]
734
- .filter(binFile => binFile.startsWith('bin'))
735
- .map(binFile => [
736
- `./src/${binFile.replace(/(\.[cm]?)js$/, '$1ts')}`,
737
- `./dist/${binFile}`
738
- ])
739
- .forEach(([input, output]) => {
740
- configs.push(...generateConfigs({
741
- path: output,
742
- name,
743
- input,
744
- output,
745
- external,
746
- pkgIsModule,
747
- conditionals: output.endsWith('.mjs')
748
- ? ['import']
749
- : output.endsWith('.cjs')
750
- ? ['require']
751
- : []
752
- }, {
753
- internalModuleCollect,
754
- disableDTS: true,
755
- disableMinify: true,
756
- commonPlugins: [
757
- collectPlugin
758
- ]
759
- }))
760
- leafMap.set(input, [[output]])
761
- inputTags.set(input, 'binary')
762
- })
763
- }
764
- if (internalEntrypoints) {
765
- const [filteredResolvedInternalEntrypoints, imports] = resolveExports({
766
- entrypoints: internalEntrypoints,
767
- pkgIsModule,
768
- pkgName: JIEK_NAME!,
769
- outdir: `${jsOutdir}/.internal`,
770
- config,
771
- skipJS: SKIP_JS ?? skipJS
772
- })
773
- getAllLeafs(filteredResolvedInternalEntrypoints as RecursiveRecord<string>, ({ keys, value }) => {
774
- if (typeof value === 'string') {
775
- const keysArr = leafMap.get(value) ?? []
776
- leafMap.set(value, keysArr)
777
- inputExports.set(value, imports)
778
- inputTags.set(value, 'internal')
779
- keysArr.push(keys)
780
- }
781
- return false
782
- })
783
- }
784
-
785
- leafMap.forEach((keysArr, input) => {
786
- if (inputTags.get(input) === 'binary') return
787
- const isInternal = inputTags.get(input) === 'internal'
788
- const exports = inputExports.get(input)!
789
-
790
- keysArr.forEach((keys) => {
791
- const [path, ...conditionals] = keys
792
-
793
- const name = packageName + (path === '.' ? '' : pascalCase(path))
794
- const keyExports = reveal(exports, keys)
795
- const commonContext = {
796
- path,
797
- name,
798
- input,
799
- external,
800
- pkgIsModule
801
- }
802
- const commonOptions: GenerateConfigsOptions = isInternal
803
- ? {
804
- commonPlugins: [
805
- {
806
- name: 'jiek:loadInternalModules',
807
- async options(inputOptions) {
808
- await collected.promise
809
- inputOptions.input = [...intersection(
810
- Array.isArray(inputOptions.input)
811
- ? inputOptions.input
812
- : [inputOptions.input as string],
813
- internalModules
814
- )]
815
- if (inputOptions.input.length === 0) {
816
- inputOptions.input = '__jiek_empty__'
817
- const plugins = await inputOptions.plugins
818
- if (!Array.isArray(plugins)) {
819
- throw new TypeError('plugins is not an array')
820
- }
821
- inputOptions.plugins = plugins.filter(
822
- p =>
823
- typeof p !== 'object'
824
- ? true
825
- : p === null
826
- ? true
827
- : 'name' in p && p.name === 'jiek:loadInternalModules'
828
- )
829
- }
830
- return inputOptions
831
- },
832
- resolveId: {
833
- order: 'post',
834
- handler(id) {
835
- if (id === '__jiek_empty__') return id
836
- }
837
- },
838
- load: {
839
- order: 'post',
840
- handler(id) {
841
- if (id === '__jiek_empty__') return ''
842
- }
843
- }
844
- }
845
- ],
846
- disableCollectInternalModule: true
847
- }
848
- : {
849
- internalModuleCollect,
850
- commonPlugins: [
851
- collectPlugin
852
- ]
853
- }
854
-
855
- // eslint-disable-next-line ts/switch-exhaustiveness-check
856
- switch (typeof keyExports) {
857
- case 'string': {
858
- configs.push(...generateConfigs({
859
- ...commonContext,
860
- output: keyExports,
861
- conditionals
862
- }, commonOptions))
863
- break
864
- }
865
- case 'object': {
866
- getAllLeafs(keyExports as RecursiveRecord<string>, ({ keys: nextKeys, value }) => {
867
- const allConditionals = [...new Set([...conditionals, ...nextKeys])]
868
- if (typeof value === 'string') {
869
- configs.push(...generateConfigs({
870
- ...commonContext,
871
- output: value,
872
- conditionals: allConditionals
873
- }, commonOptions))
874
- }
875
- return false
876
- })
877
- break
878
- }
879
- }
880
- })
881
- })
882
-
883
- void publish('init', { leafMap, targetsLength: configs.length })
884
- return configs.map(c => ({
885
- ...COMMON_OPTIONS,
886
- ...c,
887
- plugins: [
888
- ...COMMON_PLUGINS,
889
- c.plugins
890
- ]
891
- }))
892
- }