jiek 2.2.3 → 2.2.5-alpha.1

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.
@@ -324,34 +324,63 @@ async function prepublish({ bumper }: {
324
324
  .readdirSync(resolveByDir(resolvedOutdir), { recursive: true })
325
325
  .filter(file => typeof file === 'string')
326
326
  .filter(file => file !== 'package.json')
327
- for (const file of allBuildFiles) {
328
- const filepath = resolveByDir(resolvedOutdir, file)
329
- const stat = fs.statSync(filepath)
330
- if (stat.isDirectory()) {
331
- const existsIndexFile = allBuildFiles
332
- .some(f =>
333
- [
334
- path.join(file, 'index.js'),
335
- path.join(file, 'index.mjs'),
336
- path.join(file, 'index.cjs')
337
- ].includes(f)
338
- )
339
- if (existsIndexFile) {
340
- const cpDistPath = resolveByDir(resolvedOutdir, resolvedOutdir, file)
341
- const pkgJSONPath = resolveByDir(resolvedOutdir, file, 'package.json')
342
- const relativePath = path.relative(filepath, cpDistPath)
343
- const { type } = manifest
344
- fs.writeFileSync(
345
- pkgJSONPath,
346
- JSON.stringify({
347
- type,
348
- main: [relativePath, `index.${type === 'module' ? 'c' : ''}js`].join('/'),
349
- module: [relativePath, `index.${type === 'module' ? '' : 'm'}js`].join('/')
350
- })
351
- )
327
+ const resolvedExports = manifest.exports as Record<string, unknown>
328
+ Object
329
+ .keys(resolvedExports)
330
+ .forEach(key => {
331
+ if (key === '.') return
332
+ if (/\.[cm]?js$/.test(key)) return
333
+ // resource file suffix
334
+ const resourceFileSuffixes = [
335
+ '.d.ts',
336
+ '.d.mts',
337
+ '.d.cts',
338
+ '.css',
339
+ '.scss',
340
+ '.sass',
341
+ '.less',
342
+ '.styl',
343
+ '.stylus',
344
+ '.json',
345
+ '.json5'
346
+ ]
347
+ if (resourceFileSuffixes.find(suffix => key.endsWith(suffix))) return
348
+
349
+ const value = resolvedExports[key] as {
350
+ import?: string
351
+ require?: string
352
+ default?: string
352
353
  }
353
- }
354
- }
354
+
355
+ const filepath = resolveByDir(resolvedOutdir, key)
356
+
357
+ fs.mkdirSync(filepath, { recursive: true })
358
+ const pkgJSONPath = resolveByDir(resolvedOutdir, key, 'package.json')
359
+ const relativePath = Array.from({ length: key.split('/').length - 1 }, () => '..').join('/')
360
+ const { type } = manifest
361
+ const pkgJSON: Record<string, unknown> = { type }
362
+ if ('default' in value) {
363
+ pkgJSON[
364
+ type === 'module' ? 'module' : 'main'
365
+ ] = [
366
+ relativePath,
367
+ value.default?.replace(/^\.\//, '')
368
+ ].join('/')
369
+ }
370
+ if ('import' in value) {
371
+ pkgJSON.module = [
372
+ relativePath,
373
+ value.import?.replace(/^\.\//, '')
374
+ ].join('/')
375
+ }
376
+ if ('require' in value) {
377
+ pkgJSON.main = [
378
+ relativePath,
379
+ value.require?.replace(/^\.\//, '')
380
+ ].join('/')
381
+ }
382
+ fs.writeFileSync(pkgJSONPath, JSON.stringify(pkgJSON))
383
+ })
355
384
  fs.mkdirSync(resolveByDir(resolvedOutdir, resolvedOutdir))
356
385
  for (const file of allBuildFiles) {
357
386
  const filepath = resolveByDir(resolvedOutdir, file)
@@ -411,13 +440,20 @@ async function prepublish({ bumper }: {
411
440
  async function postpublish() {
412
441
  await forEachSelectedProjectsGraphEntries(dir => {
413
442
  const jiekTempDir = path.resolve(dir, 'node_modules/.jiek/.tmp')
414
- const packageJSON = path.resolve(dir, 'package.json')
415
- const jiekTempPackageJSON = path.resolve(jiekTempDir, 'package.json')
416
- if (fs.existsSync(jiekTempPackageJSON)) {
417
- fs.copyFileSync(jiekTempPackageJSON, packageJSON)
418
- fs.rmSync(jiekTempPackageJSON)
419
- // eslint-disable-next-line no-console
443
+ const packageJSONPath = path.resolve(dir, 'package.json')
444
+ const { name, version } = JSON.parse(fs.readFileSync(packageJSONPath, 'utf-8')) as {
445
+ name: string
446
+ version: string
447
+ }
448
+ const jiekTempPackageJSONPath = path.resolve(jiekTempDir, 'package.json')
449
+ if (fs.existsSync(jiekTempPackageJSONPath)) {
450
+ fs.copyFileSync(jiekTempPackageJSONPath, packageJSONPath)
451
+ fs.rmSync(jiekTempPackageJSONPath)
452
+ /* eslint-disable no-console */
420
453
  console.log(`${dir}/package.json has been restored`)
454
+ console.log(`if you want to check the compatibility of the package, you can visit:`)
455
+ console.log(`https://arethetypeswrong.github.io/?p=${name}%40${version}`)
456
+ /* eslint-enable no-console */
421
457
  } else {
422
458
  throw new Error(
423
459
  `jiek temp \`${dir}/package.json\` not found, please confirm the jiek pre-publish command has been executed`
@@ -110,4 +110,28 @@ export interface TemplateOptions {
110
110
  js?: InputPluginOption
111
111
  dts: InputPluginOption
112
112
  }
113
+ /**
114
+ * https://www.npmjs.com/package/@rollup/plugin-inject#usage
115
+ *
116
+ * @example
117
+ * ```js
118
+ * {
119
+ * // import { Promise } from 'es6-promise'
120
+ * Promise: [ 'es6-promise', 'Promise' ],
121
+ *
122
+ * // import { Promise as P } from 'es6-promise'
123
+ * P: [ 'es6-promise', 'Promise' ],
124
+ *
125
+ * // import $ from 'jquery'
126
+ * $: 'jquery',
127
+ *
128
+ * // import * as fs from 'fs'
129
+ * fs: [ 'fs', '*' ],
130
+ *
131
+ * // use a local module instead of a third-party one
132
+ * 'Object.assign': path.resolve( 'src/helpers/object-assign.js' ),
133
+ * }
134
+ * ```
135
+ */
136
+ injects?: Record<string, string | [string, string]>
113
137
  }
@@ -8,6 +8,7 @@ import { getAllLeafs } from '@jiek/pkger/entrypoints'
8
8
  import { dts } from '@jiek/rollup-plugin-dts'
9
9
  import { getWorkspaceDir } from '@jiek/utils/getWorkspaceDir'
10
10
  import commonjs from '@rollup/plugin-commonjs'
11
+ import inject from '@rollup/plugin-inject'
11
12
  import json from '@rollup/plugin-json'
12
13
  import { nodeResolve } from '@rollup/plugin-node-resolve'
13
14
  import { isMatch } from 'micromatch'
@@ -23,7 +24,7 @@ import { recusiveListFiles } from '#~/utils/recusiveListFiles.ts'
23
24
  import { getCompilerOptionsByFilePath } from '#~/utils/ts.ts'
24
25
 
25
26
  import type { ConfigGenerateContext, TemplateOptions } from './base'
26
- import createRequire, { isFormatEsm } from './plugins/create-require'
27
+ import createRequire, { CREATE_REQUIRE_VIRTUAL_MODULE_NAME } from './plugins/create-require'
27
28
  import progress from './plugins/progress'
28
29
  import skip from './plugins/skip'
29
30
  import externalResolver from './utils/externalResolver'
@@ -389,7 +390,16 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
389
390
  esbuild({
390
391
  sourceMap: sourcemap === 'hidden' ? false : !!sourcemap,
391
392
  tsconfig: buildTSConfigPath,
392
- target: 'node22',
393
+ loaders: {
394
+ cts: 'ts',
395
+ ctsx: 'tsx',
396
+ mts: 'ts',
397
+ mtsx: 'tsx',
398
+ cjs: 'js',
399
+ cjsx: 'jsx',
400
+ mjs: 'js',
401
+ mjsx: 'jsx'
402
+ },
393
403
  ...noTypeResolvedBuilderOptions,
394
404
  supported: {
395
405
  'import-attributes': features.keepImportAttributes !== false,
@@ -411,6 +421,14 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
411
421
  ...noTypeResolvedBuilderOptions,
412
422
  jsc: {
413
423
  ...resolvedBuilderOptions.jsc,
424
+ parser: resolvedBuilderOptions.jsc?.parser
425
+ ? resolvedBuilderOptions.jsc?.parser
426
+ : {
427
+ syntax: 'typescript',
428
+ tsx: true,
429
+ decorators: true,
430
+ dynamicImport: true
431
+ },
414
432
  experimental: {
415
433
  ...resolvedBuilderOptions.jsc?.experimental,
416
434
  keepImportAttributes: features.keepImportAttributes !== false
@@ -451,9 +469,7 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
451
469
  : features.keepImportAttributes === true
452
470
  ? 'with'
453
471
  : features.keepImportAttributes,
454
- plugins: [
455
- isFormatEsm(format === 'esm')
456
- ]
472
+ plugins: []
457
473
  }, onlyOncePlugins)
458
474
  ],
459
475
  plugins: [
@@ -467,8 +483,16 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
467
483
  )
468
484
  .catch(() => void 0),
469
485
  commonjs(),
470
- createRequire(),
471
486
  builder,
487
+ // inject plugin can't resolve `import type`, so we should register it after the builder plugin
488
+ inject({
489
+ sourceMap: sourcemap === 'hidden' ? false : !!sourcemap,
490
+ modules: {
491
+ ...build.injects ?? {},
492
+ require: CREATE_REQUIRE_VIRTUAL_MODULE_NAME
493
+ }
494
+ }),
495
+ createRequire(format === 'esm'),
472
496
  ana,
473
497
  progress({
474
498
  onEvent: (event, message) => void publishInEntry('progress', { event, message, tags: ['js'] })
@@ -479,15 +503,16 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
479
503
  }
480
504
 
481
505
  if (dtsOutput && !WITHOUT_DTS) {
506
+ const sourcemap = typeof options?.output?.sourcemap === 'object'
507
+ ? options.output.sourcemap.dts
508
+ : options?.output?.sourcemap
482
509
  rollupOptions.push({
483
510
  input: inputObj,
484
511
  external,
485
512
  output: [
486
513
  {
487
514
  dir: dtsOutdir,
488
- sourcemap: typeof options?.output?.sourcemap === 'object'
489
- ? options.output.sourcemap.dts
490
- : options?.output?.sourcemap,
515
+ sourcemap,
491
516
  entryFileNames: (chunkInfo) => (
492
517
  Array.isArray(inputObj)
493
518
  ? chunkInfo.facadeModuleId!.replace(`${process.cwd()}/`, '')
@@ -1,74 +1,23 @@
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
1
  import type { Plugin } from 'rollup'
7
2
 
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'
3
+ export const CREATE_REQUIRE_VIRTUAL_MODULE_NAME = 'jiek:create-require'
18
4
 
19
- export default (
20
- ${isEsmVariableName}
21
- ? /* @__PURE__ */ createRequire(import.meta.url)
22
- : require
23
- )
5
+ const INSERT_STR = (isESM: boolean) =>
6
+ `
7
+ ${isESM ? `import { createRequire } from 'node:module'` : ''}
8
+ export default ${isESM ? '/* @__PURE__ */ createRequire(import.meta.url)' : 'require'}
24
9
  `.trim()
25
10
 
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
-
11
+ export default (isEsm: boolean): Plugin => ({
41
12
  name: 'create-require',
42
-
43
- resolveId: source => (
44
- (source === virtualModuleName)
45
- ? source
13
+ resolveId: id => (
14
+ id === CREATE_REQUIRE_VIRTUAL_MODULE_NAME
15
+ ? id
46
16
  : null
47
17
  ),
48
-
49
- load: (id) => {
50
- if (id !== virtualModuleName) {
51
- return null
52
- }
53
-
54
- return INSERT_STR
55
- }
18
+ load: id => (
19
+ id === CREATE_REQUIRE_VIRTUAL_MODULE_NAME
20
+ ? INSERT_STR(isEsm)
21
+ : null
22
+ )
56
23
  })
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
- }
@@ -1,7 +1,7 @@
1
+ import { execSync } from 'node:child_process'
1
2
  import process from 'node:process'
2
3
 
3
4
  import { confirm } from '@inquirer/prompts'
4
- import { execaCommand } from 'execa'
5
5
 
6
6
  import { getWD } from '#~/utils/getWD.ts'
7
7
 
@@ -11,9 +11,13 @@ export async function checkDependency(dependency: string) {
11
11
  } catch {
12
12
  console.error(`The package '${dependency}' is not installed, please install it first.`)
13
13
  const { notWorkspace } = getWD()
14
- const command = `pnpm install -${notWorkspace ? '' : 'w'}D ${dependency}`
15
- if (await confirm({ message: 'Do you want to install it now?' })) {
16
- await execaCommand(command)
14
+ const command = `pnpm add -${notWorkspace ? '' : 'w'}D ${dependency}`
15
+ if (await confirm({ message: `Do you want to add it now? (${command})` })) {
16
+ execSync(command, {
17
+ stdio: 'inherit',
18
+ cwd: process.cwd(),
19
+ env: process.env
20
+ })
17
21
  } else {
18
22
  console.warn(`You can run the command '${command}' to install it manually.`)
19
23
  process.exit(1)
@@ -1,5 +1,4 @@
1
1
  import fs from 'node:fs'
2
- import { createRequire } from 'node:module'
3
2
  import path from 'node:path'
4
3
 
5
4
  import { program } from 'commander'
@@ -11,7 +10,6 @@ import { getWD } from '#~/utils/getWD.ts'
11
10
  export let type = ''
12
11
 
13
12
  try {
14
- const require = createRequire(import.meta.url)
15
13
  require.resolve('@pnpm/filter-workspace-packages')
16
14
  type = 'pnpm'
17
15
  } catch { /* empty */ }
@@ -26,7 +24,7 @@ export interface ProjectsGraph {
26
24
  }>
27
25
  }
28
26
 
29
- export function filterPackagesGraph(filters: string[]): Promise<ProjectsGraph[]> {
27
+ export async function filterPackagesGraph(filters: string[]): Promise<ProjectsGraph[]> {
30
28
  return Promise.all(filters.map(async filter => getSelectedProjectsGraph(filter)))
31
29
  }
32
30
 
@@ -1,11 +1,12 @@
1
1
  import { isAbsolute, relative, resolve } from 'node:path'
2
+ import process from 'node:process'
2
3
 
3
4
  import {
5
+ type Entrypoints2ExportsOptions,
6
+ type RecursiveRecord,
4
7
  DEFAULT_SKIP_VALUES,
5
8
  entrypoints2Exports,
6
- type Entrypoints2ExportsOptions,
7
9
  filterLeafs,
8
- type RecursiveRecord,
9
10
  resolveEntrypoints
10
11
  } from '@jiek/pkger/entrypoints'
11
12
  import type { Config } from 'jiek'
@@ -14,10 +15,14 @@ import { isMatch } from 'micromatch'
14
15
  const intersection = <T>(a: Set<T>, b: Set<T>) => new Set([...a].filter(i => b.has(i)))
15
16
 
16
17
  const {
17
- JIEK_OUT_DIR
18
+ JIEK_OUT_DIR,
19
+ JIEK_CROSS_MODULE_CONVERTOR
18
20
  } = process.env
19
21
 
20
22
  const OUTDIR = JIEK_OUT_DIR ?? 'dist'
23
+ const crossModuleConvertorDefault = JIEK_CROSS_MODULE_CONVERTOR === undefined
24
+ ? true
25
+ : JIEK_CROSS_MODULE_CONVERTOR === 'true'
21
26
 
22
27
  export function getOutDirs({
23
28
  cwd = process.cwd(),
@@ -85,7 +90,7 @@ export function getExports({
85
90
  } = {}
86
91
  } = config ?? {}
87
92
  const {
88
- crossModuleConvertor = true
93
+ crossModuleConvertor = crossModuleConvertorDefault
89
94
  } = build
90
95
  const [, resolvedEntrypoints] = resolveEntrypoints(entrypoints)
91
96
  if (entries) {
@@ -109,20 +114,30 @@ export function getExports({
109
114
  )
110
115
  const crossModuleWithConditional: Entrypoints2ExportsOptions['withConditional'] = crossModuleConvertor
111
116
  ? {
112
- import: opts =>
113
- !pkgIsModule && intersection(
114
- new Set(opts.conditionals),
115
- new Set(['import', 'module'])
116
- ).size === 0
117
- ? opts.dist.replace(/\.js$/, '.mjs')
118
- : false,
119
- require: opts =>
120
- pkgIsModule && intersection(
121
- new Set(opts.conditionals),
122
- new Set(['require', 'node'])
123
- ).size === 0
124
- ? opts.dist.replace(/\.js$/, '.cjs')
125
- : false
117
+ import: opts => {
118
+ if (pkgIsModule) return false
119
+ if (opts.src.endsWith('.cts')) return false
120
+ if (
121
+ intersection(
122
+ new Set(opts.conditionals),
123
+ new Set(['import', 'module'])
124
+ ).size !== 0
125
+ ) return false
126
+
127
+ return opts.dist.replace(/\.js$/, '.mjs')
128
+ },
129
+ require: opts => {
130
+ if (!pkgIsModule) return false
131
+ if (opts.src.endsWith('.mts')) return false
132
+ if (
133
+ intersection(
134
+ new Set(opts.conditionals),
135
+ new Set(['require', 'node'])
136
+ ).size !== 0
137
+ ) return false
138
+
139
+ return opts.dist.replace(/\.js$/, '.cjs')
140
+ }
126
141
  }
127
142
  : {}
128
143
  return [
@@ -1,5 +1,4 @@
1
1
  import fs from 'node:fs'
2
- import { createRequire } from 'node:module'
3
2
  import path from 'node:path'
4
3
 
5
4
  import { program } from 'commander'
@@ -9,8 +8,6 @@ import { load } from 'js-yaml'
9
8
  import { getWD } from './getWD'
10
9
  import { tsRegisterName } from './tsRegister'
11
10
 
12
- const require = createRequire(import.meta.url)
13
-
14
11
  let configName = 'jiek.config'
15
12
 
16
13
  function getConfigPath(root: string, dir?: string) {
@@ -1,7 +1,3 @@
1
- import { createRequire } from 'node:module'
2
-
3
- const require = createRequire(import.meta.url)
4
-
5
1
  function packageIsExist(name: string) {
6
2
  try {
7
3
  require.resolve(name)