jiek 2.3.3 → 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 (77) 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 +90 -97
  6. package/dist/.internal/bin/common.js +91 -98
  7. package/dist/.internal/bin/parseArgv.cjs +2 -2
  8. package/dist/.internal/bin/parseArgv.js +2 -2
  9. package/dist/.internal/commands/utils/createAreaManagement.cjs +108 -0
  10. package/dist/.internal/commands/utils/createAreaManagement.d.cts +18 -0
  11. package/dist/.internal/commands/utils/createAreaManagement.d.ts +18 -0
  12. package/dist/.internal/commands/utils/createAreaManagement.js +106 -0
  13. package/dist/.internal/polyfill.cjs +13 -0
  14. package/dist/.internal/polyfill.d.cts +1 -0
  15. package/dist/.internal/polyfill.d.ts +1 -0
  16. package/dist/.internal/polyfill.js +11 -0
  17. package/dist/.internal/utils/filterSupport.cjs +1 -1
  18. package/dist/.internal/utils/filterSupport.js +2 -2
  19. package/dist/.internal/utils/loadConfig.cjs +3 -3
  20. package/dist/.internal/utils/loadConfig.d.cts +1 -0
  21. package/dist/.internal/utils/loadConfig.d.ts +1 -0
  22. package/dist/.internal/utils/loadConfig.js +4 -4
  23. package/dist/.internal/utils/pascalCase.cjs +5 -0
  24. package/dist/.internal/utils/pascalCase.d.cts +3 -0
  25. package/dist/.internal/utils/pascalCase.d.ts +3 -0
  26. package/dist/.internal/utils/pascalCase.js +3 -0
  27. package/dist/.internal/utils/reveal.cjs +9 -0
  28. package/dist/.internal/utils/reveal.d.cts +3 -0
  29. package/dist/.internal/utils/reveal.d.ts +3 -0
  30. package/dist/.internal/utils/reveal.js +7 -0
  31. package/dist/bin/index.cjs +101 -43
  32. package/dist/index.d.cts +7 -0
  33. package/dist/index.d.ts +7 -0
  34. package/dist/rollup/index.cjs +16 -18
  35. package/dist/rollup/index.js +13 -15
  36. package/package.json +2 -2
  37. package/src/bin/build.cts +0 -5
  38. package/src/bin/common.ts +0 -3
  39. package/src/bin/index.cts +0 -7
  40. package/src/bin/parseArgv.ts +0 -26
  41. package/src/bridge.ts +0 -46
  42. package/src/commands/base.ts +0 -18
  43. package/src/commands/build/analyzer.ts +0 -122
  44. package/src/commands/build/client/analyzer.tsx +0 -121
  45. package/src/commands/build/client/index.ts +0 -26
  46. package/src/commands/build.ts +0 -544
  47. package/src/commands/descriptions.ts +0 -17
  48. package/src/commands/meta.ts +0 -5
  49. package/src/commands/publish.ts +0 -628
  50. package/src/commands/utils/optionParser.ts +0 -4
  51. package/src/index.ts +0 -12
  52. package/src/inner.ts +0 -11
  53. package/src/rollup/base.ts +0 -152
  54. package/src/rollup/bundle-analyzer.ts +0 -62
  55. package/src/rollup/index.ts +0 -893
  56. package/src/rollup/plugins/create-require.ts +0 -23
  57. package/src/rollup/plugins/progress.ts +0 -26
  58. package/src/rollup/plugins/replace.ts +0 -185
  59. package/src/rollup/plugins/skip.ts +0 -21
  60. package/src/rollup/plugins/with-external.ts +0 -23
  61. package/src/rollup/utils/commonOptions.ts +0 -9
  62. package/src/rollup/utils/externalResolver.ts +0 -47
  63. package/src/rollup/utils/globalResolver.ts +0 -13
  64. package/src/rollup/utils/withMinify.ts +0 -18
  65. package/src/rollup-plugin-utils.ts +0 -32
  66. package/src/server.ts +0 -30
  67. package/src/utils/checkDependency.ts +0 -26
  68. package/src/utils/filterSupport.ts +0 -90
  69. package/src/utils/getInternalModuleName.ts +0 -5
  70. package/src/utils/getRoot.ts +0 -14
  71. package/src/utils/getWD.ts +0 -31
  72. package/src/utils/intersection.ts +0 -1
  73. package/src/utils/loadConfig.ts +0 -108
  74. package/src/utils/recursiveListFiles.ts +0 -13
  75. package/src/utils/resolveExports.ts +0 -165
  76. package/src/utils/ts.ts +0 -94
  77. package/src/utils/tsRegister.ts +0 -22
@@ -1,893 +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
- ...build.replacementsOptions,
432
- sourcemap: sourcemap === 'hidden' ? false : !!sourcemap,
433
- values: build.replacements
434
- }),
435
- ...inputCommonPlugins,
436
- withExternal(),
437
- !disableCollectInternalModule && {
438
- name: 'jiek:collect-internal-module',
439
- resolveId: {
440
- order: 'pre',
441
- async handler(source, importer, options) {
442
- if (!source.startsWith('#')) return
443
-
444
- if (!nodeResolvePluginInstance.resolveId || !('handler' in nodeResolvePluginInstance.resolveId)) {
445
- throw new Error('nodeResolvePluginInstance.resolveId is not a plugin instance')
446
- }
447
- let resolved = await nodeResolvePluginInstance
448
- .resolveId
449
- .handler
450
- .call(this, source, importer, options)
451
- if (typeof resolved === 'string') {
452
- resolved = { id: resolved }
453
- }
454
- if (!resolved || !('id' in resolved)) {
455
- throw new Error('nodeResolvePluginInstance.resolveId.handler did not return a resolved object')
456
- }
457
- internalModuleCollect?.(`./${relative(process.cwd(), resolved.id)}`)
458
- return {
459
- id: experimental?.importsDowngrade
460
- ? source
461
- .replaceAll('#', `${INTERNAL_MODULE_NAME}/`)
462
- .replaceAll('~', '+')
463
- : source,
464
- external: true
465
- }
466
- }
467
- }
468
- }
469
- ]
470
- const features = Object.assign(
471
- {
472
- keepImportAttributes: false
473
- },
474
- build.features,
475
- FEATURES
476
- )
477
- const importAttributesKey = (
478
- features.keepImportAttributes === false
479
- || features.keepImportAttributes === undefined
480
- )
481
- ? undefined
482
- : features.keepImportAttributes === true
483
- ? 'with'
484
- : features.keepImportAttributes
485
- if (jsOutput && !WITHOUT_JS) {
486
- const sourcemap = typeof buildOptions?.output?.sourcemap === 'object'
487
- ? buildOptions.output.sourcemap.js
488
- : buildOptions?.output?.sourcemap
489
- const builder = resolvedBuilderOptions.type === 'esbuild'
490
- ? import('rollup-plugin-esbuild').then(({ default: esbuild }) =>
491
- esbuild({
492
- sourceMap: sourcemap === 'hidden' ? false : !!sourcemap,
493
- tsconfig: buildTSConfigPath,
494
- loaders: {
495
- cts: 'ts',
496
- ctsx: 'tsx',
497
- mts: 'ts',
498
- mtsx: 'tsx',
499
- cjs: 'js',
500
- cjsx: 'jsx',
501
- mjs: 'js',
502
- mjsx: 'jsx'
503
- },
504
- ...noTypeResolvedBuilderOptions,
505
- supported: {
506
- ...resolvedBuilderOptions.supported,
507
- 'import-attributes': true
508
- }
509
- })
510
- )
511
- : import('rollup-plugin-swc3').then(({ default: swc }) =>
512
- swc({
513
- sourceMaps: typeof sourcemap === 'boolean'
514
- ? sourcemap
515
- : typeof sourcemap === 'undefined'
516
- ? undefined
517
- : ({
518
- hidden: false,
519
- inline: 'inline'
520
- } as const)[sourcemap] ?? undefined,
521
- tsconfig: buildTSConfigPath,
522
- ...noTypeResolvedBuilderOptions,
523
- jsc: {
524
- ...resolvedBuilderOptions.jsc,
525
- parser: resolvedBuilderOptions.jsc?.parser
526
- ? resolvedBuilderOptions.jsc?.parser
527
- : {
528
- syntax: 'typescript',
529
- tsx: true,
530
- decorators: true,
531
- dynamicImport: true
532
- },
533
- experimental: {
534
- ...resolvedBuilderOptions.jsc?.experimental,
535
- keepImportAttributes: true
536
- }
537
- }
538
- })
539
- )
540
- const [ana, anaOutputPlugin] = bundleAnalyzer(modules => void publishInEntry('modulesAnalyze', { modules }))
541
- const onlyOncePlugins = [
542
- anaOutputPlugin
543
- ]
544
- rollupOptions.push({
545
- input: inputObj,
546
- external,
547
- output: [
548
- ...withMinify(
549
- {
550
- dir: jsOutdir,
551
- name,
552
- interop: 'auto',
553
- entryFileNames: (chunkInfo) => {
554
- return Array.isArray(inputObj)
555
- ? chunkInfo.facadeModuleId!
556
- .replace(`${process.cwd()}/`, './')
557
- .replace(globCommonDir, outputCommonDir)
558
- .replace(/(\.[cm]?)ts$/, jsOutputSuffix)
559
- .replace(`${jsOutdir}/`, '')
560
- : output
561
- .replace(`${jsOutdir}/`, '')
562
- },
563
- chunkFileNames: (chunkInfo) => {
564
- return `.internal/.chunks/${chunkInfo.name}.[hash]${jsOutputSuffix}`
565
- },
566
- sourcemap,
567
- format,
568
- strict: typeof buildOptions?.output?.strict === 'object'
569
- ? buildOptions.output.strict.js
570
- : buildOptions?.output?.strict,
571
- externalImportAttributes: features.keepImportAttributes === true
572
- ? true
573
- : features.keepImportAttributes,
574
- importAttributesKey
575
- },
576
- disableMinify,
577
- onlyOncePlugins
578
- )
579
- ],
580
- plugins: [
581
- ...commonPlugins({ sourcemap }),
582
- nodeResolvePluginInstance,
583
- import('rollup-plugin-postcss')
584
- .then(({ default: postcss }) =>
585
- postcss({
586
- extract: resolve(output.replace(/\.[cm]?js$/, '.css')),
587
- minimize: true
588
- })
589
- )
590
- .catch(() => void 0),
591
- commonjs(),
592
- builder,
593
- // inject plugin can't resolve `import type`, so we should register it after the builder plugin
594
- inject({
595
- sourceMap: sourcemap === 'hidden' ? false : !!sourcemap,
596
- modules: {
597
- ...build.injects ?? {},
598
- require: CREATE_REQUIRE_VIRTUAL_MODULE_NAME
599
- }
600
- }),
601
- createRequire(format === 'esm'),
602
- ana,
603
- progress({
604
- onEvent: (event, message) => void publishInEntry('progress', { event, message, tags: ['js'] })
605
- }),
606
- jsPlugins
607
- ]
608
- })
609
- }
610
-
611
- if (!disableDTS && dtsOutput && !WITHOUT_DTS) {
612
- const sourcemap = typeof buildOptions?.output?.sourcemap === 'object'
613
- ? buildOptions.output.sourcemap.dts
614
- : buildOptions?.output?.sourcemap
615
- rollupOptions.push({
616
- input: inputObj,
617
- external,
618
- output: [
619
- {
620
- dir: dtsOutdir,
621
- sourcemap,
622
- entryFileNames: (chunkInfo) => (
623
- Array.isArray(inputObj)
624
- ? chunkInfo.facadeModuleId!
625
- .replace(`${process.cwd()}/`, './')
626
- .replace(globCommonDir, outputCommonDir)
627
- .replace(/(\.[cm]?)ts$/, tsOutputSuffix)
628
- .replace(`${jsOutdir}/`, '')
629
- : output
630
- .replace(/(\.[cm]?)js$/, tsOutputSuffix)
631
- .replace(`${jsOutdir}/`, '')
632
- ),
633
- strict: typeof buildOptions?.output?.strict === 'object'
634
- ? buildOptions.output.strict.dts
635
- : buildOptions?.output?.strict,
636
- externalImportAttributes: features.keepImportAttributes !== false,
637
- importAttributesKey
638
- }
639
- ],
640
- plugins: [
641
- ...commonPlugins({ sourcemap }),
642
- skip({ patterns: [STYLE_REGEXP] }),
643
- dts({
644
- respectExternal: true,
645
- compilerOptions: {
646
- // temp directory, it not affect the output
647
- // but if the user not set it and `declaration`, inputs can't generate any dts files when the input relative imports of `package.json`
648
- outDir: 'dist',
649
- declaration: true,
650
- // https://github.com/Swatinem/rollup-plugin-dts/issues/143
651
- preserveSymlinks: false,
652
- // Expected '{', got 'type' (Note that you need plugins to import files that are not JavaScript)
653
- // https://github.com/Swatinem/rollup-plugin-dts/issues/96
654
- noEmit: false
655
- },
656
- tsconfig: dtsTSConfigPath
657
- }),
658
- progress({
659
- onEvent: (event, message) => void publishInEntry('progress', { event, message, tags: ['dts'] })
660
- }),
661
- dtsPlugins
662
- ]
663
- })
664
- }
665
- if (rollupOptions.length > 0) {
666
- // only push the first one a watcher plugin
667
- rollupOptions[0].plugins = [
668
- {
669
- name: 'jiek-plugin-watcher',
670
- watchChange: id => void publishInEntry('watchChange', { id })
671
- },
672
- ...(rollupOptions[0].plugins as Plugin[])
673
- ]
674
- }
675
- return rollupOptions
676
- }
677
-
678
- export function template(packageJSON: PackageJSON): RollupOptions[] {
679
- const {
680
- name,
681
- type,
682
- bin,
683
- exports: entrypoints,
684
- imports: internalEntrypoints
685
- } = packageJSON
686
- const pkgIsModule = type === 'module'
687
- const packageName = pascalCase(name)
688
- const leafMap = new Map<string, string[][]>()
689
- const inputTags = new Map<string, string>()
690
- const inputExports = new Map<string, Record<string, unknown>>()
691
- const configs: RollupOptions[] = []
692
- const external = externalResolver(packageJSON)
693
-
694
- let collectConfigTotal = 0
695
- const collected = Promise.withResolvers<void>()
696
- const internalModules = new Set<string>()
697
- const internalModuleCollect = (id?: string) => {
698
- if (!id) return
699
- internalModules.add(id)
700
- }
701
- const collectPlugin: Plugin = {
702
- name: 'jiek:collect',
703
- buildStart() {
704
- collectConfigTotal++
705
- },
706
- buildEnd() {
707
- if (--collectConfigTotal === 0) {
708
- collected.resolve()
709
- }
710
- }
711
- }
712
-
713
- if (entrypoints) {
714
- const [filteredResolvedEntrypoints, exports] = resolveExports({
715
- entrypoints,
716
- pkgIsModule,
717
- entries,
718
- pkgName: JIEK_NAME!,
719
- outdir: jsOutdir,
720
- config,
721
- skipJS: skipJS ?? SKIP_JS
722
- })
723
- getAllLeafs(filteredResolvedEntrypoints as RecursiveRecord<string>, ({ keys, value }) => {
724
- if (typeof value === 'string') {
725
- const keysArr = leafMap.get(value) ?? []
726
- leafMap.set(value, keysArr)
727
- inputExports.set(value, exports)
728
- keysArr.push(keys)
729
- }
730
- return false
731
- })
732
- }
733
- if (bin) {
734
- ;[...new Set(typeof bin === 'string' ? [bin] : Object.values(bin))]
735
- .filter(binFile => binFile.startsWith('bin'))
736
- .map(binFile => [
737
- `./src/${binFile.replace(/(\.[cm]?)js$/, '$1ts')}`,
738
- `./dist/${binFile}`
739
- ])
740
- .forEach(([input, output]) => {
741
- configs.push(...generateConfigs({
742
- path: output,
743
- name,
744
- input,
745
- output,
746
- external,
747
- pkgIsModule,
748
- conditionals: output.endsWith('.mjs')
749
- ? ['import']
750
- : output.endsWith('.cjs')
751
- ? ['require']
752
- : []
753
- }, {
754
- internalModuleCollect,
755
- disableDTS: true,
756
- disableMinify: true,
757
- commonPlugins: [
758
- collectPlugin
759
- ]
760
- }))
761
- leafMap.set(input, [[output]])
762
- inputTags.set(input, 'binary')
763
- })
764
- }
765
- if (internalEntrypoints) {
766
- const [filteredResolvedInternalEntrypoints, imports] = resolveExports({
767
- entrypoints: internalEntrypoints,
768
- pkgIsModule,
769
- pkgName: JIEK_NAME!,
770
- outdir: `${jsOutdir}/.internal`,
771
- config,
772
- skipJS: SKIP_JS ?? skipJS
773
- })
774
- getAllLeafs(filteredResolvedInternalEntrypoints as RecursiveRecord<string>, ({ keys, value }) => {
775
- if (typeof value === 'string') {
776
- const keysArr = leafMap.get(value) ?? []
777
- leafMap.set(value, keysArr)
778
- inputExports.set(value, imports)
779
- inputTags.set(value, 'internal')
780
- keysArr.push(keys)
781
- }
782
- return false
783
- })
784
- }
785
-
786
- leafMap.forEach((keysArr, input) => {
787
- if (inputTags.get(input) === 'binary') return
788
- const isInternal = inputTags.get(input) === 'internal'
789
- const exports = inputExports.get(input)!
790
-
791
- keysArr.forEach((keys) => {
792
- const [path, ...conditionals] = keys
793
-
794
- const name = packageName + (path === '.' ? '' : pascalCase(path))
795
- const keyExports = reveal(exports, keys)
796
- const commonContext = {
797
- path,
798
- name,
799
- input,
800
- external,
801
- pkgIsModule
802
- }
803
- const commonOptions: GenerateConfigsOptions = isInternal
804
- ? {
805
- commonPlugins: [
806
- {
807
- name: 'jiek:loadInternalModules',
808
- async options(inputOptions) {
809
- await collected.promise
810
- inputOptions.input = [...intersection(
811
- Array.isArray(inputOptions.input)
812
- ? inputOptions.input
813
- : [inputOptions.input as string],
814
- internalModules
815
- )]
816
- if (inputOptions.input.length === 0) {
817
- inputOptions.input = '__jiek_empty__'
818
- const plugins = await inputOptions.plugins
819
- if (!Array.isArray(plugins)) {
820
- throw new TypeError('plugins is not an array')
821
- }
822
- inputOptions.plugins = plugins.filter(
823
- p =>
824
- typeof p !== 'object'
825
- ? true
826
- : p === null
827
- ? true
828
- : 'name' in p && p.name === 'jiek:loadInternalModules'
829
- )
830
- }
831
- return inputOptions
832
- },
833
- resolveId: {
834
- order: 'post',
835
- handler(id) {
836
- if (id === '__jiek_empty__') return id
837
- }
838
- },
839
- load: {
840
- order: 'post',
841
- handler(id) {
842
- if (id === '__jiek_empty__') return ''
843
- }
844
- }
845
- }
846
- ],
847
- disableCollectInternalModule: true
848
- }
849
- : {
850
- internalModuleCollect,
851
- commonPlugins: [
852
- collectPlugin
853
- ]
854
- }
855
-
856
- // eslint-disable-next-line ts/switch-exhaustiveness-check
857
- switch (typeof keyExports) {
858
- case 'string': {
859
- configs.push(...generateConfigs({
860
- ...commonContext,
861
- output: keyExports,
862
- conditionals
863
- }, commonOptions))
864
- break
865
- }
866
- case 'object': {
867
- getAllLeafs(keyExports as RecursiveRecord<string>, ({ keys: nextKeys, value }) => {
868
- const allConditionals = [...new Set([...conditionals, ...nextKeys])]
869
- if (typeof value === 'string') {
870
- configs.push(...generateConfigs({
871
- ...commonContext,
872
- output: value,
873
- conditionals: allConditionals
874
- }, commonOptions))
875
- }
876
- return false
877
- })
878
- break
879
- }
880
- }
881
- })
882
- })
883
-
884
- void publish('init', { leafMap, targetsLength: configs.length })
885
- return configs.map(c => ({
886
- ...COMMON_OPTIONS,
887
- ...c,
888
- plugins: [
889
- ...COMMON_PLUGINS,
890
- c.plugins
891
- ]
892
- }))
893
- }