jiek 2.1.10 → 2.1.12

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.
@@ -1,5 +1,7 @@
1
+ /* eslint-disable ts/strict-boolean-expressions */
1
2
  import fs from 'node:fs'
2
- import { dirname, extname, relative, resolve } from 'node:path'
3
+ import { dirname, extname, join, relative, resolve } from 'node:path'
4
+ import process from 'node:process'
3
5
 
4
6
  import type { RecursiveRecord } from '@jiek/pkger/entrypoints'
5
7
  import { getAllLeafs } from '@jiek/pkger/entrypoints'
@@ -13,12 +15,13 @@ import { isMatch } from 'micromatch'
13
15
  import type { InputPluginOption, OutputOptions, OutputPlugin, Plugin, RollupOptions } from 'rollup'
14
16
  import ts from 'typescript'
15
17
 
18
+ import { getExports, getOutDirs } from '#~/utils/getExports.ts'
19
+ import { loadConfig } from '#~/utils/loadConfig.ts'
16
20
  import { recusiveListFiles } from '#~/utils/recusiveListFiles.ts'
21
+ import { getCompilerOptionsByFilePath } from '#~/utils/ts.ts'
17
22
 
18
- import { getExports, getOutDirs } from '../utils/getExports'
19
- import { loadConfig } from '../utils/loadConfig'
20
- import { getCompilerOptionsByFilePath } from '../utils/ts'
21
23
  import type { ConfigGenerateContext, RollupProgressEvent, TemplateOptions } from './base'
24
+ import createRequire, { isFormatEsm } from './plugins/create-require'
22
25
  import progress from './plugins/progress'
23
26
  import skip from './plugins/skip'
24
27
  import externalResolver from './utils/externalResolver'
@@ -30,6 +33,7 @@ interface PackageJSON {
30
33
  }
31
34
 
32
35
  const {
36
+ JIEK_ANALYZER,
33
37
  JIEK_ROOT,
34
38
  JIEK_NAME,
35
39
  JIEK_BUILDER,
@@ -58,6 +62,14 @@ const resolveArrayString = (str: string | undefined) => {
58
62
  return arr?.length ? arr : undefined
59
63
  }
60
64
 
65
+ const ANALYZER = JIEK_ANALYZER && JSON.parse(JIEK_ANALYZER) as {
66
+ dir?: string
67
+ mode?: string
68
+ size?: string
69
+ port?: number
70
+ open?: boolean
71
+ }
72
+
61
73
  const entries = resolveArrayString(JIEK_ENTRIES)?.map(e => ({ 'index': '.' }[e] ?? e))
62
74
 
63
75
  const commandExternal = resolveArrayString(JIEK_EXTERNAL)?.map(e => new RegExp(`^${e}$`))
@@ -119,6 +131,7 @@ const resolveBuildPlugins = (context: ConfigGenerateContext, plugins: TemplateOp
119
131
  }
120
132
  let js: InputPluginOption = []
121
133
  let dts: InputPluginOption = []
134
+ // eslint-disable-next-line ts/switch-exhaustiveness-check
122
135
  switch (typeof plugins) {
123
136
  case 'function':
124
137
  js = plugins('js', context)
@@ -157,7 +170,9 @@ const resolveWorkspacePath = (p: string) => resolve(WORKSPACE_ROOT, p)
157
170
 
158
171
  const pascalCase = (str: string) =>
159
172
  str
173
+ // eslint-disable-next-line ts/no-unsafe-member-access,ts/no-unsafe-return,ts/no-unsafe-call
160
174
  .replace(/[@|/-](\w)/g, (_, $1) => $1.toUpperCase())
175
+ // eslint-disable-next-line ts/no-unsafe-member-access,ts/no-unsafe-return,ts/no-unsafe-call
161
176
  .replace(/(?:^|-)(\w)/g, (_, $1) => $1.toUpperCase())
162
177
 
163
178
  const reveal = (obj: string | Record<string, unknown>, keys: string[]) =>
@@ -190,13 +205,28 @@ const withMinify = (
190
205
  },
191
206
  minify = build?.output?.minify ?? MINIFY_DEFAULT_VALUE
192
207
  ): OutputOptions[] => {
193
- if (minify === false) return [output]
208
+ output.plugins = output.plugins ?? []
209
+ const onlyOncePlugins: Plugin[] = [
210
+ // adapter(analyzer({
211
+ // analyzerMode: 'server',
212
+ // analyzerPort: 8888,
213
+ // reportTitle: 'Bundle Analysis'
214
+ // }))
215
+ ]
216
+ if (minify === false) {
217
+ output.plugins.push(...onlyOncePlugins)
218
+ return [output]
219
+ }
194
220
 
195
221
  const minifyPlugin = resolvedMinifyOptions.type === 'esbuild'
222
+ // eslint-disable-next-line ts/no-unsafe-argument
196
223
  ? import('rollup-plugin-esbuild').then(({ minify }) => minify(noTypeResolvedMinifyOptions as any))
197
224
  : resolvedMinifyOptions.type === 'swc'
225
+ // eslint-disable-next-line ts/no-unsafe-argument
198
226
  ? import('rollup-plugin-swc3').then(({ minify }) => minify(noTypeResolvedMinifyOptions as any))
227
+ // eslint-disable-next-line ts/no-unsafe-argument
199
228
  : import('@rollup/plugin-terser').then(({ default: minify }) => minify(noTypeResolvedMinifyOptions as any))
229
+ const notOnlyOncePlugins = output.plugins
200
230
  return minify === 'only-minify'
201
231
  ? [{
202
232
  ...output,
@@ -209,7 +239,7 @@ const withMinify = (
209
239
  throw new Error('entryFileNames must be a function')
210
240
  })(),
211
241
  plugins: [
212
- ...(output.plugins ?? []),
242
+ ...notOnlyOncePlugins,
213
243
  minifyPlugin
214
244
  ]
215
245
  }]
@@ -225,7 +255,7 @@ const withMinify = (
225
255
  })(),
226
256
  file: output.file?.replace(/(\.[cm]?js)$/, '.min$1'),
227
257
  plugins: [
228
- ...(output.plugins ?? []),
258
+ ...notOnlyOncePlugins,
229
259
  minifyPlugin
230
260
  ]
231
261
  }
@@ -347,6 +377,59 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
347
377
  ...noTypeResolvedBuilderOptions
348
378
  })
349
379
  )
380
+ const ana = ANALYZER
381
+ ? import('vite-bundle-analyzer').then(({ adapter, analyzer }) => {
382
+ const defaultSizes = ({
383
+ parsed: 'parsed',
384
+ stat: 'stat',
385
+ gzip: 'gzip'
386
+ } as const)[ANALYZER.size ?? 'stat'] ?? 'parsed'
387
+ const title = `${join(context.name, context.path)} ${context.conditionals.join(',')}`
388
+ const filename = title
389
+ .replace('\/', '_')
390
+ .replace(' ', '_')
391
+ switch (ANALYZER.mode ?? 'server') {
392
+ case 'server':
393
+ return adapter(analyzer({
394
+ defaultSizes,
395
+ analyzerMode: 'server',
396
+ analyzerPort: ANALYZER.port ?? 'auto',
397
+ openAnalyzer: ANALYZER.open ?? false,
398
+ reportTitle: `Bundle Analysis ${title}`
399
+ }))
400
+ case 'json':
401
+ return adapter(analyzer({
402
+ defaultSizes,
403
+ analyzerMode: 'json',
404
+ fileName: ANALYZER.dir ? join(ANALYZER.dir, filename) : filename
405
+ }))
406
+ case 'static':
407
+ return adapter(analyzer({
408
+ defaultSizes,
409
+ analyzerMode: 'static',
410
+ analyzerPort: ANALYZER.port ?? 'auto',
411
+ openAnalyzer: ANALYZER.open ?? false,
412
+ reportTitle: `Bundle Analysis ${title}`,
413
+ fileName: ANALYZER.dir ? join(ANALYZER.dir, filename) : filename
414
+ }))
415
+ case undefined: {
416
+ throw new Error('Not implemented yet: undefined case')
417
+ }
418
+ default:
419
+ void sendMessage(
420
+ {
421
+ ...throughEventProps,
422
+ data: {
423
+ ...throughEventProps.data,
424
+ event: 'error',
425
+ message: 'ANALYZER.mode not supported',
426
+ tags: ['js']
427
+ }
428
+ } satisfies RollupProgressEvent
429
+ )
430
+ }
431
+ })
432
+ : undefined
350
433
  rollupOptions.push({
351
434
  input: inputObj,
352
435
  external,
@@ -372,7 +455,10 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
372
455
  ),
373
456
  strict: typeof options?.output?.strict === 'object'
374
457
  ? options.output.strict.js
375
- : options?.output?.strict
458
+ : options?.output?.strict,
459
+ plugins: [
460
+ isFormatEsm(isModule)
461
+ ]
376
462
  })
377
463
  ],
378
464
  plugins: [
@@ -385,11 +471,13 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
385
471
  })
386
472
  )
387
473
  .catch(() => void 0),
388
- builder,
389
474
  commonjs(),
475
+ createRequire(),
476
+ builder,
477
+ ana,
390
478
  progress({
391
479
  onEvent: (event, message) =>
392
- sendMessage(
480
+ void sendMessage(
393
481
  {
394
482
  ...throughEventProps,
395
483
  data: { ...throughEventProps.data, event, message, tags: ['js'] }
@@ -445,7 +533,7 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
445
533
  }),
446
534
  progress({
447
535
  onEvent: (event, message) =>
448
- sendMessage(
536
+ void sendMessage(
449
537
  {
450
538
  ...throughEventProps,
451
539
  data: { ...throughEventProps.data, event, message, tags: ['dts'] }
@@ -462,14 +550,14 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
462
550
  {
463
551
  name: 'jiek-plugin-watcher',
464
552
  watchChange: (id) =>
465
- sendMessage(
553
+ void sendMessage(
466
554
  {
467
555
  type: 'watchChange',
468
556
  data: { id, name: JIEK_NAME!, path, input }
469
557
  } satisfies RollupProgressEvent
470
558
  )
471
559
  },
472
- ...(rollupOptions[0].plugins as any)
560
+ ...(rollupOptions[0].plugins as Plugin[])
473
561
  ]
474
562
  }
475
563
  return rollupOptions
@@ -519,6 +607,7 @@ export function template(packageJSON: PackageJSON): RollupOptions[] {
519
607
  pkgIsModule
520
608
  }
521
609
 
610
+ // eslint-disable-next-line ts/switch-exhaustiveness-check
522
611
  switch (typeof keyExports) {
523
612
  case 'string': {
524
613
  configs.push(...generateConfigs({
@@ -545,7 +634,7 @@ export function template(packageJSON: PackageJSON): RollupOptions[] {
545
634
  }
546
635
  })
547
636
  )
548
- sendMessage(
637
+ void sendMessage(
549
638
  {
550
639
  type: 'init',
551
640
  data: {
@@ -0,0 +1,74 @@
1
+ // https://github.com/privatenumber/pkgroll/blob/73559f8864203a50a5aa12c0a6503ceed3690aff/src/utils/rollup-plugins/create-require.ts#L1
2
+ // Thanks to @privatenumber for the snippet
3
+
4
+ import inject from '@rollup/plugin-inject'
5
+ import replace from '@rollup/plugin-replace'
6
+ import type { Plugin } from 'rollup'
7
+
8
+ const virtualModuleName = 'jiek:create-require'
9
+
10
+ /**
11
+ * Since rollup is bundled by rollup, it needs to add a run-time
12
+ * suffix so that this doesn't get replaced.
13
+ */
14
+ const isEsmVariableName = `IS_ESM${Math.random().toString(36).slice(2)}`
15
+
16
+ const INSERT_STR = `
17
+ import { createRequire } from 'node:module'
18
+
19
+ export default (
20
+ ${isEsmVariableName}
21
+ ? /* @__PURE__ */ createRequire(import.meta.url)
22
+ : require
23
+ )
24
+ `.trim()
25
+
26
+ /**
27
+ * Plugin to seamlessly allow usage of `require`
28
+ * across CJS and ESM modules.
29
+ *
30
+ * This is usually nor a problem for CJS outputs,
31
+ * but for ESM outputs, it must be used via
32
+ * createRequire.
33
+ *
34
+ * This plugin automatically injects it for ESM.
35
+ */
36
+ export default (): Plugin => ({
37
+ ...inject({
38
+ require: virtualModuleName
39
+ }),
40
+
41
+ name: 'create-require',
42
+
43
+ resolveId: source => (
44
+ (source === virtualModuleName)
45
+ ? source
46
+ : null
47
+ ),
48
+
49
+ load: (id) => {
50
+ if (id !== virtualModuleName) {
51
+ return null
52
+ }
53
+
54
+ return INSERT_STR
55
+ }
56
+ })
57
+
58
+ export const isFormatEsm = (
59
+ isEsm: boolean
60
+ ): Plugin => {
61
+ const handler = replace({
62
+ [isEsmVariableName]: isEsm
63
+ }).renderChunk!
64
+
65
+ return ({
66
+ name: 'create-require-insert-format',
67
+
68
+ // Pick out renderChunk because it's used as an output plugin
69
+ renderChunk: {
70
+ order: 'pre',
71
+ handler: typeof handler === 'function' ? handler : handler.handler
72
+ }
73
+ })
74
+ }
@@ -2,7 +2,6 @@ import fs from 'node:fs'
2
2
  import { createRequire } from 'node:module'
3
3
  import path from 'node:path'
4
4
 
5
- import { filterPackagesFromDir } from '@pnpm/filter-workspace-packages'
6
5
  import { program } from 'commander'
7
6
  import { load } from 'js-yaml'
8
7
 
@@ -69,6 +68,7 @@ export async function getSelectedProjectsGraph(
69
68
  }
70
69
  filter = packageJSON.name
71
70
  }
71
+ const { filterPackagesFromDir } = await import('@pnpm/filter-workspace-packages')
72
72
  const { selectedProjectsGraph } = await filterPackagesFromDir(wd, [{
73
73
  filter: filter ?? '',
74
74
  followProdDepsOnly: true